issue_id
int64 2.03k
426k
| title
stringlengths 9
251
| body
stringlengths 1
32.8k
⌀ | status
stringclasses 6
values | after_fix_sha
stringlengths 7
7
| project_name
stringclasses 6
values | repo_url
stringclasses 6
values | repo_name
stringclasses 6
values | language
stringclasses 1
value | issue_url
null | before_fix_sha
null | pull_url
null | commit_datetime
timestamp[us, tz=UTC] | report_datetime
timestamp[us, tz=UTC] | updated_file
stringlengths 2
187
| file_content
stringlengths 0
368k
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
72,531
|
Bug 72531 declare warning warns at wrong points
| null |
resolved fixed
|
82eae55
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-24T21:10:56Z
| 2004-08-24T17:53:20Z
|
weaver/testsrc/org/aspectj/weaver/patterns/TypePatternTestCase.java
|
/* *******************************************************************
* 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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.patterns;
import java.io.*;
import org.aspectj.weaver.bcel.*;
import org.aspectj.bridge.AbortException;
import org.aspectj.util.FuzzyBoolean;
import junit.framework.TestCase;
import org.aspectj.weaver.*;
public class TypePatternTestCase extends TestCase {
/**
* Constructor for PatternTestCase.
* @param name
*/
public TypePatternTestCase(String name) {
super(name);
}
World world;
public void testStaticMatch() {
world = new BcelWorld();
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() {
world = new BcelWorld();
// 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() {
world = new BcelWorld();
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() {
world = new BcelWorld();
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() {
world = new BcelWorld();
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);
}
private void checkIllegalInstanceofMatch(String pattern, String name) {
try {
TypePattern p = makeTypePattern(pattern);
ResolvedTypeX type = world.resolve(name);
/*FuzzyBoolean result = */p.matchesInstanceof(type);
} catch (AbortException e) {
return;
}
assertTrue("matching " + pattern + " with " + name + " should fail", false);
}
private void checkInstanceofMatch(String pattern, String name, FuzzyBoolean shouldMatch) {
TypePattern p = makeTypePattern(pattern);
ResolvedTypeX 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) {
return new PatternParser(pattern).parseSingleTypePattern();
}
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)
{
ResolvedTypeX 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();
DataOutputStream out = new DataOutputStream(bo);
p.write(out);
out.close();
ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray());
DataInputStream in = new DataInputStream(bi);
TypePattern newP = TypePattern.read(in, null);
assertEquals("write/read", p, newP);
}
}
|
72,150
|
Bug 72150 AJC possible bug with static nested classes
| null |
resolved fixed
|
b5e6307
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-27T10:03:54Z
| 2004-08-18T06:20:00Z
|
tests/bugs/java5/arrayCloning/A.java
| |
72,150
|
Bug 72150 AJC possible bug with static nested classes
| null |
resolved fixed
|
b5e6307
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-27T10:03:54Z
| 2004-08-18T06:20:00Z
|
tests/bugs/java5/arrayCloning/C.java
| |
72,150
|
Bug 72150 AJC possible bug with static nested classes
| null |
resolved fixed
|
b5e6307
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-27T10:03:54Z
| 2004-08-18T06:20:00Z
|
tests/src/org/aspectj/systemtest/ajc121/Ajc121Tests.java
|
/* *******************************************************************
* Copyright (c) 2004 IBM Corporation
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* ******************************************************************/
package org.aspectj.systemtest.ajc121;
import java.io.File;
import junit.framework.Test;
import org.aspectj.testing.XMLBasedAjcTestCase;
public class Ajc121Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc121Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc121/ajc121.xml");
}
public void test001(){
runTest("false ambiguous binding error (introduced in 1.2rc2)");
}
public void test002(){
runTest("An if() pointcut inside a perthis() clauses an ABORT - null pointer exception in ajc");
}
public void test003(){
runTest("An if() pointcut inside a perthis() clauses an ABORT - null pointer exception in ajc");
}
public void test004(){
runTest("An if() pointcut inside a perthis() clauses an ABORT - null pointer exception in ajc");
}
public void test005(){
runTest("compiler aborts with 'conflicting dominates orders' with circular declare precedences");
}
public void test006(){
runTest("'can't bind type' message has $ for . in type name for declare soft");
}
public void test007(){
runTest("Hiding of Instance Methods by static methods");
}
public void test008(){
runTest("if(false) optimisation");
}
public void test009(){
runTest("if(true) optimisation");
}
public void test010(){
runTest("java.lang.NullPointerException in WeaverMessageHandler class");
}
public void test011(){
runTest("ClassCastException at BcelRenderer.java:169");
}
public void test012(){
runTest("Front-end bug, shouldn't allow patterns of the form foo.., should be foo..*");
}
public void test013() {
runTest("Nullpointer-Exception when defining a withincode() pointcut");
}
public void test014() {
runTest("NPE, Incorrect XLint:unmatchedSuperTypeInCall warning");
}
public void test015_invalidXlint() { // keywords: "laurie hendren"
runTest("invalid warning indicating no match when a match really occurs");
}
public void test016_ByteConversionInstructions() {
runTest("RuntimeException thrown: Could not find instruction: org.apache.bcel.generic.B2I");
String output = getLastRunResult().getStdErr();
assertTrue("Expected to find [b2] in this output but didn't:"+output,output.indexOf("[b2]")!=-1);
assertTrue("Expected to find [b127] in this output but didn't:"+output,output.indexOf("[b127]")!=-1);
assertTrue("Expected to find [b0] in this output but didn't:"+output,output.indexOf("[b0]")!=-1);
assertTrue("Expected to find [c65] in this output but didn't:"+output,output.indexOf("[c65]")!=-1);
assertTrue("Expected to find [c66] in this output but didn't:"+output,output.indexOf("[c66]")!=-1);
assertTrue("Expected to find [c67] in this output but didn't:"+output,output.indexOf("[c67]")!=-1);
assertTrue("Expected to find [s1] in this output but didn't:"+output,output.indexOf("[s1]")!=-1);
assertTrue("Expected to find [s32767] in this output but didn't:"+output,output.indexOf("[s32767]")!=-1);
assertTrue("Expected to find [b0] in this output but didn't:"+output,output.indexOf("[b0]")!=-1);
}
public void test017_PrivateMethodCallsInAroundAdvice() {
runTest("Cannot advise private method call in around advice");
System.err.println(getLastRunResult().getStdErr());
}
public void test018_PrivateFieldSetsInAroundAdvice() {
runTest("Cannot advise private field sets in around advice");
System.err.println(getLastRunResult().getStdErr());
}
public void test019_PrivateFieldGetsInAroundAdvice() {
runTest("Cannot advise private field gets in around advice");
System.err.println(getLastRunResult().getStdErr());
}
// test takes over 5 minutes to run, so not included in normal suite run
// public void test020_branchTargetOffsetTooLargeForShort() {
// runTest("Branch target offset too large for short");
// }
// public void test021_BcelFailureWithVeryLargeClasses() {
// runTest("Weaver fails in BCEL for large classes");
// }
//
// public void test022_BcelFailureWithVeryLargeClasses_Binary() {
// runTest("Weaver fails in BCEL for large classes (binary)");
// }
public void test023_proceedInAround1() {
runTest("proceed used as method name in around advice (1)");
}
public void test024_proceedInAround2() {
runTest("proceed used as method name in around advice (2)");
}
public void test025_proceedInAround3() {
runTest("proceed used as method name in around advice (3)");
}
public void test026_bindingThisAndTargetToTheSameFormal() {
runTest("ajc crashes when compiling the following program (binding this() and target())");
}
public void test027_itdsOnInnerClassesAsStatic() {
runTest("ITDs on inner classes should be static context");
}
public void test028_itdsAndInitializers() {
runTest("resolution of IT field inits");
}
public void test029_falseInvalidAbsoluteTypeName() {
runTest("Valid but inaccessible type names should not be flagged by XLint:invalidAbsoluteTypeName");
}
public void test030_privateITDinitialisersBeingMatched() {
runTest("intertype initialisers should match field set pointcuts");
}
public void test031_privateITDinitialisersBeingMatched_OxfordTest() {
runTest("intertype initialisers should match field set pointcuts (oxford testcase)");
//System.err.println(">"+getLastRunResult().getStdErr());
String exp = ":set field set(int C.n):set field set(int C.m):get field get(int C.n):set field set(int C.n)";
assertTrue("Expected output '"+exp+"' but got "+getLastRunResult().getStdErr(),
getLastRunResult().getStdErr().equals(exp));
}
public void test032_stringConcatForDEOW() {
runTest("Compile time declarations (warning and error) do not accept string concatenation (with +)");
}
public void test033_stringConcatForDEOWErrorCase() {
runTest("Compile time declarations (warning and error) do not accept string concatenation (with +) (2)");
}
public void test034_scopeForITDS_pr61768() {
runTest("scope for inter-type methods");
}
public void test035_innerAspectCallsPrivateMethod_pr71372() {
runTest("NoSuchMethodError calling private method from around advice in inner aspect");
String s = getLastRunResult().getStdErr();
assertTrue("Expected ':before:around' but got "+s,
s.equals(":before:around"));
}
public void test036_innerAspectCallsPrivateMethod_pr71372_2() {
runTest("NoSuchMethodError calling private method from around advice in inner aspect (2)");
String s = getLastRunResult().getStdErr();
assertTrue("Expected ':before:around' but got "+s,
s.equals(":before:around"));
}
public void test037_innerAspectCallsPrivateMethod_pr71372_3() {
runTest("NoSuchMethodError calling private method from around advice in inner aspect (3)");
String s = getLastRunResult().getStdErr();
assertTrue("Expected ':before:around' but got "+s,
s.equals(":before:around"));
}
public void test038_innerAspectCallsPrivateMethod_pr71372_4() {
runTest("NoSuchMethodError calling private method from around advice in inner aspect (4)");
String s = getLastRunResult().getStdErr();
assertTrue("Expected ':before:around' but got "+s,
s.equals(":before:around"));
}
public void test039_privilegedAspectAccessingPrivateMethods_pr67579() {
runTest("NPE on privileged aspect error");
}
public void test040_privilegedAspectAccessingPrivateMethods_pr67579_2() {
runTest("NPE on privileged aspect error (2)");
}
public void test041_ITDaccessingPrivateMethod_pr67578() {
runTest("Privileged Aspect Access Problem Across Packages");
}
public void test042_ITDaccessingPrivateMethod_pr67578_2() {
runTest("Privileged Aspect Access Problem Across Packages (2)");
}
public void test043_pr62642_ExceptionInInitializerError() {
runTest("proper handling of ExceptionInIntializer inside clinit in presence of after throwing advice");
String s = getLastRunResult().getStdErr();
assertTrue("Output should contain java.lang.ExceptionInInitializerError but is '"+s+"'",
s.indexOf("java.lang.ExceptionInInitializerError")!=-1);
// No getCause on 1.3 JVMs
// assertTrue("Output should contain 'CAUSE=org.aspectj.lang.NoAspectBoundException' but is '"+s+"'",
// s.indexOf("CAUSE=org.aspectj.lang.NoAspectBoundException")!=-1);
}
public void test044_ITDnameClashes() {
runTest("ITD name clashes with private members");
}
public void test045_ITDprotectedVisibility() {
runTest("Inconsistency in scoping of protected members in ITDs");
}
public void test045_wrongLineForExecutionJoinPoint() {
runTest("wrong line for method execution join point");
}
public void test046_interfaceITD_pr70794_1() {
runTest("The introduction on interface causes the interface implementation class error (1)");
}
public void test047_interfaceITD_pr70794_2() {
runTest("The introduction on interface causes the interface implementation class error (2)");
}
public void test048_interfaceITD_pr70794_3() {
runTest("The introduction on interface causes the interface implementation class error (3)");
}
public void test049_interfaceITD_pr70794_4() {
runTest("The introduction on interface causes the interface implementation class error (4)");
}
public void test050_typePatternMatchingWithArrays() {
runTest("declare warning warns at wrong points");
}
}
|
72,150
|
Bug 72150 AJC possible bug with static nested classes
| null |
resolved fixed
|
b5e6307
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-27T10:03:54Z
| 2004-08-18T06:20:00Z
|
weaver/src/org/aspectj/weaver/TypeX.java
|
/* *******************************************************************
* 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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Iterator;
public class TypeX {
/**
* This is the bytecode string representation of this Type
*/
protected String signature;
/**
* @param signature the bytecode string representation of this Type
*/
protected TypeX(String signature) {
super();
this.signature = signature;
}
// ---- Things we can do without a world
/**
* This is the size of this type as used in JVM.
*/
public int getSize() {
return 1;
}
/**
* Equality is checked based on the underlying signature.
* {@link ResolvedType} objects' equals is by reference.
*/
public boolean equals(Object other) {
if (! (other instanceof TypeX)) return false;
return signature.equals(((TypeX) other).signature);
}
/**
* Equality is checked based on the underlying signature, so the hash code
* of a particular type is the hash code of its signature string.
*/
public final int hashCode() {
return signature.hashCode();
}
public static TypeX makeArray(TypeX base, int dims) {
StringBuffer sig = new StringBuffer();
for (int i=0; i < dims; i++) sig.append("[");
sig.append(base.getSignature());
return TypeX.forSignature(sig.toString());
}
/**
* Constructs a TypeX for a java language type name. For example:
*
* <blockquote><pre>
* TypeX.forName("java.lang.Thread[]")
* TypeX.forName("int")
* </pre></blockquote>
*
* Types may equivalently be produced by this or by {@link #forSignature(String)}.
*
* <blockquote><pre>
* TypeX.forName("java.lang.Thread[]").equals(Type.forSignature("[Ljava/lang/Thread;")
* TypeX.forName("int").equals(Type.forSignature("I"))
* </pre></blockquote>
*
* @param name the java language type name in question.
* @return a type object representing that java language type.
*/
public static TypeX forName(String name) {
return forSignature(nameToSignature(name));
}
/** Constructs a TypeX for each java language type name in an incoming array.
*
* @param names an array of java language type names.
* @return an array of TypeX objects.
* @see #forName(String)
*/
public static TypeX[] forNames(String[] names) {
TypeX[] ret = new TypeX[names.length];
for (int i = 0, len = names.length; i < len; i++) {
ret[i] = TypeX.forName(names[i]);
}
return ret;
}
/**
* Creates a new type array with a fresh type appended to the end.
*
* @param types the left hand side of the new array
* @param end the right hand side of the new array
*/
public static TypeX[] add(TypeX[] types, TypeX end) {
int len = types.length;
TypeX[] ret = new TypeX[len + 1];
System.arraycopy(types, 0, ret, 0, len);
ret[len] = end;
return ret;
}
/**
* Creates a new type array with a fresh type inserted at the beginning.
*
*
* @param start the left hand side of the new array
* @param types the right hand side of the new array
*/
public static TypeX[] insert(TypeX start, TypeX[] types) {
int len = types.length;
TypeX[] ret = new TypeX[len + 1];
ret[0] = start;
System.arraycopy(types, 0, ret, 1, len);
return ret;
}
/**
* Constructs a Type for a JVM bytecode signature string. For example:
*
* <blockquote><pre>
* TypeX.forSignature("[Ljava/lang/Thread;")
* TypeX.forSignature("I");
* </pre></blockquote>
*
* Types may equivalently be produced by this or by {@link #forName(String)}.
*
* <blockquote><pre>
* TypeX.forName("java.lang.Thread[]").equals(Type.forSignature("[Ljava/lang/Thread;")
* TypeX.forName("int").equals(Type.forSignature("I"))
* </pre></blockquote>
*
* @param signature the JVM bytecode signature string for the desired type.
* @return a type object represnting that JVM bytecode signature.
*/
public static TypeX forSignature(String signature) {
switch (signature.charAt(0)) {
case 'B': return ResolvedTypeX.BYTE;
case 'C': return ResolvedTypeX.CHAR;
case 'D': return ResolvedTypeX.DOUBLE;
case 'F': return ResolvedTypeX.FLOAT;
case 'I': return ResolvedTypeX.INT;
case 'J': return ResolvedTypeX.LONG;
case 'L':
return new TypeX(signature);
case 'S': return ResolvedTypeX.SHORT;
case 'V': return ResolvedTypeX.VOID;
case 'Z': return ResolvedTypeX.BOOLEAN;
case '[':
return new TypeX(signature);
default:
throw new BCException("Bad type signature " + signature);
}
}
/** Constructs a TypeX for each JVM bytecode type signature in an incoming array.
*
* @param names an array of JVM bytecode type signatures
* @return an array of TypeX objects.
* @see #forSignature(String)
*/
public static TypeX[] forSignatures(String[] sigs) {
TypeX[] ret = new TypeX[sigs.length];
for (int i = 0, len = sigs.length; i < len; i++) {
ret[i] = TypeX.forSignature(sigs[i]);
}
return ret;
}
/**
* Returns the name of this type in java language form. For all
* TypeX t:
*
* <blockquote><pre>
* TypeX.forName(t.getName()).equals(t)
* </pre></blockquote>
*
* and for all String s where s is a lexically valid java language typename:
*
* <blockquote><pre>
* TypeX.forName(s).getName().equals(s)
* </pre></blockquote>
*
* This produces a more esthetically pleasing string than
* {@link java.lang.Class#getName()}.
*
* @return the java language name of this type.
*/
public String getName() {
return signatureToName(signature);
}
/**
* Returns an array of strings representing the java langauge names of
* an array of types.
*
* @param types an array of TypeX objects
* @return an array of Strings fo the java language names of types.
* @see #getName()
*/
public static String[] getNames(TypeX[] types) {
String[] ret = new String[types.length];
for (int i = 0, len = types.length; i < len; i++) {
ret[i] = types[i].getName();
}
return ret;
}
/**
* Returns the name of this type in JVM signature form. For all
* TypeX t:
*
* <blockquote><pre>
* TypeX.forSignature(t.getSignature()).equals(t)
* </pre></blockquote>
*
* and for all String s where s is a lexically valid JVM type signature string:
*
* <blockquote><pre>
* TypeX.forSignature(s).getSignature().equals(s)
* </pre></blockquote>
*
* @return the java JVM signature string for this type.
*/
public String getSignature() {
return signature;
}
/**
* Determins if this represents an array type.
*
* @return true iff this represents an array type.
*/
public final boolean isArray() {
return signature.startsWith("[");
}
/**
* Returns a TypeX object representing the effective outermost enclosing type
* for a name type. For all other types, this will return the type itself.
*
* The only guarantee is given in JLS 13.1 where code generated according to
* those rules will have type names that can be split apart in this way.
* @return the outermost enclosing TypeX object or this.
*/
public TypeX getOutermostType() {
if (isArray() || isPrimitive()) return this;
String sig = getSignature();
int dollar = sig.indexOf('$');
if (dollar != -1) {
return TypeX.forSignature(sig.substring(0, dollar) + ';');
} else {
return this;
}
}
/**
* Returns a TypeX object representing the component type of this array, or
* null if this type does not represent an array type.
*
* @return the component TypeX object, or null.
*/
public TypeX getComponentType() {
if (isArray()) {
return forSignature(signature.substring(1));
} else {
return null;
}
}
/**
* Determines if this represents a primitive type. A primitive type
* is one of nine predefined resolved types.
*
* @return true iff this type represents a primitive type
*
* @see ResolvedTypeX#Boolean
* @see ResolvedTypeX#Character
* @see ResolvedTypeX#Byte
* @see ResolvedTypeX#Short
* @see ResolvedTypeX#Integer
* @see ResolvedTypeX#Long
* @see ResolvedTypeX#Float
* @see ResolvedTypeX#Double
* @see ResolvedTypeX#Void
*/
public boolean isPrimitive() {
return false;
}
/**
* Returns a java language string representation of this type.
*/
public String toString() {
return getName();
}
// ---- requires worlds
/**
* Types may have pointcuts just as they have methods and fields.
*/
public ResolvedPointcutDefinition findPointcut(String name, World world) {
return world.findPointcut(this, name);
}
/**
* Determines if variables of this type could be assigned values of another
* with lots of help.
* java.lang.Object is convertable from all types.
* A primitive type is convertable from X iff it's assignable from X.
* A reference type is convertable from X iff it's coerceable from X.
* In other words, X isConvertableFrom Y iff the compiler thinks that _some_ value of Y
* could be assignable to a variable of type X without loss of precision.
*
* @param other the other type
* @param world the {@link World} in which the possible assignment should be checked.
* @return true iff variables of this type could be assigned values of other with possible conversion
*/
public final boolean isConvertableFrom(TypeX other, World world) {
if (this.equals(OBJECT)) return true;
if (this.isPrimitive() || other.isPrimitive()) return this.isAssignableFrom(other, world);
return this.isCoerceableFrom(other, world);
}
/**
* Determines if variables of this type could be assigned values of another
* without any conversion computation of any kind. For primitive types
* this means equality, and for reference types it means assignability.
*
* @param other the other type
* @param world the {@link World} in which the possible assignment should be checked.
* @return true iff variables of this type could be assigned values of other without any conversion computation
*/
public boolean needsNoConversionFrom(TypeX other, World world) {
// primitives override this method, so we know we're not primitive.
// So if the other is primitive, don't bother asking the world anything.
if (other.isPrimitive()) return false;
return world.needsNoConversionFrom(this, other);
}
/**
* Determines if the variables of this type could be assigned values
* of another type without casting. This still allows for assignment conversion
* as per JLS 2ed 5.2. For object types, this means supertypeOrEqual(THIS, OTHER).
*
* @param other the other type
* @param world the {@link World} in which the possible assignment should be checked.
* @return true iff variables of this type could be assigned values of other without casting
* @exception NullPointerException if other is null
*/
public boolean isAssignableFrom(TypeX other, World world) {
// primitives override this method, so we know we're not primitive.
// So if the other is primitive, don't bother asking the world anything.
if (other.isPrimitive()) return false;
return world.isAssignableFrom(this, other);
}
/**
* Determines if values of another type could possibly be cast to
* this type. The rules followed are from JLS 2ed 5.5, "Casting Conversion".
*
* <p> This method should be commutative, i.e., for all TypeX a, b and all World w:
*
* <blockquote><pre>
* a.isCoerceableFrom(b, w) == b.isCoerceableFrom(a, w)
* </pre></blockquote>
*
* @param other the other type
* @param world the {@link World} in which the possible coersion should be checked.
* @return true iff values of other could possibly be cast to this type.
* @exception NullPointerException if other is null.
*/
public boolean isCoerceableFrom(TypeX other, World world) {
// primitives override this method, so we know we're not primitive.
// So if the other is primitive, don't bother asking the world anything.
if (other.isPrimitive()) return false;
return world.isCoerceableFrom(this, other);
}
/**
* Determines if this represents an interface type.
*
* @param world the {@link World} in which we should check.
* @return true iff this represents an interface type.
*/
public final boolean isInterface(World world) {
return world.resolve(this).isInterface();
}
/**
* Determines if this represents a class type.
*
* @param world the {@link World} in which we should check.
* @return true iff this represents a class type.
*/
public final boolean isClass(World world) {
return world.resolve(this).isClass();
}
/**
* Determines if this represents an aspect type.
*
* @param world the {@link World} in which we should check.
* @return true iff this represents an aspect type.
*/
public final boolean isAspect(World world) {
return world.resolve(this).isAspect();
}
/**
* Returns a TypeX object representing the superclass of this type, or null.
* If this represents a java.lang.Object, a primitive type, or void, this
* method returns null.
*
* <p>
* This differs from {@link java.lang.class#getSuperclass()} in that
* this returns a TypeX object representing java.lang.Object for interfaces instead
* of returning null.
*
* @param world the {@link World} in which the lookup should be made.
* @return this type's superclass, or null if none exists.
*/
public TypeX getSuperclass(World world) {
return world.getSuperclass(this);
}
/**
* Returns an array of TypeX objects representing the declared interfaces
* of this type.
*
* <p>
* If this object represents a class, the declared interfaces are those it
* implements. If this object represents an interface, the declared interfaces
* are those it extends. If this object represents a primitive, an empty
* array is returned. If this object represents an array, an array
* containing types for java.lang.Cloneable and java.io.Serializable is returned.
*
* @param world the {@link World} in which the lookup should be made.
* @return an iterator through the declared interfaces of this type.
*/
public TypeX[] getDeclaredInterfaces(World world) {
return world.getDeclaredInterfaces(this);
}
/**
* Returns an iterator through TypeX objects representing all the direct
* supertypes of this type. That is, through the superclass, if any, and
* all declared interfaces.
*
* @param world the {@link World} in which the lookup should be made.
* @return an iterator through the direct supertypes of this type.
*/
public Iterator getDirectSupertypes(World world) {
return world.resolve(this).getDirectSupertypes();
}
/**
* Returns the modifiers for this type.
*
* See {@link java.lang.Class#getModifiers()} for a description
* of the weirdness of this methods on primitives and arrays.
*
* @param world the {@link World} in which the lookup is made.
* @return an int representing the modifiers for this type
* @see java.lang.reflect.Modifier
*/
public int getModifiers(World world) {
return world.getModifiers(this);
}
/**
* Returns an array representing the declared fields of this object. This may include
* non-user-visible fields.
* This method returns an
* empty array if it represents an array type or a primitive type, so
* the implicit length field of arrays is just that, implicit.
*
* @param world the {@link World} in which the lookup is done.
* @return the array representing the declared fields of this type
*/
public ResolvedMember[] getDeclaredFields(World world) {
return world.getDeclaredFields(this);
}
/**
* Returns an array representing the declared methods of this object. This includes
* constructors and the static initialzation method. This also includes all
* shadowMungers in an aspect. So it may include more than the user-visible methods.
* This method returns an
* empty array if it represents an array type or a primitive type.
*
* @param world the {@link World} in which the lookup is done.
* @return the array representing the declared methods of this type
*/
public ResolvedMember[] getDeclaredMethods(World world) {
return world.getDeclaredMethods(this);
}
/**
* Returns an array representing the declared pointcuts of this object.
* This method returns an
* empty array if it represents an array type or a primitive type.
*
* @param world the {@link World} in which the lookup is done.
* @return the array representing the declared pointcuts of this type
*/
public ResolvedMember[] getDeclaredPointcuts(World world) {
return world.getDeclaredPointcuts(this);
}
/**
* Returns a resolved version of this type according to a particular world.
*
* @param world thie {@link World} within which to resolve.
* @return a resolved type representing this type in the appropriate world.
*/
public ResolvedTypeX resolve(World world) {
return world.resolve(this);
}
// ---- fields
public static final TypeX[] NONE = new TypeX[0];
public static final TypeX OBJECT = forSignature("Ljava/lang/Object;");
public static final TypeX OBJECTARRAY = forSignature("[Ljava/lang/Object;");
public static final TypeX CLONEABLE = forSignature("Ljava/lang/Cloneable;");
public static final TypeX SERIALIZABLE = forSignature("Ljava/io/Serializable;");
public static final TypeX THROWABLE = forSignature("Ljava/lang/Throwable;");
public static final TypeX RUNTIME_EXCEPTION = forSignature("Ljava/lang/RuntimeException;");
public static final TypeX ERROR = forSignature("Ljava/lang/Error;");
// ---- helpers
private static String signatureToName(String signature) {
switch (signature.charAt(0)) {
case 'B': return "byte";
case 'C': return "char";
case 'D': return "double";
case 'F': return "float";
case 'I': return "int";
case 'J': return "long";
case 'L':
return signature.substring(1, signature.length() - 1).replace('/', '.');
case 'S': return "short";
case 'V': return "void";
case 'Z': return "boolean";
case '[':
return signatureToName(signature.substring(1, signature.length())) + "[]";
default:
throw new BCException("Bad type signature: " + signature);
}
}
private static String nameToSignature(String name) {
if (name.equals("byte")) return "B";
if (name.equals("char")) return "C";
if (name.equals("double")) return "D";
if (name.equals("float")) return "F";
if (name.equals("int")) return "I";
if (name.equals("long")) return "J";
if (name.equals("short")) return "S";
if (name.equals("boolean")) return "Z";
if (name.equals("void")) return "V";
if (name.endsWith("[]"))
return "[" + nameToSignature(name.substring(0, name.length() - 2));
if (name.length() != 0) // lots more tests could be made here...
return "L" + name.replace('.', '/') + ";";
else
throw new BCException("Bad type name: " + name);
}
public void write(DataOutputStream s) throws IOException {
s.writeUTF(signature);
}
public static TypeX read(DataInputStream s) throws IOException {
String sig = s.readUTF();
if (sig.equals(MISSING_NAME)) {
return ResolvedTypeX.MISSING;
} else {
return TypeX.forSignature(sig);
}
}
public static void writeArray(TypeX[] types, DataOutputStream s) throws IOException {
int len = types.length;
s.writeShort(len);
for (int i=0; i < len; i++) {
types[i].write(s);
}
}
public static TypeX[] readArray(DataInputStream s) throws IOException {
int len = s.readShort();
TypeX[] types = new TypeX[len];
for (int i=0; i < len; i++) {
types[i] = TypeX.read(s);
}
return types;
}
/**
* For debugging purposes
*/
public void dump(World world) {
if (isAspect(world)) System.out.print("aspect ");
else if (isInterface(world)) System.out.print("interface ");
else if (isClass(world)) System.out.print("class ");
System.out.println(toString());
dumpResolvedMembers("fields", getDeclaredFields(world));
dumpResolvedMembers("methods", getDeclaredMethods(world));
dumpResolvedMembers("pointcuts", getDeclaredPointcuts(world));
}
private void dumpResolvedMembers(String label, ResolvedMember[] l) {
final String indent = " ";
System.out.println(label);
if (l == null) {
System.out.println(indent + "null");
return;
}
for (int i=0, len=l.length; i < len; i++) {
System.out.println(indent + l[i]);
}
}
// ----
public String getNameAsIdentifier() {
return getName().replace('.', '_');
}
public String getPackageNameAsIdentifier() {
String name = getName();
int index = name.lastIndexOf('.');
if (index == -1) {
return "";
} else {
return name.substring(0, index).replace('.', '_');
}
}
public String getPackageName() {
String name = getName();
int index = name.lastIndexOf('.');
if (index == -1) {
return null;
} else {
return name.substring(0, index);
}
}
public String getClassName() {
String name = getName();
int index = name.lastIndexOf('.');
if (index == -1) {
return name;
} else {
return name.substring(index+1);
}
}
public static final String MISSING_NAME = "<missing>";
}
|
72,699
|
Bug 72699 Bogus error message: The abstract method ajc$pointcut$$tracingScope$a2 in type Tracing can only be defined by an abstract class
|
When attempting to compile the following aspect the resulting error message should say something like "The abstract method pointcut tracingScope in type Tracing can only be defined by an abstract aspect" public aspect Tracing { public abstract pointcut tracingScope(); }
|
resolved fixed
|
5e08765
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-27T11:18:01Z
| 2004-08-26T17:06:40Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/PointcutDeclaration.java
|
/* *******************************************************************
* 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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.ast;
import java.lang.reflect.Modifier;
import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory;
import org.aspectj.ajdt.internal.core.builder.EclipseSourceContext;
import org.aspectj.weaver.AjAttribute;
import org.aspectj.weaver.ResolvedPointcutDefinition;
//import org.aspectj.weaver.ResolvedTypeX;
//import org.aspectj.weaver.TypeX;
import org.aspectj.weaver.patterns.Pointcut;
import org.eclipse.jdt.internal.compiler.ClassFile;
import org.eclipse.jdt.internal.compiler.CompilationResult;
import org.eclipse.jdt.internal.compiler.ast.Argument;
import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration;
import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration;
import org.eclipse.jdt.internal.compiler.ast.TypeReference;
import org.eclipse.jdt.internal.compiler.lookup.ClassScope;
import org.eclipse.jdt.internal.compiler.parser.Parser;
import org.eclipse.jdt.core.compiler.CharOperation;
/**
* pointcut [declaredModifiers] [declaredName]([arguments]): [pointcutDesignator];
*
* <p>No method will actually be generated for this node but an attribute
* will be added to the enclosing class.</p>
*
* @author Jim Hugunin
*/
public class PointcutDeclaration extends AjMethodDeclaration {
public static final char[] mangledPrefix = "ajc$pointcut$".toCharArray();
public PointcutDesignator pointcutDesignator;
private int declaredModifiers;
private String declaredName;
private ResolvedPointcutDefinition resolvedPointcutDeclaration = null;
public PointcutDeclaration(CompilationResult compilationResult) {
super(compilationResult);
this.returnType = TypeReference.baseTypeReference(T_void, 0);
}
private Pointcut getPointcut() {
if (pointcutDesignator == null) {
return Pointcut.makeMatchesNothing(Pointcut.RESOLVED);
} else {
return pointcutDesignator.getPointcut();
}
}
public void parseStatements(
Parser parser,
CompilationUnitDeclaration unit) {
// do nothing
}
public void postParse(TypeDeclaration typeDec) {
if (arguments == null) arguments = new Argument[0];
this.declaredModifiers = modifiers;
this.declaredName = new String(selector);
selector = CharOperation.concat(mangledPrefix, '$', selector, '$',
Integer.toHexString(sourceStart).toCharArray());
if (Modifier.isAbstract(this.declaredModifiers) &&
!(typeDec instanceof AspectDeclaration))
{
typeDec.scope.problemReporter().signalError(sourceStart, sourceEnd,
"The abstract pointcut " + new String(declaredName) +
" can only be defined in an aspect");
ignoreFurtherInvestigation = true;
return;
}
if (pointcutDesignator != null) {
pointcutDesignator.postParse(typeDec, this);
}
}
public void resolve(ClassScope upperScope) {
// this method should do nothing, use the entry point below...
}
public void resolvePointcut(ClassScope upperScope) {
super.resolve(upperScope);
}
public void resolveStatements() {
if (isAbstract()) {
this.modifiers |= AccSemicolonBody;
}
if (binding == null || ignoreFurtherInvestigation) return;
if (Modifier.isAbstract(this.declaredModifiers)&& (pointcutDesignator != null)) {
scope.problemReporter().signalError(sourceStart, sourceEnd, "abstract pointcut can't have body");
ignoreFurtherInvestigation = true;
return;
}
if (pointcutDesignator != null) {
pointcutDesignator.finishResolveTypes(this, this.binding, arguments.length,
scope.enclosingSourceType());
}
//System.out.println("resolved: " + getPointcut() + ", " + getPointcut().state);
makeResolvedPointcutDefinition();
resolvedPointcutDeclaration.setPointcut(getPointcut());
super.resolveStatements();
}
public ResolvedPointcutDefinition makeResolvedPointcutDefinition() {
if (resolvedPointcutDeclaration != null) return resolvedPointcutDeclaration;
//System.out.println("pc: " + getPointcut() + ", " + getPointcut().state);
resolvedPointcutDeclaration = new ResolvedPointcutDefinition(
EclipseFactory.fromBinding(this.binding.declaringClass),
declaredModifiers,
declaredName,
EclipseFactory.fromBindings(this.binding.parameters),
getPointcut()); //??? might want to use null
resolvedPointcutDeclaration.setPosition(sourceStart, sourceEnd);
resolvedPointcutDeclaration.setSourceContext(new EclipseSourceContext(compilationResult));
return resolvedPointcutDeclaration;
}
public AjAttribute makeAttribute() {
return new AjAttribute.PointcutDeclarationAttribute(makeResolvedPointcutDefinition());
}
/**
* A pointcut declaration exists in a classfile only as an attibute on the
* class. Unlike advice and inter-type declarations, it has no corresponding
* method.
*/
public void generateCode(ClassScope classScope, ClassFile classFile) {
if (ignoreFurtherInvestigation) return ;
classFile.extraAttributes.add(new EclipseAttributeAdapter(makeAttribute()));
return;
}
public StringBuffer printReturnType(int indent, StringBuffer output) {
return output.append("pointcut");
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration#printBody(int, java.lang.StringBuffer)
*/
public StringBuffer printBody(int indent, StringBuffer output) {
output.append(": ");
output.append(getPointcut());
output.append(";");
return output;
}
}
|
72,699
|
Bug 72699 Bogus error message: The abstract method ajc$pointcut$$tracingScope$a2 in type Tracing can only be defined by an abstract class
|
When attempting to compile the following aspect the resulting error message should say something like "The abstract method pointcut tracingScope in type Tracing can only be defined by an abstract aspect" public aspect Tracing { public abstract pointcut tracingScope(); }
|
resolved fixed
|
5e08765
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-27T11:18:01Z
| 2004-08-26T17:06:40Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/problem/AjProblemReporter.java
|
/* *******************************************************************
* 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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.problem;
import java.lang.reflect.Modifier;
import java.util.Iterator;
import org.aspectj.ajdt.internal.compiler.ast.AdviceDeclaration;
import org.aspectj.ajdt.internal.compiler.ast.PointcutDeclaration;
import org.aspectj.ajdt.internal.compiler.ast.Proceed;
import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory;
import org.aspectj.util.FuzzyBoolean;
import org.aspectj.weaver.AjcMemberMaker;
import org.aspectj.weaver.ConcreteTypeMunger;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedTypeX;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.patterns.DeclareSoft;
import org.eclipse.jdt.internal.compiler.CompilationResult;
import org.eclipse.jdt.internal.compiler.IErrorHandlingPolicy;
import org.eclipse.jdt.internal.compiler.IProblemFactory;
import org.eclipse.jdt.internal.compiler.ast.ASTNode;
import org.eclipse.jdt.internal.compiler.ast.Argument;
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
import org.eclipse.jdt.internal.compiler.impl.ReferenceContext;
import org.eclipse.jdt.internal.compiler.lookup.MethodBinding;
import org.eclipse.jdt.internal.compiler.lookup.MethodScope;
import org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding;
import org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding;
import org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
import org.eclipse.jdt.internal.compiler.problem.ProblemReporter;
import org.eclipse.jdt.core.compiler.CharOperation;
/**
* Extends problem reporter to support compiler-side implementation of declare soft.
* Also overrides error reporting for the need to implement abstract methods to
* account for inter-type declarations and pointcut declarations. This second
* job might be better done directly in the SourceTypeBinding/ClassScope classes.
*
* @author Jim Hugunin
*/
public class AjProblemReporter extends ProblemReporter {
private static final boolean DUMP_STACK = false;
public EclipseFactory factory;
public AjProblemReporter(
IErrorHandlingPolicy policy,
CompilerOptions options,
IProblemFactory problemFactory) {
super(policy, options, problemFactory);
}
public void unhandledException(
TypeBinding exceptionType,
ASTNode location)
{
if (!factory.getWorld().getDeclareSoft().isEmpty()) {
Shadow callSite = factory.makeShadow(location, referenceContext);
Shadow enclosingExec = factory.makeShadow(referenceContext);
// System.err.println("about to show error for unhandled exception: " + new String(exceptionType.sourceName()) +
// " at " + location + " in " + referenceContext);
for (Iterator i = factory.getWorld().getDeclareSoft().iterator(); i.hasNext(); ) {
DeclareSoft d = (DeclareSoft)i.next();
// We need the exceptionType to match the type in the declare soft statement
// This means it must either be the same type or a subtype
ResolvedTypeX throwException = factory.fromEclipse((ReferenceBinding)exceptionType);
FuzzyBoolean isExceptionTypeOrSubtype =
d.getException().matchesInstanceof(throwException);
if (!isExceptionTypeOrSubtype.alwaysTrue() ) continue;
if (callSite != null) {
FuzzyBoolean match = d.getPointcut().match(callSite);
if (match.alwaysTrue()) {
//System.err.println("matched callSite: " + callSite + " with " + d);
return;
} else if (!match.alwaysFalse()) {
//!!! need this check to happen much sooner
//throw new RuntimeException("unimplemented, shouldn't have fuzzy match here");
}
}
if (enclosingExec != null) {
FuzzyBoolean match = d.getPointcut().match(enclosingExec);
if (match.alwaysTrue()) {
//System.err.println("matched enclosingExec: " + enclosingExec + " with " + d);
return;
} else if (!match.alwaysFalse()) {
//!!! need this check to happen much sooner
//throw new RuntimeException("unimplemented, shouldn't have fuzzy match here");
}
}
}
}
//??? is this always correct
if (location instanceof Proceed) {
return;
}
super.unhandledException(exceptionType, location);
}
private boolean isPointcutDeclaration(MethodBinding binding) {
return CharOperation.prefixEquals(PointcutDeclaration.mangledPrefix, binding.selector);
}
public void abstractMethodCannotBeOverridden(
SourceTypeBinding type,
MethodBinding concreteMethod)
{
if (isPointcutDeclaration(concreteMethod)) {
return;
}
super.abstractMethodCannotBeOverridden(type, concreteMethod);
}
public void abstractMethodMustBeImplemented(
SourceTypeBinding type,
MethodBinding abstractMethod)
{
// if this is a PointcutDeclaration then there is no error
if (isPointcutDeclaration(abstractMethod)) {
return;
}
if (CharOperation.prefixEquals("ajc$interField".toCharArray(), abstractMethod.selector)) {
//??? think through how this could go wrong
return;
}
// if we implemented this method by an inter-type declaration, then there is no error
//??? be sure this is always right
ResolvedTypeX onTypeX = factory.fromEclipse(type); //abstractMethod.declaringClass);
for (Iterator i = onTypeX.getInterTypeMungersIncludingSupers().iterator(); i.hasNext(); ) {
ConcreteTypeMunger m = (ConcreteTypeMunger)i.next();
ResolvedMember sig = m.getSignature();
if (!Modifier.isAbstract(sig.getModifiers())) {
if (ResolvedTypeX
.matches(
AjcMemberMaker.interMethod(
sig,
m.getAspectType(),
sig.getDeclaringType().isInterface(
factory.getWorld())),
EclipseFactory.makeResolvedMember(abstractMethod))) {
return;
}
}
}
super.abstractMethodMustBeImplemented(type, abstractMethod);
}
public void handle(
int problemId,
String[] problemArguments,
String[] messageArguments,
int severity,
int problemStartPosition,
int problemEndPosition,
ReferenceContext referenceContext,
CompilationResult unitResult)
{
if (severity != Ignore && DUMP_STACK) {
Thread.dumpStack();
}
super.handle(
problemId,
problemArguments,
messageArguments,
severity,
problemStartPosition,
problemEndPosition,
referenceContext,
unitResult);
}
// PR71076
public void javadocMissingParamTag(Argument arg, int modifiers) {
boolean reportIt = true;
if (arg.binding!=null && (arg.binding.declaringScope instanceof MethodScope) ) {
MethodScope ms = (MethodScope) arg.binding.declaringScope;
if (ms.referenceContext!=null && (ms.referenceContext instanceof AdviceDeclaration)) {
AdviceDeclaration adviceDecl = (AdviceDeclaration)ms.referenceContext;
if (arg.name!=null) {
if (adviceDecl.selector.length>4 &&
adviceDecl.selector[0] == 'a' &&
adviceDecl.selector[1] == 'j' &&
adviceDecl.selector[2] == 'c' &&
adviceDecl.selector[3] == '$') {
String stringArgName = new String(arg.name);
if (stringArgName.equals("thisJoinPoint")) reportIt = false;
if (stringArgName.equals("thisJoinPointStaticPart")) reportIt = false;
if (stringArgName.equals("thisEnclosingJoinPointStaticPart")) reportIt = false;
if (arg.type.toString().indexOf("AroundClosure")!=-1) reportIt = false;
}
}
}
}
if (arg.name!=null && new String(arg.name).startsWith("ajc$")) reportIt = false;
if (reportIt)
super.javadocMissingParamTag(arg, modifiers);
}
}
|
72,699
|
Bug 72699 Bogus error message: The abstract method ajc$pointcut$$tracingScope$a2 in type Tracing can only be defined by an abstract class
|
When attempting to compile the following aspect the resulting error message should say something like "The abstract method pointcut tracingScope in type Tracing can only be defined by an abstract aspect" public aspect Tracing { public abstract pointcut tracingScope(); }
|
resolved fixed
|
5e08765
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-27T11:18:01Z
| 2004-08-26T17:06:40Z
|
tests/bugs/BogusMessage.java
| |
72,699
|
Bug 72699 Bogus error message: The abstract method ajc$pointcut$$tracingScope$a2 in type Tracing can only be defined by an abstract class
|
When attempting to compile the following aspect the resulting error message should say something like "The abstract method pointcut tracingScope in type Tracing can only be defined by an abstract aspect" public aspect Tracing { public abstract pointcut tracingScope(); }
|
resolved fixed
|
5e08765
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-27T11:18:01Z
| 2004-08-26T17:06:40Z
|
tests/bugs/BogusMessage2.java
| |
72,699
|
Bug 72699 Bogus error message: The abstract method ajc$pointcut$$tracingScope$a2 in type Tracing can only be defined by an abstract class
|
When attempting to compile the following aspect the resulting error message should say something like "The abstract method pointcut tracingScope in type Tracing can only be defined by an abstract aspect" public aspect Tracing { public abstract pointcut tracingScope(); }
|
resolved fixed
|
5e08765
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-08-27T11:18:01Z
| 2004-08-26T17:06:40Z
|
tests/src/org/aspectj/systemtest/ajc121/Ajc121Tests.java
|
/* *******************************************************************
* Copyright (c) 2004 IBM Corporation
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* ******************************************************************/
package org.aspectj.systemtest.ajc121;
import java.io.File;
import junit.framework.Test;
import org.aspectj.testing.XMLBasedAjcTestCase;
public class Ajc121Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc121Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc121/ajc121.xml");
}
public void test001(){
runTest("false ambiguous binding error (introduced in 1.2rc2)");
}
public void test002(){
runTest("An if() pointcut inside a perthis() clauses an ABORT - null pointer exception in ajc");
}
public void test003(){
runTest("An if() pointcut inside a perthis() clauses an ABORT - null pointer exception in ajc");
}
public void test004(){
runTest("An if() pointcut inside a perthis() clauses an ABORT - null pointer exception in ajc");
}
public void test005(){
runTest("compiler aborts with 'conflicting dominates orders' with circular declare precedences");
}
public void test006(){
runTest("'can't bind type' message has $ for . in type name for declare soft");
}
public void test007(){
runTest("Hiding of Instance Methods by static methods");
}
public void test008(){
runTest("if(false) optimisation");
}
public void test009(){
runTest("if(true) optimisation");
}
public void test010(){
runTest("java.lang.NullPointerException in WeaverMessageHandler class");
}
public void test011(){
runTest("ClassCastException at BcelRenderer.java:169");
}
public void test012(){
runTest("Front-end bug, shouldn't allow patterns of the form foo.., should be foo..*");
}
public void test013() {
runTest("Nullpointer-Exception when defining a withincode() pointcut");
}
public void test014() {
runTest("NPE, Incorrect XLint:unmatchedSuperTypeInCall warning");
}
public void test015_invalidXlint() { // keywords: "laurie hendren"
runTest("invalid warning indicating no match when a match really occurs");
}
public void test016_ByteConversionInstructions() {
runTest("RuntimeException thrown: Could not find instruction: org.apache.bcel.generic.B2I");
String output = getLastRunResult().getStdErr();
assertTrue("Expected to find [b2] in this output but didn't:"+output,output.indexOf("[b2]")!=-1);
assertTrue("Expected to find [b127] in this output but didn't:"+output,output.indexOf("[b127]")!=-1);
assertTrue("Expected to find [b0] in this output but didn't:"+output,output.indexOf("[b0]")!=-1);
assertTrue("Expected to find [c65] in this output but didn't:"+output,output.indexOf("[c65]")!=-1);
assertTrue("Expected to find [c66] in this output but didn't:"+output,output.indexOf("[c66]")!=-1);
assertTrue("Expected to find [c67] in this output but didn't:"+output,output.indexOf("[c67]")!=-1);
assertTrue("Expected to find [s1] in this output but didn't:"+output,output.indexOf("[s1]")!=-1);
assertTrue("Expected to find [s32767] in this output but didn't:"+output,output.indexOf("[s32767]")!=-1);
assertTrue("Expected to find [b0] in this output but didn't:"+output,output.indexOf("[b0]")!=-1);
}
public void test017_PrivateMethodCallsInAroundAdvice() {
runTest("Cannot advise private method call in around advice");
System.err.println(getLastRunResult().getStdErr());
}
public void test018_PrivateFieldSetsInAroundAdvice() {
runTest("Cannot advise private field sets in around advice");
System.err.println(getLastRunResult().getStdErr());
}
public void test019_PrivateFieldGetsInAroundAdvice() {
runTest("Cannot advise private field gets in around advice");
System.err.println(getLastRunResult().getStdErr());
}
// test takes over 5 minutes to run, so not included in normal suite run
// public void test020_branchTargetOffsetTooLargeForShort() {
// runTest("Branch target offset too large for short");
// }
// public void test021_BcelFailureWithVeryLargeClasses() {
// runTest("Weaver fails in BCEL for large classes");
// }
//
// public void test022_BcelFailureWithVeryLargeClasses_Binary() {
// runTest("Weaver fails in BCEL for large classes (binary)");
// }
public void test023_proceedInAround1() {
runTest("proceed used as method name in around advice (1)");
}
public void test024_proceedInAround2() {
runTest("proceed used as method name in around advice (2)");
}
public void test025_proceedInAround3() {
runTest("proceed used as method name in around advice (3)");
}
public void test026_bindingThisAndTargetToTheSameFormal() {
runTest("ajc crashes when compiling the following program (binding this() and target())");
}
public void test027_itdsOnInnerClassesAsStatic() {
runTest("ITDs on inner classes should be static context");
}
public void test028_itdsAndInitializers() {
runTest("resolution of IT field inits");
}
public void test029_falseInvalidAbsoluteTypeName() {
runTest("Valid but inaccessible type names should not be flagged by XLint:invalidAbsoluteTypeName");
}
public void test030_privateITDinitialisersBeingMatched() {
runTest("intertype initialisers should match field set pointcuts");
}
public void test031_privateITDinitialisersBeingMatched_OxfordTest() {
runTest("intertype initialisers should match field set pointcuts (oxford testcase)");
//System.err.println(">"+getLastRunResult().getStdErr());
String exp = ":set field set(int C.n):set field set(int C.m):get field get(int C.n):set field set(int C.n)";
assertTrue("Expected output '"+exp+"' but got "+getLastRunResult().getStdErr(),
getLastRunResult().getStdErr().equals(exp));
}
public void test032_stringConcatForDEOW() {
runTest("Compile time declarations (warning and error) do not accept string concatenation (with +)");
}
public void test033_stringConcatForDEOWErrorCase() {
runTest("Compile time declarations (warning and error) do not accept string concatenation (with +) (2)");
}
public void test034_scopeForITDS_pr61768() {
runTest("scope for inter-type methods");
}
public void test035_innerAspectCallsPrivateMethod_pr71372() {
runTest("NoSuchMethodError calling private method from around advice in inner aspect");
String s = getLastRunResult().getStdErr();
assertTrue("Expected ':before:around' but got "+s,
s.equals(":before:around"));
}
public void test036_innerAspectCallsPrivateMethod_pr71372_2() {
runTest("NoSuchMethodError calling private method from around advice in inner aspect (2)");
String s = getLastRunResult().getStdErr();
assertTrue("Expected ':before:around' but got "+s,
s.equals(":before:around"));
}
public void test037_innerAspectCallsPrivateMethod_pr71372_3() {
runTest("NoSuchMethodError calling private method from around advice in inner aspect (3)");
String s = getLastRunResult().getStdErr();
assertTrue("Expected ':before:around' but got "+s,
s.equals(":before:around"));
}
public void test038_innerAspectCallsPrivateMethod_pr71372_4() {
runTest("NoSuchMethodError calling private method from around advice in inner aspect (4)");
String s = getLastRunResult().getStdErr();
assertTrue("Expected ':before:around' but got "+s,
s.equals(":before:around"));
}
public void test039_privilegedAspectAccessingPrivateMethods_pr67579() {
runTest("NPE on privileged aspect error");
}
public void test040_privilegedAspectAccessingPrivateMethods_pr67579_2() {
runTest("NPE on privileged aspect error (2)");
}
public void test041_ITDaccessingPrivateMethod_pr67578() {
runTest("Privileged Aspect Access Problem Across Packages");
}
public void test042_ITDaccessingPrivateMethod_pr67578_2() {
runTest("Privileged Aspect Access Problem Across Packages (2)");
}
public void test043_pr62642_ExceptionInInitializerError() {
runTest("proper handling of ExceptionInIntializer inside clinit in presence of after throwing advice");
String s = getLastRunResult().getStdErr();
assertTrue("Output should contain java.lang.ExceptionInInitializerError but is '"+s+"'",
s.indexOf("java.lang.ExceptionInInitializerError")!=-1);
// No getCause on 1.3 JVMs
// assertTrue("Output should contain 'CAUSE=org.aspectj.lang.NoAspectBoundException' but is '"+s+"'",
// s.indexOf("CAUSE=org.aspectj.lang.NoAspectBoundException")!=-1);
}
public void test044_ITDnameClashes() {
runTest("ITD name clashes with private members");
}
public void test045_ITDprotectedVisibility() {
runTest("Inconsistency in scoping of protected members in ITDs");
}
public void test045_wrongLineForExecutionJoinPoint() {
runTest("wrong line for method execution join point");
}
public void test046_interfaceITD_pr70794_1() {
runTest("The introduction on interface causes the interface implementation class error (1)");
}
public void test047_interfaceITD_pr70794_2() {
runTest("The introduction on interface causes the interface implementation class error (2)");
}
public void test048_interfaceITD_pr70794_3() {
runTest("The introduction on interface causes the interface implementation class error (3)");
}
public void test049_interfaceITD_pr70794_4() {
runTest("The introduction on interface causes the interface implementation class error (4)");
}
public void test050_typePatternMatchingWithArrays() {
runTest("declare warning warns at wrong points");
}
public void test051_arrayCloningInJava5() {
runTest("AJC possible bug with static nested classes");
}
}
|
49,743
|
Bug 49743 performance improvements for runtime library
|
I am heavily using the runtime signature information from thisJoinPoint.getSignature() and the toString() method of it. This causes heavy String operations each time the toString method is called. Would it be possible to cache the resulting string for example in MethodSignatureImpl and similar classes for other signatures?
|
resolved fixed
|
438e61c
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-01T10:30:07Z
| 2004-01-08T22:13:20Z
|
runtime/src/org/aspectj/runtime/reflect/AdviceSignatureImpl.java
|
/* *******************************************************************
* Copyright (c) 1999-2001 Xerox Corporation,
* 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Xerox/PARC initial implementation
* ******************************************************************/
package org.aspectj.runtime.reflect;
import org.aspectj.lang.reflect.AdviceSignature;
class AdviceSignatureImpl extends CodeSignatureImpl implements AdviceSignature {
Class returnType;
AdviceSignatureImpl(int modifiers, String name, Class declaringType,
Class[] parameterTypes, String[] parameterNames, Class[] exceptionTypes,
Class returnType)
{
super(modifiers, name, declaringType, parameterTypes, parameterNames,
exceptionTypes);
this.returnType = returnType;
}
AdviceSignatureImpl(String stringRep) {
super(stringRep);
}
/* name is consistent with reflection API
before and after always return Void.TYPE
(some around also return Void.Type) */
public Class getReturnType() {
if (returnType == null) returnType = extractType(6);
return returnType;
}
String toString(StringMaker sm) {
//XXX this signature needs a lot of work
StringBuffer buf = new StringBuffer("ADVICE: ");
buf.append(sm.makeModifiersString(getModifiers()));
if (sm.includeArgs) buf.append(sm.makeTypeName(getReturnType()));
if (sm.includeArgs) buf.append(" ");
buf.append(sm.makePrimaryTypeName(getDeclaringType(),getDeclaringTypeName()));
buf.append(".");
buf.append(getName());
sm.addSignature(buf, getParameterTypes());
sm.addThrows(buf, getExceptionTypes());
return buf.toString();
}
}
|
49,743
|
Bug 49743 performance improvements for runtime library
|
I am heavily using the runtime signature information from thisJoinPoint.getSignature() and the toString() method of it. This causes heavy String operations each time the toString method is called. Would it be possible to cache the resulting string for example in MethodSignatureImpl and similar classes for other signatures?
|
resolved fixed
|
438e61c
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-01T10:30:07Z
| 2004-01-08T22:13:20Z
|
runtime/src/org/aspectj/runtime/reflect/CatchClauseSignatureImpl.java
|
/* *******************************************************************
* Copyright (c) 1999-2001 Xerox Corporation,
* 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Xerox/PARC initial implementation
* ******************************************************************/
package org.aspectj.runtime.reflect;
import org.aspectj.lang.reflect.CatchClauseSignature;
class CatchClauseSignatureImpl extends SignatureImpl implements CatchClauseSignature {
Class parameterType;
String parameterName;
CatchClauseSignatureImpl(Class declaringType,
Class parameterType, String parameterName)
{
super(0, "catch", declaringType);
this.parameterType = parameterType;
this.parameterName = parameterName;
}
CatchClauseSignatureImpl(String stringRep) {
super(stringRep);
}
public Class getParameterType() {
if (parameterType == null) parameterType = extractType(3);
return parameterType;
}
public String getParameterName() {
if (parameterName == null) parameterName = extractString(4);
return parameterName;
}
String toString(StringMaker sm) {
return "catch(" + sm.makeTypeName(getParameterType()) + ")";
}
}
|
49,743
|
Bug 49743 performance improvements for runtime library
|
I am heavily using the runtime signature information from thisJoinPoint.getSignature() and the toString() method of it. This causes heavy String operations each time the toString method is called. Would it be possible to cache the resulting string for example in MethodSignatureImpl and similar classes for other signatures?
|
resolved fixed
|
438e61c
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-01T10:30:07Z
| 2004-01-08T22:13:20Z
|
runtime/src/org/aspectj/runtime/reflect/ConstructorSignatureImpl.java
|
/* *******************************************************************
* Copyright (c) 1999-2001 Xerox Corporation,
* 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Xerox/PARC initial implementation
* ******************************************************************/
package org.aspectj.runtime.reflect;
import org.aspectj.lang.reflect.ConstructorSignature;
class ConstructorSignatureImpl extends CodeSignatureImpl implements ConstructorSignature {
ConstructorSignatureImpl(int modifiers, Class declaringType,
Class[] parameterTypes, String[] parameterNames, Class[] exceptionTypes)
{
super(modifiers, "<init>", declaringType, parameterTypes, parameterNames, exceptionTypes);
}
ConstructorSignatureImpl(String stringRep) {
super(stringRep);
}
public String getName() { return "<init>"; }
String toString(StringMaker sm) {
StringBuffer buf = new StringBuffer();
buf.append(sm.makeModifiersString(getModifiers()));
buf.append(sm.makePrimaryTypeName(getDeclaringType(),getDeclaringTypeName()));
sm.addSignature(buf, getParameterTypes());
sm.addThrows(buf, getExceptionTypes());
return buf.toString();
}
}
|
49,743
|
Bug 49743 performance improvements for runtime library
|
I am heavily using the runtime signature information from thisJoinPoint.getSignature() and the toString() method of it. This causes heavy String operations each time the toString method is called. Would it be possible to cache the resulting string for example in MethodSignatureImpl and similar classes for other signatures?
|
resolved fixed
|
438e61c
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-01T10:30:07Z
| 2004-01-08T22:13:20Z
|
runtime/src/org/aspectj/runtime/reflect/Factory.java
|
/* *******************************************************************
* Copyright (c) 1999-2001 Xerox Corporation,
* 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Xerox/PARC initial implementation
* ******************************************************************/
package org.aspectj.runtime.reflect;
import org.aspectj.lang.*;
import org.aspectj.lang.reflect.*;
public final class Factory {
Class lexicalClass;
ClassLoader lookupClassLoader;
String filename;
public Factory(String filename, Class lexicalClass) {
//System.out.println("making
this.filename = filename;
this.lexicalClass = lexicalClass;
lookupClassLoader = lexicalClass.getClassLoader();
}
public JoinPoint.StaticPart makeSJP(String kind, Signature sig, SourceLocation loc) {
return new JoinPointImpl.StaticPartImpl(kind, sig, loc);
}
public JoinPoint.StaticPart makeSJP(String kind, Signature sig, int l, int c) {
return new JoinPointImpl.StaticPartImpl(kind, sig, makeSourceLoc(l, c));
}
public JoinPoint.StaticPart makeSJP(String kind, Signature sig, int l) {
return new JoinPointImpl.StaticPartImpl(kind, sig, makeSourceLoc(l, -1));
}
private static Object[] NO_ARGS = new Object[0];
public static JoinPoint makeJP(JoinPoint.StaticPart staticPart,
Object _this, Object target)
{
return new JoinPointImpl(staticPart, _this, target, NO_ARGS);
}
public static JoinPoint makeJP(JoinPoint.StaticPart staticPart,
Object _this, Object target, Object arg0)
{
return new JoinPointImpl(staticPart, _this, target, new Object[] {arg0});
}
public static JoinPoint makeJP(JoinPoint.StaticPart staticPart,
Object _this, Object target, Object arg0, Object arg1)
{
return new JoinPointImpl(staticPart, _this, target, new Object[] {arg0, arg1});
}
public static JoinPoint makeJP(JoinPoint.StaticPart staticPart,
Object _this, Object target, Object[] args)
{
return new JoinPointImpl(staticPart, _this, target, args);
}
public MethodSignature makeMethodSig(String stringRep) {
MethodSignatureImpl ret = new MethodSignatureImpl(stringRep);
ret.setLookupClassLoader(lookupClassLoader);
return ret;
}
public MethodSignature makeMethodSig(int modifiers, String name, Class declaringType,
Class[] parameterTypes, String[] parameterNames, Class[] exceptionTypes,
Class returnType) {
MethodSignatureImpl ret = new MethodSignatureImpl(modifiers,name,declaringType,parameterTypes,parameterNames,exceptionTypes,returnType);
ret.setLookupClassLoader(lookupClassLoader);
return ret;
}
public ConstructorSignature makeConstructorSig(String stringRep) {
ConstructorSignatureImpl ret = new ConstructorSignatureImpl(stringRep);
ret.setLookupClassLoader(lookupClassLoader);
return ret;
}
public ConstructorSignature makeConstructorSig(int modifiers, Class declaringType,
Class[] parameterTypes, String[] parameterNames, Class[] exceptionTypes) {
ConstructorSignatureImpl ret = new ConstructorSignatureImpl(modifiers,declaringType,parameterTypes,parameterNames,exceptionTypes);
ret.setLookupClassLoader(lookupClassLoader);
return ret;
}
public FieldSignature makeFieldSig(String stringRep) {
FieldSignatureImpl ret = new FieldSignatureImpl(stringRep);
ret.setLookupClassLoader(lookupClassLoader);
return ret;
}
public FieldSignature makeFieldSig(int modifiers, String name, Class declaringType,
Class fieldType) {
FieldSignatureImpl ret = new FieldSignatureImpl(modifiers,name,declaringType,fieldType);
ret.setLookupClassLoader(lookupClassLoader);
return ret;
}
public AdviceSignature makeAdviceSig(String stringRep) {
AdviceSignatureImpl ret = new AdviceSignatureImpl(stringRep);
ret.setLookupClassLoader(lookupClassLoader);
return ret;
}
public AdviceSignature makeAdviceSig(int modifiers, String name, Class declaringType,
Class[] parameterTypes, String[] parameterNames, Class[] exceptionTypes,
Class returnType) {
AdviceSignatureImpl ret = new AdviceSignatureImpl(modifiers,name,declaringType,parameterTypes,parameterNames,exceptionTypes,returnType);
ret.setLookupClassLoader(lookupClassLoader);
return ret;
}
public InitializerSignature makeInitializerSig(String stringRep) {
InitializerSignatureImpl ret = new InitializerSignatureImpl(stringRep);
ret.setLookupClassLoader(lookupClassLoader);
return ret;
}
public InitializerSignature makeInitializerSig(int modifiers, Class declaringType) {
InitializerSignatureImpl ret = new InitializerSignatureImpl(modifiers,declaringType);
ret.setLookupClassLoader(lookupClassLoader);
return ret;
}
public CatchClauseSignature makeCatchClauseSig(String stringRep) {
CatchClauseSignatureImpl ret = new CatchClauseSignatureImpl(stringRep);
ret.setLookupClassLoader(lookupClassLoader);
return ret;
}
public CatchClauseSignature makeCatchClauseSig(Class declaringType,
Class parameterType, String parameterName) {
CatchClauseSignatureImpl ret = new CatchClauseSignatureImpl(declaringType,parameterType,parameterName);
ret.setLookupClassLoader(lookupClassLoader);
return ret;
}
public SourceLocation makeSourceLoc(int line, int col)
{
return new SourceLocationImpl(lexicalClass, this.filename, line, col);
}
}
|
49,743
|
Bug 49743 performance improvements for runtime library
|
I am heavily using the runtime signature information from thisJoinPoint.getSignature() and the toString() method of it. This causes heavy String operations each time the toString method is called. Would it be possible to cache the resulting string for example in MethodSignatureImpl and similar classes for other signatures?
|
resolved fixed
|
438e61c
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-01T10:30:07Z
| 2004-01-08T22:13:20Z
|
runtime/src/org/aspectj/runtime/reflect/FieldSignatureImpl.java
|
/* *******************************************************************
* Copyright (c) 1999-2001 Xerox Corporation,
* 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Xerox/PARC initial implementation
* ******************************************************************/
package org.aspectj.runtime.reflect;
import org.aspectj.lang.reflect.FieldSignature;
public class FieldSignatureImpl extends MemberSignatureImpl implements FieldSignature {
Class fieldType;
FieldSignatureImpl(int modifiers, String name, Class declaringType,
Class fieldType)
{
super(modifiers, name, declaringType);
this.fieldType = fieldType;
}
FieldSignatureImpl(String stringRep) {
super(stringRep);
}
public Class getFieldType() {
if (fieldType == null) fieldType = extractType(3);
return fieldType;
}
String toString(StringMaker sm) {
StringBuffer buf = new StringBuffer();
buf.append(sm.makeModifiersString(getModifiers()));
if (sm.includeArgs) buf.append(sm.makeTypeName(getFieldType()));
if (sm.includeArgs) buf.append(" ");
buf.append(sm.makePrimaryTypeName(getDeclaringType(),getDeclaringTypeName()));
buf.append(".");
buf.append(getName());
return buf.toString();
}
}
|
49,743
|
Bug 49743 performance improvements for runtime library
|
I am heavily using the runtime signature information from thisJoinPoint.getSignature() and the toString() method of it. This causes heavy String operations each time the toString method is called. Would it be possible to cache the resulting string for example in MethodSignatureImpl and similar classes for other signatures?
|
resolved fixed
|
438e61c
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-01T10:30:07Z
| 2004-01-08T22:13:20Z
|
runtime/src/org/aspectj/runtime/reflect/InitializerSignatureImpl.java
|
/* *******************************************************************
* Copyright (c) 1999-2001 Xerox Corporation,
* 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Xerox/PARC initial implementation
* ******************************************************************/
package org.aspectj.runtime.reflect;
import org.aspectj.lang.reflect.InitializerSignature;
import java.lang.reflect.Modifier;
class InitializerSignatureImpl extends CodeSignatureImpl implements InitializerSignature {
InitializerSignatureImpl(int modifiers, Class declaringType) {
super(modifiers, Modifier.isStatic(modifiers) ? "<clinit>" : "<init>", declaringType, EMPTY_CLASS_ARRAY,
EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY);
}
InitializerSignatureImpl(String stringRep) {
super(stringRep);
}
public String getName() {
return Modifier.isStatic(getModifiers()) ? "<clinit>": "<init>";
}
String toString(StringMaker sm) {
StringBuffer buf = new StringBuffer();
buf.append(sm.makeModifiersString(getModifiers()));
buf.append(sm.makePrimaryTypeName(getDeclaringType(),getDeclaringTypeName()));
buf.append(".");
buf.append(getName());
return buf.toString();
}
}
|
49,743
|
Bug 49743 performance improvements for runtime library
|
I am heavily using the runtime signature information from thisJoinPoint.getSignature() and the toString() method of it. This causes heavy String operations each time the toString method is called. Would it be possible to cache the resulting string for example in MethodSignatureImpl and similar classes for other signatures?
|
resolved fixed
|
438e61c
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-01T10:30:07Z
| 2004-01-08T22:13:20Z
|
runtime/src/org/aspectj/runtime/reflect/MethodSignatureImpl.java
|
/* *******************************************************************
* Copyright (c) 1999-2001 Xerox Corporation,
* 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Xerox/PARC initial implementation
* ******************************************************************/
package org.aspectj.runtime.reflect;
import org.aspectj.lang.reflect.MethodSignature;
class MethodSignatureImpl extends CodeSignatureImpl implements MethodSignature {
Class returnType;
MethodSignatureImpl(int modifiers, String name, Class declaringType,
Class[] parameterTypes, String[] parameterNames, Class[] exceptionTypes,
Class returnType)
{
super(modifiers, name, declaringType, parameterTypes, parameterNames,
exceptionTypes);
this.returnType = returnType;
}
MethodSignatureImpl(String stringRep) {
super(stringRep);
}
/* name is consistent with reflection API */
public Class getReturnType() {
if (returnType == null) returnType = extractType(6);
return returnType;
}
String toString(StringMaker sm) {
StringBuffer buf = new StringBuffer();
buf.append(sm.makeModifiersString(getModifiers()));
if (sm.includeArgs) buf.append(sm.makeTypeName(getReturnType()));
if (sm.includeArgs) buf.append(" ");
buf.append(sm.makePrimaryTypeName(getDeclaringType(),getDeclaringTypeName()));
buf.append(".");
buf.append(getName());
sm.addSignature(buf, getParameterTypes());
sm.addThrows(buf, getExceptionTypes());
return buf.toString();
}
}
|
49,743
|
Bug 49743 performance improvements for runtime library
|
I am heavily using the runtime signature information from thisJoinPoint.getSignature() and the toString() method of it. This causes heavy String operations each time the toString method is called. Would it be possible to cache the resulting string for example in MethodSignatureImpl and similar classes for other signatures?
|
resolved fixed
|
438e61c
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-01T10:30:07Z
| 2004-01-08T22:13:20Z
|
runtime/src/org/aspectj/runtime/reflect/SignatureImpl.java
|
/* *******************************************************************
* Copyright (c) 1999-2001 Xerox Corporation,
* 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Xerox/PARC initial implementation
* ******************************************************************/
package org.aspectj.runtime.reflect;
import org.aspectj.lang.Signature;
import java.util.Hashtable;
import java.util.StringTokenizer;
abstract class SignatureImpl implements Signature {
int modifiers = -1;
String name;
String declaringTypeName;
Class declaringType;
SignatureImpl(int modifiers, String name, Class declaringType) {
this.modifiers = modifiers;
this.name = name;
this.declaringType = declaringType;
}
abstract String toString(StringMaker sm);
public final String toString() { return toString(StringMaker.middleStringMaker); }
public final String toShortString() { return toString(StringMaker.shortStringMaker); }
public final String toLongString() { return toString(StringMaker.longStringMaker); }
public int getModifiers() {
if (modifiers == -1) modifiers = extractInt(0);
return modifiers;
}
public String getName() {
if (name == null) name = extractString(1);
return name;
}
public Class getDeclaringType() {
if (declaringType == null) declaringType = extractType(2);
return declaringType;
}
public String getDeclaringTypeName() {
if (declaringTypeName == null) {
declaringTypeName = getDeclaringType().getName();
}
return declaringTypeName;
}
String fullTypeName(Class type) {
if (type == null) return "ANONYMOUS";
if (type.isArray()) return fullTypeName(type.getComponentType()) + "[]";
return type.getName().replace('$', '.');
}
String stripPackageName(String name) {
int dot = name.lastIndexOf('.');
if (dot == -1) return name;
return name.substring(dot+1);
}
String shortTypeName(Class type) {
if (type == null) return "ANONYMOUS";
if (type.isArray()) return shortTypeName(type.getComponentType()) + "[]";
return stripPackageName(type.getName()).replace('$', '.');
}
void addFullTypeNames(StringBuffer buf, Class[] types) {
for (int i = 0; i < types.length; i++) {
if (i > 0) buf.append(", ");
buf.append(fullTypeName(types[i]));
}
}
void addShortTypeNames(StringBuffer buf, Class[] types) {
for (int i = 0; i < types.length; i++) {
if (i > 0) buf.append(", ");
buf.append(shortTypeName(types[i]));
}
}
void addTypeArray(StringBuffer buf, Class[] types) {
addFullTypeNames(buf, types);
}
// lazy version
String stringRep;
ClassLoader lookupClassLoader = null;
public void setLookupClassLoader(ClassLoader loader) {
this.lookupClassLoader = loader;
}
private ClassLoader getLookupClassLoader() {
if (lookupClassLoader == null) lookupClassLoader = this.getClass().getClassLoader();
return lookupClassLoader;
}
public SignatureImpl(String stringRep) {
this.stringRep = stringRep;
}
static final char SEP = '-';
String extractString(int n) {
//System.out.println(n + ": from " + stringRep);
int startIndex = 0;
int endIndex = stringRep.indexOf(SEP);
while (n-- > 0) {
startIndex = endIndex+1;
endIndex = stringRep.indexOf(SEP, startIndex);
}
if (endIndex == -1) endIndex = stringRep.length();
//System.out.println(" " + stringRep.substring(startIndex, endIndex));
return stringRep.substring(startIndex, endIndex);
}
int extractInt(int n) {
String s = extractString(n);
return Integer.parseInt(s, 16);
}
Class extractType(int n) {
String s = extractString(n);
return makeClass(s);
}
static Hashtable prims = new Hashtable();
static {
prims.put("void", Void.TYPE);
prims.put("boolean", Boolean.TYPE);
prims.put("byte", Byte.TYPE);
prims.put("char", Character.TYPE);
prims.put("short", Short.TYPE);
prims.put("int", Integer.TYPE);
prims.put("long", Long.TYPE);
prims.put("float", Float.TYPE);
prims.put("double", Double.TYPE);
}
Class makeClass(String s) {
if (s.equals("*")) return null;
Class ret = (Class)prims.get(s);
if (ret != null) return ret;
try {
/* The documentation of Class.forName explains why this is the right thing
* better than I could here.
*/
ClassLoader loader = getLookupClassLoader();
if (loader == null) {
return Class.forName(s);
} else {
// used to be 'return loader.loadClass(s)' but that didn't cause
// array types to be created and loaded correctly. (pr70404)
return Class.forName(s,false,loader);
}
} catch (ClassNotFoundException e) {
//System.out.println("null for: " + s);
//XXX there should be a better return value for this
return ClassNotFoundException.class;
}
}
static String[] EMPTY_STRING_ARRAY = new String[0];
static Class[] EMPTY_CLASS_ARRAY = new Class[0];
static final String INNER_SEP = ":";
String[] extractStrings(int n) {
String s = extractString(n);
StringTokenizer st = new StringTokenizer(s, INNER_SEP);
final int N = st.countTokens();
String[] ret = new String[N];
for (int i = 0; i < N; i++) ret[i]= st.nextToken();
return ret;
}
Class[] extractTypes(int n) {
String s = extractString(n);
StringTokenizer st = new StringTokenizer(s, INNER_SEP);
final int N = st.countTokens();
Class[] ret = new Class[N];
for (int i = 0; i < N; i++) ret[i]= makeClass(st.nextToken());
return ret;
}
}
|
49,743
|
Bug 49743 performance improvements for runtime library
|
I am heavily using the runtime signature information from thisJoinPoint.getSignature() and the toString() method of it. This causes heavy String operations each time the toString method is called. Would it be possible to cache the resulting string for example in MethodSignatureImpl and similar classes for other signatures?
|
resolved fixed
|
438e61c
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-01T10:30:07Z
| 2004-01-08T22:13:20Z
|
runtime/src/org/aspectj/runtime/reflect/SourceLocationImpl.java
|
/* *******************************************************************
* Copyright (c) 1999-2001 Xerox Corporation,
* 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Xerox/PARC initial implementation
* ******************************************************************/
package org.aspectj.runtime.reflect;
import org.aspectj.lang.reflect.SourceLocation;
class SourceLocationImpl implements SourceLocation {
Class withinType;
String fileName;
int line;
int column;
SourceLocationImpl(Class withinType, String fileName, int line, int column) {
this.withinType = withinType;
this.fileName = fileName;
this.line = line;
this.column = column;
}
public Class getWithinType() { return withinType; }
public String getFileName() { return fileName; }
public int getLine() { return line; }
public int getColumn() { return column; }
public String toString() {
return getFileName() + ":" + getLine() +
((getColumn() == -1) ? "" : ":" + getColumn());
}
}
|
49,743
|
Bug 49743 performance improvements for runtime library
|
I am heavily using the runtime signature information from thisJoinPoint.getSignature() and the toString() method of it. This causes heavy String operations each time the toString method is called. Would it be possible to cache the resulting string for example in MethodSignatureImpl and similar classes for other signatures?
|
resolved fixed
|
438e61c
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-01T10:30:07Z
| 2004-01-08T22:13:20Z
|
runtime/src/org/aspectj/runtime/reflect/StringMaker.java
|
/* *******************************************************************
* Copyright (c) 1999-2001 Xerox Corporation,
* 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Xerox/PARC initial implementation
* ******************************************************************/
package org.aspectj.runtime.reflect;
import java.lang.reflect.Modifier;
class StringMaker {
boolean shortTypeNames = true;
boolean includeArgs = true;
boolean includeThrows = false;
boolean includeModifiers = false;
boolean shortPrimaryTypeNames = false;
boolean includeJoinPointTypeName = true;
boolean includeEnclosingPoint = true;
boolean shortKindName = true;
static StringMaker shortStringMaker;
static {
shortStringMaker = new StringMaker();
shortStringMaker.shortTypeNames = true;
shortStringMaker.includeArgs = false;
shortStringMaker.includeThrows = false;
shortStringMaker.includeModifiers = false;
shortStringMaker.shortPrimaryTypeNames = true;
shortStringMaker.includeJoinPointTypeName = false;
shortStringMaker.includeEnclosingPoint = false;
}
static StringMaker middleStringMaker;
static {
middleStringMaker = new StringMaker();
middleStringMaker.shortTypeNames = true;
middleStringMaker.includeArgs = true;
middleStringMaker.includeThrows = false;
middleStringMaker.includeModifiers = false;
middleStringMaker.shortPrimaryTypeNames = false;
}
static StringMaker longStringMaker;
static {
longStringMaker = new StringMaker();
longStringMaker.shortTypeNames = false;
longStringMaker.includeArgs = true;
longStringMaker.includeThrows = false;
longStringMaker.includeModifiers = true;
longStringMaker.shortPrimaryTypeNames = false;
longStringMaker.shortKindName = false;
}
String makeKindName(String name) {
int dash = name.lastIndexOf('-');
if (dash == -1) return name;
return name.substring(dash+1);
}
String makeModifiersString(int modifiers) {
if (!includeModifiers) return "";
String str = Modifier.toString(modifiers);
if (str.length() == 0) return "";
return str + " ";
}
String stripPackageName(String name) {
int dot = name.lastIndexOf('.');
if (dot == -1) return name;
return name.substring(dot+1);
}
String makeTypeName(Class type, String typeName, boolean shortName) {
if (type == null) return "ANONYMOUS";
if (type.isArray()) {
Class componentType = type.getComponentType();
return makeTypeName(componentType, componentType.getName(), shortName) + "[]";
}
if (shortName) {
return stripPackageName(typeName).replace('$', '.');
} else {
return typeName.replace('$', '.');
}
}
public String makeTypeName(Class type) {
return makeTypeName(type, type.getName(),shortTypeNames);
}
public String makePrimaryTypeName(Class type, String typeName) {
return makeTypeName(type, typeName, shortPrimaryTypeNames);
}
public void addTypeNames(StringBuffer buf, Class[] types) {
for (int i = 0; i < types.length; i++) {
if (i > 0) buf.append(", ");
buf.append(makeTypeName(types[i]));
}
}
public void addSignature(StringBuffer buf, Class[] types) {
if (types == null) return;
if (!includeArgs) {
if (types.length == 0) {
buf.append("()");
return;
} else {
buf.append("(..)");
return;
}
}
buf.append("(");
addTypeNames(buf, types);
buf.append(")");
}
public void addThrows(StringBuffer buf, Class[] types) {
if (!includeThrows || types == null || types.length == 0) return;
buf.append(" throws ");
addTypeNames(buf, types);
}
}
|
49,743
|
Bug 49743 performance improvements for runtime library
|
I am heavily using the runtime signature information from thisJoinPoint.getSignature() and the toString() method of it. This causes heavy String operations each time the toString method is called. Would it be possible to cache the resulting string for example in MethodSignatureImpl and similar classes for other signatures?
|
resolved fixed
|
438e61c
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-01T10:30:07Z
| 2004-01-08T22:13:20Z
|
runtime/testsrc/RuntimeModuleTests.java
|
/* *******************************************************************
* Copyright (c) 1999-2001 Xerox Corporation,
* 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Xerox/PARC initial implementation
* ******************************************************************/
// default package
import java.io.*;
import org.aspectj.lang.*;
import org.aspectj.runtime.reflect.JoinPointImplTest;
import org.aspectj.runtime.reflect.SignatureTest;
import junit.framework.*;
public class RuntimeModuleTests extends TestCase {
public static TestSuite suite() {
TestSuite suite = new TestSuite(RuntimeModuleTests.class.getName());
suite.addTestSuite(RuntimeModuleTests.class); // minimum 1 test (testNothing)
suite.addTestSuite(SignatureTest.class);
suite.addTestSuite(JoinPointImplTest.class);
return suite;
}
public RuntimeModuleTests(String name) { super(name); }
public void testNoAspectBoundException() {
RuntimeException fun = new RuntimeException("fun");
NoAspectBoundException nab = new NoAspectBoundException("Foo", fun);
assertEquals(fun,nab.getCause());
}
public void testSoftExceptionPrintStackTrace() {
// let's see
// Throwable t = new Error("xyz");
// new SoftException(t).printStackTrace();
// save to specified PrintStream
ByteArrayOutputStream sink = new ByteArrayOutputStream();
PrintStream out = new PrintStream(sink);
new SoftException(new Error("xyz")).printStackTrace(out);
String s = new String(sink.toByteArray());
out.flush();
checkSoftExceptionString(s);
// save to specified PrintWriter
sink = new ByteArrayOutputStream();
PrintWriter pout = new PrintWriter(sink);
new SoftException(new Error("xyz")).printStackTrace(pout);
pout.flush();
s = new String(sink.toByteArray());
checkSoftExceptionString(s);
// check System.err redirect
PrintStream systemErr = System.err;
try {
sink = new ByteArrayOutputStream();
out = new PrintStream(sink);
System.setErr(out);
new SoftException(new Error("xyz")).printStackTrace();
out.flush();
s = new String(sink.toByteArray());
checkSoftExceptionString(s);
} finally {
System.setErr(systemErr);
}
}
static void checkSoftExceptionString(String s) {
assertTrue(-1 != s.indexOf("SoftException"));
assertTrue(-1 != s.indexOf("Caused by: java.lang.Error"));
assertTrue(-1 != s.indexOf("xyz"));
assertTrue(-1 != s.indexOf("testSoftExceptionPrintStackTrace"));
}
}
|
49,743
|
Bug 49743 performance improvements for runtime library
|
I am heavily using the runtime signature information from thisJoinPoint.getSignature() and the toString() method of it. This causes heavy String operations each time the toString method is called. Would it be possible to cache the resulting string for example in MethodSignatureImpl and similar classes for other signatures?
|
resolved fixed
|
438e61c
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-01T10:30:07Z
| 2004-01-08T22:13:20Z
|
runtime/testsrc/org/aspectj/runtime/reflect/RuntimePerformanceTest.java
| |
49,743
|
Bug 49743 performance improvements for runtime library
|
I am heavily using the runtime signature information from thisJoinPoint.getSignature() and the toString() method of it. This causes heavy String operations each time the toString method is called. Would it be possible to cache the resulting string for example in MethodSignatureImpl and similar classes for other signatures?
|
resolved fixed
|
438e61c
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-01T10:30:07Z
| 2004-01-08T22:13:20Z
|
runtime/testsrc/org/aspectj/runtime/reflect/SignatureTest.java
|
/*******************************************************************************
* Copyright (c) 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.aspectj.runtime.reflect;
import junit.framework.TestCase;
/**
*/
public class SignatureTest extends TestCase {
public void testGetDeclaringTypeName() {
FieldSignatureImpl fsi = new FieldSignatureImpl(0,"x",SignatureTest.class,String.class);
assertEquals(SignatureTest.class.getName(),fsi.getDeclaringTypeName());
assertSame(fsi.getDeclaringTypeName(),fsi.getDeclaringTypeName()); // should be cached.
}
}
|
46,298
|
Bug 46298 Aspectj generate code does not de-compile cleanly.
| null |
resolved fixed
|
4921f0c
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-01T15:26:43Z
| 2003-11-07T18:33:20Z
|
weaver/src/org/aspectj/weaver/bcel/BcelShadow.java
|
/* *******************************************************************
* 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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.bcel;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.aspectj.apache.bcel.Constants;
import org.aspectj.apache.bcel.classfile.Field;
import org.aspectj.apache.bcel.generic.ACONST_NULL;
import org.aspectj.apache.bcel.generic.ArrayType;
import org.aspectj.apache.bcel.generic.BranchInstruction;
import org.aspectj.apache.bcel.generic.ConstantPoolGen;
import org.aspectj.apache.bcel.generic.DUP;
import org.aspectj.apache.bcel.generic.DUP_X1;
import org.aspectj.apache.bcel.generic.FieldInstruction;
import org.aspectj.apache.bcel.generic.INVOKESPECIAL;
import org.aspectj.apache.bcel.generic.INVOKESTATIC;
import org.aspectj.apache.bcel.generic.Instruction;
import org.aspectj.apache.bcel.generic.InstructionConstants;
import org.aspectj.apache.bcel.generic.InstructionFactory;
import org.aspectj.apache.bcel.generic.InstructionHandle;
import org.aspectj.apache.bcel.generic.InstructionList;
import org.aspectj.apache.bcel.generic.InstructionTargeter;
import org.aspectj.apache.bcel.generic.InvokeInstruction;
import org.aspectj.apache.bcel.generic.NEW;
import org.aspectj.apache.bcel.generic.ObjectType;
import org.aspectj.apache.bcel.generic.ReturnInstruction;
import org.aspectj.apache.bcel.generic.SWAP;
import org.aspectj.apache.bcel.generic.StoreInstruction;
import org.aspectj.apache.bcel.generic.TargetLostException;
import org.aspectj.apache.bcel.generic.Type;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.Message;
import org.aspectj.weaver.Advice;
import org.aspectj.weaver.AdviceKind;
import org.aspectj.weaver.AjcMemberMaker;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.IntMap;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.NameMangler;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedTypeX;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.ShadowMunger;
import org.aspectj.weaver.TypeX;
import org.aspectj.weaver.WeaverMessages;
import org.aspectj.weaver.World;
import org.aspectj.weaver.ast.Var;
/*
* Some fun implementation stuff:
*
* * expressionKind advice is non-execution advice
* * may have a target.
* * if the body is extracted, it will be extracted into
* a static method. The first argument to the static
* method is the target
* * advice may expose a this object, but that's the advice's
* consideration, not ours. This object will NOT be cached in another
* local, but will always come from frame zero.
*
* * non-expressionKind advice is execution advice
* * may have a this.
* * target is same as this, and is exposed that way to advice
* (i.e., target will not be cached, will always come from frame zero)
* * if the body is extracted, it will be extracted into a method
* with same static/dynamic modifier as enclosing method. If non-static,
* target of callback call will be this.
*
* * because of these two facts, the setup of the actual arguments (including
* possible target) callback method is the same for both kinds of advice:
* push the targetVar, if it exists (it will not exist for advice on static
* things), then push all the argVars.
*
* Protected things:
*
* * the above is sufficient for non-expressionKind advice for protected things,
* since the target will always be this.
*
* * For expressionKind things, we have to modify the signature of the callback
* method slightly. For non-static expressionKind things, we modify
* the first argument of the callback method NOT to be the type specified
* by the method/field signature (the owner), but rather we type it to
* the currentlyEnclosing type. We are guaranteed this will be fine,
* since the verifier verifies that the target is a subtype of the currently
* enclosingType.
*
* Worries:
*
* * ConstructorCalls will be weirder than all of these, since they
* supposedly don't have a target (according to AspectJ), but they clearly
* do have a target of sorts, just one that needs to be pushed on the stack,
* dupped, and not touched otherwise until the constructor runs.
*
* @author Jim Hugunin
* @author Erik Hilsdale
*
*/
public class BcelShadow extends Shadow {
private ShadowRange range;
private final BcelWorld world;
private final LazyMethodGen enclosingMethod;
private boolean fallsThrough; //XXX not used anymore
// ---- initialization
/**
* This generates an unassociated shadow, rooted in a particular method but not rooted
* to any particular point in the code. It should be given to a rooted ShadowRange
* in the {@link ShadowRange#associateWithShadow(BcelShadow)} method.
*/
public BcelShadow(
BcelWorld world,
Kind kind,
Member signature,
LazyMethodGen enclosingMethod,
BcelShadow enclosingShadow)
{
super(kind, signature, enclosingShadow);
this.world = world;
this.enclosingMethod = enclosingMethod;
fallsThrough = kind.argsOnStack();
}
// ---- copies all state, including Shadow's mungers...
public BcelShadow copyInto(LazyMethodGen recipient, BcelShadow enclosing) {
BcelShadow s = new BcelShadow(world, getKind(), getSignature(), recipient, enclosing);
List src = mungers;
List dest = s.mungers;
for (Iterator i = src.iterator(); i.hasNext(); ) {
dest.add(i.next());
}
return s;
}
// ---- overridden behaviour
public World getIWorld() {
return world;
}
private void deleteNewAndDup() {
final ConstantPoolGen cpg = getEnclosingClass().getConstantPoolGen();
int depth = 1;
InstructionHandle ih = range.getStart();
while (true) {
Instruction inst = ih.getInstruction();
if (inst instanceof INVOKESPECIAL
&& ((INVOKESPECIAL) inst).getName(cpg).equals("<init>")) {
depth++;
} else if (inst instanceof NEW) {
depth--;
if (depth == 0) break;
}
ih = ih.getPrev();
}
// now IH points to the NEW. We're followed by the DUP, and that is followed
// by the actual instruciton we care about.
InstructionHandle newHandle = ih;
InstructionHandle endHandle = newHandle.getNext();
InstructionHandle nextHandle;
if (endHandle.getInstruction() instanceof DUP) {
nextHandle = endHandle.getNext();
retargetFrom(newHandle, nextHandle);
retargetFrom(endHandle, nextHandle);
} else if (endHandle.getInstruction() instanceof DUP_X1) {
InstructionHandle dupHandle = endHandle;
endHandle = endHandle.getNext();
nextHandle = endHandle.getNext();
if (endHandle.getInstruction() instanceof SWAP) {}
else {
// XXX see next XXX comment
throw new RuntimeException("Unhandled kind of new " + endHandle);
}
retargetFrom(newHandle, nextHandle);
retargetFrom(dupHandle, nextHandle);
retargetFrom(endHandle, nextHandle);
} else {
endHandle = newHandle;
nextHandle = endHandle.getNext();
retargetFrom(newHandle, nextHandle);
// add a POP here... we found a NEW w/o a dup or anything else, so
// we must be in statement context.
getRange().insert(InstructionConstants.POP, Range.OutsideAfter);
}
// assert (dupHandle.getInstruction() instanceof DUP);
try {
range.getBody().delete(newHandle, endHandle);
} catch (TargetLostException e) {
throw new BCException("shouldn't happen");
}
}
private void retargetFrom(InstructionHandle old, InstructionHandle fresh) {
InstructionTargeter[] sources = old.getTargeters();
if (sources != null) {
for (int i = sources.length - 1; i >= 0; i--) {
sources[i].updateTarget(old, fresh);
}
}
}
protected void prepareForMungers() {
// if we're a constructor call, we need to remove the new:dup or the new:dup_x1:swap,
// and store all our
// arguments on the frame.
// ??? This is a bit of a hack (for the Java langauge). We do this because
// we sometime add code "outsideBefore" when dealing with weaving join points. We only
// do this for exposing state that is on the stack. It turns out to just work for
// everything except for constructor calls and exception handlers. If we were to clean
// this up, every ShadowRange would have three instructionHandle points, the start of
// the arg-setup code, the start of the running code, and the end of the running code.
if (getKind() == ConstructorCall) {
deleteNewAndDup();
initializeArgVars();
} else if (getKind() == ExceptionHandler) {
ShadowRange range = getRange();
InstructionList body = range.getBody();
InstructionHandle start = range.getStart();
InstructionHandle freshIh = body.insert(start, InstructionConstants.NOP);
InstructionTargeter[] targeters = start.getTargeters();
for (int i = 0; i < targeters.length; i++) {
InstructionTargeter t = targeters[i];
if (t instanceof ExceptionRange) {
ExceptionRange er = (ExceptionRange) t;
er.updateTarget(start, freshIh, body);
}
}
}
// now we ask each munger to request our state
isThisJoinPointLazy = world.isXlazyTjp();
for (Iterator iter = mungers.iterator(); iter.hasNext();) {
ShadowMunger munger = (ShadowMunger) iter.next();
munger.specializeOn(this);
}
initializeThisJoinPoint();
// If we are an expression kind, we require our target/arguments on the stack
// before we do our actual thing. However, they may have been removed
// from the stack as the shadowMungers have requested state.
// if any of our shadowMungers requested either the arguments or target,
// the munger will have added code
// to pop the target/arguments into temporary variables, represented by
// targetVar and argVars. In such a case, we must make sure to re-push the
// values.
// If we are nonExpressionKind, we don't expect arguments on the stack
// so this is moot. If our argVars happen to be null, then we know that
// no ShadowMunger has squirrelled away our arguments, so they're still
// on the stack.
InstructionFactory fact = getFactory();
if (getKind().argsOnStack() && argVars != null) {
range.insert(
BcelRenderer.renderExprs(fact, world, argVars),
Range.InsideBefore);
if (targetVar != null) {
range.insert(
BcelRenderer.renderExpr(fact, world, targetVar),
Range.InsideBefore);
}
if (getKind() == ConstructorCall) {
range.insert((Instruction) InstructionFactory.createDup(1), Range.InsideBefore);
range.insert(
fact.createNew(
(ObjectType) BcelWorld.makeBcelType(
getSignature().getDeclaringType())),
Range.InsideBefore);
}
}
}
// ---- getters
public ShadowRange getRange() {
return range;
}
public void setRange(ShadowRange range) {
this.range = range;
}
public int getSourceLine() {
// if the kind of join point for which we are a shadow represents
// a method or constructor execution, then the best source line is
// the one from the enclosingMethod declarationLineNumber if available.
Kind kind = getKind();
if ( (kind == MethodExecution) ||
(kind == ConstructorExecution) ||
(kind == AdviceExecution) ||
(kind == StaticInitialization) ||
(kind == PreInitialization) ||
(kind == Initialization)) {
if (getEnclosingMethod().hasDeclaredLineNumberInfo()) {
return getEnclosingMethod().getDeclarationLineNumber();
}
}
if (range == null) {
if (getEnclosingMethod().hasBody()) {
return Utility.getSourceLine(getEnclosingMethod().getBody().getStart());
} else {
return 0;
}
}
int ret = Utility.getSourceLine(range.getStart());
if (ret < 0) return 0;
return ret;
}
// overrides
public TypeX getEnclosingType() {
return getEnclosingClass().getType();
}
public LazyClassGen getEnclosingClass() {
return enclosingMethod.getEnclosingClass();
}
public BcelWorld getWorld() {
return world;
}
// ---- factory methods
public static BcelShadow makeConstructorExecution(
BcelWorld world,
LazyMethodGen enclosingMethod,
InstructionHandle justBeforeStart)
{
final InstructionList body = enclosingMethod.getBody();
BcelShadow s =
new BcelShadow(
world,
ConstructorExecution,
world.makeMethodSignature(enclosingMethod),
enclosingMethod,
null);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, justBeforeStart.getNext()),
Range.genEnd(body));
return s;
}
public static BcelShadow makeStaticInitialization(
BcelWorld world,
LazyMethodGen enclosingMethod)
{
InstructionList body = enclosingMethod.getBody();
// move the start past ajc$preClinit
InstructionHandle clinitStart = body.getStart();
if (clinitStart.getInstruction() instanceof InvokeInstruction) {
InvokeInstruction ii = (InvokeInstruction)clinitStart.getInstruction();
if (ii
.getName(enclosingMethod.getEnclosingClass().getConstantPoolGen())
.equals(NameMangler.AJC_PRE_CLINIT_NAME)) {
clinitStart = clinitStart.getNext();
}
}
InstructionHandle clinitEnd = body.getEnd();
//XXX should move the end before the postClinit, but the return is then tricky...
// if (clinitEnd.getInstruction() instanceof InvokeInstruction) {
// InvokeInstruction ii = (InvokeInstruction)clinitEnd.getInstruction();
// if (ii.getName(enclosingMethod.getEnclosingClass().getConstantPoolGen()).equals(NameMangler.AJC_POST_CLINIT_NAME)) {
// clinitEnd = clinitEnd.getPrev();
// }
// }
BcelShadow s =
new BcelShadow(
world,
StaticInitialization,
world.makeMethodSignature(enclosingMethod),
enclosingMethod,
null);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, clinitStart),
Range.genEnd(body, clinitEnd));
return s;
}
/** Make the shadow for an exception handler. Currently makes an empty shadow that
* only allows before advice to be woven into it.
*/
public static BcelShadow makeExceptionHandler(
BcelWorld world,
ExceptionRange exceptionRange,
LazyMethodGen enclosingMethod,
InstructionHandle startOfHandler,
BcelShadow enclosingShadow)
{
InstructionList body = enclosingMethod.getBody();
TypeX catchType = exceptionRange.getCatchType();
TypeX inType = enclosingMethod.getEnclosingClass().getType();
ResolvedMember sig = Member.makeExceptionHandlerSignature(inType, catchType);
sig.parameterNames = new String[] {findHandlerParamName(startOfHandler)};
BcelShadow s =
new BcelShadow(
world,
ExceptionHandler,
sig,
enclosingMethod,
enclosingShadow);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
InstructionHandle start = Range.genStart(body, startOfHandler);
InstructionHandle end = Range.genEnd(body, start);
r.associateWithTargets(start, end);
exceptionRange.updateTarget(startOfHandler, start, body);
return s;
}
private static String findHandlerParamName(InstructionHandle startOfHandler) {
if (startOfHandler.getInstruction() instanceof StoreInstruction &&
startOfHandler.getNext() != null)
{
int slot = ((StoreInstruction)startOfHandler.getInstruction()).getIndex();
//System.out.println("got store: " + startOfHandler.getInstruction() + ", " + index);
InstructionTargeter[] targeters = startOfHandler.getNext().getTargeters();
if (targeters!=null) {
for (int i=targeters.length-1; i >= 0; i--) {
if (targeters[i] instanceof LocalVariableTag) {
LocalVariableTag t = (LocalVariableTag)targeters[i];
if (t.getSlot() == slot) {
return t.getName();
}
//System.out.println("tag: " + targeters[i]);
}
}
}
}
return "<missing>";
}
/** create an init join point associated w/ an interface in the body of a constructor */
public static BcelShadow makeIfaceInitialization(
BcelWorld world,
LazyMethodGen constructor,
Member interfaceConstructorSignature)
{
InstructionList body = constructor.getBody();
// TypeX inType = constructor.getEnclosingClass().getType();
BcelShadow s =
new BcelShadow(
world,
Initialization,
interfaceConstructorSignature,
constructor,
null);
s.fallsThrough = true;
// ShadowRange r = new ShadowRange(body);
// r.associateWithShadow(s);
// InstructionHandle start = Range.genStart(body, handle);
// InstructionHandle end = Range.genEnd(body, handle);
//
// r.associateWithTargets(start, end);
return s;
}
public void initIfaceInitializer(InstructionHandle end) {
final InstructionList body = enclosingMethod.getBody();
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(this);
InstructionHandle nop = body.insert(end, InstructionConstants.NOP);
r.associateWithTargets(
Range.genStart(body, nop),
Range.genEnd(body, nop));
}
// public static BcelShadow makeIfaceConstructorExecution(
// BcelWorld world,
// LazyMethodGen constructor,
// InstructionHandle next,
// Member interfaceConstructorSignature)
// {
// // final InstructionFactory fact = constructor.getEnclosingClass().getFactory();
// InstructionList body = constructor.getBody();
// // TypeX inType = constructor.getEnclosingClass().getType();
// BcelShadow s =
// new BcelShadow(
// world,
// ConstructorExecution,
// interfaceConstructorSignature,
// constructor,
// null);
// s.fallsThrough = true;
// ShadowRange r = new ShadowRange(body);
// r.associateWithShadow(s);
// // ??? this may or may not work
// InstructionHandle start = Range.genStart(body, next);
// //InstructionHandle end = Range.genEnd(body, body.append(start, fact.NOP));
// InstructionHandle end = Range.genStart(body, next);
// //body.append(start, fact.NOP);
//
// r.associateWithTargets(start, end);
// return s;
// }
/** Create an initialization join point associated with a constructor, but not
* with any body of code yet. If this is actually matched, it's range will be set
* when we inline self constructors.
*
* @param constructor The constructor starting this initialization.
*/
public static BcelShadow makeUnfinishedInitialization(
BcelWorld world,
LazyMethodGen constructor)
{
return new BcelShadow(
world,
Initialization,
world.makeMethodSignature(constructor),
constructor,
null);
}
public static BcelShadow makeUnfinishedPreinitialization(
BcelWorld world,
LazyMethodGen constructor)
{
BcelShadow ret = new BcelShadow(
world,
PreInitialization,
world.makeMethodSignature(constructor),
constructor,
null);
ret.fallsThrough = true;
return ret;
}
public static BcelShadow makeMethodExecution(
BcelWorld world,
LazyMethodGen enclosingMethod,
boolean lazyInit)
{
if (!lazyInit) return makeMethodExecution(world, enclosingMethod);
BcelShadow s =
new BcelShadow(
world,
MethodExecution,
enclosingMethod.getMemberView(),
enclosingMethod,
null);
return s;
}
public void init() {
if (range != null) return;
final InstructionList body = enclosingMethod.getBody();
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(this);
r.associateWithTargets(
Range.genStart(body),
Range.genEnd(body));
}
public static BcelShadow makeMethodExecution(
BcelWorld world,
LazyMethodGen enclosingMethod)
{
return makeShadowForMethod(world, enclosingMethod, MethodExecution,
enclosingMethod.getMemberView()); //world.makeMethodSignature(enclosingMethod));
}
public static BcelShadow makeShadowForMethod(BcelWorld world,
LazyMethodGen enclosingMethod, Shadow.Kind kind, Member sig)
{
final InstructionList body = enclosingMethod.getBody();
BcelShadow s =
new BcelShadow(
world,
kind,
sig,
enclosingMethod,
null);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body),
Range.genEnd(body));
return s;
}
public static BcelShadow makeAdviceExecution(
BcelWorld world,
LazyMethodGen enclosingMethod)
{
final InstructionList body = enclosingMethod.getBody();
BcelShadow s =
new BcelShadow(
world,
AdviceExecution,
world.makeMethodSignature(enclosingMethod, Member.ADVICE),
enclosingMethod,
null);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(Range.genStart(body), Range.genEnd(body));
return s;
}
// constructor call shadows are <em>initially</em> just around the
// call to the constructor. If ANY advice gets put on it, we move
// the NEW instruction inside the join point, which involves putting
// all the arguments in temps.
public static BcelShadow makeConstructorCall(
BcelWorld world,
LazyMethodGen enclosingMethod,
InstructionHandle callHandle,
BcelShadow enclosingShadow)
{
final InstructionList body = enclosingMethod.getBody();
Member sig = BcelWorld.makeMethodSignature(
enclosingMethod.getEnclosingClass(),
(InvokeInstruction) callHandle.getInstruction());
BcelShadow s =
new BcelShadow(
world,
ConstructorCall,
sig,
enclosingMethod,
enclosingShadow);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, callHandle),
Range.genEnd(body, callHandle));
retargetAllBranches(callHandle, r.getStart());
return s;
}
public static BcelShadow makeMethodCall(
BcelWorld world,
LazyMethodGen enclosingMethod,
InstructionHandle callHandle,
BcelShadow enclosingShadow)
{
final InstructionList body = enclosingMethod.getBody();
BcelShadow s =
new BcelShadow(
world,
MethodCall,
BcelWorld.makeMethodSignature(
enclosingMethod.getEnclosingClass(),
(InvokeInstruction) callHandle.getInstruction()),
enclosingMethod,
enclosingShadow);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, callHandle),
Range.genEnd(body, callHandle));
retargetAllBranches(callHandle, r.getStart());
return s;
}
public static BcelShadow makeShadowForMethodCall(
BcelWorld world,
LazyMethodGen enclosingMethod,
InstructionHandle callHandle,
BcelShadow enclosingShadow,
Kind kind,
ResolvedMember sig)
{
final InstructionList body = enclosingMethod.getBody();
BcelShadow s =
new BcelShadow(
world,
kind,
sig,
enclosingMethod,
enclosingShadow);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, callHandle),
Range.genEnd(body, callHandle));
retargetAllBranches(callHandle, r.getStart());
return s;
}
public static BcelShadow makeFieldGet(
BcelWorld world,
LazyMethodGen enclosingMethod,
InstructionHandle getHandle,
BcelShadow enclosingShadow)
{
final InstructionList body = enclosingMethod.getBody();
BcelShadow s =
new BcelShadow(
world,
FieldGet,
BcelWorld.makeFieldSignature(
enclosingMethod.getEnclosingClass(),
(FieldInstruction) getHandle.getInstruction()),
enclosingMethod,
enclosingShadow);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, getHandle),
Range.genEnd(body, getHandle));
retargetAllBranches(getHandle, r.getStart());
return s;
}
public static BcelShadow makeFieldSet(
BcelWorld world,
LazyMethodGen enclosingMethod,
InstructionHandle setHandle,
BcelShadow enclosingShadow)
{
final InstructionList body = enclosingMethod.getBody();
BcelShadow s =
new BcelShadow(
world,
FieldSet,
BcelWorld.makeFieldSignature(
enclosingMethod.getEnclosingClass(),
(FieldInstruction) setHandle.getInstruction()),
enclosingMethod,
enclosingShadow);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, setHandle),
Range.genEnd(body, setHandle));
retargetAllBranches(setHandle, r.getStart());
return s;
}
public static void retargetAllBranches(InstructionHandle from, InstructionHandle to) {
InstructionTargeter[] sources = from.getTargeters();
if (sources != null) {
for (int i = sources.length - 1; i >= 0; i--) {
InstructionTargeter source = sources[i];
if (source instanceof BranchInstruction) {
source.updateTarget(from, to);
}
}
}
}
// // ---- type access methods
// private ObjectType getTargetBcelType() {
// return (ObjectType) BcelWorld.makeBcelType(getTargetType());
// }
// private Type getArgBcelType(int arg) {
// return BcelWorld.makeBcelType(getArgType(arg));
// }
// ---- kinding
/**
* If the end of my range has no real instructions following then
* my context needs a return at the end.
*/
public boolean terminatesWithReturn() {
return getRange().getRealNext() == null;
}
/**
* Is arg0 occupied with the value of this
*/
public boolean arg0HoldsThis() {
if (getKind().isEnclosingKind()) {
return !getSignature().isStatic();
} else if (enclosingShadow == null) {
//XXX this is mostly right
// this doesn't do the right thing for calls in the pre part of introduced constructors.
return !enclosingMethod.isStatic();
} else {
return ((BcelShadow)enclosingShadow).arg0HoldsThis();
}
}
// ---- argument getting methods
private BcelVar thisVar = null;
private BcelVar targetVar = null;
private BcelVar[] argVars = null;
public Var getThisVar() {
if (!hasThis()) {
throw new IllegalStateException("no this");
}
initializeThisVar();
return thisVar;
}
public Var getTargetVar() {
if (!hasTarget()) {
throw new IllegalStateException("no target");
}
initializeTargetVar();
return targetVar;
}
public Var getArgVar(int i) {
initializeArgVars();
return argVars[i];
}
// reflective thisJoinPoint support
private BcelVar thisJoinPointVar = null;
private boolean isThisJoinPointLazy;
private int lazyTjpConsumers = 0;
private BcelVar thisJoinPointStaticPartVar = null;
// private BcelVar thisEnclosingJoinPointStaticPartVar = null;
public final Var getThisJoinPointStaticPartVar() {
return getThisJoinPointStaticPartBcelVar();
}
public final Var getThisEnclosingJoinPointStaticPartVar() {
return getThisEnclosingJoinPointStaticPartBcelVar();
}
public void requireThisJoinPoint(boolean hasGuardTest) {
if (!hasGuardTest) {
isThisJoinPointLazy = false;
} else {
lazyTjpConsumers++;
}
if (thisJoinPointVar == null) {
thisJoinPointVar = genTempVar(TypeX.forName("org.aspectj.lang.JoinPoint"));
}
}
public Var getThisJoinPointVar() {
requireThisJoinPoint(false);
return thisJoinPointVar;
}
void initializeThisJoinPoint() {
if (thisJoinPointVar == null) return;
if (isThisJoinPointLazy) {
isThisJoinPointLazy = checkLazyTjp();
}
if (isThisJoinPointLazy) {
createThisJoinPoint(); // make sure any state needed is initialized, but throw the instructions out
if (lazyTjpConsumers == 1) return; // special case only one lazyTjpUser
InstructionFactory fact = getFactory();
InstructionList il = new InstructionList();
il.append(InstructionConstants.ACONST_NULL);
il.append(thisJoinPointVar.createStore(fact));
range.insert(il, Range.OutsideBefore);
} else {
InstructionFactory fact = getFactory();
InstructionList il = createThisJoinPoint();
il.append(thisJoinPointVar.createStore(fact));
range.insert(il, Range.OutsideBefore);
}
}
private boolean checkLazyTjp() {
// check for around advice
for (Iterator i = mungers.iterator(); i.hasNext();) {
ShadowMunger munger = (ShadowMunger) i.next();
if (munger instanceof Advice) {
if ( ((Advice)munger).getKind() == AdviceKind.Around) {
world.getLint().canNotImplementLazyTjp.signal(
new String[] {toString()},
getSourceLocation(),
new ISourceLocation[] { munger.getSourceLocation() }
);
return false;
}
}
}
return true;
}
InstructionList loadThisJoinPoint() {
InstructionFactory fact = getFactory();
InstructionList il = new InstructionList();
if (isThisJoinPointLazy) {
il.append(createThisJoinPoint());
if (lazyTjpConsumers > 1) {
il.append(thisJoinPointVar.createStore(fact));
InstructionHandle end = il.append(thisJoinPointVar.createLoad(fact));
il.insert(InstructionFactory.createBranchInstruction(Constants.IFNONNULL, end));
il.insert(thisJoinPointVar.createLoad(fact));
}
} else {
thisJoinPointVar.appendLoad(il, fact);
}
return il;
}
InstructionList createThisJoinPoint() {
InstructionFactory fact = getFactory();
InstructionList il = new InstructionList();
BcelVar staticPart = getThisJoinPointStaticPartBcelVar();
staticPart.appendLoad(il, fact);
if (hasThis()) {
((BcelVar)getThisVar()).appendLoad(il, fact);
} else {
il.append(new ACONST_NULL());
}
if (hasTarget()) {
((BcelVar)getTargetVar()).appendLoad(il, fact);
} else {
il.append(new ACONST_NULL());
}
switch(getArgCount()) {
case 0:
il.append(fact.createInvoke("org.aspectj.runtime.reflect.Factory",
"makeJP", LazyClassGen.tjpType,
new Type[] { LazyClassGen.staticTjpType,
Type.OBJECT, Type.OBJECT},
Constants.INVOKESTATIC));
break;
case 1:
((BcelVar)getArgVar(0)).appendLoadAndConvert(il, fact, world.getCoreType(ResolvedTypeX.OBJECT));
il.append(fact.createInvoke("org.aspectj.runtime.reflect.Factory",
"makeJP", LazyClassGen.tjpType,
new Type[] { LazyClassGen.staticTjpType,
Type.OBJECT, Type.OBJECT, Type.OBJECT},
Constants.INVOKESTATIC));
break;
case 2:
((BcelVar)getArgVar(0)).appendLoadAndConvert(il, fact, world.getCoreType(ResolvedTypeX.OBJECT));
((BcelVar)getArgVar(1)).appendLoadAndConvert(il, fact, world.getCoreType(ResolvedTypeX.OBJECT));
il.append(fact.createInvoke("org.aspectj.runtime.reflect.Factory",
"makeJP", LazyClassGen.tjpType,
new Type[] { LazyClassGen.staticTjpType,
Type.OBJECT, Type.OBJECT, Type.OBJECT, Type.OBJECT},
Constants.INVOKESTATIC));
break;
default:
il.append(makeArgsObjectArray());
il.append(fact.createInvoke("org.aspectj.runtime.reflect.Factory",
"makeJP", LazyClassGen.tjpType,
new Type[] { LazyClassGen.staticTjpType,
Type.OBJECT, Type.OBJECT, new ArrayType(Type.OBJECT, 1)},
Constants.INVOKESTATIC));
break;
}
return il;
}
public BcelVar getThisJoinPointStaticPartBcelVar() {
if (thisJoinPointStaticPartVar == null) {
Field field = getEnclosingClass().getTjpField(this);
thisJoinPointStaticPartVar =
new BcelFieldRef(
world.getCoreType(TypeX.forName("org.aspectj.lang.JoinPoint$StaticPart")),
getEnclosingClass().getClassName(),
field.getName());
// getEnclosingClass().warnOnAddedStaticInitializer(this,munger.getSourceLocation());
}
return thisJoinPointStaticPartVar;
}
public BcelVar getThisEnclosingJoinPointStaticPartBcelVar() {
if (enclosingShadow == null) {
// the enclosing of an execution is itself
return getThisJoinPointStaticPartBcelVar();
} else {
return ((BcelShadow)enclosingShadow).getThisJoinPointStaticPartBcelVar();
}
}
//??? need to better understand all the enclosing variants
public Member getEnclosingCodeSignature() {
if (getKind().isEnclosingKind()) {
return getSignature();
} else if (getKind() == Shadow.PreInitialization) {
// PreInit doesn't enclose code but its signature
// is correctly the signature of the ctor.
return getSignature();
} else if (enclosingShadow == null) {
return getEnclosingMethod().getMemberView();
} else {
return enclosingShadow.getSignature();
}
}
private InstructionList makeArgsObjectArray() {
InstructionFactory fact = getFactory();
BcelVar arrayVar = genTempVar(TypeX.OBJECTARRAY);
final InstructionList il = new InstructionList();
int alen = getArgCount() ;
il.append(Utility.createConstant(fact, alen));
il.append((Instruction)fact.createNewArray(Type.OBJECT, (short)1));
arrayVar.appendStore(il, fact);
int stateIndex = 0;
for (int i = 0, len = getArgCount(); i<len; i++) {
arrayVar.appendConvertableArrayStore(il, fact, stateIndex, (BcelVar)getArgVar(i));
stateIndex++;
}
arrayVar.appendLoad(il, fact);
return il;
}
// ---- initializing var tables
/* initializing this is doesn't do anything, because this
* is protected from side-effects, so we don't need to copy its location
*/
private void initializeThisVar() {
if (thisVar != null) return;
thisVar = new BcelVar(getThisType().resolve(world), 0);
thisVar.setPositionInAroundState(0);
}
public void initializeTargetVar() {
InstructionFactory fact = getFactory();
if (targetVar != null) return;
if (getKind().isTargetSameAsThis()) {
if (hasThis()) initializeThisVar();
targetVar = thisVar;
} else {
initializeArgVars(); // gotta pop off the args before we find the target
TypeX type = getTargetType();
targetVar = genTempVar(type, "ajc$target");
range.insert(targetVar.createStore(fact), Range.OutsideBefore);
targetVar.setPositionInAroundState(hasThis() ? 1 : 0);
}
}
public void initializeArgVars() {
if (argVars != null) return;
InstructionFactory fact = getFactory();
int len = getArgCount();
argVars = new BcelVar[len];
int positionOffset = (hasTarget() ? 1 : 0) +
((hasThis() && !getKind().isTargetSameAsThis()) ? 1 : 0);
if (getKind().argsOnStack()) {
// we move backwards because we're popping off the stack
for (int i = len - 1; i >= 0; i--) {
TypeX type = getArgType(i);
BcelVar tmp = genTempVar(type, "ajc$arg" + i);
range.insert(tmp.createStore(getFactory()), Range.OutsideBefore);
int position = i;
position += positionOffset;
tmp.setPositionInAroundState(position);
argVars[i] = tmp;
}
} else {
int index = 0;
if (arg0HoldsThis()) index++;
for (int i = 0; i < len; i++) {
TypeX type = getArgType(i);
BcelVar tmp = genTempVar(type, "ajc$arg" + i);
range.insert(tmp.createCopyFrom(fact, index), Range.OutsideBefore);
argVars[i] = tmp;
int position = i;
position += positionOffset;
// System.out.println("set position: " + tmp + ", " + position + " in " + this);
// System.out.println(" hasThis: " + hasThis() + ", hasTarget: " + hasTarget());
tmp.setPositionInAroundState(position);
index += type.getSize();
}
}
}
public void initializeForAroundClosure() {
initializeArgVars();
if (hasTarget()) initializeTargetVar();
if (hasThis()) initializeThisVar();
// System.out.println("initialized: " + this + " thisVar = " + thisVar);
}
// ---- weave methods
void weaveBefore(BcelAdvice munger) {
range.insert(
munger.getAdviceInstructions(this, null, range.getRealStart()),
Range.InsideBefore);
}
public void weaveAfter(BcelAdvice munger) {
weaveAfterThrowing(munger, TypeX.THROWABLE);
weaveAfterReturning(munger);
}
/**
* We guarantee that the return value is on the top of the stack when
* munger.getAdviceInstructions() will be run
* (Unless we have a void return type in which case there's nothing)
*/
public void weaveAfterReturning(BcelAdvice munger) {
// InstructionFactory fact = getFactory();
List returns = new ArrayList();
Instruction ret = null;
for (InstructionHandle ih = range.getStart(); ih != range.getEnd(); ih = ih.getNext()) {
if (ih.getInstruction() instanceof ReturnInstruction) {
returns.add(ih);
ret = Utility.copyInstruction(ih.getInstruction());
}
}
InstructionList retList;
InstructionHandle afterAdvice;
if (ret != null) {
retList = new InstructionList(ret);
afterAdvice = retList.getStart();
} else /* if (munger.hasDynamicTests()) */ {
retList = new InstructionList(InstructionConstants.NOP);
afterAdvice = retList.getStart();
// } else {
// retList = new InstructionList();
// afterAdvice = null;
}
InstructionList advice = new InstructionList();
BcelVar tempVar = null;
if (munger.hasExtraParameter()) {
TypeX tempVarType = getReturnType();
if (tempVarType.equals(ResolvedTypeX.VOID)) {
tempVar = genTempVar(TypeX.OBJECT);
advice.append(InstructionConstants.ACONST_NULL);
tempVar.appendStore(advice, getFactory());
} else {
tempVar = genTempVar(tempVarType);
advice.append(InstructionFactory.createDup(tempVarType.getSize()));
tempVar.appendStore(advice, getFactory());
}
}
advice.append(munger.getAdviceInstructions(this, tempVar, afterAdvice));
if (ret != null) {
InstructionHandle gotoTarget = advice.getStart();
for (Iterator i = returns.iterator(); i.hasNext();) {
InstructionHandle ih = (InstructionHandle) i.next();
Utility.replaceInstruction(
ih,
InstructionFactory.createBranchInstruction(
Constants.GOTO,
gotoTarget),
enclosingMethod);
}
range.append(advice);
range.append(retList);
} else {
range.append(advice);
range.append(retList);
}
}
public void weaveAfterThrowing(BcelAdvice munger, TypeX catchType) {
// a good optimization would be not to generate anything here
// if the shadow is GUARANTEED empty (i.e., there's NOTHING, not even
// a shadow, inside me).
if (getRange().getStart().getNext() == getRange().getEnd()) return;
InstructionFactory fact = getFactory();
InstructionList handler = new InstructionList();
BcelVar exceptionVar = genTempVar(catchType);
exceptionVar.appendStore(handler, fact);
// pr62642
// I will now jump through some firey BCEL hoops to generate a trivial bit of code:
// if (exc instanceof ExceptionInInitializerError)
// throw (ExceptionInInitializerError)exc;
if (this.getEnclosingMethod().getName().equals("<clinit>")) {
ResolvedTypeX eiieType = world.resolve("java.lang.ExceptionInInitializerError");
ObjectType eiieBcelType = (ObjectType)BcelWorld.makeBcelType(eiieType);
InstructionList ih = new InstructionList(InstructionConstants.NOP);
handler.append(exceptionVar.createLoad(fact));
handler.append(fact.createInstanceOf(eiieBcelType));
BranchInstruction bi =
InstructionFactory.createBranchInstruction(Constants.IFEQ,ih.getStart());
handler.append(bi);
handler.append(exceptionVar.createLoad(fact));
handler.append(fact.createCheckCast(eiieBcelType));
handler.append(InstructionConstants.ATHROW);
handler.append(ih);
}
InstructionList endHandler = new InstructionList(
exceptionVar.createLoad(fact));
handler.append(munger.getAdviceInstructions(this, exceptionVar, endHandler.getStart()));
handler.append(endHandler);
handler.append(InstructionConstants.ATHROW);
InstructionHandle handlerStart = handler.getStart();
if (isFallsThrough()) {
InstructionHandle jumpTarget = handler.append(InstructionConstants.NOP);
handler.insert(InstructionFactory.createBranchInstruction(Constants.GOTO, jumpTarget));
}
InstructionHandle protectedEnd = handler.getStart();
range.insert(handler, Range.InsideAfter);
enclosingMethod.addExceptionHandler(range.getStart().getNext(), protectedEnd.getPrev(),
handlerStart, (ObjectType)BcelWorld.makeBcelType(catchType), //???Type.THROWABLE,
// high priority if our args are on the stack
getKind().hasHighPriorityExceptions());
}
//??? this shares a lot of code with the above weaveAfterThrowing
//??? would be nice to abstract that to say things only once
public void weaveSoftener(BcelAdvice munger, TypeX catchType) {
// a good optimization would be not to generate anything here
// if the shadow is GUARANTEED empty (i.e., there's NOTHING, not even
// a shadow, inside me).
if (getRange().getStart().getNext() == getRange().getEnd()) return;
InstructionFactory fact = getFactory();
InstructionList handler = new InstructionList();
BcelVar exceptionVar = genTempVar(catchType);
exceptionVar.appendStore(handler, fact);
// ENH 42743 suggests that we don't soften runtime exceptions.
// To implement that, would need to add instructions into the handler
// stream here to test if exceptionVar is an instanceof RuntimeException,
// and if it is, just re-throw it without softening.
// (Not yet implemented obviously).
handler.append(fact.createNew(NameMangler.SOFT_EXCEPTION_TYPE));
handler.append(InstructionFactory.createDup(1));
handler.append(exceptionVar.createLoad(fact));
handler.append(fact.createInvoke(NameMangler.SOFT_EXCEPTION_TYPE, "<init>",
Type.VOID, new Type[] { Type.THROWABLE }, Constants.INVOKESPECIAL)); //??? special
handler.append(InstructionConstants.ATHROW);
InstructionHandle handlerStart = handler.getStart();
if (isFallsThrough()) {
InstructionHandle jumpTarget = range.getEnd();//handler.append(fact.NOP);
handler.insert(InstructionFactory.createBranchInstruction(Constants.GOTO, jumpTarget));
}
InstructionHandle protectedEnd = handler.getStart();
range.insert(handler, Range.InsideAfter);
enclosingMethod.addExceptionHandler(range.getStart().getNext(), protectedEnd.getPrev(),
handlerStart, (ObjectType)BcelWorld.makeBcelType(catchType),
// high priority if our args are on the stack
getKind().hasHighPriorityExceptions());
}
public void weavePerObjectEntry(final BcelAdvice munger, final BcelVar onVar) {
final InstructionFactory fact = getFactory();
InstructionList entryInstructions = new InstructionList();
InstructionList entrySuccessInstructions = new InstructionList();
onVar.appendLoad(entrySuccessInstructions, fact);
entrySuccessInstructions.append(
Utility.createInvoke(fact, world,
AjcMemberMaker.perObjectBind(munger.getConcreteAspect())));
InstructionList testInstructions =
munger.getTestInstructions(this, entrySuccessInstructions.getStart(),
range.getRealStart(),
entrySuccessInstructions.getStart());
entryInstructions.append(testInstructions);
entryInstructions.append(entrySuccessInstructions);
range.insert(entryInstructions, Range.InsideBefore);
}
public void weaveCflowEntry(final BcelAdvice munger, final Member cflowStackField) {
final boolean isPer = munger.getKind() == AdviceKind.PerCflowBelowEntry ||
munger.getKind() == AdviceKind.PerCflowEntry;
final Type objectArrayType = new ArrayType(Type.OBJECT, 1);
final InstructionFactory fact = getFactory();
final BcelVar testResult = genTempVar(ResolvedTypeX.BOOLEAN);
InstructionList entryInstructions = new InstructionList();
{
InstructionList entrySuccessInstructions = new InstructionList();
if (munger.hasDynamicTests()) {
entryInstructions.append(Utility.createConstant(fact, 0));
testResult.appendStore(entryInstructions, fact);
entrySuccessInstructions.append(Utility.createConstant(fact, 1));
testResult.appendStore(entrySuccessInstructions, fact);
}
if (isPer) {
entrySuccessInstructions.append(
fact.createInvoke(munger.getConcreteAspect().getName(),
NameMangler.PERCFLOW_PUSH_METHOD,
Type.VOID,
new Type[] { },
Constants.INVOKESTATIC));
} else {
BcelVar[] cflowStateVars = munger.getExposedStateAsBcelVars();
BcelVar arrayVar = genTempVar(TypeX.OBJECTARRAY);
int alen = cflowStateVars.length;
entrySuccessInstructions.append(Utility.createConstant(fact, alen));
entrySuccessInstructions.append(
(Instruction) fact.createNewArray(Type.OBJECT, (short) 1));
arrayVar.appendStore(entrySuccessInstructions, fact);
for (int i = 0; i < alen; i++) {
arrayVar.appendConvertableArrayStore(
entrySuccessInstructions,
fact,
i,
cflowStateVars[i]);
}
entrySuccessInstructions.append(
Utility.createGet(fact, cflowStackField));
arrayVar.appendLoad(entrySuccessInstructions, fact);
entrySuccessInstructions.append(
fact.createInvoke(NameMangler.CFLOW_STACK_TYPE, "push", Type.VOID,
new Type[] { objectArrayType },
Constants.INVOKEVIRTUAL));
}
InstructionList testInstructions =
munger.getTestInstructions(this, entrySuccessInstructions.getStart(),
range.getRealStart(),
entrySuccessInstructions.getStart());
entryInstructions.append(testInstructions);
entryInstructions.append(entrySuccessInstructions);
}
// this is the same for both per and non-per
weaveAfter(new BcelAdvice(null, null, null, 0, 0, 0, null, null) {
public InstructionList getAdviceInstructions(
BcelShadow s,
BcelVar extraArgVar,
InstructionHandle ifNoAdvice) {
InstructionList exitInstructions = new InstructionList();
if (munger.hasDynamicTests()) {
testResult.appendLoad(exitInstructions, fact);
exitInstructions.append(
InstructionFactory.createBranchInstruction(
Constants.IFEQ,
ifNoAdvice));
}
exitInstructions.append(Utility.createGet(fact, cflowStackField));
exitInstructions
.append(
fact
.createInvoke(
NameMangler.CFLOW_STACK_TYPE,
"pop",
Type.VOID,
new Type[] {
}, Constants.INVOKEVIRTUAL));
return exitInstructions;
}
});
range.insert(entryInstructions, Range.InsideBefore);
}
public void weaveAroundInline(
BcelAdvice munger,
boolean hasDynamicTest)
{
/* Implementation notes:
*
* AroundInline still extracts the instructions of the original shadow into
* an extracted method. This allows inlining of even that advice that doesn't
* call proceed or calls proceed more than once.
*
* It extracts the instructions of the original shadow into a method.
*
* Then it extracts the instructions of the advice into a new method defined on
* this enclosing class. This new method can then be specialized as below.
*
* Then it searches in the instructions of the advice for any call to the
* proceed method.
*
* At such a call, there is stuff on the stack representing the arguments to
* proceed. Pop these into the frame.
*
* Now build the stack for the call to the extracted method, taking values
* either from the join point state or from the new frame locs from proceed.
* Now call the extracted method. The right return value should be on the
* stack, so no cast is necessary.
*
* If only one call to proceed is made, we can re-inline the original shadow.
* We are not doing that presently.
*
* If the body of the advice can be determined to not alter the stack, or if
* this shadow doesn't care about the stack, i.e. method-execution, then the
* new method for the advice can also be re-lined. We are not doing that
* presently.
*/
// !!! THIS BLOCK OF CODE SHOULD BE IN A METHOD CALLED weaveAround(...);
Member mungerSig = munger.getSignature();
ResolvedTypeX declaringType = world.resolve(mungerSig.getDeclaringType(),true);
if (declaringType == ResolvedTypeX.MISSING) {
IMessage msg = new Message(
WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_DURING_AROUND_WEAVE,declaringType.getClassName()),
"",IMessage.ERROR,getSourceLocation(),null,
new ISourceLocation[]{ munger.getSourceLocation()});
world.getMessageHandler().handleMessage(msg);
}
//??? might want some checks here to give better errors
BcelObjectType ot = BcelWorld.getBcelObjectType(declaringType);
LazyMethodGen adviceMethod = ot.getLazyClassGen().getLazyMethodGen(mungerSig);
if (!adviceMethod.getCanInline())
{
weaveAroundClosure(munger, hasDynamicTest);
return;
}
// We can't inline around methods if they have around advice on them, this
// is because the weaving will extract the body and hence the proceed call.
//??? should consider optimizations to recognize simple cases that don't require body extraction
enclosingMethod.setCanInline(false);
// start by exposing various useful things into the frame
final InstructionFactory fact = getFactory();
// now generate the aroundBody method
LazyMethodGen extractedMethod =
extractMethod(
NameMangler.aroundCallbackMethodName(
getSignature(),
getEnclosingClass()),
Modifier.PRIVATE,
munger);
// now extract the advice into its own method
String adviceMethodName =
NameMangler.aroundCallbackMethodName(
getSignature(),
getEnclosingClass()) + "$advice";
List argVarList = new ArrayList();
List proceedVarList = new ArrayList();
int extraParamOffset = 0;
// Create the extra parameters that are needed for passing to proceed
// This code is very similar to that found in makeCallToCallback and should
// be rationalized in the future
if (thisVar != null) {
argVarList.add(thisVar);
proceedVarList.add(new BcelVar(thisVar.getType(), extraParamOffset));
extraParamOffset += thisVar.getType().getSize();
}
if (targetVar != null && targetVar != thisVar) {
argVarList.add(targetVar);
proceedVarList.add(new BcelVar(targetVar.getType(), extraParamOffset));
extraParamOffset += targetVar.getType().getSize();
}
for (int i = 0, len = getArgCount(); i < len; i++) {
argVarList.add(argVars[i]);
proceedVarList.add(new BcelVar(argVars[i].getType(), extraParamOffset));
extraParamOffset += argVars[i].getType().getSize();
}
if (thisJoinPointVar != null) {
argVarList.add(thisJoinPointVar);
proceedVarList.add(new BcelVar(thisJoinPointVar.getType(), extraParamOffset));
extraParamOffset += thisJoinPointVar.getType().getSize();
}
Type[] adviceParameterTypes = adviceMethod.getArgumentTypes();
Type[] extractedMethodParameterTypes = extractedMethod.getArgumentTypes();
Type[] parameterTypes =
new Type[extractedMethodParameterTypes.length
+ adviceParameterTypes.length
+ 1];
int parameterIndex = 0;
System.arraycopy(
extractedMethodParameterTypes,
0,
parameterTypes,
parameterIndex,
extractedMethodParameterTypes.length);
parameterIndex += extractedMethodParameterTypes.length;
parameterTypes[parameterIndex++] =
BcelWorld.makeBcelType(adviceMethod.getEnclosingClass().getType());
System.arraycopy(
adviceParameterTypes,
0,
parameterTypes,
parameterIndex,
adviceParameterTypes.length);
LazyMethodGen localAdviceMethod =
new LazyMethodGen(
Modifier.PRIVATE | Modifier.FINAL | Modifier.STATIC,
adviceMethod.getReturnType(),
adviceMethodName,
parameterTypes,
new String[0],
getEnclosingClass());
String donorFileName = adviceMethod.getEnclosingClass().getInternalFileName();
String recipientFileName = getEnclosingClass().getInternalFileName();
// System.err.println("donor " + donorFileName);
// System.err.println("recip " + recipientFileName);
if (! donorFileName.equals(recipientFileName)) {
localAdviceMethod.fromFilename = donorFileName;
getEnclosingClass().addInlinedSourceFileInfo(
donorFileName,
adviceMethod.highestLineNumber);
}
getEnclosingClass().addMethodGen(localAdviceMethod);
// create a map that will move all slots in advice method forward by extraParamOffset
// in order to make room for the new proceed-required arguments that are added at
// the beginning of the parameter list
int nVars = adviceMethod.getMaxLocals() + extraParamOffset;
IntMap varMap = IntMap.idMap(nVars);
for (int i=extraParamOffset; i < nVars; i++) {
varMap.put(i-extraParamOffset, i);
}
localAdviceMethod.getBody().insert(
BcelClassWeaver.genInlineInstructions(adviceMethod,
localAdviceMethod, varMap, fact, true));
localAdviceMethod.setMaxLocals(nVars);
//System.err.println(localAdviceMethod);
// the shadow is now empty. First, create a correct call
// to the around advice. This includes both the call (which may involve
// value conversion of the advice arguments) and the return
// (which may involve value conversion of the return value). Right now
// we push a null for the unused closure. It's sad, but there it is.
InstructionList advice = new InstructionList();
// InstructionHandle adviceMethodInvocation;
{
for (Iterator i = argVarList.iterator(); i.hasNext(); ) {
BcelVar var = (BcelVar)i.next();
var.appendLoad(advice, fact);
}
// ??? we don't actually need to push NULL for the closure if we take care
advice.append(
munger.getAdviceArgSetup(
this,
null,
new InstructionList(InstructionConstants.ACONST_NULL)));
// adviceMethodInvocation =
advice.append(
Utility.createInvoke(fact, localAdviceMethod)); //(fact, getWorld(), munger.getSignature()));
advice.append(
Utility.createConversion(
getFactory(),
BcelWorld.makeBcelType(munger.getSignature().getReturnType()),
extractedMethod.getReturnType()));
if (! isFallsThrough()) {
advice.append(InstructionFactory.createReturn(extractedMethod.getReturnType()));
}
}
// now, situate the call inside the possible dynamic tests,
// and actually add the whole mess to the shadow
if (! hasDynamicTest) {
range.append(advice);
} else {
InstructionList afterThingie = new InstructionList(InstructionConstants.NOP);
InstructionList callback = makeCallToCallback(extractedMethod);
if (terminatesWithReturn()) {
callback.append(
InstructionFactory.createReturn(extractedMethod.getReturnType()));
} else {
//InstructionHandle endNop = range.insert(fact.NOP, Range.InsideAfter);
advice.append(
InstructionFactory.createBranchInstruction(
Constants.GOTO,
afterThingie.getStart()));
}
range.append(
munger.getTestInstructions(
this,
advice.getStart(),
callback.getStart(),
advice.getStart()));
range.append(advice);
range.append(callback);
range.append(afterThingie);
}
// now search through the advice, looking for a call to PROCEED.
// Then we replace the call to proceed with some argument setup, and a
// call to the extracted method.
String proceedName =
NameMangler.proceedMethodName(munger.getSignature().getName());
InstructionHandle curr = localAdviceMethod.getBody().getStart();
InstructionHandle end = localAdviceMethod.getBody().getEnd();
ConstantPoolGen cpg = localAdviceMethod.getEnclosingClass().getConstantPoolGen();
while (curr != end) {
InstructionHandle next = curr.getNext();
Instruction inst = curr.getInstruction();
if ((inst instanceof INVOKESTATIC)
&& proceedName.equals(((INVOKESTATIC) inst).getMethodName(cpg))) {
localAdviceMethod.getBody().append(
curr,
getRedoneProceedCall(
fact,
extractedMethod,
munger,
localAdviceMethod,
proceedVarList));
Utility.deleteInstruction(curr, localAdviceMethod);
}
curr = next;
}
// and that's it.
}
private InstructionList getRedoneProceedCall(
InstructionFactory fact,
LazyMethodGen callbackMethod,
BcelAdvice munger,
LazyMethodGen localAdviceMethod,
List argVarList)
{
InstructionList ret = new InstructionList();
// we have on stack all the arguments for the ADVICE call.
// we have in frame somewhere all the arguments for the non-advice call.
BcelVar[] adviceVars = munger.getExposedStateAsBcelVars();
IntMap proceedMap = makeProceedArgumentMap(adviceVars);
// System.out.println(proceedMap + " for " + this);
// System.out.println(argVarList);
ResolvedTypeX[] proceedParamTypes =
world.resolve(munger.getSignature().getParameterTypes());
// remove this*JoinPoint* as arguments to proceed
if (munger.getBaseParameterCount()+1 < proceedParamTypes.length) {
int len = munger.getBaseParameterCount()+1;
ResolvedTypeX[] newTypes = new ResolvedTypeX[len];
System.arraycopy(proceedParamTypes, 0, newTypes, 0, len);
proceedParamTypes = newTypes;
}
//System.out.println("stateTypes: " + Arrays.asList(stateTypes));
BcelVar[] proceedVars =
Utility.pushAndReturnArrayOfVars(proceedParamTypes, ret, fact, localAdviceMethod);
Type[] stateTypes = callbackMethod.getArgumentTypes();
// System.out.println("stateTypes: " + Arrays.asList(stateTypes));
for (int i=0, len=stateTypes.length; i < len; i++) {
Type stateType = stateTypes[i];
ResolvedTypeX stateTypeX = BcelWorld.fromBcel(stateType).resolve(world);
if (proceedMap.hasKey(i)) {
//throw new RuntimeException("unimplemented");
proceedVars[proceedMap.get(i)].appendLoadAndConvert(ret, fact, stateTypeX);
} else {
((BcelVar) argVarList.get(i)).appendLoad(ret, fact);
}
}
ret.append(Utility.createInvoke(fact, callbackMethod));
ret.append(Utility.createConversion(fact, callbackMethod.getReturnType(),
BcelWorld.makeBcelType(munger.getSignature().getReturnType())));
return ret;
}
public void weaveAroundClosure(
BcelAdvice munger,
boolean hasDynamicTest)
{
InstructionFactory fact = getFactory();
enclosingMethod.setCanInline(false);
// MOVE OUT ALL THE INSTRUCTIONS IN MY SHADOW INTO ANOTHER METHOD!
LazyMethodGen callbackMethod =
extractMethod(
NameMangler.aroundCallbackMethodName(
getSignature(),
getEnclosingClass()),
0,
munger);
BcelVar[] adviceVars = munger.getExposedStateAsBcelVars();
String closureClassName =
NameMangler.makeClosureClassName(
getEnclosingClass().getType(),
getEnclosingClass().getNewGeneratedNameTag());
Member constructorSig = new Member(Member.CONSTRUCTOR,
TypeX.forName(closureClassName), 0, "<init>",
"([Ljava/lang/Object;)V");
BcelVar closureHolder = null;
// This is not being used currently since getKind() == preinitializaiton
// cannot happen in around advice
if (getKind() == PreInitialization) {
closureHolder = genTempVar(AjcMemberMaker.AROUND_CLOSURE_TYPE);
}
InstructionList closureInstantiation =
makeClosureInstantiation(constructorSig, closureHolder);
/*LazyMethodGen constructor = */
makeClosureClassAndReturnConstructor(
closureClassName,
callbackMethod,
makeProceedArgumentMap(adviceVars)
);
InstructionList returnConversionCode;
if (getKind() == PreInitialization) {
returnConversionCode = new InstructionList();
BcelVar stateTempVar = genTempVar(TypeX.OBJECTARRAY);
closureHolder.appendLoad(returnConversionCode, fact);
returnConversionCode.append(
Utility.createInvoke(
fact,
world,
AjcMemberMaker.aroundClosurePreInitializationGetter()));
stateTempVar.appendStore(returnConversionCode, fact);
Type[] stateTypes = getSuperConstructorParameterTypes();
returnConversionCode.append(InstructionConstants.ALOAD_0); // put "this" back on the stack
for (int i = 0, len = stateTypes.length; i < len; i++) {
TypeX bcelTX = BcelWorld.fromBcel(stateTypes[i]);
ResolvedTypeX stateRTX = world.resolve(bcelTX,true);
if (stateRTX == ResolvedTypeX.MISSING) {
IMessage msg = new Message(
WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_DURING_AROUND_WEAVE_PREINIT,bcelTX.getClassName()),
"",IMessage.ERROR,getSourceLocation(),null,
new ISourceLocation[]{ munger.getSourceLocation()});
world.getMessageHandler().handleMessage(msg);
}
stateTempVar.appendConvertableArrayLoad(
returnConversionCode,
fact,
i,
stateRTX);
}
} else {
returnConversionCode =
Utility.createConversion(
getFactory(),
BcelWorld.makeBcelType(munger.getSignature().getReturnType()),
callbackMethod.getReturnType());
if (!isFallsThrough()) {
returnConversionCode.append(
InstructionFactory.createReturn(callbackMethod.getReturnType()));
}
}
InstructionList advice = new InstructionList();
advice.append(munger.getAdviceArgSetup(this, null, closureInstantiation));
// advice.append(closureInstantiation);
advice.append(munger.getNonTestAdviceInstructions(this));
advice.append(returnConversionCode);
if (!hasDynamicTest) {
range.append(advice);
} else {
InstructionList callback = makeCallToCallback(callbackMethod);
InstructionList postCallback = new InstructionList();
if (terminatesWithReturn()) {
callback.append(
InstructionFactory.createReturn(callbackMethod.getReturnType()));
} else {
advice.append(
InstructionFactory.createBranchInstruction(
Constants.GOTO,
postCallback.append(InstructionConstants.NOP)));
}
range.append(
munger.getTestInstructions(
this,
advice.getStart(),
callback.getStart(),
advice.getStart()));
range.append(advice);
range.append(callback);
range.append(postCallback);
}
}
// exposed for testing
InstructionList makeCallToCallback(LazyMethodGen callbackMethod) {
InstructionFactory fact = getFactory();
InstructionList callback = new InstructionList();
if (thisVar != null) {
callback.append(InstructionConstants.ALOAD_0);
}
if (targetVar != null && targetVar != thisVar) {
callback.append(BcelRenderer.renderExpr(fact, world, targetVar));
}
callback.append(BcelRenderer.renderExprs(fact, world, argVars));
// remember to render tjps
if (thisJoinPointVar != null) {
callback.append(BcelRenderer.renderExpr(fact, world, thisJoinPointVar));
}
callback.append(Utility.createInvoke(fact, callbackMethod));
return callback;
}
/** side-effect-free */
private InstructionList makeClosureInstantiation(Member constructor, BcelVar holder) {
// LazyMethodGen constructor) {
InstructionFactory fact = getFactory();
BcelVar arrayVar = genTempVar(TypeX.OBJECTARRAY);
//final Type objectArrayType = new ArrayType(Type.OBJECT, 1);
final InstructionList il = new InstructionList();
int alen = getArgCount() + (thisVar == null ? 0 : 1) +
((targetVar != null && targetVar != thisVar) ? 1 : 0) +
(thisJoinPointVar == null ? 0 : 1);
il.append(Utility.createConstant(fact, alen));
il.append((Instruction)fact.createNewArray(Type.OBJECT, (short)1));
arrayVar.appendStore(il, fact);
int stateIndex = 0;
if (thisVar != null) {
arrayVar.appendConvertableArrayStore(il, fact, stateIndex, thisVar);
thisVar.setPositionInAroundState(stateIndex);
stateIndex++;
}
if (targetVar != null && targetVar != thisVar) {
arrayVar.appendConvertableArrayStore(il, fact, stateIndex, targetVar);
targetVar.setPositionInAroundState(stateIndex);
stateIndex++;
}
for (int i = 0, len = getArgCount(); i<len; i++) {
arrayVar.appendConvertableArrayStore(il, fact, stateIndex, argVars[i]);
argVars[i].setPositionInAroundState(stateIndex);
stateIndex++;
}
if (thisJoinPointVar != null) {
arrayVar.appendConvertableArrayStore(il, fact, stateIndex, thisJoinPointVar);
thisJoinPointVar.setPositionInAroundState(stateIndex);
stateIndex++;
}
il.append(fact.createNew(new ObjectType(constructor.getDeclaringType().getName())));
il.append(new DUP());
arrayVar.appendLoad(il, fact);
il.append(Utility.createInvoke(fact, world, constructor));
if (getKind() == PreInitialization) {
il.append(InstructionConstants.DUP);
holder.appendStore(il, fact);
}
return il;
}
private IntMap makeProceedArgumentMap(BcelVar[] adviceArgs) {
//System.err.println("coming in with " + Arrays.asList(adviceArgs));
IntMap ret = new IntMap();
for(int i = 0, len = adviceArgs.length; i < len; i++) {
BcelVar v = (BcelVar) adviceArgs[i];
if (v == null) continue; // XXX we don't know why this is required
int pos = v.getPositionInAroundState();
if (pos >= 0) { // need this test to avoid args bound via cflow
ret.put(pos, i);
}
}
//System.err.println("returning " + ret);
return ret;
}
/**
*
*
* @param callbackMethod the method we will call back to when our run method gets called.
*
* @param proceedMap A map from state position to proceed argument position. May be
* non covering on state position.
*/
private LazyMethodGen makeClosureClassAndReturnConstructor(
String closureClassName,
LazyMethodGen callbackMethod,
IntMap proceedMap)
{
String superClassName = "org.aspectj.runtime.internal.AroundClosure";
Type objectArrayType = new ArrayType(Type.OBJECT, 1);
LazyClassGen closureClass = new LazyClassGen(closureClassName,
superClassName,
getEnclosingClass().getFileName(),
Modifier.PUBLIC,
new String[] {});
InstructionFactory fact = new InstructionFactory(closureClass.getConstantPoolGen());
// constructor
LazyMethodGen constructor = new LazyMethodGen(Modifier.PUBLIC,
Type.VOID,
"<init>",
new Type[] {objectArrayType},
new String[] {},
closureClass);
InstructionList cbody = constructor.getBody();
cbody.append(InstructionFactory.createLoad(Type.OBJECT, 0));
cbody.append(InstructionFactory.createLoad(objectArrayType, 1));
cbody.append(fact.createInvoke(superClassName, "<init>", Type.VOID,
new Type[] {objectArrayType}, Constants.INVOKESPECIAL));
cbody.append(InstructionFactory.createReturn(Type.VOID));
closureClass.addMethodGen(constructor);
// method
LazyMethodGen runMethod = new LazyMethodGen(Modifier.PUBLIC,
Type.OBJECT,
"run",
new Type[] {objectArrayType},
new String[] {},
closureClass);
InstructionList mbody = runMethod.getBody();
BcelVar proceedVar = new BcelVar(TypeX.OBJECTARRAY.resolve(world), 1);
// int proceedVarIndex = 1;
BcelVar stateVar =
new BcelVar(TypeX.OBJECTARRAY.resolve(world), runMethod.allocateLocal(1));
// int stateVarIndex = runMethod.allocateLocal(1);
mbody.append(InstructionFactory.createThis());
mbody.append(fact.createGetField(superClassName, "state", objectArrayType));
mbody.append(stateVar.createStore(fact));
// mbody.append(fact.createStore(objectArrayType, stateVarIndex));
Type[] stateTypes = callbackMethod.getArgumentTypes();
for (int i=0, len=stateTypes.length; i < len; i++) {
Type stateType = stateTypes[i];
ResolvedTypeX stateTypeX = BcelWorld.fromBcel(stateType).resolve(world);
if (proceedMap.hasKey(i)) {
mbody.append(
proceedVar.createConvertableArrayLoad(fact, proceedMap.get(i),
stateTypeX));
} else {
mbody.append(
stateVar.createConvertableArrayLoad(fact, i,
stateTypeX));
}
}
mbody.append(Utility.createInvoke(fact, callbackMethod));
if (getKind() == PreInitialization) {
mbody.append(Utility.createSet(
fact,
AjcMemberMaker.aroundClosurePreInitializationField()));
mbody.append(InstructionConstants.ACONST_NULL);
} else {
mbody.append(
Utility.createConversion(
fact,
callbackMethod.getReturnType(),
Type.OBJECT));
}
mbody.append(InstructionFactory.createReturn(Type.OBJECT));
closureClass.addMethodGen(runMethod);
// class
getEnclosingClass().addGeneratedInner(closureClass);
return constructor;
}
// ---- extraction methods
public LazyMethodGen extractMethod(String newMethodName, int visibilityModifier, ShadowMunger munger) {
LazyMethodGen.assertGoodBody(range.getBody(), newMethodName);
if (!getKind().allowsExtraction()) throw new BCException();
LazyMethodGen freshMethod = createMethodGen(newMethodName,visibilityModifier);
// System.err.println("******");
// System.err.println("ABOUT TO EXTRACT METHOD for" + this);
// enclosingMethod.print(System.err);
// System.err.println("INTO");
// freshMethod.print(System.err);
// System.err.println("WITH REMAP");
// System.err.println(makeRemap());
range.extractInstructionsInto(freshMethod, makeRemap(),
(getKind() != PreInitialization) &&
isFallsThrough());
if (getKind() == PreInitialization) {
addPreInitializationReturnCode(
freshMethod,
getSuperConstructorParameterTypes());
}
getEnclosingClass().addMethodGen(freshMethod,munger.getSourceLocation());
return freshMethod;
}
private void addPreInitializationReturnCode(
LazyMethodGen extractedMethod,
Type[] superConstructorTypes)
{
InstructionList body = extractedMethod.getBody();
final InstructionFactory fact = getFactory();
BcelVar arrayVar = new BcelVar(
world.getCoreType(TypeX.OBJECTARRAY),
extractedMethod.allocateLocal(1));
int len = superConstructorTypes.length;
body.append(Utility.createConstant(fact, len));
body.append((Instruction)fact.createNewArray(Type.OBJECT, (short)1));
arrayVar.appendStore(body, fact);
for (int i = len - 1; i >= 0; i++) {
// convert thing on top of stack to object
body.append(
Utility.createConversion(fact, superConstructorTypes[i], Type.OBJECT));
// push object array
arrayVar.appendLoad(body, fact);
// swap
body.append(InstructionConstants.SWAP);
// do object array store.
body.append(Utility.createConstant(fact, i));
body.append(InstructionConstants.SWAP);
body.append(InstructionFactory.createArrayStore(Type.OBJECT));
}
arrayVar.appendLoad(body, fact);
body.append(InstructionConstants.ARETURN);
}
private Type[] getSuperConstructorParameterTypes() {
// assert getKind() == PreInitialization
InstructionHandle superCallHandle = getRange().getEnd().getNext();
InvokeInstruction superCallInstruction =
(InvokeInstruction) superCallHandle.getInstruction();
return superCallInstruction.getArgumentTypes(
getEnclosingClass().getConstantPoolGen());
}
/** make a map from old frame location to new frame location. Any unkeyed frame
* location picks out a copied local */
private IntMap makeRemap() {
IntMap ret = new IntMap(5);
int reti = 0;
if (thisVar != null) {
ret.put(0, reti++); // thisVar guaranteed to be 0
}
if (targetVar != null && targetVar != thisVar) {
ret.put(targetVar.getSlot(), reti++);
}
for (int i = 0, len = argVars.length; i < len; i++) {
ret.put(argVars[i].getSlot(), reti);
reti += argVars[i].getType().getSize();
}
if (thisJoinPointVar != null) {
ret.put(thisJoinPointVar.getSlot(), reti++);
}
// we not only need to put the arguments, we also need to remap their
// aliases, which we so helpfully put into temps at the beginning of this join
// point.
if (! getKind().argsOnStack()) {
int oldi = 0;
int newi = 0;
// if we're passing in a this and we're not argsOnStack we're always
// passing in a target too
if (arg0HoldsThis()) { ret.put(0, 0); oldi++; newi+=1; }
//assert targetVar == thisVar
for (int i = 0; i < getArgCount(); i++) {
TypeX type = getArgType(i);
ret.put(oldi, newi);
oldi += type.getSize();
newi += type.getSize();
}
}
// System.err.println("making remap for : " + this);
// if (targetVar != null) System.err.println("target slot : " + targetVar.getSlot());
// if (thisVar != null) System.err.println(" this slot : " + thisVar.getSlot());
// System.err.println(ret);
return ret;
}
/**
* The new method always static.
* It may take some extra arguments: this, target.
* If it's argsOnStack, then it must take both this/target
* If it's argsOnFrame, it shares this and target.
* ??? rewrite this to do less array munging, please
*/
private LazyMethodGen createMethodGen(String newMethodName, int visibilityModifier) {
Type[] parameterTypes = BcelWorld.makeBcelTypes(getArgTypes());
int modifiers = Modifier.FINAL | visibilityModifier;
// XXX some bug
// if (! isExpressionKind() && getSignature().isStrict(world)) {
// modifiers |= Modifier.STRICT;
// }
modifiers |= Modifier.STATIC;
if (targetVar != null && targetVar != thisVar) {
TypeX targetType = getTargetType();
ResolvedMember resolvedMember = getSignature().resolve(world);
if (resolvedMember != null && Modifier.isProtected(resolvedMember.getModifiers()) &&
!samePackage(targetType.getPackageName(), getEnclosingType().getPackageName()))
{
if (!targetType.isAssignableFrom(getThisType(), world)) {
throw new BCException("bad bytecode");
}
targetType = getThisType();
}
parameterTypes = addType(BcelWorld.makeBcelType(targetType), parameterTypes);
}
if (thisVar != null) {
TypeX thisType = getThisType();
parameterTypes = addType(BcelWorld.makeBcelType(thisType), parameterTypes);
}
// We always want to pass down thisJoinPoint in case we have already woven
// some advice in here. If we only have a single piece of around advice on a
// join point, it is unnecessary to accept (and pass) tjp.
if (thisJoinPointVar != null) {
parameterTypes = addTypeToEnd(LazyClassGen.tjpType, parameterTypes);
}
TypeX returnType;
if (getKind() == PreInitialization) {
returnType = TypeX.OBJECTARRAY;
} else {
returnType = getReturnType();
}
return
new LazyMethodGen(
modifiers,
BcelWorld.makeBcelType(returnType),
newMethodName,
parameterTypes,
new String[0],
// XXX again, we need to look up methods!
// TypeX.getNames(getSignature().getExceptions(world)),
getEnclosingClass());
}
private boolean samePackage(String p1, String p2) {
if (p1 == null) return p2 == null;
if (p2 == null) return false;
return p1.equals(p2);
}
private Type[] addType(Type type, Type[] types) {
int len = types.length;
Type[] ret = new Type[len+1];
ret[0] = type;
System.arraycopy(types, 0, ret, 1, len);
return ret;
}
private Type[] addTypeToEnd(Type type, Type[] types) {
int len = types.length;
Type[] ret = new Type[len+1];
ret[len] = type;
System.arraycopy(types, 0, ret, 0, len);
return ret;
}
public BcelVar genTempVar(TypeX typeX) {
return new BcelVar(typeX.resolve(world), genTempVarIndex(typeX.getSize()));
}
// public static final boolean CREATE_TEMP_NAMES = true;
public BcelVar genTempVar(TypeX typeX, String localName) {
BcelVar tv = genTempVar(typeX);
// if (CREATE_TEMP_NAMES) {
// for (InstructionHandle ih = range.getStart(); ih != range.getEnd(); ih = ih.getNext()) {
// if (Range.isRangeHandle(ih)) continue;
// ih.addTargeter(new LocalVariableTag(typeX, localName, tv.getSlot()));
// }
// }
return tv;
}
// eh doesn't think we need to garbage collect these (64K is a big number...)
private int genTempVarIndex(int size) {
return enclosingMethod.allocateLocal(size);
}
public InstructionFactory getFactory() {
return getEnclosingClass().getFactory();
}
public ISourceLocation getSourceLocation() {
int sourceLine = getSourceLine();
if (sourceLine == 0 || sourceLine == -1) {
// Thread.currentThread().dumpStack();
// System.err.println(this + ": " + range);
return getEnclosingClass().getType().getSourceLocation();
} else {
return getEnclosingClass().getType().getSourceContext().makeSourceLocation(sourceLine);
}
}
public Shadow getEnclosingShadow() {
return enclosingShadow;
}
public LazyMethodGen getEnclosingMethod() {
return enclosingMethod;
}
public boolean isFallsThrough() {
return !terminatesWithReturn(); //fallsThrough;
}
}
|
72,528
|
Bug 72528 around advice throws java.lang.VerifyError at runtime
|
I have an aspect that captures around() a pcd and returns an Object[], though the actual methods being instrumented might return any valid POJO array, i understand that AspectJ will take care of casting at assignment. I expected the following code to work properly, but at runtime i get a java.lang.VerifyError as shown below: F:\wd\Hello>ajbrowser HelloWorld.lst java.lang.VerifyError: (class: de/rohith/PrinterWorld, method: returnArrayWithCl oning signature: ()[Ljava/lang/Integer;) Incompatible argument to function at de.rohith.HelloWorld.main(HelloWorld.java:18) Exception in thread "main" I suspect the compiler fails to notice the return types of the methods being caught at compile time. I have tested this code with both ajbrowser as well as AJDT, both result in the same error output. -----------HelloWorldAspect.java--------------- package de.rohith; import java.lang.Object; public aspect HelloWorldAspect { private int callDepth = -1; public HelloWorldAspect() { } pointcut hello(): !within(HelloWorldAspect); pointcut method(): execution(public (*[]) de..*(..)); pointcut cloning(): call(* java.lang.Object.clone()); declare warning: method() && hello(): "*[] returning method called" ; Object[] around(): cflow(method()) && cloning() && hello() { print("", thisEnclosingJoinPointStaticPart); Object[] ret = proceed(); return (Object[])ret.clone(); } private void print(String prefix, Object message) { for (int i = 0, spaces = callDepth * 2; i < spaces; i++) { System.out.print(" "); } System.out.println(prefix + message); } } -----------PrinterWorld.java------------ package de.rohith; public class PrinterWorld { private Integer[] intArray = new Integer[2]; public PrinterWorld() { } public void print() { System.out.println("Hello World!"); } public Integer returnInt() { return new Integer(3); } public Integer[] returnArrayWithCloning() { for (int i = 0; i < intArray.length; i++) { intArray[i] = new Integer(i++); } return (Integer[])intArray.clone(); } public Integer[] returnArrayWithoutCloning() { return intArray; } } -----------HelloWorld.java------------ package de.rohith; public class HelloWorld { public static void main(String[] args) { PrinterWorld p = new PrinterWorld(); p.print(); Integer i = p.returnInt(); Integer[] intArray = p.returnArrayWithCloning(); Integer[] array2 = p.returnArrayWithoutCloning(); } }
|
resolved fixed
|
27d204c
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-03T13:45:46Z
| 2004-08-24T17:53:20Z
|
tests/bugs/ArrayCloning.java
| |
72,528
|
Bug 72528 around advice throws java.lang.VerifyError at runtime
|
I have an aspect that captures around() a pcd and returns an Object[], though the actual methods being instrumented might return any valid POJO array, i understand that AspectJ will take care of casting at assignment. I expected the following code to work properly, but at runtime i get a java.lang.VerifyError as shown below: F:\wd\Hello>ajbrowser HelloWorld.lst java.lang.VerifyError: (class: de/rohith/PrinterWorld, method: returnArrayWithCl oning signature: ()[Ljava/lang/Integer;) Incompatible argument to function at de.rohith.HelloWorld.main(HelloWorld.java:18) Exception in thread "main" I suspect the compiler fails to notice the return types of the methods being caught at compile time. I have tested this code with both ajbrowser as well as AJDT, both result in the same error output. -----------HelloWorldAspect.java--------------- package de.rohith; import java.lang.Object; public aspect HelloWorldAspect { private int callDepth = -1; public HelloWorldAspect() { } pointcut hello(): !within(HelloWorldAspect); pointcut method(): execution(public (*[]) de..*(..)); pointcut cloning(): call(* java.lang.Object.clone()); declare warning: method() && hello(): "*[] returning method called" ; Object[] around(): cflow(method()) && cloning() && hello() { print("", thisEnclosingJoinPointStaticPart); Object[] ret = proceed(); return (Object[])ret.clone(); } private void print(String prefix, Object message) { for (int i = 0, spaces = callDepth * 2; i < spaces; i++) { System.out.print(" "); } System.out.println(prefix + message); } } -----------PrinterWorld.java------------ package de.rohith; public class PrinterWorld { private Integer[] intArray = new Integer[2]; public PrinterWorld() { } public void print() { System.out.println("Hello World!"); } public Integer returnInt() { return new Integer(3); } public Integer[] returnArrayWithCloning() { for (int i = 0; i < intArray.length; i++) { intArray[i] = new Integer(i++); } return (Integer[])intArray.clone(); } public Integer[] returnArrayWithoutCloning() { return intArray; } } -----------HelloWorld.java------------ package de.rohith; public class HelloWorld { public static void main(String[] args) { PrinterWorld p = new PrinterWorld(); p.print(); Integer i = p.returnInt(); Integer[] intArray = p.returnArrayWithCloning(); Integer[] array2 = p.returnArrayWithoutCloning(); } }
|
resolved fixed
|
27d204c
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-03T13:45:46Z
| 2004-08-24T17:53:20Z
|
tests/src/org/aspectj/systemtest/ajc121/Ajc121Tests.java
|
/* *******************************************************************
* Copyright (c) 2004 IBM Corporation
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* ******************************************************************/
package org.aspectj.systemtest.ajc121;
import java.io.File;
import java.util.Iterator;
import java.util.List;
import junit.framework.Test;
import org.aspectj.bridge.WeaveMessage;
import org.aspectj.testing.XMLBasedAjcTestCase;
public class Ajc121Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc121Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc121/ajc121.xml");
}
public void test001(){
runTest("false ambiguous binding error (introduced in 1.2rc2)");
}
public void test002(){
runTest("An if() pointcut inside a perthis() clauses an ABORT - null pointer exception in ajc");
}
public void test003(){
runTest("An if() pointcut inside a perthis() clauses an ABORT - null pointer exception in ajc");
}
public void test004(){
runTest("An if() pointcut inside a perthis() clauses an ABORT - null pointer exception in ajc");
}
public void test005(){
runTest("compiler aborts with 'conflicting dominates orders' with circular declare precedences");
}
public void test006(){
runTest("'can't bind type' message has $ for . in type name for declare soft");
}
public void test007(){
runTest("Hiding of Instance Methods by static methods");
}
public void test008(){
runTest("if(false) optimisation");
}
public void test009(){
runTest("if(true) optimisation");
}
public void test010(){
runTest("java.lang.NullPointerException in WeaverMessageHandler class");
}
public void test011(){
runTest("ClassCastException at BcelRenderer.java:169");
}
public void test012(){
runTest("Front-end bug, shouldn't allow patterns of the form foo.., should be foo..*");
}
public void test013() {
runTest("Nullpointer-Exception when defining a withincode() pointcut");
}
public void test014() {
runTest("NPE, Incorrect XLint:unmatchedSuperTypeInCall warning");
}
public void test015_invalidXlint() { // keywords: "laurie hendren"
runTest("invalid warning indicating no match when a match really occurs");
}
public void test016_ByteConversionInstructions() {
runTest("RuntimeException thrown: Could not find instruction: org.apache.bcel.generic.B2I");
String output = getLastRunResult().getStdErr();
assertTrue("Expected to find [b2] in this output but didn't:"+output,output.indexOf("[b2]")!=-1);
assertTrue("Expected to find [b127] in this output but didn't:"+output,output.indexOf("[b127]")!=-1);
assertTrue("Expected to find [b0] in this output but didn't:"+output,output.indexOf("[b0]")!=-1);
assertTrue("Expected to find [c65] in this output but didn't:"+output,output.indexOf("[c65]")!=-1);
assertTrue("Expected to find [c66] in this output but didn't:"+output,output.indexOf("[c66]")!=-1);
assertTrue("Expected to find [c67] in this output but didn't:"+output,output.indexOf("[c67]")!=-1);
assertTrue("Expected to find [s1] in this output but didn't:"+output,output.indexOf("[s1]")!=-1);
assertTrue("Expected to find [s32767] in this output but didn't:"+output,output.indexOf("[s32767]")!=-1);
assertTrue("Expected to find [b0] in this output but didn't:"+output,output.indexOf("[b0]")!=-1);
}
public void test017_PrivateMethodCallsInAroundAdvice() {
runTest("Cannot advise private method call in around advice");
System.err.println(getLastRunResult().getStdErr());
}
public void test018_PrivateFieldSetsInAroundAdvice() {
runTest("Cannot advise private field sets in around advice");
System.err.println(getLastRunResult().getStdErr());
}
public void test019_PrivateFieldGetsInAroundAdvice() {
runTest("Cannot advise private field gets in around advice");
System.err.println(getLastRunResult().getStdErr());
}
// test takes over 5 minutes to run, so not included in normal suite run
// public void test020_branchTargetOffsetTooLargeForShort() {
// runTest("Branch target offset too large for short");
// }
// public void test021_BcelFailureWithVeryLargeClasses() {
// runTest("Weaver fails in BCEL for large classes");
// }
//
// public void test022_BcelFailureWithVeryLargeClasses_Binary() {
// runTest("Weaver fails in BCEL for large classes (binary)");
// }
public void test023_proceedInAround1() {
runTest("proceed used as method name in around advice (1)");
}
public void test024_proceedInAround2() {
runTest("proceed used as method name in around advice (2)");
}
public void test025_proceedInAround3() {
runTest("proceed used as method name in around advice (3)");
}
public void test026_bindingThisAndTargetToTheSameFormal() {
runTest("ajc crashes when compiling the following program (binding this() and target())");
}
public void test027_itdsOnInnerClassesAsStatic() {
runTest("ITDs on inner classes should be static context");
}
public void test028_itdsAndInitializers() {
runTest("resolution of IT field inits");
}
public void test029_falseInvalidAbsoluteTypeName() {
runTest("Valid but inaccessible type names should not be flagged by XLint:invalidAbsoluteTypeName");
}
public void test030_privateITDinitialisersBeingMatched() {
runTest("intertype initialisers should match field set pointcuts");
}
public void test031_privateITDinitialisersBeingMatched_OxfordTest() {
runTest("intertype initialisers should match field set pointcuts (oxford testcase)");
//System.err.println(">"+getLastRunResult().getStdErr());
String exp = ":set field set(int C.n):set field set(int C.m):get field get(int C.n):set field set(int C.n)";
assertTrue("Expected output '"+exp+"' but got "+getLastRunResult().getStdErr(),
getLastRunResult().getStdErr().equals(exp));
}
public void test032_stringConcatForDEOW() {
runTest("Compile time declarations (warning and error) do not accept string concatenation (with +)");
}
public void test033_stringConcatForDEOWErrorCase() {
runTest("Compile time declarations (warning and error) do not accept string concatenation (with +) (2)");
}
public void test034_scopeForITDS_pr61768() {
runTest("scope for inter-type methods");
}
public void test035_innerAspectCallsPrivateMethod_pr71372() {
runTest("NoSuchMethodError calling private method from around advice in inner aspect");
String s = getLastRunResult().getStdErr();
assertTrue("Expected ':before:around' but got "+s,
s.equals(":before:around"));
}
public void test036_innerAspectCallsPrivateMethod_pr71372_2() {
runTest("NoSuchMethodError calling private method from around advice in inner aspect (2)");
String s = getLastRunResult().getStdErr();
assertTrue("Expected ':before:around' but got "+s,
s.equals(":before:around"));
}
public void test037_innerAspectCallsPrivateMethod_pr71372_3() {
runTest("NoSuchMethodError calling private method from around advice in inner aspect (3)");
String s = getLastRunResult().getStdErr();
assertTrue("Expected ':before:around' but got "+s,
s.equals(":before:around"));
}
public void test038_innerAspectCallsPrivateMethod_pr71372_4() {
runTest("NoSuchMethodError calling private method from around advice in inner aspect (4)");
String s = getLastRunResult().getStdErr();
assertTrue("Expected ':before:around' but got "+s,
s.equals(":before:around"));
}
public void test039_privilegedAspectAccessingPrivateMethods_pr67579() {
runTest("NPE on privileged aspect error");
}
public void test040_privilegedAspectAccessingPrivateMethods_pr67579_2() {
runTest("NPE on privileged aspect error (2)");
}
public void test041_ITDaccessingPrivateMethod_pr67578() {
runTest("Privileged Aspect Access Problem Across Packages");
}
public void test042_ITDaccessingPrivateMethod_pr67578_2() {
runTest("Privileged Aspect Access Problem Across Packages (2)");
}
public void test043_pr62642_ExceptionInInitializerError() {
runTest("proper handling of ExceptionInIntializer inside clinit in presence of after throwing advice");
String s = getLastRunResult().getStdErr();
assertTrue("Output should contain java.lang.ExceptionInInitializerError but is '"+s+"'",
s.indexOf("java.lang.ExceptionInInitializerError")!=-1);
// No getCause on 1.3 JVMs
// assertTrue("Output should contain 'CAUSE=org.aspectj.lang.NoAspectBoundException' but is '"+s+"'",
// s.indexOf("CAUSE=org.aspectj.lang.NoAspectBoundException")!=-1);
}
public void test044_ITDnameClashes() {
runTest("ITD name clashes with private members");
}
public void test045_ITDprotectedVisibility() {
runTest("Inconsistency in scoping of protected members in ITDs");
}
public void test045_wrongLineForExecutionJoinPoint() {
runTest("wrong line for method execution join point");
}
public void test046_interfaceITD_pr70794_1() {
runTest("The introduction on interface causes the interface implementation class error (1)");
}
public void test047_interfaceITD_pr70794_2() {
runTest("The introduction on interface causes the interface implementation class error (2)");
}
public void test048_interfaceITD_pr70794_3() {
runTest("The introduction on interface causes the interface implementation class error (3)");
}
public void test049_interfaceITD_pr70794_4() {
runTest("The introduction on interface causes the interface implementation class error (4)");
}
public void test050_typePatternMatchingWithArrays() {
runTest("declare warning warns at wrong points");
}
public void test051_arrayCloningInJava5() {
runTest("AJC possible bug with static nested classes");
List l = ajc.getLastCompilationResult().getInfoMessages();
assertTrue("Should at least have had one weaving message",l!=null && l.size()>0);
boolean gotWeaveMessage = false;
for (Iterator msg = l.iterator(); msg.hasNext();) {
Object element = (Object) msg.next();
if (element instanceof WeaveMessage) {
WeaveMessage wm = (WeaveMessage)element;
if (wm.getMessage().indexOf("advised by around advice from")!=-1) gotWeaveMessage = true;
}
}
assertTrue("Expected a weaving message but only found "+l,gotWeaveMessage);
}
public void test052_bogusMessage1() {
runTest("Bogus error message: The abstract method ajc$pointcut$$tracingScope$a2 in type Tracing can only be defined by an abstract class (1)");
}
public void test053_bogusMessage2() {
runTest("Bogus error message: The abstract method ajc$pointcut$$tracingScope$a2 in type Tracing can only be defined by an abstract class (2)");
}
public void test054_cnfe() {
runTest("passing null to array arguments confuzes static join point signature. (1)");
}
public void test055_cnfe() {
runTest("passing null to array arguments confuzes static join point signature. (2)");
}
}
|
72,528
|
Bug 72528 around advice throws java.lang.VerifyError at runtime
|
I have an aspect that captures around() a pcd and returns an Object[], though the actual methods being instrumented might return any valid POJO array, i understand that AspectJ will take care of casting at assignment. I expected the following code to work properly, but at runtime i get a java.lang.VerifyError as shown below: F:\wd\Hello>ajbrowser HelloWorld.lst java.lang.VerifyError: (class: de/rohith/PrinterWorld, method: returnArrayWithCl oning signature: ()[Ljava/lang/Integer;) Incompatible argument to function at de.rohith.HelloWorld.main(HelloWorld.java:18) Exception in thread "main" I suspect the compiler fails to notice the return types of the methods being caught at compile time. I have tested this code with both ajbrowser as well as AJDT, both result in the same error output. -----------HelloWorldAspect.java--------------- package de.rohith; import java.lang.Object; public aspect HelloWorldAspect { private int callDepth = -1; public HelloWorldAspect() { } pointcut hello(): !within(HelloWorldAspect); pointcut method(): execution(public (*[]) de..*(..)); pointcut cloning(): call(* java.lang.Object.clone()); declare warning: method() && hello(): "*[] returning method called" ; Object[] around(): cflow(method()) && cloning() && hello() { print("", thisEnclosingJoinPointStaticPart); Object[] ret = proceed(); return (Object[])ret.clone(); } private void print(String prefix, Object message) { for (int i = 0, spaces = callDepth * 2; i < spaces; i++) { System.out.print(" "); } System.out.println(prefix + message); } } -----------PrinterWorld.java------------ package de.rohith; public class PrinterWorld { private Integer[] intArray = new Integer[2]; public PrinterWorld() { } public void print() { System.out.println("Hello World!"); } public Integer returnInt() { return new Integer(3); } public Integer[] returnArrayWithCloning() { for (int i = 0; i < intArray.length; i++) { intArray[i] = new Integer(i++); } return (Integer[])intArray.clone(); } public Integer[] returnArrayWithoutCloning() { return intArray; } } -----------HelloWorld.java------------ package de.rohith; public class HelloWorld { public static void main(String[] args) { PrinterWorld p = new PrinterWorld(); p.print(); Integer i = p.returnInt(); Integer[] intArray = p.returnArrayWithCloning(); Integer[] array2 = p.returnArrayWithoutCloning(); } }
|
resolved fixed
|
27d204c
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-03T13:45:46Z
| 2004-08-24T17:53:20Z
|
weaver/src/org/aspectj/weaver/ResolvedTypeX.java
|
/* *******************************************************************
* 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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.Message;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.weaver.patterns.Declare;
import org.aspectj.weaver.patterns.PerClause;
public abstract class ResolvedTypeX extends TypeX {
protected World world;
ResolvedTypeX(String signature, World world) {
super(signature);
this.world = world;
}
// ---- things that don't require a world
/** returns Iterator<ResolvedTypeX>
*/
public final Iterator getDirectSupertypes() {
Iterator ifacesIterator = Iterators.array(getDeclaredInterfaces());
ResolvedTypeX superclass = getSuperclass();
if (superclass == null) {
return ifacesIterator;
} else {
return Iterators.snoc(ifacesIterator, superclass);
}
}
public abstract ResolvedMember[] getDeclaredFields();
public abstract ResolvedMember[] getDeclaredMethods();
public abstract ResolvedTypeX[] getDeclaredInterfaces();
public abstract ResolvedMember[] getDeclaredPointcuts();
public abstract ResolvedTypeX getSuperclass();
public abstract int getModifiers();
public abstract boolean needsNoConversionFrom(TypeX other);
public abstract boolean isCoerceableFrom(TypeX other);
public abstract boolean isAssignableFrom(TypeX other);
// ---- things that would require a world if I weren't resolved
public final Iterator getDirectSupertypes(World world) {
return getDirectSupertypes();
}
public final ResolvedMember[] getDeclaredFields(World world) {
return getDeclaredFields();
}
public final ResolvedMember[] getDeclaredMethods(World world) {
return getDeclaredMethods();
}
public final TypeX[] getDeclaredInterfaces(World world) {
return getDeclaredInterfaces();
}
public final ResolvedMember[] getDeclaredPointcuts(World world) {
return getDeclaredPointcuts();
}
public final int getModifiers(World world) {
return getModifiers();
}
public final TypeX getSuperclass(World world) {
return getSuperclass();
}
// conversions
public final boolean isAssignableFrom(TypeX other, World world) {
return isAssignableFrom(other);
}
public final boolean isCoerceableFrom(TypeX other, World world) {
return isCoerceableFrom(other);
}
public boolean needsNoConversionFrom(TypeX other, World world) {
return needsNoConversionFrom(other);
}
public final boolean isConvertableFrom(TypeX other) {
if (this.equals(OBJECT) || other.equals(OBJECT)) return true;
return this.isCoerceableFrom(other);
}
// utilities
public ResolvedTypeX getResolvedComponentType() {
return null;
}
public ResolvedTypeX resolve(World world) {
return this;
}
public World getWorld() {
return world;
}
// ---- things from object
public final boolean equals(Object other) {
if (other instanceof ResolvedTypeX) {
return this == other;
} else {
return super.equals(other);
}
}
// ---- difficult things
/**
* returns an iterator through all of the fields of this type, in order
* for checking from JVM spec 2ed 5.4.3.2. This means that the order is
*
* <ul><li> fields from current class </li>
* <li> recur into direct superinterfaces </li>
* <li> recur into superclass </li>
* </ul>
*
* We keep a hashSet of interfaces that we've visited so we don't spiral
* out into 2^n land.
*/
public Iterator getFields() {
final Iterators.Filter dupFilter = Iterators.dupFilter();
Iterators.Getter typeGetter = new Iterators.Getter() {
public Iterator get(Object o) {
return
dupFilter.filter(
((ResolvedTypeX)o).getDirectSupertypes());
}
};
Iterators.Getter fieldGetter = new Iterators.Getter() {
public Iterator get(Object o) {
return Iterators.array(((ResolvedTypeX)o).getDeclaredFields());
}
};
return
Iterators.mapOver(
Iterators.recur(this, typeGetter),
fieldGetter);
}
/**
* returns an iterator through all of the methods of this type, in order
* for checking from JVM spec 2ed 5.4.3.3. This means that the order is
*
* <ul><li> methods from current class </li>
* <li> recur into superclass, all the way up, not touching interfaces </li>
* <li> recur into all superinterfaces, in some unspecified order </li>
* </ul>
*
* We keep a hashSet of interfaces that we've visited so we don't spiral
* out into 2^n land.
*/
public Iterator getMethods() {
final Iterators.Filter dupFilter = Iterators.dupFilter();
Iterators.Getter ifaceGetter = new Iterators.Getter() {
public Iterator get(Object o) {
return
dupFilter.filter(
Iterators.array(((ResolvedTypeX)o).getDeclaredInterfaces())
);
}
};
Iterators.Getter methodGetter = new Iterators.Getter() {
public Iterator get(Object o) {
return Iterators.array(((ResolvedTypeX)o).getDeclaredMethods());
}
};
return
Iterators.mapOver(
Iterators.append(
new Iterator() {
ResolvedTypeX curr = ResolvedTypeX.this;
public boolean hasNext() {
return curr != null;
}
public Object next() {
ResolvedTypeX ret = curr;
curr = curr.getSuperclass();
return ret;
}
public void remove() {
throw new UnsupportedOperationException();
}
},
Iterators.recur(this, ifaceGetter)),
methodGetter);
}
/**
* described in JVM spec 2ed 5.4.3.2
*/
public ResolvedMember lookupField(Member m) {
return lookupMember(m, getFields());
}
/**
* described in JVM spec 2ed 5.4.3.3
*/
public ResolvedMember lookupMethod(Member m) {
return lookupMember(m, getMethods());
}
/** return null if not found */
private ResolvedMember lookupMember(Member m, Iterator i) {
while (i.hasNext()) {
ResolvedMember f = (ResolvedMember) i.next();
if (matches(f, m)) return f;
}
return null; //ResolvedMember.Missing;
//throw new BCException("can't find " + m);
}
/** return null if not found */
private ResolvedMember lookupMember(Member m, ResolvedMember[] a) {
for (int i = 0; i < a.length; i++) {
ResolvedMember f = a[i];
if (matches(f, m)) return f;
}
return null;
}
public static boolean matches(Member m1, Member m2) {
if (m1 == null) return m2 == null;
if (m2 == null) return false;
return m1.getName().equals(m2.getName()) && m1.getSignature().equals(m2.getSignature());
}
public static boolean conflictingSignature(Member m1, Member m2) {
if (m1 == null || m2 == null) return false;
if (!m1.getName().equals(m2.getName())) { return false; }
if (m1.getKind() != m2.getKind()) { return false; }
if (m1.getKind() == Member.FIELD) {
return m1.getDeclaringType().equals(m2.getDeclaringType());
} else if (m1.getKind() == Member.POINTCUT) {
return true;
}
TypeX[] p1 = m1.getParameterTypes();
TypeX[] p2 = m2.getParameterTypes();
int n = p1.length;
if (n != p2.length) return false;
for (int i=0; i < n; i++) {
if (!p1[i].equals(p2[i])) return false;
}
return true;
}
/**
* returns an iterator through all of the pointcuts of this type, in order
* for checking from JVM spec 2ed 5.4.3.2 (as for fields). This means that the order is
*
* <ul><li> pointcuts from current class </li>
* <li> recur into direct superinterfaces </li>
* <li> recur into superclass </li>
* </ul>
*
* We keep a hashSet of interfaces that we've visited so we don't spiral
* out into 2^n land.
*/
public Iterator getPointcuts() {
final Iterators.Filter dupFilter = Iterators.dupFilter();
// same order as fields
Iterators.Getter typeGetter = new Iterators.Getter() {
public Iterator get(Object o) {
return
dupFilter.filter(
((ResolvedTypeX)o).getDirectSupertypes());
}
};
Iterators.Getter pointcutGetter = new Iterators.Getter() {
public Iterator get(Object o) {
//System.err.println("getting for " + o);
return Iterators.array(((ResolvedTypeX)o).getDeclaredPointcuts());
}
};
return
Iterators.mapOver(
Iterators.recur(this, typeGetter),
pointcutGetter);
}
public ResolvedPointcutDefinition findPointcut(String name) {
//System.err.println("looking for pointcuts " + this);
for (Iterator i = getPointcuts(); i.hasNext(); ) {
ResolvedPointcutDefinition f = (ResolvedPointcutDefinition) i.next();
//System.err.println(f);
if (name.equals(f.getName())) {
return f;
}
}
return null; // should we throw an exception here?
}
// all about collecting CrosscuttingMembers
//??? collecting data-structure, shouldn't really be a field
public CrosscuttingMembers crosscuttingMembers;
public CrosscuttingMembers collectCrosscuttingMembers() {
crosscuttingMembers = new CrosscuttingMembers(this);
crosscuttingMembers.setPerClause(getPerClause());
crosscuttingMembers.addShadowMungers(collectShadowMungers());
crosscuttingMembers.addTypeMungers(getTypeMungers());
crosscuttingMembers.addDeclares(collectDeclares(!this.doesNotExposeShadowMungers()));
crosscuttingMembers.addPrivilegedAccesses(getPrivilegedAccesses());
//System.err.println("collected cc members: " + this + ", " + collectDeclares());
return crosscuttingMembers;
}
public final Collection collectDeclares(boolean includeAdviceLike) {
if (! this.isAspect() ) return Collections.EMPTY_LIST;
ArrayList ret = new ArrayList();
//if (this.isAbstract()) {
for (Iterator i = getDeclares().iterator(); i.hasNext();) {
Declare dec = (Declare) i.next();
if (!dec.isAdviceLike()) ret.add(dec);
}
if (!includeAdviceLike) return ret;
if (!this.isAbstract()) {
//ret.addAll(getDeclares());
final Iterators.Filter dupFilter = Iterators.dupFilter();
Iterators.Getter typeGetter = new Iterators.Getter() {
public Iterator get(Object o) {
return
dupFilter.filter(
((ResolvedTypeX)o).getDirectSupertypes());
}
};
Iterator typeIterator = Iterators.recur(this, typeGetter);
while (typeIterator.hasNext()) {
ResolvedTypeX ty = (ResolvedTypeX) typeIterator.next();
//System.out.println("super: " + ty + ", " + );
for (Iterator i = ty.getDeclares().iterator(); i.hasNext();) {
Declare dec = (Declare) i.next();
if (dec.isAdviceLike()) ret.add(dec);
}
}
}
return ret;
}
private final Collection collectShadowMungers() {
if (! this.isAspect() || this.isAbstract() || this.doesNotExposeShadowMungers()) return Collections.EMPTY_LIST;
ArrayList acc = new ArrayList();
final Iterators.Filter dupFilter = Iterators.dupFilter();
Iterators.Getter typeGetter = new Iterators.Getter() {
public Iterator get(Object o) {
return
dupFilter.filter(
((ResolvedTypeX)o).getDirectSupertypes());
}
};
Iterator typeIterator = Iterators.recur(this, typeGetter);
while (typeIterator.hasNext()) {
ResolvedTypeX ty = (ResolvedTypeX) typeIterator.next();
acc.addAll(ty.getDeclaredShadowMungers());
}
return acc;
}
protected boolean doesNotExposeShadowMungers() {
return false;
}
public PerClause getPerClause() { return null; }
protected Collection getDeclares() {
return Collections.EMPTY_LIST;
}
protected Collection getTypeMungers() { return Collections.EMPTY_LIST; }
protected Collection getPrivilegedAccesses() { return Collections.EMPTY_LIST; }
// ---- useful things
public final boolean isInterface() {
return Modifier.isInterface(getModifiers());
}
public final boolean isAbstract() {
return Modifier.isAbstract(getModifiers());
}
public boolean isClass() {
return false;
}
public boolean isAspect() {
return false;
}
public boolean isSynthetic() {
return signature.indexOf("$ajc") != -1;
}
public final boolean isFinal() {
return Modifier.isFinal(getModifiers());
}
public Collection getDeclaredAdvice() {
List l = new ArrayList();
ResolvedMember[] methods = getDeclaredMethods();
for (int i=0, len = methods.length; i < len; i++) {
ShadowMunger munger = methods[i].getAssociatedShadowMunger();
if (munger != null) l.add(munger);
}
return l;
}
private List shadowMungers = new ArrayList(0);
public Collection getDeclaredShadowMungers() {
Collection c = getDeclaredAdvice();
c.addAll(shadowMungers);
return c;
}
public void addShadowMunger(ShadowMunger munger) {
shadowMungers.add(munger);
}
// ---- only for testing!
public ResolvedMember[] getDeclaredJavaFields() {
return filterInJavaVisible(getDeclaredFields());
}
public ResolvedMember[] getDeclaredJavaMethods() {
return filterInJavaVisible(getDeclaredMethods());
}
public ShadowMunger[] getDeclaredShadowMungersArray() {
List l = (List) getDeclaredShadowMungers();
return (ShadowMunger[]) l.toArray(new ShadowMunger[l.size()]);
}
private ResolvedMember[] filterInJavaVisible(ResolvedMember[] ms) {
List l = new ArrayList();
for (int i=0, len = ms.length; i < len; i++) {
if (! ms[i].isAjSynthetic() && ms[i].getAssociatedShadowMunger() == null) {
l.add(ms[i]);
}
}
return (ResolvedMember[]) l.toArray(new ResolvedMember[l.size()]);
}
public abstract ISourceContext getSourceContext();
// ---- fields
public static final ResolvedTypeX[] NONE = new ResolvedTypeX[0];
public static final Primitive BYTE = new Primitive("B", 1, 0);
public static final Primitive CHAR = new Primitive("C", 1, 1);
public static final Primitive DOUBLE = new Primitive("D", 2, 2);
public static final Primitive FLOAT = new Primitive("F", 1, 3);
public static final Primitive INT = new Primitive("I", 1, 4);
public static final Primitive LONG = new Primitive("J", 2, 5);
public static final Primitive SHORT = new Primitive("S", 1, 6);
public static final Primitive VOID = new Primitive("V", 0, 8);
public static final Primitive BOOLEAN = new Primitive("Z", 1, 7);
public static final Missing MISSING = new Missing();
// ---- types
public static class Name extends ResolvedTypeX {
private ConcreteName delegate = null;
private ISourceContext sourceContext = null;
private int startPos = 0;
private int endPos = 0;
//??? should set delegate before any use
public Name(String signature, World world) {
super(signature, world);
}
public final boolean isClass() {
return delegate.isClass();
}
public boolean isAspect() {
return delegate.isAspect();
}
public final boolean needsNoConversionFrom(TypeX o) {
return isAssignableFrom(o);
}
public final boolean isAssignableFrom(TypeX o) {
if (o.isPrimitive()) return false;
ResolvedTypeX other = o.resolve(world);
return isAssignableFrom(other);
}
public final boolean isCoerceableFrom(TypeX o) {
ResolvedTypeX other = o.resolve(world);
if (this.isAssignableFrom(other) || other.isAssignableFrom(this)) {
return true;
}
if (!this.isInterface() && !other.isInterface()) {
return false;
}
if (this.isFinal() || other.isFinal()) {
return false;
}
// ??? needs to be Methods, not just declared methods? JLS 5.5 unclear
ResolvedMember[] a = getDeclaredMethods();
ResolvedMember[] b = ((Name)other).getDeclaredMethods(); //??? is this cast always safe
for (int ai = 0, alen = a.length; ai < alen; ai++) {
for (int bi = 0, blen = b.length; bi < blen; bi++) {
if (! b[bi].isCompatibleWith(a[ai])) return false;
}
}
return true;
}
private boolean isAssignableFrom(ResolvedTypeX other) {
if (this == other) return true;
for(Iterator i = other.getDirectSupertypes(); i.hasNext(); ) {
if (this.isAssignableFrom((ResolvedTypeX) i.next())) return true;
}
return false;
}
public ISourceContext getSourceContext() {
return sourceContext;
}
public ISourceLocation getSourceLocation() {
if (sourceContext == null) return null;
return sourceContext.makeSourceLocation(new Position(startPos, endPos));
}
public boolean isExposedToWeaver() {
return (delegate == null) || delegate.isExposedToWeaver(); //??? where does this belong
}
public WeaverStateInfo getWeaverState() {
return delegate.getWeaverState();
}
public ResolvedMember[] getDeclaredFields() {
return delegate.getDeclaredFields();
}
public ResolvedTypeX[] getDeclaredInterfaces() {
return delegate.getDeclaredInterfaces();
}
public ResolvedMember[] getDeclaredMethods() {
return delegate.getDeclaredMethods();
}
public ResolvedMember[] getDeclaredPointcuts() {
return delegate.getDeclaredPointcuts();
}
public PerClause getPerClause() { return delegate.getPerClause(); }
protected Collection getDeclares() { return delegate.getDeclares(); }
protected Collection getTypeMungers() { return delegate.getTypeMungers(); }
protected Collection getPrivilegedAccesses() { return delegate.getPrivilegedAccesses(); }
public int getModifiers() {
return delegate.getModifiers();
}
public ResolvedTypeX getSuperclass() {
return delegate.getSuperclass();
}
public ConcreteName getDelegate() {
return delegate;
}
public void setDelegate(ConcreteName delegate) {
this.delegate = delegate;
}
public int getEndPos() {
return endPos;
}
public int getStartPos() {
return startPos;
}
public void setEndPos(int endPos) {
this.endPos = endPos;
}
public void setSourceContext(ISourceContext sourceContext) {
this.sourceContext = sourceContext;
}
public void setStartPos(int startPos) {
this.startPos = startPos;
}
public boolean doesNotExposeShadowMungers() {
return delegate.doesNotExposeShadowMungers();
}
}
public static abstract class ConcreteName {
//protected ISourceContext sourceContext;
protected boolean exposedToWeaver;
protected ResolvedTypeX.Name resolvedTypeX;
public ConcreteName(ResolvedTypeX.Name resolvedTypeX, boolean exposedToWeaver) {
//???super(signature, world);
this.resolvedTypeX = resolvedTypeX;
this.exposedToWeaver = exposedToWeaver;
}
public final boolean isClass() {
return !isAspect() && !isInterface();
}
public abstract boolean isAspect();
public abstract boolean isInterface();
public abstract ResolvedMember[] getDeclaredFields();
public abstract ResolvedTypeX[] getDeclaredInterfaces();
public abstract ResolvedMember[] getDeclaredMethods();
public abstract ResolvedMember[] getDeclaredPointcuts();
public abstract PerClause getPerClause();
protected abstract Collection getDeclares() ;
protected abstract Collection getTypeMungers();
protected abstract Collection getPrivilegedAccesses();
public abstract int getModifiers();
public abstract ResolvedTypeX getSuperclass();
// public abstract ISourceLocation getSourceLocation();
public abstract WeaverStateInfo getWeaverState();
// public ISourceContext getSourceContext() {
// return sourceContext;
// }
/**
* Designed to be overriden by EclipseType to disable collection of shadow mungers
* during pre-weave compilation phase
*/
public boolean doesNotExposeShadowMungers() {
return false;
}
public boolean isExposedToWeaver() {
return exposedToWeaver;
}
public ResolvedTypeX.Name getResolvedTypeX() {
return resolvedTypeX;
}
}
static class Array extends ResolvedTypeX {
ResolvedTypeX componentType;
Array(String s, World world, ResolvedTypeX componentType) {
super(s, world);
this.componentType = componentType;
}
public final ResolvedMember[] getDeclaredFields() {
return ResolvedMember.NONE;
}
public final ResolvedMember[] getDeclaredMethods() {
// ??? should this return clone? Probably not...
return ResolvedMember.NONE;
}
public final ResolvedTypeX[] getDeclaredInterfaces() {
return
new ResolvedTypeX[] {
world.getCoreType(CLONEABLE),
world.getCoreType(SERIALIZABLE)
};
}
public final ResolvedMember[] getDeclaredPointcuts() {
return ResolvedMember.NONE;
}
public final ResolvedTypeX getSuperclass() {
return world.getCoreType(OBJECT);
}
public final boolean isAssignableFrom(TypeX o) {
if (! o.isArray()) return false;
if (o.getComponentType().isPrimitive()) {
return o.equals(this);
} else {
return getComponentType().isAssignableFrom(o.getComponentType(), world);
}
}
public final boolean isCoerceableFrom(TypeX o) {
if (o.equals(TypeX.OBJECT) ||
o.equals(TypeX.SERIALIZABLE) ||
o.equals(TypeX.CLONEABLE)) {
return true;
}
if (! o.isArray()) return false;
if (o.getComponentType().isPrimitive()) {
return o.equals(this);
} else {
return getComponentType().isCoerceableFrom(o.getComponentType(), world);
}
}
public final boolean needsNoConversionFrom(TypeX o) {
return isAssignableFrom(o);
}
public final int getModifiers() {
int mask = Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED;
return (componentType.getModifiers() & mask) | Modifier.FINAL;
}
public TypeX getComponentType() {
return componentType;
}
public ResolvedTypeX getResolvedComponentType() {
return componentType;
}
public ISourceContext getSourceContext() {
return getResolvedComponentType().getSourceContext();
}
}
static class Primitive extends ResolvedTypeX {
private int size;
private int index;
Primitive(String signature, int size, int index) {
super(signature, null);
this.size = size;
this.index = index;
}
public final int getSize() {
return size;
}
public final int getModifiers() {
return Modifier.PUBLIC | Modifier.FINAL;
}
public final boolean isPrimitive() {
return true;
}
public final boolean isAssignableFrom(TypeX other) {
if (! other.isPrimitive()) return false;
return assignTable[((Primitive)other).index][index];
}
public final boolean isCoerceableFrom(TypeX other) {
if (this == other) return true;
if (! other.isPrimitive()) return false;
if (index > 6 || ((Primitive)other).index > 6) return false;
return true;
}
public final boolean needsNoConversionFrom(TypeX other) {
if (! other.isPrimitive()) return false;
return noConvertTable[((Primitive)other).index][index];
}
private static final boolean[][] assignTable =
{// to: B C D F I J S V Z from
{ true , true , true , true , true , true , true , false, false }, // B
{ false, true , true , true , true , true , false, false, false }, // C
{ false, false, true , false, false, false, false, false, false }, // D
{ false, false, true , true , false, false, false, false, false }, // F
{ false, false, true , true , true , true , false, false, false }, // I
{ false, false, true , true , false, true , false, false, false }, // J
{ false, false, true , true , true , true , true , false, false }, // S
{ false, false, false, false, false, false, false, true , false }, // V
{ false, false, false, false, false, false, false, false, true }, // Z
};
private static final boolean[][] noConvertTable =
{// to: B C D F I J S V Z from
{ true , true , false, false, true , false, true , false, false }, // B
{ false, true , false, false, true , false, false, false, false }, // C
{ false, false, true , false, false, false, false, false, false }, // D
{ false, false, false, true , false, false, false, false, false }, // F
{ false, false, false, false, true , false, false, false, false }, // I
{ false, false, false, false, false, true , false, false, false }, // J
{ false, false, false, false, true , false, true , false, false }, // S
{ false, false, false, false, false, false, false, true , false }, // V
{ false, false, false, false, false, false, false, false, true }, // Z
};
// ----
public final ResolvedMember[] getDeclaredFields() {
return ResolvedMember.NONE;
}
public final ResolvedMember[] getDeclaredMethods() {
return ResolvedMember.NONE;
}
public final ResolvedTypeX[] getDeclaredInterfaces() {
return ResolvedTypeX.NONE;
}
public final ResolvedMember[] getDeclaredPointcuts() {
return ResolvedMember.NONE;
}
public final ResolvedTypeX getSuperclass() {
return null;
}
public ISourceContext getSourceContext() {
return null;
}
}
static class Missing extends ResolvedTypeX {
Missing() {
super(MISSING_NAME, null);
}
// public final String toString() {
// return "<missing>";
// }
public final String getName() {
return MISSING_NAME;
}
public final ResolvedMember[] getDeclaredFields() {
return ResolvedMember.NONE;
}
public final ResolvedMember[] getDeclaredMethods() {
return ResolvedMember.NONE;
}
public final ResolvedTypeX[] getDeclaredInterfaces() {
return ResolvedTypeX.NONE;
}
public final ResolvedMember[] getDeclaredPointcuts() {
return ResolvedMember.NONE;
}
public final ResolvedTypeX getSuperclass() {
return null;
}
public final int getModifiers() {
return 0;
}
public final boolean isAssignableFrom(TypeX other) {
return false;
}
public final boolean isCoerceableFrom(TypeX other) {
return false;
}
public boolean needsNoConversionFrom(TypeX other) {
return false;
}
public ISourceContext getSourceContext() {
return null;
}
}
/** return null if not found */
public ResolvedMember lookupMemberNoSupers(Member member) {
ResolvedMember ret;
if (member.getKind() == Member.FIELD) {
ret = lookupMember(member, getDeclaredFields());
} else {
// assert member.getKind() == Member.METHOD || member.getKind() == Member.CONSTRUCTOR
ret = lookupMember(member, getDeclaredMethods());
}
if (ret == null && interTypeMungers != null) {
for (Iterator i = interTypeMungers.iterator(); i.hasNext();) {
ConcreteTypeMunger tm = (ConcreteTypeMunger) i.next();
if (matches(tm.getSignature(), member)) {
return tm.getSignature();
}
}
}
return ret;
}
protected List interTypeMungers = new ArrayList(0);
public List getInterTypeMungers() {
return interTypeMungers;
}
/**
* ??? This method is O(N*M) where N = number of methods and M is number of
* inter-type declarations in my super
*/
public List getInterTypeMungersIncludingSupers() {
ArrayList ret = new ArrayList();
collectInterTypeMungers(ret);
return ret;
}
private void collectInterTypeMungers(List collector) {
for (Iterator iter = getDirectSupertypes(); iter.hasNext();) {
ResolvedTypeX superType = (ResolvedTypeX) iter.next();
superType.collectInterTypeMungers(collector);
}
outer: for (Iterator iter1 = collector.iterator(); iter1.hasNext(); ) {
ConcreteTypeMunger superMunger = (ConcreteTypeMunger) iter1.next();
if ( superMunger.getSignature() == null) continue;
if ( !superMunger.getSignature().isAbstract()) continue;
for (Iterator iter = getInterTypeMungers().iterator(); iter.hasNext();) {
ConcreteTypeMunger myMunger = (ConcreteTypeMunger) iter.next();
if (conflictingSignature(myMunger.getSignature(), superMunger.getSignature())) {
iter1.remove();
continue outer;
}
}
if (!superMunger.getSignature().isPublic()) continue;
for (Iterator iter = getMethods(); iter.hasNext(); ) {
ResolvedMember method = (ResolvedMember)iter.next();
if (conflictingSignature(method, superMunger.getSignature())) {
iter1.remove();
continue outer;
}
}
}
collector.addAll(getInterTypeMungers());
}
/**
* Check:
* 1) That we don't have any abstract type mungers unless this type is abstract.
* 2) That an abstract ITDM on an interface is declared public. (Compiler limitation) (PR70794)
*/
public void checkInterTypeMungers() {
if (isAbstract()) return;
boolean itdProblem = false;
for (Iterator iter = getInterTypeMungersIncludingSupers().iterator(); iter.hasNext();) {
ConcreteTypeMunger munger = (ConcreteTypeMunger) iter.next();
itdProblem = checkAbstractDeclaration(munger) || itdProblem; // Rule 2
}
if (itdProblem) return; // If the rules above are broken, return right now
for (Iterator iter = getInterTypeMungersIncludingSupers().iterator(); iter.hasNext();) {
ConcreteTypeMunger munger = (ConcreteTypeMunger) iter.next();
if (munger.getSignature() != null && munger.getSignature().isAbstract()) { // Rule 1
world.getMessageHandler().handleMessage(
new Message("must implement abstract inter-type declaration: " + munger.getSignature(),
"", IMessage.ERROR, getSourceLocation(), null,
new ISourceLocation[] { getMungerLocation(munger) }));
}
}
}
/**
* See PR70794. This method checks that if an abstract inter-type method declaration is made on
* an interface then it must also be public.
* This is a compiler limitation that could be made to work in the future (if someone
* provides a worthwhile usecase)
*
* @return indicates if the munger failed the check
*/
private boolean checkAbstractDeclaration(ConcreteTypeMunger munger) {
if (munger.getMunger()!=null && (munger.getMunger() instanceof NewMethodTypeMunger)) {
ResolvedMember itdMember = munger.getSignature();
ResolvedTypeX onType = itdMember.getDeclaringType().resolve(world);
if (onType.isInterface() && itdMember.isAbstract() && !itdMember.isPublic()) {
world.getMessageHandler().handleMessage(
new Message(WeaverMessages.format(WeaverMessages.ITD_ABSTRACT_MUST_BE_PUBLIC_ON_INTERFACE,munger.getSignature(),onType),"",
Message.ERROR,getSourceLocation(),null,
new ISourceLocation[]{getMungerLocation(munger)})
);
return true;
}
}
return false;
}
/**
* Get a source location for the munger.
* Until intertype mungers remember where they came from, the source location
* for the munger itself is null. In these cases use the
* source location for the aspect containing the ITD.
*
*/
private ISourceLocation getMungerLocation(ConcreteTypeMunger munger) {
ISourceLocation sloc = munger.getSourceLocation();
if (sloc == null) {
sloc = munger.getAspectType().getSourceLocation();
}
return sloc;
}
/**
* Returns a ResolvedTypeX object representing the declaring type of this type, or
* null if this type does not represent a non-package-level-type.
*
* <strong>Warning</strong>: This is guaranteed to work for all member types.
* For anonymous/local types, the only guarantee is given in JLS 13.1, where
* it guarantees that if you call getDeclaringType() repeatedly, you will eventually
* get the top-level class, but it does not say anything about classes in between.
*
* @return the declaring TypeX object, or null.
*/
public ResolvedTypeX getDeclaringType() {
if (isArray()) return null;
String name = getName();
int lastDollar = name.lastIndexOf('$');
while (lastDollar != -1) {
ResolvedTypeX ret = world.resolve(TypeX.forName(name.substring(0, lastDollar)), true);
if (ret != ResolvedTypeX.MISSING) return ret;
lastDollar = name.lastIndexOf('$', lastDollar-1);
}
return null;
}
public static boolean isVisible(int modifiers, ResolvedTypeX targetType, ResolvedTypeX fromType) {
//System.err.println("mod: " + modifiers + ", " + targetType + " and " + fromType);
if (Modifier.isPublic(modifiers)) {
return true;
} else if (Modifier.isPrivate(modifiers)) {
return targetType.getOutermostType().equals(fromType.getOutermostType());
} else if (Modifier.isProtected(modifiers)) {
return samePackage(targetType, fromType) || targetType.isAssignableFrom(fromType);
} else { // package-visible
return samePackage(targetType, fromType);
}
}
private static boolean samePackage(
ResolvedTypeX targetType,
ResolvedTypeX fromType)
{
String p1 = targetType.getPackageName();
String p2 = fromType.getPackageName();
if (p1 == null) return p2 == null;
if (p2 == null) return false;
return p1.equals(p2);
}
public void addInterTypeMunger(ConcreteTypeMunger munger) {
ResolvedMember sig = munger.getSignature();
if (sig == null || munger.getMunger() == null ||
munger.getMunger().getKind() == ResolvedTypeMunger.PrivilegedAccess)
{
interTypeMungers.add(munger);
return;
}
//System.err.println("add: " + munger + " to " + this.getClassName() + " with " + interTypeMungers);
if (sig.getKind() == Member.METHOD) {
if (!compareToExistingMembers(munger, getMethods())) return;
if (this.isInterface()) {
if (!compareToExistingMembers(munger,
Arrays.asList(world.getCoreType(OBJECT).getDeclaredMethods()).iterator())) return;
}
} else if (sig.getKind() == Member.FIELD) {
if (!compareToExistingMembers(munger, Arrays.asList(getDeclaredFields()).iterator())) return;
} else {
if (!compareToExistingMembers(munger, Arrays.asList(getDeclaredMethods()).iterator())) return;
}
// now compare to existingMungers
for (Iterator i = interTypeMungers.iterator(); i.hasNext(); ) {
ConcreteTypeMunger existingMunger = (ConcreteTypeMunger)i.next();
if (conflictingSignature(existingMunger.getSignature(), munger.getSignature())) {
//System.err.println("match " + munger + " with " + existingMunger);
if (isVisible(munger.getSignature().getModifiers(),
munger.getAspectType(), existingMunger.getAspectType()))
{
//System.err.println(" is visible");
int c = compareMemberPrecedence(sig, existingMunger.getSignature());
if (c == 0) {
c = getWorld().comparePrecedence(munger.getAspectType(), existingMunger.getAspectType());
}
//System.err.println(" compare: " + c);
if (c < 0) {
// the existing munger dominates the new munger
checkLegalOverride(munger.getSignature(), existingMunger.getSignature());
return;
} else if (c > 0) {
// the new munger dominates the existing one
checkLegalOverride(existingMunger.getSignature(), munger.getSignature());
i.remove();
break;
} else {
interTypeConflictError(munger, existingMunger);
interTypeConflictError(existingMunger, munger);
return;
}
}
}
}
//System.err.println("adding: " + munger + " to " + this);
interTypeMungers.add(munger);
}
//??? returning too soon
private boolean compareToExistingMembers(ConcreteTypeMunger munger, Iterator existingMembers) {
ResolvedMember sig = munger.getSignature();
while (existingMembers.hasNext()) {
ResolvedMember existingMember = (ResolvedMember)existingMembers.next();
//System.err.println("Comparing munger: "+sig+" with member "+existingMember);
if (conflictingSignature(existingMember, munger.getSignature())) {
//System.err.println("conflict: existingMember=" + existingMember + " typeMunger=" + munger);
//System.err.println(munger.getSourceLocation() + ", " + munger.getSignature() + ", " + munger.getSignature().getSourceLocation());
if (isVisible(existingMember.getModifiers(), this, munger.getAspectType())) {
int c = compareMemberPrecedence(sig, existingMember);
//System.err.println(" c: " + c);
if (c < 0) {
// existingMember dominates munger
checkLegalOverride(munger.getSignature(), existingMember);
return false;
} else if (c > 0) {
// munger dominates existingMember
checkLegalOverride(existingMember, munger.getSignature());
//interTypeMungers.add(munger);
//??? might need list of these overridden abstracts
continue;
} else {
//XXX dual errors possible if (this instanceof BcelObjectType) return false; //XXX ignores separate comp
getWorld().getMessageHandler().handleMessage(
MessageUtil.error(WeaverMessages.format(WeaverMessages.ITD_MEMBER_CONFLICT,munger.getAspectType().getName(),
existingMember),
munger.getSourceLocation())
);
}
} else if (isDuplicateMemberWithinTargetType(existingMember,this,sig)) {
getWorld().getMessageHandler().handleMessage(
MessageUtil.error(WeaverMessages.format(WeaverMessages.ITD_MEMBER_CONFLICT,munger.getAspectType().getName(),
existingMember),
munger.getSourceLocation())
);;
}
//return;
}
}
return true;
}
// we know that the member signature matches, but that the member in the target type is not visible to the aspect.
// this may still be disallowed if it would result in two members within the same declaring type with the same
// signature AND more than one of them is concrete AND they are both visible within the target type.
private boolean isDuplicateMemberWithinTargetType(ResolvedMember existingMember, ResolvedTypeX targetType,ResolvedMember itdMember) {
if ( (existingMember.isAbstract() || itdMember.isAbstract())) return false;
TypeX declaringType = existingMember.getDeclaringType();
if (!targetType.equals(declaringType)) return false;
// now have to test that itdMember is visible from targetType
if (itdMember.isPrivate()) return false;
if (itdMember.isPublic()) return true;
// must be in same package to be visible then...
if (!targetType.getPackageName().equals(itdMember.getDeclaringType().getPackageName())) return false;
// trying to put two members with the same signature into the exact same type..., and both visible in that type.
return true;
}
public boolean checkLegalOverride(ResolvedMember parent, ResolvedMember child) {
//System.err.println("check: " + child.getDeclaringType() + " overrides " + parent.getDeclaringType());
if (!parent.getReturnType().equals(child.getReturnType())) {
world.showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.ITD_RETURN_TYPE_MISMATCH,parent,child),
child.getSourceLocation(), parent.getSourceLocation());
return false;
}
if (parent.getKind() == Member.POINTCUT) {
TypeX[] pTypes = parent.getParameterTypes();
TypeX[] cTypes = child.getParameterTypes();
if (!Arrays.equals(pTypes, cTypes)) {
world.showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.ITD_PARAM_TYPE_MISMATCH,parent,child),
child.getSourceLocation(), parent.getSourceLocation());
return false;
}
}
//System.err.println("check: " + child.getModifiers() + " more visible " + parent.getModifiers());
if (isMoreVisible(parent.getModifiers(), child.getModifiers())) {
world.showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.ITD_VISIBILITY_REDUCTION,parent,child),
child.getSourceLocation(), parent.getSourceLocation());
return false;
}
// check declared exceptions
ResolvedTypeX[] childExceptions = world.resolve(child.getExceptions());
ResolvedTypeX[] parentExceptions = world.resolve(parent.getExceptions());
ResolvedTypeX runtimeException = world.resolve("java.lang.RuntimeException");
ResolvedTypeX error = world.resolve("java.lang.Error");
outer: for (int i=0, leni = childExceptions.length; i < leni; i++) {
//System.err.println("checking: " + childExceptions[i]);
if (runtimeException.isAssignableFrom(childExceptions[i])) continue;
if (error.isAssignableFrom(childExceptions[i])) continue;
for (int j = 0, lenj = parentExceptions.length; j < lenj; j++) {
if (parentExceptions[j].isAssignableFrom(childExceptions[i])) continue outer;
}
world.showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.ITD_DOESNT_THROW,childExceptions[i].getName()),
child.getSourceLocation(), null);
return false;
}
if (parent.isStatic() && !child.isStatic()) {
world.showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.ITD_OVERRIDDEN_STATIC,child,parent),
child.getSourceLocation(),null);
} else if (child.isStatic() && !parent.isStatic()) {
world.showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.ITD_OVERIDDING_STATIC,child,parent),
child.getSourceLocation(),null);
}
return true;
}
private int compareMemberPrecedence(ResolvedMember m1, ResolvedMember m2) {
//if (!m1.getReturnType().equals(m2.getReturnType())) return 0;
if (Modifier.isAbstract(m1.getModifiers())) return -1;
if (Modifier.isAbstract(m2.getModifiers())) return +1;
if (m1.getDeclaringType().equals(m2.getDeclaringType())) return 0;
ResolvedTypeX t1 = m1.getDeclaringType().resolve(world);
ResolvedTypeX t2 = m2.getDeclaringType().resolve(world);
if (t1.isAssignableFrom(t2)) {
return -1;
}
if (t2.isAssignableFrom(t1)) {
return +1;
}
return 0;
}
public static boolean isMoreVisible(int m1, int m2) {
if (Modifier.isPrivate(m1)) return false;
if (isPackage(m1)) return Modifier.isPrivate(m2);
if (Modifier.isProtected(m1)) return /* private package */ (Modifier.isPrivate(m2) || isPackage(m2));
if (Modifier.isPublic(m1)) return /* private package protected */ ! Modifier.isPublic(m2);
throw new RuntimeException("bad modifier: " + m1);
}
private static boolean isPackage(int i) {
return (0 == (i & (Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED)));
}
private void interTypeConflictError(
ConcreteTypeMunger m1,
ConcreteTypeMunger m2)
{
//XXX this works only if we ignore separate compilation issues
//XXX dual errors possible if (this instanceof BcelObjectType) return;
//System.err.println("conflict at " + m2.getSourceLocation());
getWorld().showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.ITD_CONFLICT,m1.getAspectType().getName(),
m2.getSignature(),m2.getAspectType().getName()),
m2.getSourceLocation(), getSourceLocation());
}
public ResolvedMember lookupSyntheticMember(Member member) {
//??? horribly inefficient
//for (Iterator i =
//System.err.println("lookup " + member + " in " + interTypeMungers);
for (Iterator i = interTypeMungers.iterator(); i.hasNext(); ) {
ConcreteTypeMunger m = (ConcreteTypeMunger)i.next();
ResolvedMember ret = m.getMatchingSyntheticMember(member);
if (ret != null) {
//System.err.println(" found: " + ret);
return ret;
}
}
return null;
}
public void clearInterTypeMungers() {
interTypeMungers = new ArrayList();
}
public boolean isTopmostImplementor(ResolvedTypeX interfaceType) {
if (isInterface()) return false;
if (!interfaceType.isAssignableFrom(this)) return false;
// check that I'm truly the topmost implementor
if (interfaceType.isAssignableFrom(this.getSuperclass())) {
return false;
}
return true;
}
public ResolvedTypeX getTopmostImplementor(ResolvedTypeX interfaceType) {
if (isInterface()) return null;
if (!interfaceType.isAssignableFrom(this)) return null;
// Check if my super class is an implementor?
ResolvedTypeX higherType = this.getSuperclass().getTopmostImplementor(interfaceType);
if (higherType!=null) return higherType;
return this;
}
private ResolvedTypeX findHigher(ResolvedTypeX other) {
if (this == other) return this;
for(Iterator i = other.getDirectSupertypes(); i.hasNext(); ) {
ResolvedTypeX rtx = (ResolvedTypeX)i.next();
boolean b = this.isAssignableFrom(rtx);
if (b) return rtx;
}
return null;
}
public List getExposedPointcuts() {
List ret = new ArrayList();
if (getSuperclass() != null) ret.addAll(getSuperclass().getExposedPointcuts());
for (Iterator i = Arrays.asList(getDeclaredInterfaces()).iterator(); i.hasNext(); ) {
ResolvedTypeX t = (ResolvedTypeX)i.next();
addPointcutsResolvingConflicts(ret, Arrays.asList(t.getDeclaredPointcuts()), false);
}
addPointcutsResolvingConflicts(ret, Arrays.asList(getDeclaredPointcuts()), true);
for (Iterator i = ret.iterator(); i.hasNext(); ) {
ResolvedPointcutDefinition inherited = (ResolvedPointcutDefinition)i.next();
// System.err.println("looking at: " + inherited + " in " + this);
// System.err.println(" " + inherited.isAbstract() + " in " + this.isAbstract());
if (inherited.isAbstract()) {
if (!this.isAbstract()) {
getWorld().showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.POINCUT_NOT_CONCRETE,inherited,this.getName()),
inherited.getSourceLocation(), this.getSourceLocation());
}
}
}
return ret;
}
private void addPointcutsResolvingConflicts(List acc, List added, boolean isOverriding) {
for (Iterator i = added.iterator(); i.hasNext();) {
ResolvedPointcutDefinition toAdd =
(ResolvedPointcutDefinition) i.next();
//System.err.println("adding: " + toAdd);
for (Iterator j = acc.iterator(); j.hasNext();) {
ResolvedPointcutDefinition existing =
(ResolvedPointcutDefinition) j.next();
if (existing == toAdd) continue;
if (!isVisible(existing.getModifiers(),
existing.getDeclaringType().resolve(getWorld()),
this)) {
continue;
}
if (conflictingSignature(existing, toAdd)) {
if (isOverriding) {
checkLegalOverride(existing, toAdd);
j.remove();
} else {
getWorld().showMessage(
IMessage.ERROR,
WeaverMessages.format(WeaverMessages.CONFLICTING_INHERITED_POINTCUTS,this.getName() + toAdd.getSignature()),
existing.getSourceLocation(),
toAdd.getSourceLocation());
j.remove();
}
}
}
acc.add(toAdd);
}
}
public ISourceLocation getSourceLocation() { return null; }
public boolean isExposedToWeaver() { return false; }
public WeaverStateInfo getWeaverState() {
return null;
}
}
|
72,528
|
Bug 72528 around advice throws java.lang.VerifyError at runtime
|
I have an aspect that captures around() a pcd and returns an Object[], though the actual methods being instrumented might return any valid POJO array, i understand that AspectJ will take care of casting at assignment. I expected the following code to work properly, but at runtime i get a java.lang.VerifyError as shown below: F:\wd\Hello>ajbrowser HelloWorld.lst java.lang.VerifyError: (class: de/rohith/PrinterWorld, method: returnArrayWithCl oning signature: ()[Ljava/lang/Integer;) Incompatible argument to function at de.rohith.HelloWorld.main(HelloWorld.java:18) Exception in thread "main" I suspect the compiler fails to notice the return types of the methods being caught at compile time. I have tested this code with both ajbrowser as well as AJDT, both result in the same error output. -----------HelloWorldAspect.java--------------- package de.rohith; import java.lang.Object; public aspect HelloWorldAspect { private int callDepth = -1; public HelloWorldAspect() { } pointcut hello(): !within(HelloWorldAspect); pointcut method(): execution(public (*[]) de..*(..)); pointcut cloning(): call(* java.lang.Object.clone()); declare warning: method() && hello(): "*[] returning method called" ; Object[] around(): cflow(method()) && cloning() && hello() { print("", thisEnclosingJoinPointStaticPart); Object[] ret = proceed(); return (Object[])ret.clone(); } private void print(String prefix, Object message) { for (int i = 0, spaces = callDepth * 2; i < spaces; i++) { System.out.print(" "); } System.out.println(prefix + message); } } -----------PrinterWorld.java------------ package de.rohith; public class PrinterWorld { private Integer[] intArray = new Integer[2]; public PrinterWorld() { } public void print() { System.out.println("Hello World!"); } public Integer returnInt() { return new Integer(3); } public Integer[] returnArrayWithCloning() { for (int i = 0; i < intArray.length; i++) { intArray[i] = new Integer(i++); } return (Integer[])intArray.clone(); } public Integer[] returnArrayWithoutCloning() { return intArray; } } -----------HelloWorld.java------------ package de.rohith; public class HelloWorld { public static void main(String[] args) { PrinterWorld p = new PrinterWorld(); p.print(); Integer i = p.returnInt(); Integer[] intArray = p.returnArrayWithCloning(); Integer[] array2 = p.returnArrayWithoutCloning(); } }
|
resolved fixed
|
27d204c
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-03T13:45:46Z
| 2004-08-24T17:53:20Z
|
weaver/src/org/aspectj/weaver/bcel/BcelShadow.java
|
/* *******************************************************************
* 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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.bcel;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.aspectj.apache.bcel.Constants;
import org.aspectj.apache.bcel.classfile.Field;
import org.aspectj.apache.bcel.generic.ACONST_NULL;
import org.aspectj.apache.bcel.generic.ArrayType;
import org.aspectj.apache.bcel.generic.BranchInstruction;
import org.aspectj.apache.bcel.generic.ConstantPoolGen;
import org.aspectj.apache.bcel.generic.DUP;
import org.aspectj.apache.bcel.generic.DUP_X1;
import org.aspectj.apache.bcel.generic.FieldInstruction;
import org.aspectj.apache.bcel.generic.INVOKESPECIAL;
import org.aspectj.apache.bcel.generic.INVOKESTATIC;
import org.aspectj.apache.bcel.generic.Instruction;
import org.aspectj.apache.bcel.generic.InstructionConstants;
import org.aspectj.apache.bcel.generic.InstructionFactory;
import org.aspectj.apache.bcel.generic.InstructionHandle;
import org.aspectj.apache.bcel.generic.InstructionList;
import org.aspectj.apache.bcel.generic.InstructionTargeter;
import org.aspectj.apache.bcel.generic.InvokeInstruction;
import org.aspectj.apache.bcel.generic.NEW;
import org.aspectj.apache.bcel.generic.ObjectType;
import org.aspectj.apache.bcel.generic.ReturnInstruction;
import org.aspectj.apache.bcel.generic.SWAP;
import org.aspectj.apache.bcel.generic.StoreInstruction;
import org.aspectj.apache.bcel.generic.TargetLostException;
import org.aspectj.apache.bcel.generic.Type;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.Message;
import org.aspectj.weaver.Advice;
import org.aspectj.weaver.AdviceKind;
import org.aspectj.weaver.AjcMemberMaker;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.IntMap;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.NameMangler;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedTypeX;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.ShadowMunger;
import org.aspectj.weaver.TypeX;
import org.aspectj.weaver.WeaverMessages;
import org.aspectj.weaver.World;
import org.aspectj.weaver.ast.Var;
/*
* Some fun implementation stuff:
*
* * expressionKind advice is non-execution advice
* * may have a target.
* * if the body is extracted, it will be extracted into
* a static method. The first argument to the static
* method is the target
* * advice may expose a this object, but that's the advice's
* consideration, not ours. This object will NOT be cached in another
* local, but will always come from frame zero.
*
* * non-expressionKind advice is execution advice
* * may have a this.
* * target is same as this, and is exposed that way to advice
* (i.e., target will not be cached, will always come from frame zero)
* * if the body is extracted, it will be extracted into a method
* with same static/dynamic modifier as enclosing method. If non-static,
* target of callback call will be this.
*
* * because of these two facts, the setup of the actual arguments (including
* possible target) callback method is the same for both kinds of advice:
* push the targetVar, if it exists (it will not exist for advice on static
* things), then push all the argVars.
*
* Protected things:
*
* * the above is sufficient for non-expressionKind advice for protected things,
* since the target will always be this.
*
* * For expressionKind things, we have to modify the signature of the callback
* method slightly. For non-static expressionKind things, we modify
* the first argument of the callback method NOT to be the type specified
* by the method/field signature (the owner), but rather we type it to
* the currentlyEnclosing type. We are guaranteed this will be fine,
* since the verifier verifies that the target is a subtype of the currently
* enclosingType.
*
* Worries:
*
* * ConstructorCalls will be weirder than all of these, since they
* supposedly don't have a target (according to AspectJ), but they clearly
* do have a target of sorts, just one that needs to be pushed on the stack,
* dupped, and not touched otherwise until the constructor runs.
*
* @author Jim Hugunin
* @author Erik Hilsdale
*
*/
public class BcelShadow extends Shadow {
private ShadowRange range;
private final BcelWorld world;
private final LazyMethodGen enclosingMethod;
private boolean fallsThrough; //XXX not used anymore
// ---- initialization
/**
* This generates an unassociated shadow, rooted in a particular method but not rooted
* to any particular point in the code. It should be given to a rooted ShadowRange
* in the {@link ShadowRange#associateWithShadow(BcelShadow)} method.
*/
public BcelShadow(
BcelWorld world,
Kind kind,
Member signature,
LazyMethodGen enclosingMethod,
BcelShadow enclosingShadow)
{
super(kind, signature, enclosingShadow);
this.world = world;
this.enclosingMethod = enclosingMethod;
fallsThrough = kind.argsOnStack();
}
// ---- copies all state, including Shadow's mungers...
public BcelShadow copyInto(LazyMethodGen recipient, BcelShadow enclosing) {
BcelShadow s = new BcelShadow(world, getKind(), getSignature(), recipient, enclosing);
List src = mungers;
List dest = s.mungers;
for (Iterator i = src.iterator(); i.hasNext(); ) {
dest.add(i.next());
}
return s;
}
// ---- overridden behaviour
public World getIWorld() {
return world;
}
private void deleteNewAndDup() {
final ConstantPoolGen cpg = getEnclosingClass().getConstantPoolGen();
int depth = 1;
InstructionHandle ih = range.getStart();
while (true) {
Instruction inst = ih.getInstruction();
if (inst instanceof INVOKESPECIAL
&& ((INVOKESPECIAL) inst).getName(cpg).equals("<init>")) {
depth++;
} else if (inst instanceof NEW) {
depth--;
if (depth == 0) break;
}
ih = ih.getPrev();
}
// now IH points to the NEW. We're followed by the DUP, and that is followed
// by the actual instruciton we care about.
InstructionHandle newHandle = ih;
InstructionHandle endHandle = newHandle.getNext();
InstructionHandle nextHandle;
if (endHandle.getInstruction() instanceof DUP) {
nextHandle = endHandle.getNext();
retargetFrom(newHandle, nextHandle);
retargetFrom(endHandle, nextHandle);
} else if (endHandle.getInstruction() instanceof DUP_X1) {
InstructionHandle dupHandle = endHandle;
endHandle = endHandle.getNext();
nextHandle = endHandle.getNext();
if (endHandle.getInstruction() instanceof SWAP) {}
else {
// XXX see next XXX comment
throw new RuntimeException("Unhandled kind of new " + endHandle);
}
retargetFrom(newHandle, nextHandle);
retargetFrom(dupHandle, nextHandle);
retargetFrom(endHandle, nextHandle);
} else {
endHandle = newHandle;
nextHandle = endHandle.getNext();
retargetFrom(newHandle, nextHandle);
// add a POP here... we found a NEW w/o a dup or anything else, so
// we must be in statement context.
getRange().insert(InstructionConstants.POP, Range.OutsideAfter);
}
// assert (dupHandle.getInstruction() instanceof DUP);
try {
range.getBody().delete(newHandle, endHandle);
} catch (TargetLostException e) {
throw new BCException("shouldn't happen");
}
}
private void retargetFrom(InstructionHandle old, InstructionHandle fresh) {
InstructionTargeter[] sources = old.getTargeters();
if (sources != null) {
for (int i = sources.length - 1; i >= 0; i--) {
sources[i].updateTarget(old, fresh);
}
}
}
protected void prepareForMungers() {
// if we're a constructor call, we need to remove the new:dup or the new:dup_x1:swap,
// and store all our
// arguments on the frame.
// ??? This is a bit of a hack (for the Java langauge). We do this because
// we sometime add code "outsideBefore" when dealing with weaving join points. We only
// do this for exposing state that is on the stack. It turns out to just work for
// everything except for constructor calls and exception handlers. If we were to clean
// this up, every ShadowRange would have three instructionHandle points, the start of
// the arg-setup code, the start of the running code, and the end of the running code.
if (getKind() == ConstructorCall) {
deleteNewAndDup();
initializeArgVars();
} else if (getKind() == ExceptionHandler) {
ShadowRange range = getRange();
InstructionList body = range.getBody();
InstructionHandle start = range.getStart();
// Create a store instruction to put the value from the top of the
// stack into a local variable slot. This is a trimmed version of
// what is in initializeArgVars() (since there is only one argument
// at a handler jp and only before advice is supported) (pr46298)
argVars = new BcelVar[1];
int positionOffset = (hasTarget() ? 1 : 0) + ((hasThis() && !getKind().isTargetSameAsThis()) ? 1 : 0);
TypeX tx = getArgType(0);
argVars[0] = genTempVar(tx, "ajc$arg0");
InstructionHandle insertedInstruction =
range.insert(argVars[0].createStore(getFactory()), Range.OutsideBefore);
// Now the exception range starts just after our new instruction.
// The next bit of code changes the exception range to point at
// the store instruction
InstructionTargeter[] targeters = start.getTargeters();
for (int i = 0; i < targeters.length; i++) {
InstructionTargeter t = targeters[i];
if (t instanceof ExceptionRange) {
ExceptionRange er = (ExceptionRange) t;
er.updateTarget(start, insertedInstruction, body);
}
}
}
// now we ask each munger to request our state
isThisJoinPointLazy = world.isXlazyTjp();
for (Iterator iter = mungers.iterator(); iter.hasNext();) {
ShadowMunger munger = (ShadowMunger) iter.next();
munger.specializeOn(this);
}
initializeThisJoinPoint();
// If we are an expression kind, we require our target/arguments on the stack
// before we do our actual thing. However, they may have been removed
// from the stack as the shadowMungers have requested state.
// if any of our shadowMungers requested either the arguments or target,
// the munger will have added code
// to pop the target/arguments into temporary variables, represented by
// targetVar and argVars. In such a case, we must make sure to re-push the
// values.
// If we are nonExpressionKind, we don't expect arguments on the stack
// so this is moot. If our argVars happen to be null, then we know that
// no ShadowMunger has squirrelled away our arguments, so they're still
// on the stack.
InstructionFactory fact = getFactory();
if (getKind().argsOnStack() && argVars != null) {
// Special case first (pr46298). If we are an exception handler and the instruction
// just after the shadow is a POP then we should remove the pop. The code
// above which generated the store instruction has already cleared the stack.
// We also don't generate any code for the arguments in this case as it would be
// an incorrect aload.
if (getKind() == ExceptionHandler
&& range.getEnd().getNext().getInstruction().equals(InstructionConstants.POP)) {
// easier than deleting it ...
range.getEnd().getNext().setInstruction(InstructionConstants.NOP);
} else {
range.insert(
BcelRenderer.renderExprs(fact, world, argVars),
Range.InsideBefore);
if (targetVar != null) {
range.insert(
BcelRenderer.renderExpr(fact, world, targetVar),
Range.InsideBefore);
}
if (getKind() == ConstructorCall) {
range.insert((Instruction) InstructionFactory.createDup(1), Range.InsideBefore);
range.insert(
fact.createNew(
(ObjectType) BcelWorld.makeBcelType(
getSignature().getDeclaringType())),
Range.InsideBefore);
}
}
}
}
// ---- getters
public ShadowRange getRange() {
return range;
}
public void setRange(ShadowRange range) {
this.range = range;
}
public int getSourceLine() {
// if the kind of join point for which we are a shadow represents
// a method or constructor execution, then the best source line is
// the one from the enclosingMethod declarationLineNumber if available.
Kind kind = getKind();
if ( (kind == MethodExecution) ||
(kind == ConstructorExecution) ||
(kind == AdviceExecution) ||
(kind == StaticInitialization) ||
(kind == PreInitialization) ||
(kind == Initialization)) {
if (getEnclosingMethod().hasDeclaredLineNumberInfo()) {
return getEnclosingMethod().getDeclarationLineNumber();
}
}
if (range == null) {
if (getEnclosingMethod().hasBody()) {
return Utility.getSourceLine(getEnclosingMethod().getBody().getStart());
} else {
return 0;
}
}
int ret = Utility.getSourceLine(range.getStart());
if (ret < 0) return 0;
return ret;
}
// overrides
public TypeX getEnclosingType() {
return getEnclosingClass().getType();
}
public LazyClassGen getEnclosingClass() {
return enclosingMethod.getEnclosingClass();
}
public BcelWorld getWorld() {
return world;
}
// ---- factory methods
public static BcelShadow makeConstructorExecution(
BcelWorld world,
LazyMethodGen enclosingMethod,
InstructionHandle justBeforeStart)
{
final InstructionList body = enclosingMethod.getBody();
BcelShadow s =
new BcelShadow(
world,
ConstructorExecution,
world.makeMethodSignature(enclosingMethod),
enclosingMethod,
null);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, justBeforeStart.getNext()),
Range.genEnd(body));
return s;
}
public static BcelShadow makeStaticInitialization(
BcelWorld world,
LazyMethodGen enclosingMethod)
{
InstructionList body = enclosingMethod.getBody();
// move the start past ajc$preClinit
InstructionHandle clinitStart = body.getStart();
if (clinitStart.getInstruction() instanceof InvokeInstruction) {
InvokeInstruction ii = (InvokeInstruction)clinitStart.getInstruction();
if (ii
.getName(enclosingMethod.getEnclosingClass().getConstantPoolGen())
.equals(NameMangler.AJC_PRE_CLINIT_NAME)) {
clinitStart = clinitStart.getNext();
}
}
InstructionHandle clinitEnd = body.getEnd();
//XXX should move the end before the postClinit, but the return is then tricky...
// if (clinitEnd.getInstruction() instanceof InvokeInstruction) {
// InvokeInstruction ii = (InvokeInstruction)clinitEnd.getInstruction();
// if (ii.getName(enclosingMethod.getEnclosingClass().getConstantPoolGen()).equals(NameMangler.AJC_POST_CLINIT_NAME)) {
// clinitEnd = clinitEnd.getPrev();
// }
// }
BcelShadow s =
new BcelShadow(
world,
StaticInitialization,
world.makeMethodSignature(enclosingMethod),
enclosingMethod,
null);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, clinitStart),
Range.genEnd(body, clinitEnd));
return s;
}
/** Make the shadow for an exception handler. Currently makes an empty shadow that
* only allows before advice to be woven into it.
*/
public static BcelShadow makeExceptionHandler(
BcelWorld world,
ExceptionRange exceptionRange,
LazyMethodGen enclosingMethod,
InstructionHandle startOfHandler,
BcelShadow enclosingShadow)
{
InstructionList body = enclosingMethod.getBody();
TypeX catchType = exceptionRange.getCatchType();
TypeX inType = enclosingMethod.getEnclosingClass().getType();
ResolvedMember sig = Member.makeExceptionHandlerSignature(inType, catchType);
sig.parameterNames = new String[] {findHandlerParamName(startOfHandler)};
BcelShadow s =
new BcelShadow(
world,
ExceptionHandler,
sig,
enclosingMethod,
enclosingShadow);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
InstructionHandle start = Range.genStart(body, startOfHandler);
InstructionHandle end = Range.genEnd(body, start);
r.associateWithTargets(start, end);
exceptionRange.updateTarget(startOfHandler, start, body);
return s;
}
private static String findHandlerParamName(InstructionHandle startOfHandler) {
if (startOfHandler.getInstruction() instanceof StoreInstruction &&
startOfHandler.getNext() != null)
{
int slot = ((StoreInstruction)startOfHandler.getInstruction()).getIndex();
//System.out.println("got store: " + startOfHandler.getInstruction() + ", " + index);
InstructionTargeter[] targeters = startOfHandler.getNext().getTargeters();
if (targeters!=null) {
for (int i=targeters.length-1; i >= 0; i--) {
if (targeters[i] instanceof LocalVariableTag) {
LocalVariableTag t = (LocalVariableTag)targeters[i];
if (t.getSlot() == slot) {
return t.getName();
}
//System.out.println("tag: " + targeters[i]);
}
}
}
}
return "<missing>";
}
/** create an init join point associated w/ an interface in the body of a constructor */
public static BcelShadow makeIfaceInitialization(
BcelWorld world,
LazyMethodGen constructor,
Member interfaceConstructorSignature)
{
InstructionList body = constructor.getBody();
// TypeX inType = constructor.getEnclosingClass().getType();
BcelShadow s =
new BcelShadow(
world,
Initialization,
interfaceConstructorSignature,
constructor,
null);
s.fallsThrough = true;
// ShadowRange r = new ShadowRange(body);
// r.associateWithShadow(s);
// InstructionHandle start = Range.genStart(body, handle);
// InstructionHandle end = Range.genEnd(body, handle);
//
// r.associateWithTargets(start, end);
return s;
}
public void initIfaceInitializer(InstructionHandle end) {
final InstructionList body = enclosingMethod.getBody();
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(this);
InstructionHandle nop = body.insert(end, InstructionConstants.NOP);
r.associateWithTargets(
Range.genStart(body, nop),
Range.genEnd(body, nop));
}
// public static BcelShadow makeIfaceConstructorExecution(
// BcelWorld world,
// LazyMethodGen constructor,
// InstructionHandle next,
// Member interfaceConstructorSignature)
// {
// // final InstructionFactory fact = constructor.getEnclosingClass().getFactory();
// InstructionList body = constructor.getBody();
// // TypeX inType = constructor.getEnclosingClass().getType();
// BcelShadow s =
// new BcelShadow(
// world,
// ConstructorExecution,
// interfaceConstructorSignature,
// constructor,
// null);
// s.fallsThrough = true;
// ShadowRange r = new ShadowRange(body);
// r.associateWithShadow(s);
// // ??? this may or may not work
// InstructionHandle start = Range.genStart(body, next);
// //InstructionHandle end = Range.genEnd(body, body.append(start, fact.NOP));
// InstructionHandle end = Range.genStart(body, next);
// //body.append(start, fact.NOP);
//
// r.associateWithTargets(start, end);
// return s;
// }
/** Create an initialization join point associated with a constructor, but not
* with any body of code yet. If this is actually matched, it's range will be set
* when we inline self constructors.
*
* @param constructor The constructor starting this initialization.
*/
public static BcelShadow makeUnfinishedInitialization(
BcelWorld world,
LazyMethodGen constructor)
{
return new BcelShadow(
world,
Initialization,
world.makeMethodSignature(constructor),
constructor,
null);
}
public static BcelShadow makeUnfinishedPreinitialization(
BcelWorld world,
LazyMethodGen constructor)
{
BcelShadow ret = new BcelShadow(
world,
PreInitialization,
world.makeMethodSignature(constructor),
constructor,
null);
ret.fallsThrough = true;
return ret;
}
public static BcelShadow makeMethodExecution(
BcelWorld world,
LazyMethodGen enclosingMethod,
boolean lazyInit)
{
if (!lazyInit) return makeMethodExecution(world, enclosingMethod);
BcelShadow s =
new BcelShadow(
world,
MethodExecution,
enclosingMethod.getMemberView(),
enclosingMethod,
null);
return s;
}
public void init() {
if (range != null) return;
final InstructionList body = enclosingMethod.getBody();
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(this);
r.associateWithTargets(
Range.genStart(body),
Range.genEnd(body));
}
public static BcelShadow makeMethodExecution(
BcelWorld world,
LazyMethodGen enclosingMethod)
{
return makeShadowForMethod(world, enclosingMethod, MethodExecution,
enclosingMethod.getMemberView()); //world.makeMethodSignature(enclosingMethod));
}
public static BcelShadow makeShadowForMethod(BcelWorld world,
LazyMethodGen enclosingMethod, Shadow.Kind kind, Member sig)
{
final InstructionList body = enclosingMethod.getBody();
BcelShadow s =
new BcelShadow(
world,
kind,
sig,
enclosingMethod,
null);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body),
Range.genEnd(body));
return s;
}
public static BcelShadow makeAdviceExecution(
BcelWorld world,
LazyMethodGen enclosingMethod)
{
final InstructionList body = enclosingMethod.getBody();
BcelShadow s =
new BcelShadow(
world,
AdviceExecution,
world.makeMethodSignature(enclosingMethod, Member.ADVICE),
enclosingMethod,
null);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(Range.genStart(body), Range.genEnd(body));
return s;
}
// constructor call shadows are <em>initially</em> just around the
// call to the constructor. If ANY advice gets put on it, we move
// the NEW instruction inside the join point, which involves putting
// all the arguments in temps.
public static BcelShadow makeConstructorCall(
BcelWorld world,
LazyMethodGen enclosingMethod,
InstructionHandle callHandle,
BcelShadow enclosingShadow)
{
final InstructionList body = enclosingMethod.getBody();
Member sig = BcelWorld.makeMethodSignature(
enclosingMethod.getEnclosingClass(),
(InvokeInstruction) callHandle.getInstruction());
BcelShadow s =
new BcelShadow(
world,
ConstructorCall,
sig,
enclosingMethod,
enclosingShadow);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, callHandle),
Range.genEnd(body, callHandle));
retargetAllBranches(callHandle, r.getStart());
return s;
}
public static BcelShadow makeMethodCall(
BcelWorld world,
LazyMethodGen enclosingMethod,
InstructionHandle callHandle,
BcelShadow enclosingShadow)
{
final InstructionList body = enclosingMethod.getBody();
BcelShadow s =
new BcelShadow(
world,
MethodCall,
BcelWorld.makeMethodSignature(
enclosingMethod.getEnclosingClass(),
(InvokeInstruction) callHandle.getInstruction()),
enclosingMethod,
enclosingShadow);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, callHandle),
Range.genEnd(body, callHandle));
retargetAllBranches(callHandle, r.getStart());
return s;
}
public static BcelShadow makeShadowForMethodCall(
BcelWorld world,
LazyMethodGen enclosingMethod,
InstructionHandle callHandle,
BcelShadow enclosingShadow,
Kind kind,
ResolvedMember sig)
{
final InstructionList body = enclosingMethod.getBody();
BcelShadow s =
new BcelShadow(
world,
kind,
sig,
enclosingMethod,
enclosingShadow);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, callHandle),
Range.genEnd(body, callHandle));
retargetAllBranches(callHandle, r.getStart());
return s;
}
public static BcelShadow makeFieldGet(
BcelWorld world,
LazyMethodGen enclosingMethod,
InstructionHandle getHandle,
BcelShadow enclosingShadow)
{
final InstructionList body = enclosingMethod.getBody();
BcelShadow s =
new BcelShadow(
world,
FieldGet,
BcelWorld.makeFieldSignature(
enclosingMethod.getEnclosingClass(),
(FieldInstruction) getHandle.getInstruction()),
enclosingMethod,
enclosingShadow);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, getHandle),
Range.genEnd(body, getHandle));
retargetAllBranches(getHandle, r.getStart());
return s;
}
public static BcelShadow makeFieldSet(
BcelWorld world,
LazyMethodGen enclosingMethod,
InstructionHandle setHandle,
BcelShadow enclosingShadow)
{
final InstructionList body = enclosingMethod.getBody();
BcelShadow s =
new BcelShadow(
world,
FieldSet,
BcelWorld.makeFieldSignature(
enclosingMethod.getEnclosingClass(),
(FieldInstruction) setHandle.getInstruction()),
enclosingMethod,
enclosingShadow);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, setHandle),
Range.genEnd(body, setHandle));
retargetAllBranches(setHandle, r.getStart());
return s;
}
public static void retargetAllBranches(InstructionHandle from, InstructionHandle to) {
InstructionTargeter[] sources = from.getTargeters();
if (sources != null) {
for (int i = sources.length - 1; i >= 0; i--) {
InstructionTargeter source = sources[i];
if (source instanceof BranchInstruction) {
source.updateTarget(from, to);
}
}
}
}
// // ---- type access methods
// private ObjectType getTargetBcelType() {
// return (ObjectType) BcelWorld.makeBcelType(getTargetType());
// }
// private Type getArgBcelType(int arg) {
// return BcelWorld.makeBcelType(getArgType(arg));
// }
// ---- kinding
/**
* If the end of my range has no real instructions following then
* my context needs a return at the end.
*/
public boolean terminatesWithReturn() {
return getRange().getRealNext() == null;
}
/**
* Is arg0 occupied with the value of this
*/
public boolean arg0HoldsThis() {
if (getKind().isEnclosingKind()) {
return !getSignature().isStatic();
} else if (enclosingShadow == null) {
//XXX this is mostly right
// this doesn't do the right thing for calls in the pre part of introduced constructors.
return !enclosingMethod.isStatic();
} else {
return ((BcelShadow)enclosingShadow).arg0HoldsThis();
}
}
// ---- argument getting methods
private BcelVar thisVar = null;
private BcelVar targetVar = null;
private BcelVar[] argVars = null;
public Var getThisVar() {
if (!hasThis()) {
throw new IllegalStateException("no this");
}
initializeThisVar();
return thisVar;
}
public Var getTargetVar() {
if (!hasTarget()) {
throw new IllegalStateException("no target");
}
initializeTargetVar();
return targetVar;
}
public Var getArgVar(int i) {
initializeArgVars();
return argVars[i];
}
// reflective thisJoinPoint support
private BcelVar thisJoinPointVar = null;
private boolean isThisJoinPointLazy;
private int lazyTjpConsumers = 0;
private BcelVar thisJoinPointStaticPartVar = null;
// private BcelVar thisEnclosingJoinPointStaticPartVar = null;
public final Var getThisJoinPointStaticPartVar() {
return getThisJoinPointStaticPartBcelVar();
}
public final Var getThisEnclosingJoinPointStaticPartVar() {
return getThisEnclosingJoinPointStaticPartBcelVar();
}
public void requireThisJoinPoint(boolean hasGuardTest) {
if (!hasGuardTest) {
isThisJoinPointLazy = false;
} else {
lazyTjpConsumers++;
}
if (thisJoinPointVar == null) {
thisJoinPointVar = genTempVar(TypeX.forName("org.aspectj.lang.JoinPoint"));
}
}
public Var getThisJoinPointVar() {
requireThisJoinPoint(false);
return thisJoinPointVar;
}
void initializeThisJoinPoint() {
if (thisJoinPointVar == null) return;
if (isThisJoinPointLazy) {
isThisJoinPointLazy = checkLazyTjp();
}
if (isThisJoinPointLazy) {
createThisJoinPoint(); // make sure any state needed is initialized, but throw the instructions out
if (lazyTjpConsumers == 1) return; // special case only one lazyTjpUser
InstructionFactory fact = getFactory();
InstructionList il = new InstructionList();
il.append(InstructionConstants.ACONST_NULL);
il.append(thisJoinPointVar.createStore(fact));
range.insert(il, Range.OutsideBefore);
} else {
InstructionFactory fact = getFactory();
InstructionList il = createThisJoinPoint();
il.append(thisJoinPointVar.createStore(fact));
range.insert(il, Range.OutsideBefore);
}
}
private boolean checkLazyTjp() {
// check for around advice
for (Iterator i = mungers.iterator(); i.hasNext();) {
ShadowMunger munger = (ShadowMunger) i.next();
if (munger instanceof Advice) {
if ( ((Advice)munger).getKind() == AdviceKind.Around) {
world.getLint().canNotImplementLazyTjp.signal(
new String[] {toString()},
getSourceLocation(),
new ISourceLocation[] { munger.getSourceLocation() }
);
return false;
}
}
}
return true;
}
InstructionList loadThisJoinPoint() {
InstructionFactory fact = getFactory();
InstructionList il = new InstructionList();
if (isThisJoinPointLazy) {
il.append(createThisJoinPoint());
if (lazyTjpConsumers > 1) {
il.append(thisJoinPointVar.createStore(fact));
InstructionHandle end = il.append(thisJoinPointVar.createLoad(fact));
il.insert(InstructionFactory.createBranchInstruction(Constants.IFNONNULL, end));
il.insert(thisJoinPointVar.createLoad(fact));
}
} else {
thisJoinPointVar.appendLoad(il, fact);
}
return il;
}
InstructionList createThisJoinPoint() {
InstructionFactory fact = getFactory();
InstructionList il = new InstructionList();
BcelVar staticPart = getThisJoinPointStaticPartBcelVar();
staticPart.appendLoad(il, fact);
if (hasThis()) {
((BcelVar)getThisVar()).appendLoad(il, fact);
} else {
il.append(new ACONST_NULL());
}
if (hasTarget()) {
((BcelVar)getTargetVar()).appendLoad(il, fact);
} else {
il.append(new ACONST_NULL());
}
switch(getArgCount()) {
case 0:
il.append(fact.createInvoke("org.aspectj.runtime.reflect.Factory",
"makeJP", LazyClassGen.tjpType,
new Type[] { LazyClassGen.staticTjpType,
Type.OBJECT, Type.OBJECT},
Constants.INVOKESTATIC));
break;
case 1:
((BcelVar)getArgVar(0)).appendLoadAndConvert(il, fact, world.getCoreType(ResolvedTypeX.OBJECT));
il.append(fact.createInvoke("org.aspectj.runtime.reflect.Factory",
"makeJP", LazyClassGen.tjpType,
new Type[] { LazyClassGen.staticTjpType,
Type.OBJECT, Type.OBJECT, Type.OBJECT},
Constants.INVOKESTATIC));
break;
case 2:
((BcelVar)getArgVar(0)).appendLoadAndConvert(il, fact, world.getCoreType(ResolvedTypeX.OBJECT));
((BcelVar)getArgVar(1)).appendLoadAndConvert(il, fact, world.getCoreType(ResolvedTypeX.OBJECT));
il.append(fact.createInvoke("org.aspectj.runtime.reflect.Factory",
"makeJP", LazyClassGen.tjpType,
new Type[] { LazyClassGen.staticTjpType,
Type.OBJECT, Type.OBJECT, Type.OBJECT, Type.OBJECT},
Constants.INVOKESTATIC));
break;
default:
il.append(makeArgsObjectArray());
il.append(fact.createInvoke("org.aspectj.runtime.reflect.Factory",
"makeJP", LazyClassGen.tjpType,
new Type[] { LazyClassGen.staticTjpType,
Type.OBJECT, Type.OBJECT, new ArrayType(Type.OBJECT, 1)},
Constants.INVOKESTATIC));
break;
}
return il;
}
public BcelVar getThisJoinPointStaticPartBcelVar() {
if (thisJoinPointStaticPartVar == null) {
Field field = getEnclosingClass().getTjpField(this);
thisJoinPointStaticPartVar =
new BcelFieldRef(
world.getCoreType(TypeX.forName("org.aspectj.lang.JoinPoint$StaticPart")),
getEnclosingClass().getClassName(),
field.getName());
// getEnclosingClass().warnOnAddedStaticInitializer(this,munger.getSourceLocation());
}
return thisJoinPointStaticPartVar;
}
public BcelVar getThisEnclosingJoinPointStaticPartBcelVar() {
if (enclosingShadow == null) {
// the enclosing of an execution is itself
return getThisJoinPointStaticPartBcelVar();
} else {
return ((BcelShadow)enclosingShadow).getThisJoinPointStaticPartBcelVar();
}
}
//??? need to better understand all the enclosing variants
public Member getEnclosingCodeSignature() {
if (getKind().isEnclosingKind()) {
return getSignature();
} else if (getKind() == Shadow.PreInitialization) {
// PreInit doesn't enclose code but its signature
// is correctly the signature of the ctor.
return getSignature();
} else if (enclosingShadow == null) {
return getEnclosingMethod().getMemberView();
} else {
return enclosingShadow.getSignature();
}
}
private InstructionList makeArgsObjectArray() {
InstructionFactory fact = getFactory();
BcelVar arrayVar = genTempVar(TypeX.OBJECTARRAY);
final InstructionList il = new InstructionList();
int alen = getArgCount() ;
il.append(Utility.createConstant(fact, alen));
il.append((Instruction)fact.createNewArray(Type.OBJECT, (short)1));
arrayVar.appendStore(il, fact);
int stateIndex = 0;
for (int i = 0, len = getArgCount(); i<len; i++) {
arrayVar.appendConvertableArrayStore(il, fact, stateIndex, (BcelVar)getArgVar(i));
stateIndex++;
}
arrayVar.appendLoad(il, fact);
return il;
}
// ---- initializing var tables
/* initializing this is doesn't do anything, because this
* is protected from side-effects, so we don't need to copy its location
*/
private void initializeThisVar() {
if (thisVar != null) return;
thisVar = new BcelVar(getThisType().resolve(world), 0);
thisVar.setPositionInAroundState(0);
}
public void initializeTargetVar() {
InstructionFactory fact = getFactory();
if (targetVar != null) return;
if (getKind().isTargetSameAsThis()) {
if (hasThis()) initializeThisVar();
targetVar = thisVar;
} else {
initializeArgVars(); // gotta pop off the args before we find the target
TypeX type = getTargetType();
targetVar = genTempVar(type, "ajc$target");
range.insert(targetVar.createStore(fact), Range.OutsideBefore);
targetVar.setPositionInAroundState(hasThis() ? 1 : 0);
}
}
public void initializeArgVars() {
if (argVars != null) return;
InstructionFactory fact = getFactory();
int len = getArgCount();
argVars = new BcelVar[len];
int positionOffset = (hasTarget() ? 1 : 0) +
((hasThis() && !getKind().isTargetSameAsThis()) ? 1 : 0);
if (getKind().argsOnStack()) {
// we move backwards because we're popping off the stack
for (int i = len - 1; i >= 0; i--) {
TypeX type = getArgType(i);
BcelVar tmp = genTempVar(type, "ajc$arg" + i);
range.insert(tmp.createStore(getFactory()), Range.OutsideBefore);
int position = i;
position += positionOffset;
tmp.setPositionInAroundState(position);
argVars[i] = tmp;
}
} else {
int index = 0;
if (arg0HoldsThis()) index++;
for (int i = 0; i < len; i++) {
TypeX type = getArgType(i);
BcelVar tmp = genTempVar(type, "ajc$arg" + i);
range.insert(tmp.createCopyFrom(fact, index), Range.OutsideBefore);
argVars[i] = tmp;
int position = i;
position += positionOffset;
// System.out.println("set position: " + tmp + ", " + position + " in " + this);
// System.out.println(" hasThis: " + hasThis() + ", hasTarget: " + hasTarget());
tmp.setPositionInAroundState(position);
index += type.getSize();
}
}
}
public void initializeForAroundClosure() {
initializeArgVars();
if (hasTarget()) initializeTargetVar();
if (hasThis()) initializeThisVar();
// System.out.println("initialized: " + this + " thisVar = " + thisVar);
}
// ---- weave methods
void weaveBefore(BcelAdvice munger) {
range.insert(
munger.getAdviceInstructions(this, null, range.getRealStart()),
Range.InsideBefore);
}
public void weaveAfter(BcelAdvice munger) {
weaveAfterThrowing(munger, TypeX.THROWABLE);
weaveAfterReturning(munger);
}
/**
* We guarantee that the return value is on the top of the stack when
* munger.getAdviceInstructions() will be run
* (Unless we have a void return type in which case there's nothing)
*/
public void weaveAfterReturning(BcelAdvice munger) {
// InstructionFactory fact = getFactory();
List returns = new ArrayList();
Instruction ret = null;
for (InstructionHandle ih = range.getStart(); ih != range.getEnd(); ih = ih.getNext()) {
if (ih.getInstruction() instanceof ReturnInstruction) {
returns.add(ih);
ret = Utility.copyInstruction(ih.getInstruction());
}
}
InstructionList retList;
InstructionHandle afterAdvice;
if (ret != null) {
retList = new InstructionList(ret);
afterAdvice = retList.getStart();
} else /* if (munger.hasDynamicTests()) */ {
retList = new InstructionList(InstructionConstants.NOP);
afterAdvice = retList.getStart();
// } else {
// retList = new InstructionList();
// afterAdvice = null;
}
InstructionList advice = new InstructionList();
BcelVar tempVar = null;
if (munger.hasExtraParameter()) {
TypeX tempVarType = getReturnType();
if (tempVarType.equals(ResolvedTypeX.VOID)) {
tempVar = genTempVar(TypeX.OBJECT);
advice.append(InstructionConstants.ACONST_NULL);
tempVar.appendStore(advice, getFactory());
} else {
tempVar = genTempVar(tempVarType);
advice.append(InstructionFactory.createDup(tempVarType.getSize()));
tempVar.appendStore(advice, getFactory());
}
}
advice.append(munger.getAdviceInstructions(this, tempVar, afterAdvice));
if (ret != null) {
InstructionHandle gotoTarget = advice.getStart();
for (Iterator i = returns.iterator(); i.hasNext();) {
InstructionHandle ih = (InstructionHandle) i.next();
Utility.replaceInstruction(
ih,
InstructionFactory.createBranchInstruction(
Constants.GOTO,
gotoTarget),
enclosingMethod);
}
range.append(advice);
range.append(retList);
} else {
range.append(advice);
range.append(retList);
}
}
public void weaveAfterThrowing(BcelAdvice munger, TypeX catchType) {
// a good optimization would be not to generate anything here
// if the shadow is GUARANTEED empty (i.e., there's NOTHING, not even
// a shadow, inside me).
if (getRange().getStart().getNext() == getRange().getEnd()) return;
InstructionFactory fact = getFactory();
InstructionList handler = new InstructionList();
BcelVar exceptionVar = genTempVar(catchType);
exceptionVar.appendStore(handler, fact);
// pr62642
// I will now jump through some firey BCEL hoops to generate a trivial bit of code:
// if (exc instanceof ExceptionInInitializerError)
// throw (ExceptionInInitializerError)exc;
if (this.getEnclosingMethod().getName().equals("<clinit>")) {
ResolvedTypeX eiieType = world.resolve("java.lang.ExceptionInInitializerError");
ObjectType eiieBcelType = (ObjectType)BcelWorld.makeBcelType(eiieType);
InstructionList ih = new InstructionList(InstructionConstants.NOP);
handler.append(exceptionVar.createLoad(fact));
handler.append(fact.createInstanceOf(eiieBcelType));
BranchInstruction bi =
InstructionFactory.createBranchInstruction(Constants.IFEQ,ih.getStart());
handler.append(bi);
handler.append(exceptionVar.createLoad(fact));
handler.append(fact.createCheckCast(eiieBcelType));
handler.append(InstructionConstants.ATHROW);
handler.append(ih);
}
InstructionList endHandler = new InstructionList(
exceptionVar.createLoad(fact));
handler.append(munger.getAdviceInstructions(this, exceptionVar, endHandler.getStart()));
handler.append(endHandler);
handler.append(InstructionConstants.ATHROW);
InstructionHandle handlerStart = handler.getStart();
if (isFallsThrough()) {
InstructionHandle jumpTarget = handler.append(InstructionConstants.NOP);
handler.insert(InstructionFactory.createBranchInstruction(Constants.GOTO, jumpTarget));
}
InstructionHandle protectedEnd = handler.getStart();
range.insert(handler, Range.InsideAfter);
enclosingMethod.addExceptionHandler(range.getStart().getNext(), protectedEnd.getPrev(),
handlerStart, (ObjectType)BcelWorld.makeBcelType(catchType), //???Type.THROWABLE,
// high priority if our args are on the stack
getKind().hasHighPriorityExceptions());
}
//??? this shares a lot of code with the above weaveAfterThrowing
//??? would be nice to abstract that to say things only once
public void weaveSoftener(BcelAdvice munger, TypeX catchType) {
// a good optimization would be not to generate anything here
// if the shadow is GUARANTEED empty (i.e., there's NOTHING, not even
// a shadow, inside me).
if (getRange().getStart().getNext() == getRange().getEnd()) return;
InstructionFactory fact = getFactory();
InstructionList handler = new InstructionList();
BcelVar exceptionVar = genTempVar(catchType);
exceptionVar.appendStore(handler, fact);
// ENH 42743 suggests that we don't soften runtime exceptions.
// To implement that, would need to add instructions into the handler
// stream here to test if exceptionVar is an instanceof RuntimeException,
// and if it is, just re-throw it without softening.
// (Not yet implemented obviously).
handler.append(fact.createNew(NameMangler.SOFT_EXCEPTION_TYPE));
handler.append(InstructionFactory.createDup(1));
handler.append(exceptionVar.createLoad(fact));
handler.append(fact.createInvoke(NameMangler.SOFT_EXCEPTION_TYPE, "<init>",
Type.VOID, new Type[] { Type.THROWABLE }, Constants.INVOKESPECIAL)); //??? special
handler.append(InstructionConstants.ATHROW);
InstructionHandle handlerStart = handler.getStart();
if (isFallsThrough()) {
InstructionHandle jumpTarget = range.getEnd();//handler.append(fact.NOP);
handler.insert(InstructionFactory.createBranchInstruction(Constants.GOTO, jumpTarget));
}
InstructionHandle protectedEnd = handler.getStart();
range.insert(handler, Range.InsideAfter);
enclosingMethod.addExceptionHandler(range.getStart().getNext(), protectedEnd.getPrev(),
handlerStart, (ObjectType)BcelWorld.makeBcelType(catchType),
// high priority if our args are on the stack
getKind().hasHighPriorityExceptions());
}
public void weavePerObjectEntry(final BcelAdvice munger, final BcelVar onVar) {
final InstructionFactory fact = getFactory();
InstructionList entryInstructions = new InstructionList();
InstructionList entrySuccessInstructions = new InstructionList();
onVar.appendLoad(entrySuccessInstructions, fact);
entrySuccessInstructions.append(
Utility.createInvoke(fact, world,
AjcMemberMaker.perObjectBind(munger.getConcreteAspect())));
InstructionList testInstructions =
munger.getTestInstructions(this, entrySuccessInstructions.getStart(),
range.getRealStart(),
entrySuccessInstructions.getStart());
entryInstructions.append(testInstructions);
entryInstructions.append(entrySuccessInstructions);
range.insert(entryInstructions, Range.InsideBefore);
}
public void weaveCflowEntry(final BcelAdvice munger, final Member cflowStackField) {
final boolean isPer = munger.getKind() == AdviceKind.PerCflowBelowEntry ||
munger.getKind() == AdviceKind.PerCflowEntry;
final Type objectArrayType = new ArrayType(Type.OBJECT, 1);
final InstructionFactory fact = getFactory();
final BcelVar testResult = genTempVar(ResolvedTypeX.BOOLEAN);
InstructionList entryInstructions = new InstructionList();
{
InstructionList entrySuccessInstructions = new InstructionList();
if (munger.hasDynamicTests()) {
entryInstructions.append(Utility.createConstant(fact, 0));
testResult.appendStore(entryInstructions, fact);
entrySuccessInstructions.append(Utility.createConstant(fact, 1));
testResult.appendStore(entrySuccessInstructions, fact);
}
if (isPer) {
entrySuccessInstructions.append(
fact.createInvoke(munger.getConcreteAspect().getName(),
NameMangler.PERCFLOW_PUSH_METHOD,
Type.VOID,
new Type[] { },
Constants.INVOKESTATIC));
} else {
BcelVar[] cflowStateVars = munger.getExposedStateAsBcelVars();
BcelVar arrayVar = genTempVar(TypeX.OBJECTARRAY);
int alen = cflowStateVars.length;
entrySuccessInstructions.append(Utility.createConstant(fact, alen));
entrySuccessInstructions.append(
(Instruction) fact.createNewArray(Type.OBJECT, (short) 1));
arrayVar.appendStore(entrySuccessInstructions, fact);
for (int i = 0; i < alen; i++) {
arrayVar.appendConvertableArrayStore(
entrySuccessInstructions,
fact,
i,
cflowStateVars[i]);
}
entrySuccessInstructions.append(
Utility.createGet(fact, cflowStackField));
arrayVar.appendLoad(entrySuccessInstructions, fact);
entrySuccessInstructions.append(
fact.createInvoke(NameMangler.CFLOW_STACK_TYPE, "push", Type.VOID,
new Type[] { objectArrayType },
Constants.INVOKEVIRTUAL));
}
InstructionList testInstructions =
munger.getTestInstructions(this, entrySuccessInstructions.getStart(),
range.getRealStart(),
entrySuccessInstructions.getStart());
entryInstructions.append(testInstructions);
entryInstructions.append(entrySuccessInstructions);
}
// this is the same for both per and non-per
weaveAfter(new BcelAdvice(null, null, null, 0, 0, 0, null, null) {
public InstructionList getAdviceInstructions(
BcelShadow s,
BcelVar extraArgVar,
InstructionHandle ifNoAdvice) {
InstructionList exitInstructions = new InstructionList();
if (munger.hasDynamicTests()) {
testResult.appendLoad(exitInstructions, fact);
exitInstructions.append(
InstructionFactory.createBranchInstruction(
Constants.IFEQ,
ifNoAdvice));
}
exitInstructions.append(Utility.createGet(fact, cflowStackField));
exitInstructions
.append(
fact
.createInvoke(
NameMangler.CFLOW_STACK_TYPE,
"pop",
Type.VOID,
new Type[] {
}, Constants.INVOKEVIRTUAL));
return exitInstructions;
}
});
range.insert(entryInstructions, Range.InsideBefore);
}
public void weaveAroundInline(
BcelAdvice munger,
boolean hasDynamicTest)
{
/* Implementation notes:
*
* AroundInline still extracts the instructions of the original shadow into
* an extracted method. This allows inlining of even that advice that doesn't
* call proceed or calls proceed more than once.
*
* It extracts the instructions of the original shadow into a method.
*
* Then it extracts the instructions of the advice into a new method defined on
* this enclosing class. This new method can then be specialized as below.
*
* Then it searches in the instructions of the advice for any call to the
* proceed method.
*
* At such a call, there is stuff on the stack representing the arguments to
* proceed. Pop these into the frame.
*
* Now build the stack for the call to the extracted method, taking values
* either from the join point state or from the new frame locs from proceed.
* Now call the extracted method. The right return value should be on the
* stack, so no cast is necessary.
*
* If only one call to proceed is made, we can re-inline the original shadow.
* We are not doing that presently.
*
* If the body of the advice can be determined to not alter the stack, or if
* this shadow doesn't care about the stack, i.e. method-execution, then the
* new method for the advice can also be re-lined. We are not doing that
* presently.
*/
// !!! THIS BLOCK OF CODE SHOULD BE IN A METHOD CALLED weaveAround(...);
Member mungerSig = munger.getSignature();
ResolvedTypeX declaringType = world.resolve(mungerSig.getDeclaringType(),true);
if (declaringType == ResolvedTypeX.MISSING) {
IMessage msg = new Message(
WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_DURING_AROUND_WEAVE,declaringType.getClassName()),
"",IMessage.ERROR,getSourceLocation(),null,
new ISourceLocation[]{ munger.getSourceLocation()});
world.getMessageHandler().handleMessage(msg);
}
//??? might want some checks here to give better errors
BcelObjectType ot = BcelWorld.getBcelObjectType(declaringType);
LazyMethodGen adviceMethod = ot.getLazyClassGen().getLazyMethodGen(mungerSig);
if (!adviceMethod.getCanInline())
{
weaveAroundClosure(munger, hasDynamicTest);
return;
}
// We can't inline around methods if they have around advice on them, this
// is because the weaving will extract the body and hence the proceed call.
//??? should consider optimizations to recognize simple cases that don't require body extraction
enclosingMethod.setCanInline(false);
// start by exposing various useful things into the frame
final InstructionFactory fact = getFactory();
// now generate the aroundBody method
LazyMethodGen extractedMethod =
extractMethod(
NameMangler.aroundCallbackMethodName(
getSignature(),
getEnclosingClass()),
Modifier.PRIVATE,
munger);
// now extract the advice into its own method
String adviceMethodName =
NameMangler.aroundCallbackMethodName(
getSignature(),
getEnclosingClass()) + "$advice";
List argVarList = new ArrayList();
List proceedVarList = new ArrayList();
int extraParamOffset = 0;
// Create the extra parameters that are needed for passing to proceed
// This code is very similar to that found in makeCallToCallback and should
// be rationalized in the future
if (thisVar != null) {
argVarList.add(thisVar);
proceedVarList.add(new BcelVar(thisVar.getType(), extraParamOffset));
extraParamOffset += thisVar.getType().getSize();
}
if (targetVar != null && targetVar != thisVar) {
argVarList.add(targetVar);
proceedVarList.add(new BcelVar(targetVar.getType(), extraParamOffset));
extraParamOffset += targetVar.getType().getSize();
}
for (int i = 0, len = getArgCount(); i < len; i++) {
argVarList.add(argVars[i]);
proceedVarList.add(new BcelVar(argVars[i].getType(), extraParamOffset));
extraParamOffset += argVars[i].getType().getSize();
}
if (thisJoinPointVar != null) {
argVarList.add(thisJoinPointVar);
proceedVarList.add(new BcelVar(thisJoinPointVar.getType(), extraParamOffset));
extraParamOffset += thisJoinPointVar.getType().getSize();
}
Type[] adviceParameterTypes = adviceMethod.getArgumentTypes();
Type[] extractedMethodParameterTypes = extractedMethod.getArgumentTypes();
Type[] parameterTypes =
new Type[extractedMethodParameterTypes.length
+ adviceParameterTypes.length
+ 1];
int parameterIndex = 0;
System.arraycopy(
extractedMethodParameterTypes,
0,
parameterTypes,
parameterIndex,
extractedMethodParameterTypes.length);
parameterIndex += extractedMethodParameterTypes.length;
parameterTypes[parameterIndex++] =
BcelWorld.makeBcelType(adviceMethod.getEnclosingClass().getType());
System.arraycopy(
adviceParameterTypes,
0,
parameterTypes,
parameterIndex,
adviceParameterTypes.length);
LazyMethodGen localAdviceMethod =
new LazyMethodGen(
Modifier.PRIVATE | Modifier.FINAL | Modifier.STATIC,
adviceMethod.getReturnType(),
adviceMethodName,
parameterTypes,
new String[0],
getEnclosingClass());
String donorFileName = adviceMethod.getEnclosingClass().getInternalFileName();
String recipientFileName = getEnclosingClass().getInternalFileName();
// System.err.println("donor " + donorFileName);
// System.err.println("recip " + recipientFileName);
if (! donorFileName.equals(recipientFileName)) {
localAdviceMethod.fromFilename = donorFileName;
getEnclosingClass().addInlinedSourceFileInfo(
donorFileName,
adviceMethod.highestLineNumber);
}
getEnclosingClass().addMethodGen(localAdviceMethod);
// create a map that will move all slots in advice method forward by extraParamOffset
// in order to make room for the new proceed-required arguments that are added at
// the beginning of the parameter list
int nVars = adviceMethod.getMaxLocals() + extraParamOffset;
IntMap varMap = IntMap.idMap(nVars);
for (int i=extraParamOffset; i < nVars; i++) {
varMap.put(i-extraParamOffset, i);
}
localAdviceMethod.getBody().insert(
BcelClassWeaver.genInlineInstructions(adviceMethod,
localAdviceMethod, varMap, fact, true));
localAdviceMethod.setMaxLocals(nVars);
//System.err.println(localAdviceMethod);
// the shadow is now empty. First, create a correct call
// to the around advice. This includes both the call (which may involve
// value conversion of the advice arguments) and the return
// (which may involve value conversion of the return value). Right now
// we push a null for the unused closure. It's sad, but there it is.
InstructionList advice = new InstructionList();
// InstructionHandle adviceMethodInvocation;
{
for (Iterator i = argVarList.iterator(); i.hasNext(); ) {
BcelVar var = (BcelVar)i.next();
var.appendLoad(advice, fact);
}
// ??? we don't actually need to push NULL for the closure if we take care
advice.append(
munger.getAdviceArgSetup(
this,
null,
new InstructionList(InstructionConstants.ACONST_NULL)));
// adviceMethodInvocation =
advice.append(
Utility.createInvoke(fact, localAdviceMethod)); //(fact, getWorld(), munger.getSignature()));
advice.append(
Utility.createConversion(
getFactory(),
BcelWorld.makeBcelType(munger.getSignature().getReturnType()),
extractedMethod.getReturnType()));
if (! isFallsThrough()) {
advice.append(InstructionFactory.createReturn(extractedMethod.getReturnType()));
}
}
// now, situate the call inside the possible dynamic tests,
// and actually add the whole mess to the shadow
if (! hasDynamicTest) {
range.append(advice);
} else {
InstructionList afterThingie = new InstructionList(InstructionConstants.NOP);
InstructionList callback = makeCallToCallback(extractedMethod);
if (terminatesWithReturn()) {
callback.append(
InstructionFactory.createReturn(extractedMethod.getReturnType()));
} else {
//InstructionHandle endNop = range.insert(fact.NOP, Range.InsideAfter);
advice.append(
InstructionFactory.createBranchInstruction(
Constants.GOTO,
afterThingie.getStart()));
}
range.append(
munger.getTestInstructions(
this,
advice.getStart(),
callback.getStart(),
advice.getStart()));
range.append(advice);
range.append(callback);
range.append(afterThingie);
}
// now search through the advice, looking for a call to PROCEED.
// Then we replace the call to proceed with some argument setup, and a
// call to the extracted method.
String proceedName =
NameMangler.proceedMethodName(munger.getSignature().getName());
InstructionHandle curr = localAdviceMethod.getBody().getStart();
InstructionHandle end = localAdviceMethod.getBody().getEnd();
ConstantPoolGen cpg = localAdviceMethod.getEnclosingClass().getConstantPoolGen();
while (curr != end) {
InstructionHandle next = curr.getNext();
Instruction inst = curr.getInstruction();
if ((inst instanceof INVOKESTATIC)
&& proceedName.equals(((INVOKESTATIC) inst).getMethodName(cpg))) {
localAdviceMethod.getBody().append(
curr,
getRedoneProceedCall(
fact,
extractedMethod,
munger,
localAdviceMethod,
proceedVarList));
Utility.deleteInstruction(curr, localAdviceMethod);
}
curr = next;
}
// and that's it.
}
private InstructionList getRedoneProceedCall(
InstructionFactory fact,
LazyMethodGen callbackMethod,
BcelAdvice munger,
LazyMethodGen localAdviceMethod,
List argVarList)
{
InstructionList ret = new InstructionList();
// we have on stack all the arguments for the ADVICE call.
// we have in frame somewhere all the arguments for the non-advice call.
BcelVar[] adviceVars = munger.getExposedStateAsBcelVars();
IntMap proceedMap = makeProceedArgumentMap(adviceVars);
// System.out.println(proceedMap + " for " + this);
// System.out.println(argVarList);
ResolvedTypeX[] proceedParamTypes =
world.resolve(munger.getSignature().getParameterTypes());
// remove this*JoinPoint* as arguments to proceed
if (munger.getBaseParameterCount()+1 < proceedParamTypes.length) {
int len = munger.getBaseParameterCount()+1;
ResolvedTypeX[] newTypes = new ResolvedTypeX[len];
System.arraycopy(proceedParamTypes, 0, newTypes, 0, len);
proceedParamTypes = newTypes;
}
//System.out.println("stateTypes: " + Arrays.asList(stateTypes));
BcelVar[] proceedVars =
Utility.pushAndReturnArrayOfVars(proceedParamTypes, ret, fact, localAdviceMethod);
Type[] stateTypes = callbackMethod.getArgumentTypes();
// System.out.println("stateTypes: " + Arrays.asList(stateTypes));
for (int i=0, len=stateTypes.length; i < len; i++) {
Type stateType = stateTypes[i];
ResolvedTypeX stateTypeX = BcelWorld.fromBcel(stateType).resolve(world);
if (proceedMap.hasKey(i)) {
//throw new RuntimeException("unimplemented");
proceedVars[proceedMap.get(i)].appendLoadAndConvert(ret, fact, stateTypeX);
} else {
((BcelVar) argVarList.get(i)).appendLoad(ret, fact);
}
}
ret.append(Utility.createInvoke(fact, callbackMethod));
ret.append(Utility.createConversion(fact, callbackMethod.getReturnType(),
BcelWorld.makeBcelType(munger.getSignature().getReturnType())));
return ret;
}
public void weaveAroundClosure(
BcelAdvice munger,
boolean hasDynamicTest)
{
InstructionFactory fact = getFactory();
enclosingMethod.setCanInline(false);
// MOVE OUT ALL THE INSTRUCTIONS IN MY SHADOW INTO ANOTHER METHOD!
LazyMethodGen callbackMethod =
extractMethod(
NameMangler.aroundCallbackMethodName(
getSignature(),
getEnclosingClass()),
0,
munger);
BcelVar[] adviceVars = munger.getExposedStateAsBcelVars();
String closureClassName =
NameMangler.makeClosureClassName(
getEnclosingClass().getType(),
getEnclosingClass().getNewGeneratedNameTag());
Member constructorSig = new Member(Member.CONSTRUCTOR,
TypeX.forName(closureClassName), 0, "<init>",
"([Ljava/lang/Object;)V");
BcelVar closureHolder = null;
// This is not being used currently since getKind() == preinitializaiton
// cannot happen in around advice
if (getKind() == PreInitialization) {
closureHolder = genTempVar(AjcMemberMaker.AROUND_CLOSURE_TYPE);
}
InstructionList closureInstantiation =
makeClosureInstantiation(constructorSig, closureHolder);
/*LazyMethodGen constructor = */
makeClosureClassAndReturnConstructor(
closureClassName,
callbackMethod,
makeProceedArgumentMap(adviceVars)
);
InstructionList returnConversionCode;
if (getKind() == PreInitialization) {
returnConversionCode = new InstructionList();
BcelVar stateTempVar = genTempVar(TypeX.OBJECTARRAY);
closureHolder.appendLoad(returnConversionCode, fact);
returnConversionCode.append(
Utility.createInvoke(
fact,
world,
AjcMemberMaker.aroundClosurePreInitializationGetter()));
stateTempVar.appendStore(returnConversionCode, fact);
Type[] stateTypes = getSuperConstructorParameterTypes();
returnConversionCode.append(InstructionConstants.ALOAD_0); // put "this" back on the stack
for (int i = 0, len = stateTypes.length; i < len; i++) {
TypeX bcelTX = BcelWorld.fromBcel(stateTypes[i]);
ResolvedTypeX stateRTX = world.resolve(bcelTX,true);
if (stateRTX == ResolvedTypeX.MISSING) {
IMessage msg = new Message(
WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_DURING_AROUND_WEAVE_PREINIT,bcelTX.getClassName()),
"",IMessage.ERROR,getSourceLocation(),null,
new ISourceLocation[]{ munger.getSourceLocation()});
world.getMessageHandler().handleMessage(msg);
}
stateTempVar.appendConvertableArrayLoad(
returnConversionCode,
fact,
i,
stateRTX);
}
} else {
returnConversionCode =
Utility.createConversion(
getFactory(),
BcelWorld.makeBcelType(munger.getSignature().getReturnType()),
callbackMethod.getReturnType());
if (!isFallsThrough()) {
returnConversionCode.append(
InstructionFactory.createReturn(callbackMethod.getReturnType()));
}
}
InstructionList advice = new InstructionList();
advice.append(munger.getAdviceArgSetup(this, null, closureInstantiation));
// advice.append(closureInstantiation);
advice.append(munger.getNonTestAdviceInstructions(this));
advice.append(returnConversionCode);
if (!hasDynamicTest) {
range.append(advice);
} else {
InstructionList callback = makeCallToCallback(callbackMethod);
InstructionList postCallback = new InstructionList();
if (terminatesWithReturn()) {
callback.append(
InstructionFactory.createReturn(callbackMethod.getReturnType()));
} else {
advice.append(
InstructionFactory.createBranchInstruction(
Constants.GOTO,
postCallback.append(InstructionConstants.NOP)));
}
range.append(
munger.getTestInstructions(
this,
advice.getStart(),
callback.getStart(),
advice.getStart()));
range.append(advice);
range.append(callback);
range.append(postCallback);
}
}
// exposed for testing
InstructionList makeCallToCallback(LazyMethodGen callbackMethod) {
InstructionFactory fact = getFactory();
InstructionList callback = new InstructionList();
if (thisVar != null) {
callback.append(InstructionConstants.ALOAD_0);
}
if (targetVar != null && targetVar != thisVar) {
callback.append(BcelRenderer.renderExpr(fact, world, targetVar));
}
callback.append(BcelRenderer.renderExprs(fact, world, argVars));
// remember to render tjps
if (thisJoinPointVar != null) {
callback.append(BcelRenderer.renderExpr(fact, world, thisJoinPointVar));
}
callback.append(Utility.createInvoke(fact, callbackMethod));
return callback;
}
/** side-effect-free */
private InstructionList makeClosureInstantiation(Member constructor, BcelVar holder) {
// LazyMethodGen constructor) {
InstructionFactory fact = getFactory();
BcelVar arrayVar = genTempVar(TypeX.OBJECTARRAY);
//final Type objectArrayType = new ArrayType(Type.OBJECT, 1);
final InstructionList il = new InstructionList();
int alen = getArgCount() + (thisVar == null ? 0 : 1) +
((targetVar != null && targetVar != thisVar) ? 1 : 0) +
(thisJoinPointVar == null ? 0 : 1);
il.append(Utility.createConstant(fact, alen));
il.append((Instruction)fact.createNewArray(Type.OBJECT, (short)1));
arrayVar.appendStore(il, fact);
int stateIndex = 0;
if (thisVar != null) {
arrayVar.appendConvertableArrayStore(il, fact, stateIndex, thisVar);
thisVar.setPositionInAroundState(stateIndex);
stateIndex++;
}
if (targetVar != null && targetVar != thisVar) {
arrayVar.appendConvertableArrayStore(il, fact, stateIndex, targetVar);
targetVar.setPositionInAroundState(stateIndex);
stateIndex++;
}
for (int i = 0, len = getArgCount(); i<len; i++) {
arrayVar.appendConvertableArrayStore(il, fact, stateIndex, argVars[i]);
argVars[i].setPositionInAroundState(stateIndex);
stateIndex++;
}
if (thisJoinPointVar != null) {
arrayVar.appendConvertableArrayStore(il, fact, stateIndex, thisJoinPointVar);
thisJoinPointVar.setPositionInAroundState(stateIndex);
stateIndex++;
}
il.append(fact.createNew(new ObjectType(constructor.getDeclaringType().getName())));
il.append(new DUP());
arrayVar.appendLoad(il, fact);
il.append(Utility.createInvoke(fact, world, constructor));
if (getKind() == PreInitialization) {
il.append(InstructionConstants.DUP);
holder.appendStore(il, fact);
}
return il;
}
private IntMap makeProceedArgumentMap(BcelVar[] adviceArgs) {
//System.err.println("coming in with " + Arrays.asList(adviceArgs));
IntMap ret = new IntMap();
for(int i = 0, len = adviceArgs.length; i < len; i++) {
BcelVar v = (BcelVar) adviceArgs[i];
if (v == null) continue; // XXX we don't know why this is required
int pos = v.getPositionInAroundState();
if (pos >= 0) { // need this test to avoid args bound via cflow
ret.put(pos, i);
}
}
//System.err.println("returning " + ret);
return ret;
}
/**
*
*
* @param callbackMethod the method we will call back to when our run method gets called.
*
* @param proceedMap A map from state position to proceed argument position. May be
* non covering on state position.
*/
private LazyMethodGen makeClosureClassAndReturnConstructor(
String closureClassName,
LazyMethodGen callbackMethod,
IntMap proceedMap)
{
String superClassName = "org.aspectj.runtime.internal.AroundClosure";
Type objectArrayType = new ArrayType(Type.OBJECT, 1);
LazyClassGen closureClass = new LazyClassGen(closureClassName,
superClassName,
getEnclosingClass().getFileName(),
Modifier.PUBLIC,
new String[] {});
InstructionFactory fact = new InstructionFactory(closureClass.getConstantPoolGen());
// constructor
LazyMethodGen constructor = new LazyMethodGen(Modifier.PUBLIC,
Type.VOID,
"<init>",
new Type[] {objectArrayType},
new String[] {},
closureClass);
InstructionList cbody = constructor.getBody();
cbody.append(InstructionFactory.createLoad(Type.OBJECT, 0));
cbody.append(InstructionFactory.createLoad(objectArrayType, 1));
cbody.append(fact.createInvoke(superClassName, "<init>", Type.VOID,
new Type[] {objectArrayType}, Constants.INVOKESPECIAL));
cbody.append(InstructionFactory.createReturn(Type.VOID));
closureClass.addMethodGen(constructor);
// method
LazyMethodGen runMethod = new LazyMethodGen(Modifier.PUBLIC,
Type.OBJECT,
"run",
new Type[] {objectArrayType},
new String[] {},
closureClass);
InstructionList mbody = runMethod.getBody();
BcelVar proceedVar = new BcelVar(TypeX.OBJECTARRAY.resolve(world), 1);
// int proceedVarIndex = 1;
BcelVar stateVar =
new BcelVar(TypeX.OBJECTARRAY.resolve(world), runMethod.allocateLocal(1));
// int stateVarIndex = runMethod.allocateLocal(1);
mbody.append(InstructionFactory.createThis());
mbody.append(fact.createGetField(superClassName, "state", objectArrayType));
mbody.append(stateVar.createStore(fact));
// mbody.append(fact.createStore(objectArrayType, stateVarIndex));
Type[] stateTypes = callbackMethod.getArgumentTypes();
for (int i=0, len=stateTypes.length; i < len; i++) {
Type stateType = stateTypes[i];
ResolvedTypeX stateTypeX = BcelWorld.fromBcel(stateType).resolve(world);
if (proceedMap.hasKey(i)) {
mbody.append(
proceedVar.createConvertableArrayLoad(fact, proceedMap.get(i),
stateTypeX));
} else {
mbody.append(
stateVar.createConvertableArrayLoad(fact, i,
stateTypeX));
}
}
mbody.append(Utility.createInvoke(fact, callbackMethod));
if (getKind() == PreInitialization) {
mbody.append(Utility.createSet(
fact,
AjcMemberMaker.aroundClosurePreInitializationField()));
mbody.append(InstructionConstants.ACONST_NULL);
} else {
mbody.append(
Utility.createConversion(
fact,
callbackMethod.getReturnType(),
Type.OBJECT));
}
mbody.append(InstructionFactory.createReturn(Type.OBJECT));
closureClass.addMethodGen(runMethod);
// class
getEnclosingClass().addGeneratedInner(closureClass);
return constructor;
}
// ---- extraction methods
public LazyMethodGen extractMethod(String newMethodName, int visibilityModifier, ShadowMunger munger) {
LazyMethodGen.assertGoodBody(range.getBody(), newMethodName);
if (!getKind().allowsExtraction()) throw new BCException();
LazyMethodGen freshMethod = createMethodGen(newMethodName,visibilityModifier);
// System.err.println("******");
// System.err.println("ABOUT TO EXTRACT METHOD for" + this);
// enclosingMethod.print(System.err);
// System.err.println("INTO");
// freshMethod.print(System.err);
// System.err.println("WITH REMAP");
// System.err.println(makeRemap());
range.extractInstructionsInto(freshMethod, makeRemap(),
(getKind() != PreInitialization) &&
isFallsThrough());
if (getKind() == PreInitialization) {
addPreInitializationReturnCode(
freshMethod,
getSuperConstructorParameterTypes());
}
getEnclosingClass().addMethodGen(freshMethod,munger.getSourceLocation());
return freshMethod;
}
private void addPreInitializationReturnCode(
LazyMethodGen extractedMethod,
Type[] superConstructorTypes)
{
InstructionList body = extractedMethod.getBody();
final InstructionFactory fact = getFactory();
BcelVar arrayVar = new BcelVar(
world.getCoreType(TypeX.OBJECTARRAY),
extractedMethod.allocateLocal(1));
int len = superConstructorTypes.length;
body.append(Utility.createConstant(fact, len));
body.append((Instruction)fact.createNewArray(Type.OBJECT, (short)1));
arrayVar.appendStore(body, fact);
for (int i = len - 1; i >= 0; i++) {
// convert thing on top of stack to object
body.append(
Utility.createConversion(fact, superConstructorTypes[i], Type.OBJECT));
// push object array
arrayVar.appendLoad(body, fact);
// swap
body.append(InstructionConstants.SWAP);
// do object array store.
body.append(Utility.createConstant(fact, i));
body.append(InstructionConstants.SWAP);
body.append(InstructionFactory.createArrayStore(Type.OBJECT));
}
arrayVar.appendLoad(body, fact);
body.append(InstructionConstants.ARETURN);
}
private Type[] getSuperConstructorParameterTypes() {
// assert getKind() == PreInitialization
InstructionHandle superCallHandle = getRange().getEnd().getNext();
InvokeInstruction superCallInstruction =
(InvokeInstruction) superCallHandle.getInstruction();
return superCallInstruction.getArgumentTypes(
getEnclosingClass().getConstantPoolGen());
}
/** make a map from old frame location to new frame location. Any unkeyed frame
* location picks out a copied local */
private IntMap makeRemap() {
IntMap ret = new IntMap(5);
int reti = 0;
if (thisVar != null) {
ret.put(0, reti++); // thisVar guaranteed to be 0
}
if (targetVar != null && targetVar != thisVar) {
ret.put(targetVar.getSlot(), reti++);
}
for (int i = 0, len = argVars.length; i < len; i++) {
ret.put(argVars[i].getSlot(), reti);
reti += argVars[i].getType().getSize();
}
if (thisJoinPointVar != null) {
ret.put(thisJoinPointVar.getSlot(), reti++);
}
// we not only need to put the arguments, we also need to remap their
// aliases, which we so helpfully put into temps at the beginning of this join
// point.
if (! getKind().argsOnStack()) {
int oldi = 0;
int newi = 0;
// if we're passing in a this and we're not argsOnStack we're always
// passing in a target too
if (arg0HoldsThis()) { ret.put(0, 0); oldi++; newi+=1; }
//assert targetVar == thisVar
for (int i = 0; i < getArgCount(); i++) {
TypeX type = getArgType(i);
ret.put(oldi, newi);
oldi += type.getSize();
newi += type.getSize();
}
}
// System.err.println("making remap for : " + this);
// if (targetVar != null) System.err.println("target slot : " + targetVar.getSlot());
// if (thisVar != null) System.err.println(" this slot : " + thisVar.getSlot());
// System.err.println(ret);
return ret;
}
/**
* The new method always static.
* It may take some extra arguments: this, target.
* If it's argsOnStack, then it must take both this/target
* If it's argsOnFrame, it shares this and target.
* ??? rewrite this to do less array munging, please
*/
private LazyMethodGen createMethodGen(String newMethodName, int visibilityModifier) {
Type[] parameterTypes = BcelWorld.makeBcelTypes(getArgTypes());
int modifiers = Modifier.FINAL | visibilityModifier;
// XXX some bug
// if (! isExpressionKind() && getSignature().isStrict(world)) {
// modifiers |= Modifier.STRICT;
// }
modifiers |= Modifier.STATIC;
if (targetVar != null && targetVar != thisVar) {
TypeX targetType = getTargetType();
ResolvedMember resolvedMember = getSignature().resolve(world);
if (resolvedMember != null && Modifier.isProtected(resolvedMember.getModifiers()) &&
!samePackage(targetType.getPackageName(), getEnclosingType().getPackageName()))
{
if (!targetType.isAssignableFrom(getThisType(), world)) {
throw new BCException("bad bytecode");
}
targetType = getThisType();
}
parameterTypes = addType(BcelWorld.makeBcelType(targetType), parameterTypes);
}
if (thisVar != null) {
TypeX thisType = getThisType();
parameterTypes = addType(BcelWorld.makeBcelType(thisType), parameterTypes);
}
// We always want to pass down thisJoinPoint in case we have already woven
// some advice in here. If we only have a single piece of around advice on a
// join point, it is unnecessary to accept (and pass) tjp.
if (thisJoinPointVar != null) {
parameterTypes = addTypeToEnd(LazyClassGen.tjpType, parameterTypes);
}
TypeX returnType;
if (getKind() == PreInitialization) {
returnType = TypeX.OBJECTARRAY;
} else {
returnType = getReturnType();
}
return
new LazyMethodGen(
modifiers,
BcelWorld.makeBcelType(returnType),
newMethodName,
parameterTypes,
new String[0],
// XXX again, we need to look up methods!
// TypeX.getNames(getSignature().getExceptions(world)),
getEnclosingClass());
}
private boolean samePackage(String p1, String p2) {
if (p1 == null) return p2 == null;
if (p2 == null) return false;
return p1.equals(p2);
}
private Type[] addType(Type type, Type[] types) {
int len = types.length;
Type[] ret = new Type[len+1];
ret[0] = type;
System.arraycopy(types, 0, ret, 1, len);
return ret;
}
private Type[] addTypeToEnd(Type type, Type[] types) {
int len = types.length;
Type[] ret = new Type[len+1];
ret[len] = type;
System.arraycopy(types, 0, ret, 0, len);
return ret;
}
public BcelVar genTempVar(TypeX typeX) {
return new BcelVar(typeX.resolve(world), genTempVarIndex(typeX.getSize()));
}
// public static final boolean CREATE_TEMP_NAMES = true;
public BcelVar genTempVar(TypeX typeX, String localName) {
BcelVar tv = genTempVar(typeX);
// if (CREATE_TEMP_NAMES) {
// for (InstructionHandle ih = range.getStart(); ih != range.getEnd(); ih = ih.getNext()) {
// if (Range.isRangeHandle(ih)) continue;
// ih.addTargeter(new LocalVariableTag(typeX, localName, tv.getSlot()));
// }
// }
return tv;
}
// eh doesn't think we need to garbage collect these (64K is a big number...)
private int genTempVarIndex(int size) {
return enclosingMethod.allocateLocal(size);
}
public InstructionFactory getFactory() {
return getEnclosingClass().getFactory();
}
public ISourceLocation getSourceLocation() {
int sourceLine = getSourceLine();
if (sourceLine == 0 || sourceLine == -1) {
// Thread.currentThread().dumpStack();
// System.err.println(this + ": " + range);
return getEnclosingClass().getType().getSourceLocation();
} else {
return getEnclosingClass().getType().getSourceContext().makeSourceLocation(sourceLine);
}
}
public Shadow getEnclosingShadow() {
return enclosingShadow;
}
public LazyMethodGen getEnclosingMethod() {
return enclosingMethod;
}
public boolean isFallsThrough() {
return !terminatesWithReturn(); //fallsThrough;
}
}
|
72,671
|
Bug 72671 Bootclasspath specification for compiling is not possible
|
I have following bug running eclipse 3.0 and ajdt 1.1.12 I have following class: import java.io.FileNotFoundException; import java.io.FileOutputStream; import org.w3c.dom.DOMConfiguration; import org.w3c.dom.DOMError; import org.w3c.dom.DOMErrorHandler; import org.w3c.dom.Document; import org.w3c.dom.DocumentFragment; import org.w3c.dom.NodeList; import org.w3c.dom.ls.DOMImplementationLS; import org.w3c.dom.ls.LSInput; import org.w3c.dom.ls.LSOutput; import org.w3c.dom.ls.LSParser; import com.dcbank.common.DOMImplementationLSSingleton; public class DOMHelper { public static final String CLASS_ID = "%full_filespec: DOMHelper.java~1:java:1 %"; public static void save(Document document, String filename) throws ClassNotFoundException, InstantiationException, IllegalAccessException, FileNotFoundException { document.normalizeDocument(); } } which compiles very fine with JDK 1.4.2_02 on Windows XP, as soon as the dom2-xml-apis.jar and dom3-xercesImpl.jar are added at the beginning of the jre container, or are included in the jar-library list before the system jar. As soon as I convert this project to an AspectJ project, the code does not compile anymore. The aspectJ compiler does not find the normalizeDocument, which is included in the one of the two additional jars. method any more. kind regards Arno Schmidmeier
|
resolved fixed
|
d1551bd
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:13:46Z
| 2004-08-26T11:33:20Z
|
ajde/src/org/aspectj/ajde/internal/CompilerAdapter.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC),
* 2003 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Xerox/PARC initial implementation
* AMC 01.20.2003 extended to support new AspectJ 1.1 options,
* bugzilla #29769
* ******************************************************************/
package org.aspectj.ajde.internal;
import java.io.File;
import java.util.*;
import org.aspectj.ajde.*;
import org.aspectj.ajdt.ajc.*;
import org.aspectj.ajdt.internal.core.builder.*;
import org.aspectj.bridge.*;
import org.aspectj.util.LangUtil;
//import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
public class CompilerAdapter {
private static final Set DEFAULT__AJDE_WARNINGS;
static {
DEFAULT__AJDE_WARNINGS = new HashSet();
DEFAULT__AJDE_WARNINGS.add(BuildOptionsAdapter.WARN_ASSERT_IDENITIFIER);
DEFAULT__AJDE_WARNINGS.add(BuildOptionsAdapter.WARN_CONSTRUCTOR_NAME);
DEFAULT__AJDE_WARNINGS.add(BuildOptionsAdapter.WARN_DEPRECATION);
DEFAULT__AJDE_WARNINGS.add(BuildOptionsAdapter.WARN_MASKED_CATCH_BLOCKS);
DEFAULT__AJDE_WARNINGS.add(BuildOptionsAdapter.WARN_PACKAGE_DEFAULT_METHOD);
DEFAULT__AJDE_WARNINGS.add(BuildOptionsAdapter.WARN_UNUSED_IMPORTS);
// DEFAULT__AJDE_WARNINGS.put(BuildOptionsAdapter.WARN_);
// DEFAULT__AJDE_WARNINGS.put(BuildOptionsAdapter.WARN_);
}
// private Map optionsMap;
private AjBuildManager buildManager = null;
private MessageHandlerAdapter messageHandler = null;
private BuildNotifierAdapter currNotifier = null;
private boolean initialized = false;
private boolean structureDirty = true;
private boolean showInfoMessages = false;
// set to false in incremental mode to re-do initial build
private boolean nextBuild = false;
public CompilerAdapter() {
super();
}
public void showInfoMessages(boolean show) { // XXX surface in GUI
showInfoMessages = show;
}
public boolean getShowInfoMessages() {
return showInfoMessages;
}
public void nextBuildFresh() {
if (nextBuild) {
nextBuild = false;
}
}
public void requestCompileExit() {
if (currNotifier != null) {
currNotifier.cancelBuild();
} else {
signalText("unable to cancel build process");
}
}
public boolean isStructureDirty() {
return structureDirty;
}
public void setStructureDirty(boolean structureDirty) {
this.structureDirty = structureDirty;
}
public boolean compile(String configFile, BuildProgressMonitor progressMonitor, boolean buildModel) {
if (configFile == null) {
Ajde.getDefault().getErrorHandler().handleError(
"Tried to build null config file."
);
}
init();
try {
AjBuildConfig buildConfig = genBuildConfig(configFile);
if (buildConfig == null) {
return false;
}
buildConfig.setGenerateModelMode(buildModel);
currNotifier = new BuildNotifierAdapter(progressMonitor, buildManager);
buildManager.setProgressListener(currNotifier);
messageHandler.setBuildNotifierAdapter(currNotifier);
String rtInfo = buildManager.checkRtJar(buildConfig); // !!! will get called twice
if (rtInfo != null) {
Ajde.getDefault().getErrorHandler().handleWarning(
"AspectJ Runtime error: " + rtInfo
+ " Please place a valid aspectjrt.jar on the classpath.");
return false;
}
boolean incrementalEnabled =
buildConfig.isIncrementalMode()
|| buildConfig.isIncrementalFileMode();
if (incrementalEnabled && nextBuild) {
return buildManager.incrementalBuild(buildConfig, messageHandler);
} else {
if (incrementalEnabled) {
nextBuild = incrementalEnabled;
}
return buildManager.batchBuild(buildConfig, messageHandler);
}
// } catch (OperationCanceledException ce) {
// Ajde.getDefault().getErrorHandler().handleWarning(
// "build cancelled by user");
// return false;
} catch (AbortException e) {
final IMessage message = e.getIMessage();
if (null == message) {
signalThrown(e);
} else if (null != message.getMessage()) {
Ajde.getDefault().getErrorHandler().handleWarning(message.getMessage());
} else if (null != message.getThrown()) {
signalThrown(message.getThrown());
} else {
signalThrown(e);
}
return false;
} catch (Throwable t) {
signalThrown(t);
return false;
}
}
/**
* Generate AjBuildConfig from the local configFile parameter
* plus global project and build options.
* Errors signalled using signal... methods.
* @param configFile
* @return null if invalid configuration,
* corresponding AjBuildConfig otherwise
*/
public AjBuildConfig genBuildConfig(String configFilePath) {
init();
File configFile = new File(configFilePath);
if (!configFile.exists()) {
Ajde.getDefault().getErrorHandler().handleError(
"Config file \"" + configFile + "\" does not exist."
);
return null;
}
String[] args = new String[] { "@" + configFile.getAbsolutePath() };
CountingMessageHandler handler
= CountingMessageHandler.makeCountingMessageHandler(messageHandler);
BuildArgParser parser = new BuildArgParser(handler);
AjBuildConfig config = new AjBuildConfig();
parser.populateBuildConfig(config, args, false, configFile);
configureBuildOptions(config,Ajde.getDefault().getBuildManager().getBuildOptions(),handler);
configureProjectOptions(config, Ajde.getDefault().getProjectProperties()); // !!! not what the API intended
// // -- get globals, treat as defaults used if no local values
// AjBuildConfig global = new AjBuildConfig();
// // AMC refactored into two methods to populate buildConfig from buildOptions and
// // project properties - bugzilla 29769.
// BuildOptionsAdapter buildOptions
// = Ajde.getDefault().getBuildManager().getBuildOptions();
// if (!configureBuildOptions(/* global */ config, buildOptions, handler)) {
// return null;
// }
// ProjectPropertiesAdapter projectOptions =
// Ajde.getDefault().getProjectProperties();
// configureProjectOptions(global, projectOptions);
// config.installGlobals(global);
ISourceLocation location = null;
if (config.getConfigFile() != null) {
location = new SourceLocation(config.getConfigFile(), 0);
}
String message = parser.getOtherMessages(true);
if (null != message) {
IMessage m = new Message(message, IMessage.ERROR, null, location);
handler.handleMessage(m);
}
// always force model generation in AJDE
config.setGenerateModelMode(true);
if (Ajde.getDefault().getBuildManager().getBuildOptions().getJavaOptionsMap() != null) {
config.getOptions().set(Ajde.getDefault().getBuildManager().getBuildOptions().getJavaOptionsMap());
}
return config;
// return fixupBuildConfig(config);
}
// /**
// * Fix up build configuration just before using to compile.
// * This should be delegated to a BuildAdapter callback (XXX)
// * for implementation-specific value checks
// * (e.g., to force use of project classpath rather
// * than local config classpath).
// * This implementation does no checks and returns local.
// * @param local the AjBuildConfig generated to validate
// * @param global
// * @param buildOptions
// * @param projectOptions
// * @return null if unable to fix problems or fixed AjBuildConfig if no errors
// *
// */
// protected AjBuildConfig fixupBuildConfig(AjBuildConfig local) {
// if (Ajde.getDefault().getBuildManager().getBuildOptions().getJavaOptionsMap() != null) {
// local.getJavaOptions().putAll(Ajde.getDefault().getBuildManager().getBuildOptions().getJavaOptionsMap());
// }
// return local;
// }
// /** signal error text to user */
// protected void signalError(String text) {
// }
// /** signal warning text to user */
// protected void signalWarning(String text) {
//
// }
/** signal text to user */
protected void signalText(String text) {
Ajde.getDefault().getIdeUIAdapter().displayStatusInformation(text);
}
/** signal Throwable to user (summary in GUI, trace to stdout). */
protected void signalThrown(Throwable t) { // nothing to error handler?
String text = LangUtil.unqualifiedClassName(t)
+ " thrown: "
+ t.getMessage();
Ajde.getDefault().getErrorHandler().handleError(text, t);
}
/**
* Populate options in a build configuration, using the Ajde BuildOptionsAdapter.
* Added by AMC 01.20.2003, bugzilla #29769
*/
private static boolean configureBuildOptions( AjBuildConfig config, BuildOptionsAdapter options, IMessageHandler handler) {
LangUtil.throwIaxIfNull(options, "options");
LangUtil.throwIaxIfNull(config, "config");
Map optionsToSet = new HashMap();
LangUtil.throwIaxIfNull(optionsToSet, "javaOptions");
if (options.getSourceOnePointFourMode()) {
optionsToSet.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_4);
optionsToSet.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_4);
}
String enc = options.getCharacterEncoding();
if (!LangUtil.isEmpty(enc)) {
optionsToSet.put(CompilerOptions.OPTION_Encoding, enc );
}
String compliance = options.getComplianceLevel();
if (!LangUtil.isEmpty(compliance)) {
String version = CompilerOptions.VERSION_1_4;
if ( compliance.equals( BuildOptionsAdapter.VERSION_13 ) ) {
version = CompilerOptions.VERSION_1_3;
}
optionsToSet.put(CompilerOptions.OPTION_Compliance, version );
optionsToSet.put(CompilerOptions.OPTION_Source, version );
}
String sourceLevel = options.getSourceCompatibilityLevel();
if (!LangUtil.isEmpty(sourceLevel)) {
String slVersion = CompilerOptions.VERSION_1_4;
if ( sourceLevel.equals( BuildOptionsAdapter.VERSION_13 ) ) {
slVersion = CompilerOptions.VERSION_1_3;
}
// never set a lower source level than compliance level
String setCompliance = (String) optionsToSet.get( CompilerOptions.OPTION_Compliance);
if ( ! (setCompliance.equals( CompilerOptions.VERSION_1_4 )
&& slVersion.equals(CompilerOptions.VERSION_1_3)) ) {
optionsToSet.put(CompilerOptions.OPTION_Source, slVersion);
}
}
Set warnings = options.getWarnings();
if (!LangUtil.isEmpty(warnings)) {
// turn off all warnings
disableWarnings( optionsToSet );
// then selectively enable those in the set
enableWarnings( optionsToSet, warnings );
} else if (warnings == null) {
// set default warnings on...
enableWarnings( optionsToSet, DEFAULT__AJDE_WARNINGS);
}
Set debugOptions = options.getDebugLevel();
if (!LangUtil.isEmpty(debugOptions)) {
// default is all options on, so just need to selectively
// disable
boolean sourceLine = false;
boolean varAttr = false;
boolean lineNo = false;
Iterator it = debugOptions.iterator();
while (it.hasNext()){
String debug = (String) it.next();
if ( debug.equals( BuildOptionsAdapter.DEBUG_ALL )) {
sourceLine = true;
varAttr = true;
lineNo = true;
} else if ( debug.equals( BuildOptionsAdapter.DEBUG_LINES )) {
lineNo = true;
} else if ( debug.equals( BuildOptionsAdapter.DEBUG_SOURCE )) {
sourceLine = true;
} else if ( debug.equals( BuildOptionsAdapter.DEBUG_VARS)) {
varAttr = true;
}
}
if (sourceLine) optionsToSet.put(CompilerOptions.OPTION_SourceFileAttribute,
CompilerOptions.GENERATE);
if (varAttr) optionsToSet.put(CompilerOptions.OPTION_LocalVariableAttribute,
CompilerOptions.GENERATE);
if (lineNo) optionsToSet.put(CompilerOptions.OPTION_LineNumberAttribute,
CompilerOptions.GENERATE);
}
//XXX we can't turn off import errors in 3.0 stream
// if ( options.getNoImportError() ) {
// javaOptions.put( CompilerOptions.OPTION_ReportInvalidImport,
// CompilerOptions.WARNING);
// }
if ( options.getPreserveAllLocals() ) {
optionsToSet.put( CompilerOptions.OPTION_PreserveUnusedLocal,
CompilerOptions.PRESERVE);
}
if ( !config.isIncrementalMode()
&& options.getIncrementalMode() ) {
config.setIncrementalMode(true);
}
config.getOptions().set(optionsToSet);
String toAdd = options.getNonStandardOptions();
return LangUtil.isEmpty(toAdd)
? true
: configureNonStandardOptions( config, toAdd, handler );
// ignored: lenient, porting, preprocess, strict, usejavac, workingdir
}
/**
* Helper method for configureBuildOptions
*/
private static void disableWarnings( Map options ) {
options.put(
CompilerOptions.OPTION_ReportOverridingPackageDefaultMethod,
CompilerOptions.IGNORE);
options.put(
CompilerOptions.OPTION_ReportMethodWithConstructorName,
CompilerOptions.IGNORE);
options.put(
CompilerOptions.OPTION_ReportDeprecation,
CompilerOptions.IGNORE);
options.put(
CompilerOptions.OPTION_ReportHiddenCatchBlock,
CompilerOptions.IGNORE);
options.put(
CompilerOptions.OPTION_ReportUnusedLocal,
CompilerOptions.IGNORE);
options.put(
CompilerOptions.OPTION_ReportUnusedParameter,
CompilerOptions.IGNORE);
options.put(
CompilerOptions.OPTION_ReportSyntheticAccessEmulation,
CompilerOptions.IGNORE);
options.put(
CompilerOptions.OPTION_ReportNonExternalizedStringLiteral,
CompilerOptions.IGNORE);
options.put(
CompilerOptions.OPTION_ReportAssertIdentifier,
CompilerOptions.IGNORE);
options.put(
CompilerOptions.OPTION_ReportUnusedImport,
CompilerOptions.IGNORE);
}
/**
* Helper method for configureBuildOptions
*/
private static void enableWarnings( Map options, Set warnings ) {
Iterator it = warnings.iterator();
while (it.hasNext() ) {
String thisWarning = (String) it.next();
if ( thisWarning.equals( BuildOptionsAdapter.WARN_ASSERT_IDENITIFIER )) {
options.put( CompilerOptions.OPTION_ReportAssertIdentifier,
CompilerOptions.WARNING );
} else if ( thisWarning.equals( BuildOptionsAdapter.WARN_CONSTRUCTOR_NAME )) {
options.put( CompilerOptions.OPTION_ReportMethodWithConstructorName,
CompilerOptions.WARNING );
} else if ( thisWarning.equals( BuildOptionsAdapter.WARN_DEPRECATION )) {
options.put( CompilerOptions.OPTION_ReportDeprecation,
CompilerOptions.WARNING );
} else if ( thisWarning.equals( BuildOptionsAdapter.WARN_MASKED_CATCH_BLOCKS )) {
options.put( CompilerOptions.OPTION_ReportHiddenCatchBlock,
CompilerOptions.WARNING );
} else if ( thisWarning.equals( BuildOptionsAdapter.WARN_PACKAGE_DEFAULT_METHOD )) {
options.put( CompilerOptions.OPTION_ReportOverridingPackageDefaultMethod,
CompilerOptions.WARNING );
} else if ( thisWarning.equals( BuildOptionsAdapter.WARN_SYNTHETIC_ACCESS )) {
options.put( CompilerOptions.OPTION_ReportSyntheticAccessEmulation,
CompilerOptions.WARNING );
} else if ( thisWarning.equals( BuildOptionsAdapter.WARN_UNUSED_ARGUMENTS )) {
options.put( CompilerOptions.OPTION_ReportUnusedParameter,
CompilerOptions.WARNING );
} else if ( thisWarning.equals( BuildOptionsAdapter.WARN_UNUSED_IMPORTS )) {
options.put( CompilerOptions.OPTION_ReportUnusedImport,
CompilerOptions.WARNING );
} else if ( thisWarning.equals( BuildOptionsAdapter.WARN_UNUSED_LOCALS )) {
options.put( CompilerOptions.OPTION_ReportUnusedLocal,
CompilerOptions.WARNING );
} else if ( thisWarning.equals( BuildOptionsAdapter.WARN_NLS )) {
options.put( CompilerOptions.OPTION_ReportNonExternalizedStringLiteral,
CompilerOptions.WARNING );
}
}
}
/** Local helper method for splitting option strings */
private static List tokenizeString(String str) {
List tokens = new ArrayList();
StringTokenizer tok = new StringTokenizer(str);
while ( tok.hasMoreTokens() ) {
tokens.add(tok.nextToken());
}
return tokens;
}
/**
* Helper method for configure build options.
* This reads all command-line options specified
* in the non-standard options text entry and
* sets any corresponding unset values in config.
* @return false if config failed
*/
private static boolean configureNonStandardOptions(
AjBuildConfig config,
String nonStdOptions,
IMessageHandler messageHandler ) {
if (LangUtil.isEmpty(nonStdOptions)) {
return true;
}
// Break a string into a string array of non-standard options.
// Allows for one option to include a ' '. i.e. assuming it has been quoted, it
// won't accidentally get treated as a pair of options (can be needed for xlint props file option)
List tokens = new ArrayList();
int ind = nonStdOptions.indexOf('\"');
int ind2 = nonStdOptions.indexOf('\"',ind+1);
if ((ind > -1) && (ind2 > -1)) { // dont tokenize within double quotes
String pre = nonStdOptions.substring(0,ind);
String quoted = nonStdOptions.substring(ind+1,ind2);
String post = nonStdOptions.substring(ind2+1,nonStdOptions.length());
tokens.addAll(tokenizeString(pre));
tokens.add(quoted);
tokens.addAll(tokenizeString(post));
} else {
tokens.addAll(tokenizeString(nonStdOptions));
}
String[] args = (String[])tokens.toArray(new String[]{});
// set the non-standard options in an alternate build config
// (we don't want to lose the settings we already have)
CountingMessageHandler counter
= CountingMessageHandler.makeCountingMessageHandler(messageHandler);
AjBuildConfig altConfig = AjdtCommand.genBuildConfig(args, counter);
if (counter.hasErrors()) {
return false;
}
// copy globals where local is not set
config.installGlobals(altConfig);
return true;
}
/**
* Add new options from the ProjectPropertiesAdapter to the configuration.
* <ul>
* <li>New list entries are added if not duplicates in,
* for classpath, aspectpath, injars, inpath and sourceroots</li>
* <li>New bootclasspath entries are ignored XXX</li>
* <li>Set only one new entry for output dir or output jar
* only if there is no output dir/jar entry in the config</li>
* </ul>
* Subsequent changes to the ProjectPropertiesAdapter will not affect
* the configuration.
* <p>Added by AMC 01.20.2003, bugzilla #29769
*/
private void configureProjectOptions( AjBuildConfig config, ProjectPropertiesAdapter properties ) {
// XXX no error handling in copying project properties
String propcp = properties.getClasspath(); // XXX omitting bootclasspath...
if (!LangUtil.isEmpty(propcp)) {
StringTokenizer st = new StringTokenizer(propcp, File.pathSeparator);
List configClasspath = config.getClasspath();
ArrayList toAdd = new ArrayList();
while (st.hasMoreTokens()) {
String entry = st.nextToken();
if (!configClasspath.contains(entry)) {
toAdd.add(entry);
}
}
if (0 < toAdd.size()) {
ArrayList both = new ArrayList(configClasspath.size() + toAdd.size());
both.addAll(configClasspath);
both.addAll(toAdd);
config.setClasspath(both);
Ajde.getDefault().logEvent("building with classpath: " + both);
}
}
// set outputdir and outputjar only if both not set
if ((null == config.getOutputDir() && (null == config.getOutputJar()))) {
String outPath = properties.getOutputPath();
if (!LangUtil.isEmpty(outPath)) {
config.setOutputDir(new File(outPath));
}
String outJar = properties.getOutJar();
if (!LangUtil.isEmpty(outJar)) {
config.setOutputJar(new File( outJar ) );
}
}
join(config.getSourceRoots(), properties.getSourceRoots());
join(config.getInJars(), properties.getInJars());
join(config.getInpath(),properties.getInpath());
config.setSourcePathResources(properties.getSourcePathResources());
join(config.getAspectpath(), properties.getAspectPath());
}
void join(Collection target, Collection source) { // XXX dup Util
if ((null == target) || (null == source)) {
return;
}
for (Iterator iter = source.iterator(); iter.hasNext();) {
Object next = iter.next();
if (! target.contains(next)) {
target.add(next);
}
}
}
private void init() {
if (!initialized) { // XXX plug into AJDE initialization
// Ajde.getDefault().setErrorHandler(new DebugErrorHandler());
this.messageHandler = new MessageHandlerAdapter();
buildManager = new AjBuildManager(messageHandler);
// XXX need to remove the properties file each time!
initialized = true;
}
}
class MessageHandlerAdapter extends MessageHandler {
private TaskListManager taskListManager;
private BuildNotifierAdapter buildNotifierAdapter;
public MessageHandlerAdapter() {
this.taskListManager = Ajde.getDefault().getTaskListManager();
}
public boolean handleMessage(IMessage message) throws AbortException {
IMessage.Kind kind = message.getKind();
if (isIgnoring(kind)
|| (!showInfoMessages && IMessage.INFO.equals(kind))) {
return true;
}
taskListManager.addSourcelineTask(message);
return super.handleMessage(message); // also store...
}
// --------------- adje methods
public void setBuildNotifierAdapter(BuildNotifierAdapter buildNotifierAdapter) {
this.buildNotifierAdapter = buildNotifierAdapter;
}
}
}
|
72,671
|
Bug 72671 Bootclasspath specification for compiling is not possible
|
I have following bug running eclipse 3.0 and ajdt 1.1.12 I have following class: import java.io.FileNotFoundException; import java.io.FileOutputStream; import org.w3c.dom.DOMConfiguration; import org.w3c.dom.DOMError; import org.w3c.dom.DOMErrorHandler; import org.w3c.dom.Document; import org.w3c.dom.DocumentFragment; import org.w3c.dom.NodeList; import org.w3c.dom.ls.DOMImplementationLS; import org.w3c.dom.ls.LSInput; import org.w3c.dom.ls.LSOutput; import org.w3c.dom.ls.LSParser; import com.dcbank.common.DOMImplementationLSSingleton; public class DOMHelper { public static final String CLASS_ID = "%full_filespec: DOMHelper.java~1:java:1 %"; public static void save(Document document, String filename) throws ClassNotFoundException, InstantiationException, IllegalAccessException, FileNotFoundException { document.normalizeDocument(); } } which compiles very fine with JDK 1.4.2_02 on Windows XP, as soon as the dom2-xml-apis.jar and dom3-xercesImpl.jar are added at the beginning of the jre container, or are included in the jar-library list before the system jar. As soon as I convert this project to an AspectJ project, the code does not compile anymore. The aspectJ compiler does not find the normalizeDocument, which is included in the one of the two additional jars. method any more. kind regards Arno Schmidmeier
|
resolved fixed
|
d1551bd
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:13:46Z
| 2004-08-26T11:33:20Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/ajc/BuildArgParser.java
|
/* *******************************************************************
* 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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.ajc;
import java.io.*;
import java.util.*;
import org.aspectj.ajdt.internal.core.builder.*;
import org.aspectj.bridge.*;
import org.aspectj.util.*;
import org.aspectj.weaver.Dump;
import org.aspectj.weaver.WeaverMessages;
import org.eclipse.jdt.core.compiler.InvalidInputException;
import org.eclipse.jdt.internal.compiler.batch.Main;
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
public class BuildArgParser extends Main {
private static final String BUNDLE_NAME = "org.aspectj.ajdt.ajc.messages";
private static boolean LOADED_BUNDLE = false;
static {
bundle = ResourceBundle.getBundle(BUNDLE_NAME);
if (!LOADED_BUNDLE) {
LOADED_BUNDLE = true;
}
}
/** to initialize super's PrintWriter but refer to underlying StringWriter */
private static class StringPrintWriter extends PrintWriter {
public final StringWriter stringWriter;
StringPrintWriter(StringWriter sw) {
super(sw);
this.stringWriter = sw;
}
}
/** @return multi-line String usage for the compiler */
public static String getUsage() {
return Main.bind("misc.usage");
}
public static String getXOptionUsage() {
return Main.bind("xoption.usage");
}
/**
* StringWriter sink for some errors.
* This only captures errors not handled by any IMessageHandler parameter
* and only when no PrintWriter is set in the constructor.
* XXX This relies on (Sun's) implementation of StringWriter,
* which returns the actual (not copy) internal StringBuffer.
*/
private final StringBuffer errorSink;
private IMessageHandler handler;
/**
* Overrides super's bundle.
*/
public BuildArgParser(PrintWriter writer, IMessageHandler handler) {
super(writer, writer, false);
if (writer instanceof StringPrintWriter) {
errorSink = ((StringPrintWriter) writer).stringWriter.getBuffer();
} else {
errorSink = null;
}
this.handler = handler;
}
/** Set up to capture messages using getOtherMessages(boolean) */
public BuildArgParser(IMessageHandler handler) {
this(new StringPrintWriter(new StringWriter()),handler);
}
/**
* Generate build configuration for the input args,
* passing to handler any error messages.
* @param args the String[] arguments for the build configuration
* @return AjBuildConfig per args,
* which will be invalid unless there are no handler errors.
*/
public AjBuildConfig genBuildConfig(String[] args) {
AjBuildConfig config = new AjBuildConfig();
populateBuildConfig(config, args, true, null);
return config;
}
/**
* Generate build configuration for the input args,
* passing to handler any error messages.
* @param args the String[] arguments for the build configuration
* @param setClasspath determines if the classpath should be parsed and set on the build configuration
* @param configFile can be null
* @return AjBuildConfig per args,
* which will be invalid unless there are no handler errors.
*/
public AjBuildConfig populateBuildConfig(AjBuildConfig buildConfig, String[] args, boolean setClasspath, File configFile) {
Dump.saveCommandLine(args);
buildConfig.setConfigFile(configFile);
try {
// sets filenames to be non-null in order to make sure that file paramters are ignored
super.filenames = new String[] { "" };
AjcConfigParser parser = new AjcConfigParser(buildConfig, handler);
parser.parseCommandLine(args);
boolean swi = buildConfig.getShowWeavingInformation();
// Now jump through firey hoops to turn them on/off
if (handler instanceof CountingMessageHandler) {
IMessageHandler delegate = ((CountingMessageHandler)handler).delegate;
// Without dontIgnore() on the IMessageHandler interface, we have to do this *blurgh*
if (delegate instanceof MessageHandler) {
if (swi)
((MessageHandler)delegate).dontIgnore(IMessage.WEAVEINFO);
else
((MessageHandler)delegate).ignore(IMessage.WEAVEINFO);
}
}
boolean incrementalMode = buildConfig.isIncrementalMode()
|| buildConfig.isIncrementalFileMode();
List fileList = new ArrayList();
List files = parser.getFiles();
if (!LangUtil.isEmpty(files)) {
if (incrementalMode) {
MessageUtil.error(handler, "incremental mode only handles source files using -sourceroots");
} else {
fileList.addAll(files);
}
}
List javaArgList = new ArrayList();
// disable all special eclipse warnings by default - why???
//??? might want to instead override getDefaultOptions()
javaArgList.add("-warn:none");
// these next four lines are some nonsense to fool the eclipse batch compiler
// without these it will go searching for reasonable values from properties
//TODO fix org.eclipse.jdt.internal.compiler.batch.Main so this hack isn't needed
javaArgList.add("-classpath");
javaArgList.add(System.getProperty("user.dir"));
javaArgList.add("-bootclasspath");
javaArgList.add(System.getProperty("user.dir"));
javaArgList.addAll(parser.getUnparsedArgs());
super.configure((String[])javaArgList.toArray(new String[javaArgList.size()]));
if (!proceed) {
buildConfig.doNotProceed();
return buildConfig;
}
if (buildConfig.getSourceRoots() != null) {
for (Iterator i = buildConfig.getSourceRoots().iterator(); i.hasNext(); ) {
fileList.addAll(collectSourceRootFiles((File)i.next()));
}
}
buildConfig.setFiles(fileList);
if (destinationPath != null) { // XXX ?? unparsed but set?
buildConfig.setOutputDir(new File(destinationPath));
}
if (setClasspath) {
buildConfig.setClasspath(getClasspath(parser));
}
if (incrementalMode
&& (0 == buildConfig.getSourceRoots().size())) {
MessageUtil.error(handler, "specify a source root when in incremental mode");
}
/*
* Ensure we don't overwrite injars, inpath or aspectpath with outjar
* bug-71339
*/
File outjar = buildConfig.getOutputJar();
if (outjar != null) {
/* Search injars */
for (Iterator i = buildConfig.getInJars().iterator(); i.hasNext(); ) {
File injar = (File)i.next();
if (injar.equals(outjar)) {
String message = WeaverMessages.format(WeaverMessages.OUTJAR_IN_INPUT_PATH);
MessageUtil.error(handler,message);
}
}
/* Search inpath */
for (Iterator i = buildConfig.getInpath().iterator(); i.hasNext(); ) {
File inPathElement = (File)i.next();
if (!inPathElement.isDirectory() && inPathElement.equals(outjar)) {
String message = WeaverMessages.format(WeaverMessages.OUTJAR_IN_INPUT_PATH);
MessageUtil.error(handler,message);
}
}
/* Search aspectpath */
for (Iterator i = buildConfig.getAspectpath().iterator(); i.hasNext(); ) {
File pathElement = (File)i.next();
if (!pathElement.isDirectory() && pathElement.equals(outjar)) {
String message = WeaverMessages.format(WeaverMessages.OUTJAR_IN_INPUT_PATH);
MessageUtil.error(handler,message);
}
}
}
setDebugOptions();
buildConfig.getOptions().set(options);
} catch (InvalidInputException iie) {
ISourceLocation location = null;
if (buildConfig.getConfigFile() != null) {
location = new SourceLocation(buildConfig.getConfigFile(), 0);
}
IMessage m = new Message(iie.getMessage(), IMessage.ERROR, null, location);
handler.handleMessage(m);
}
return buildConfig;
}
// from super...
public void printVersion() {
System.err.println("AspectJ Compiler " + Version.text + " built on " + Version.time_text); //$NON-NLS-1$
System.err.flush();
}
public void printUsage() {
System.out.println(bind("misc.usage")); //$NON-NLS-1$
System.out.flush();
}
/**
* Get messages not dumped to handler or any PrintWriter.
* @param flush if true, empty errors
* @return null if none, String otherwise
* @see BuildArgParser()
*/
public String getOtherMessages(boolean flush) {
if (null == errorSink) {
return null;
}
String result = errorSink.toString().trim();
if (0 == result.length()) {
result = null;
}
if (flush) {
errorSink.setLength(0);
}
return result;
}
private void setDebugOptions() {
options.put(
CompilerOptions.OPTION_LocalVariableAttribute,
CompilerOptions.GENERATE);
options.put(
CompilerOptions.OPTION_LineNumberAttribute,
CompilerOptions.GENERATE);
options.put(
CompilerOptions.OPTION_SourceFileAttribute,
CompilerOptions.GENERATE);
}
private Collection collectSourceRootFiles(File dir) {
return Arrays.asList(FileUtil.listFiles(dir, FileUtil.aspectjSourceFileFilter));
}
/**
* If the classpath is not set, we use the environment's java.class.path, but remove
* the aspectjtools.jar entry from that list in order to prevent wierd bootstrap issues
* (refer to bug#39959).
*/
public List getClasspath(AjcConfigParser parser) {
List ret = new ArrayList();
if (parser.bootclasspath == null) {
addClasspath(System.getProperty("sun.boot.class.path", ""), ret);
} else {
addClasspath(parser.bootclasspath, ret);
}
String extdirs = parser.extdirs;
if (extdirs == null) {
extdirs = System.getProperty("java.ext.dirs", "");
}
addExtDirs(extdirs, ret);
if (parser.classpath == null) {
addClasspath(System.getProperty("java.class.path", ""), ret);
List fixedList = new ArrayList();
for (Iterator it = ret.iterator(); it.hasNext(); ) {
String entry = (String)it.next();
if (!entry.endsWith("aspectjtools.jar")) {
fixedList.add(entry);
}
}
ret = fixedList;
} else {
addClasspath(parser.classpath, ret);
}
//??? eclipse seems to put outdir on the classpath
//??? we're brave and believe we don't need it
return ret;
}
private void addExtDirs(String extdirs, List classpathCollector) {
StringTokenizer tokenizer = new StringTokenizer(extdirs, File.pathSeparator);
while (tokenizer.hasMoreTokens()) {
// classpathCollector.add(tokenizer.nextToken());
File dirFile = new File((String)tokenizer.nextToken());
if (dirFile.canRead() && dirFile.isDirectory()) {
File[] files = dirFile.listFiles(FileUtil.ZIP_FILTER);
for (int i = 0; i < files.length; i++) {
classpathCollector.add(files[i].getAbsolutePath());
}
} else {
// XXX alert on invalid -extdirs entries
}
}
}
private void addClasspath(String classpath, List classpathCollector) {
StringTokenizer tokenizer = new StringTokenizer(classpath, File.pathSeparator);
while (tokenizer.hasMoreTokens()) {
classpathCollector.add(tokenizer.nextToken());
}
}
private class AjcConfigParser extends ConfigParser {
private String bootclasspath = null;
private String classpath = null;
private String extdirs = null;
private List unparsedArgs = new ArrayList();
private AjBuildConfig buildConfig;
private IMessageHandler handler;
public AjcConfigParser(AjBuildConfig buildConfig, IMessageHandler handler) {
this.buildConfig = buildConfig;
this.handler = handler;
}
public List getUnparsedArgs() {
return unparsedArgs;
}
/**
* Extract AspectJ-specific options (except for argfiles).
* Caller should warn when sourceroots is empty but in
* incremental mode.
* Signals warnings or errors through handler set in constructor.
*/
public void parseOption(String arg, LinkedList args) { // XXX use ListIterator.remove()
int nextArgIndex = args.indexOf(arg)+1; // XXX assumes unique
// trim arg?
if (LangUtil.isEmpty(arg)) {
showWarning("empty arg found");
} else if (arg.equals("-inpath")) {;
if (args.size() > nextArgIndex) {
// buildConfig.getAjOptions().put(AjCompilerOptions.OPTION_Inpath, CompilerOptions.PRESERVE);
List inPath = buildConfig.getInpath();
StringTokenizer st = new StringTokenizer(
((ConfigParser.Arg)args.get(nextArgIndex)).getValue(),
File.pathSeparator);
while (st.hasMoreTokens()) {
String filename = st.nextToken();
File file = makeFile(filename);
if (file.exists() && FileUtil.hasZipSuffix(filename)) {
inPath.add(file);
} else {
if (file.isDirectory()) {
inPath.add(file);
} else
showError("bad inpath component: " + filename);
}
}
buildConfig.setInPath(inPath);
args.remove(args.get(nextArgIndex));
}
} else if (arg.equals("-injars")) {;
if (args.size() > nextArgIndex) {
// buildConfig.getAjOptions().put(AjCompilerOptions.OPTION_InJARs, CompilerOptions.PRESERVE);
StringTokenizer st = new StringTokenizer(
((ConfigParser.Arg)args.get(nextArgIndex)).getValue(),
File.pathSeparator);
while (st.hasMoreTokens()) {
String filename = st.nextToken();
File jarFile = makeFile(filename);
if (jarFile.exists() && FileUtil.hasZipSuffix(filename)) {
buildConfig.getInJars().add(jarFile);
} else {
File dirFile = makeFile(filename);
if (dirFile.isDirectory()) {
buildConfig.getInJars().add(dirFile);
} else
showError("bad injar: " + filename);
}
}
args.remove(args.get(nextArgIndex));
}
} else if (arg.equals("-aspectpath")) {;
if (args.size() > nextArgIndex) {
StringTokenizer st = new StringTokenizer(
((ConfigParser.Arg)args.get(nextArgIndex)).getValue(),
File.pathSeparator);
while (st.hasMoreTokens()) {
String filename = st.nextToken();
File jarFile = makeFile(filename);
if (jarFile.exists() && FileUtil.hasZipSuffix(filename)) {
buildConfig.getAspectpath().add(jarFile);
} else {
showError("bad aspectpath: " + filename);
}
}
args.remove(args.get(nextArgIndex));
}
} else if (arg.equals("-sourceroots")) {
if (args.size() > nextArgIndex) {
List sourceRoots = new ArrayList();
StringTokenizer st = new StringTokenizer(
((ConfigParser.Arg)args.get(nextArgIndex)).getValue(),
File.pathSeparator);
while (st.hasMoreTokens()) {
File f = makeFile(st.nextToken());
if (f.isDirectory() && f.canRead()) {
sourceRoots.add(f);
} else {
showError("bad sourceroot: " + f);
}
}
if (0 < sourceRoots.size()) {
buildConfig.setSourceRoots(sourceRoots);
}
args.remove(args.get(nextArgIndex));
} else {
showError("-sourceroots requires list of directories");
}
} else if (arg.equals("-outjar")) {
if (args.size() > nextArgIndex) {
// buildConfig.getAjOptions().put(AjCompilerOptions.OPTION_OutJAR, CompilerOptions.GENERATE);
File jarFile = makeFile(((ConfigParser.Arg)args.get(nextArgIndex)).getValue());
if (FileUtil.hasZipSuffix(jarFile)) {
try {
if (!jarFile.exists()) {
jarFile.createNewFile();
}
buildConfig.setOutputJar(jarFile);
} catch (IOException ioe) {
showError("unable to create outjar file: " + jarFile);
}
} else {
showError("invalid -outjar file: " + jarFile);
}
args.remove(args.get(nextArgIndex));
} else {
showError("-outjar requires jar path argument");
}
} else if (arg.equals("-incremental")) {
buildConfig.setIncrementalMode(true);
} else if (arg.equals("-XincrementalFile")) {
if (args.size() > nextArgIndex) {
File file = makeFile(((ConfigParser.Arg)args.get(nextArgIndex)).getValue());
buildConfig.setIncrementalFile(file);
if (!file.canRead()) {
showError("bad -XincrementalFile : " + file);
// if not created before recompile test, stop after first compile
}
args.remove(args.get(nextArgIndex));
} else {
showError("-XincrementalFile requires file argument");
}
} else if (arg.equals("-emacssym")) {
buildConfig.setEmacsSymMode(true);
buildConfig.setGenerateModelMode(true);
} else if (arg.equals("-XjavadocsInModel")) {
buildConfig.setGenerateModelMode(true);
buildConfig.setGenerateJavadocsInModelMode(true);
} else if (arg.equals("-noweave") || arg.equals( "-XnoWeave")) {
buildConfig.setNoWeave(true);
} else if (arg.equals("-XserializableAspects")) {
buildConfig.setXserializableAspects(true);
} else if (arg.equals("-XlazyTjp")) {
buildConfig.setXlazyTjp(true);
} else if (arg.startsWith("-Xreweavable")) {
buildConfig.setXreweavable(true);
if (arg.endsWith(":compress")) {
buildConfig.setXreweavableCompressClasses(true);
}
} else if (arg.equals("-XnoInline")) {
buildConfig.setXnoInline(true);
} else if (arg.startsWith("-showWeaveInfo")) {
buildConfig.setShowWeavingInformation(true);
} else if (arg.equals("-Xlintfile")) {
if (args.size() > nextArgIndex) {
File lintSpecFile = makeFile(((ConfigParser.Arg)args.get(nextArgIndex)).getValue());
// XXX relax restriction on props file suffix?
if (lintSpecFile.canRead() && lintSpecFile.getName().endsWith(".properties")) {
buildConfig.setLintSpecFile(lintSpecFile);
} else {
showError("bad -Xlintfile file: " + lintSpecFile);
buildConfig.setLintSpecFile(null);
}
args.remove(args.get(nextArgIndex));
} else {
showError("-Xlintfile requires .properties file argument");
}
} else if (arg.equals("-Xlint")) {
// buildConfig.getAjOptions().put(
// AjCompilerOptions.OPTION_Xlint,
// CompilerOptions.GENERATE);
buildConfig.setLintMode(AjBuildConfig.AJLINT_DEFAULT);
} else if (arg.startsWith("-Xlint:")) {
if (7 < arg.length()) {
buildConfig.setLintMode(arg.substring(7));
} else {
showError("invalid lint option " + arg);
}
} else if (arg.equals("-bootclasspath")) {
if (args.size() > nextArgIndex) {
String bcpArg = ((ConfigParser.Arg)args.get(nextArgIndex)).getValue();
StringBuffer bcp = new StringBuffer();
StringTokenizer strTok = new StringTokenizer(bcpArg,File.pathSeparator);
while (strTok.hasMoreTokens()) {
bcp.append(makeFile(strTok.nextToken()));
if (strTok.hasMoreTokens()) {
bcp.append(File.pathSeparator);
}
}
bootclasspath = bcp.toString();
args.remove(args.get(nextArgIndex));
} else {
showError("-bootclasspath requires classpath entries");
}
} else if (arg.equals("-classpath")) {
if (args.size() > nextArgIndex) {
String cpArg = ((ConfigParser.Arg)args.get(nextArgIndex)).getValue();
StringBuffer cp = new StringBuffer();
StringTokenizer strTok = new StringTokenizer(cpArg,File.pathSeparator);
while (strTok.hasMoreTokens()) {
cp.append(makeFile(strTok.nextToken()));
if (strTok.hasMoreTokens()) {
cp.append(File.pathSeparator);
}
}
classpath = cp.toString();
args.remove(args.get(nextArgIndex));
} else {
showError("-classpath requires classpath entries");
}
} else if (arg.equals("-extdirs")) {
if (args.size() > nextArgIndex) {
String extdirsArg = ((ConfigParser.Arg)args.get(nextArgIndex)).getValue();
StringBuffer ed = new StringBuffer();
StringTokenizer strTok = new StringTokenizer(extdirsArg,File.pathSeparator);
while (strTok.hasMoreTokens()) {
ed.append(makeFile(strTok.nextToken()));
if (strTok.hasMoreTokens()) {
ed.append(File.pathSeparator);
}
}
extdirs = ed.toString();
args.remove(args.get(nextArgIndex));
} else {
showError("-extdirs requires list of external directories");
}
// error on directory unless -d, -{boot}classpath, or -extdirs
} else if (arg.equals("-d")) {
dirLookahead(arg, args, nextArgIndex);
// } else if (arg.equals("-classpath")) {
// dirLookahead(arg, args, nextArgIndex);
// } else if (arg.equals("-bootclasspath")) {
// dirLookahead(arg, args, nextArgIndex);
// } else if (arg.equals("-extdirs")) {
// dirLookahead(arg, args, nextArgIndex);
} else if (new File(arg).isDirectory()) {
showError("dir arg not permitted: " + arg);
} else {
// argfile, @file parsed by superclass
// no eclipse options parsed:
// -d args, -help (handled),
// -classpath, -target, -1.3, -1.4, -source [1.3|1.4]
// -nowarn, -warn:[...], -deprecation, -noImportError,
// -proceedOnError, -g:[...], -preserveAllLocals,
// -referenceInfo, -encoding, -verbose, -log, -time
// -noExit, -repeat
unparsedArgs.add(arg);
}
}
protected void dirLookahead(String arg, LinkedList argList, int nextArgIndex) {
unparsedArgs.add(arg);
ConfigParser.Arg next = (ConfigParser.Arg) argList.get(nextArgIndex);
String value = next.getValue();
if (!LangUtil.isEmpty(value)) {
if (new File(value).isDirectory()) {
unparsedArgs.add(value);
argList.remove(next);
return;
}
}
}
public void showError(String message) {
ISourceLocation location = null;
if (buildConfig.getConfigFile() != null) {
location = new SourceLocation(buildConfig.getConfigFile(), 0);
}
IMessage errorMessage = new Message(CONFIG_MSG + message, IMessage.ERROR, null, location);
handler.handleMessage(errorMessage);
// MessageUtil.error(handler, CONFIG_MSG + message);
}
protected void showWarning(String message) {
ISourceLocation location = null;
if (buildConfig.getConfigFile() != null) {
location = new SourceLocation(buildConfig.getConfigFile(), 0);
}
IMessage errorMessage = new Message(CONFIG_MSG + message, IMessage.WARNING, null, location);
handler.handleMessage(errorMessage);
// MessageUtil.warn(handler, message);
}
protected File makeFile(File dir, String name) {
name = name.replace('/', File.separatorChar);
File ret = new File(name);
if (dir == null || ret.isAbsolute()) return ret;
try {
dir = dir.getCanonicalFile();
} catch (IOException ioe) { }
return new File(dir, name);
}
}
}
|
72,671
|
Bug 72671 Bootclasspath specification for compiling is not possible
|
I have following bug running eclipse 3.0 and ajdt 1.1.12 I have following class: import java.io.FileNotFoundException; import java.io.FileOutputStream; import org.w3c.dom.DOMConfiguration; import org.w3c.dom.DOMError; import org.w3c.dom.DOMErrorHandler; import org.w3c.dom.Document; import org.w3c.dom.DocumentFragment; import org.w3c.dom.NodeList; import org.w3c.dom.ls.DOMImplementationLS; import org.w3c.dom.ls.LSInput; import org.w3c.dom.ls.LSOutput; import org.w3c.dom.ls.LSParser; import com.dcbank.common.DOMImplementationLSSingleton; public class DOMHelper { public static final String CLASS_ID = "%full_filespec: DOMHelper.java~1:java:1 %"; public static void save(Document document, String filename) throws ClassNotFoundException, InstantiationException, IllegalAccessException, FileNotFoundException { document.normalizeDocument(); } } which compiles very fine with JDK 1.4.2_02 on Windows XP, as soon as the dom2-xml-apis.jar and dom3-xercesImpl.jar are added at the beginning of the jre container, or are included in the jar-library list before the system jar. As soon as I convert this project to an AspectJ project, the code does not compile anymore. The aspectJ compiler does not find the normalizeDocument, which is included in the one of the two additional jars. method any more. kind regards Arno Schmidmeier
|
resolved fixed
|
d1551bd
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:13:46Z
| 2004-08-26T11:33:20Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AjBuildConfig.java
|
/* *******************************************************************
* 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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* Adrian Colyer added constructor to populate javaOptions with
* default settings - 01.20.2003
* Bugzilla #29768, 29769
* ******************************************************************/
package org.aspectj.ajdt.internal.core.builder;
import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.aspectj.util.FileUtil;
/**
* All configuration information needed to run the AspectJ compiler.
* Compiler options (as opposed to path information) are held in an AjCompilerOptions instance
*/
public class AjBuildConfig { // XXX needs bootclasspath?
private boolean shouldProceed = true;
public static final String AJLINT_IGNORE = "ignore";
public static final String AJLINT_WARN = "warn";
public static final String AJLINT_ERROR = "error";
public static final String AJLINT_DEFAULT = "default";
private File outputDir;
private File outputJar;
private List/*File*/ sourceRoots = new ArrayList();
private List/*File*/ files = new ArrayList();
private List /*File*/ binaryFiles = new ArrayList(); // .class files in indirs...
private List/*File*/ inJars = new ArrayList();
private List/*File*/ inPath = new ArrayList();
private Map/*String->File*/ sourcePathResources = new HashMap();
private List/*File*/ aspectpath = new ArrayList();
private List/*String*/ classpath = new ArrayList();
private File configFile;
private String lintMode = AJLINT_DEFAULT;
private File lintSpecFile = null;
private AjCompilerOptions options;
/** if true, then global values override local when joining */
private boolean override = true;
// incremental variants handled by the compiler client, but parsed here
private boolean incrementalMode;
private File incrementalFile;
public static class BinarySourceFile {
public BinarySourceFile(File dir, File src) {
this.fromInPathDirectory = dir;
this.binSrc = src;
}
public File fromInPathDirectory;
public File binSrc;
public boolean equals(Object obj) {
if ((obj instanceof BinarySourceFile) &&
(obj != null)) {
BinarySourceFile other = (BinarySourceFile)obj;
return(binSrc.equals(other.binSrc));
}
return false;
}
public int hashCode() {
return binSrc != null ? binSrc.hashCode() : 0;
}
}
/**
* Intialises the javaOptions Map to hold the default
* JDT Compiler settings. Added by AMC 01.20.2003 in reponse
* to bug #29768 and enh. 29769.
* The settings here are duplicated from those set in
* org.eclipse.jdt.internal.compiler.batch.Main, but I've elected to
* copy them rather than refactor the JDT class since this keeps
* integration with future JDT releases easier (?).
*/
public AjBuildConfig( ) {
options = new AjCompilerOptions();
}
/**
* returned files includes <ul>
* <li>files explicitly listed on command-line</li>
* <li>files listed by reference in argument list files</li>
* <li>files contained in sourceRootDir if that exists</li>
* </ul>
*
* @return all source files that should be compiled.
*/
public List/*File*/ getFiles() {
return files;
}
/**
* returned files includes all .class files found in
* a directory on the inpath, but does not include
* .class files contained within jars.
*/
public List/*BinarySourceFile*/ getBinaryFiles() {
return binaryFiles;
}
public File getOutputDir() {
return outputDir;
}
public void setFiles(List files) {
this.files = files;
}
public void setOutputDir(File outputDir) {
this.outputDir = outputDir;
}
public AjCompilerOptions getOptions() {
return options;
}
/**
* This includes all entries from -bootclasspath, -extdirs, -classpath,
*/
public List getClasspath() { // XXX setters don't respect javadoc contract...
return classpath;
}
public void setClasspath(List classpath) {
this.classpath = classpath;
}
public File getOutputJar() {
return outputJar;
}
public List/*File*/ getInpath() {
// Elements of the list are either archives (jars/zips) or directories
return inPath;
}
public List/*File*/ getInJars() {
return inJars;
}
public Map getSourcePathResources() {
return sourcePathResources;
}
public void setOutputJar(File outputJar) {
this.outputJar = outputJar;
}
public void setInJars(List sourceJars) {
this.inJars = sourceJars;
}
public void setInPath(List dirsOrJars) {
inPath = dirsOrJars;
// remember all the class files in directories on the inpath
binaryFiles = new ArrayList();
FileFilter filter = new FileFilter() {
public boolean accept(File pathname) {
return pathname.getPath().endsWith(".class");
}};
for (Iterator iter = dirsOrJars.iterator(); iter.hasNext();) {
File inpathElement = (File) iter.next();
if (inpathElement.isDirectory()) {
File[] files = FileUtil.listFiles(inpathElement, filter);
for (int i = 0; i < files.length; i++) {
binaryFiles.add(new BinarySourceFile(inpathElement,files[i]));
}
}
}
}
public List getSourceRoots() {
return sourceRoots;
}
public void setSourceRoots(List sourceRootDir) {
this.sourceRoots = sourceRootDir;
}
public File getConfigFile() {
return configFile;
}
public void setConfigFile(File configFile) {
this.configFile = configFile;
}
public void setIncrementalMode(boolean incrementalMode) {
this.incrementalMode = incrementalMode;
}
public boolean isIncrementalMode() {
return incrementalMode;
}
public void setIncrementalFile(File incrementalFile) {
this.incrementalFile = incrementalFile;
}
public boolean isIncrementalFileMode() {
return (null != incrementalFile);
}
/**
* @return List (String) classpath of injars, inpath, aspectpath
* entries, specified classpath (bootclasspath, extdirs, and
* classpath), and output dir or jar
*/
public List getFullClasspath() {
List full = new ArrayList();
for (Iterator i = inJars.iterator(); i.hasNext(); ) {
full.add(((File)i.next()).getAbsolutePath());
}
for (Iterator i = inPath.iterator();i.hasNext();) {
full.add(((File)i.next()).getAbsolutePath());
}
for (Iterator i = aspectpath.iterator(); i.hasNext(); ) {
full.add(((File)i.next()).getAbsolutePath());
}
full.addAll(getClasspath());
// if (null != outputDir) {
// full.add(outputDir.getAbsolutePath());
// } else if (null != outputJar) {
// full.add(outputJar.getAbsolutePath());
// }
return full;
}
public File getLintSpecFile() {
return lintSpecFile;
}
public void setLintSpecFile(File lintSpecFile) {
this.lintSpecFile = lintSpecFile;
}
public List getAspectpath() {
return aspectpath;
}
public void setAspectpath(List aspectpath) {
this.aspectpath = aspectpath;
}
/** @return true if any config file, sourceroots, sourcefiles, injars or inpath */
public boolean hasSources() {
return ((null != configFile)
|| (0 < sourceRoots.size())
|| (0 < files.size())
|| (0 < inJars.size())
|| (0 < inPath.size())
);
}
// /** @return null if no errors, String errors otherwise */
// public String configErrors() {
// StringBuffer result = new StringBuffer();
// // ok, permit both. sigh.
//// if ((null != outputDir) && (null != outputJar)) {
//// result.append("specified both outputDir and outputJar");
//// }
// // incremental => only sourceroots
// //
// return (0 == result.length() ? null : result.toString());
// }
/**
* Install global values into local config
* unless values conflict:
* <ul>
* <li>Collections are unioned</li>
* <li>values takes local value unless default and global set</li>
* <li>this only sets one of outputDir and outputJar as needed</li>
* <ul>
* This also configures super if javaOptions change.
* @param global the AjBuildConfig to read globals from
*/
public void installGlobals(AjBuildConfig global) { // XXX relies on default values
// don't join the options - they already have defaults taken care of.
// Map optionsMap = options.getMap();
// join(optionsMap,global.getOptions().getMap());
// options.set(optionsMap);
join(aspectpath, global.aspectpath);
join(classpath, global.classpath);
if (null == configFile) {
configFile = global.configFile; // XXX correct?
}
if (!isEmacsSymMode() && global.isEmacsSymMode()) {
setEmacsSymMode(true);
}
join(files, global.files);
if (!isGenerateModelMode() && global.isGenerateModelMode()) {
setGenerateModelMode(true);
}
if (null == incrementalFile) {
incrementalFile = global.incrementalFile;
}
if (!incrementalMode && global.incrementalMode) {
incrementalMode = true;
}
join(inJars, global.inJars);
join(inPath, global.inPath);
if ((null == lintMode)
|| (AJLINT_DEFAULT.equals(lintMode))) {
setLintMode(global.lintMode);
}
if (null == lintSpecFile) {
lintSpecFile = global.lintSpecFile;
}
if (!isNoWeave() && global.isNoWeave()) {
setNoWeave(true);
}
if ((null == outputDir) && (null == outputJar)) {
if (null != global.outputDir) {
outputDir = global.outputDir;
}
if (null != global.outputJar) {
outputJar = global.outputJar;
}
}
join(sourceRoots, global.sourceRoots);
if (!isXnoInline() && global.isXnoInline()) {
setXnoInline(true);
}
if (!isXserializableAspects() && global.isXserializableAspects()) {
setXserializableAspects(true);
}
if (!isXlazyTjp() && global.isXlazyTjp()) {
setXlazyTjp(true);
}
if (!isXreweavable() && global.isXreweavable()) {
setXreweavable(true);
}
if (!getXreweavableCompressClasses() && global.getXreweavableCompressClasses()) {
setXreweavableCompressClasses(true);
}
}
void join(Collection local, Collection global) {
for (Iterator iter = global.iterator(); iter.hasNext();) {
Object next = iter.next();
if (!local.contains(next)) {
local.add(next);
}
}
}
void join(Map local, Map global) {
for (Iterator iter = global.keySet().iterator(); iter.hasNext();) {
Object key = iter.next();
if (override || (null == local.get(key))) { //
Object value = global.get(key);
if (null != value) {
local.put(key, value);
}
}
}
}
public void setSourcePathResources(Map map) {
sourcePathResources = map;
}
/**
* used to indicate whether to proceed after parsing config
*/
public boolean shouldProceed() {
return shouldProceed;
}
public void doNotProceed() {
shouldProceed = false;
}
public String getLintMode() {
return lintMode;
}
// options...
public void setLintMode(String lintMode) {
this.lintMode = lintMode;
String lintValue = null;
if (AJLINT_IGNORE.equals(lintMode)) {
lintValue = AjCompilerOptions.IGNORE;
} else if (AJLINT_WARN.equals(lintMode)) {
lintValue = AjCompilerOptions.WARNING;
} else if (AJLINT_ERROR.equals(lintMode)) {
lintValue = AjCompilerOptions.ERROR;
}
if (lintValue != null) {
Map lintOptions = new HashMap();
lintOptions.put(AjCompilerOptions.OPTION_ReportInvalidAbsoluteTypeName,lintValue);
lintOptions.put(AjCompilerOptions.OPTION_ReportInvalidWildcardTypeName,lintValue);
lintOptions.put(AjCompilerOptions.OPTION_ReportUnresolvableMember,lintValue);
lintOptions.put(AjCompilerOptions.OPTION_ReportTypeNotExposedToWeaver,lintValue);
lintOptions.put(AjCompilerOptions.OPTION_ReportShadowNotInStructure,lintValue);
lintOptions.put(AjCompilerOptions.OPTION_ReportUnmatchedSuperTypeInCall,lintValue);
lintOptions.put(AjCompilerOptions.OPTION_ReportCannotImplementLazyTJP,lintValue);
lintOptions.put(AjCompilerOptions.OPTION_ReportNeedSerialVersionUIDField,lintValue);
lintOptions.put(AjCompilerOptions.OPTION_ReportIncompatibleSerialVersion,lintValue);
options.set(lintOptions);
}
}
public boolean isNoWeave() {
return options.noWeave;
}
public void setNoWeave(boolean noWeave) {
options.noWeave = noWeave;
}
public boolean isXserializableAspects() {
return options.xSerializableAspects;
}
public void setXserializableAspects(boolean xserializableAspects) {
options.xSerializableAspects = xserializableAspects;
}
public boolean isXnoInline() {
return options.xNoInline;
}
public void setXnoInline(boolean xnoInline) {
options.xNoInline = xnoInline;
}
public boolean isXlazyTjp() {
return options.xLazyThisJoinPoint;
}
public void setXlazyTjp(boolean b) {
options.xLazyThisJoinPoint = b;
}
public void setXreweavable(boolean b) {
options.xReweavable = b;
}
public boolean isXreweavable() {
return options.xReweavable;
}
public void setXreweavableCompressClasses(boolean b) {
options.xReweavableCompress = b;
}
public boolean getXreweavableCompressClasses() {
return options.xReweavableCompress;
}
public boolean isGenerateJavadocsInModelMode() {
return options.generateJavaDocsInModel;
}
public void setGenerateJavadocsInModelMode(
boolean generateJavadocsInModelMode) {
options.generateJavaDocsInModel = generateJavadocsInModelMode;
}
public boolean isEmacsSymMode() {
return options.generateEmacsSymFiles;
}
public void setEmacsSymMode(boolean emacsSymMode) {
options.generateEmacsSymFiles = emacsSymMode;
}
public boolean isGenerateModelMode() {
return options.generateModel;
}
public void setGenerateModelMode(boolean structureModelMode) {
options.generateModel = structureModelMode;
}
public void setShowWeavingInformation(boolean b) {
options.showWeavingInformation = true;
}
public boolean getShowWeavingInformation() {
return options.showWeavingInformation;
}
}
|
72,671
|
Bug 72671 Bootclasspath specification for compiling is not possible
|
I have following bug running eclipse 3.0 and ajdt 1.1.12 I have following class: import java.io.FileNotFoundException; import java.io.FileOutputStream; import org.w3c.dom.DOMConfiguration; import org.w3c.dom.DOMError; import org.w3c.dom.DOMErrorHandler; import org.w3c.dom.Document; import org.w3c.dom.DocumentFragment; import org.w3c.dom.NodeList; import org.w3c.dom.ls.DOMImplementationLS; import org.w3c.dom.ls.LSInput; import org.w3c.dom.ls.LSOutput; import org.w3c.dom.ls.LSParser; import com.dcbank.common.DOMImplementationLSSingleton; public class DOMHelper { public static final String CLASS_ID = "%full_filespec: DOMHelper.java~1:java:1 %"; public static void save(Document document, String filename) throws ClassNotFoundException, InstantiationException, IllegalAccessException, FileNotFoundException { document.normalizeDocument(); } } which compiles very fine with JDK 1.4.2_02 on Windows XP, as soon as the dom2-xml-apis.jar and dom3-xercesImpl.jar are added at the beginning of the jre container, or are included in the jar-library list before the system jar. As soon as I convert this project to an AspectJ project, the code does not compile anymore. The aspectJ compiler does not find the normalizeDocument, which is included in the one of the two additional jars. method any more. kind regards Arno Schmidmeier
|
resolved fixed
|
d1551bd
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:13:46Z
| 2004-08-26T11:33:20Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AjBuildManager.java
|
/* *******************************************************************
* 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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.core.builder;
import java.io.*;
import java.util.*;
import java.util.jar.*;
import java.util.zip.ZipEntry;
import org.aspectj.ajdt.internal.compiler.AjCompilerAdapter;
import org.aspectj.ajdt.internal.compiler.IBinarySourceProvider;
import org.aspectj.ajdt.internal.compiler.IIntermediateResultsRequestor;
import org.aspectj.ajdt.internal.compiler.IOutputClassFileNameProvider;
import org.aspectj.ajdt.internal.compiler.InterimCompilationResult;
import org.aspectj.ajdt.internal.compiler.lookup.*;
import org.aspectj.ajdt.internal.compiler.problem.AjProblemReporter;
import org.aspectj.asm.*;
//import org.aspectj.asm.internal.*;
import org.aspectj.asm.internal.ProgramElement;
import org.aspectj.bridge.*;
import org.aspectj.util.FileUtil;
import org.aspectj.weaver.Dump;
import org.aspectj.weaver.World;
import org.aspectj.weaver.bcel.*;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.jdt.core.compiler.*;
import org.eclipse.jdt.internal.compiler.*;
import org.eclipse.jdt.internal.compiler.batch.*;
import org.eclipse.jdt.internal.compiler.batch.FileSystem;
import org.eclipse.jdt.internal.compiler.env.*;
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
import org.eclipse.jdt.internal.compiler.parser.Parser;
import org.eclipse.jdt.internal.compiler.problem.AbortCompilation;
import org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory;
//import org.eclipse.jdt.internal.compiler.util.HashtableOfObject;
public class AjBuildManager implements IOutputClassFileNameProvider,IBinarySourceProvider,ICompilerAdapterFactory {
private static final String CANT_WRITE_RESULT = "unable to write compilation result";
private static final String MANIFEST_NAME = "META-INF/MANIFEST.MF";
static final boolean COPY_INPATH_DIR_RESOURCES = false;
static final boolean FAIL_IF_RUNTIME_NOT_FOUND = false;
private static final FileFilter binarySourceFilter =
new FileFilter() {
public boolean accept(File f) {
return f.getName().endsWith(".class");
}};
/**
* This builder is static so that it can be subclassed and reset. However, note
* that there is only one builder present, so if two extendsion reset it, only
* the latter will get used.
*/
private static AsmHierarchyBuilder asmHierarchyBuilder = new AsmHierarchyBuilder();
private IProgressListener progressListener = null;
private int compiledCount;
private int sourceFileCount;
private JarOutputStream zos;
private boolean batchCompile = true;
private INameEnvironment environment;
private Map /* String -> List<UCF>*/ binarySourcesForTheNextCompile = new HashMap();
private IHierarchy structureModel;
public AjBuildConfig buildConfig;
AjState state = new AjState(this);
BcelWeaver bcelWeaver;
public BcelWorld bcelWorld;
public CountingMessageHandler handler;
public AjBuildManager(IMessageHandler holder) {
super();
this.handler = CountingMessageHandler.makeCountingMessageHandler(holder);
}
/** @return true if we should generate a model as a side-effect */
public boolean doGenerateModel() {
return buildConfig.isGenerateModelMode();
}
public boolean batchBuild(
AjBuildConfig buildConfig,
IMessageHandler baseHandler)
throws IOException, AbortException {
return doBuild(buildConfig, baseHandler, true);
}
public boolean incrementalBuild(
AjBuildConfig buildConfig,
IMessageHandler baseHandler)
throws IOException, AbortException {
return doBuild(buildConfig, baseHandler, false);
}
/** @throws AbortException if check for runtime fails */
protected boolean doBuild(
AjBuildConfig buildConfig,
IMessageHandler baseHandler,
boolean batch) throws IOException, AbortException {
boolean ret = true;
batchCompile = batch;
try {
if (batch) {
this.state = new AjState(this);
}
boolean canIncremental = state.prepareForNextBuild(buildConfig);
if (!canIncremental && !batch) { // retry as batch?
return doBuild(buildConfig, baseHandler, true);
}
this.handler =
CountingMessageHandler.makeCountingMessageHandler(baseHandler);
// XXX duplicate, no? remove?
String check = checkRtJar(buildConfig);
if (check != null) {
if (FAIL_IF_RUNTIME_NOT_FOUND) {
MessageUtil.error(handler, check);
return false;
} else {
MessageUtil.warn(handler, check);
}
}
// if (batch) {
setBuildConfig(buildConfig);
//}
if (batch || !AsmManager.attemptIncrementalModelRepairs) {
// if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) {
setupModel(buildConfig);
// }
}
if (batch) {
initBcelWorld(handler);
}
if (handler.hasErrors()) {
return false;
}
if (buildConfig.getOutputJar() != null) {
if (!openOutputStream(buildConfig.getOutputJar())) return false;
}
if (batch) {
// System.err.println("XXXX batch: " + buildConfig.getFiles());
if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) {
bcelWorld.setModel(AsmManager.getDefault().getHierarchy());
// in incremental build, only get updated model?
}
binarySourcesForTheNextCompile = state.getBinaryFilesToCompile(true);
performCompilation(buildConfig.getFiles());
if (handler.hasErrors()) {
return false;
}
if (AsmManager.isReporting())
AsmManager.getDefault().reportModelInfo("After a batch build");
} else {
// done already?
// if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) {
// bcelWorld.setModel(StructureModelManager.INSTANCE.getStructureModel());
// }
// System.err.println("XXXX start inc ");
binarySourcesForTheNextCompile = state.getBinaryFilesToCompile(true);
List files = state.getFilesToCompile(true);
if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode())
if (AsmManager.attemptIncrementalModelRepairs)
AsmManager.getDefault().processDelta(files,state.addedFiles,state.deletedFiles);
boolean hereWeGoAgain = !(files.isEmpty() && binarySourcesForTheNextCompile.isEmpty());
for (int i = 0; (i < 5) && hereWeGoAgain; i++) {
// System.err.println("XXXX inc: " + files);
performCompilation(files);
if (handler.hasErrors() || (progressListener!=null && progressListener.isCancelledRequested())) {
return false;
}
binarySourcesForTheNextCompile = state.getBinaryFilesToCompile(false);
files = state.getFilesToCompile(false);
hereWeGoAgain = !(files.isEmpty() && binarySourcesForTheNextCompile.isEmpty());
// TODO Andy - Needs some thought here...
// I think here we might want to pass empty addedFiles/deletedFiles as they were
// dealt with on the first call to processDelta - we are going through this loop
// again because in compiling something we found something else we needed to
// rebuild. But what case causes this?
if (hereWeGoAgain)
if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode())
if (AsmManager.attemptIncrementalModelRepairs)
AsmManager.getDefault().processDelta(files,state.addedFiles,state.deletedFiles);
}
if (!files.isEmpty()) {
return batchBuild(buildConfig, baseHandler);
} else {
if (AsmManager.isReporting())
AsmManager.getDefault().reportModelInfo("After an incremental build");
}
}
// XXX not in Mik's incremental
if (buildConfig.isEmacsSymMode()) {
new org.aspectj.ajdt.internal.core.builder.EmacsStructureModelManager().externalizeModel();
}
// have to tell state we succeeded or next is not incremental
state.successfulCompile(buildConfig);
copyResourcesToDestination();
/*boolean weaved = *///weaveAndGenerateClassFiles();
// if not weaved, then no-op build, no model changes
// but always returns true
// XXX weaved not in Mik's incremental
if (buildConfig.isGenerateModelMode()) {
AsmManager.getDefault().fireModelUpdated();
}
} finally {
if (zos != null) {
closeOutputStream(buildConfig.getOutputJar());
}
ret = !handler.hasErrors();
// bug 59895, don't release reference to handler as may be needed by a nested call
//handler = null;
}
return ret;
}
private boolean openOutputStream(File outJar) {
try {
OutputStream os = FileUtil.makeOutputStream(buildConfig.getOutputJar());
zos = new JarOutputStream(os,bcelWeaver.getManifest(true));
} catch (IOException ex) {
IMessage message =
new Message("Unable to open outjar "
+ outJar.getPath()
+ "(" + ex.getMessage()
+ ")",
new SourceLocation(outJar,0),
true);
handler.handleMessage(message);
return false;
}
return true;
}
private void closeOutputStream(File outJar) {
try {
if (zos != null) zos.close();
zos = null;
/* Ensure we don't write an incomplete JAR bug-71339 */
if (handler.hasErrors()) {
outJar.delete();
}
} catch (IOException ex) {
IMessage message =
new Message("Unable to write outjar "
+ outJar.getPath()
+ "(" + ex.getMessage()
+ ")",
new SourceLocation(outJar,0),
true);
handler.handleMessage(message);
}
}
private void copyResourcesToDestination() throws IOException {
// resources that we need to copy are contained in the injars and inpath only
for (Iterator i = buildConfig.getInJars().iterator(); i.hasNext(); ) {
File inJar = (File)i.next();
copyResourcesFromJarFile(inJar);
}
for (Iterator i = buildConfig.getInpath().iterator(); i.hasNext(); ) {
File inPathElement = (File)i.next();
if (inPathElement.isDirectory()) {
copyResourcesFromDirectory(inPathElement);
} else {
copyResourcesFromJarFile(inPathElement);
}
}
if (buildConfig.getSourcePathResources() != null) {
for (Iterator i = buildConfig.getSourcePathResources().keySet().iterator(); i.hasNext(); ) {
String resource = (String)i.next();
File from = (File)buildConfig.getSourcePathResources().get(resource);
copyResourcesFromFile(from,resource,from);
}
}
writeManifest();
}
private void copyResourcesFromJarFile(File jarFile) throws IOException {
JarInputStream inStream = null;
try {
inStream = new JarInputStream(new FileInputStream(jarFile));
while (true) {
ZipEntry entry = inStream.getNextEntry();
if (entry == null) break;
String filename = entry.getName();
// System.out.println("? copyResourcesFromJarFile() filename='" + filename +"'");
if (!entry.isDirectory() && acceptResource(filename)) {
byte[] bytes = FileUtil.readAsByteArray(inStream);
writeResource(filename,bytes,jarFile);
}
inStream.closeEntry();
}
} finally {
if (inStream != null) inStream.close();
}
}
private void copyResourcesFromDirectory(File dir) throws IOException {
if (!COPY_INPATH_DIR_RESOURCES) return;
// Get a list of all files (i.e. everything that isnt a directory)
File[] files = FileUtil.listFiles(dir,new FileFilter() {
public boolean accept(File f) {
boolean accept = !(f.isDirectory() || f.getName().endsWith(".class")) ;
return accept;
}
});
// For each file, add it either as a real .class file or as a resource
for (int i = 0; i < files.length; i++) {
// ASSERT: files[i].getAbsolutePath().startsWith(inFile.getAbsolutePath()
// or we are in trouble...
String filename = files[i].getAbsolutePath().substring(
dir.getAbsolutePath().length()+1);
copyResourcesFromFile(files[i],filename,dir);
}
}
private void copyResourcesFromFile(File f,String filename,File src) throws IOException {
if (!acceptResource(filename)) return;
FileInputStream fis = null;
try {
fis = new FileInputStream(f);
byte[] bytes = FileUtil.readAsByteArray(fis);
// String relativePath = files[i].getPath();
writeResource(filename,bytes,src);
} finally {
if (fis != null) fis.close();
}
}
private void writeResource(String filename, byte[] content, File srcLocation) throws IOException {
if (state.resources.contains(filename)) {
IMessage msg = new Message("duplicate resource: '" + filename + "'",
IMessage.WARNING,
null,
new SourceLocation(srcLocation,0));
handler.handleMessage(msg);
return;
}
if (zos != null) {
ZipEntry newEntry = new ZipEntry(filename); //??? get compression scheme right
zos.putNextEntry(newEntry);
zos.write(content);
zos.closeEntry();
} else {
OutputStream fos =
FileUtil.makeOutputStream(new File(buildConfig.getOutputDir(),filename));
fos.write(content);
fos.close();
}
state.resources.add(filename);
}
/*
* If we are writing to an output directory copy the manifest but only
* if we already have one
*/
private void writeManifest () throws IOException {
Manifest manifest = bcelWeaver.getManifest(false);
if (manifest != null && zos == null) {
OutputStream fos =
FileUtil.makeOutputStream(new File(buildConfig.getOutputDir(),MANIFEST_NAME));
manifest.write(fos);
fos.close();
}
}
private boolean acceptResource(String resourceName) {
if (
(resourceName.startsWith("CVS/")) ||
(resourceName.indexOf("/CVS/") != -1) ||
(resourceName.endsWith("/CVS")) ||
(resourceName.endsWith(".class")) ||
(resourceName.toUpperCase().equals(MANIFEST_NAME))
)
{
return false;
} else {
return true;
}
}
// public static void dumprels() {
// IRelationshipMap irm = AsmManager.getDefault().getRelationshipMap();
// int ctr = 1;
// Set entries = irm.getEntries();
// for (Iterator iter = entries.iterator(); iter.hasNext();) {
// String hid = (String) iter.next();
// List rels = irm.get(hid);
// for (Iterator iterator = rels.iterator(); iterator.hasNext();) {
// IRelationship ir = (IRelationship) iterator.next();
// List targets = ir.getTargets();
// for (Iterator iterator2 = targets.iterator();
// iterator2.hasNext();
// ) {
// String thid = (String) iterator2.next();
// System.err.println("Hid:"+(ctr++)+":(targets="+targets.size()+") "+hid+" ("+ir.getName()+") "+thid);
// }
// }
// }
// }
/**
* Responsible for managing the ASM model between builds. Contains the policy for
* maintaining the persistance of elements in the model.
*
* TODO: implement incremental policy.
*/
private void setupModel(AjBuildConfig config) {
IHierarchy model = AsmManager.getDefault().getHierarchy();
String rootLabel = "<root>";
AsmManager.getDefault().getRelationshipMap().clear();
IProgramElement.Kind kind = IProgramElement.Kind.FILE_JAVA;
if (buildConfig.getConfigFile() != null) {
rootLabel = buildConfig.getConfigFile().getName();
model.setConfigFile(
buildConfig.getConfigFile().getAbsolutePath()
);
kind = IProgramElement.Kind.FILE_LST;
}
model.setRoot(new ProgramElement(rootLabel, kind, new ArrayList()));
model.setFileMap(new HashMap());
setStructureModel(model);
}
//
// private void dumplist(List l) {
// System.err.println("---- "+l.size());
// for (int i =0 ;i<l.size();i++) System.err.println(i+"\t "+l.get(i));
// }
// private void accumulateFileNodes(IProgramElement ipe,List store) {
// if (ipe.getKind()==IProgramElement.Kind.FILE_JAVA ||
// ipe.getKind()==IProgramElement.Kind.FILE_ASPECTJ) {
// if (!ipe.getName().equals("<root>")) {
// store.add(ipe);
// return;
// }
// }
// for (Iterator i = ipe.getChildren().iterator();i.hasNext();) {
// accumulateFileNodes((IProgramElement)i.next(),store);
// }
// }
/** init only on initial batch compile? no file-specific options */
private void initBcelWorld(IMessageHandler handler) throws IOException {
bcelWorld = new BcelWorld(buildConfig.getClasspath(), handler, null);
bcelWorld.setXnoInline(buildConfig.isXnoInline());
bcelWorld.setXlazyTjp(buildConfig.isXlazyTjp());
bcelWeaver = new BcelWeaver(bcelWorld);
state.binarySourceFiles = new HashMap();
for (Iterator i = buildConfig.getAspectpath().iterator(); i.hasNext();) {
File f = (File) i.next();
bcelWeaver.addLibraryJarFile(f);
}
// String lintMode = buildConfig.getLintMode();
if (buildConfig.getLintMode().equals(AjBuildConfig.AJLINT_DEFAULT)) {
bcelWorld.getLint().loadDefaultProperties();
} else {
bcelWorld.getLint().setAll(buildConfig.getLintMode());
}
if (buildConfig.getLintSpecFile() != null) {
bcelWorld.getLint().setFromProperties(buildConfig.getLintSpecFile());
}
//??? incremental issues
for (Iterator i = buildConfig.getInJars().iterator(); i.hasNext(); ) {
File inJar = (File)i.next();
List unwovenClasses = bcelWeaver.addJarFile(inJar, buildConfig.getOutputDir(),false);
state.binarySourceFiles.put(inJar.getPath(), unwovenClasses);
}
for (Iterator i = buildConfig.getInpath().iterator(); i.hasNext(); ) {
File inPathElement = (File)i.next();
if (!inPathElement.isDirectory()) {
// its a jar file on the inpath
// the weaver method can actually handle dirs, but we don't call it, see next block
List unwovenClasses = bcelWeaver.addJarFile(inPathElement,buildConfig.getOutputDir(),true);
state.binarySourceFiles.put(inPathElement.getPath(),unwovenClasses);
} else {
// add each class file in an in-dir individually, this gives us the best error reporting
// (they are like 'source' files then), and enables a cleaner incremental treatment of
// class file changes in indirs.
File[] binSrcs = FileUtil.listFiles(inPathElement, binarySourceFilter);
for (int j = 0; j < binSrcs.length; j++) {
UnwovenClassFile ucf =
bcelWeaver.addClassFile(binSrcs[j], inPathElement, buildConfig.getOutputDir());
List ucfl = new ArrayList();
ucfl.add(ucf);
state.binarySourceFiles.put(binSrcs[j].getPath(),ucfl);
}
}
}
bcelWeaver.setReweavableMode(buildConfig.isXreweavable(),buildConfig.getXreweavableCompressClasses());
//check for org.aspectj.runtime.JoinPoint
bcelWorld.resolve("org.aspectj.lang.JoinPoint");
}
public World getWorld() {
return bcelWorld;
}
void addAspectClassFilesToWeaver(List addedClassFiles) throws IOException {
for (Iterator i = addedClassFiles.iterator(); i.hasNext(); ) {
UnwovenClassFile classFile = (UnwovenClassFile) i.next();
bcelWeaver.addClassFile(classFile);
}
}
// public boolean weaveAndGenerateClassFiles() throws IOException {
// handler.handleMessage(MessageUtil.info("weaving"));
// if (progressListener != null) progressListener.setText("weaving aspects");
// bcelWeaver.setProgressListener(progressListener, 0.5, 0.5/state.addedClassFiles.size());
// //!!! doesn't provide intermediate progress during weaving
// // XXX add all aspects even during incremental builds?
// addAspectClassFilesToWeaver(state.addedClassFiles);
// if (buildConfig.isNoWeave()) {
// if (buildConfig.getOutputJar() != null) {
// bcelWeaver.dumpUnwoven(buildConfig.getOutputJar());
// } else {
// bcelWeaver.dumpUnwoven();
// bcelWeaver.dumpResourcesToOutPath();
// }
// } else {
// if (buildConfig.getOutputJar() != null) {
// bcelWeaver.weave(buildConfig.getOutputJar());
// } else {
// bcelWeaver.weave();
// bcelWeaver.dumpResourcesToOutPath();
// }
// }
// if (progressListener != null) progressListener.setProgress(1.0);
// return true;
// //return messageAdapter.getErrorCount() == 0; //!javaBuilder.notifier.anyErrors();
// }
public FileSystem getLibraryAccess(String[] classpaths, String[] filenames) {
String defaultEncoding = buildConfig.getOptions().defaultEncoding;
if ("".equals(defaultEncoding)) //$NON-NLS-1$
defaultEncoding = null; //$NON-NLS-1$
// Bug 46671: We need an array as long as the number of elements in the classpath - *even though* not every
// element of the classpath is likely to be a directory. If we ensure every element of the array is set to
// only look for BINARY, then we make sure that for any classpath element that is a directory, we won't build
// a classpathDirectory object that will attempt to look for source when it can't find binary.
int[] classpathModes = new int[classpaths.length];
for (int i =0 ;i<classpaths.length;i++) classpathModes[i]=ClasspathDirectory.BINARY;
return new FileSystem(classpaths, filenames, defaultEncoding,classpathModes);
}
public IProblemFactory getProblemFactory() {
return new DefaultProblemFactory(Locale.getDefault());
}
/*
* Build the set of compilation source units
*/
public CompilationUnit[] getCompilationUnits(String[] filenames, String[] encodings) {
int fileCount = filenames.length;
CompilationUnit[] units = new CompilationUnit[fileCount];
// HashtableOfObject knownFileNames = new HashtableOfObject(fileCount);
String defaultEncoding = buildConfig.getOptions().defaultEncoding;
if ("".equals(defaultEncoding)) //$NON-NLS-1$
defaultEncoding = null; //$NON-NLS-1$
for (int i = 0; i < fileCount; i++) {
String encoding = encodings[i];
if (encoding == null)
encoding = defaultEncoding;
units[i] = new CompilationUnit(null, filenames[i], encoding);
}
return units;
}
public String extractDestinationPathFromSourceFile(CompilationResult result) {
ICompilationUnit compilationUnit = result.compilationUnit;
if (compilationUnit != null) {
char[] fileName = compilationUnit.getFileName();
int lastIndex = CharOperation.lastIndexOf(java.io.File.separatorChar, fileName);
if (lastIndex == -1) {
return System.getProperty("user.dir"); //$NON-NLS-1$
}
return new String(CharOperation.subarray(fileName, 0, lastIndex));
}
return System.getProperty("user.dir"); //$NON-NLS-1$
}
public void performCompilation(List files) {
if (progressListener != null) {
compiledCount = 0;
sourceFileCount = files.size();
progressListener.setText("compiling source files");
}
//System.err.println("got files: " + files);
String[] filenames = new String[files.size()];
String[] encodings = new String[files.size()];
//System.err.println("filename: " + this.filenames);
for (int i=0; i < files.size(); i++) {
filenames[i] = ((File)files.get(i)).getPath();
}
List cps = buildConfig.getFullClasspath();
Dump.saveFullClasspath(cps);
String[] classpaths = new String[cps.size()];
for (int i=0; i < cps.size(); i++) {
classpaths[i] = (String)cps.get(i);
}
//System.out.println("compiling");
environment = getLibraryAccess(classpaths, filenames);
if (!state.classesFromName.isEmpty()) {
environment = new StatefulNameEnvironment(environment, state.classesFromName);
}
org.eclipse.jdt.internal.compiler.Compiler.setCompilerAdapterFactory(this);
org.eclipse.jdt.internal.compiler.Compiler compiler =
new org.eclipse.jdt.internal.compiler.Compiler(environment,
DefaultErrorHandlingPolicies.proceedWithAllProblems(),
buildConfig.getOptions().getMap(),
getBatchRequestor(),
getProblemFactory());
CompilerOptions options = compiler.options;
options.produceReferenceInfo = true; //TODO turn off when not needed
try {
compiler.compile(getCompilationUnits(filenames, encodings));
} catch (OperationCanceledException oce) {
handler.handleMessage(new Message("build cancelled:"+oce.getMessage(),IMessage.WARNING,null,null));
}
// cleanup
environment.cleanup();
environment = null;
}
/*
* Answer the component to which will be handed back compilation results from the compiler
*/
public IIntermediateResultsRequestor getInterimResultRequestor() {
return new IIntermediateResultsRequestor() {
int lineDelta = 0;
public void acceptResult(InterimCompilationResult result) {
if (progressListener != null) {
compiledCount++;
progressListener.setProgress((compiledCount/2.0)/sourceFileCount);
progressListener.setText("compiled: " + result.fileName());
}
state.noteResult(result);
if (progressListener!=null && progressListener.isCancelledRequested()) {
throw new AbortCompilation(true,
new OperationCanceledException("Compilation cancelled as requested"));
}
}
};
}
public ICompilerRequestor getBatchRequestor() {
return new ICompilerRequestor() {
public void acceptResult(CompilationResult unitResult) {
// end of compile, must now write the results to the output destination
// this is either a jar file or a file in a directory
if (!(unitResult.hasErrors() && !proceedOnError())) {
Enumeration classFiles = unitResult.compiledTypes.elements();
while (classFiles.hasMoreElements()) {
ClassFile classFile = (ClassFile) classFiles.nextElement();
String filename = new String(classFile.fileName());
filename = filename.replace('/', File.separatorChar) + ".class";
try {
if (buildConfig.getOutputJar() == null) {
writeDirectoryEntry(unitResult, classFile,filename);
} else {
writeZipEntry(classFile,filename);
}
} catch (IOException ex) {
IMessage message = EclipseAdapterUtils.makeErrorMessage(
new String(unitResult.fileName),
CANT_WRITE_RESULT,
ex);
handler.handleMessage(message);
}
}
}
if (unitResult.hasProblems() || unitResult.hasTasks()) {
IProblem[] problems = unitResult.getAllProblems();
for (int i=0; i < problems.length; i++) {
IMessage message =
EclipseAdapterUtils.makeMessage(unitResult.compilationUnit, problems[i]);
handler.handleMessage(message);
}
}
}
private void writeDirectoryEntry(
CompilationResult unitResult,
ClassFile classFile,
String filename)
throws IOException {
File destinationPath = buildConfig.getOutputDir();
String outFile;
if (destinationPath == null) {
outFile = new File(filename).getName();
outFile = new File(extractDestinationPathFromSourceFile(unitResult), outFile).getPath();
} else {
outFile = new File(destinationPath, filename).getPath();
}
BufferedOutputStream os =
FileUtil.makeOutputStream(new File(outFile));
os.write(classFile.getBytes());
os.close();
}
private void writeZipEntry(ClassFile classFile, String name)
throws IOException {
name = name.replace(File.separatorChar,'/');
ZipEntry newEntry = new ZipEntry(name); //??? get compression scheme right
zos.putNextEntry(newEntry);
zos.write(classFile.getBytes());
zos.closeEntry();
}
};
}
protected boolean proceedOnError() {
return true; //???
}
// public void noteClassFiles(AjCompiler.InterimResult result) {
// if (result == null) return;
// CompilationResult unitResult = result.result;
// String sourceFileName = result.fileName();
// if (!(unitResult.hasErrors() && !proceedOnError())) {
// List unwovenClassFiles = new ArrayList();
// Enumeration classFiles = unitResult.compiledTypes.elements();
// while (classFiles.hasMoreElements()) {
// ClassFile classFile = (ClassFile) classFiles.nextElement();
// String filename = new String(classFile.fileName());
// filename = filename.replace('/', File.separatorChar) + ".class";
//
// File destinationPath = buildConfig.getOutputDir();
// if (destinationPath == null) {
// filename = new File(filename).getName();
// filename = new File(extractDestinationPathFromSourceFile(unitResult), filename).getPath();
// } else {
// filename = new File(destinationPath, filename).getPath();
// }
//
// //System.out.println("classfile: " + filename);
// unwovenClassFiles.add(new UnwovenClassFile(filename, classFile.getBytes()));
// }
// state.noteClassesFromFile(unitResult, sourceFileName, unwovenClassFiles);
//// System.out.println("file: " + sourceFileName);
//// for (int i=0; i < unitResult.simpleNameReferences.length; i++) {
//// System.out.println("simple: " + new String(unitResult.simpleNameReferences[i]));
//// }
//// for (int i=0; i < unitResult.qualifiedReferences.length; i++) {
//// System.out.println("qualified: " +
//// new String(CharOperation.concatWith(unitResult.qualifiedReferences[i], '/')));
//// }
// } else {
// state.noteClassesFromFile(null, sourceFileName, Collections.EMPTY_LIST);
// }
// }
//
private void setBuildConfig(AjBuildConfig buildConfig) {
this.buildConfig = buildConfig;
handler.reset();
}
String makeClasspathString() {
if (buildConfig == null || buildConfig.getClasspath() == null) return "";
StringBuffer buf = new StringBuffer();
boolean first = true;
for (Iterator it = buildConfig.getClasspath().iterator(); it.hasNext(); ) {
if (first) { first = false; }
else { buf.append(File.pathSeparator); }
buf.append(it.next().toString());
}
return buf.toString();
}
/**
* This will return null if aspectjrt.jar is present and has the correct version.
* Otherwise it will return a string message indicating the problem.
*/
public String checkRtJar(AjBuildConfig buildConfig) {
// omitting dev info
if (Version.text.equals(Version.DEVELOPMENT)) {
// in the development version we can't do this test usefully
// MessageUtil.info(holder, "running development version of aspectj compiler");
return null;
}
if (buildConfig == null || buildConfig.getClasspath() == null) return "no classpath specified";
for (Iterator it = buildConfig.getClasspath().iterator(); it.hasNext(); ) {
File p = new File( (String)it.next() );
if (p.isFile() && p.getName().equals("aspectjrt.jar")) {
try {
String version = null;
Manifest manifest = new JarFile(p).getManifest();
if (manifest == null) {
return "no manifest found in " + p.getAbsolutePath() +
", expected " + Version.text;
}
Attributes attr = manifest.getAttributes("org/aspectj/lang/");
if (null != attr) {
version = attr.getValue(Attributes.Name.IMPLEMENTATION_VERSION);
if (null != version) {
version = version.trim();
}
}
// assume that users of development aspectjrt.jar know what they're doing
if (Version.DEVELOPMENT.equals(version)) {
// MessageUtil.info(holder,
// "running with development version of aspectjrt.jar in " +
// p.getAbsolutePath());
return null;
} else if (!Version.text.equals(version)) {
return "bad version number found in " + p.getAbsolutePath() +
" expected " + Version.text + " found " + version;
}
} catch (IOException ioe) {
return "bad jar file found in " + p.getAbsolutePath() + " error: " + ioe;
}
return null;
} else {
// might want to catch other classpath errors
}
}
return "couldn't find aspectjrt.jar on classpath, checked: " + makeClasspathString();
}
public String toString() {
StringBuffer buf = new StringBuffer();
buf.append("AjBuildManager(");
buf.append(")");
return buf.toString();
}
public void setStructureModel(IHierarchy structureModel) {
this.structureModel = structureModel;
}
/**
* Returns null if there is no structure model
*/
public IHierarchy getStructureModel() {
return structureModel;
}
public IProgressListener getProgressListener() {
return progressListener;
}
public void setProgressListener(IProgressListener progressListener) {
this.progressListener = progressListener;
}
/* (non-Javadoc)
* @see org.aspectj.ajdt.internal.compiler.AjCompiler.IOutputClassFileNameProvider#getOutputClassFileName(char[])
*/
public String getOutputClassFileName(char[] eclipseClassFileName, CompilationResult result) {
String filename = new String(eclipseClassFileName);
filename = filename.replace('/', File.separatorChar) + ".class";
File destinationPath = buildConfig.getOutputDir();
String outFile;
if (destinationPath == null) {
outFile = new File(filename).getName();
outFile = new File(extractDestinationPathFromSourceFile(result), outFile).getPath();
} else {
outFile = new File(destinationPath, filename).getPath();
}
return outFile;
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.compiler.ICompilerAdapterFactory#getAdapter(org.eclipse.jdt.internal.compiler.Compiler)
*/
public ICompilerAdapter getAdapter(org.eclipse.jdt.internal.compiler.Compiler forCompiler) {
// complete compiler config and return a suitable adapter...
AjProblemReporter pr =
new AjProblemReporter(DefaultErrorHandlingPolicies.proceedWithAllProblems(),
forCompiler.options, getProblemFactory());
forCompiler.problemReporter = pr;
AjLookupEnvironment le =
new AjLookupEnvironment(forCompiler, forCompiler.options, pr, environment);
EclipseFactory factory = new EclipseFactory(le,this);
le.factory = factory;
pr.factory = factory;
forCompiler.lookupEnvironment = le;
forCompiler.parser =
new Parser(
pr,
forCompiler.options.parseLiteralExpressionsAsConstants);
return new AjCompilerAdapter(forCompiler,batchCompile,bcelWorld,bcelWeaver,
factory,
getInterimResultRequestor(),
progressListener,
this, // IOutputFilenameProvider
this, // IBinarySourceProvider
state.binarySourceFiles,
state.resultsFromFile.values(),
buildConfig.isNoWeave());
}
/* (non-Javadoc)
* @see org.aspectj.ajdt.internal.compiler.IBinarySourceProvider#getBinarySourcesForThisWeave()
*/
public Map getBinarySourcesForThisWeave() {
return binarySourcesForTheNextCompile;
}
public static AsmHierarchyBuilder getAsmHierarchyBuilder() {
return asmHierarchyBuilder;
}
/**
* Override the the default hierarchy builder.
*/
public static void setAsmHierarchyBuilder(AsmHierarchyBuilder newBuilder) {
asmHierarchyBuilder = newBuilder;
}
public AjState getState() {
return state;
}
} // class AjBuildManager
|
72,671
|
Bug 72671 Bootclasspath specification for compiling is not possible
|
I have following bug running eclipse 3.0 and ajdt 1.1.12 I have following class: import java.io.FileNotFoundException; import java.io.FileOutputStream; import org.w3c.dom.DOMConfiguration; import org.w3c.dom.DOMError; import org.w3c.dom.DOMErrorHandler; import org.w3c.dom.Document; import org.w3c.dom.DocumentFragment; import org.w3c.dom.NodeList; import org.w3c.dom.ls.DOMImplementationLS; import org.w3c.dom.ls.LSInput; import org.w3c.dom.ls.LSOutput; import org.w3c.dom.ls.LSParser; import com.dcbank.common.DOMImplementationLSSingleton; public class DOMHelper { public static final String CLASS_ID = "%full_filespec: DOMHelper.java~1:java:1 %"; public static void save(Document document, String filename) throws ClassNotFoundException, InstantiationException, IllegalAccessException, FileNotFoundException { document.normalizeDocument(); } } which compiles very fine with JDK 1.4.2_02 on Windows XP, as soon as the dom2-xml-apis.jar and dom3-xercesImpl.jar are added at the beginning of the jre container, or are included in the jar-library list before the system jar. As soon as I convert this project to an AspectJ project, the code does not compile anymore. The aspectJ compiler does not find the normalizeDocument, which is included in the one of the two additional jars. method any more. kind regards Arno Schmidmeier
|
resolved fixed
|
d1551bd
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:13:46Z
| 2004-08-26T11:33:20Z
|
org.aspectj.ajdt.core/testsrc/org/aspectj/ajdt/ajc/BuildArgParserTestCase.java
|
/* *******************************************************************
* 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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.ajc;
import java.io.*;
import java.util.*;
import junit.framework.TestCase;
import org.aspectj.ajdt.internal.core.builder.*;
import org.aspectj.bridge.CountingMessageHandler;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.IMessageHandler;
import org.aspectj.bridge.MessageWriter;
import org.aspectj.testing.util.TestUtil;
import org.eclipse.jdt.core.compiler.InvalidInputException;
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
/**
* Some black-box test is happening here.
*/
public class BuildArgParserTestCase extends TestCase {
private static final String TEST_DIR = AjdtAjcTests.TESTDATA_PATH + File.separator + "ajc" + File.separator;
private MessageWriter messageWriter = new MessageWriter(new PrintWriter(System.out), false);
public BuildArgParserTestCase(String name) {
super(name);
}
private AjBuildConfig genBuildConfig(String[] args, IMessageHandler handler) {
return new BuildArgParser(handler).genBuildConfig(args);
}
public void testDefaultClasspathAndTargetCombo() throws Exception {
String ENTRY = "1.jar" + File.pathSeparator + "2.jar";
final String classpath = System.getProperty("java.class.path");
try {
System.setProperty("java.class.path", ENTRY); // see finally below
BuildArgParser parser = new BuildArgParser(messageWriter);
AjBuildConfig config = parser.genBuildConfig(new String[] { });
/*String err = */parser.getOtherMessages(true);
//!!!assertTrue(err, null == err);
assertTrue(
config.getClasspath().toString(),
config.getClasspath().contains("1.jar"));
assertTrue(
config.getClasspath().toString(),
config.getClasspath().contains("2.jar"));
config = genBuildConfig(new String[] { "-1.3" }, messageWriter);
// these errors are deffered to the compiler now
//err = parser.getOtherMessages(true);
//!!!assertTrue(err, null == err);
assertTrue(
config.getClasspath().toString(),
config.getClasspath().contains("1.jar"));
assertTrue(
config.getClasspath().toString(),
config.getClasspath().contains("2.jar"));
parser = new BuildArgParser(messageWriter);
config = parser.genBuildConfig(new String[] { "-1.3" });
/*err = */parser.getOtherMessages(true);
//!!!assertTrue(err, null == err);
assertTrue(
config.getClasspath().toString(),
config.getClasspath().contains("1.jar"));
assertTrue(
config.getClasspath().toString(),
config.getClasspath().contains("2.jar"));
config = genBuildConfig(new String[] {
"-classpath", ENTRY, "-1.4" }, messageWriter);
// these errors are deffered to the compiler now
//err = parser.getOtherMessages(true);
//assertTrue("expected errors for missing jars", null != err);
List cp = config.getClasspath();
boolean jar1Found = false;
boolean jar2Found = false;
for (Iterator iter = cp.iterator(); iter.hasNext();) {
String element = (String) iter.next();
if (element.indexOf("1.jar") != -1) jar1Found = true;
if (element.indexOf("2.jar") != -1) jar2Found = true;
}
assertTrue(
config.getClasspath().toString(),
jar1Found);
assertTrue(
config.getClasspath().toString(),
jar2Found);
} finally {
// do finally to avoid messing up classpath for other tests
System.setProperty("java.class.path", classpath);
String setPath = System.getProperty("java.class.path");
String m = "other tests will fail - classpath not reset";
assertEquals(m, classpath, setPath);
}
}
public void testPathResolutionFromConfigArgs() {
String FILE_PATH = "@" + TEST_DIR + "configWithClasspathExtdirsBootCPArgs.lst";
AjBuildConfig config = genBuildConfig(new String[] { FILE_PATH }, messageWriter);
List classpath = config.getClasspath();
// should have three entries, resolved relative to location of .lst file
assertEquals("Three entries in classpath",3,classpath.size());
Iterator cpIter = classpath.iterator();
try {
assertEquals("Should be relative to TESTDIR",new File(TEST_DIR+File.separator+"xyz").getCanonicalPath(),cpIter.next());
assertEquals("Should be relative to TESTDIR",new File(TEST_DIR+File.separator+"myextdir" + File.separator + "dummy.jar").getCanonicalPath(),cpIter.next());
assertEquals("Should be relative to TESTDIR",new File(TEST_DIR+File.separator+"abc.jar").getCanonicalPath(),cpIter.next());
List files = config.getFiles();
assertEquals("Two source files",2,files.size());
Iterator fIter = files.iterator();
assertEquals("Should be relative to TESTDIR",new File(TEST_DIR+File.separator+"Abc.java").getCanonicalFile(),fIter.next());
assertEquals("Should be relative to TESTDIR",new File(TEST_DIR+File.separator+"xyz"+File.separator+"Def.aj").getCanonicalFile(),fIter.next());
} catch (IOException ex) {
fail("Test case failure attempting to create canonical path: " + ex);
}
}
public void testAjOptions() throws InvalidInputException {
AjBuildConfig config = genBuildConfig(new String[] { "-Xlint" }, messageWriter);
assertTrue(
"default options",
config.getLintMode().equals(AjBuildConfig.AJLINT_DEFAULT));
}
public void testAspectpath() throws InvalidInputException {
final String SOURCE_JAR = AjdtAjcTests.TESTDATA_PATH + "/testclasses.jar";
final String SOURCE_JARS = AjdtAjcTests.TESTDATA_PATH + "/testclasses.jar" + File.pathSeparator
+ "../weaver/testdata/tracing.jar" + File.pathSeparator
+ "../weaver/testdata/dummyAspect.jar";
AjBuildConfig config = genBuildConfig(new String[] {
"-aspectpath", SOURCE_JAR },
messageWriter);
assertTrue(((File)config.getAspectpath().get(0)).getName(), ((File)config.getAspectpath().get(0)).getName().equals("testclasses.jar"));
config = genBuildConfig(new String[] {
"-aspectpath", SOURCE_JARS },
messageWriter);
assertTrue("size", + config.getAspectpath().size() == 3);
}
public void testInJars() throws InvalidInputException {
final String SOURCE_JAR = AjdtAjcTests.TESTDATA_PATH + "/testclasses.jar";
final String SOURCE_JARS = AjdtAjcTests.TESTDATA_PATH + "/testclasses.jar" + File.pathSeparator
+ "../weaver/testdata/tracing.jar" + File.pathSeparator
+ "../weaver/testdata/dummyAspect.jar";
AjBuildConfig config = genBuildConfig(new String[] {
"-injars", SOURCE_JAR },
messageWriter);
//XXX don't let this remain in both places in beta1
// assertTrue(
// "" + config.getAjOptions().get(AjCompilerOptions.OPTION_InJARs),
// config.getAjOptions().get(AjCompilerOptions.OPTION_InJARs).equals(CompilerOptions.PRESERVE));
assertTrue(((File)config.getInJars().get(0)).getName(), ((File)config.getInJars().get(0)).getName().equals("testclasses.jar"));
config = genBuildConfig(new String[] {
"-injars", SOURCE_JARS },
messageWriter);
assertTrue("size", + config.getInJars().size() == 3);
}
public void testBadInJars() throws InvalidInputException {
final String SOURCE_JARS = AjdtAjcTests.TESTDATA_PATH + "/testclasses.jar" + File.pathSeparator + "b.far" + File.pathSeparator + "c.jar";
AjBuildConfig config = genBuildConfig(new String[] {
"-injars", SOURCE_JARS },
messageWriter);
assertTrue("size: " + config.getInJars().size(), config.getInJars().size() == 1);
}
public void testBadPathToSourceFiles() {
CountingMessageHandler countingHandler = new CountingMessageHandler(messageWriter);
/*AjBuildConfig config = */genBuildConfig(new String[]{ "inventedDir/doesntexist/*.java"},countingHandler);
assertTrue("Expected an error for the invalid path.",countingHandler.numMessages(IMessage.ERROR,false)==1);
}
public void testMultipleSourceRoots() throws InvalidInputException, IOException {
final String SRCROOT_1 = AjdtAjcTests.TESTDATA_PATH + "/src1/p1";
final String SRCROOT_2 = AjdtAjcTests.TESTDATA_PATH + "/ajc";
AjBuildConfig config = genBuildConfig(new String[] {
"-sourceroots", SRCROOT_1 + File.pathSeparator + SRCROOT_2 },
messageWriter);
assertEquals(getCanonicalPath(new File(SRCROOT_1)), ((File)config.getSourceRoots().get(0)).getAbsolutePath());
Collection expectedFiles = Arrays.asList(new File[] {
new File(SRCROOT_1+File.separator+"A.java").getCanonicalFile(),
new File(SRCROOT_1+File.separator+"Foo.java").getCanonicalFile(),
new File(SRCROOT_2+File.separator+"A.java").getCanonicalFile(),
new File(SRCROOT_2+File.separator+"B.java").getCanonicalFile(),
new File(SRCROOT_2+File.separator+"X.aj").getCanonicalFile(),
new File(SRCROOT_2+File.separator+"Y.aj").getCanonicalFile(),
new File(SRCROOT_2+File.separator+"pkg"+File.separator+"Hello.java").getCanonicalFile(),
});
//System.out.println(config.getFiles());
TestUtil.assertSetEquals(expectedFiles, config.getFiles());
}
/**
* @param file
* @return String
*/
private String getCanonicalPath(File file) {
String ret = "";
try {
ret = file.getCanonicalPath();
} catch (IOException ioEx) {
fail("Unable to canonicalize " + file + " : " + ioEx);
}
return ret;
}
public void testSourceRootDir() throws InvalidInputException, IOException {
final String SRCROOT = AjdtAjcTests.TESTDATA_PATH + "/ajc";
AjBuildConfig config = genBuildConfig(new String[] {
"-sourceroots", SRCROOT },
messageWriter);
assertEquals(getCanonicalPath(new File(SRCROOT)), ((File)config.getSourceRoots().get(0)).getAbsolutePath());
Collection expectedFiles = Arrays.asList(new File[] {
new File(SRCROOT+File.separator+"A.java").getCanonicalFile(),
new File(SRCROOT+File.separator+"B.java").getCanonicalFile(),
new File(SRCROOT+File.separator+"X.aj").getCanonicalFile(),
new File(SRCROOT+File.separator+"Y.aj").getCanonicalFile(),
new File(SRCROOT+File.separator+"pkg"+File.separator+"Hello.java").getCanonicalFile(),
});
//System.out.println(config.getFiles());
TestUtil.assertSetEquals(expectedFiles, config.getFiles());
}
public void testBadSourceRootDir() throws InvalidInputException {
AjBuildConfig config = genBuildConfig(new String[] {
"-sourceroots",
AjdtAjcTests.TESTDATA_PATH + "/mumbleDoesNotExist" + File.pathSeparator
+ AjdtAjcTests.TESTDATA_PATH + "/ajc" },
messageWriter);
assertTrue(config.getSourceRoots().toString(), config.getSourceRoots().size() == 1);
config = genBuildConfig(new String[] {
"-sourceroots" },
messageWriter);
assertTrue("" + config.getSourceRoots(), config.getSourceRoots().size() == 0);
}
//??? we've decided not to make this an error
public void testSourceRootDirWithFiles() throws InvalidInputException, IOException {
final String SRCROOT = AjdtAjcTests.TESTDATA_PATH + "/ajc/pkg";
AjBuildConfig config = genBuildConfig(new String[] {
"-sourceroots", SRCROOT, AjdtAjcTests.TESTDATA_PATH + "/src1/A.java"},
messageWriter);
assertEquals(getCanonicalPath(new File(SRCROOT)), ((File)config.getSourceRoots().get(0)).getAbsolutePath());
Collection expectedFiles = Arrays.asList(new File[] {
new File(SRCROOT+File.separator+"Hello.java").getCanonicalFile(),
new File(AjdtAjcTests.TESTDATA_PATH +File.separator+"src1"+File.separator+"A.java").getCanonicalFile(),
});
TestUtil.assertSetEquals(expectedFiles, config.getFiles());
}
public void testExtDirs() throws Exception {
final String DIR = AjdtAjcTests.TESTDATA_PATH;
AjBuildConfig config = genBuildConfig(new String[] {
"-extdirs", DIR },
messageWriter);
assertTrue(config.getClasspath().toString(), config.getClasspath().contains(
new File(DIR + File.separator + "testclasses.jar").getCanonicalPath()
));
}
public void testBootclasspath() throws InvalidInputException {
final String PATH = "mumble" + File.separator + "rt.jar";
AjBuildConfig config = genBuildConfig(new String[] {
"-bootclasspath", PATH },
messageWriter);
assertTrue("Should find '" + PATH + "' contained in the first entry of '" + config.getClasspath().toString(),
((String)config.getClasspath().get(0)).indexOf(PATH) != -1);
config = genBuildConfig(new String[] {
},
messageWriter);
assertTrue(config.getClasspath().toString(), !config.getClasspath().get(0).equals(PATH));
}
public void testOutputJar() throws InvalidInputException {
final String OUT_JAR = AjdtAjcTests.TESTDATA_PATH + "/testclasses.jar";
AjBuildConfig config = genBuildConfig(new String[] {
"-outjar", OUT_JAR },
messageWriter);
//XXX don't let this remain in both places in beta1
// assertTrue(
// "will generate: " + config.getAjOptions().get(AjCompilerOptions.OPTION_OutJAR),
// config.getAjOptions().get(AjCompilerOptions.OPTION_OutJAR).equals(CompilerOptions.GENERATE));
assertEquals(
getCanonicalPath(new File(OUT_JAR)),config.getOutputJar().getAbsolutePath());
File nonExistingJar = new File(AjdtAjcTests.TESTDATA_PATH + "/mumbleDoesNotExist.jar");
config = genBuildConfig(new String[] {
"-outjar", nonExistingJar.getAbsolutePath() },
messageWriter);
assertEquals(
getCanonicalPath(nonExistingJar),
config.getOutputJar().getAbsolutePath());
nonExistingJar.delete();
}
//XXX shouldn't need -1.4 to get this to pass
public void testCombinedOptions() throws InvalidInputException {
AjBuildConfig config = genBuildConfig(new String[] { "-Xlint:error", "-target", "1.4"}, messageWriter);
assertTrue(
"target set",
config.getOptions().targetJDK == CompilerOptions.JDK1_4);
assertTrue(
"Xlint option set",
config.getLintMode().equals(AjBuildConfig.AJLINT_ERROR));
}
public void testOutputDirectorySetting() throws InvalidInputException {
AjBuildConfig config = genBuildConfig(new String[] { "-d", TEST_DIR }, messageWriter);
assertTrue(
new File(config.getOutputDir().getPath()).getAbsolutePath() + " ?= " +
new File(TEST_DIR).getAbsolutePath(),
config.getOutputDir().getAbsolutePath().equals((new File(TEST_DIR)).getAbsolutePath()));
}
public void testClasspathSetting() throws InvalidInputException {
String ENTRY = "1.jar" + File.pathSeparator + "2.jar";
AjBuildConfig config = genBuildConfig(new String[] { "-classpath", ENTRY }, messageWriter);
List cp = config.getClasspath();
boolean jar1Found = false;
boolean jar2Found = false;
for (Iterator iter = cp.iterator(); iter.hasNext();) {
String element = (String) iter.next();
if (element.indexOf("1.jar") != -1) jar1Found = true;
if (element.indexOf("2.jar") != -1) jar2Found = true;
}
assertTrue(
config.getClasspath().toString(),
jar1Found);
assertTrue(
config.getClasspath().toString(),
jar2Found);
}
public void testArgInConfigFile() throws InvalidInputException {
String FILE_PATH = "@" + TEST_DIR + "configWithArgs.lst";
String OUT_PATH = "bin";
AjBuildConfig config = genBuildConfig(new String[] { FILE_PATH }, messageWriter);
assertNotNull(config);
File outputDir = config.getOutputDir();
assertNotNull(outputDir);
assertEquals(outputDir.getPath(), OUT_PATH);
}
public void testNonExistentConfigFile() throws IOException {
String FILE_PATH = "@" + TEST_DIR + "../bug-40257/d1/test.lst";
AjBuildConfig config = genBuildConfig(new String[] { FILE_PATH }, messageWriter);
String a = new File(TEST_DIR + "../bug-40257/d1/A.java").getCanonicalPath();
String b = new File(TEST_DIR + "../bug-40257/d1/d2/B.java").getCanonicalPath();
String c = new File(TEST_DIR + "../bug-40257/d3/C.java").getCanonicalPath();
List pathList = new ArrayList();
for (Iterator it = config.getFiles().iterator(); it.hasNext(); ) {
pathList.add(((File)it.next()).getCanonicalPath());
}
assertTrue(pathList.contains(a));
assertTrue(pathList.contains(b));
assertTrue(pathList.contains(c));
}
public void testXlint() throws InvalidInputException {
// AjdtCommand command = new AjdtCommand();
AjBuildConfig config = genBuildConfig(new String[] {"-Xlint"}, messageWriter);
assertTrue("", config.getLintMode().equals(AjBuildConfig.AJLINT_DEFAULT));
config = genBuildConfig(new String[] {"-Xlint:warn"}, messageWriter);
assertTrue("", config.getLintMode().equals(AjBuildConfig.AJLINT_WARN));
config = genBuildConfig(new String[] {"-Xlint:error"}, messageWriter);
assertTrue("", config.getLintMode().equals(AjBuildConfig.AJLINT_ERROR));
config = genBuildConfig(new String[] {"-Xlint:ignore"}, messageWriter);
assertTrue("", config.getLintMode().equals(AjBuildConfig.AJLINT_IGNORE));
}
public void testXlintfile() throws InvalidInputException {
String lintFile = AjdtAjcTests.TESTDATA_PATH + "/lintspec.properties";
// String badLintFile = "lint.props";
AjBuildConfig config = genBuildConfig(new String[] {"-Xlintfile", lintFile}, messageWriter);
assertTrue(new File(lintFile).exists());
assertEquals(getCanonicalPath(new File(lintFile)),config.getLintSpecFile().getAbsolutePath());
}
public void testOptions() throws InvalidInputException {
// AjdtCommand command = new AjdtCommand();
String TARGET = "1.4";
AjBuildConfig config = genBuildConfig(new String[] {"-target", TARGET, "-source", TARGET}, messageWriter);
assertTrue(
"target set",
config.getOptions().targetJDK == CompilerOptions.JDK1_4);
assertTrue(
"source set",
config.getOptions().sourceLevel == CompilerOptions.JDK1_4);
}
public void testLstFileExpansion() throws IOException, FileNotFoundException, InvalidInputException {
String FILE_PATH = TEST_DIR + "config.lst";
String SOURCE_PATH_1 = "A.java";
String SOURCE_PATH_2 = "B.java";
// File f = new File(FILE_PATH);
AjBuildConfig config = genBuildConfig(new String[] { "@" + FILE_PATH }, messageWriter);
List resultList = config.getFiles();
assertTrue("correct number of files", resultList.size() == 2);
assertTrue(resultList.toString() + new File(TEST_DIR + SOURCE_PATH_1).getCanonicalFile(),
resultList.contains(new File(TEST_DIR + SOURCE_PATH_1).getCanonicalFile()));
assertTrue(resultList.toString() + SOURCE_PATH_2,
resultList.contains(new File(TEST_DIR + SOURCE_PATH_2).getCanonicalFile()));
}
//??? do we need to remove this limitation
// public void testArgInConfigFileAndRelativizingPathParam() throws InvalidInputException {
// String FILE_PATH = "@" + TEST_DIR + "configWithArgs.lst";
// String OUT_PATH = TEST_DIR + "bin";
// AjBuildConfig config = genBuildConfig(new String[] { FILE_PATH });
//
// assertTrue(
// config.getOutputDir().getPath() + " ?= " + OUT_PATH,
// config.getOutputDir().getAbsolutePath().equals((new File(OUT_PATH)).getAbsolutePath()));
// }
public void testAjFileInclusion() throws InvalidInputException {
genBuildConfig(new String[] { TEST_DIR + "X.aj", TEST_DIR + "Y.aj"}, messageWriter);
}
protected void setUp() throws Exception {
super.setUp();
}
protected void tearDown() throws Exception {
super.tearDown();
}
}
|
73,334
|
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
|
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
|
resolved fixed
|
b133299
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:40:02Z
| 2004-09-06T17:00:00Z
|
ajde/src/org/aspectj/ajde/internal/CompilerAdapter.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC),
* 2003 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Xerox/PARC initial implementation
* AMC 01.20.2003 extended to support new AspectJ 1.1 options,
* bugzilla #29769
* ******************************************************************/
package org.aspectj.ajde.internal;
import java.io.File;
import java.util.*;
import org.aspectj.ajde.*;
import org.aspectj.ajdt.ajc.*;
import org.aspectj.ajdt.internal.core.builder.*;
import org.aspectj.bridge.*;
import org.aspectj.util.LangUtil;
//import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
public class CompilerAdapter {
private static final Set DEFAULT__AJDE_WARNINGS;
static {
DEFAULT__AJDE_WARNINGS = new HashSet();
DEFAULT__AJDE_WARNINGS.add(BuildOptionsAdapter.WARN_ASSERT_IDENITIFIER);
DEFAULT__AJDE_WARNINGS.add(BuildOptionsAdapter.WARN_CONSTRUCTOR_NAME);
DEFAULT__AJDE_WARNINGS.add(BuildOptionsAdapter.WARN_DEPRECATION);
DEFAULT__AJDE_WARNINGS.add(BuildOptionsAdapter.WARN_MASKED_CATCH_BLOCKS);
DEFAULT__AJDE_WARNINGS.add(BuildOptionsAdapter.WARN_PACKAGE_DEFAULT_METHOD);
DEFAULT__AJDE_WARNINGS.add(BuildOptionsAdapter.WARN_UNUSED_IMPORTS);
// DEFAULT__AJDE_WARNINGS.put(BuildOptionsAdapter.WARN_);
// DEFAULT__AJDE_WARNINGS.put(BuildOptionsAdapter.WARN_);
}
// private Map optionsMap;
private AjBuildManager buildManager = null;
private MessageHandlerAdapter messageHandler = null;
private BuildNotifierAdapter currNotifier = null;
private boolean initialized = false;
private boolean structureDirty = true;
private boolean showInfoMessages = false;
// set to false in incremental mode to re-do initial build
private boolean nextBuild = false;
public CompilerAdapter() {
super();
}
public void showInfoMessages(boolean show) { // XXX surface in GUI
showInfoMessages = show;
}
public boolean getShowInfoMessages() {
return showInfoMessages;
}
public void nextBuildFresh() {
if (nextBuild) {
nextBuild = false;
}
}
public void requestCompileExit() {
if (currNotifier != null) {
currNotifier.cancelBuild();
} else {
signalText("unable to cancel build process");
}
}
public boolean isStructureDirty() {
return structureDirty;
}
public void setStructureDirty(boolean structureDirty) {
this.structureDirty = structureDirty;
}
public boolean compile(String configFile, BuildProgressMonitor progressMonitor, boolean buildModel) {
if (configFile == null) {
Ajde.getDefault().getErrorHandler().handleError(
"Tried to build null config file."
);
}
init();
try {
AjBuildConfig buildConfig = genBuildConfig(configFile);
if (buildConfig == null) {
return false;
}
buildConfig.setGenerateModelMode(buildModel);
currNotifier = new BuildNotifierAdapter(progressMonitor, buildManager);
buildManager.setProgressListener(currNotifier);
messageHandler.setBuildNotifierAdapter(currNotifier);
String rtInfo = buildManager.checkRtJar(buildConfig); // !!! will get called twice
if (rtInfo != null) {
Ajde.getDefault().getErrorHandler().handleWarning(
"AspectJ Runtime error: " + rtInfo
+ " Please place a valid aspectjrt.jar on the classpath.");
return false;
}
boolean incrementalEnabled =
buildConfig.isIncrementalMode()
|| buildConfig.isIncrementalFileMode();
if (incrementalEnabled && nextBuild) {
return buildManager.incrementalBuild(buildConfig, messageHandler);
} else {
if (incrementalEnabled) {
nextBuild = incrementalEnabled;
}
return buildManager.batchBuild(buildConfig, messageHandler);
}
// } catch (OperationCanceledException ce) {
// Ajde.getDefault().getErrorHandler().handleWarning(
// "build cancelled by user");
// return false;
} catch (AbortException e) {
final IMessage message = e.getIMessage();
if (null == message) {
signalThrown(e);
} else if (null != message.getMessage()) {
Ajde.getDefault().getErrorHandler().handleWarning(message.getMessage());
} else if (null != message.getThrown()) {
signalThrown(message.getThrown());
} else {
signalThrown(e);
}
return false;
} catch (Throwable t) {
signalThrown(t);
return false;
}
}
/**
* Generate AjBuildConfig from the local configFile parameter
* plus global project and build options.
* Errors signalled using signal... methods.
* @param configFile
* @return null if invalid configuration,
* corresponding AjBuildConfig otherwise
*/
public AjBuildConfig genBuildConfig(String configFilePath) {
init();
File configFile = new File(configFilePath);
if (!configFile.exists()) {
Ajde.getDefault().getErrorHandler().handleError(
"Config file \"" + configFile + "\" does not exist."
);
return null;
}
String[] args = new String[] { "@" + configFile.getAbsolutePath() };
CountingMessageHandler handler
= CountingMessageHandler.makeCountingMessageHandler(messageHandler);
BuildArgParser parser = new BuildArgParser(handler);
AjBuildConfig config = new AjBuildConfig();
parser.populateBuildConfig(config, args, false, configFile);
configureBuildOptions(config,Ajde.getDefault().getBuildManager().getBuildOptions(),handler);
configureProjectOptions(config, Ajde.getDefault().getProjectProperties()); // !!! not what the API intended
// // -- get globals, treat as defaults used if no local values
// AjBuildConfig global = new AjBuildConfig();
// // AMC refactored into two methods to populate buildConfig from buildOptions and
// // project properties - bugzilla 29769.
// BuildOptionsAdapter buildOptions
// = Ajde.getDefault().getBuildManager().getBuildOptions();
// if (!configureBuildOptions(/* global */ config, buildOptions, handler)) {
// return null;
// }
// ProjectPropertiesAdapter projectOptions =
// Ajde.getDefault().getProjectProperties();
// configureProjectOptions(global, projectOptions);
// config.installGlobals(global);
ISourceLocation location = null;
if (config.getConfigFile() != null) {
location = new SourceLocation(config.getConfigFile(), 0);
}
String message = parser.getOtherMessages(true);
if (null != message) {
IMessage m = new Message(message, IMessage.ERROR, null, location);
handler.handleMessage(m);
}
// always force model generation in AJDE
config.setGenerateModelMode(true);
if (Ajde.getDefault().getBuildManager().getBuildOptions().getJavaOptionsMap() != null) {
config.getOptions().set(Ajde.getDefault().getBuildManager().getBuildOptions().getJavaOptionsMap());
}
return config;
// return fixupBuildConfig(config);
}
// /**
// * Fix up build configuration just before using to compile.
// * This should be delegated to a BuildAdapter callback (XXX)
// * for implementation-specific value checks
// * (e.g., to force use of project classpath rather
// * than local config classpath).
// * This implementation does no checks and returns local.
// * @param local the AjBuildConfig generated to validate
// * @param global
// * @param buildOptions
// * @param projectOptions
// * @return null if unable to fix problems or fixed AjBuildConfig if no errors
// *
// */
// protected AjBuildConfig fixupBuildConfig(AjBuildConfig local) {
// if (Ajde.getDefault().getBuildManager().getBuildOptions().getJavaOptionsMap() != null) {
// local.getJavaOptions().putAll(Ajde.getDefault().getBuildManager().getBuildOptions().getJavaOptionsMap());
// }
// return local;
// }
// /** signal error text to user */
// protected void signalError(String text) {
// }
// /** signal warning text to user */
// protected void signalWarning(String text) {
//
// }
/** signal text to user */
protected void signalText(String text) {
Ajde.getDefault().getIdeUIAdapter().displayStatusInformation(text);
}
/** signal Throwable to user (summary in GUI, trace to stdout). */
protected void signalThrown(Throwable t) { // nothing to error handler?
String text = LangUtil.unqualifiedClassName(t)
+ " thrown: "
+ t.getMessage();
Ajde.getDefault().getErrorHandler().handleError(text, t);
}
/**
* Populate options in a build configuration, using the Ajde BuildOptionsAdapter.
* Added by AMC 01.20.2003, bugzilla #29769
*/
private static boolean configureBuildOptions( AjBuildConfig config, BuildOptionsAdapter options, IMessageHandler handler) {
LangUtil.throwIaxIfNull(options, "options");
LangUtil.throwIaxIfNull(config, "config");
Map optionsToSet = new HashMap();
LangUtil.throwIaxIfNull(optionsToSet, "javaOptions");
if (options.getSourceOnePointFourMode()) {
optionsToSet.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_4);
optionsToSet.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_4);
}
String enc = options.getCharacterEncoding();
if (!LangUtil.isEmpty(enc)) {
optionsToSet.put(CompilerOptions.OPTION_Encoding, enc );
}
String compliance = options.getComplianceLevel();
if (!LangUtil.isEmpty(compliance)) {
String version = CompilerOptions.VERSION_1_4;
if ( compliance.equals( BuildOptionsAdapter.VERSION_13 ) ) {
version = CompilerOptions.VERSION_1_3;
}
optionsToSet.put(CompilerOptions.OPTION_Compliance, version );
optionsToSet.put(CompilerOptions.OPTION_Source, version );
}
String sourceLevel = options.getSourceCompatibilityLevel();
if (!LangUtil.isEmpty(sourceLevel)) {
String slVersion = CompilerOptions.VERSION_1_4;
if ( sourceLevel.equals( BuildOptionsAdapter.VERSION_13 ) ) {
slVersion = CompilerOptions.VERSION_1_3;
}
// never set a lower source level than compliance level
String setCompliance = (String) optionsToSet.get( CompilerOptions.OPTION_Compliance);
if ( ! (setCompliance.equals( CompilerOptions.VERSION_1_4 )
&& slVersion.equals(CompilerOptions.VERSION_1_3)) ) {
optionsToSet.put(CompilerOptions.OPTION_Source, slVersion);
}
}
Set warnings = options.getWarnings();
if (!LangUtil.isEmpty(warnings)) {
// turn off all warnings
disableWarnings( optionsToSet );
// then selectively enable those in the set
enableWarnings( optionsToSet, warnings );
} else if (warnings == null) {
// set default warnings on...
enableWarnings( optionsToSet, DEFAULT__AJDE_WARNINGS);
}
Set debugOptions = options.getDebugLevel();
if (!LangUtil.isEmpty(debugOptions)) {
// default is all options on, so just need to selectively
// disable
boolean sourceLine = false;
boolean varAttr = false;
boolean lineNo = false;
Iterator it = debugOptions.iterator();
while (it.hasNext()){
String debug = (String) it.next();
if ( debug.equals( BuildOptionsAdapter.DEBUG_ALL )) {
sourceLine = true;
varAttr = true;
lineNo = true;
} else if ( debug.equals( BuildOptionsAdapter.DEBUG_LINES )) {
lineNo = true;
} else if ( debug.equals( BuildOptionsAdapter.DEBUG_SOURCE )) {
sourceLine = true;
} else if ( debug.equals( BuildOptionsAdapter.DEBUG_VARS)) {
varAttr = true;
}
}
if (sourceLine) optionsToSet.put(CompilerOptions.OPTION_SourceFileAttribute,
CompilerOptions.GENERATE);
if (varAttr) optionsToSet.put(CompilerOptions.OPTION_LocalVariableAttribute,
CompilerOptions.GENERATE);
if (lineNo) optionsToSet.put(CompilerOptions.OPTION_LineNumberAttribute,
CompilerOptions.GENERATE);
}
//XXX we can't turn off import errors in 3.0 stream
// if ( options.getNoImportError() ) {
// javaOptions.put( CompilerOptions.OPTION_ReportInvalidImport,
// CompilerOptions.WARNING);
// }
if ( options.getPreserveAllLocals() ) {
optionsToSet.put( CompilerOptions.OPTION_PreserveUnusedLocal,
CompilerOptions.PRESERVE);
}
if ( !config.isIncrementalMode()
&& options.getIncrementalMode() ) {
config.setIncrementalMode(true);
}
config.getOptions().set(optionsToSet);
String toAdd = options.getNonStandardOptions();
return LangUtil.isEmpty(toAdd)
? true
: configureNonStandardOptions( config, toAdd, handler );
// ignored: lenient, porting, preprocess, strict, usejavac, workingdir
}
/**
* Helper method for configureBuildOptions
*/
private static void disableWarnings( Map options ) {
options.put(
CompilerOptions.OPTION_ReportOverridingPackageDefaultMethod,
CompilerOptions.IGNORE);
options.put(
CompilerOptions.OPTION_ReportMethodWithConstructorName,
CompilerOptions.IGNORE);
options.put(
CompilerOptions.OPTION_ReportDeprecation,
CompilerOptions.IGNORE);
options.put(
CompilerOptions.OPTION_ReportHiddenCatchBlock,
CompilerOptions.IGNORE);
options.put(
CompilerOptions.OPTION_ReportUnusedLocal,
CompilerOptions.IGNORE);
options.put(
CompilerOptions.OPTION_ReportUnusedParameter,
CompilerOptions.IGNORE);
options.put(
CompilerOptions.OPTION_ReportSyntheticAccessEmulation,
CompilerOptions.IGNORE);
options.put(
CompilerOptions.OPTION_ReportNonExternalizedStringLiteral,
CompilerOptions.IGNORE);
options.put(
CompilerOptions.OPTION_ReportAssertIdentifier,
CompilerOptions.IGNORE);
options.put(
CompilerOptions.OPTION_ReportUnusedImport,
CompilerOptions.IGNORE);
}
/**
* Helper method for configureBuildOptions
*/
private static void enableWarnings( Map options, Set warnings ) {
Iterator it = warnings.iterator();
while (it.hasNext() ) {
String thisWarning = (String) it.next();
if ( thisWarning.equals( BuildOptionsAdapter.WARN_ASSERT_IDENITIFIER )) {
options.put( CompilerOptions.OPTION_ReportAssertIdentifier,
CompilerOptions.WARNING );
} else if ( thisWarning.equals( BuildOptionsAdapter.WARN_CONSTRUCTOR_NAME )) {
options.put( CompilerOptions.OPTION_ReportMethodWithConstructorName,
CompilerOptions.WARNING );
} else if ( thisWarning.equals( BuildOptionsAdapter.WARN_DEPRECATION )) {
options.put( CompilerOptions.OPTION_ReportDeprecation,
CompilerOptions.WARNING );
} else if ( thisWarning.equals( BuildOptionsAdapter.WARN_MASKED_CATCH_BLOCKS )) {
options.put( CompilerOptions.OPTION_ReportHiddenCatchBlock,
CompilerOptions.WARNING );
} else if ( thisWarning.equals( BuildOptionsAdapter.WARN_PACKAGE_DEFAULT_METHOD )) {
options.put( CompilerOptions.OPTION_ReportOverridingPackageDefaultMethod,
CompilerOptions.WARNING );
} else if ( thisWarning.equals( BuildOptionsAdapter.WARN_SYNTHETIC_ACCESS )) {
options.put( CompilerOptions.OPTION_ReportSyntheticAccessEmulation,
CompilerOptions.WARNING );
} else if ( thisWarning.equals( BuildOptionsAdapter.WARN_UNUSED_ARGUMENTS )) {
options.put( CompilerOptions.OPTION_ReportUnusedParameter,
CompilerOptions.WARNING );
} else if ( thisWarning.equals( BuildOptionsAdapter.WARN_UNUSED_IMPORTS )) {
options.put( CompilerOptions.OPTION_ReportUnusedImport,
CompilerOptions.WARNING );
} else if ( thisWarning.equals( BuildOptionsAdapter.WARN_UNUSED_LOCALS )) {
options.put( CompilerOptions.OPTION_ReportUnusedLocal,
CompilerOptions.WARNING );
} else if ( thisWarning.equals( BuildOptionsAdapter.WARN_NLS )) {
options.put( CompilerOptions.OPTION_ReportNonExternalizedStringLiteral,
CompilerOptions.WARNING );
}
}
}
/** Local helper method for splitting option strings */
private static List tokenizeString(String str) {
List tokens = new ArrayList();
StringTokenizer tok = new StringTokenizer(str);
while ( tok.hasMoreTokens() ) {
tokens.add(tok.nextToken());
}
return tokens;
}
/**
* Helper method for configure build options.
* This reads all command-line options specified
* in the non-standard options text entry and
* sets any corresponding unset values in config.
* @return false if config failed
*/
private static boolean configureNonStandardOptions(
AjBuildConfig config,
String nonStdOptions,
IMessageHandler messageHandler ) {
if (LangUtil.isEmpty(nonStdOptions)) {
return true;
}
// Break a string into a string array of non-standard options.
// Allows for one option to include a ' '. i.e. assuming it has been quoted, it
// won't accidentally get treated as a pair of options (can be needed for xlint props file option)
List tokens = new ArrayList();
int ind = nonStdOptions.indexOf('\"');
int ind2 = nonStdOptions.indexOf('\"',ind+1);
if ((ind > -1) && (ind2 > -1)) { // dont tokenize within double quotes
String pre = nonStdOptions.substring(0,ind);
String quoted = nonStdOptions.substring(ind+1,ind2);
String post = nonStdOptions.substring(ind2+1,nonStdOptions.length());
tokens.addAll(tokenizeString(pre));
tokens.add(quoted);
tokens.addAll(tokenizeString(post));
} else {
tokens.addAll(tokenizeString(nonStdOptions));
}
String[] args = (String[])tokens.toArray(new String[]{});
// set the non-standard options in an alternate build config
// (we don't want to lose the settings we already have)
CountingMessageHandler counter
= CountingMessageHandler.makeCountingMessageHandler(messageHandler);
AjBuildConfig altConfig = AjdtCommand.genBuildConfig(args, counter);
if (counter.hasErrors()) {
return false;
}
// copy globals where local is not set
config.installGlobals(altConfig);
return true;
}
/**
* Add new options from the ProjectPropertiesAdapter to the configuration.
* <ul>
* <li>New list entries are added if not duplicates in,
* for classpath, aspectpath, injars, inpath and sourceroots</li>
* <li>Set only one new entry for output dir or output jar
* only if there is no output dir/jar entry in the config</li>
* </ul>
* Subsequent changes to the ProjectPropertiesAdapter will not affect
* the configuration.
* <p>Added by AMC 01.20.2003, bugzilla #29769
*/
private void configureProjectOptions( AjBuildConfig config, ProjectPropertiesAdapter properties ) {
// XXX no error handling in copying project properties
// Handle regular classpath
String propcp = properties.getClasspath();
if (!LangUtil.isEmpty(propcp)) {
StringTokenizer st = new StringTokenizer(propcp, File.pathSeparator);
List configClasspath = config.getClasspath();
ArrayList toAdd = new ArrayList();
while (st.hasMoreTokens()) {
String entry = st.nextToken();
if (!configClasspath.contains(entry)) {
toAdd.add(entry);
}
}
if (0 < toAdd.size()) {
ArrayList both = new ArrayList(configClasspath.size() + toAdd.size());
both.addAll(configClasspath);
both.addAll(toAdd);
config.setClasspath(both);
Ajde.getDefault().logEvent("building with classpath: " + both);
}
}
// Handle boot classpath
propcp = properties.getBootClasspath();
if (!LangUtil.isEmpty(propcp)) {
StringTokenizer st = new StringTokenizer(propcp, File.pathSeparator);
List configClasspath = config.getBootclasspath();
ArrayList toAdd = new ArrayList();
while (st.hasMoreTokens()) {
String entry = st.nextToken();
if (!configClasspath.contains(entry)) {
toAdd.add(entry);
}
}
if (0 < toAdd.size()) {
ArrayList both = new ArrayList(configClasspath.size() + toAdd.size());
both.addAll(configClasspath);
both.addAll(toAdd);
config.setBootclasspath(both);
Ajde.getDefault().logEvent("building with boot classpath: " + both);
}
}
// set outputdir and outputjar only if both not set
if ((null == config.getOutputDir() && (null == config.getOutputJar()))) {
String outPath = properties.getOutputPath();
if (!LangUtil.isEmpty(outPath)) {
config.setOutputDir(new File(outPath));
}
String outJar = properties.getOutJar();
if (!LangUtil.isEmpty(outJar)) {
config.setOutputJar(new File( outJar ) );
}
}
join(config.getSourceRoots(), properties.getSourceRoots());
join(config.getInJars(), properties.getInJars());
join(config.getInpath(),properties.getInpath());
config.setSourcePathResources(properties.getSourcePathResources());
join(config.getAspectpath(), properties.getAspectPath());
}
void join(Collection target, Collection source) { // XXX dup Util
if ((null == target) || (null == source)) {
return;
}
for (Iterator iter = source.iterator(); iter.hasNext();) {
Object next = iter.next();
if (! target.contains(next)) {
target.add(next);
}
}
}
private void init() {
if (!initialized) { // XXX plug into AJDE initialization
// Ajde.getDefault().setErrorHandler(new DebugErrorHandler());
this.messageHandler = new MessageHandlerAdapter();
buildManager = new AjBuildManager(messageHandler);
// XXX need to remove the properties file each time!
initialized = true;
}
}
class MessageHandlerAdapter extends MessageHandler {
private TaskListManager taskListManager;
private BuildNotifierAdapter buildNotifierAdapter;
public MessageHandlerAdapter() {
this.taskListManager = Ajde.getDefault().getTaskListManager();
}
public boolean handleMessage(IMessage message) throws AbortException {
IMessage.Kind kind = message.getKind();
if (isIgnoring(kind)
|| (!showInfoMessages && IMessage.INFO.equals(kind))) {
return true;
}
taskListManager.addSourcelineTask(message);
return super.handleMessage(message); // also store...
}
// --------------- adje methods
public void setBuildNotifierAdapter(BuildNotifierAdapter buildNotifierAdapter) {
this.buildNotifierAdapter = buildNotifierAdapter;
}
}
}
|
73,334
|
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
|
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
|
resolved fixed
|
b133299
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:40:02Z
| 2004-09-06T17:00:00Z
|
ajde/testsrc/org/aspectj/ajde/BuildConfigurationTests.java
|
/**********************************************************************
Copyright (c) 2003 IBM Corporation and others.
All rights reserved. This program and the accompanying materials
are made available under the terms of the Common Public License v1.0
which accompanies this distribution, and is available at
http://www.eclipse.org/legal/cpl-v10.html
Contributors:
Adrian Colyer - initial version
...
**********************************************************************/
package org.aspectj.ajde;
import java.io.File;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import junit.framework.TestSuite;
import org.aspectj.ajde.internal.CompilerAdapter;
import org.aspectj.ajde.ui.UserPreferencesAdapter;
import org.aspectj.ajde.ui.internal.AjcBuildOptions;
import org.aspectj.ajde.ui.internal.UserPreferencesStore;
import org.aspectj.ajdt.internal.core.builder.AjBuildConfig;
import org.aspectj.bridge.*;
import org.aspectj.bridge.MessageHandler;
import org.aspectj.util.LangUtil;
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
/**
* Tests that a correctly populated AjBuildConfig object is created
* in reponse to the setting in BuildOptionsAdapter and
* ProjectPropretiesAdapter
*/
public class BuildConfigurationTests extends AjdeTestCase {
private CompilerAdapter compilerAdapter;
private AjBuildConfig buildConfig = null;
private AjcBuildOptions buildOptions = null;
private UserPreferencesAdapter preferencesAdapter = null;
private NullIdeProperties projectProperties = null;
private MessageHandler messageHandler;
private static final String configFile =
AjdeTests.TESTDATA_PATH + "/examples/figures-coverage/all.lst";
public BuildConfigurationTests( String name ) {
super( name );
}
public static void main(String[] args) {
junit.swingui.TestRunner.run(BuildConfigurationTests.class);
}
public static TestSuite suite() {
TestSuite result = new TestSuite();
result.addTestSuite(BuildConfigurationTests.class);
return result;
}
// The tests...
public void testCharacterEncoding() {
buildOptions.setCharacterEncoding( "UTF-8" );
buildConfig = compilerAdapter.genBuildConfig( configFile );
assertTrue(configFile + " failed", null != buildConfig);
Map options = buildConfig.getOptions().getMap();
String encoding = (String) options.get( CompilerOptions.OPTION_Encoding );
assertEquals( "character encoding", "UTF-8", encoding );
}
public void testComplianceLevel() {
buildOptions.setComplianceLevel( BuildOptionsAdapter.VERSION_14 );
buildConfig = compilerAdapter.genBuildConfig( configFile );
assertTrue(configFile + " failed", null != buildConfig);
Map options = buildConfig.getOptions().getMap();
String compliance = (String) options.get(CompilerOptions.OPTION_Compliance);
String sourceLevel = (String) options.get(CompilerOptions.OPTION_Source);
assertEquals( "compliance level", CompilerOptions.VERSION_1_4, compliance);
assertEquals( "source level", CompilerOptions.VERSION_1_4, sourceLevel );
}
public void testSourceCompatibilityLevel() {
buildOptions.setComplianceLevel( BuildOptionsAdapter.VERSION_13);
buildOptions.setSourceCompatibilityLevel( BuildOptionsAdapter.VERSION_14);
buildConfig = compilerAdapter.genBuildConfig( configFile );
assertTrue(configFile + " failed", null != buildConfig);
Map options = buildConfig.getOptions().getMap();
String compliance = (String) options.get(CompilerOptions.OPTION_Compliance);
String sourceLevel = (String) options.get(CompilerOptions.OPTION_Source);
assertEquals( "compliance level", CompilerOptions.VERSION_1_3, compliance);
assertEquals( "source level", CompilerOptions.VERSION_1_4, sourceLevel );
}
public void testSourceIncompatibilityLevel() {
// this config should "fail" and leave source level at 1.4
buildOptions.setComplianceLevel( BuildOptionsAdapter.VERSION_14);
buildOptions.setSourceCompatibilityLevel( BuildOptionsAdapter.VERSION_13);
buildConfig = compilerAdapter.genBuildConfig( configFile );
assertTrue(configFile + " failed", null != buildConfig);
Map options = buildConfig.getOptions().getMap();
String compliance = (String) options.get(CompilerOptions.OPTION_Compliance);
String sourceLevel = (String) options.get(CompilerOptions.OPTION_Source);
assertEquals( "compliance level", CompilerOptions.VERSION_1_4, compliance);
assertEquals( "source level", CompilerOptions.VERSION_1_4, sourceLevel );
}
public void testNullWarnings() {
buildOptions.setWarnings( null );
buildConfig = compilerAdapter.genBuildConfig( configFile );
assertTrue(configFile + " failed", null != buildConfig);
Map options = buildConfig.getOptions().getMap();
// this should leave us with the default warnings
assertOptionEquals( "report overriding package default",
options,
CompilerOptions.OPTION_ReportOverridingPackageDefaultMethod,
CompilerOptions.WARNING);
assertOptionEquals( "report method with cons name",
options,
CompilerOptions.OPTION_ReportMethodWithConstructorName,
CompilerOptions.WARNING);
assertOptionEquals( "report deprecation",
options,
CompilerOptions.OPTION_ReportDeprecation,
CompilerOptions.WARNING);
assertOptionEquals( "report hidden catch block",
options,
CompilerOptions.OPTION_ReportHiddenCatchBlock,
CompilerOptions.WARNING);
assertOptionEquals( "report unused local",
options,
CompilerOptions.OPTION_ReportUnusedLocal,
CompilerOptions.IGNORE);
assertOptionEquals( "report unused param",
options,
CompilerOptions.OPTION_ReportUnusedParameter,
CompilerOptions.IGNORE);
assertOptionEquals( "report synthectic access",
options,
CompilerOptions.OPTION_ReportSyntheticAccessEmulation,
CompilerOptions.IGNORE);
assertOptionEquals( "report non-externalized string literal",
options,
CompilerOptions.OPTION_ReportNonExternalizedStringLiteral,
CompilerOptions.IGNORE);
assertOptionEquals( "report assert identifer",
options,
CompilerOptions.OPTION_ReportAssertIdentifier,
CompilerOptions.WARNING);
}
// public void testEmptyWarnings() {
// buildOptions.setWarnings( new HashSet() );
// buildConfig = compilerAdapter.genBuildConfig( configFile );
// Map options = buildConfig.getJavaOptions();
//
// // this should leave us with the user specifiable warnings
// // turned off
// assertOptionEquals( "report overriding package default",
// options,
// CompilerOptions.OPTION_ReportOverridingPackageDefaultMethod,
// CompilerOptions.WARNING);
// assertOptionEquals( "report method with cons name",
// options,
// CompilerOptions.OPTION_ReportMethodWithConstructorName,
// CompilerOptions.WARNING);
// assertOptionEquals( "report deprecation",
// options,
// CompilerOptions.OPTION_ReportDeprecation,
// CompilerOptions.WARNING);
// assertOptionEquals( "report hidden catch block",
// options,
// CompilerOptions.OPTION_ReportHiddenCatchBlock,
// CompilerOptions.WARNING);
// assertOptionEquals( "report unused local",
// options,
// CompilerOptions.OPTION_ReportUnusedLocal,
// CompilerOptions.WARNING);
// assertOptionEquals( "report unused param",
// options,
// CompilerOptions.OPTION_ReportUnusedParameter,
// CompilerOptions.WARNING);
// assertOptionEquals( "report synthectic access",
// options,
// CompilerOptions.OPTION_ReportSyntheticAccessEmulation,
// CompilerOptions.WARNING);
// assertOptionEquals( "report non-externalized string literal",
// options,
// CompilerOptions.OPTION_ReportNonExternalizedStringLiteral,
// CompilerOptions.WARNING);
// assertOptionEquals( "report assert identifer",
// options,
// CompilerOptions.OPTION_ReportAssertIdentifier,
// CompilerOptions.WARNING);
// }
public void testSetOfWarnings() {
HashSet warnings = new HashSet();
warnings.add( BuildOptionsAdapter.WARN_ASSERT_IDENITIFIER );
warnings.add( BuildOptionsAdapter.WARN_CONSTRUCTOR_NAME );
warnings.add( BuildOptionsAdapter.WARN_DEPRECATION );
warnings.add( BuildOptionsAdapter.WARN_MASKED_CATCH_BLOCKS );
warnings.add( BuildOptionsAdapter.WARN_PACKAGE_DEFAULT_METHOD );
warnings.add( BuildOptionsAdapter.WARN_SYNTHETIC_ACCESS );
warnings.add( BuildOptionsAdapter.WARN_UNUSED_ARGUMENTS );
warnings.add( BuildOptionsAdapter.WARN_UNUSED_IMPORTS );
warnings.add( BuildOptionsAdapter.WARN_UNUSED_LOCALS );
warnings.add( BuildOptionsAdapter.WARN_NLS );
buildOptions.setWarnings( warnings );
buildConfig = compilerAdapter.genBuildConfig( configFile );
assertTrue(configFile + " failed", null != buildConfig);
Map options = buildConfig.getOptions().getMap();
// this should leave us with all the user specifiable warnings
// turned on
assertOptionEquals( "report overriding package default",
options,
CompilerOptions.OPTION_ReportOverridingPackageDefaultMethod,
CompilerOptions.WARNING);
assertOptionEquals( "report method with cons name",
options,
CompilerOptions.OPTION_ReportMethodWithConstructorName,
CompilerOptions.WARNING);
assertOptionEquals( "report deprecation",
options,
CompilerOptions.OPTION_ReportDeprecation,
CompilerOptions.WARNING);
assertOptionEquals( "report hidden catch block",
options,
CompilerOptions.OPTION_ReportHiddenCatchBlock,
CompilerOptions.WARNING);
assertOptionEquals( "report unused local",
options,
CompilerOptions.OPTION_ReportUnusedLocal,
CompilerOptions.WARNING);
assertOptionEquals( "report unused param",
options,
CompilerOptions.OPTION_ReportUnusedParameter,
CompilerOptions.WARNING);
assertOptionEquals( "report synthectic access",
options,
CompilerOptions.OPTION_ReportSyntheticAccessEmulation,
CompilerOptions.WARNING);
assertOptionEquals( "report non-externalized string literal",
options,
CompilerOptions.OPTION_ReportNonExternalizedStringLiteral,
CompilerOptions.WARNING);
assertOptionEquals( "report assert identifer",
options,
CompilerOptions.OPTION_ReportAssertIdentifier,
CompilerOptions.WARNING);
}
public void testNoDebugOptions() {
buildOptions.setDebugLevel( null );
buildConfig = compilerAdapter.genBuildConfig( configFile );
assertTrue(configFile + " failed", null != buildConfig);
Map options = buildConfig.getOptions().getMap();
// this should leave us with the default debug settings
assertOptionEquals( "debug source",
options,
CompilerOptions.OPTION_SourceFileAttribute,
CompilerOptions.GENERATE);
assertOptionEquals( "debug lines",
options,
CompilerOptions.OPTION_LineNumberAttribute,
CompilerOptions.GENERATE);
assertOptionEquals( "debug vars",
options,
CompilerOptions.OPTION_LocalVariableAttribute,
CompilerOptions.GENERATE);
}
public void testEmptyDebugOptions() {
buildOptions.setDebugLevel( new HashSet() );
buildConfig = compilerAdapter.genBuildConfig( configFile );
assertTrue(configFile + " failed", null != buildConfig);
Map options = buildConfig.getOptions().getMap();
// this should leave us with the default debug
assertOptionEquals( "debug source",
options,
CompilerOptions.OPTION_SourceFileAttribute,
CompilerOptions.GENERATE);
assertOptionEquals( "debug lines",
options,
CompilerOptions.OPTION_LineNumberAttribute,
CompilerOptions.GENERATE);
assertOptionEquals( "debug vars",
options,
CompilerOptions.OPTION_LocalVariableAttribute,
CompilerOptions.GENERATE);
}
public void testDebugAll() {
HashSet debugOpts = new HashSet();
debugOpts.add( BuildOptionsAdapter.DEBUG_ALL );
buildOptions.setDebugLevel( debugOpts );
buildConfig = compilerAdapter.genBuildConfig( configFile );
assertTrue(configFile + " failed", null != buildConfig);
Map options = buildConfig.getOptions().getMap();
// this should leave us with all debug on
assertOptionEquals( "debug source",
options,
CompilerOptions.OPTION_SourceFileAttribute,
CompilerOptions.GENERATE);
assertOptionEquals( "debug lines",
options,
CompilerOptions.OPTION_LineNumberAttribute,
CompilerOptions.GENERATE);
assertOptionEquals( "debug vars",
options,
CompilerOptions.OPTION_LocalVariableAttribute,
CompilerOptions.GENERATE);
}
public void testDebugSet() {
HashSet debugOpts = new HashSet();
debugOpts.add( BuildOptionsAdapter.DEBUG_SOURCE );
debugOpts.add( BuildOptionsAdapter.DEBUG_VARS );
buildOptions.setDebugLevel( debugOpts );
buildConfig = compilerAdapter.genBuildConfig( configFile );
assertTrue(configFile + " failed", null != buildConfig);
Map options = buildConfig.getOptions().getMap();
// this should leave us with all debug on
assertOptionEquals( "debug source",
options,
CompilerOptions.OPTION_SourceFileAttribute,
CompilerOptions.GENERATE);
assertOptionEquals( "debug lines",
options,
CompilerOptions.OPTION_LineNumberAttribute,
CompilerOptions.GENERATE);
assertOptionEquals( "debug vars",
options,
CompilerOptions.OPTION_LocalVariableAttribute,
CompilerOptions.GENERATE);
}
public void testNoImport() {
buildOptions.setNoImportError( true );
buildConfig = compilerAdapter.genBuildConfig( configFile );
assertTrue(configFile + " failed", null != buildConfig);
// Map options = buildConfig.getJavaOptions();
// String noImport = (String) options.get( CompilerOptions.OPTION_ReportInvalidImport );
// assertEquals( "no import", CompilerOptions.WARNING, noImport );
// buildOptions.setNoImportError( false );
}
public void testPreserveAllLocals() {
buildOptions.setPreserveAllLocals( true );
buildConfig = compilerAdapter.genBuildConfig( configFile );
assertTrue(configFile + " failed", null != buildConfig);
Map options = buildConfig.getOptions().getMap();
String preserve = (String) options.get( CompilerOptions.OPTION_PreserveUnusedLocal );
assertEquals( "preserve unused", CompilerOptions.PRESERVE, preserve );
}
public void testNonStandardOptions() {
buildOptions.setNonStandardOptions( "-XnoWeave" );
buildConfig = compilerAdapter.genBuildConfig( configFile );
assertTrue(configFile + " failed", null != buildConfig);
assertTrue( "XnoWeave", buildConfig.isNoWeave() );
buildOptions.setNonStandardOptions( "-XserializableAspects" );
buildConfig = compilerAdapter.genBuildConfig( configFile );
assertTrue( "XserializableAspects", buildConfig.isXserializableAspects() );
buildOptions.setNonStandardOptions( "-XnoInline" );
buildConfig = compilerAdapter.genBuildConfig( configFile );
assertTrue( "XnoInline", buildConfig.isXnoInline());
buildOptions.setNonStandardOptions( "-Xlint" );
buildConfig = compilerAdapter.genBuildConfig( configFile );
assertEquals( "Xlint", AjBuildConfig.AJLINT_DEFAULT,
buildConfig.getLintMode());
buildOptions.setNonStandardOptions( "-Xlint:error" );
buildConfig = compilerAdapter.genBuildConfig( configFile );
assertEquals( "Xlint", AjBuildConfig.AJLINT_ERROR,
buildConfig.getLintMode());
// XXX test for lintfile
// buildOptions.setNonStandardOptions( "-Xlintfile testdata/AspectJBuildManagerTest/lint.properties" );
// buildConfig = compilerAdapter.genBuildConfig( configFile );
// assertEquals( "Xlintfile", new File( "testdata/AspectJBuildManagerTest/lint.properties" ).getAbsolutePath(),
// buildConfig.getLintSpecFile().toString());
// and a few options thrown in at once
buildOptions.setNonStandardOptions( "-Xlint -XnoInline -XserializableAspects" );
buildConfig = compilerAdapter.genBuildConfig( configFile );
assertTrue(configFile + " failed", null != buildConfig);
assertEquals( "Xlint", AjBuildConfig.AJLINT_DEFAULT,
buildConfig.getLintMode());
assertTrue( "XnoInline", buildConfig.isXnoInline());
assertTrue( "XserializableAspects", buildConfig.isXserializableAspects() );
}
public void testSourceRoots() {
Set roots = new HashSet();
projectProperties.setSourceRoots( roots );
buildConfig = compilerAdapter.genBuildConfig( configFile );
assertTrue(configFile + " failed", null != buildConfig);
List configRoots = buildConfig.getSourceRoots();
assertTrue( "no source dirs", configRoots.isEmpty() );
File f = new File( AjdeTests.TESTDATA_PATH + "/examples/figures/figures-coverage" );
roots.add( f );
buildConfig = compilerAdapter.genBuildConfig( configFile );
assertTrue(configFile + " failed", null != buildConfig);
List configRoots2 = buildConfig.getSourceRoots();
assertTrue( "one source dir", configRoots2.size() == 1 );
assertTrue( "source dir", configRoots2.contains(f) );
File f2 = new File( AjdeTests.TESTDATA_PATH + "/examples/figures/figures-demo" );
roots.add( f2 );
buildConfig = compilerAdapter.genBuildConfig( configFile );
assertTrue(configFile + " failed", null != buildConfig);
List configRoots3 = buildConfig.getSourceRoots();
assertTrue( "two source dirs", configRoots3.size() == 2 );
assertTrue( "source dir 1", configRoots3.contains(f) );
assertTrue( "source dir 2", configRoots3.contains(f2) );
}
public void testInJars() {
Set jars = new HashSet();
projectProperties.setInJars( jars );
buildConfig = compilerAdapter.genBuildConfig( configFile );
assertTrue(configFile + " failed", null != buildConfig);
List inJars = buildConfig.getInJars();
assertTrue( "no in jars", inJars.isEmpty() );
File f = new File( "jarone.jar" );
jars.add( f );
buildConfig = compilerAdapter.genBuildConfig( configFile );
assertTrue(configFile + " failed", null != buildConfig);
List inJars2 = buildConfig.getInJars();
assertTrue( "one in jar", inJars2.size() == 1 );
assertTrue( "in jar", inJars2.contains(f) );
File f2 = new File( "jartwo.jar" );
jars.add( f2 );
buildConfig = compilerAdapter.genBuildConfig( configFile );
List inJars3 = buildConfig.getInJars();
assertTrue( "two in jars", inJars3.size() == 2 );
assertTrue( "in jar 1", inJars3.contains(f) );
assertTrue( "in jar 2", inJars3.contains(f2) );
}
public void testAspectPath() {
Set aspects = new HashSet();
projectProperties.setAspectPath( aspects );
buildConfig = compilerAdapter.genBuildConfig( configFile );
assertTrue(configFile + " failed", null != buildConfig);
List aPath = buildConfig.getAspectpath();
assertTrue( "no aspect path", aPath.isEmpty() );
File f = new File( "jarone.jar" );
aspects.add( f );
buildConfig = compilerAdapter.genBuildConfig( configFile );
assertTrue(configFile + " failed", null != buildConfig);
List aPath2 = buildConfig.getAspectpath();
assertEquals("aspectpath", 1, aPath2.size());
assertTrue( "1 aspectpath", aPath2.contains(f) );
File f2 = new File( "jartwo.jar" );
aspects.add( f2 );
buildConfig = compilerAdapter.genBuildConfig( configFile );
assertTrue(configFile + " failed", null != buildConfig);
List aPath3 = buildConfig.getAspectpath();
assertTrue( "two jars in path", aPath3.size() == 2 );
assertTrue( "1 aspectpath", aPath3.contains(f) );
assertTrue( "2 aspectpath", aPath3.contains(f2) );
}
public void testOutJar() {
String outJar = "mybuild.jar";
projectProperties.setOutJar( outJar );
buildConfig = compilerAdapter.genBuildConfig( configFile );
assertTrue(configFile + " failed", null != buildConfig);
assertNotNull("output jar", buildConfig.getOutputJar());
assertEquals( "out jar", outJar, buildConfig.getOutputJar().toString() );
}
protected void setUp() throws Exception {
preferencesAdapter = new UserPreferencesStore(false);
buildOptions = new AjcBuildOptions(preferencesAdapter);
compilerAdapter = new CompilerAdapter();
projectProperties = new NullIdeProperties( "" );
messageHandler = new MessageHandler(true);
ErrorHandler handler = new ErrorHandler() {
public void handleWarning(String message) {
MessageUtil.warn(messageHandler, message);
}
public void handleError(String message) {
MessageUtil.error(messageHandler, message);
}
public void handleError(String message, Throwable t) {
IMessage m = new Message(message, IMessage.ERROR, t, null);
messageHandler.handleMessage(m);
}
};
try {
// String s = null;
Ajde.init(
null,
null,
null,
projectProperties,
buildOptions,
null,
null,
handler);
} catch (Throwable t) {
String s = "Unable to initialize AJDE "
+ LangUtil.renderException(t);
assertTrue(s, false);
}
}
protected void tearDown() throws Exception {
super.tearDown();
preferencesAdapter = null;
buildOptions = null;
compilerAdapter = null;
projectProperties = null;
messageHandler = null;
}
private void assertOptionEquals( String reason, Map options, String optionName, String value) {
String mapValue = (String) options.get(optionName);
assertEquals( reason, value, mapValue );
}
}
|
73,334
|
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
|
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
|
resolved fixed
|
b133299
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:40:02Z
| 2004-09-06T17:00:00Z
|
ajde/testsrc/org/aspectj/ajde/ExtensionTests.java
|
/*******************************************************************************
* Copyright (c) 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Andy Clement - initial implementation
*******************************************************************************/
package org.aspectj.ajde;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.io.File;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.IProgramElement;
import org.aspectj.bridge.IMessage;
import org.aspectj.tools.ajc.AjcTestCase;
import org.aspectj.tools.ajc.CompilationResult;
import org.eclipse.jdt.core.compiler.IProblem;
/**
* Tests the 'extensions' to AJDE:
* 1) ID is now available on messages to allow you to see what 'kind' of
* message it is - this activates quick fixes/etc in Eclipse.
*/
public class ExtensionTests extends AjcTestCase {
public static final String PROJECT_DIR = "extensions";
private File baseDir;
protected void setUp() throws Exception {
super.setUp();
baseDir = new File("../ajde/testdata",PROJECT_DIR);
}
/**
* Aim: Check that the ID of certain message kinds are correct
*
* ajc -warn:unusedImport UnusedImport.java
*
* Expected result is that id matches IProblem.UnusedImport
*/
public void testMessageID () {
String[] args = new String[] {"UnusedImport.java","-warn:unusedImport"};
CompilationResult result = ajc(baseDir,args);
List l = result.getWarningMessages();
IMessage m = ((IMessage)l.get(0));
assertTrue("Expected ID of message to be "+IProblem.UnusedImport+" (UnusedImport) but found an ID of "+m.getID(),
m.getID()==IProblem.UnusedImport);
}
public void testInnerClassesInASM() {
String[] args = new String[] {"InnerClasses.java","-emacssym"};
CompilationResult result = ajc(baseDir,args);
List l = result.getWarningMessages();
Properties p = AsmManager.ModelInfo.summarizeModel().getProperties();
System.out.println("Structure Model for InnerClasses.java:");
walkit(AsmManager.getDefault().getHierarchy().getRoot(),0);
foundNode = null;
findChild("main",AsmManager.getDefault().getHierarchy().getRoot());
assertTrue("Should have found node 'main' in the model",foundNode!=null);
IProgramElement runnableChild = getChild(foundNode,"new Runnable() {..}");
assertTrue("'main' should have a child 'new Runnable() {..}'",
runnableChild!=null);
assertTrue("'new Runnable() {..}' should have a 'run' child",
getChild(runnableChild,"run")!=null);
/* Left hand side is before the fix, right hand side is after:
<root>
InnerClasses.java
import declarations
InnerClasses
A A
method method
1 new Runnable() {..}
run run
main main
2 new Runnable() {..}
run run
3 new Object() {..}
toString toString
4 new Runnable
run run
*/
}
private IProgramElement getChild(IProgramElement parent,String s) {
List kids = parent.getChildren();
for (Iterator iter = kids.iterator(); iter.hasNext();) {
IProgramElement element = (IProgramElement) iter.next();
if (element.getName().indexOf(s)!=-1) return element;
}
return null;
}
private IProgramElement foundNode = null;
private void findChild(String s,IProgramElement ipe) {
if (ipe == null) return;
if (ipe.getName().indexOf(s)!=-1) {foundNode = ipe; return;}
if (ipe.getChildren()!=null) {
List kids = ipe.getChildren();
for (Iterator iter = kids.iterator(); iter.hasNext();) {
IProgramElement element = (IProgramElement) iter.next();
findChild(s,element);
}
}
}
public void walkit(IProgramElement ipe,int indent) {
if (ipe!=null) {
for (int i = 0 ;i<indent;i++) System.out.print(" ");
System.out.println(ipe.toLabelString());//getName());
if (ipe.getChildren()!=null) {
List kids = ipe.getChildren();
for (Iterator iter = kids.iterator(); iter.hasNext();) {
IProgramElement element = (IProgramElement) iter.next();
walkit(element,indent+2);
}
}
}
}
/**
* Aim: Check that the start/end of certain warnings are correct
*
* ajc -warn:unusedImport UnusedImport.java
*
* Expected result is first warning message has start=7 end=20
*/
public void testMessageSourceStartEnd() {
String[] args = new String[] {"UnusedImport.java","-warn:unusedImport"};
CompilationResult result = ajc(baseDir,args);
List l = result.getWarningMessages();
IMessage m = ((IMessage)l.get(0));
assertTrue("Expected source start to be 7 but was "+m.getSourceStart(),
m.getSourceStart()==7);
assertTrue("Expected source end to be 20 but was "+m.getSourceEnd(),
m.getSourceEnd()==20);
}
}
|
73,334
|
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
|
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
|
resolved fixed
|
b133299
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:40:02Z
| 2004-09-06T17:00:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/ajc/AjdtCommand.java
|
/* *******************************************************************
* 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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.ajc;
import org.aspectj.ajdt.internal.core.builder.*;
import org.aspectj.bridge.*;
import org.aspectj.weaver.Dump;
import org.eclipse.jdt.internal.core.builder.MissingSourceFileException;
/**
* ICommand adapter for the AspectJ compiler.
* Not thread-safe.
*/
public class AjdtCommand implements ICommand {
/** Message String for any AbortException thrown from ICommand API's */
public static final String ABORT_MESSAGE = "ABORT";
// private boolean canRepeatCommand = true;
AjBuildManager buildManager = null;
String[] savedArgs = null;
/**
* Run AspectJ compiler, wrapping any exceptions thrown as
* ABORT messages (containing ABORT_MESSAGE String).
* @param args the String[] for the compiler
* @param handler the IMessageHandler for any messages
* @see org.aspectj.bridge.ICommand#runCommand(String[], IMessageHandler)
* @return false if handler has errors or the command failed
*/
public boolean runCommand(String[] args, IMessageHandler handler) {
buildManager = new AjBuildManager(handler);
savedArgs = new String[args.length];
System.arraycopy(args, 0, savedArgs, 0, savedArgs.length);
for (int i = 0; i < args.length; i++) {
// AMC - PR58681. No need to abort on -help as the Eclipse compiler does the right thing.
// if ("-help".equals(args[i])) {
// // should be info, but handler usually suppresses
// MessageUtil.abort(handler, BuildArgParser.getUsage());
// return true;
// } else
if ("-X".equals(args[i])) {
// should be info, but handler usually suppresses
MessageUtil.abort(handler, BuildArgParser.getXOptionUsage());
return true;
}
}
return doCommand(handler, false);
}
/**
* Run AspectJ compiler, wrapping any exceptions thrown as
* ABORT messages (containing ABORT_MESSAGE String).
* @param handler the IMessageHandler for any messages
* @see org.aspectj.bridge.ICommand#repeatCommand(IMessageHandler)
* @return false if handler has errors or the command failed
*/
public boolean repeatCommand(IMessageHandler handler) {
if (null == buildManager) {
MessageUtil.abort(handler, "repeatCommand called before runCommand");
return false;
}
return doCommand(handler, true);
}
/**
* Delegate of both runCommand and repeatCommand.
* This invokes the argument parser each time
* (even when repeating).
* If the parser detects errors, this signals an
* abort with the usage message and returns false.
* @param handler the IMessageHandler sink for any messages
* @param repeat if true, do incremental build, else do batch build
* @return false if handler has any errors or command failed
*/
protected boolean doCommand(IMessageHandler handler, boolean repeat) {
try {
//buildManager.setMessageHandler(handler);
CountingMessageHandler counter = new CountingMessageHandler(handler);
if (counter.hasErrors()) {
return false;
}
// regenerate configuration b/c world might have changed (?)
AjBuildConfig config = genBuildConfig(savedArgs, counter);
if (!config.shouldProceed()) {
return true;
}
if (!config.hasSources()) {
MessageUtil.error(counter, "no sources specified");
}
if (counter.hasErrors()) { // print usage for config errors
String usage = BuildArgParser.getUsage();
MessageUtil.abort(handler, usage);
return false;
}
//System.err.println("errs: " + counter.hasErrors());
boolean result = ((repeat
? buildManager.incrementalBuild(config, handler)
: buildManager.batchBuild(config, handler))
&& !counter.hasErrors());
Dump.dumpOnExit();
return result;
} catch (AbortException ae) {
if (ae.isSilent()) {
throw ae;
} else {
MessageUtil.abort(handler, ABORT_MESSAGE, ae);
}
} catch (MissingSourceFileException t) {
MessageUtil.error(handler, t.getMessage());
} catch (Throwable t) {
MessageUtil.abort(handler, ABORT_MESSAGE, t);
Dump.dumpWithException(t);
}
return false;
}
/**
* This creates a build configuration for the arguments.
* Errors reported to the handler:
* <ol>
* <li>The parser detects some directly</li>
* <li>The parser grabs some from the error stream
* emitted by its superclass</li>
* <li>The configuration has a self-test</li>
* </ol>
* In the latter two cases, the errors do not have
* a source location context for locating the error.
*/
public static AjBuildConfig genBuildConfig(String[] args, CountingMessageHandler handler) {
BuildArgParser parser = new BuildArgParser(handler);
AjBuildConfig config = parser.genBuildConfig(args);
ISourceLocation location = null;
if (config.getConfigFile() != null) {
location = new SourceLocation(config.getConfigFile(), 0);
}
String message = parser.getOtherMessages(true);
if (null != message) {
IMessage.Kind kind = inferKind(message);
IMessage m = new Message(message, kind, null, location);
handler.handleMessage(m);
}
// message = config.configErrors();
// if (null != message) {
// IMessage.Kind kind = inferKind(message);
// IMessage m = new Message(message, kind, null, location);
// handler.handleMessage(m);
// }
return config;
}
/** @return IMessage.WARNING unless message contains error or info */
protected static IMessage.Kind inferKind(String message) { // XXX dubious
if (-1 != message.indexOf("error")) {
return IMessage.ERROR;
} else if (-1 != message.indexOf("info")) {
return IMessage.INFO;
} else {
return IMessage.WARNING;
}
}
}
|
73,334
|
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
|
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
|
resolved fixed
|
b133299
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:40:02Z
| 2004-09-06T17:00:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/ajc/BuildArgParser.java
|
/* *******************************************************************
* 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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.ajc;
import java.io.*;
import java.util.*;
import org.aspectj.ajdt.internal.core.builder.*;
import org.aspectj.bridge.*;
import org.aspectj.util.*;
import org.aspectj.weaver.Dump;
import org.aspectj.weaver.WeaverMessages;
import org.eclipse.jdt.core.compiler.InvalidInputException;
import org.eclipse.jdt.internal.compiler.batch.Main;
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
public class BuildArgParser extends Main {
private static final String BUNDLE_NAME = "org.aspectj.ajdt.ajc.messages";
private static boolean LOADED_BUNDLE = false;
static {
bundle = ResourceBundle.getBundle(BUNDLE_NAME);
if (!LOADED_BUNDLE) {
LOADED_BUNDLE = true;
}
}
/** to initialize super's PrintWriter but refer to underlying StringWriter */
private static class StringPrintWriter extends PrintWriter {
public final StringWriter stringWriter;
StringPrintWriter(StringWriter sw) {
super(sw);
this.stringWriter = sw;
}
}
/** @return multi-line String usage for the compiler */
public static String getUsage() {
return Main.bind("misc.usage");
}
public static String getXOptionUsage() {
return Main.bind("xoption.usage");
}
/**
* StringWriter sink for some errors.
* This only captures errors not handled by any IMessageHandler parameter
* and only when no PrintWriter is set in the constructor.
* XXX This relies on (Sun's) implementation of StringWriter,
* which returns the actual (not copy) internal StringBuffer.
*/
private final StringBuffer errorSink;
private IMessageHandler handler;
/**
* Overrides super's bundle.
*/
public BuildArgParser(PrintWriter writer, IMessageHandler handler) {
super(writer, writer, false);
if (writer instanceof StringPrintWriter) {
errorSink = ((StringPrintWriter) writer).stringWriter.getBuffer();
} else {
errorSink = null;
}
this.handler = handler;
}
/** Set up to capture messages using getOtherMessages(boolean) */
public BuildArgParser(IMessageHandler handler) {
this(new StringPrintWriter(new StringWriter()),handler);
}
/**
* Generate build configuration for the input args,
* passing to handler any error messages.
* @param args the String[] arguments for the build configuration
* @return AjBuildConfig per args,
* which will be invalid unless there are no handler errors.
*/
public AjBuildConfig genBuildConfig(String[] args) {
AjBuildConfig config = new AjBuildConfig();
populateBuildConfig(config, args, true, null);
return config;
}
/**
* Generate build configuration for the input args,
* passing to handler any error messages.
* @param args the String[] arguments for the build configuration
* @param setClasspath determines if the classpath should be parsed and set on the build configuration
* @param configFile can be null
* @return AjBuildConfig per args,
* which will be invalid unless there are no handler errors.
*/
public AjBuildConfig populateBuildConfig(AjBuildConfig buildConfig, String[] args, boolean setClasspath, File configFile) {
Dump.saveCommandLine(args);
buildConfig.setConfigFile(configFile);
try {
// sets filenames to be non-null in order to make sure that file paramters are ignored
super.filenames = new String[] { "" };
AjcConfigParser parser = new AjcConfigParser(buildConfig, handler);
parser.parseCommandLine(args);
boolean swi = buildConfig.getShowWeavingInformation();
// Now jump through firey hoops to turn them on/off
if (handler instanceof CountingMessageHandler) {
IMessageHandler delegate = ((CountingMessageHandler)handler).delegate;
// Without dontIgnore() on the IMessageHandler interface, we have to do this *blurgh*
if (delegate instanceof MessageHandler) {
if (swi)
((MessageHandler)delegate).dontIgnore(IMessage.WEAVEINFO);
else
((MessageHandler)delegate).ignore(IMessage.WEAVEINFO);
}
}
boolean incrementalMode = buildConfig.isIncrementalMode()
|| buildConfig.isIncrementalFileMode();
List fileList = new ArrayList();
List files = parser.getFiles();
if (!LangUtil.isEmpty(files)) {
if (incrementalMode) {
MessageUtil.error(handler, "incremental mode only handles source files using -sourceroots");
} else {
fileList.addAll(files);
}
}
List javaArgList = new ArrayList();
// disable all special eclipse warnings by default - why???
//??? might want to instead override getDefaultOptions()
javaArgList.add("-warn:none");
// these next four lines are some nonsense to fool the eclipse batch compiler
// without these it will go searching for reasonable values from properties
//TODO fix org.eclipse.jdt.internal.compiler.batch.Main so this hack isn't needed
javaArgList.add("-classpath");
javaArgList.add(System.getProperty("user.dir"));
javaArgList.add("-bootclasspath");
javaArgList.add(System.getProperty("user.dir"));
javaArgList.addAll(parser.getUnparsedArgs());
super.configure((String[])javaArgList.toArray(new String[javaArgList.size()]));
if (!proceed) {
buildConfig.doNotProceed();
return buildConfig;
}
if (buildConfig.getSourceRoots() != null) {
for (Iterator i = buildConfig.getSourceRoots().iterator(); i.hasNext(); ) {
fileList.addAll(collectSourceRootFiles((File)i.next()));
}
}
buildConfig.setFiles(fileList);
if (destinationPath != null) { // XXX ?? unparsed but set?
buildConfig.setOutputDir(new File(destinationPath));
}
if (setClasspath) {
buildConfig.setClasspath(getClasspath(parser));
buildConfig.setBootclasspath(getBootclasspath(parser));
}
if (incrementalMode
&& (0 == buildConfig.getSourceRoots().size())) {
MessageUtil.error(handler, "specify a source root when in incremental mode");
}
/*
* Ensure we don't overwrite injars, inpath or aspectpath with outjar
* bug-71339
*/
File outjar = buildConfig.getOutputJar();
if (outjar != null) {
/* Search injars */
for (Iterator i = buildConfig.getInJars().iterator(); i.hasNext(); ) {
File injar = (File)i.next();
if (injar.equals(outjar)) {
String message = WeaverMessages.format(WeaverMessages.OUTJAR_IN_INPUT_PATH);
MessageUtil.error(handler,message);
}
}
/* Search inpath */
for (Iterator i = buildConfig.getInpath().iterator(); i.hasNext(); ) {
File inPathElement = (File)i.next();
if (!inPathElement.isDirectory() && inPathElement.equals(outjar)) {
String message = WeaverMessages.format(WeaverMessages.OUTJAR_IN_INPUT_PATH);
MessageUtil.error(handler,message);
}
}
/* Search aspectpath */
for (Iterator i = buildConfig.getAspectpath().iterator(); i.hasNext(); ) {
File pathElement = (File)i.next();
if (!pathElement.isDirectory() && pathElement.equals(outjar)) {
String message = WeaverMessages.format(WeaverMessages.OUTJAR_IN_INPUT_PATH);
MessageUtil.error(handler,message);
}
}
}
setDebugOptions();
buildConfig.getOptions().set(options);
} catch (InvalidInputException iie) {
ISourceLocation location = null;
if (buildConfig.getConfigFile() != null) {
location = new SourceLocation(buildConfig.getConfigFile(), 0);
}
IMessage m = new Message(iie.getMessage(), IMessage.ERROR, null, location);
handler.handleMessage(m);
}
return buildConfig;
}
// from super...
public void printVersion() {
System.err.println("AspectJ Compiler " + Version.text + " built on " + Version.time_text); //$NON-NLS-1$
System.err.flush();
}
public void printUsage() {
System.out.println(bind("misc.usage")); //$NON-NLS-1$
System.out.flush();
}
/**
* Get messages not dumped to handler or any PrintWriter.
* @param flush if true, empty errors
* @return null if none, String otherwise
* @see BuildArgParser()
*/
public String getOtherMessages(boolean flush) {
if (null == errorSink) {
return null;
}
String result = errorSink.toString().trim();
if (0 == result.length()) {
result = null;
}
if (flush) {
errorSink.setLength(0);
}
return result;
}
private void setDebugOptions() {
options.put(
CompilerOptions.OPTION_LocalVariableAttribute,
CompilerOptions.GENERATE);
options.put(
CompilerOptions.OPTION_LineNumberAttribute,
CompilerOptions.GENERATE);
options.put(
CompilerOptions.OPTION_SourceFileAttribute,
CompilerOptions.GENERATE);
}
private Collection collectSourceRootFiles(File dir) {
return Arrays.asList(FileUtil.listFiles(dir, FileUtil.aspectjSourceFileFilter));
}
public List getBootclasspath(AjcConfigParser parser) {
List ret = new ArrayList();
if (parser.bootclasspath == null) {
addClasspath(System.getProperty("sun.boot.class.path", ""), ret);
} else {
addClasspath(parser.bootclasspath, ret);
}
return ret;
}
/**
* If the classpath is not set, we use the environment's java.class.path, but remove
* the aspectjtools.jar entry from that list in order to prevent wierd bootstrap issues
* (refer to bug#39959).
*/
public List getClasspath(AjcConfigParser parser) {
List ret = new ArrayList();
// if (parser.bootclasspath == null) {
// addClasspath(System.getProperty("sun.boot.class.path", ""), ret);
// } else {
// addClasspath(parser.bootclasspath, ret);
// }
String extdirs = parser.extdirs;
if (extdirs == null) {
extdirs = System.getProperty("java.ext.dirs", "");
}
addExtDirs(extdirs, ret);
if (parser.classpath == null) {
addClasspath(System.getProperty("java.class.path", ""), ret);
List fixedList = new ArrayList();
for (Iterator it = ret.iterator(); it.hasNext(); ) {
String entry = (String)it.next();
if (!entry.endsWith("aspectjtools.jar")) {
fixedList.add(entry);
}
}
ret = fixedList;
} else {
addClasspath(parser.classpath, ret);
}
//??? eclipse seems to put outdir on the classpath
//??? we're brave and believe we don't need it
return ret;
}
private void addExtDirs(String extdirs, List classpathCollector) {
StringTokenizer tokenizer = new StringTokenizer(extdirs, File.pathSeparator);
while (tokenizer.hasMoreTokens()) {
// classpathCollector.add(tokenizer.nextToken());
File dirFile = new File((String)tokenizer.nextToken());
if (dirFile.canRead() && dirFile.isDirectory()) {
File[] files = dirFile.listFiles(FileUtil.ZIP_FILTER);
for (int i = 0; i < files.length; i++) {
classpathCollector.add(files[i].getAbsolutePath());
}
} else {
// XXX alert on invalid -extdirs entries
}
}
}
private void addClasspath(String classpath, List classpathCollector) {
StringTokenizer tokenizer = new StringTokenizer(classpath, File.pathSeparator);
while (tokenizer.hasMoreTokens()) {
classpathCollector.add(tokenizer.nextToken());
}
}
private class AjcConfigParser extends ConfigParser {
private String bootclasspath = null;
private String classpath = null;
private String extdirs = null;
private List unparsedArgs = new ArrayList();
private AjBuildConfig buildConfig;
private IMessageHandler handler;
public AjcConfigParser(AjBuildConfig buildConfig, IMessageHandler handler) {
this.buildConfig = buildConfig;
this.handler = handler;
}
public List getUnparsedArgs() {
return unparsedArgs;
}
/**
* Extract AspectJ-specific options (except for argfiles).
* Caller should warn when sourceroots is empty but in
* incremental mode.
* Signals warnings or errors through handler set in constructor.
*/
public void parseOption(String arg, LinkedList args) { // XXX use ListIterator.remove()
int nextArgIndex = args.indexOf(arg)+1; // XXX assumes unique
// trim arg?
if (LangUtil.isEmpty(arg)) {
showWarning("empty arg found");
} else if (arg.equals("-inpath")) {;
if (args.size() > nextArgIndex) {
// buildConfig.getAjOptions().put(AjCompilerOptions.OPTION_Inpath, CompilerOptions.PRESERVE);
List inPath = buildConfig.getInpath();
StringTokenizer st = new StringTokenizer(
((ConfigParser.Arg)args.get(nextArgIndex)).getValue(),
File.pathSeparator);
while (st.hasMoreTokens()) {
String filename = st.nextToken();
File file = makeFile(filename);
if (file.exists() && FileUtil.hasZipSuffix(filename)) {
inPath.add(file);
} else {
if (file.isDirectory()) {
inPath.add(file);
} else
showError("bad inpath component: " + filename);
}
}
buildConfig.setInPath(inPath);
args.remove(args.get(nextArgIndex));
}
} else if (arg.equals("-injars")) {;
if (args.size() > nextArgIndex) {
// buildConfig.getAjOptions().put(AjCompilerOptions.OPTION_InJARs, CompilerOptions.PRESERVE);
StringTokenizer st = new StringTokenizer(
((ConfigParser.Arg)args.get(nextArgIndex)).getValue(),
File.pathSeparator);
while (st.hasMoreTokens()) {
String filename = st.nextToken();
File jarFile = makeFile(filename);
if (jarFile.exists() && FileUtil.hasZipSuffix(filename)) {
buildConfig.getInJars().add(jarFile);
} else {
File dirFile = makeFile(filename);
if (dirFile.isDirectory()) {
buildConfig.getInJars().add(dirFile);
} else
showError("bad injar: " + filename);
}
}
args.remove(args.get(nextArgIndex));
}
} else if (arg.equals("-aspectpath")) {;
if (args.size() > nextArgIndex) {
StringTokenizer st = new StringTokenizer(
((ConfigParser.Arg)args.get(nextArgIndex)).getValue(),
File.pathSeparator);
while (st.hasMoreTokens()) {
String filename = st.nextToken();
File jarFile = makeFile(filename);
if (jarFile.exists() && FileUtil.hasZipSuffix(filename)) {
buildConfig.getAspectpath().add(jarFile);
} else {
showError("bad aspectpath: " + filename);
}
}
args.remove(args.get(nextArgIndex));
}
} else if (arg.equals("-sourceroots")) {
if (args.size() > nextArgIndex) {
List sourceRoots = new ArrayList();
StringTokenizer st = new StringTokenizer(
((ConfigParser.Arg)args.get(nextArgIndex)).getValue(),
File.pathSeparator);
while (st.hasMoreTokens()) {
File f = makeFile(st.nextToken());
if (f.isDirectory() && f.canRead()) {
sourceRoots.add(f);
} else {
showError("bad sourceroot: " + f);
}
}
if (0 < sourceRoots.size()) {
buildConfig.setSourceRoots(sourceRoots);
}
args.remove(args.get(nextArgIndex));
} else {
showError("-sourceroots requires list of directories");
}
} else if (arg.equals("-outjar")) {
if (args.size() > nextArgIndex) {
// buildConfig.getAjOptions().put(AjCompilerOptions.OPTION_OutJAR, CompilerOptions.GENERATE);
File jarFile = makeFile(((ConfigParser.Arg)args.get(nextArgIndex)).getValue());
if (FileUtil.hasZipSuffix(jarFile)) {
try {
if (!jarFile.exists()) {
jarFile.createNewFile();
}
buildConfig.setOutputJar(jarFile);
} catch (IOException ioe) {
showError("unable to create outjar file: " + jarFile);
}
} else {
showError("invalid -outjar file: " + jarFile);
}
args.remove(args.get(nextArgIndex));
} else {
showError("-outjar requires jar path argument");
}
} else if (arg.equals("-incremental")) {
buildConfig.setIncrementalMode(true);
} else if (arg.equals("-XincrementalFile")) {
if (args.size() > nextArgIndex) {
File file = makeFile(((ConfigParser.Arg)args.get(nextArgIndex)).getValue());
buildConfig.setIncrementalFile(file);
if (!file.canRead()) {
showError("bad -XincrementalFile : " + file);
// if not created before recompile test, stop after first compile
}
args.remove(args.get(nextArgIndex));
} else {
showError("-XincrementalFile requires file argument");
}
} else if (arg.equals("-emacssym")) {
buildConfig.setEmacsSymMode(true);
buildConfig.setGenerateModelMode(true);
} else if (arg.equals("-XjavadocsInModel")) {
buildConfig.setGenerateModelMode(true);
buildConfig.setGenerateJavadocsInModelMode(true);
} else if (arg.equals("-noweave") || arg.equals( "-XnoWeave")) {
buildConfig.setNoWeave(true);
} else if (arg.equals("-XserializableAspects")) {
buildConfig.setXserializableAspects(true);
} else if (arg.equals("-XlazyTjp")) {
buildConfig.setXlazyTjp(true);
} else if (arg.startsWith("-Xreweavable")) {
buildConfig.setXreweavable(true);
if (arg.endsWith(":compress")) {
buildConfig.setXreweavableCompressClasses(true);
}
} else if (arg.equals("-XnoInline")) {
buildConfig.setXnoInline(true);
} else if (arg.startsWith("-showWeaveInfo")) {
buildConfig.setShowWeavingInformation(true);
} else if (arg.equals("-Xlintfile")) {
if (args.size() > nextArgIndex) {
File lintSpecFile = makeFile(((ConfigParser.Arg)args.get(nextArgIndex)).getValue());
// XXX relax restriction on props file suffix?
if (lintSpecFile.canRead() && lintSpecFile.getName().endsWith(".properties")) {
buildConfig.setLintSpecFile(lintSpecFile);
} else {
showError("bad -Xlintfile file: " + lintSpecFile);
buildConfig.setLintSpecFile(null);
}
args.remove(args.get(nextArgIndex));
} else {
showError("-Xlintfile requires .properties file argument");
}
} else if (arg.equals("-Xlint")) {
// buildConfig.getAjOptions().put(
// AjCompilerOptions.OPTION_Xlint,
// CompilerOptions.GENERATE);
buildConfig.setLintMode(AjBuildConfig.AJLINT_DEFAULT);
} else if (arg.startsWith("-Xlint:")) {
if (7 < arg.length()) {
buildConfig.setLintMode(arg.substring(7));
} else {
showError("invalid lint option " + arg);
}
} else if (arg.equals("-bootclasspath")) {
if (args.size() > nextArgIndex) {
String bcpArg = ((ConfigParser.Arg)args.get(nextArgIndex)).getValue();
StringBuffer bcp = new StringBuffer();
StringTokenizer strTok = new StringTokenizer(bcpArg,File.pathSeparator);
while (strTok.hasMoreTokens()) {
bcp.append(makeFile(strTok.nextToken()));
if (strTok.hasMoreTokens()) {
bcp.append(File.pathSeparator);
}
}
bootclasspath = bcp.toString();
args.remove(args.get(nextArgIndex));
} else {
showError("-bootclasspath requires classpath entries");
}
} else if (arg.equals("-classpath")) {
if (args.size() > nextArgIndex) {
String cpArg = ((ConfigParser.Arg)args.get(nextArgIndex)).getValue();
StringBuffer cp = new StringBuffer();
StringTokenizer strTok = new StringTokenizer(cpArg,File.pathSeparator);
while (strTok.hasMoreTokens()) {
cp.append(makeFile(strTok.nextToken()));
if (strTok.hasMoreTokens()) {
cp.append(File.pathSeparator);
}
}
classpath = cp.toString();
args.remove(args.get(nextArgIndex));
} else {
showError("-classpath requires classpath entries");
}
} else if (arg.equals("-extdirs")) {
if (args.size() > nextArgIndex) {
String extdirsArg = ((ConfigParser.Arg)args.get(nextArgIndex)).getValue();
StringBuffer ed = new StringBuffer();
StringTokenizer strTok = new StringTokenizer(extdirsArg,File.pathSeparator);
while (strTok.hasMoreTokens()) {
ed.append(makeFile(strTok.nextToken()));
if (strTok.hasMoreTokens()) {
ed.append(File.pathSeparator);
}
}
extdirs = ed.toString();
args.remove(args.get(nextArgIndex));
} else {
showError("-extdirs requires list of external directories");
}
// error on directory unless -d, -{boot}classpath, or -extdirs
} else if (arg.equals("-d")) {
dirLookahead(arg, args, nextArgIndex);
// } else if (arg.equals("-classpath")) {
// dirLookahead(arg, args, nextArgIndex);
// } else if (arg.equals("-bootclasspath")) {
// dirLookahead(arg, args, nextArgIndex);
// } else if (arg.equals("-extdirs")) {
// dirLookahead(arg, args, nextArgIndex);
} else if (new File(arg).isDirectory()) {
showError("dir arg not permitted: " + arg);
} else {
// argfile, @file parsed by superclass
// no eclipse options parsed:
// -d args, -help (handled),
// -classpath, -target, -1.3, -1.4, -source [1.3|1.4]
// -nowarn, -warn:[...], -deprecation, -noImportError,
// -proceedOnError, -g:[...], -preserveAllLocals,
// -referenceInfo, -encoding, -verbose, -log, -time
// -noExit, -repeat
unparsedArgs.add(arg);
}
}
protected void dirLookahead(String arg, LinkedList argList, int nextArgIndex) {
unparsedArgs.add(arg);
ConfigParser.Arg next = (ConfigParser.Arg) argList.get(nextArgIndex);
String value = next.getValue();
if (!LangUtil.isEmpty(value)) {
if (new File(value).isDirectory()) {
unparsedArgs.add(value);
argList.remove(next);
return;
}
}
}
public void showError(String message) {
ISourceLocation location = null;
if (buildConfig.getConfigFile() != null) {
location = new SourceLocation(buildConfig.getConfigFile(), 0);
}
IMessage errorMessage = new Message(CONFIG_MSG + message, IMessage.ERROR, null, location);
handler.handleMessage(errorMessage);
// MessageUtil.error(handler, CONFIG_MSG + message);
}
protected void showWarning(String message) {
ISourceLocation location = null;
if (buildConfig.getConfigFile() != null) {
location = new SourceLocation(buildConfig.getConfigFile(), 0);
}
IMessage errorMessage = new Message(CONFIG_MSG + message, IMessage.WARNING, null, location);
handler.handleMessage(errorMessage);
// MessageUtil.warn(handler, message);
}
protected File makeFile(File dir, String name) {
name = name.replace('/', File.separatorChar);
File ret = new File(name);
if (dir == null || ret.isAbsolute()) return ret;
try {
dir = dir.getCanonicalFile();
} catch (IOException ioe) { }
return new File(dir, name);
}
}
}
|
73,334
|
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
|
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
|
resolved fixed
|
b133299
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:40:02Z
| 2004-09-06T17:00:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/compiler/IAjTerminalSymbols.java
|
/* *******************************************************************
* 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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.compiler;
import org.eclipse.jdt.internal.compiler.parser.TerminalTokens;
/**
* This should contain a list of symbols unique to AspectJ grammar, but
* getting jikespg to do that is too much work right now.
*/
public interface IAjTerminalSymbols extends TerminalTokens {
}
|
73,334
|
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
|
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
|
resolved fixed
|
b133299
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:40:02Z
| 2004-09-06T17:00:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/core/AspectJCore.java
|
/*******************************************************************************
* Copyright (c) 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.aspectj.ajdt.core;
import java.util.Map;
import org.aspectj.ajdt.internal.core.builder.AjCompilerOptions;
import org.eclipse.jdt.core.JavaCore;
/**
* This is the plugin class for AspectJ.
*/
public class AspectJCore extends JavaCore {
public static final String COMPILER_PB_INVALID_ABSOLUTE_TYPE_NAME = AjCompilerOptions.OPTION_ReportInvalidAbsoluteTypeName;
public static final String COMPILER_PB_INVALID_WILDCARD_TYPE_NAME = AjCompilerOptions.OPTION_ReportInvalidWildcardTypeName;
public static final String COMPILER_PB_UNRESOLVABLE_MEMBER = AjCompilerOptions.OPTION_ReportUnresolvableMember;
public static final String COMPILER_PB_TYPE_NOT_EXPOSED_TO_WEAVER = AjCompilerOptions.OPTION_ReportTypeNotExposedToWeaver;
public static final String COMPILER_PB_SHADOW_NOT_IN_STRUCTURE = AjCompilerOptions.OPTION_ReportShadowNotInStructure;
public static final String COMPILER_PB_UNMATCHED_SUPERTYPE_IN_CALL = AjCompilerOptions.OPTION_ReportUnmatchedSuperTypeInCall;
public static final String COMPILER_PB_CANNOT_IMPLEMENT_LAZY_TJP = AjCompilerOptions.OPTION_ReportCannotImplementLazyTJP;
public static final String COMPILER_PB_NEED_SERIAL_VERSION_UID = AjCompilerOptions.OPTION_ReportNeedSerialVersionUIDField;
public static final String COMPILER_PB_INCOMPATIBLE_SERIAL_VERSION = AjCompilerOptions.OPTION_ReportIncompatibleSerialVersion;
public static final String COMPILER_NO_WEAVE = AjCompilerOptions.OPTION_NoWeave;
public static final String COMPILER_SERIALIZABLE_ASPECTS = AjCompilerOptions.OPTION_XSerializableAspects;
public static final String COMPILER_LAZY_TJP = AjCompilerOptions.OPTION_XLazyThisJoinPoint;
public static final String COMPILER_NO_ADVICE_INLINE = AjCompilerOptions.OPTION_XNoInline;
public static final String COMPILER_REWEAVABLE = AjCompilerOptions.OPTION_XReweavable;
public static final String COMPILER_REWEAVABLE_COMPRESS = AjCompilerOptions.OPTION_XReweavableCompress;
public AspectJCore() {
super();
}
public static AspectJCore getAspectJCore() {
return (AspectJCore) getPlugin();
}
/* (non-Javadoc)
* @see org.eclipse.jdt.core.JavaCore#getCompilerOptions()
*/
protected Map getCompilerOptions() {
return new AjCompilerOptions().getMap();
}
}
|
73,334
|
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
|
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
|
resolved fixed
|
b133299
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:40:02Z
| 2004-09-06T17:00:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/AjClassFile.java
|
/*******************************************************************************
* Copyright (c) 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.aspectj.ajdt.internal.compiler;
import org.eclipse.jdt.internal.compiler.ClassFile;
/**
* @author colyer
*
* XXX lightweight subclass of ClassFile that only genuinely supports fileName and getBytes
* operations. This nasty hack enables us to keep the rest of the implementation much simpler.
*/
public class AjClassFile extends ClassFile {
char[] filename;
byte[] bytes;
public AjClassFile(char[] fileName, byte[] byteCodes) {
this.filename = fileName;
bytes = byteCodes;
}
public char[] fileName() {
return filename;
}
public byte[] getBytes() {
return bytes;
}
}
|
73,334
|
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
|
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
|
resolved fixed
|
b133299
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:40:02Z
| 2004-09-06T17:00:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/AjCompilerAdapter.java
|
/*******************************************************************************
* Copyright (c) 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.aspectj.ajdt.internal.compiler;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.IMessageHandler;
import org.aspectj.bridge.IProgressListener;
import org.aspectj.weaver.bcel.BcelWeaver;
import org.aspectj.weaver.bcel.BcelWorld;
import org.eclipse.jdt.internal.compiler.CompilationResult;
import org.eclipse.jdt.internal.compiler.Compiler;
import org.eclipse.jdt.internal.compiler.ICompilerAdapter;
import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration;
import org.eclipse.jdt.internal.compiler.env.ICompilationUnit;
import org.eclipse.jdt.internal.compiler.problem.AbortCompilation;
/**
* @author colyer
*
* Adapts standard JDT Compiler to add in AspectJ specific behaviours.
*/
public class AjCompilerAdapter implements ICompilerAdapter {
private Compiler compiler;
private BcelWeaver weaver;
private EclipseFactory eWorld;
private boolean isBatchCompile;
private boolean reportedErrors;
private boolean isXNoWeave;
private IIntermediateResultsRequestor intermediateResultsRequestor;
private IProgressListener progressListener;
private IOutputClassFileNameProvider outputFileNameProvider;
private IBinarySourceProvider binarySourceProvider;
private WeaverMessageHandler weaverMessageHandler;
private Map /* fileName |-> List<UnwovenClassFile> */ binarySourceSetForFullWeave = new HashMap();
private Collection /*InterimCompilationResult*/ resultSetForFullWeave = Collections.EMPTY_LIST;
List /*InterimResult*/ resultsPendingWeave = new ArrayList();
/**
* Create an adapter, and tell it everything it needs to now to drive the AspectJ
* parts of a compile cycle.
* @param compiler the JDT compiler that produces class files from source
* @param isBatchCompile true if this is a full build (non-incremental)
* @param world the bcelWorld used for type resolution during weaving
* @param weaver the weaver
* @param intRequestor recipient of interim compilation results from compiler (pre-weave)
* @param outputFileNameProvider implementor of a strategy providing output file names for results
* @param binarySourceEntries binary source that we didn't compile, but that we need to weave
* @param resultSetForFullWeave if we are doing an incremental build, and the weaver determines
* that we need to weave the world, this is the set of intermediate
* results that will be passed to the weaver.
* @param isXNoWeave
*/
public AjCompilerAdapter(Compiler compiler,
boolean isBatchCompile,
BcelWorld world,
BcelWeaver weaver,
EclipseFactory eFactory,
IIntermediateResultsRequestor intRequestor,
IProgressListener progressListener,
IOutputClassFileNameProvider outputFileNameProvider,
IBinarySourceProvider binarySourceProvider,
Map fullBinarySourceEntries, /* fileName |-> List<UnwovenClassFile> */
Collection /* InterimCompilationResult */ resultSetForFullWeave,
boolean isXNoWeave) {
this.compiler = compiler;
this.isBatchCompile = isBatchCompile;
this.weaver = weaver;
this.intermediateResultsRequestor = intRequestor;
this.progressListener = progressListener;
this.outputFileNameProvider = outputFileNameProvider;
this.binarySourceProvider = binarySourceProvider;
this.isXNoWeave = isXNoWeave;
this.binarySourceSetForFullWeave = fullBinarySourceEntries;
this.resultSetForFullWeave = resultSetForFullWeave;
this.eWorld = eFactory;
IMessageHandler msgHandler = world.getMessageHandler();
weaverMessageHandler = new WeaverMessageHandler(msgHandler, compiler);
world.setMessageHandler(weaverMessageHandler);
}
public void beforeCompiling(ICompilationUnit[] sourceUnits) {
resultsPendingWeave = new ArrayList();
reportedErrors = false;
}
public void afterCompiling() {
try {
if (isXNoWeave || reportedErrors) {
// no point weaving... just tell the requestor we're done
notifyRequestor();
} else {
weave(); // notification happens as weave progresses...
}
} catch (IOException ex) {
AbortCompilation ac = new AbortCompilation(null,ex);
throw ac;
} catch (RuntimeException rEx) {
if (rEx instanceof AbortCompilation) throw rEx; // Don't wrap AbortCompilation exceptions!
// This will be unwrapped in Compiler.handleInternalException() and the nested
// RuntimeException thrown back to the original caller - which is AspectJ
// which will then then log it as a compiler problem.
throw new AbortCompilation(true,rEx);
}
}
public void beforeProcessing(CompilationUnitDeclaration unit) {
eWorld.showMessage(IMessage.INFO, "compiling " + new String(unit.getFileName()), null, null);
}
public void afterProcessing(CompilationUnitDeclaration unit, int unitIndex) {
eWorld.finishedCompilationUnit(unit);
InterimCompilationResult intRes = new InterimCompilationResult(unit.compilationResult,outputFileNameProvider);
if (unit.compilationResult.hasErrors()) reportedErrors = true;
if (intermediateResultsRequestor != null) {
intermediateResultsRequestor.acceptResult(intRes);
}
if (isXNoWeave) {
acceptResult(unit.compilationResult);
} else {
resultsPendingWeave.add(intRes);
}
}
public void beforeResolving(CompilationUnitDeclaration unit, ICompilationUnit sourceUnit, boolean verifyMethods, boolean analyzeCode, boolean generateCode) {
resultsPendingWeave = new ArrayList();
reportedErrors = false;
}
public void afterResolving(CompilationUnitDeclaration unit, ICompilationUnit sourceUnit, boolean verifyMethods, boolean analyzeCode, boolean generateCode) {
InterimCompilationResult intRes = new InterimCompilationResult(unit.compilationResult,outputFileNameProvider);
if (unit.compilationResult.hasErrors()) reportedErrors = true;
if (isXNoWeave || !generateCode) {
acceptResult(unit.compilationResult);
} else if (generateCode){
resultsPendingWeave.add(intRes);
try {
weave();
} catch (IOException ex) {
AbortCompilation ac = new AbortCompilation(null,ex);
throw ac;
}
}
}
// helper methods...
// ==================================================================================
/*
* Called from the weaverAdapter once it has finished weaving the class files
* associated with a given compilation result.
*/
public void acceptResult(CompilationResult result) {
compiler.requestor.acceptResult(result.tagAsAccepted());
if (compiler.unitsToProcess != null) {
for (int i = 0; i < compiler.unitsToProcess.length; i++) {
if (compiler.unitsToProcess[i] != null) {
if (compiler.unitsToProcess[i].compilationResult == result) {
compiler.unitsToProcess[i] = null;
}
}
}
}
}
private List getBinarySourcesFrom(Map binarySourceEntries) {
// Map is fileName |-> List<UnwovenClassFile>
List ret = new ArrayList();
for (Iterator binIter = binarySourceEntries.keySet().iterator(); binIter.hasNext();) {
String sourceFileName = (String) binIter.next();
List unwovenClassFiles = (List) binarySourceEntries.get(sourceFileName);
// XXX - see bugs 57432,58679 - final parameter on next call should be "compiler.options.maxProblemsPerUnit"
CompilationResult result = new CompilationResult(sourceFileName.toCharArray(),0,0,Integer.MAX_VALUE);
result.noSourceAvailable();
InterimCompilationResult binarySource =
new InterimCompilationResult(result,unwovenClassFiles);
ret.add(binarySource);
}
return ret;
}
private void notifyRequestor() {
for (Iterator iter = resultsPendingWeave.iterator(); iter.hasNext();) {
InterimCompilationResult iresult = (InterimCompilationResult) iter.next();
compiler.requestor.acceptResult(iresult.result().tagAsAccepted());
}
}
private void weave() throws IOException {
// ensure weaver state is set up correctly
for (Iterator iter = resultsPendingWeave.iterator(); iter.hasNext();) {
InterimCompilationResult iresult = (InterimCompilationResult) iter.next();
for (int i = 0; i < iresult.unwovenClassFiles().length; i++) {
weaver.addClassFile(iresult.unwovenClassFiles()[i]);
}
}
weaver.prepareForWeave();
if (weaver.needToReweaveWorld()) {
if (!isBatchCompile) addAllKnownClassesToWeaveList(); // if it's batch, they're already on the list...
resultsPendingWeave.addAll(getBinarySourcesFrom(binarySourceSetForFullWeave));
} else {
Map binarySourcesToAdd = binarySourceProvider.getBinarySourcesForThisWeave();
resultsPendingWeave.addAll(getBinarySourcesFrom(binarySourcesToAdd));
}
// if (isBatchCompile) {
// resultsPendingWeave.addAll(getBinarySourcesFrom(binarySourceSetForFullWeave));
// // passed into the compiler, the set of classes in injars and inpath...
// } else if (weaver.needToReweaveWorld()) {
// addAllKnownClassesToWeaveList();
// resultsPendingWeave.addAll(getBinarySourcesFrom(binarySourceSetForFullWeave));
// }
weaver.weave(new WeaverAdapter(this,weaverMessageHandler,progressListener));
}
private void addAllKnownClassesToWeaveList() {
// results pending weave already has some results from this (incremental) compile
// add in results from any other source
for (Iterator iter = resultSetForFullWeave.iterator(); iter.hasNext();) {
InterimCompilationResult ir = (InterimCompilationResult) iter.next();
if (!resultsPendingWeave.contains(ir)) { // equality based on source file name...
ir.result().hasBeenAccepted = false; // it may have been accepted before, start again
resultsPendingWeave.add(ir);
}
}
}
}
|
73,334
|
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
|
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
|
resolved fixed
|
b133299
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:40:02Z
| 2004-09-06T17:00:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ClassFileBasedByteCodeProvider.java
|
/*******************************************************************************
* Copyright (c) 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.aspectj.ajdt.internal.compiler;
import org.aspectj.weaver.bcel.UnwovenClassFile;
import org.aspectj.weaver.bcel.UnwovenClassFileWithThirdPartyManagedBytecode;
import org.eclipse.jdt.internal.compiler.ClassFile;
import org.eclipse.jdt.internal.compiler.CompilationResult;
/**
* @author colyer
*
* Adaptor for ClassFiles that lets them act as the bytecode repository
* for UnwovenClassFiles (asking a ClassFile for its bytes causes a
* copy to be made).
*/
public class ClassFileBasedByteCodeProvider
implements UnwovenClassFileWithThirdPartyManagedBytecode.IByteCodeProvider{
private ClassFile cf;
public ClassFileBasedByteCodeProvider(ClassFile cf) {
this.cf = cf;
}
public byte[] getBytes() {
return cf.getBytes();
}
public static UnwovenClassFile[] unwovenClassFilesFor(CompilationResult result,
IOutputClassFileNameProvider nameProvider) {
ClassFile[] cfs = result.getClassFiles();
UnwovenClassFile[] ret = new UnwovenClassFile[cfs.length];
for (int i = 0; i < ret.length; i++) {
ClassFileBasedByteCodeProvider p = new ClassFileBasedByteCodeProvider(cfs[i]);
String fileName = nameProvider.getOutputClassFileName(cfs[i].fileName(), result);
ret[i] = new UnwovenClassFileWithThirdPartyManagedBytecode(fileName,p);
}
return ret;
}
}
|
73,334
|
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
|
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
|
resolved fixed
|
b133299
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:40:02Z
| 2004-09-06T17:00:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/IOutputClassFileNameProvider.java
|
/*******************************************************************************
* Copyright (c) 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.aspectj.ajdt.internal.compiler;
import org.eclipse.jdt.internal.compiler.CompilationResult;
/**
* @author colyer
*
* Implementors of this interface know how to create an output destination name
* for a given compilation result and class file. This interface capures the variation
* in strategy between ajc command-line compiles and an AJDT driven compilation.
*/
public interface IOutputClassFileNameProvider {
String getOutputClassFileName(char[] eclipseClassFileName, CompilationResult result);
}
|
73,334
|
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
|
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
|
resolved fixed
|
b133299
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:40:02Z
| 2004-09-06T17:00:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/InterimCompilationResult.java
|
/*******************************************************************************
* Copyright (c) 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.aspectj.ajdt.internal.compiler;
import java.util.List;
import org.aspectj.weaver.bcel.UnwovenClassFile;
import org.eclipse.jdt.internal.compiler.CompilationResult;
/**
* Holds a compilation result produced by the Java compilation phase,
* ready for weaving in the weave phase.
* NOTE: This class defines equality based solely on the fileName
* of the compiled file (not the bytecodes produced for example)
*/
public class InterimCompilationResult {
private CompilationResult result;
private UnwovenClassFile[] unwovenClassFiles; // longer term would be nice not to have two copies of
// the byte codes, one in result.classFiles and another
// in unwovenClassFiles;
public InterimCompilationResult(CompilationResult cr,
IOutputClassFileNameProvider np) {
result = cr;
unwovenClassFiles = ClassFileBasedByteCodeProvider.unwovenClassFilesFor(result,np);
}
public InterimCompilationResult(CompilationResult cr, List ucfList) {
result = cr;
unwovenClassFiles = new UnwovenClassFile[ucfList.size()];
for (int i=0; i < ucfList.size(); i++) {
UnwovenClassFile element = (UnwovenClassFile) ucfList.get(i);
unwovenClassFiles[i] = element;
AjClassFile ajcf = new AjClassFile(element.getClassName().replace('.', '/').toCharArray(),
element.getBytes());
result.record(ajcf.fileName(),ajcf);
}
}
public CompilationResult result() { return result; }
public UnwovenClassFile[] unwovenClassFiles() { return unwovenClassFiles; }
public String fileName() {
return new String(result.fileName);
}
public boolean equals(Object other) {
if( other == null || !(other instanceof InterimCompilationResult)) {
return false;
}
InterimCompilationResult ir = (InterimCompilationResult) other;
return fileName().equals(ir.fileName());
}
public int hashCode() {
return fileName().hashCode();
}
}
|
73,334
|
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
|
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
|
resolved fixed
|
b133299
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:40:02Z
| 2004-09-06T17:00:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/WeaverAdapter.java
|
/*******************************************************************************
* Copyright (c) 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.aspectj.ajdt.internal.compiler;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import org.aspectj.bridge.IProgressListener;
import org.aspectj.weaver.IClassFileProvider;
import org.aspectj.weaver.IWeaveRequestor;
import org.aspectj.weaver.bcel.UnwovenClassFile;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.jdt.internal.compiler.problem.AbortCompilation;
/**
* @author colyer
* This class provides the weaver with a source of class files to weave (via the
* iterator and IClassFileProvider interfaces). It receives results back from the
* weaver via the IWeaveRequestor interface.
*/
public class WeaverAdapter implements IClassFileProvider, IWeaveRequestor, Iterator {
private AjCompilerAdapter compilerAdapter;
private Iterator resultIterator;
private int classFileIndex = 0;
private InterimCompilationResult nowProcessing;
private InterimCompilationResult lastReturnedResult;
private WeaverMessageHandler weaverMessageHandler;
private IProgressListener progressListener;
private boolean finalPhase = false;
private int localIteratorCounter;
// Fields related to progress monitoring
private int progressMaxTypes;
private String progressPhasePrefix;
private double fromPercent;
private double toPercent = 100.0;
private int progressCompletionCount;
public WeaverAdapter(AjCompilerAdapter forCompiler,
WeaverMessageHandler weaverMessageHandler,
IProgressListener progressListener) {
this.compilerAdapter = forCompiler;
this.weaverMessageHandler = weaverMessageHandler;
this.progressListener = progressListener;
}
/* (non-Javadoc)
* @see org.aspectj.weaver.IClassFileProvider#getClassFileIterator()
*/
public Iterator getClassFileIterator() {
classFileIndex = 0;
localIteratorCounter = 0;
nowProcessing = null;
lastReturnedResult = null;
resultIterator = compilerAdapter.resultsPendingWeave.iterator();
return this;
}
/* (non-Javadoc)
* @see org.aspectj.weaver.IClassFileProvider#getRequestor()
*/
public IWeaveRequestor getRequestor() {
return this;
}
// Iteration
// ================================================================
/* (non-Javadoc)
* @see java.util.Iterator#hasNext()
*/
public boolean hasNext() {
if (nowProcessing == null) {
if (!resultIterator.hasNext()) return false;
nowProcessing = (InterimCompilationResult) resultIterator.next();
classFileIndex = 0;
}
while (nowProcessing.unwovenClassFiles().length == 0 ) {
if (!resultIterator.hasNext()) return false;
nowProcessing = (InterimCompilationResult) resultIterator.next();
}
if (classFileIndex < nowProcessing.unwovenClassFiles().length) {
return true;
} else {
classFileIndex = 0;
if (!resultIterator.hasNext()) return false;
nowProcessing = (InterimCompilationResult) resultIterator.next();
while (nowProcessing.unwovenClassFiles().length == 0 ) {
if (!resultIterator.hasNext()) return false;
nowProcessing = (InterimCompilationResult) resultIterator.next();
}
}
return true;
}
/* (non-Javadoc)
* @see java.util.Iterator#next()
*/
public Object next() {
if (!hasNext()) return null; // sets up indices correctly
if (finalPhase) {
if ((lastReturnedResult != null) && (lastReturnedResult != nowProcessing)) {
// we're done with the lastReturnedResult
finishedWith(lastReturnedResult);
}
}
localIteratorCounter++;
lastReturnedResult = nowProcessing;
weaverMessageHandler.setCurrentResult(nowProcessing.result());
// weaverMessageHandler.handleMessage(new Message("weaving " + nowProcessing.fileName(),IMessage.INFO, null, null));
return nowProcessing.unwovenClassFiles()[classFileIndex++];
}
/* (non-Javadoc)
* @see java.util.Iterator#remove()
*/
public void remove() {
throw new UnsupportedOperationException();
}
// IWeaveRequestor
// =====================================================================================
// weave phases as indicated by bcelWeaver...
public void processingReweavableState() {
// progress reporting logic
fromPercent = 50.0; // Assume weaving takes 50% of the progress bar...
recordProgress("processing reweavable state");
}
public void addingTypeMungers() {
// progress reporting logic
// At this point we have completed one iteration through all the classes/aspects
// we'll be dealing with, so let us remember this max value for localIteratorCounter
// (for accurate progress reporting)
recordProgress("adding type mungers");
progressMaxTypes = localIteratorCounter;
}
public void weavingAspects() {
// progress reporting logic
progressPhasePrefix="woven aspect ";
progressCompletionCount=0; // Start counting from *now*
}
public void weavingClasses() {
finalPhase = true;
// progress reporting logic
progressPhasePrefix="woven class ";
}
public void weaveCompleted() {
if ((lastReturnedResult != null) && (!lastReturnedResult.result().hasBeenAccepted)) {
finishedWith(lastReturnedResult);
}
}
/* (non-Javadoc)
* @see org.aspectj.weaver.IWeaveRequestor#acceptResult(org.aspectj.weaver.bcel.UnwovenClassFile)
*/
public void acceptResult(UnwovenClassFile result) {
char[] key = result.getClassName().replace('.','/').toCharArray();
removeFromHashtable(lastReturnedResult.result().compiledTypes,key);
String className = result.getClassName().replace('.', '/');
AjClassFile ajcf = new AjClassFile(className.toCharArray(),
result.getBytes());
lastReturnedResult.result().record(ajcf.fileName(),ajcf);
if (progressListener != null) {
progressCompletionCount++;
// Smoothly take progress from 'fromPercent' to 'toPercent'
recordProgress(
fromPercent
+((progressCompletionCount/(double)progressMaxTypes)*(toPercent-fromPercent)),
progressPhasePrefix+result.getClassName()+" (from "+nowProcessing.fileName()+")");
if (progressListener.isCancelledRequested()) {
throw new AbortCompilation(true,new OperationCanceledException("Weaving cancelled as requested"));
}
}
}
// helpers...
// =================================================================
private void finishedWith(InterimCompilationResult result) {
compilerAdapter.acceptResult(result.result());
}
private void removeFromHashtable(Hashtable table, char[] key) {
// jdt uses char[] as a key in the hashtable, which is not very useful as equality is based on being
// the same array, not having the same content.
String skey = new String(key);
char[] victim = null;
for (Enumeration iter = table.keys(); iter.hasMoreElements();) {
char[] thisKey = (char[]) iter.nextElement();
if (skey.equals(new String(thisKey))) {
victim = thisKey;
break;
}
}
if (victim != null) {
table.remove(victim);
}
}
private void recordProgress(String message) {
if (progressListener!=null) {
progressListener.setText(message);
}
}
private void recordProgress(double percentage,String message) {
if (progressListener!=null) {
progressListener.setProgress(percentage/100);
progressListener.setText(message);
}
}
}
|
73,334
|
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
|
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
|
resolved fixed
|
b133299
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:40:02Z
| 2004-09-06T17:00:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/WeaverMessageHandler.java
|
/*******************************************************************************
* Copyright (c) 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.aspectj.ajdt.internal.compiler;
import java.util.ArrayList;
import java.util.List;
import org.aspectj.ajdt.internal.compiler.lookup.EclipseSourceLocation;
import org.aspectj.bridge.AbortException;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.IMessageHandler;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.IMessage.Kind;
import org.eclipse.jdt.core.compiler.IProblem;
import org.eclipse.jdt.internal.compiler.CompilationResult;
import org.eclipse.jdt.internal.compiler.Compiler;
import org.eclipse.jdt.internal.compiler.impl.ReferenceContext;
import org.eclipse.jdt.internal.compiler.problem.DefaultProblem;
import org.eclipse.jdt.internal.compiler.problem.ProblemSeverities;
/**
* @author colyer
*
* To change the template for this generated type comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
public class WeaverMessageHandler implements IMessageHandler {
private IMessageHandler sink;
private CompilationResult currentlyWeaving;
private Compiler compiler;
public WeaverMessageHandler(IMessageHandler handler, Compiler compiler) {
this.sink = handler;
this.compiler = compiler;
}
public void setCurrentResult(CompilationResult result) {
currentlyWeaving = result;
}
public boolean handleMessage(IMessage message) throws AbortException {
if (! (message.isError() || message.isWarning()) ) return sink.handleMessage(message);
// we only care about warnings and errors here...
ISourceLocation sLoc = message.getSourceLocation();
// See bug 62073. We should assert that the caller pass the correct primary source location.
// But for AJ1.2 final we will simply do less processing of the locations if that is not the
// case (By calling sink.handleMessage()) - this ensures we don't put out bogus source context info.
if (sLoc instanceof EclipseSourceLocation) {
EclipseSourceLocation esLoc = (EclipseSourceLocation)sLoc;
if (currentlyWeaving!=null && esLoc.getCompilationResult()!=null) {
if (!currentlyWeaving.equals(((EclipseSourceLocation)sLoc).getCompilationResult()))
return sink.handleMessage(message);
// throw new RuntimeException("Primary source location must match the file we are currently processing!");
}
}
CompilationResult problemSource = currentlyWeaving;
if (problemSource == null) {
// must be a problem found during completeTypeBindings phase of begin to compile
if (sLoc instanceof EclipseSourceLocation) {
problemSource = ((EclipseSourceLocation)sLoc).getCompilationResult();
}
if (problemSource == null) {
// XXX this is ok for ajc, will have to do better for AJDT in time...
return sink.handleMessage(message);
}
}
int startPos = getStartPos(sLoc,problemSource);
int endPos = getEndPos(sLoc,problemSource);
int severity = message.isError() ? ProblemSeverities.Error : ProblemSeverities.Warning;
char[] filename = problemSource.fileName;
boolean usedBinarySourceFileName = false;
if (problemSource.isFromBinarySource()) {
if (sLoc != null) {
filename = sLoc.getSourceFile().getPath().toCharArray();
usedBinarySourceFileName = true;
}
}
ReferenceContext referenceContext = findReferenceContextFor(problemSource);
IProblem problem = compiler.problemReporter.createProblem(
filename,
IProblem.Unclassified,
new String[0],
new String[] {message.getMessage()},
severity,
startPos,
endPos,
sLoc != null ? sLoc.getLine() : 0
);
IProblem[] seeAlso = buildSeeAlsoProblems(message.getExtraSourceLocations(),
problemSource,
usedBinarySourceFileName);
problem.setSeeAlsoProblems(seeAlso);
StringBuffer details = new StringBuffer();
// Stick more info in supplementary message info
if (message.getDetails() != null) {
details.append(message.getDetails());
}
// Remember if this message was due to a deow
if (message.getDeclared()) {
details.append("[deow=true]");
}
if (details.length()!=0) {
problem.setSupplementaryMessageInfo(details.toString());
}
compiler.problemReporter.record(problem, problemSource, referenceContext);
return true;
}
public boolean isIgnoring(Kind kind) {
return sink.isIgnoring(kind);
}
private int getStartPos(ISourceLocation sLoc,CompilationResult result) {
int pos = 0;
if (sLoc == null) return 0;
int line = sLoc.getLine();
if (sLoc instanceof EclipseSourceLocation) {
pos = ((EclipseSourceLocation)sLoc).getStartPos();
} else {
if (line <= 1) return 0;
if (result != null) {
if ((result.lineSeparatorPositions != null) &&
(result.lineSeparatorPositions.length >= (line-1))) {
pos = result.lineSeparatorPositions[line-2] + 1;
}
}
}
return pos;
}
private int getEndPos(ISourceLocation sLoc,CompilationResult result) {
int pos = 0;
if (sLoc == null) return 0;
int line = sLoc.getLine();
if (line <= 0) line = 1;
if (sLoc instanceof EclipseSourceLocation) {
pos = ((EclipseSourceLocation)sLoc).getEndPos();
} else {
if (result != null) {
if ((result.lineSeparatorPositions != null) &&
(result.lineSeparatorPositions.length >= line)) {
pos = result.lineSeparatorPositions[line -1] -1;
}
}
}
return pos;
}
private ReferenceContext findReferenceContextFor(CompilationResult result) {
ReferenceContext context = null;
if (compiler.unitsToProcess == null) return null;
for (int i = 0; i < compiler.unitsToProcess.length; i++) {
if ((compiler.unitsToProcess[i] != null) &&
(compiler.unitsToProcess[i].compilationResult == result)) {
context = compiler.unitsToProcess[i];
break;
}
}
return context;
}
private IProblem[] buildSeeAlsoProblems(List sourceLocations,
CompilationResult problemSource,
boolean usedBinarySourceFileName) {
List ret = new ArrayList();
for (int i = 0; i < sourceLocations.size(); i++) {
ISourceLocation loc = (ISourceLocation) sourceLocations.get(i);
if (loc != null ) {
DefaultProblem dp =
new DefaultProblem( loc.getSourceFile().getPath().toCharArray(),
"see also",
0,
new String[] {},
ProblemSeverities.Ignore,
getStartPos(loc,null),
getEndPos(loc,null),
loc.getLine());
ret.add(dp);
} else {
throw new RuntimeException("Internal Compiler Error: Unexpected null source location passed as 'see also' location.");
}
}
if (usedBinarySourceFileName) {
DefaultProblem dp = new DefaultProblem(problemSource.fileName,"see also",0,new String[] {},
ProblemSeverities.Ignore,0,
0,0);
ret.add(dp);
}
IProblem[] retValue = (IProblem[])ret.toArray(new IProblem[]{});
return retValue;
}
}
|
73,334
|
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
|
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
|
resolved fixed
|
b133299
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:40:02Z
| 2004-09-06T17:00:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/AccessForInlineVisitor.java
|
/* *******************************************************************
* 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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.ast;
//import java.util.Arrays;
import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory;
import org.aspectj.ajdt.internal.compiler.lookup.InlineAccessFieldBinding;
import org.aspectj.ajdt.internal.compiler.lookup.InterTypeFieldBinding;
import org.aspectj.ajdt.internal.compiler.lookup.InterTypeMethodBinding;
import org.aspectj.ajdt.internal.compiler.lookup.PrivilegedFieldBinding;
import org.aspectj.ajdt.internal.compiler.lookup.PrivilegedHandler;
import org.aspectj.weaver.AjcMemberMaker;
import org.aspectj.weaver.ResolvedMember;
import org.eclipse.jdt.internal.compiler.ASTVisitor;
//import org.eclipse.jdt.internal.compiler.AbstractSyntaxTreeVisitorAdapter;
import org.eclipse.jdt.internal.compiler.ast.AllocationExpression;
import org.eclipse.jdt.internal.compiler.ast.AssertStatement;
import org.eclipse.jdt.internal.compiler.ast.ClassLiteralAccess;
import org.eclipse.jdt.internal.compiler.ast.FieldReference;
import org.eclipse.jdt.internal.compiler.ast.MessageSend;
import org.eclipse.jdt.internal.compiler.ast.QualifiedNameReference;
import org.eclipse.jdt.internal.compiler.ast.QualifiedTypeReference;
import org.eclipse.jdt.internal.compiler.ast.SingleNameReference;
import org.eclipse.jdt.internal.compiler.ast.SingleTypeReference;
import org.eclipse.jdt.internal.compiler.ast.ThisReference;
import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration;
import org.eclipse.jdt.internal.compiler.lookup.ArrayBinding;
import org.eclipse.jdt.internal.compiler.lookup.BlockScope;
import org.eclipse.jdt.internal.compiler.lookup.FieldBinding;
import org.eclipse.jdt.internal.compiler.lookup.MethodBinding;
import org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding;
import org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
import org.eclipse.jdt.internal.compiler.lookup.VariableBinding;
/**
* Walks the body of around advice
*
* Makes sure that all member accesses are to public members. Will
* convert to use access methods when needed to ensure that. This
* makes it much simpler (and more modular) to inline the body of
* an around.
*
* ??? constructors are handled different and require access to the
* target type. changes to org.eclipse.jdt.internal.compiler.ast.AllocationExpression
* would be required to fix this issue.
*
* @author Jim Hugunin
*/
public class AccessForInlineVisitor extends ASTVisitor {
PrivilegedHandler handler;
AspectDeclaration inAspect;
EclipseFactory world; // alias for inAspect.world
// set to true for ClassLiteralAccess and AssertStatement
// ??? A better answer would be to transform these into inlinable forms
public boolean isInlinable = true;
public AccessForInlineVisitor(AspectDeclaration inAspect, PrivilegedHandler handler) {
this.inAspect = inAspect;
this.world = inAspect.factory;
this.handler = handler;
}
public void endVisit(SingleNameReference ref, BlockScope scope) {
if (ref.binding instanceof FieldBinding) {
ref.binding = getAccessibleField((FieldBinding)ref.binding, ref.actualReceiverType);
}
}
public void endVisit(QualifiedNameReference ref, BlockScope scope) {
if (ref.binding instanceof FieldBinding) {
ref.binding = getAccessibleField((FieldBinding)ref.binding, ref.actualReceiverType);
}
if (ref.otherBindings != null && ref.otherBindings.length > 0) {
TypeBinding receiverType;
if (ref.binding instanceof FieldBinding) {
receiverType = ((FieldBinding)ref.binding).type;
} else if (ref.binding instanceof VariableBinding) {
receiverType = ((VariableBinding)ref.binding).type;
} else {
//!!! understand and fix this case later
receiverType = ref.otherBindings[0].declaringClass;
}
for (int i=0, len=ref.otherBindings.length; i < len; i++) {
FieldBinding binding = ref.otherBindings[i];
ref.otherBindings[i] = getAccessibleField(binding, receiverType);
receiverType = binding.type;
}
}
}
public void endVisit(FieldReference ref, BlockScope scope) {
ref.binding = getAccessibleField(ref.binding, ref.receiverType);
}
public void endVisit(MessageSend send, BlockScope scope) {
if (send instanceof Proceed) return;
if (send.binding == null || !send.binding.isValidBinding()) return;
if (send.isSuperAccess() && !send.binding.isStatic()) {
send.receiver = new ThisReference(send.sourceStart, send.sourceEnd);
MethodBinding superAccessBinding = getSuperAccessMethod(send.binding);
AstUtil.replaceMethodBinding(send, superAccessBinding);
} else if (!isPublic(send.binding)) {
send.syntheticAccessor = getAccessibleMethod(send.binding, send.receiverType);
}
}
public void endVisit(AllocationExpression send, BlockScope scope) {
if (send.binding == null || !send.binding.isValidBinding()) return;
//XXX TBD
if (isPublic(send.binding)) return;
makePublic(send.binding.declaringClass);
send.binding = handler.getPrivilegedAccessMethod(send.binding, send);
}
public void endVisit(
QualifiedTypeReference ref,
BlockScope scope)
{
makePublic(ref.resolvedType); //getTypeBinding(scope)); //??? might be trouble
}
public void endVisit(
SingleTypeReference ref,
BlockScope scope)
{
makePublic(ref.resolvedType); //getTypeBinding(scope)); //??? might be trouble
}
private FieldBinding getAccessibleField(FieldBinding binding, TypeBinding receiverType) {
//System.err.println("checking field: " + binding);
if (!binding.isValidBinding()) return binding;
makePublic(receiverType);
if (isPublic(binding)) return binding;
if (binding instanceof PrivilegedFieldBinding) return binding;
if (binding instanceof InterTypeFieldBinding) return binding;
if (binding.isPrivate() && binding.declaringClass != inAspect.binding) {
binding.modifiers = AstUtil.makePackageVisible(binding.modifiers);
}
ResolvedMember m = EclipseFactory.makeResolvedMember(binding, receiverType);
if (inAspect.accessForInline.containsKey(m)) return (FieldBinding)inAspect.accessForInline.get(m);
FieldBinding ret = new InlineAccessFieldBinding(inAspect, binding, m);
//System.err.println(" made accessor: " + ret);
inAspect.accessForInline.put(m, ret);
return ret;
}
private MethodBinding getAccessibleMethod(MethodBinding binding, TypeBinding receiverType) {
if (!binding.isValidBinding()) return binding;
makePublic(receiverType); //???
if (isPublic(binding)) return binding;
if (binding instanceof InterTypeMethodBinding) return binding;
ResolvedMember m = null;
if (binding.isPrivate() && binding.declaringClass != inAspect.binding) {
// does this always mean that the aspect is an inner aspect of the bindings
// declaring class? After all, the field is private but we can see it from
// where we are.
binding.modifiers = AstUtil.makePackageVisible(binding.modifiers);
m = EclipseFactory.makeResolvedMember(binding);
} else {
// Sometimes receiverType and binding.declaringClass are *not* the same.
// Sometimes receiverType is a subclass of binding.declaringClass. In these situations
// we want the generated inline accessor to call the method on the subclass (at
// runtime this will be satisfied by the super).
m = EclipseFactory.makeResolvedMember(binding, receiverType);
}
if (inAspect.accessForInline.containsKey(m)) return (MethodBinding)inAspect.accessForInline.get(m);
MethodBinding ret = world.makeMethodBinding(
AjcMemberMaker.inlineAccessMethodForMethod(inAspect.typeX, m));
inAspect.accessForInline.put(m, ret);
return ret;
}
static class SuperAccessMethodPair {
public ResolvedMember originalMethod;
public MethodBinding accessMethod;
public SuperAccessMethodPair(ResolvedMember originalMethod, MethodBinding accessMethod) {
this.originalMethod = originalMethod;
this.accessMethod = accessMethod;
}
}
private MethodBinding getSuperAccessMethod(MethodBinding binding) {
ResolvedMember m = EclipseFactory.makeResolvedMember(binding);
ResolvedMember superAccessMember = AjcMemberMaker.superAccessMethod(inAspect.typeX, m);
if (inAspect.superAccessForInline.containsKey(superAccessMember)) {
return ((SuperAccessMethodPair)inAspect.superAccessForInline.get(superAccessMember)).accessMethod;
}
MethodBinding ret = world.makeMethodBinding(superAccessMember);
inAspect.superAccessForInline.put(superAccessMember, new SuperAccessMethodPair(m, ret));
return ret;
}
private boolean isPublic(FieldBinding fieldBinding) {
// these are always effectively public to the inliner
if (fieldBinding instanceof InterTypeFieldBinding) return true;
return fieldBinding.isPublic();
}
private boolean isPublic(MethodBinding methodBinding) {
// these are always effectively public to the inliner
if (methodBinding instanceof InterTypeMethodBinding) return true;
return methodBinding.isPublic();
}
private void makePublic(TypeBinding binding) {
if (binding == null || !binding.isValidBinding()) return; // has already produced an error
if (binding instanceof ReferenceBinding) {
ReferenceBinding rb = (ReferenceBinding)binding;
if (!rb.isPublic()) handler.notePrivilegedTypeAccess(rb, null); //???
} else if (binding instanceof ArrayBinding) {
makePublic( ((ArrayBinding)binding).leafComponentType );
} else {
return;
}
}
public void endVisit(AssertStatement assertStatement, BlockScope scope) {
isInlinable = false;
}
public void endVisit(ClassLiteralAccess classLiteral, BlockScope scope) {
isInlinable = false;
}
public boolean visit(
TypeDeclaration localTypeDeclaration,
BlockScope scope) {
// we don't want to transform any local anonymous classes as they won't be inlined
return false;
}
}
|
73,334
|
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
|
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
|
resolved fixed
|
b133299
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:40:02Z
| 2004-09-06T17:00:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/AdviceDeclaration.java
|
/* *******************************************************************
* 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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.ast;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
import org.aspectj.ajdt.internal.compiler.lookup.AjTypeConstants;
import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory;
import org.aspectj.ajdt.internal.compiler.lookup.PrivilegedHandler;
import org.aspectj.weaver.Advice;
import org.aspectj.weaver.AdviceKind;
import org.aspectj.weaver.AjAttribute;
import org.aspectj.weaver.NameMangler;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.TypeX;
import org.eclipse.jdt.internal.compiler.ClassFile;
import org.eclipse.jdt.internal.compiler.CompilationResult;
import org.eclipse.jdt.internal.compiler.ast.Argument;
import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration;
import org.eclipse.jdt.internal.compiler.ast.TypeReference;
import org.eclipse.jdt.internal.compiler.codegen.CodeStream;
import org.eclipse.jdt.internal.compiler.lookup.ArrayBinding;
import org.eclipse.jdt.internal.compiler.lookup.ClassScope;
import org.eclipse.jdt.internal.compiler.lookup.MethodBinding;
import org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding;
import org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
import org.eclipse.jdt.core.compiler.CharOperation;
/**
* Represents before, after and around advice in an aspect.
* Will generate a method corresponding to the body of the advice with an
* attribute including additional information.
*
* @author Jim Hugunin
*/
public class AdviceDeclaration extends AjMethodDeclaration {
public PointcutDesignator pointcutDesignator;
int baseArgumentCount;
public Argument extraArgument;
public AdviceKind kind;
private int extraArgumentFlags = 0;
public MethodBinding proceedMethodBinding;
public List proceedCalls = new ArrayList(2);
public boolean proceedInInners;
public ResolvedMember[] proceedCallSignatures;
public boolean[] formalsUnchangedToProceed;
public TypeX[] declaredExceptions;
public AdviceDeclaration(CompilationResult result, AdviceKind kind) {
super(result);
this.returnType = TypeReference.baseTypeReference(T_void, 0);
this.kind = kind;
}
protected int generateInfoAttributes(ClassFile classFile) {
List l = new ArrayList(1);
l.add(new EclipseAttributeAdapter(makeAttribute()));
addDeclarationStartLineAttribute(l,classFile);
return classFile.generateMethodInfoAttribute(binding, l);
}
public AjAttribute makeAttribute() {
if (kind == AdviceKind.Around) {
return new AjAttribute.AdviceAttribute(kind, pointcutDesignator.getPointcut(),
extraArgumentFlags, sourceStart, sourceEnd, null,
proceedInInners, proceedCallSignatures, formalsUnchangedToProceed,
declaredExceptions);
} else {
return new AjAttribute.AdviceAttribute(kind, pointcutDesignator.getPointcut(),
extraArgumentFlags, sourceStart, sourceEnd, null);
}
}
public void resolveStatements() {
if (binding == null || ignoreFurtherInvestigation) return;
ClassScope upperScope = (ClassScope)scope.parent; //!!! safety
modifiers = binding.modifiers = checkAndSetModifiers(modifiers, upperScope);
if (kind == AdviceKind.AfterThrowing && extraArgument != null) {
TypeBinding argTb = extraArgument.binding.type;
TypeBinding expectedTb = upperScope.getJavaLangThrowable();
if (!argTb.isCompatibleWith(expectedTb)) {
scope.problemReporter().typeMismatchError(argTb, expectedTb, extraArgument);
ignoreFurtherInvestigation = true;
return;
}
}
pointcutDesignator.finishResolveTypes(this, this.binding,
baseArgumentCount, upperScope.referenceContext.binding);
if (binding == null || ignoreFurtherInvestigation) return;
if (kind == AdviceKind.Around) {
ReferenceBinding[] exceptions =
new ReferenceBinding[] { upperScope.getJavaLangThrowable() };
proceedMethodBinding = new MethodBinding(Modifier.STATIC,
"proceed".toCharArray(), binding.returnType,
resize(baseArgumentCount+1, binding.parameters),
exceptions, binding.declaringClass);
proceedMethodBinding.selector =
CharOperation.concat(selector, proceedMethodBinding.selector);
}
super.resolveStatements(); //upperScope);
if (binding != null) determineExtraArgumentFlags();
if (kind == AdviceKind.Around) {
int n = proceedCalls.size();
// EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(upperScope);
//System.err.println("access to: " + Arrays.asList(handler.getMembers()));
//XXX set these correctly
formalsUnchangedToProceed = new boolean[baseArgumentCount];
proceedCallSignatures = new ResolvedMember[0];
proceedInInners = false;
declaredExceptions = new TypeX[0];
for (int i=0; i < n; i++) {
Proceed call = (Proceed)proceedCalls.get(i);
if (call.inInner) {
//System.err.println("proceed in inner: " + call);
proceedInInners = true;
//XXX wrong
//proceedCallSignatures[i] = world.makeResolvedMember(call.binding);
}
}
// ??? should reorganize into AspectDeclaration
// if we have proceed in inners we won't ever be inlined so the code below is unneeded
if (!proceedInInners) {
PrivilegedHandler handler = (PrivilegedHandler)upperScope.referenceContext.binding.privilegedHandler;
if (handler == null) {
handler = new PrivilegedHandler((AspectDeclaration)upperScope.referenceContext);
//upperScope.referenceContext.binding.privilegedHandler = handler;
}
this.traverse(new MakeDeclsPublicVisitor(), (ClassScope)null);
AccessForInlineVisitor v = new AccessForInlineVisitor((AspectDeclaration)upperScope.referenceContext, handler);
this.traverse(v, (ClassScope) null);
// ??? if we found a construct that we can't inline, set
// proceedInInners so that we won't try to inline this body
if (!v.isInlinable) proceedInInners = true;
}
}
}
public int getDeclaredParameterCount() {
// this only works before code generation
return this.arguments.length - 3 - ((extraArgument == null) ? 0 : 1);
//Advice.countOnes(extraArgumentFlags);
}
public void generateProceedMethod(ClassScope classScope, ClassFile classFile) {
MethodBinding binding = (MethodBinding)proceedMethodBinding;
classFile.generateMethodInfoHeader(binding);
int methodAttributeOffset = classFile.contentsOffset;
int attributeNumber = classFile.generateMethodInfoAttribute(binding, AstUtil.getAjSyntheticAttribute());
int codeAttributeOffset = classFile.contentsOffset;
classFile.generateCodeAttributeHeader();
CodeStream codeStream = classFile.codeStream;
codeStream.reset(this, classFile);
// push the closure
int nargs = binding.parameters.length;
int closureIndex = 0;
for (int i=0; i < nargs-1; i++) {
closureIndex += AstUtil.slotsNeeded(binding.parameters[i]);
}
codeStream.loadObject(closureIndex);
// build the Object[]
codeStream.generateInlinedValue(nargs-1);
codeStream.newArray(classScope, new ArrayBinding(classScope.getType(TypeBinding.JAVA_LANG_OBJECT), 1));
int index = 0;
for (int i=0; i < nargs-1; i++) {
TypeBinding type = binding.parameters[i];
codeStream.dup();
codeStream.generateInlinedValue(i);
codeStream.load(type, index);
index += AstUtil.slotsNeeded(type);
if (type.isBaseType()) {
codeStream.invokestatic(AjTypeConstants.getConversionMethodToObject(classScope, type));
}
codeStream.aastore();
}
// call run
ReferenceBinding closureType = (ReferenceBinding)binding.parameters[nargs-1];
MethodBinding runMethod = closureType.getMethods("run".toCharArray())[0];
codeStream.invokevirtual(runMethod);
TypeBinding returnType = binding.returnType;
if (returnType.isBaseType()) {
codeStream.invokestatic(AjTypeConstants.getConversionMethodFromObject(classScope, returnType));
} else {
codeStream.checkcast(returnType);
}
AstUtil.generateReturn(returnType, codeStream);
classFile.completeCodeAttribute(codeAttributeOffset);
attributeNumber++;
classFile.completeMethodInfo(methodAttributeOffset, attributeNumber);
}
public void generateCode(ClassScope classScope, ClassFile classFile) {
if (ignoreFurtherInvestigation) return;
super.generateCode(classScope, classFile);
if (proceedMethodBinding != null) {
generateProceedMethod(classScope, classFile);
}
}
private void determineExtraArgumentFlags() {
if (extraArgument != null) extraArgumentFlags |= Advice.ExtraArgument;
ThisJoinPointVisitor tjp = new ThisJoinPointVisitor(this);
extraArgumentFlags |= tjp.removeUnusedExtraArguments();
}
private static TypeBinding[] resize(int newSize, TypeBinding[] bindings) {
int len = bindings.length;
TypeBinding[] ret = new TypeBinding[newSize];
System.arraycopy(bindings, 0, ret, 0, Math.min(newSize, len));
return ret;
}
public void postParse(TypeDeclaration typeDec) {
int adviceSequenceNumberInType = ((AspectDeclaration)typeDec).adviceCounter++;
StringBuffer stringifiedPointcut = new StringBuffer(30);
pointcutDesignator.print(0,stringifiedPointcut);
this.selector =
NameMangler.adviceName(
EclipseFactory.fromBinding(typeDec.binding),
kind,
adviceSequenceNumberInType,
stringifiedPointcut.toString().hashCode()).toCharArray();
if (arguments != null) {
baseArgumentCount = arguments.length;
}
if (kind == AdviceKind.Around) {
extraArgument = makeFinalArgument("ajc_aroundClosure",
AjTypeConstants.getAroundClosureType());
}
int addedArguments = 3;
if (extraArgument != null) {
addedArguments += 1;
}
arguments = extendArgumentsLength(arguments, addedArguments);
int index = baseArgumentCount;
if (extraArgument != null) {
arguments[index++] = extraArgument;
}
arguments[index++] = makeFinalArgument("thisJoinPointStaticPart", AjTypeConstants.getJoinPointStaticPartType());
arguments[index++] = makeFinalArgument("thisJoinPoint", AjTypeConstants.getJoinPointType());
arguments[index++] = makeFinalArgument("thisEnclosingJoinPointStaticPart", AjTypeConstants.getJoinPointStaticPartType());
if (pointcutDesignator.isError()) {
this.ignoreFurtherInvestigation = true;
}
pointcutDesignator.postParse(typeDec, this);
}
private int checkAndSetModifiers(int modifiers, ClassScope scope) {
if (modifiers == 0) return Modifier.PUBLIC;
else if (modifiers == Modifier.STRICT) return Modifier.PUBLIC | Modifier.STRICT;
else {
tagAsHavingErrors();
scope.problemReporter().signalError(declarationSourceStart, sourceStart-1, "illegal modifier on advice, only strictfp is allowed");
return Modifier.PUBLIC;
}
}
public static Argument[] addTjpArguments(Argument[] arguments) {
int index = arguments.length;
arguments = extendArgumentsLength(arguments, 3);
arguments[index++] = makeFinalArgument("thisJoinPointStaticPart", AjTypeConstants.getJoinPointStaticPartType());
arguments[index++] = makeFinalArgument("thisJoinPoint", AjTypeConstants.getJoinPointType());
arguments[index++] = makeFinalArgument("thisEnclosingJoinPointStaticPart", AjTypeConstants.getJoinPointStaticPartType());
return arguments;
}
private static Argument makeFinalArgument(String name, TypeReference typeRef) {
long pos = 0; //XXX encode start and end location
return new Argument(name.toCharArray(), pos, typeRef, Modifier.FINAL);
}
private static Argument[] extendArgumentsLength(Argument[] args, int addedArguments) {
if (args == null) {
return new Argument[addedArguments];
}
int len = args.length;
Argument[] ret = new Argument[len + addedArguments];
System.arraycopy(args, 0, ret, 0, len);
return ret;
}
// public String toString(int tab) {
// String s = tabString(tab);
// if (modifiers != AccDefault) {
// s += modifiersString(modifiers);
// }
//
// if (kind == AdviceKind.Around) {
// s += returnTypeToString(0);
// }
//
// s += new String(selector) + "("; //$NON-NLS-1$
// if (arguments != null) {
// for (int i = 0; i < arguments.length; i++) {
// s += arguments[i].toString(0);
// if (i != (arguments.length - 1))
// s = s + ", "; //$NON-NLS-1$
// };
// };
// s += ")"; //$NON-NLS-1$
//
// if (extraArgument != null) {
// s += "(" + extraArgument.toString(0) + ")";
// }
//
//
//
// if (thrownExceptions != null) {
// s += " throws "; //$NON-NLS-1$
// for (int i = 0; i < thrownExceptions.length; i++) {
// s += thrownExceptions[i].toString(0);
// if (i != (thrownExceptions.length - 1))
// s = s + ", "; //$NON-NLS-1$
// };
// };
//
// s += ": ";
// if (pointcutDesignator != null) {
// s += pointcutDesignator.toString(0);
// }
//
// s += toStringStatements(tab + 1);
// return s;
// }
public StringBuffer printBody(int indent, StringBuffer output) {
output.append(": ");
if (pointcutDesignator != null) {
output.append(pointcutDesignator.toString());
}
return super.printBody(indent,output);
}
public StringBuffer printReturnType(int indent, StringBuffer output) {
if (this.kind == AdviceKind.Around) {
return super.printReturnType(indent,output);
}
return output;
}
}
|
73,334
|
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
|
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
|
resolved fixed
|
b133299
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:40:02Z
| 2004-09-06T17:00:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/AjConstructorDeclaration.java
|
/*******************************************************************************
* Copyright (c) 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation
*******************************************************************************/
package org.aspectj.ajdt.internal.compiler.ast;
import java.util.ArrayList;
import java.util.List;
import org.aspectj.weaver.AjAttribute;
import org.eclipse.jdt.internal.compiler.ClassFile;
import org.eclipse.jdt.internal.compiler.CompilationResult;
import org.eclipse.jdt.internal.compiler.ast.ConstructorDeclaration;
/**
* Root class for all ConstructorDeclaration objects created by the parser.
* Enables us to generate extra attributes in the method_info attribute
* to support aspectj.
*/
public class AjConstructorDeclaration extends ConstructorDeclaration {
/**
* @param compilationResult
*/
public AjConstructorDeclaration(CompilationResult compilationResult) {
super(compilationResult);
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration#generateInfoAttributes(org.eclipse.jdt.internal.compiler.ClassFile)
*/
protected int generateInfoAttributes(ClassFile classFile) {
// add extra attributes into list then call 2-arg version of generateInfoAttributes...
List extras = new ArrayList();
addDeclarationStartLineAttribute(extras,classFile);
return classFile.generateMethodInfoAttribute(binding,extras);
}
protected void addDeclarationStartLineAttribute(List extraAttributeList, ClassFile classFile) {
if (!classFile.codeStream.generateLineNumberAttributes) return;
int[] separators = compilationResult().lineSeparatorPositions;
int declarationStartLine = 1;
for (int i = 0; i < separators.length; i++) {
if (sourceStart < separators[i]) break;
declarationStartLine++;
}
extraAttributeList.add(
new EclipseAttributeAdapter(new AjAttribute.MethodDeclarationLineNumberAttribute(declarationStartLine)));
}
}
|
73,334
|
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
|
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
|
resolved fixed
|
b133299
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:40:02Z
| 2004-09-06T17:00:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/AjMethodDeclaration.java
|
/*******************************************************************************
* Copyright (c) 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation
*******************************************************************************/
package org.aspectj.ajdt.internal.compiler.ast;
import java.util.ArrayList;
import java.util.List;
import org.aspectj.weaver.AjAttribute;
import org.eclipse.jdt.internal.compiler.ClassFile;
import org.eclipse.jdt.internal.compiler.CompilationResult;
import org.eclipse.jdt.internal.compiler.ast.MethodDeclaration;
/**
* Root class for all MethodDeclaration objects created by the parser.
* Enables us to generate extra attributes in the method_info attribute
* to support aspectj.
*/
public class AjMethodDeclaration extends MethodDeclaration {
/**
* @param compilationResult
*/
public AjMethodDeclaration(CompilationResult compilationResult) {
super(compilationResult);
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration#generateInfoAttributes(org.eclipse.jdt.internal.compiler.ClassFile)
*/
protected int generateInfoAttributes(ClassFile classFile) {
// add extra attributes into list then call 2-arg version of generateInfoAttributes...
List extras = new ArrayList();
addDeclarationStartLineAttribute(extras,classFile);
return classFile.generateMethodInfoAttribute(binding,extras);
}
protected void addDeclarationStartLineAttribute(List extraAttributeList, ClassFile classFile) {
if (!classFile.codeStream.generateLineNumberAttributes) return;
int[] separators = compilationResult().lineSeparatorPositions;
int declarationStartLine = 1;
for (int i = 0; i < separators.length; i++) {
if (sourceStart < separators[i]) break;
declarationStartLine++;
}
extraAttributeList.add(
new EclipseAttributeAdapter(new AjAttribute.MethodDeclarationLineNumberAttribute(declarationStartLine)));
}
}
|
73,334
|
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
|
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
|
resolved fixed
|
b133299
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:40:02Z
| 2004-09-06T17:00:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/AspectClinit.java
|
/* *******************************************************************
* 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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.ast;
import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory;
import org.aspectj.weaver.AjcMemberMaker;
import org.eclipse.jdt.internal.compiler.CompilationResult;
import org.eclipse.jdt.internal.compiler.ast.Clinit;
import org.eclipse.jdt.internal.compiler.codegen.CodeStream;
import org.eclipse.jdt.internal.compiler.codegen.ExceptionLabel;
import org.eclipse.jdt.internal.compiler.codegen.Label;
import org.eclipse.jdt.internal.compiler.lookup.ClassScope;
import org.eclipse.jdt.internal.compiler.lookup.FieldBinding;
public class AspectClinit extends Clinit {
private boolean hasPre, hasPost;
private FieldBinding initFailureField;
public AspectClinit(Clinit old, CompilationResult compilationResult, boolean hasPre, boolean hasPost, FieldBinding initFailureField) {
super(compilationResult);
this.needFreeReturn = old.needFreeReturn;
this.sourceEnd = old.sourceEnd;
this.sourceStart = old.sourceStart;
this.declarationSourceEnd = old.declarationSourceEnd;
this.declarationSourceStart = old.declarationSourceStart;
this.hasPre = hasPre;
this.hasPost = hasPost;
this.initFailureField = initFailureField;
}
private ExceptionLabel handlerLabel;
protected void generateSyntheticCode(
ClassScope classScope,
CodeStream codeStream)
{
if (initFailureField != null) {
handlerLabel = new ExceptionLabel(codeStream, classScope.getJavaLangThrowable());
}
if (hasPre) {
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(classScope);
codeStream.invokestatic(world.makeMethodBindingForCall(
AjcMemberMaker.ajcPreClinitMethod(
EclipseFactory.fromBinding(classScope.referenceContext.binding)
)));
}
super.generateSyntheticCode(classScope, codeStream);
}
protected void generatePostSyntheticCode(
ClassScope classScope,
CodeStream codeStream)
{
super.generatePostSyntheticCode(classScope, codeStream);
if (hasPost) {
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(classScope);
codeStream.invokestatic(world.makeMethodBindingForCall(
AjcMemberMaker.ajcPostClinitMethod(
EclipseFactory.fromBinding(classScope.referenceContext.binding)
)));
}
if (initFailureField != null) {
// Changes to this exception handling code may require changes to
// BcelClassWeaver.isInitFailureHandler()
handlerLabel.placeEnd();
Label endLabel = new Label(codeStream);
codeStream.goto_(endLabel);
handlerLabel.place();
codeStream.astore_0(); // Bug #52394
codeStream.aload_0();
codeStream.putstatic(initFailureField);
endLabel.place();
}
}
}
|
73,334
|
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
|
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
|
resolved fixed
|
b133299
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:40:02Z
| 2004-09-06T17:00:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/AspectDeclaration.java
|
/* *******************************************************************
* 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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.ast;
import java.lang.reflect.Modifier;
import java.util.*;
import org.aspectj.ajdt.internal.compiler.lookup.*;
import org.aspectj.weaver.*;
import org.aspectj.weaver.patterns.*;
import org.eclipse.jdt.internal.compiler.ClassFile;
import org.eclipse.jdt.internal.compiler.CompilationResult;
//import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration;
import org.eclipse.jdt.internal.compiler.ast.Clinit;
import org.eclipse.jdt.internal.compiler.ast.MethodDeclaration;
//import org.eclipse.jdt.internal.compiler.ast.ConstructorDeclaration;
import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration;
import org.eclipse.jdt.internal.compiler.codegen.CodeStream;
import org.eclipse.jdt.internal.compiler.codegen.Label;
import org.eclipse.jdt.internal.compiler.lookup.*;
//import org.eclipse.jdt.internal.compiler.parser.Parser;
// (we used to...) making all aspects member types avoids a nasty hierarchy pain
// switched from MemberTypeDeclaration to TypeDeclaration
public class AspectDeclaration extends TypeDeclaration {
//public IAjDeclaration[] ajDeclarations;
private AjAttribute.Aspect aspectAttribute;
public PerClause perClause;
public ResolvedMember aspectOfMethod;
public ResolvedMember hasAspectMethod;
public Map accessForInline = new HashMap();
public Map superAccessForInline = new HashMap();
public boolean isPrivileged;
public EclipseSourceType concreteName;
public ResolvedTypeX.Name typeX;
public EclipseFactory factory; //??? should use this consistently
public int adviceCounter = 1; // Used as a part of the generated name for advice methods
// for better error messages in 1.0 to 1.1 transition
public TypePattern dominatesPattern;
public AspectDeclaration(CompilationResult compilationResult) {
super(compilationResult);
//perClause = new PerSingleton();
}
public boolean isAbstract() {
return (modifiers & AccAbstract) != 0;
}
public void resolve() {
if (binding == null) {
ignoreFurtherInvestigation = true;
return;
}
super.resolve();
}
public void checkSpec(ClassScope scope) {
if (ignoreFurtherInvestigation) return;
if (dominatesPattern != null) {
scope.problemReporter().signalError(
dominatesPattern.getStart(), dominatesPattern.getEnd(),
"dominates has changed for 1.1, use 'declare precedence: " +
new String(this.name) + ", " + dominatesPattern.toString() + ";' " +
"in the body of the aspect instead");
}
if (!isAbstract()) {
MethodBinding[] methods = binding.methods();
for (int i=0, len = methods.length; i < len; i++) {
MethodBinding m = methods[i];
if (m.isConstructor()) {
// this make all constructors in aspects invisible and thus uncallable
//XXX this only works for aspects that come from source
methods[i] = new MethodBinding(m, binding) {
public boolean canBeSeenBy(
InvocationSite invocationSite,
Scope scope) {
return false;
}
};
if (m.parameters != null && m.parameters.length != 0) {
scope.problemReporter().signalError(m.sourceStart(), m.sourceEnd(),
"only zero-argument constructors allowed in concrete aspect");
}
}
}
}
if (this.enclosingType != null) {
if (!Modifier.isStatic(modifiers)) {
scope.problemReporter().signalError(sourceStart, sourceEnd,
"inner aspects must be static");
ignoreFurtherInvestigation = true;
return;
}
}
EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(scope);
ResolvedTypeX myType = typeX;
//if (myType == null) System.err.println("bad myType for: " + this);
ResolvedTypeX superType = myType.getSuperclass();
// can't be Serializable/Cloneable unless -XserializableAspects
if (!world.isXSerializableAspects()) {
if (world.getWorld().getCoreType(TypeX.SERIALIZABLE).isAssignableFrom(myType)) {
scope.problemReporter().signalError(sourceStart, sourceEnd,
"aspects may not implement Serializable");
ignoreFurtherInvestigation = true;
return;
}
if (world.getWorld().getCoreType(TypeX.CLONEABLE).isAssignableFrom(myType)) {
scope.problemReporter().signalError(sourceStart, sourceEnd,
"aspects may not implement Cloneable");
ignoreFurtherInvestigation = true;
return;
}
}
if (superType.isAspect()) {
if (!superType.isAbstract()) {
scope.problemReporter().signalError(sourceStart, sourceEnd,
"can not extend a concrete aspect");
ignoreFurtherInvestigation = true;
return;
}
}
}
private FieldBinding initFailureField= null;
public void generateCode(ClassFile enclosingClassFile) {
if (ignoreFurtherInvestigation) {
if (binding == null)
return;
ClassFile.createProblemType(
this,
scope.referenceCompilationUnit().compilationResult);
return;
}
// make me and my binding public
this.modifiers = AstUtil.makePublic(this.modifiers);
this.binding.modifiers = AstUtil.makePublic(this.binding.modifiers);
if (!isAbstract()) {
initFailureField = factory.makeFieldBinding(AjcMemberMaker.initFailureCauseField(typeX));
binding.addField(initFailureField);
if (perClause == null) {
// we've already produced an error for this
} else if (perClause.getKind() == PerClause.SINGLETON) {
binding.addField(factory.makeFieldBinding(AjcMemberMaker.perSingletonField(
typeX)));
methods[0] = new AspectClinit((Clinit)methods[0], compilationResult, false, true, initFailureField);
} else if (perClause.getKind() == PerClause.PERCFLOW) {
binding.addField(
factory.makeFieldBinding(
AjcMemberMaker.perCflowField(
typeX)));
methods[0] = new AspectClinit((Clinit)methods[0], compilationResult, true, false, null);
} else if (perClause.getKind() == PerClause.PEROBJECT) {
// binding.addField(
// world.makeFieldBinding(
// AjcMemberMaker.perCflowField(
// typeX)));
} else {
throw new RuntimeException("unimplemented");
}
}
if (EclipseFactory.DEBUG) System.out.println(toString());
super.generateCode(enclosingClassFile);
}
public boolean needClassInitMethod() {
return true;
}
protected void generateAttributes(ClassFile classFile) {
if (!isAbstract()) generatePerSupportMembers(classFile);
generateInlineAccessMembers(classFile);
classFile.extraAttributes.add(
new EclipseAttributeAdapter(new AjAttribute.Aspect(perClause)));
if (binding.privilegedHandler != null) {
ResolvedMember[] members = ((PrivilegedHandler)binding.privilegedHandler).getMembers();
classFile.extraAttributes.add(
new EclipseAttributeAdapter(new AjAttribute.PrivilegedAttribute(members)));
}
//XXX need to get this attribute on anyone with a pointcut for good errors
classFile.extraAttributes.add(
new EclipseAttributeAdapter(new AjAttribute.SourceContextAttribute(
new String(compilationResult().getFileName()),
compilationResult().lineSeparatorPositions)));
super.generateAttributes(classFile);
}
private void generateInlineAccessMembers(ClassFile classFile) {
for (Iterator i = superAccessForInline.values().iterator(); i.hasNext(); ) {
AccessForInlineVisitor.SuperAccessMethodPair pair = (AccessForInlineVisitor.SuperAccessMethodPair)i.next();
generateSuperAccessMethod(classFile, pair.accessMethod, pair.originalMethod);
}
for (Iterator i = accessForInline.entrySet().iterator(); i.hasNext(); ) {
Map.Entry e = (Map.Entry)i.next();
generateInlineAccessMethod(classFile, (Binding)e.getValue(), (ResolvedMember)e.getKey());
}
}
private void generatePerSupportMembers(ClassFile classFile) {
if (isAbstract()) return;
//XXX otherwise we need to have this (error handling?)
if (aspectOfMethod == null) return;
if (perClause == null) {
System.err.println("has null perClause: " + this);
return;
}
EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
if (perClause.getKind() == PerClause.SINGLETON) {
generatePerSingletonAspectOfMethod(classFile);
generatePerSingletonHasAspectMethod(classFile);
generatePerSingletonAjcClinitMethod(classFile);
} else if (perClause.getKind() == PerClause.PERCFLOW) {
generatePerCflowAspectOfMethod(classFile);
generatePerCflowHasAspectMethod(classFile);
generatePerCflowPushMethod(classFile);
generatePerCflowAjcClinitMethod(classFile);
} else if (perClause.getKind() == PerClause.PEROBJECT) {
TypeBinding interfaceType =
generatePerObjectInterface(classFile);
world.addTypeBinding(interfaceType);
generatePerObjectAspectOfMethod(classFile, interfaceType);
generatePerObjectHasAspectMethod(classFile, interfaceType);
generatePerObjectBindMethod(classFile, interfaceType);
} else {
throw new RuntimeException("unimplemented");
}
}
private static interface BodyGenerator {
public void generate(CodeStream codeStream);
}
private void generateMethod(ClassFile classFile, ResolvedMember member, BodyGenerator gen) {
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, world.makeMethodBinding(member), gen);
}
private void generateMethod(ClassFile classFile, MethodBinding methodBinding, BodyGenerator gen) {
generateMethod(classFile,methodBinding,null,gen);
}
protected List makeEffectiveSignatureAttribute(ResolvedMember sig,Shadow.Kind kind,boolean weaveBody) {
List l = new ArrayList(1);
l.add(new EclipseAttributeAdapter(
new AjAttribute.EffectiveSignatureAttribute(sig, kind, weaveBody)));
return l;
}
/*
* additionalAttributes allows us to pass some optional attributes we want to attach to the method we generate.
* Currently this is used for inline accessor methods that have been generated to allow private field references or
* private method calls to be inlined (PR71377). In these cases the optional attribute is an effective signature
* attribute which means calls to these methods are able to masquerade as any join point (a field set, field get or
* method call). The effective signature attribute is 'unwrapped' in BcelClassWeaver.matchInvokeInstruction()
*/
private void generateMethod(ClassFile classFile, MethodBinding methodBinding, List additionalAttributes/*ResolvedMember realMember*/, BodyGenerator gen) {
// EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
classFile.generateMethodInfoHeader(methodBinding);
int methodAttributeOffset = classFile.contentsOffset;
int attributeNumber;
if (additionalAttributes!=null) { // mini optimization
List attrs = new ArrayList();
attrs.addAll(AstUtil.getAjSyntheticAttribute());
attrs.addAll(additionalAttributes);
attributeNumber = classFile.generateMethodInfoAttribute(methodBinding, attrs);
} else {
attributeNumber = classFile.generateMethodInfoAttribute(methodBinding, AstUtil.getAjSyntheticAttribute());
}
int codeAttributeOffset = classFile.contentsOffset;
classFile.generateCodeAttributeHeader();
CodeStream codeStream = classFile.codeStream;
// Use reset() rather than init()
// XXX We need a scope to keep reset happy, initializerScope is *not* the right one, but it works !
// codeStream.init(classFile);
// codeStream.initializeMaxLocals(methodBinding);
MethodDeclaration md = AstUtil.makeMethodDeclaration(methodBinding);
md.scope = initializerScope;
codeStream.reset(md,classFile);
// body starts here
gen.generate(codeStream);
// body ends here
classFile.completeCodeAttribute(codeAttributeOffset);
attributeNumber++;
classFile.completeMethodInfo(methodAttributeOffset, attributeNumber);
}
private void generatePerCflowAspectOfMethod(
ClassFile classFile)
{
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, aspectOfMethod, new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
codeStream.getstatic(
world.makeFieldBinding(
AjcMemberMaker.perCflowField(
typeX)));
codeStream.invokevirtual(world.makeMethodBindingForCall(
AjcMemberMaker.cflowStackPeekInstance()));
codeStream.checkcast(binding);
codeStream.areturn();
// body ends here
}});
}
private void generatePerCflowHasAspectMethod(ClassFile classFile) {
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, hasAspectMethod, new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
codeStream.getstatic(
world.makeFieldBinding(
AjcMemberMaker.perCflowField(
typeX)));
codeStream.invokevirtual(world.makeMethodBindingForCall(
AjcMemberMaker.cflowStackIsValid()));
codeStream.ireturn();
// body ends here
}});
}
private void generatePerCflowPushMethod(
ClassFile classFile)
{
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, world.makeMethodBinding(AjcMemberMaker.perCflowPush(
EclipseFactory.fromBinding(binding))),
new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
codeStream.getstatic(
world.makeFieldBinding(
AjcMemberMaker.perCflowField(
typeX)));
codeStream.new_(binding);
codeStream.dup();
codeStream.invokespecial(
new MethodBinding(0, "<init>".toCharArray(),
BaseTypes.VoidBinding, new TypeBinding[0],
new ReferenceBinding[0], binding));
codeStream.invokevirtual(world.makeMethodBindingForCall(
AjcMemberMaker.cflowStackPushInstance()));
codeStream.return_();
// body ends here
}});
}
private void generatePerCflowAjcClinitMethod(
ClassFile classFile)
{
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, world.makeMethodBinding(AjcMemberMaker.ajcPreClinitMethod(
EclipseFactory.fromBinding(binding))),
new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
codeStream.new_(world.makeTypeBinding(AjcMemberMaker.CFLOW_STACK_TYPE));
codeStream.dup();
codeStream.invokespecial(world.makeMethodBindingForCall(AjcMemberMaker.cflowStackInit()));
codeStream.putstatic(
world.makeFieldBinding(
AjcMemberMaker.perCflowField(
typeX)));
codeStream.return_();
// body ends here
}});
}
private TypeBinding generatePerObjectInterface(
ClassFile classFile)
{
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
TypeX interfaceTypeX =
AjcMemberMaker.perObjectInterfaceType(typeX);
HelperInterfaceBinding interfaceType =
new HelperInterfaceBinding(this.binding, interfaceTypeX);
world.addTypeBinding(interfaceType);
interfaceType.addMethod(world, AjcMemberMaker.perObjectInterfaceGet(typeX));
interfaceType.addMethod(world, AjcMemberMaker.perObjectInterfaceSet(typeX));
interfaceType.generateClass(compilationResult, classFile);
return interfaceType;
}
private void generatePerObjectAspectOfMethod(
ClassFile classFile,
final TypeBinding interfaceType)
{
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, aspectOfMethod, new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
Label wrongType = new Label(codeStream);
Label popWrongType = new Label(codeStream);
codeStream.aload_0();
codeStream.instance_of(interfaceType);
codeStream.ifeq(wrongType);
codeStream.aload_0();
codeStream.checkcast(interfaceType);
codeStream.invokeinterface(world.makeMethodBindingForCall(
AjcMemberMaker.perObjectInterfaceGet(typeX)));
codeStream.dup();
codeStream.ifnull(popWrongType);
codeStream.areturn();
popWrongType.place();
codeStream.pop();
wrongType.place();
codeStream.new_(world.makeTypeBinding(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION));
codeStream.dup();
codeStream.invokespecial(world.makeMethodBindingForCall(
AjcMemberMaker.noAspectBoundExceptionInit()
));
codeStream.athrow();
// body ends here
}});
}
private void generatePerObjectHasAspectMethod(ClassFile classFile,
final TypeBinding interfaceType) {
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, hasAspectMethod, new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
Label wrongType = new Label(codeStream);
codeStream.aload_0();
codeStream.instance_of(interfaceType);
codeStream.ifeq(wrongType);
codeStream.aload_0();
codeStream.checkcast(interfaceType);
codeStream.invokeinterface(world.makeMethodBindingForCall(
AjcMemberMaker.perObjectInterfaceGet(typeX)));
codeStream.ifnull(wrongType);
codeStream.iconst_1();
codeStream.ireturn();
wrongType.place();
codeStream.iconst_0();
codeStream.ireturn();
// body ends here
}});
}
private void generatePerObjectBindMethod(
ClassFile classFile,
final TypeBinding interfaceType)
{
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, AjcMemberMaker.perObjectBind(EclipseFactory.fromBinding(binding)),
new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
Label wrongType = new Label(codeStream);
codeStream.aload_0();
codeStream.instance_of(interfaceType);
codeStream.ifeq(wrongType); //XXX this case might call for screaming
codeStream.aload_0();
codeStream.checkcast(interfaceType);
codeStream.invokeinterface(world.makeMethodBindingForCall(
AjcMemberMaker.perObjectInterfaceGet(typeX)));
//XXX should do a check for null here and throw a NoAspectBound
codeStream.ifnonnull(wrongType);
codeStream.aload_0();
codeStream.checkcast(interfaceType);
codeStream.new_(binding);
codeStream.dup();
codeStream.invokespecial(
new MethodBinding(0, "<init>".toCharArray(),
BaseTypes.VoidBinding, new TypeBinding[0],
new ReferenceBinding[0], binding));
codeStream.invokeinterface(world.makeMethodBindingForCall(
AjcMemberMaker.perObjectInterfaceSet(typeX)));
wrongType.place();
codeStream.return_();
// body ends here
}});
}
private void generatePerSingletonAspectOfMethod(ClassFile classFile) {
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, aspectOfMethod, new BodyGenerator() {
public void generate(CodeStream codeStream) {
// Old style aspectOf() method which confused decompilers
// // body starts here
// codeStream.getstatic(world.makeFieldBinding(AjcMemberMaker.perSingletonField(
// typeX)));
// Label isNull = new Label(codeStream);
// codeStream.dup();
// codeStream.ifnull(isNull);
// codeStream.areturn();
// isNull.place();
//
// codeStream.incrStackSize(+1); // the dup trick above confuses the stack counter
// codeStream.new_(world.makeTypeBinding(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION));
// codeStream.dup();
// codeStream.ldc(typeX.getNameAsIdentifier());
// codeStream.getstatic(initFailureField);
// codeStream.invokespecial(world.makeMethodBindingForCall(
// AjcMemberMaker.noAspectBoundExceptionInitWithCause()
// ));
// codeStream.athrow();
// // body ends here
// The stuff below generates code that looks like this:
/*
* if (ajc$perSingletonInstance == null)
* throw new NoAspectBoundException("A", ajc$initFailureCause);
* else
* return ajc$perSingletonInstance;
*/
// body starts here (see end of each line for what it is doing!)
FieldBinding fb = world.makeFieldBinding(AjcMemberMaker.perSingletonField(typeX));
codeStream.getstatic(fb); // GETSTATIC
Label isNonNull = new Label(codeStream);
codeStream.ifnonnull(isNonNull); // IFNONNULL
codeStream.new_(world.makeTypeBinding(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION)); // NEW
codeStream.dup(); // DUP
codeStream.ldc(typeX.getNameAsIdentifier()); // LDC
codeStream.getstatic(initFailureField); // GETSTATIC
codeStream.invokespecial(world.makeMethodBindingForCall(
AjcMemberMaker.noAspectBoundExceptionInitWithCause())); // INVOKESPECIAL
codeStream.athrow(); // ATHROW
isNonNull.place();
codeStream.getstatic(fb); // GETSTATIC
codeStream.areturn(); // ARETURN
// body ends here
}});
}
private void generatePerSingletonHasAspectMethod(ClassFile classFile) {
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, hasAspectMethod, new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
codeStream.getstatic(world.makeFieldBinding(AjcMemberMaker.perSingletonField(
typeX)));
Label isNull = new Label(codeStream);
codeStream.ifnull(isNull);
codeStream.iconst_1();
codeStream.ireturn();
isNull.place();
codeStream.iconst_0();
codeStream.ireturn();
// body ends here
}});
}
private void generatePerSingletonAjcClinitMethod(
ClassFile classFile)
{
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, world.makeMethodBinding(AjcMemberMaker.ajcPostClinitMethod(
EclipseFactory.fromBinding(binding))),
new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
codeStream.new_(binding);
codeStream.dup();
codeStream.invokespecial(
new MethodBinding(0, "<init>".toCharArray(),
BaseTypes.VoidBinding, new TypeBinding[0],
new ReferenceBinding[0], binding));
codeStream.putstatic(
world.makeFieldBinding(
AjcMemberMaker.perSingletonField(
typeX)));
codeStream.return_();
// body ends here
}});
}
private void generateSuperAccessMethod(ClassFile classFile, final MethodBinding accessMethod, final ResolvedMember method) {
generateMethod(classFile, accessMethod,
new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
codeStream.aload_0();
AstUtil.generateParameterLoads(accessMethod.parameters, codeStream);
codeStream.invokespecial(
factory.makeMethodBinding(method));
AstUtil.generateReturn(accessMethod.returnType, codeStream);
// body ends here
}});
}
private void generateInlineAccessMethod(ClassFile classFile, final Binding binding, final ResolvedMember member) {
if (binding instanceof InlineAccessFieldBinding) {
generateInlineAccessors(classFile, (InlineAccessFieldBinding)binding, member);
} else {
generateInlineAccessMethod(classFile, (MethodBinding)binding, member);
}
}
private void generateInlineAccessors(ClassFile classFile, final InlineAccessFieldBinding accessField, final ResolvedMember field) {
final FieldBinding fieldBinding = factory.makeFieldBinding(field);
generateMethod(classFile, accessField.reader,
makeEffectiveSignatureAttribute(field,Shadow.FieldGet,false),
new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
if (field.isStatic()) {
codeStream.getstatic(fieldBinding);
} else {
codeStream.aload_0();
codeStream.getfield(fieldBinding);
}
AstUtil.generateReturn(accessField.reader.returnType, codeStream);
// body ends here
}});
generateMethod(classFile, accessField.writer,
makeEffectiveSignatureAttribute(field,Shadow.FieldSet,false),
new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
if (field.isStatic()) {
codeStream.load(fieldBinding.type, 0);
codeStream.putstatic(fieldBinding);
} else {
codeStream.aload_0();
codeStream.load(fieldBinding.type, 1);
codeStream.putfield(fieldBinding);
}
codeStream.return_();
// body ends here
}});
}
private void generateInlineAccessMethod(ClassFile classFile, final MethodBinding accessMethod, final ResolvedMember method) {
generateMethod(classFile, accessMethod,
makeEffectiveSignatureAttribute(method, Shadow.MethodCall, false),
new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
AstUtil.generateParameterLoads(accessMethod.parameters, codeStream);
if (method.isStatic()) {
codeStream.invokestatic(factory.makeMethodBinding(method));
} else {
codeStream.invokevirtual(factory.makeMethodBinding(method));
}
AstUtil.generateReturn(accessMethod.returnType, codeStream);
// body ends here
}});
}
private PerClause.Kind lookupPerClauseKind(ReferenceBinding binding) {
PerClause perClause;
if (binding instanceof BinaryTypeBinding) {
ResolvedTypeX superTypeX = factory.fromEclipse(binding);
perClause = superTypeX.getPerClause();
} else if (binding instanceof SourceTypeBinding ) {
SourceTypeBinding sourceSc = (SourceTypeBinding)binding;
if (sourceSc.scope.referenceContext instanceof AspectDeclaration) {
perClause = ((AspectDeclaration)sourceSc.scope.referenceContext).perClause;
} else {
return null;
}
} else {
//XXX need to handle this too
return null;
}
if (perClause == null) {
return lookupPerClauseKind(binding.superclass());
} else {
return perClause.getKind();
}
}
private void buildPerClause(ClassScope scope) {
EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(scope);
if (perClause == null) {
PerClause.Kind kind = lookupPerClauseKind(binding.superclass);
if (kind == null) {
perClause = new PerSingleton();
} else {
perClause = new PerFromSuper(kind);
}
}
aspectAttribute = new AjAttribute.Aspect(perClause);
if (ignoreFurtherInvestigation) return; //???
if (!isAbstract()) {
if (perClause.getKind() == PerClause.SINGLETON) {
aspectOfMethod = AjcMemberMaker.perSingletonAspectOfMethod(typeX);
hasAspectMethod = AjcMemberMaker.perSingletonHasAspectMethod(typeX);
} else if (perClause.getKind() == PerClause.PERCFLOW) {
aspectOfMethod = AjcMemberMaker.perCflowAspectOfMethod(typeX);
hasAspectMethod = AjcMemberMaker.perCflowHasAspectMethod(typeX);
} else if (perClause.getKind() == PerClause.PEROBJECT) {
aspectOfMethod = AjcMemberMaker.perObjectAspectOfMethod(typeX);
hasAspectMethod = AjcMemberMaker.perObjectHasAspectMethod(typeX);
} else {
throw new RuntimeException("bad per clause: " + perClause);
}
binding.addMethod(world.makeMethodBinding(aspectOfMethod));
binding.addMethod(world.makeMethodBinding(hasAspectMethod));
}
resolvePerClause(); //XXX might be too soon for some error checking
}
private PerClause resolvePerClause() {
EclipseScope iscope = new EclipseScope(new FormalBinding[0], scope);
perClause.resolve(iscope);
return perClause;
}
public void buildInterTypeAndPerClause(ClassScope classScope) {
factory = EclipseFactory.fromScopeLookupEnvironment(scope);
if (isPrivileged) {
binding.privilegedHandler = new PrivilegedHandler(this);
}
checkSpec(classScope);
if (ignoreFurtherInvestigation) return;
buildPerClause(scope);
if (methods != null) {
for (int i = 0; i < methods.length; i++) {
if (methods[i] instanceof InterTypeDeclaration) {
EclipseTypeMunger m = ((InterTypeDeclaration)methods[i]).build(classScope);
if (m != null) concreteName.typeMungers.add(m);
} else if (methods[i] instanceof DeclareDeclaration) {
Declare d = ((DeclareDeclaration)methods[i]).build(classScope);
if (d != null) concreteName.declares.add(d);
}
}
}
concreteName.getDeclaredPointcuts();
}
// public String toString(int tab) {
// return tabString(tab) + toStringHeader() + toStringBody(tab);
// }
//
// public String toStringBody(int tab) {
//
// String s = " {"; //$NON-NLS-1$
//
//
// if (memberTypes != null) {
// for (int i = 0; i < memberTypes.length; i++) {
// if (memberTypes[i] != null) {
// s += "\n" + memberTypes[i].toString(tab + 1); //$NON-NLS-1$
// }
// }
// }
// if (fields != null) {
// for (int fieldI = 0; fieldI < fields.length; fieldI++) {
// if (fields[fieldI] != null) {
// s += "\n" + fields[fieldI].toString(tab + 1); //$NON-NLS-1$
// if (fields[fieldI].isField())
// s += ";"; //$NON-NLS-1$
// }
// }
// }
// if (methods != null) {
// for (int i = 0; i < methods.length; i++) {
// if (methods[i] != null) {
// s += "\n" + methods[i].toString(tab + 1); //$NON-NLS-1$
// }
// }
// }
// s += "\n" + tabString(tab) + "}"; //$NON-NLS-2$ //$NON-NLS-1$
// return s;
// }
public StringBuffer printHeader(int indent, StringBuffer output) {
printModifiers(this.modifiers, output);
output.append("aspect " );
output.append(name);
if (superclass != null) {
output.append(" extends "); //$NON-NLS-1$
superclass.print(0, output);
}
if (superInterfaces != null && superInterfaces.length > 0) {
output.append(isInterface() ? " extends " : " implements ");//$NON-NLS-2$ //$NON-NLS-1$
for (int i = 0; i < superInterfaces.length; i++) {
if (i > 0) output.append( ", "); //$NON-NLS-1$
superInterfaces[i].print(0, output);
}
}
return output;
//XXX we should append the per-clause
}
}
|
73,334
|
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
|
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
|
resolved fixed
|
b133299
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:40:02Z
| 2004-09-06T17:00:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/AstUtil.java
|
/* *******************************************************************
* 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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.ast;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
import org.aspectj.weaver.AjAttribute;
import org.aspectj.weaver.patterns.WildTypePattern;
import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration;
import org.eclipse.jdt.internal.compiler.ast.Argument;
import org.eclipse.jdt.internal.compiler.ast.ASTNode;
import org.eclipse.jdt.internal.compiler.ast.Expression;
import org.eclipse.jdt.internal.compiler.ast.MessageSend;
import org.eclipse.jdt.internal.compiler.ast.MethodDeclaration;
import org.eclipse.jdt.internal.compiler.ast.NameReference;
import org.eclipse.jdt.internal.compiler.ast.QualifiedNameReference;
import org.eclipse.jdt.internal.compiler.ast.QualifiedTypeReference;
import org.eclipse.jdt.internal.compiler.ast.ReturnStatement;
import org.eclipse.jdt.internal.compiler.ast.SingleNameReference;
import org.eclipse.jdt.internal.compiler.ast.Statement;
import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration;
import org.eclipse.jdt.internal.compiler.ast.TypeReference;
import org.eclipse.jdt.internal.compiler.codegen.CodeStream;
import org.eclipse.jdt.internal.compiler.env.IConstants;
import org.eclipse.jdt.internal.compiler.impl.Constant;
import org.eclipse.jdt.internal.compiler.lookup.BaseTypes;
import org.eclipse.jdt.internal.compiler.lookup.BindingIds;
import org.eclipse.jdt.internal.compiler.lookup.CompilationUnitScope;
import org.eclipse.jdt.internal.compiler.lookup.LocalVariableBinding;
import org.eclipse.jdt.internal.compiler.lookup.MethodBinding;
import org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding;
import org.eclipse.jdt.internal.compiler.lookup.Scope;
import org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding;
import org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
import org.eclipse.jdt.internal.compiler.lookup.TypeIds;
import org.eclipse.jdt.core.compiler.CharOperation;
public class AstUtil {
private AstUtil() {}
public static void addMethodBinding(SourceTypeBinding sourceType, MethodBinding method) {
int len = sourceType.methods.length;
MethodBinding[] temp = new MethodBinding[len + 1];
System.arraycopy(sourceType.methods, 0, temp, 0, len);
temp[len] = method;
sourceType.methods = temp;
}
public static void addMethodDeclaration(TypeDeclaration typeDec, AbstractMethodDeclaration dec) {
AbstractMethodDeclaration[] methods = typeDec.methods;
int len = methods.length;
AbstractMethodDeclaration[] newMethods = new AbstractMethodDeclaration[len+1];
System.arraycopy(methods, 0, newMethods, 0, len);
newMethods[len] = dec;
typeDec.methods = newMethods;
}
public static Argument makeFinalArgument(char[] name, TypeBinding typeBinding) {
long pos = 0; //XXX encode start and end location
LocalVariableBinding binding =
new LocalVariableBinding(name, typeBinding, Modifier.FINAL, true);
Argument ret = new Argument(name, pos, makeTypeReference(typeBinding), Modifier.FINAL);
ret.binding = binding;
return ret;
}
public static TypeReference makeTypeReference(TypeBinding binding) {
// ??? does this work for primitives
QualifiedTypeReference ref =
new QualifiedTypeReference(new char[][] {binding.sourceName()}, binding, new long[] {0}); //???
ref.constant = Constant.NotAConstant;
return ref;
}
public static NameReference makeNameReference(TypeBinding binding) {
char[][] name = new char[][] {binding.sourceName()};
long[] dummyPositions = new long[name.length];
QualifiedNameReference ref =
new QualifiedNameReference(name, dummyPositions, 0, 0);
ref.binding = binding; ref.constant = Constant.NotAConstant;
return ref;
}
public static ReturnStatement makeReturnStatement(Expression expr) {
return new ReturnStatement(expr, 0, 0);
}
public static MethodDeclaration makeMethodDeclaration(
MethodBinding binding)
{
MethodDeclaration ret = new MethodDeclaration(null);
ret.binding = binding;
int nargs = binding.parameters.length;
ret.arguments = new Argument[nargs];
for (int i=0; i < nargs; i++) {
ret.arguments[i] = makeFinalArgument(("arg"+i).toCharArray(),
binding.parameters[i]);
}
return ret;
}
public static void setStatements(
MethodDeclaration ret, List statements)
{
ret.statements =
(Statement[])statements.toArray(new Statement[statements.size()]);
}
public static SingleNameReference makeLocalVariableReference(
LocalVariableBinding binding)
{
SingleNameReference ret = new SingleNameReference(binding.name, 0);
ret.binding = binding;
ret.codegenBinding = binding;
ret.constant = ASTNode.NotAConstant;
ret.bits &= ~ASTNode.RestrictiveFlagMASK; // clear bits
ret.bits |= BindingIds.VARIABLE;
return ret;
}
public static SingleNameReference makeResolvedLocalVariableReference(
LocalVariableBinding binding)
{
SingleNameReference ret = new SingleNameReference(binding.name, 0);
ret.binding = binding;
ret.codegenBinding = binding;
ret.constant = ASTNode.NotAConstant;
ret.bits &= ~ASTNode.RestrictiveFlagMASK; // clear bits
ret.bits |= BindingIds.LOCAL;
return ret;
}
public static int makePublic(int modifiers) {
return makePackageVisible(modifiers) | IConstants.AccPublic;
}
public static int makePackageVisible(int modifiers) {
modifiers &= ~(IConstants.AccPublic | IConstants.AccPrivate | IConstants.AccProtected);
return modifiers;
}
public static CompilationUnitScope getCompilationUnitScope(Scope scope) {
if (scope instanceof CompilationUnitScope) {
return (CompilationUnitScope)scope;
}
return getCompilationUnitScope(scope.parent);
}
public static void generateParameterLoads(TypeBinding[] parameters, CodeStream codeStream) {
int paramIndex = 0;
int varIndex = 0;
while (paramIndex < parameters.length) {
TypeBinding param = parameters[paramIndex++];
codeStream.load(param, varIndex);
varIndex += slotsNeeded(param);
}
}
public static void generateReturn(TypeBinding returnType, CodeStream codeStream) {
if (returnType.id == TypeIds.T_void) {
codeStream.return_();
} else if (returnType.isBaseType()) {
switch (returnType.id) {
case TypeBinding.T_boolean :
case TypeBinding.T_int :
case TypeBinding.T_byte :
case TypeBinding.T_short :
case TypeBinding.T_char :
codeStream.ireturn();
break;
case TypeBinding.T_float :
codeStream.freturn();
break;
case TypeBinding.T_long :
codeStream.lreturn();
break;
case TypeBinding.T_double :
codeStream.dreturn();
break;
default :
throw new RuntimeException("huh");
}
} else {
codeStream.areturn();
}
}
//XXX this could be inconsistent for wierd case, i.e. a class named "java_lang_String"
public static char[] makeMangledName(ReferenceBinding type) {
return CharOperation.concatWith(type.compoundName, '_');
}
public static final char[] PREFIX = "ajc".toCharArray();
//XXX not efficient
public static char[] makeAjcMangledName(char[] kind, ReferenceBinding type, char[] name) {
return CharOperation.concat(
CharOperation.concat(PREFIX, new char[] {'$'}, kind), '$', makeMangledName(type), '$', name);
}
public static char[] makeAjcMangledName(char[] kind, char[] p, char[] name) {
return CharOperation.concat(
CharOperation.concat(PREFIX, new char[] {'$'}, kind), '$', p, '$', name);
}
public static List getAjSyntheticAttribute() {
ArrayList ret = new ArrayList(1);
ret.add(new EclipseAttributeAdapter(new AjAttribute.AjSynthetic()));
return ret;
}
public static long makeLongPos(int start, int end) {
return (long)end | ((long)start << 32);
}
public static char[][] getCompoundName(String string) {
return WildTypePattern.splitNames(string);
}
public static TypeBinding[] insert(
TypeBinding first,
TypeBinding[] rest) {
if (rest == null) {
return new TypeBinding[] {first};
}
int len = rest.length;
TypeBinding[] ret = new TypeBinding[len+1];
ret[0] = first;
System.arraycopy(rest, 0, ret, 1, len);
return ret;
}
public static Argument[] insert(
Argument first,
Argument[] rest) {
if (rest == null) {
return new Argument[] {first};
}
int len = rest.length;
Argument[] ret = new Argument[len+1];
ret[0] = first;
System.arraycopy(rest, 0, ret, 1, len);
return ret;
}
public static Argument[] copyArguments(Argument[] inArgs) {
if (inArgs == null) return new Argument[] {};
int len = inArgs.length;
Argument[] outArgs = new Argument[len];
//??? we're not sure whether or not copying these is okay
System.arraycopy(inArgs, 0, outArgs, 0, len);
return outArgs;
}
public static Statement[] remove(int i, Statement[] statements) {
int len = statements.length;
Statement[] ret = new Statement[len-1];
System.arraycopy(statements, 0, ret, 0, i);
System.arraycopy(statements, i+1, ret, i, len-i-1);
return ret;
}
public static int slotsNeeded(TypeBinding type) {
if (type == BaseTypes.DoubleBinding || type == BaseTypes.LongBinding) return 2;
else return 1;
}
public static void replaceMethodBinding(MessageSend send, MethodBinding newBinding) {
send.binding = send.codegenBinding = newBinding;
send.setActualReceiverType(newBinding.declaringClass);
}
}
|
73,334
|
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
|
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
|
resolved fixed
|
b133299
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:40:02Z
| 2004-09-06T17:00:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/DeclareDeclaration.java
|
/* *******************************************************************
* 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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.ast;
//import java.util.List;
import org.aspectj.ajdt.internal.compiler.lookup.EclipseScope;
import org.aspectj.weaver.AjAttribute;
import org.aspectj.weaver.patterns.Declare;
import org.aspectj.weaver.patterns.FormalBinding;
import org.eclipse.jdt.internal.compiler.ClassFile;
import org.eclipse.jdt.internal.compiler.CompilationResult;
import org.eclipse.jdt.internal.compiler.ast.*;
import org.eclipse.jdt.internal.compiler.lookup.ClassScope;
import org.eclipse.jdt.internal.compiler.parser.Parser;
public class DeclareDeclaration extends AjMethodDeclaration {
public Declare declareDecl;
/**
* Constructor for IntraTypeDeclaration.
*/
static int counter = 0; //XXX evil
public DeclareDeclaration(CompilationResult result, Declare symbolicDeclare) {
super(result);
this.declareDecl = symbolicDeclare;
if (declareDecl != null) {
// AMC added init of declarationSourceXXX fields which are used
// in AsmBuilder for processing of MethodDeclaration locations.
declarationSourceStart = sourceStart = declareDecl.getStart();
declarationSourceEnd = sourceEnd = declareDecl.getEnd();
}
//??? we might need to set parameters to be empty
this.returnType = TypeReference.baseTypeReference(T_void, 0);
this.selector = ("ajc$declare_"+counter++).toCharArray(); //??? performance
}
/**
* A pointcut declaration exists in a classfile only as an attibute on the
* class. Unlike advice and inter-type declarations, it has no corresponding
* method.
*/
public void generateCode(ClassScope classScope, ClassFile classFile) {
classFile.extraAttributes.add(new EclipseAttributeAdapter(new AjAttribute.DeclareAttribute(declareDecl)));
return;
}
public void parseStatements(
Parser parser,
CompilationUnitDeclaration unit) {
// do nothing
}
public void resolveStatements(ClassScope upperScope) {
// do nothing
}
// public boolean finishResolveTypes(SourceTypeBinding sourceTypeBinding) {
// // there's nothing for our super to resolve usefully
// //if (!super.finishResolveTypes(sourceTypeBinding)) return false;
//// if (declare == null) return true;
////
//// EclipseScope scope = new EclipseScope(new FormalBinding[0], this.scope);
////
//// declare.resolve(scope);
//// return true;
// }
public Declare build(ClassScope classScope) {
if (declareDecl == null) return null;
EclipseScope scope = new EclipseScope(new FormalBinding[0], classScope);
declareDecl.resolve(scope);
return declareDecl;
}
public StringBuffer print(int tab, StringBuffer output) {
printIndent(tab, output);
if (declareDecl == null) {
output.append("<declare>");
} else {
output.append(declareDecl.toString());
}
return output;
}
}
|
73,334
|
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
|
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
|
resolved fixed
|
b133299
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:40:02Z
| 2004-09-06T17:00:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/EclipseAttributeAdapter.java
|
/* *******************************************************************
* 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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.ast;
import org.aspectj.weaver.AjAttribute;
import org.eclipse.jdt.internal.compiler.IAttribute;
public class EclipseAttributeAdapter implements IAttribute {
AjAttribute attr;
public EclipseAttributeAdapter(AjAttribute attr) {
this.attr = attr;
}
public char[] getNameChars() {
return attr.getNameChars();
}
public byte[] getAllBytes(short nameIndex) {
return attr.getAllBytes(nameIndex);
}
}
|
73,334
|
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
|
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
|
resolved fixed
|
b133299
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:40:02Z
| 2004-09-06T17:00:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/IfMethodDeclaration.java
|
/* *******************************************************************
* 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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.ast;
import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedTypeX;
import org.aspectj.weaver.patterns.IfPointcut;
import org.eclipse.jdt.internal.compiler.ClassFile;
import org.eclipse.jdt.internal.compiler.CompilationResult;
import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration;
//import org.eclipse.jdt.internal.compiler.lookup.ClassScope;
import org.eclipse.jdt.internal.compiler.parser.Parser;
public class IfMethodDeclaration extends AjMethodDeclaration {
IfPointcut ifPointcut;
public IfMethodDeclaration(CompilationResult compilationResult, IfPointcut ifPointcut) {
super(compilationResult);
this.ifPointcut = ifPointcut;
}
public void parseStatements(
Parser parser,
CompilationUnitDeclaration unit) {
// do nothing, we're already fully parsed
}
protected int generateInfoAttributes(ClassFile classFile) {
return classFile.generateMethodInfoAttribute(binding, AstUtil.getAjSyntheticAttribute());
}
public void resolveStatements() {
super.resolveStatements();
if (binding != null) {
ThisJoinPointVisitor tjp = new ThisJoinPointVisitor(this);
ifPointcut.extraParameterFlags |= tjp.removeUnusedExtraArguments();
//XXX this is where we should remove unavailable args if we're in a cflow
ifPointcut.testMethod = new ResolvedMember(
Member.METHOD,
EclipseFactory.fromBinding(binding.declaringClass),
this.modifiers, ResolvedTypeX.BOOLEAN,
new String(this.selector),
EclipseFactory.fromBindings(this.binding.parameters));
}
}
}
|
73,334
|
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
|
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
|
resolved fixed
|
b133299
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:40:02Z
| 2004-09-06T17:00:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/IfPseudoToken.java
|
/* *******************************************************************
* 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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.ast;
import java.lang.reflect.Modifier;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.TypeX;
import org.aspectj.weaver.patterns.IfPointcut;
import org.aspectj.weaver.patterns.Pointcut;
import org.eclipse.jdt.internal.compiler.CompilationResult;
import org.eclipse.jdt.internal.compiler.ast.Argument;
import org.eclipse.jdt.internal.compiler.ast.Expression;
import org.eclipse.jdt.internal.compiler.ast.FalseLiteral;
import org.eclipse.jdt.internal.compiler.ast.MethodDeclaration;
import org.eclipse.jdt.internal.compiler.ast.ReturnStatement;
import org.eclipse.jdt.internal.compiler.ast.Statement;
import org.eclipse.jdt.internal.compiler.ast.TrueLiteral;
import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration;
import org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
import org.eclipse.jdt.internal.compiler.parser.Parser;
/**
* (formals*): ... if(expr) ...
*
* generates the following:
* public static final boolean ajc$if_N(formals*, [thisJoinPoints as needed]) {
* return expr;
* }
*
* Here's the complicated bit, it deals with cflow:
* (a): ... this(a) && cflow(if (a == foo)) is an error.
* The way we capture this is:
* We generate the ajc$if method with an (a) parameter, we let eclipse do the proper
* name binding. We then, as a post pass (that we need to do anyway) look for the
* used parameters. If a is used, we signal an error because a was not one of the
* cflow variables.
* XXX we'll do this part after we do cflow
*
* The IfPointcut pcd then generates itself always as a dynamic test, it has to
* get the right parameters through any named pointcut references...
*/
public class IfPseudoToken extends PseudoToken {
public Expression expr;
public MethodDeclaration testMethod;
private IfPointcut pointcut;
public IfPseudoToken(
Parser parser,
Expression expr) {
super(parser, "if", false);
this.expr = expr;
}
public Pointcut maybeGetParsedPointcut() {
if (expr instanceof FalseLiteral) {
return IfPointcut.makeIfFalsePointcut(Pointcut.SYMBOLIC);
} else if (expr instanceof TrueLiteral) {
return IfPointcut.makeIfTruePointcut(Pointcut.SYMBOLIC);
} else {
pointcut = new IfPointcut(new ResolvedMember(Member.METHOD, TypeX.OBJECT, 0, "if_", "()V"), 0);
}
return pointcut;
}
/**
* enclosingDec is either AdviceDeclaration or PointcutDeclaration
*/
public void postParse(TypeDeclaration typeDec, MethodDeclaration enclosingDec) {
// typeDec.scope.problemReporter().signalError(sourceStart, sourceEnd,
// "if pcd is not implemented in 1.1alpha1");
//XXX need to implement correctly
if (pointcut == null) return;
testMethod = makeMethod(enclosingDec.compilationResult, enclosingDec);
AstUtil.addMethodDeclaration(typeDec, testMethod);
}
//XXX static state bad
private static int counter = 0;
//XXX todo: make sure that errors in Arguments only get displayed once
private MethodDeclaration makeMethod(CompilationResult result, MethodDeclaration enclosingDec) {
MethodDeclaration ret = new IfMethodDeclaration(result, pointcut);
ret.modifiers = AccStatic | AccFinal | AccPublic;
ret.returnType = AstUtil.makeTypeReference(TypeBinding.BooleanBinding);
ret.selector = ("ajc$if_" + counter++).toCharArray();
ret.arguments = makeArguments(enclosingDec);
ret.statements = new Statement[] {
new ReturnStatement(expr, expr.sourceStart, expr.sourceEnd)
};
return ret;
}
private Argument[] makeArguments(MethodDeclaration enclosingDec) {
Argument[] baseArguments = enclosingDec.arguments;
int len = baseArguments.length;
if (enclosingDec instanceof AdviceDeclaration) {
len = ((AdviceDeclaration)enclosingDec).baseArgumentCount;
}
Argument[] ret = new Argument[len];
for (int i=0; i < len; i ++) {
Argument a = baseArguments[i];
ret[i] = new Argument(a.name, AstUtil.makeLongPos(a.sourceStart, a.sourceEnd),
a.type, Modifier.FINAL);
}
ret = AdviceDeclaration.addTjpArguments(ret);
return ret;
}
}
|
73,334
|
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
|
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
|
resolved fixed
|
b133299
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:40:02Z
| 2004-09-06T17:00:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/InterSuperFixerVisitor.java
|
/* *******************************************************************
* 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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.ast;
import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory;
import org.aspectj.ajdt.internal.compiler.lookup.EclipseSourceLocation;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.ISourceLocation;
import org.eclipse.jdt.internal.compiler.ASTVisitor;
import org.eclipse.jdt.internal.compiler.ast.Expression;
import org.eclipse.jdt.internal.compiler.ast.FieldReference;
import org.eclipse.jdt.internal.compiler.ast.MessageSend;
import org.eclipse.jdt.internal.compiler.ast.SuperReference;
import org.eclipse.jdt.internal.compiler.lookup.BlockScope;
import org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding;
import org.eclipse.jdt.internal.compiler.lookup.Scope;
import org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
/**
* Walks the body of inter-type declarations and replaces SuperReference with InterSuperReference
*
* @author Jim Hugunin
*/
public class InterSuperFixerVisitor extends ASTVisitor {
InterTypeDeclaration dec;
ReferenceBinding onType;
TypeBinding superType;
EclipseFactory world;
public InterSuperFixerVisitor(InterTypeDeclaration dec, EclipseFactory world, Scope scope) {
this.dec = dec;
this.onType = dec.onTypeBinding;
this.world = world;
if (onType.superclass() != null) {
superType = onType.superclass();
} else if (onType.superInterfaces() == null || onType.superInterfaces().length == 0) {
superType = scope.getJavaLangObject();
} else if (onType.superInterfaces().length == 1) {
superType = onType.superInterfaces()[0];
} else {
superType = null;
}
}
public void endVisit(FieldReference ref, BlockScope scope) {
ref.receiver = fixReceiver(ref.receiver, scope);
}
public void endVisit(MessageSend send, BlockScope scope) {
send.receiver = fixReceiver(send.receiver, scope);
}
private Expression fixReceiver(Expression expression, BlockScope scope) {
if (expression instanceof SuperReference) {
SuperReference superRef = (SuperReference) expression;
if (superType == null) {
ISourceLocation location =
new EclipseSourceLocation(scope.problemReporter().referenceContext.compilationResult(),
expression.sourceStart, expression.sourceEnd);
world.showMessage(IMessage.ERROR, "multiple supertypes for this interface", location, null);
dec.ignoreFurtherInvestigation = true;
}
//FIXME note error
expression = new InterSuperReference(superRef, superType);
}
return expression;
}
}
|
73,334
|
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
|
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
|
resolved fixed
|
b133299
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:40:02Z
| 2004-09-06T17:00:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/InterSuperReference.java
|
/* *******************************************************************
* 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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.ast;
import org.eclipse.jdt.internal.compiler.ast.SuperReference;
import org.eclipse.jdt.internal.compiler.lookup.BlockScope;
import org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
/**
* Used to represent super references inside of inter-type declarations. Special mechanism
* needed for handling in an interface context.
*
* @author Jim Hugunin
*/
public class InterSuperReference extends SuperReference {
public InterSuperReference(SuperReference template, TypeBinding myType) {
super(template.sourceStart, template.sourceEnd);
this.resolvedType = myType;
}
public TypeBinding resolveType(BlockScope scope) {
return resolvedType;
}
}
|
73,334
|
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
|
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
|
resolved fixed
|
b133299
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:40:02Z
| 2004-09-06T17:00:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/InterTypeConstructorDeclaration.java
|
/* *******************************************************************
* 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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.ast;
import org.aspectj.ajdt.internal.compiler.lookup.*;
import org.aspectj.weaver.*;
import org.eclipse.jdt.internal.compiler.ClassFile;
import org.eclipse.jdt.internal.compiler.CompilationResult;
import org.eclipse.jdt.internal.compiler.ast.*;
import org.eclipse.jdt.internal.compiler.lookup.*;
import org.eclipse.jdt.internal.compiler.parser.Parser;
/**
* An inter-type constructor declaration.
*
* This will generate two implementation methods in the aspect, the main one for the body
* of the constructor, and an additional <code>preMethod</code> for the code that
* runs before the super constructor is called.
*
* @author Jim Hugunin
*/
public class InterTypeConstructorDeclaration extends InterTypeDeclaration {
private MethodDeclaration preMethod;
private ExplicitConstructorCall explicitConstructorCall = null;
public InterTypeConstructorDeclaration(CompilationResult result, TypeReference onType) {
super(result, onType);
}
public void parseStatements(Parser parser, CompilationUnitDeclaration unit) {
if (ignoreFurtherInvestigation)
return;
parser.parse(this, unit);
}
public void resolve(ClassScope upperScope) {
if (munger == null || binding == null) ignoreFurtherInvestigation = true;
if (ignoreFurtherInvestigation) return;
explicitConstructorCall = null;
if (statements != null && statements.length > 0 &&
statements[0] instanceof ExplicitConstructorCall)
{
explicitConstructorCall = (ExplicitConstructorCall) statements[0];
statements = AstUtil.remove(0, statements);
}
preMethod = makePreMethod(upperScope, explicitConstructorCall);
binding.parameters = AstUtil.insert(onTypeBinding, binding.parameters);
this.arguments = AstUtil.insert(
AstUtil.makeFinalArgument("ajc$this_".toCharArray(), onTypeBinding),
this.arguments);
super.resolve(upperScope);
}
private MethodDeclaration makePreMethod(ClassScope scope,
ExplicitConstructorCall explicitConstructorCall)
{
EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(scope);
TypeX aspectTypeX = EclipseFactory.fromBinding(binding.declaringClass);
TypeX targetTypeX = EclipseFactory.fromBinding(onTypeBinding);
ArrayBinding objectArrayBinding = scope.createArray(scope.getJavaLangObject(), 1);
MethodDeclaration pre = new MethodDeclaration(compilationResult);
pre.modifiers = AccPublic | AccStatic;
pre.returnType = AstUtil.makeTypeReference(objectArrayBinding);
pre.selector = NameMangler.postIntroducedConstructor(aspectTypeX, targetTypeX).toCharArray();
pre.arguments = AstUtil.copyArguments(this.arguments);
//XXX should do exceptions
pre.scope = new MethodScope(scope, pre, true);
//??? do we need to do anything with scope???
pre.binding = world.makeMethodBinding(
AjcMemberMaker.preIntroducedConstructor(aspectTypeX, targetTypeX,
EclipseFactory.fromBindings(binding.parameters)));
pre.bindArguments();
pre.bindThrownExceptions();
if (explicitConstructorCall == null) {
pre.statements = new Statement[] {};
} else {
pre.statements = new Statement[] {
explicitConstructorCall
};
}
InterTypeScope newParent =
new InterTypeScope(scope, onTypeBinding);
pre.scope.parent = newParent;
pre.resolveStatements(); //newParent);
int nParams = pre.arguments.length;
MethodBinding explicitConstructor = null;
if (explicitConstructorCall != null) {
explicitConstructor = explicitConstructorCall.binding;
if (explicitConstructor.alwaysNeedsAccessMethod()) {
explicitConstructor = explicitConstructor.getAccessMethod(true);
}
}
int nExprs;
if (explicitConstructor == null) nExprs = 0;
else nExprs = explicitConstructor.parameters.length;
ArrayInitializer init = new ArrayInitializer();
init.expressions = new Expression[nExprs + nParams];
int index = 0;
for (int i=0; i < nExprs; i++) {
if (i >= explicitConstructorCall.arguments.length) {
init.expressions[index++] = new NullLiteral(0, 0);
continue;
}
Expression arg = explicitConstructorCall.arguments[i];
ResolvedMember conversionMethod =
AjcMemberMaker.toObjectConversionMethod(EclipseFactory.fromBinding(explicitConstructorCall.binding.parameters[i]));
if (conversionMethod != null) {
arg = new KnownMessageSend(world.makeMethodBindingForCall(conversionMethod),
new CastExpression(new NullLiteral(0, 0),
AstUtil.makeTypeReference(world.makeTypeBinding(AjcMemberMaker.CONVERSIONS_TYPE))),
new Expression[] {arg });
}
init.expressions[index++] = arg;
}
for (int i=0; i < nParams; i++) {
LocalVariableBinding binding = pre.arguments[i].binding;
Expression arg = AstUtil.makeResolvedLocalVariableReference(binding);
ResolvedMember conversionMethod =
AjcMemberMaker.toObjectConversionMethod(EclipseFactory.fromBinding(binding.type));
if (conversionMethod != null) {
arg = new KnownMessageSend(world.makeMethodBindingForCall(conversionMethod),
new CastExpression(new NullLiteral(0, 0),
AstUtil.makeTypeReference(world.makeTypeBinding(AjcMemberMaker.CONVERSIONS_TYPE))),
new Expression[] {arg });
}
init.expressions[index++] = arg;
}
init.binding =objectArrayBinding;
ArrayAllocationExpression newArray = new ArrayAllocationExpression();
newArray.initializer = init;
newArray.type = AstUtil.makeTypeReference(scope.getJavaLangObject());
newArray.dimensions = new Expression[1];
newArray.constant = NotAConstant;
pre.statements = new Statement[] {
new ReturnStatement(newArray, 0, 0),
};
return pre;
}
public EclipseTypeMunger build(ClassScope classScope) {
EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(classScope);
resolveOnType(classScope);
if (ignoreFurtherInvestigation) return null;
binding = classScope.referenceContext.binding.resolveTypesFor(binding);
if (onTypeBinding.isInterface()) {
classScope.problemReporter().signalError(sourceStart, sourceEnd,
"can't define constructors on interfaces");
ignoreFurtherInvestigation = true;
return null;
}
if (onTypeBinding.isNestedType()) {
classScope.problemReporter().signalError(sourceStart, sourceEnd,
"can't define constructors on nested types (compiler limitation)");
ignoreFurtherInvestigation = true;
return null;
}
ResolvedTypeX declaringTypeX = world.fromEclipse(onTypeBinding);
ResolvedTypeX aspectType = world.fromEclipse(classScope.referenceContext.binding);
ResolvedMember bindingAsMember = EclipseFactory.makeResolvedMember(binding);
ResolvedMember signature =
new ResolvedMember(Member.CONSTRUCTOR, declaringTypeX, declaredModifiers,
ResolvedTypeX.VOID, "<init>", bindingAsMember.getParameterTypes(),
world.fromEclipse(binding.thrownExceptions));
ResolvedMember syntheticInterMember =
AjcMemberMaker.interConstructor(declaringTypeX, signature, aspectType);
NewConstructorTypeMunger myMunger =
new NewConstructorTypeMunger(signature, syntheticInterMember, null, null);
setMunger(myMunger);
myMunger.check(world.getWorld());
this.selector = binding.selector =
NameMangler.postIntroducedConstructor(
EclipseFactory.fromBinding(binding.declaringClass),
declaringTypeX).toCharArray();
return new EclipseTypeMunger(world, myMunger, aspectType, this);
}
private AjAttribute makeAttribute(EclipseFactory world) {
if (explicitConstructorCall != null && !(explicitConstructorCall.binding instanceof ProblemMethodBinding)) {
MethodBinding explicitConstructor = explicitConstructorCall.binding;
if (explicitConstructor.alwaysNeedsAccessMethod()) {
explicitConstructor = explicitConstructor.getAccessMethod(true);
}
((NewConstructorTypeMunger)munger).setExplicitConstructor(
EclipseFactory.makeResolvedMember(explicitConstructor));
} else {
((NewConstructorTypeMunger)munger).setExplicitConstructor(
new ResolvedMember(Member.CONSTRUCTOR,
EclipseFactory.fromBinding(onTypeBinding.superclass()),
0, ResolvedTypeX.VOID, "<init>", TypeX.NONE));
}
return new AjAttribute.TypeMunger(munger);
}
public void generateCode(ClassScope classScope, ClassFile classFile) {
if (ignoreFurtherInvestigation) return;
EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(classScope);
classFile.extraAttributes.add(new EclipseAttributeAdapter(makeAttribute(world)));
super.generateCode(classScope, classFile);
preMethod.generateCode(classScope, classFile);
}
protected Shadow.Kind getShadowKindForBody() {
return Shadow.ConstructorExecution;
}
}
|
73,334
|
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
|
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
|
resolved fixed
|
b133299
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:40:02Z
| 2004-09-06T17:00:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/InterTypeDeclaration.java
|
/* *******************************************************************
* 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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.ast;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory;
import org.aspectj.ajdt.internal.compiler.lookup.EclipseTypeMunger;
import org.aspectj.ajdt.internal.compiler.lookup.InterTypeScope;
import org.aspectj.ajdt.internal.core.builder.EclipseSourceContext;
import org.aspectj.weaver.*;
import org.eclipse.jdt.internal.compiler.ClassFile;
import org.eclipse.jdt.internal.compiler.CompilationResult;
import org.eclipse.jdt.internal.compiler.ast.TypeReference;
import org.eclipse.jdt.internal.compiler.lookup.*;
import org.eclipse.jdt.core.compiler.CharOperation;
/**
* Base type for all inter-type declarations including methods, fields and constructors.
*
* @author Jim Hugunin
*/
public abstract class InterTypeDeclaration extends AjMethodDeclaration {
public TypeReference onType;
protected ReferenceBinding onTypeBinding;
protected ResolvedTypeMunger munger;
protected int declaredModifiers;
protected char[] declaredSelector;
public InterTypeDeclaration(CompilationResult result, TypeReference onType) {
super(result);
this.onType = onType;
modifiers = AccPublic | AccStatic;
}
public void setDeclaredModifiers(int modifiers) {
this.declaredModifiers = modifiers;
}
public void setSelector(char[] selector) {
declaredSelector = selector;
this.selector = CharOperation.concat(selector, Integer.toHexString(sourceStart).toCharArray());
}
public void resolve(ClassScope upperScope) {
if (ignoreFurtherInvestigation) return;
ClassScope newParent = new InterTypeScope(upperScope, onTypeBinding);
scope.parent = newParent;
this.scope.isStatic = Modifier.isStatic(declaredModifiers);
fixSuperCallsForInterfaceContext(upperScope);
if (ignoreFurtherInvestigation) return;
super.resolve(newParent);
fixSuperCallsInBody();
}
private void fixSuperCallsForInterfaceContext(ClassScope scope) {
if (onTypeBinding.isInterface()) {
InterSuperFixerVisitor v =
new InterSuperFixerVisitor(this,
EclipseFactory.fromScopeLookupEnvironment(scope), scope);
this.traverse(v, scope);
}
}
/**
* Called from AspectDeclarations.buildInterTypeAndPerClause
*/
public abstract EclipseTypeMunger build(ClassScope classScope);
public void fixSuperCallsInBody() {
SuperFixerVisitor v = new SuperFixerVisitor(this, onTypeBinding);
this.traverse(v, (ClassScope)null);
munger.setSuperMethodsCalled(v.superMethodsCalled);
}
protected void resolveOnType(ClassScope classScope) {
checkSpec();
onTypeBinding = (ReferenceBinding)onType.getTypeBinding(classScope);
if (!onTypeBinding.isValidBinding()) {
classScope.problemReporter().invalidType(onType, onTypeBinding);
ignoreFurtherInvestigation = true;
}
}
protected void checkSpec() {
if (Modifier.isProtected(declaredModifiers)) {
scope.problemReporter().signalError(sourceStart, sourceEnd,
"protected inter-type declarations are not allowed");
ignoreFurtherInvestigation = true;
}
}
protected List makeEffectiveSignatureAttribute(
ResolvedMember sig,
Shadow.Kind kind,
boolean weaveBody)
{
List l = new ArrayList(1);
l.add(new EclipseAttributeAdapter(
new AjAttribute.EffectiveSignatureAttribute(sig, kind, weaveBody)));
return l;
}
protected void setMunger(ResolvedTypeMunger munger) {
munger.getSignature().setPosition(sourceStart, sourceEnd);
munger.getSignature().setSourceContext(new EclipseSourceContext(compilationResult));
this.munger = munger;
}
protected int generateInfoAttributes(ClassFile classFile) {
List l;;
Shadow.Kind kind = getShadowKindForBody();
if (kind != null) {
l = makeEffectiveSignatureAttribute(munger.getSignature(), kind, true);
} else {
l = new ArrayList(0);
}
addDeclarationStartLineAttribute(l,classFile);
return classFile.generateMethodInfoAttribute(binding, l);
}
protected abstract Shadow.Kind getShadowKindForBody();
public ResolvedMember getSignature() {
if (munger==null) return null; // Can be null in an erroneous program I think
return munger.getSignature();
}
public char[] getDeclaredSelector() {
return declaredSelector;
}
}
|
73,334
|
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
|
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
|
resolved fixed
|
b133299
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:40:02Z
| 2004-09-06T17:00:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/InterTypeFieldDeclaration.java
|
/* *******************************************************************
* 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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.ast;
import java.lang.reflect.Modifier;
import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory;
import org.aspectj.ajdt.internal.compiler.lookup.EclipseTypeMunger;
import org.aspectj.weaver.*;
import org.eclipse.jdt.internal.compiler.ClassFile;
import org.eclipse.jdt.internal.compiler.CompilationResult;
import org.eclipse.jdt.internal.compiler.ast.*;
import org.eclipse.jdt.internal.compiler.codegen.CodeStream;
import org.eclipse.jdt.internal.compiler.lookup.*;
import org.eclipse.jdt.internal.compiler.parser.Parser;
/**
* An inter-type field declaration.
*
* returnType encodes the type of the field
* selector encodes the name
* statements is null until resolution when it is filled in from the initializer
*
* @author Jim Hugunin
*/
public class InterTypeFieldDeclaration extends InterTypeDeclaration {
public Expression initialization;
//public InterTypeFieldBinding interBinding;
public InterTypeFieldDeclaration(CompilationResult result, TypeReference onType) {
super(result, onType);
}
public void parseStatements(Parser parser, CompilationUnitDeclaration unit) {
//we don't have a body to parse
}
public void resolveOnType(ClassScope classScope) {
super.resolveOnType(classScope);
if (ignoreFurtherInvestigation) return;
if (Modifier.isStatic(declaredModifiers) && onTypeBinding.isInterface()) {
scope.problemReporter().signalError(sourceStart, sourceEnd,
"static inter-type field on interface not supported");
ignoreFurtherInvestigation = true;
}
}
public void resolve(ClassScope upperScope) {
if (munger == null) ignoreFurtherInvestigation = true;
if (ignoreFurtherInvestigation) return;
EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(upperScope);
ResolvedMember sig = munger.getSignature();
TypeX aspectType = EclipseFactory.fromBinding(upperScope.referenceContext.binding);
if (sig.getReturnType() == ResolvedTypeX.VOID ||
(sig.getReturnType().isArray() && (sig.getReturnType().getComponentType() == ResolvedTypeX.VOID)))
{
upperScope.problemReporter().signalError(sourceStart, sourceEnd,
"field type can not be void");
}
//
// System.err.println("sig: " + sig);
// System.err.println("field: " + world.makeFieldBinding(
// AjcMemberMaker.interFieldClassField(sig, aspectType)));
if (initialization != null && initialization instanceof ArrayInitializer) {
//System.err.println("got initializer: " + initialization);
ArrayAllocationExpression aae = new ArrayAllocationExpression();
aae.initializer = (ArrayInitializer)initialization;
ArrayBinding arrayType = (ArrayBinding)world.makeTypeBinding(sig.getReturnType());
aae.type = AstUtil.makeTypeReference(arrayType.leafComponentType());
aae.sourceStart = initialization.sourceStart;
aae.sourceEnd = initialization.sourceEnd;
aae.dimensions = new Expression[arrayType.dimensions];
initialization = aae;
}
if (initialization == null) {
this.statements = new Statement[] {
new ReturnStatement(null, 0, 0),
};
} else if (!onTypeBinding.isInterface()) {
MethodBinding writeMethod = world.makeMethodBinding(
AjcMemberMaker.interFieldSetDispatcher(sig,aspectType));
// For the body of an intertype field initalizer, generate a call to the inter field set dispatcher
// method as that casts the shadow of a field set join point.
if (Modifier.isStatic(declaredModifiers)) {
this.statements = new Statement[] {
new KnownMessageSend(writeMethod,
AstUtil.makeNameReference(writeMethod.declaringClass),
new Expression[] {initialization}),
};
} else {
this.statements = new Statement[] {
new KnownMessageSend(writeMethod,
AstUtil.makeNameReference(writeMethod.declaringClass),
new Expression[] {AstUtil.makeLocalVariableReference(arguments[0].binding),initialization}),
};
}
} else {
//XXX something is broken about this logic. Can we write to static interface fields?
MethodBinding writeMethod = world.makeMethodBinding(
AjcMemberMaker.interFieldInterfaceSetter(sig, sig.getDeclaringType().resolve(world.getWorld()), aspectType));
if (Modifier.isStatic(declaredModifiers)) {
this.statements = new Statement[] {
new KnownMessageSend(writeMethod,
AstUtil.makeNameReference(writeMethod.declaringClass),
new Expression[] {initialization}),
};
} else {
this.statements = new Statement[] {
new KnownMessageSend(writeMethod,
AstUtil.makeLocalVariableReference(arguments[0].binding),
new Expression[] {initialization}),
};
}
}
super.resolve(upperScope);
}
public void setInitialization(Expression initialization) {
this.initialization = initialization;
}
public EclipseTypeMunger build(ClassScope classScope) {
EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(classScope);
resolveOnType(classScope);
if (ignoreFurtherInvestigation) return null;
binding = classScope.referenceContext.binding.resolveTypesFor(binding);
if (ignoreFurtherInvestigation) return null;
if (!Modifier.isStatic(declaredModifiers)) {
super.binding.parameters = new TypeBinding[] {
onTypeBinding,
};
this.arguments = new Argument[] {
AstUtil.makeFinalArgument("ajc$this_".toCharArray(), onTypeBinding),
};
}
//System.err.println("type: " + binding.returnType + ", " + returnType);
ResolvedMember sig =
new ResolvedMember(Member.FIELD, EclipseFactory.fromBinding(onTypeBinding),
declaredModifiers, EclipseFactory.fromBinding(binding.returnType),
new String(declaredSelector), TypeX.NONE);
NewFieldTypeMunger myMunger = new NewFieldTypeMunger(sig, null);
setMunger(myMunger);
ResolvedTypeX aspectType = world.fromEclipse(classScope.referenceContext.binding);
ResolvedMember me =
myMunger.getInitMethod(aspectType);
this.selector = binding.selector = me.getName().toCharArray();
this.binding.returnType = TypeBinding.VoidBinding;
//??? all other pieces should already match
return new EclipseTypeMunger(world, myMunger, aspectType, this);
}
private AjAttribute makeAttribute() {
return new AjAttribute.TypeMunger(munger);
}
public void generateCode(ClassScope classScope, ClassFile classFile) {
if (ignoreFurtherInvestigation) return;
classFile.extraAttributes.add(new EclipseAttributeAdapter(makeAttribute()));
super.generateCode(classScope, classFile);
generateDispatchMethods(classScope, classFile);
// interBinding.reader.generateMethod(this, classScope, classFile);
// interBinding.writer.generateMethod(this, classScope, classFile);
}
private void generateDispatchMethods(ClassScope classScope, ClassFile classFile) {
EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(classScope);
ResolvedMember sig = munger.getSignature();
TypeX aspectType = EclipseFactory.fromBinding(classScope.referenceContext.binding);
generateDispatchMethod(world, sig, aspectType, classScope, classFile, true);
generateDispatchMethod(world, sig, aspectType, classScope, classFile, false);
}
private void generateDispatchMethod(
EclipseFactory world,
ResolvedMember sig,
TypeX aspectType,
ClassScope classScope,
ClassFile classFile,
boolean isGetter)
{
MethodBinding binding;
if (isGetter) {
binding = world.makeMethodBinding(AjcMemberMaker.interFieldGetDispatcher(sig, aspectType));
} else {
binding = world.makeMethodBinding(AjcMemberMaker.interFieldSetDispatcher(sig, aspectType));
}
classFile.generateMethodInfoHeader(binding);
int methodAttributeOffset = classFile.contentsOffset;
int attributeNumber = classFile.generateMethodInfoAttribute(binding,
makeEffectiveSignatureAttribute(sig, isGetter ? Shadow.FieldGet : Shadow.FieldSet, false));
int codeAttributeOffset = classFile.contentsOffset;
classFile.generateCodeAttributeHeader();
CodeStream codeStream = classFile.codeStream;
codeStream.reset(this, classFile);
FieldBinding classField = world.makeFieldBinding(
AjcMemberMaker.interFieldClassField(sig, aspectType));
codeStream.initializeMaxLocals(binding);
if (isGetter) {
if (onTypeBinding.isInterface()) {
TypeX declaringTX = sig.getDeclaringType();
ResolvedTypeX declaringRTX = world.getWorld().resolve(declaringTX,munger.getSourceLocation());
MethodBinding readMethod = world.makeMethodBinding(
AjcMemberMaker.interFieldInterfaceGetter(
sig, declaringRTX, aspectType));
generateInterfaceReadBody(binding, readMethod, codeStream);
} else {
generateClassReadBody(binding, classField, codeStream);
}
} else {
if (onTypeBinding.isInterface()) {
MethodBinding writeMethod = world.makeMethodBinding(
AjcMemberMaker.interFieldInterfaceSetter(
sig, world.getWorld().resolve(sig.getDeclaringType(),munger.getSourceLocation()), aspectType));
generateInterfaceWriteBody(binding, writeMethod, codeStream);
} else {
generateClassWriteBody(binding, classField, codeStream);
}
}
AstUtil.generateReturn(binding.returnType, codeStream);
classFile.completeCodeAttribute(codeAttributeOffset);
attributeNumber++;
classFile.completeMethodInfo(methodAttributeOffset, attributeNumber);
}
private void generateInterfaceReadBody(MethodBinding binding, MethodBinding readMethod, CodeStream codeStream) {
codeStream.aload_0();
codeStream.invokeinterface(readMethod);
}
private void generateInterfaceWriteBody(MethodBinding binding, MethodBinding writeMethod, CodeStream codeStream) {
codeStream.aload_0();
codeStream.load(writeMethod.parameters[0], 1);
codeStream.invokeinterface(writeMethod);
}
private void generateClassReadBody(MethodBinding binding, FieldBinding field, CodeStream codeStream) {
if (field.isStatic()) {
codeStream.getstatic(field);
} else {
codeStream.aload_0();
codeStream.getfield(field);
}
}
private void generateClassWriteBody(MethodBinding binding, FieldBinding field, CodeStream codeStream) {
if (field.isStatic()) {
codeStream.load(field.type, 0);
codeStream.putstatic(field);
} else {
codeStream.aload_0();
codeStream.load(field.type, 1);
codeStream.putfield(field);
}
}
protected Shadow.Kind getShadowKindForBody() {
return null;
}
}
|
73,334
|
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
|
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
|
resolved fixed
|
b133299
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:40:02Z
| 2004-09-06T17:00:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/InterTypeMethodDeclaration.java
|
/* *******************************************************************
* 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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.ast;
import java.lang.reflect.Modifier;
import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory;
import org.aspectj.ajdt.internal.compiler.lookup.EclipseTypeMunger;
import org.aspectj.weaver.AjAttribute;
import org.aspectj.weaver.AjcMemberMaker;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.NewMethodTypeMunger;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedTypeX;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.TypeX;
import org.eclipse.jdt.internal.compiler.ClassFile;
import org.eclipse.jdt.internal.compiler.CompilationResult;
import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration;
import org.eclipse.jdt.internal.compiler.ast.TypeReference;
import org.eclipse.jdt.internal.compiler.codegen.CodeStream;
import org.eclipse.jdt.internal.compiler.flow.FlowInfo;
import org.eclipse.jdt.internal.compiler.flow.InitializationFlowContext;
import org.eclipse.jdt.internal.compiler.lookup.ClassScope;
import org.eclipse.jdt.internal.compiler.lookup.MethodBinding;
import org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
import org.eclipse.jdt.internal.compiler.parser.Parser;
import org.eclipse.jdt.internal.compiler.problem.AbortCompilationUnit;
/**
* An inter-type method declaration.
*
* @author Jim Hugunin
*/
public class InterTypeMethodDeclaration extends InterTypeDeclaration {
public InterTypeMethodDeclaration(CompilationResult result, TypeReference onType) {
super(result, onType);
}
public void parseStatements(Parser parser, CompilationUnitDeclaration unit) {
if (ignoreFurtherInvestigation)
return;
if (!Modifier.isAbstract(declaredModifiers)) {
parser.parse(this, unit);
}
}
public void analyseCode(
ClassScope currentScope,
InitializationFlowContext flowContext,
FlowInfo flowInfo)
{
if (Modifier.isAbstract(declaredModifiers)) return;
super.analyseCode(currentScope, flowContext, flowInfo);
}
public void resolve(ClassScope upperScope) {
if (munger == null) ignoreFurtherInvestigation = true;
if (ignoreFurtherInvestigation) return;
if (!Modifier.isStatic(declaredModifiers)) {
this.arguments = AstUtil.insert(
AstUtil.makeFinalArgument("ajc$this_".toCharArray(), onTypeBinding),
this.arguments);
binding.parameters = AstUtil.insert(onTypeBinding, binding.parameters);
}
super.resolve(upperScope);
}
public void resolveStatements() {
if ((modifiers & AccSemicolonBody) != 0) {
if ((declaredModifiers & AccAbstract) == 0)
scope.problemReporter().methodNeedBody(this);
} else {
// the method HAS a body --> abstract native modifiers are forbiden
if (((declaredModifiers & AccAbstract) != 0))
scope.problemReporter().methodNeedingNoBody(this);
}
if (!Modifier.isAbstract(declaredModifiers)) super.resolveStatements();
if (Modifier.isStatic(declaredModifiers)) {
// Check the target for ITD is not an interface
if (onTypeBinding.isInterface()) {
scope.problemReporter().signalError(sourceStart, sourceEnd,
"methods in interfaces cannot be declared static");
}
}
}
public EclipseTypeMunger build(ClassScope classScope) {
EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(classScope);
resolveOnType(classScope);
if (ignoreFurtherInvestigation) return null;
binding = classScope.referenceContext.binding.resolveTypesFor(binding);
if (binding == null) {
// if binding is null, we failed to find a type used in the method params, this error
// has already been reported.
this.ignoreFurtherInvestigation = true;
//return null;
throw new AbortCompilationUnit(compilationResult,null);
}
ResolvedMember sig = new ResolvedMember(Member.METHOD, EclipseFactory.fromBinding(onTypeBinding),
declaredModifiers, EclipseFactory.fromBinding(binding.returnType), new String(declaredSelector),
EclipseFactory.fromBindings(binding.parameters),
world.fromEclipse(binding.thrownExceptions));
NewMethodTypeMunger myMunger = new NewMethodTypeMunger(sig, null);
setMunger(myMunger);
ResolvedTypeX aspectType = world.fromEclipse(classScope.referenceContext.binding);
ResolvedMember me =
myMunger.getDispatchMethod(aspectType);
this.selector = binding.selector = me.getName().toCharArray();
return new EclipseTypeMunger(world, myMunger, aspectType, this);
}
private AjAttribute makeAttribute() {
return new AjAttribute.TypeMunger(munger);
}
public void generateCode(ClassScope classScope, ClassFile classFile) {
if (ignoreFurtherInvestigation) {
//System.err.println("no code for " + this);
return;
}
classFile.extraAttributes.add(new EclipseAttributeAdapter(makeAttribute()));
if (!Modifier.isAbstract(declaredModifiers)) {
super.generateCode(classScope, classFile);
}
generateDispatchMethod(classScope, classFile);
}
public void generateDispatchMethod(ClassScope classScope, ClassFile classFile) {
EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(classScope);
TypeX aspectType = EclipseFactory.fromBinding(classScope.referenceContext.binding);
ResolvedMember signature = munger.getSignature();
ResolvedMember dispatchMember =
AjcMemberMaker.interMethodDispatcher(signature, aspectType);
MethodBinding dispatchBinding = world.makeMethodBinding(dispatchMember);
MethodBinding introducedMethod =
world.makeMethodBinding(AjcMemberMaker.interMethod(signature, aspectType, onTypeBinding.isInterface()));
classFile.generateMethodInfoHeader(dispatchBinding);
int methodAttributeOffset = classFile.contentsOffset;
int attributeNumber = classFile.generateMethodInfoAttribute(dispatchBinding,
makeEffectiveSignatureAttribute(signature, Shadow.MethodCall, false));
int codeAttributeOffset = classFile.contentsOffset;
classFile.generateCodeAttributeHeader();
CodeStream codeStream = classFile.codeStream;
codeStream.reset(this, classFile);
codeStream.initializeMaxLocals(dispatchBinding);
MethodBinding methodBinding = introducedMethod;
TypeBinding[] parameters = methodBinding.parameters;
int length = parameters.length;
int resolvedPosition;
if (methodBinding.isStatic())
resolvedPosition = 0;
else {
codeStream.aload_0();
resolvedPosition = 1;
}
for (int i = 0; i < length; i++) {
codeStream.load(parameters[i], resolvedPosition);
if ((parameters[i] == DoubleBinding) || (parameters[i] == LongBinding))
resolvedPosition += 2;
else
resolvedPosition++;
}
// TypeBinding type;
if (methodBinding.isStatic())
codeStream.invokestatic(methodBinding);
else {
if (methodBinding.declaringClass.isInterface()){
codeStream.invokeinterface(methodBinding);
} else {
codeStream.invokevirtual(methodBinding);
}
}
AstUtil.generateReturn(dispatchBinding.returnType, codeStream);
classFile.completeCodeAttribute(codeAttributeOffset);
attributeNumber++;
classFile.completeMethodInfo(methodAttributeOffset, attributeNumber);
}
protected Shadow.Kind getShadowKindForBody() {
return Shadow.MethodExecution;
}
}
|
73,334
|
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
|
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
|
resolved fixed
|
b133299
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:40:02Z
| 2004-09-06T17:00:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/KnownFieldReference.java
|
/* *******************************************************************
* 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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.ast;
import org.eclipse.jdt.internal.compiler.ast.QualifiedNameReference;
import org.eclipse.jdt.internal.compiler.impl.Constant;
import org.eclipse.jdt.internal.compiler.lookup.BlockScope;
import org.eclipse.jdt.internal.compiler.lookup.FieldBinding;
import org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
public class KnownFieldReference extends QualifiedNameReference {
//XXX handle source locations
public KnownFieldReference(FieldBinding binding, long pos) {
super(new char[][] {binding.name},new long[1], 0, 0);
this.binding = this.codegenBinding = binding;
this.constant = Constant.NotAConstant;
this.receiverType = this.actualReceiverType =
binding.declaringClass;
this.bits = FIELD;
//this.receiver = AstUtil.makeTypeReference(binding.declaringClass);
}
public TypeBinding resolveType(BlockScope scope) {
return fieldBinding().type;
}
}
|
73,334
|
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
|
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
|
resolved fixed
|
b133299
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:40:02Z
| 2004-09-06T17:00:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/KnownMessageSend.java
|
/* *******************************************************************
* 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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.ast;
import org.eclipse.jdt.internal.compiler.ast.Expression;
import org.eclipse.jdt.internal.compiler.ast.MessageSend;
import org.eclipse.jdt.internal.compiler.codegen.CodeStream;
import org.eclipse.jdt.internal.compiler.lookup.BlockScope;
import org.eclipse.jdt.internal.compiler.lookup.MethodBinding;
import org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
public class KnownMessageSend extends MessageSend {
public KnownMessageSend(MethodBinding binding, Expression receiver, Expression[] arguments) {
super();
this.binding = this.codegenBinding = binding;
this.arguments = arguments;
this.receiver = receiver;
this.selector = binding.selector;
constant = NotAConstant;
}
public void manageSyntheticAccessIfNecessary(BlockScope currentScope) {
return;
}
protected void resolveMethodBinding(
BlockScope scope,
TypeBinding[] argumentTypes) {
// we've already resolved this
}
public String toStringExpression() {
return "KnownMessageSend";
}
public void generateCode(
BlockScope currentScope,
CodeStream codeStream,
boolean valueRequired) {
//System.out.println("about to generate: " +this + " args: " + Arrays.asList(arguments));
super.generateCode(currentScope, codeStream, valueRequired);
}
}
|
73,334
|
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
|
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
|
resolved fixed
|
b133299
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:40:02Z
| 2004-09-06T17:00:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/MakeDeclsPublicVisitor.java
|
/* *******************************************************************
* 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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.ast;
import org.eclipse.jdt.internal.compiler.ASTVisitor;
//import org.eclipse.jdt.internal.compiler.ast.AnonymousLocalTypeDeclaration;
import org.eclipse.jdt.internal.compiler.ast.ConstructorDeclaration;
import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration;
import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration;
//import org.eclipse.jdt.internal.compiler.ast.LocalTypeDeclaration;
import org.eclipse.jdt.internal.compiler.ast.MethodDeclaration;
import org.eclipse.jdt.internal.compiler.lookup.BlockScope;
import org.eclipse.jdt.internal.compiler.lookup.ClassScope;
import org.eclipse.jdt.internal.compiler.lookup.MethodScope;
/**
* Takes a method that already has the three extra parameters
* thisJoinPointStaticPart, thisJoinPoint and thisEnclosingJoinPointStaticPart
*/
public class MakeDeclsPublicVisitor extends ASTVisitor {
public void endVisit(ConstructorDeclaration decl, ClassScope scope) {
decl.binding.modifiers = AstUtil.makePublic(decl.binding.modifiers);
}
public void endVisit(FieldDeclaration decl, MethodScope scope) {
decl.binding.modifiers = AstUtil.makePublic(decl.binding.modifiers);
}
public void endVisit(MethodDeclaration decl, ClassScope scope) {
decl.binding.modifiers = AstUtil.makePublic(decl.binding.modifiers);
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.compiler.ASTVisitor#endVisit(org.eclipse.jdt.internal.compiler.ast.TypeDeclaration, org.eclipse.jdt.internal.compiler.lookup.BlockScope)
*/
public void endVisit(
TypeDeclaration localTypeDeclaration,
BlockScope scope) {
localTypeDeclaration.binding.modifiers = AstUtil.makePublic(localTypeDeclaration.binding.modifiers);
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.compiler.ASTVisitor#endVisit(org.eclipse.jdt.internal.compiler.ast.TypeDeclaration, org.eclipse.jdt.internal.compiler.lookup.ClassScope)
*/
public void endVisit(
TypeDeclaration memberTypeDeclaration,
ClassScope scope) {
memberTypeDeclaration.binding.modifiers = AstUtil.makePublic(memberTypeDeclaration.binding.modifiers);
}
}
|
73,334
|
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
|
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
|
resolved fixed
|
b133299
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:40:02Z
| 2004-09-06T17:00:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/PointcutDeclaration.java
|
/* *******************************************************************
* 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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.ast;
import java.lang.reflect.Modifier;
import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory;
import org.aspectj.ajdt.internal.core.builder.EclipseSourceContext;
import org.aspectj.weaver.AjAttribute;
import org.aspectj.weaver.ResolvedPointcutDefinition;
//import org.aspectj.weaver.ResolvedTypeX;
//import org.aspectj.weaver.TypeX;
import org.aspectj.weaver.patterns.Pointcut;
import org.eclipse.jdt.internal.compiler.ClassFile;
import org.eclipse.jdt.internal.compiler.CompilationResult;
import org.eclipse.jdt.internal.compiler.ast.Argument;
import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration;
import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration;
import org.eclipse.jdt.internal.compiler.ast.TypeReference;
import org.eclipse.jdt.internal.compiler.lookup.ClassScope;
import org.eclipse.jdt.internal.compiler.parser.Parser;
import org.eclipse.jdt.core.compiler.CharOperation;
/**
* pointcut [declaredModifiers] [declaredName]([arguments]): [pointcutDesignator];
*
* <p>No method will actually be generated for this node but an attribute
* will be added to the enclosing class.</p>
*
* @author Jim Hugunin
*/
public class PointcutDeclaration extends AjMethodDeclaration {
public static final char[] mangledPrefix = "ajc$pointcut$".toCharArray();
public PointcutDesignator pointcutDesignator;
private int declaredModifiers;
private String declaredName;
private ResolvedPointcutDefinition resolvedPointcutDeclaration = null;
public PointcutDeclaration(CompilationResult compilationResult) {
super(compilationResult);
this.returnType = TypeReference.baseTypeReference(T_void, 0);
}
private Pointcut getPointcut() {
if (pointcutDesignator == null) {
return Pointcut.makeMatchesNothing(Pointcut.RESOLVED);
} else {
return pointcutDesignator.getPointcut();
}
}
public void parseStatements(
Parser parser,
CompilationUnitDeclaration unit) {
// do nothing
}
public void postParse(TypeDeclaration typeDec) {
if (arguments == null) arguments = new Argument[0];
this.declaredModifiers = modifiers;
this.declaredName = new String(selector);
selector = CharOperation.concat(mangledPrefix, '$', selector, '$',
Integer.toHexString(sourceStart).toCharArray());
if (Modifier.isAbstract(this.declaredModifiers)) {
if (!(typeDec instanceof AspectDeclaration)) {
typeDec.scope.problemReporter().signalError(sourceStart, sourceEnd,
"The abstract pointcut " + new String(declaredName) +
" can only be defined in an aspect");
ignoreFurtherInvestigation = true;
return;
} else if (!Modifier.isAbstract(typeDec.modifiers)) {
typeDec.scope.problemReporter().signalError(sourceStart, sourceEnd,
"The abstract pointcut " + new String(declaredName) +
" can only be defined in an abstract aspect");
ignoreFurtherInvestigation = true;
return;
}
}
if (pointcutDesignator != null) {
pointcutDesignator.postParse(typeDec, this);
}
}
public void resolve(ClassScope upperScope) {
// this method should do nothing, use the entry point below...
}
public void resolvePointcut(ClassScope upperScope) {
super.resolve(upperScope);
}
public void resolveStatements() {
if (isAbstract()) {
this.modifiers |= AccSemicolonBody;
}
if (binding == null || ignoreFurtherInvestigation) return;
if (Modifier.isAbstract(this.declaredModifiers)&& (pointcutDesignator != null)) {
scope.problemReporter().signalError(sourceStart, sourceEnd, "abstract pointcut can't have body");
ignoreFurtherInvestigation = true;
return;
}
if (pointcutDesignator != null) {
pointcutDesignator.finishResolveTypes(this, this.binding, arguments.length,
scope.enclosingSourceType());
}
//System.out.println("resolved: " + getPointcut() + ", " + getPointcut().state);
makeResolvedPointcutDefinition();
resolvedPointcutDeclaration.setPointcut(getPointcut());
super.resolveStatements();
}
public ResolvedPointcutDefinition makeResolvedPointcutDefinition() {
if (resolvedPointcutDeclaration != null) return resolvedPointcutDeclaration;
//System.out.println("pc: " + getPointcut() + ", " + getPointcut().state);
resolvedPointcutDeclaration = new ResolvedPointcutDefinition(
EclipseFactory.fromBinding(this.binding.declaringClass),
declaredModifiers,
declaredName,
EclipseFactory.fromBindings(this.binding.parameters),
getPointcut()); //??? might want to use null
resolvedPointcutDeclaration.setPosition(sourceStart, sourceEnd);
resolvedPointcutDeclaration.setSourceContext(new EclipseSourceContext(compilationResult));
return resolvedPointcutDeclaration;
}
public AjAttribute makeAttribute() {
return new AjAttribute.PointcutDeclarationAttribute(makeResolvedPointcutDefinition());
}
/**
* A pointcut declaration exists in a classfile only as an attibute on the
* class. Unlike advice and inter-type declarations, it has no corresponding
* method.
*/
public void generateCode(ClassScope classScope, ClassFile classFile) {
if (ignoreFurtherInvestigation) return ;
classFile.extraAttributes.add(new EclipseAttributeAdapter(makeAttribute()));
return;
}
public StringBuffer printReturnType(int indent, StringBuffer output) {
return output.append("pointcut");
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration#printBody(int, java.lang.StringBuffer)
*/
public StringBuffer printBody(int indent, StringBuffer output) {
output.append(": ");
output.append(getPointcut());
output.append(";");
return output;
}
}
|
73,334
|
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
|
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
|
resolved fixed
|
b133299
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:40:02Z
| 2004-09-06T17:00:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/PointcutDesignator.java
|
/* *******************************************************************
* 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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.ast;
import org.aspectj.ajdt.internal.compiler.lookup.EclipseScope;
import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory;
import org.aspectj.weaver.TypeX;
import org.aspectj.weaver.patterns.FormalBinding;
import org.aspectj.weaver.patterns.Pointcut;
import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration;
import org.eclipse.jdt.internal.compiler.ast.Argument;
import org.eclipse.jdt.internal.compiler.ast.ASTNode;
import org.eclipse.jdt.internal.compiler.ast.MethodDeclaration;
import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration;
import org.eclipse.jdt.internal.compiler.lookup.MethodBinding;
import org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding;
import org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
import org.eclipse.jdt.internal.compiler.parser.Parser;
public class PointcutDesignator extends ASTNode {
private Pointcut pointcut;
private PseudoTokens tokens; //XXX redundant
private boolean isError = false;
public PointcutDesignator(Parser parser, PseudoTokens tokens) {
super();
sourceStart = tokens.sourceStart;
sourceEnd = tokens.sourceEnd;
this.tokens = tokens;
Pointcut pc = tokens.parsePointcut(parser);
if (pc.toString().equals("")) { //??? is this a good signal
isError = true;
}
pointcut = pc;
}
public void postParse(TypeDeclaration typeDec, MethodDeclaration enclosingDec) {
tokens.postParse(typeDec, enclosingDec);
}
public boolean finishResolveTypes(final AbstractMethodDeclaration dec, MethodBinding method, final int baseArgumentCount, SourceTypeBinding sourceTypeBinding) {
//System.err.println("resolving: " + this);
//Thread.currentThread().dumpStack();
//XXX why do we need this test
// AMC added concrete too. Needed because declare declarations concretize their
// shadow mungers early.
if (pointcut.state == Pointcut.RESOLVED ||
pointcut.state == Pointcut.CONCRETE) return true;
TypeBinding[] parameters = method.parameters;
Argument[] arguments = dec.arguments;
FormalBinding[] bindings = new FormalBinding[baseArgumentCount];
for (int i = 0, len = baseArgumentCount; i < len; i++) {
Argument arg = arguments[i];
String name = new String(arg.name);
TypeX type = EclipseFactory.fromBinding(parameters[i]);
bindings[i] = new FormalBinding(type, name, i, arg.sourceStart, arg.sourceEnd, "unknown");
}
EclipseScope scope = new EclipseScope(bindings, dec.scope);
pointcut = pointcut.resolve(scope);
return true;
}
public Pointcut getPointcut() {
return pointcut;
}
public boolean isError() {
return isError;
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.compiler.ast.ASTNode#print(int, java.lang.StringBuffer)
*/
public StringBuffer print(int indent, StringBuffer output) {
if (pointcut == null) return output.append("<pcd>");
return output.append(pointcut.toString());
}
}
|
73,334
|
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
|
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
|
resolved fixed
|
b133299
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:40:02Z
| 2004-09-06T17:00:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/Proceed.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* 2004 contributors
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* IBM ongoing maintenance
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.ast;
import org.aspectj.weaver.AdviceKind;
import org.eclipse.jdt.internal.compiler.ast.Expression;
import org.eclipse.jdt.internal.compiler.ast.MessageSend;
import org.eclipse.jdt.internal.compiler.impl.ReferenceContext;
import org.eclipse.jdt.internal.compiler.lookup.BlockScope;
import org.eclipse.jdt.internal.compiler.lookup.ClassScope;
import org.eclipse.jdt.internal.compiler.lookup.MethodScope;
import org.eclipse.jdt.internal.compiler.lookup.Scope;
import org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
/**
* Used to represent any method call to a method named <code>proceed</code>. During
* <code>resolvedType</code> it will be determined if this is actually in the body
* of an <code>around</code> advice and has no receiver (must be a bare proceed call,
* see pr 53981), and if not this will be treated like any other
* MessageSend.
*
* @author Jim Hugunin
*/
public class Proceed extends MessageSend {
public boolean inInner = false;
public Proceed(MessageSend parent) {
super();
this.receiver = parent.receiver;
this.selector = parent.selector;
this.arguments = parent.arguments;
this.binding = parent.binding;
this.codegenBinding = parent.codegenBinding;
this.nameSourcePosition = parent.nameSourcePosition;
this.receiverType = parent.receiverType;
this.qualifyingType = parent.qualifyingType;
this.sourceStart = parent.sourceStart;
this.sourceEnd = parent.sourceEnd;
}
public TypeBinding resolveType(BlockScope scope) {
// find out if I'm really in an around body or not
//??? this could in theory be done by the parser, but that appears to be hard
AdviceDeclaration aroundDecl = findEnclosingAround(scope);
if (aroundDecl == null) {
return super.resolveType(scope);
}
constant = NotAConstant;
binding = codegenBinding = aroundDecl.proceedMethodBinding;
this.qualifyingType = this.receiverType = binding.declaringClass;
int baseArgCount = 0;
if (arguments != null) {
baseArgCount = arguments.length;
Expression[] newArguments = new Expression[baseArgCount + 1];
System.arraycopy(arguments, 0, newArguments, 0, baseArgCount);
arguments = newArguments;
} else {
arguments = new Expression[1];
}
arguments[baseArgCount] = AstUtil.makeLocalVariableReference(aroundDecl.extraArgument.binding);
int declaredParameterCount = aroundDecl.getDeclaredParameterCount();
if (baseArgCount < declaredParameterCount) {
scope.problemReporter().signalError(this.sourceStart, this.sourceEnd,
"too few arguments to proceed, expected " + declaredParameterCount);
aroundDecl.ignoreFurtherInvestigation = true;
return null; //binding.returnType;
}
if (baseArgCount > declaredParameterCount) {
scope.problemReporter().signalError(this.sourceStart, this.sourceEnd,
"too many arguments to proceed, expected " + declaredParameterCount);
aroundDecl.ignoreFurtherInvestigation = true;
return null; //binding.returnType;
}
for (int i=0, len=arguments.length; i < len; i++) {
Expression arg = arguments[i];
TypeBinding argType = arg.resolveType(scope);
if (argType != null) {
TypeBinding paramType = binding.parameters[i];
if (!argType.isCompatibleWith(paramType)) {
scope.problemReporter().typeMismatchError(argType, paramType, arg);
}
arg.implicitWidening(binding.parameters[i], argType);
}
}
return binding.returnType;
}
private AdviceDeclaration findEnclosingAround(Scope scope) {
if (scope == null) return null;
if (scope instanceof MethodScope) {
MethodScope methodScope = (MethodScope)scope;
ReferenceContext context = methodScope.referenceContext;
if (context instanceof AdviceDeclaration) {
AdviceDeclaration adviceDecl = (AdviceDeclaration)context;
if (adviceDecl.kind == AdviceKind.Around) {
// pr 53981 only match "bare" calls to proceed
if((receiver != null) && (!receiver.isThis())) { return null; }
adviceDecl.proceedCalls.add(this);
return adviceDecl;
} else {
return null;
}
}
} else if (scope instanceof ClassScope) {
inInner = true;
}
return findEnclosingAround(scope.parent);
}
}
|
73,334
|
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
|
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
|
resolved fixed
|
b133299
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:40:02Z
| 2004-09-06T17:00:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/ProceedVisitor.java
|
/* *******************************************************************
* 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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.ast;
import org.aspectj.weaver.Advice;
import org.eclipse.jdt.internal.compiler.ASTVisitor;
import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration;
import org.eclipse.jdt.internal.compiler.ast.Expression;
import org.eclipse.jdt.internal.compiler.ast.MessageSend;
import org.eclipse.jdt.internal.compiler.ast.NameReference;
import org.eclipse.jdt.internal.compiler.ast.SingleNameReference;
import org.eclipse.jdt.internal.compiler.lookup.Binding;
import org.eclipse.jdt.internal.compiler.lookup.BlockScope;
import org.eclipse.jdt.internal.compiler.lookup.ClassScope;
import org.eclipse.jdt.internal.compiler.lookup.LocalVariableBinding;
import org.eclipse.jdt.internal.compiler.lookup.MethodBinding;
import org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding;
import org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
/**
* Takes a method that already has the three extra parameters
* thisJoinPointStaticPart, thisJoinPoint and thisEnclosingJoinPointStaticPart
*/
public class ProceedVisitor extends ASTVisitor {
boolean needsDynamic = false;
boolean needsStatic = false;
boolean needsStaticEnclosing = false;
boolean hasEffectivelyStaticRef = false;
LocalVariableBinding thisJoinPointDec;
LocalVariableBinding thisJoinPointStaticPartDec;
LocalVariableBinding thisEnclosingJoinPointStaticPartDec;
LocalVariableBinding thisJoinPointDecLocal;
LocalVariableBinding thisJoinPointStaticPartDecLocal;
LocalVariableBinding thisEnclosingJoinPointStaticPartDecLocal;
boolean replaceEffectivelyStaticRefs = false;
AbstractMethodDeclaration method;
ProceedVisitor(AbstractMethodDeclaration method) {
this.method = method;
int index = method.arguments.length - 3;
thisJoinPointStaticPartDecLocal = method.scope.locals[index];
thisJoinPointStaticPartDec = method.arguments[index++].binding;
thisJoinPointDecLocal = method.scope.locals[index];
thisJoinPointDec = method.arguments[index++].binding;
thisEnclosingJoinPointStaticPartDecLocal = method.scope.locals[index];
thisEnclosingJoinPointStaticPartDec = method.arguments[index++].binding;
}
public void computeJoinPointParams() {
// walk my body to see what is needed
method.traverse(this, (ClassScope) null);
//??? add support for option to disable this optimization
//System.err.println("check: "+ hasEffectivelyStaticRef + ", " + needsDynamic);
if (hasEffectivelyStaticRef && !needsDynamic) {
// replace effectively static refs with thisJoinPointStaticPart
replaceEffectivelyStaticRefs = true;
needsStatic = true;
method.traverse(this, (ClassScope) null);
}
}
boolean isRef(NameReference ref, Binding binding) {
return ref.binding == binding;
}
boolean isRef(Expression expr, Binding binding) {
//System.err.println("isRef: " + expr + ", " + binding);
return expr != null
&& expr instanceof NameReference
&& isRef((NameReference) expr, binding);
}
public void endVisit(SingleNameReference ref, BlockScope scope) {
if (isRef(ref, thisJoinPointDec))
needsDynamic = true;
else if (isRef(ref, thisJoinPointStaticPartDec))
needsStatic = true;
else if (isRef(ref, thisEnclosingJoinPointStaticPartDec))
needsStaticEnclosing = true;
}
// public void checkAndFix(ASTObject body) {
// this.process(body);
// if (needsFakeStatic && !needsDynamic) {
// if (!this.getCompiler().getOptions().noMetaJoinPointOptimization) {
// makeFakeStatics = true;
// needsStatic = true;
// this.process(body);
// } else {
// needsDynamic = true;
// }
// }
// }
boolean canTreatAsStatic(String id) {
return id.equals("toString")
|| id.equals("toShortString")
|| id.equals("toLongString")
|| id.equals("getKind")
|| id.equals("getSignature")
|| id.equals("getSourceLocation")
|| id.equals("getStaticPart");
}
// boolean canTreatAsStatic(VarExpr varExpr) {
// ASTObject parent = varExpr.getParent();
// if (parent instanceof CallExpr) {
// Method calledMethod = ((CallExpr)parent).getMethod();
// return canTreatAsStatic(calledMethod);
//
// //??? should add a case here to catch
// //??? tjp.getEnclosingExecutionJoinPoint().STATIC_METHOD()
// } else if (parent instanceof BinopExpr) {
// BinopExpr binop = (BinopExpr)parent;
// if (binop.getType().isEquivalent(this.getTypeManager().getStringType())) {
// return true;
// } else {
// return false;
// }
// } else {
// return false;
// }
// }
boolean inBlockThatCantRun = false;
public boolean visit(MessageSend call, BlockScope scope) {
Expression receiver = call.receiver;
if (isRef(receiver, thisJoinPointDec)) {
if (canTreatAsStatic(new String(call.selector))) {
if (replaceEffectivelyStaticRefs) {
replaceEffectivelyStaticRef(call);
} else {
//System.err.println("has static reg");
hasEffectivelyStaticRef = true;
if (call.arguments != null) {
int argumentsLength = call.arguments.length;
for (int i = 0; i < argumentsLength; i++)
call.arguments[i].traverse(this, scope);
}
return false;
}
}
}
return super.visit(call, scope);
}
private void replaceEffectivelyStaticRef(MessageSend call) {
//System.err.println("replace static ref");
NameReference receiver = (NameReference) call.receiver;
receiver.binding = thisJoinPointStaticPartDecLocal; //thisJoinPointStaticPartDec;
receiver.codegenBinding = thisJoinPointStaticPartDecLocal;
call.binding.declaringClass =
(ReferenceBinding) thisJoinPointStaticPartDec.type;
}
public int removeUnusedExtraArguments() {
int extraArgumentFlags = 0;
this.computeJoinPointParams();
MethodBinding binding = method.binding;
int index = binding.parameters.length - 3;
if (needsStaticEnclosing) {
extraArgumentFlags |= Advice.ThisEnclosingJoinPointStaticPart;
} else {
removeParameter(index+2);
}
if (needsDynamic) {
extraArgumentFlags |= Advice.ThisJoinPoint;
} else {
removeParameter(index+1);
}
if (needsStatic) {
extraArgumentFlags |= Advice.ThisJoinPointStaticPart;
} else {
removeParameter(index+0);
}
return extraArgumentFlags;
}
private void removeParameter(int indexToRemove) {
// TypeBinding[] parameters = method.binding.parameters;
method.scope.locals = removeLocalBinding(indexToRemove, method.scope.locals);
method.binding.parameters = removeParameter(indexToRemove, method.binding.parameters);
}
private static TypeBinding[] removeParameter(int index, TypeBinding[] bindings) {
int len = bindings.length;
TypeBinding[] ret = new TypeBinding[len-1];
System.arraycopy(bindings, 0, ret, 0, index);
System.arraycopy(bindings, index+1, ret, index, len-index-1);
return ret;
}
private static LocalVariableBinding[] removeLocalBinding(int index, LocalVariableBinding[] bindings) {
int len = bindings.length;
//??? for performance we should do this in-place
LocalVariableBinding[] ret = new LocalVariableBinding[len-1];
System.arraycopy(bindings, 0, ret, 0, index);
System.arraycopy(bindings, index+1, ret, index, len-index-1);
return ret;
}
}
|
73,334
|
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
|
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
|
resolved fixed
|
b133299
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:40:02Z
| 2004-09-06T17:00:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/PseudoToken.java
|
/* *******************************************************************
* 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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.ast;
import org.aspectj.weaver.patterns.IToken;
import org.aspectj.weaver.patterns.Pointcut;
import org.eclipse.jdt.internal.compiler.ast.ASTNode;
import org.eclipse.jdt.internal.compiler.ast.MethodDeclaration;
import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration;
import org.eclipse.jdt.internal.compiler.parser.Parser;
/**
*/
public class PseudoToken extends ASTNode implements IToken {
public String value;
public boolean isIdentifier;
public String literalKind = null;
public Parser parser;
/**
* Constructor for PointcutDesignatorToken.
*/
public PseudoToken(Parser parser, String value, boolean isIdentifier) {
this.parser = parser;
this.value = value;
this.isIdentifier = isIdentifier;
}
public String toString(int tab) {
return "<" + value + "@" + getStart() + ":" + getEnd() + ">";
}
/**
* @see org.aspectj.weaver.patterns.IToken#getString()
*/
public String getString() {
return value;
}
/**
* @see org.aspectj.weaver.patterns.IToken#isIdentifier()
*/
public boolean isIdentifier() {
return isIdentifier;
}
/**
* returns null if this isn't a literal
*/
public String getLiteralKind() {
return literalKind;
}
public Pointcut maybeGetParsedPointcut() {
return null;
}
public int getStart() {
return sourceStart;
}
/**
*
*/
public int getEnd() {
return sourceEnd;
}
public String getFileName() {
return "unknown";
}
public void postParse(TypeDeclaration typeDec, MethodDeclaration enclosingDec) {
// nothing to do typically
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.compiler.ast.ASTNode#print(int, java.lang.StringBuffer)
*/
public StringBuffer print(int indent, StringBuffer output) {
output.append("PseudoToken<" + getString() + ">");
return output;
}
}
|
73,334
|
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
|
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
|
resolved fixed
|
b133299
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:40:02Z
| 2004-09-06T17:00:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/PseudoTokens.java
|
/* *******************************************************************
* 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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.ast;
import org.aspectj.weaver.IHasPosition;
import org.aspectj.weaver.ISourceContext;
import org.aspectj.weaver.patterns.BasicTokenSource;
import org.aspectj.weaver.patterns.Declare;
import org.aspectj.weaver.patterns.IToken;
import org.aspectj.weaver.patterns.ParserException;
import org.aspectj.weaver.patterns.PatternParser;
import org.aspectj.weaver.patterns.PerClause;
import org.aspectj.weaver.patterns.PerSingleton;
import org.aspectj.weaver.patterns.Pointcut;
import org.aspectj.weaver.patterns.TypePattern;
import org.eclipse.jdt.internal.compiler.ast.ASTNode;
import org.eclipse.jdt.internal.compiler.ast.MethodDeclaration;
import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration;
import org.eclipse.jdt.internal.compiler.parser.Parser;
import org.eclipse.jdt.internal.compiler.parser.TerminalTokens;
public class PseudoTokens extends ASTNode {
BasicTokenSource tokenSource;
PseudoToken[] tokens; //XXX this is redundant with the field above
String endToken;
public PseudoTokens(PseudoToken[] tokens, ISourceContext sourceContext) {
super();
this.tokens = tokens;
this.tokenSource = new BasicTokenSource(tokens, sourceContext);
endToken = tokens[tokens.length-1].getString();
sourceStart = tokens[0].sourceStart;
sourceEnd = tokens[tokens.length-2].sourceEnd;
}
public Pointcut parsePointcut(Parser parser) {
PatternParser patternParser = new PatternParser(tokenSource);
try {
Pointcut ret = patternParser.parsePointcut();
checkEof(parser);
return ret;
} catch (ParserException pe) {
reportError(parser, pe);
return Pointcut.makeMatchesNothing(Pointcut.SYMBOLIC);
}
}
private void checkEof(Parser parser) {
IToken last = tokenSource.next();
if (tokenSource.next() != IToken.EOF) {
parser.problemReporter().parseError(last.getStart(), last.getEnd(),
TerminalTokens.TokenNameIdentifier,
last.getString().toCharArray(),
last.getString(),
new String[] {endToken});
}
}
private void reportError(Parser parser, ParserException pe) {
IHasPosition tok = pe.getLocation();
int start, end;
if (tok == IToken.EOF) {
start = sourceEnd+1;
end = sourceEnd+1;
} else {
start = tok.getStart();
end = tok.getEnd();
}
String found = "<unknown>";
if (tok instanceof IToken) {
found = ((IToken)tok).getString();
}
parser.problemReporter().parseError(start, end,
TerminalTokens.TokenNameIdentifier,
found.toCharArray(),
found,
new String[] {pe.getMessage()});
}
public TypePattern maybeParseDominatesPattern(Parser parser) {
PatternParser patternParser = new PatternParser(tokenSource);
try {
if (patternParser.maybeEatIdentifier("dominates")) {
// there is no eof check here
return patternParser.parseTypePattern();
} else {
return null;
}
} catch (ParserException pe) {
reportError(parser, pe);
return null;
}
}
public PerClause parsePerClause(Parser parser) {
PatternParser patternParser = new PatternParser(tokenSource);
try {
PerClause ret = patternParser.maybeParsePerClause();
checkEof(parser);
if (ret == null) return new PerSingleton();
else return ret;
} catch (ParserException pe) {
reportError(parser, pe);
return new PerSingleton();
}
}
// public TypePattern parseTypePattern(Parser parser) {
// }
//
public Declare parseDeclare(Parser parser) {
PatternParser patternParser = new PatternParser(tokenSource);
try {
Declare ret = patternParser.parseDeclare();
checkEof(parser);
return ret;
} catch (ParserException pe) {
reportError(parser, pe);
return null;
}
}
public void postParse(TypeDeclaration typeDec, MethodDeclaration enclosingDec) {
for (int i=0, len=tokens.length; i < len; i++) {
tokens[i].postParse(typeDec, enclosingDec);
}
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.compiler.ast.ASTNode#print(int, java.lang.StringBuffer)
*/
public StringBuffer print(int indent, StringBuffer output) {
output.append(tokenSource.toString());
return output;
}
}
|
73,334
|
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
|
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
|
resolved fixed
|
b133299
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:40:02Z
| 2004-09-06T17:00:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/SuperFixerVisitor.java
|
/* *******************************************************************
* 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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.ast;
import java.util.HashSet;
import java.util.Set;
import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory;
import org.aspectj.ajdt.internal.compiler.lookup.InterTypeMethodBinding;
import org.aspectj.weaver.NameMangler;
import org.aspectj.weaver.ResolvedMember;
import org.eclipse.jdt.internal.compiler.ASTVisitor;
import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration;
import org.eclipse.jdt.internal.compiler.ast.ASTNode;
import org.eclipse.jdt.internal.compiler.ast.MessageSend;
import org.eclipse.jdt.internal.compiler.ast.ThisReference;
import org.eclipse.jdt.internal.compiler.lookup.BlockScope;
import org.eclipse.jdt.internal.compiler.lookup.MethodBinding;
import org.eclipse.jdt.internal.compiler.lookup.ProblemMethodBinding;
import org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding;
/**
* Takes a method that already has the three extra parameters
* thisJoinPointStaticPart, thisJoinPoint and thisEnclosingJoinPointStaticPart
*/
public class SuperFixerVisitor extends ASTVisitor {
Set superMethodsCalled = new HashSet();
AbstractMethodDeclaration method;
ReferenceBinding targetClass;
SuperFixerVisitor(AbstractMethodDeclaration method, ReferenceBinding targetClass) {
this.method = method;
this.targetClass = targetClass;
}
//XXX does this walk into inners
public void endVisit(MessageSend call, BlockScope scope) {
//System.out.println("endVisit: " + call);
// an error has already occurred
if (call.codegenBinding == null) return;
MethodBinding superBinding = call.codegenBinding;
if (superBinding instanceof ProblemMethodBinding) {
return;
}
// InterTypeMethodBindings are always statically bound, so there's no
// need to treat super calls specially here
if (superBinding instanceof InterTypeMethodBinding) {
return;
// InterTypeMethodBinding m = (InterTypeMethodBinding)superBinding;
// if (m.postDispatchMethod != null) {
// call.binding = m.postDispatchMethod;
// }
// return;
}
char[] accessName;
if (call.isSuperAccess() && !call.binding.isStatic()) {
call.receiver = new ThisReference(call.receiver.sourceStart, call.receiver.sourceEnd);
accessName =
NameMangler.superDispatchMethod(EclipseFactory.fromBinding(targetClass),
new String(superBinding.selector)).toCharArray();
} else if (call.receiver.isThis() && call.binding.isProtected() && !call.binding.isStatic()) {
//XXX this is a hack that violates some binary compatibility rules
if (superBinding.declaringClass.equals(targetClass)) {
accessName =
NameMangler.protectedDispatchMethod(EclipseFactory.fromBinding(targetClass),
new String(superBinding.selector)).toCharArray();
} else {
accessName =
NameMangler.superDispatchMethod(EclipseFactory.fromBinding(targetClass),
new String(superBinding.selector)).toCharArray();
}
} else {
return;
}
//??? do we want these to be unique
MethodBinding superAccessBinding =
new MethodBinding(ASTNode.AccPublic, accessName,
superBinding.returnType, superBinding.parameters, superBinding.thrownExceptions,
targetClass);
AstUtil.replaceMethodBinding(call, superAccessBinding);
ResolvedMember targetMember = EclipseFactory.makeResolvedMember(superBinding);
superMethodsCalled.add(targetMember);
}
}
|
73,334
|
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
|
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
|
resolved fixed
|
b133299
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:40:02Z
| 2004-09-06T17:00:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/ThisJoinPointVisitor.java
|
/* *******************************************************************
* 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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.ast;
import org.aspectj.weaver.Advice;
import org.eclipse.jdt.internal.compiler.ASTVisitor;
import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration;
import org.eclipse.jdt.internal.compiler.ast.Expression;
import org.eclipse.jdt.internal.compiler.ast.MessageSend;
import org.eclipse.jdt.internal.compiler.ast.NameReference;
import org.eclipse.jdt.internal.compiler.ast.SingleNameReference;
import org.eclipse.jdt.internal.compiler.lookup.Binding;
import org.eclipse.jdt.internal.compiler.lookup.BlockScope;
import org.eclipse.jdt.internal.compiler.lookup.ClassScope;
import org.eclipse.jdt.internal.compiler.lookup.LocalVariableBinding;
import org.eclipse.jdt.internal.compiler.lookup.MethodBinding;
import org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding;
import org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
/**
* Takes a method that already has the three extra parameters
* thisJoinPointStaticPart, thisJoinPoint and thisEnclosingJoinPointStaticPart
*/
public class ThisJoinPointVisitor extends ASTVisitor {
boolean needsDynamic = false;
boolean needsStatic = false;
boolean needsStaticEnclosing = false;
boolean hasEffectivelyStaticRef = false;
LocalVariableBinding thisJoinPointDec;
LocalVariableBinding thisJoinPointStaticPartDec;
LocalVariableBinding thisEnclosingJoinPointStaticPartDec;
LocalVariableBinding thisJoinPointDecLocal;
LocalVariableBinding thisJoinPointStaticPartDecLocal;
LocalVariableBinding thisEnclosingJoinPointStaticPartDecLocal;
boolean replaceEffectivelyStaticRefs = false;
AbstractMethodDeclaration method;
ThisJoinPointVisitor(AbstractMethodDeclaration method) {
this.method = method;
int index = method.arguments.length - 3;
thisJoinPointStaticPartDecLocal = method.scope.locals[index];
thisJoinPointStaticPartDec = method.arguments[index++].binding;
thisJoinPointDecLocal = method.scope.locals[index];
thisJoinPointDec = method.arguments[index++].binding;
thisEnclosingJoinPointStaticPartDecLocal = method.scope.locals[index];
thisEnclosingJoinPointStaticPartDec = method.arguments[index++].binding;
}
public void computeJoinPointParams() {
// walk my body to see what is needed
method.traverse(this, (ClassScope) null);
//??? add support for option to disable this optimization
//System.err.println("walked: " + method);
//System.err.println("check: "+ hasEffectivelyStaticRef + ", " + needsDynamic);
if (hasEffectivelyStaticRef && !needsDynamic) {
// replace effectively static refs with thisJoinPointStaticPart
replaceEffectivelyStaticRefs = true;
needsStatic = true;
method.traverse(this, (ClassScope) null);
}
//System.err.println("done: " + method);
}
boolean isRef(NameReference ref, Binding binding) {
//System.err.println("check ref: " + ref + " is " + System.identityHashCode(ref));
return ref.binding == binding;
}
boolean isRef(Expression expr, Binding binding) {
return expr != null
&& expr instanceof NameReference
&& isRef((NameReference) expr, binding);
}
public void endVisit(SingleNameReference ref, BlockScope scope) {
if (isRef(ref, thisJoinPointDec)) {
needsDynamic = true;
} else if (isRef(ref, thisJoinPointStaticPartDec)) {
needsStatic = true;
} else if (isRef(ref, thisEnclosingJoinPointStaticPartDec)) {
needsStaticEnclosing = true;
}
}
boolean canTreatAsStatic(String id) {
return id.equals("toString")
|| id.equals("toShortString")
|| id.equals("toLongString")
|| id.equals("getKind")
|| id.equals("getSignature")
|| id.equals("getSourceLocation");
//TODO: This is a good optimization, but requires more work than the above
// we have to replace a call with a direct reference, not just a different call
//|| id.equals("getStaticPart");
}
// boolean canTreatAsStatic(VarExpr varExpr) {
// ASTObject parent = varExpr.getParent();
// if (parent instanceof CallExpr) {
// Method calledMethod = ((CallExpr)parent).getMethod();
// return canTreatAsStatic(calledMethod);
//
// //??? should add a case here to catch
// //??? tjp.getEnclosingExecutionJoinPoint().STATIC_METHOD()
// } else if (parent instanceof BinopExpr) {
// BinopExpr binop = (BinopExpr)parent;
// if (binop.getType().isEquivalent(this.getTypeManager().getStringType())) {
// return true;
// } else {
// return false;
// }
// } else {
// return false;
// }
// }
boolean inBlockThatCantRun = false;
public boolean visit(MessageSend call, BlockScope scope) {
Expression receiver = call.receiver;
if (isRef(receiver, thisJoinPointDec)) {
if (canTreatAsStatic(new String(call.selector))) {
if (replaceEffectivelyStaticRefs) {
replaceEffectivelyStaticRef(call);
} else {
//System.err.println("has static reg");
hasEffectivelyStaticRef = true;
if (call.arguments != null) {
int argumentsLength = call.arguments.length;
for (int i = 0; i < argumentsLength; i++)
call.arguments[i].traverse(this, scope);
}
return false;
}
}
}
return super.visit(call, scope);
}
private void replaceEffectivelyStaticRef(MessageSend call) {
NameReference receiver = (NameReference) call.receiver;
//System.err.println("replace static ref: " + receiver + " is " + System.identityHashCode(receiver));
receiver.binding = thisJoinPointStaticPartDecLocal; //thisJoinPointStaticPartDec;
receiver.codegenBinding = thisJoinPointStaticPartDecLocal;
ReferenceBinding thisJoinPointStaticPartType =
(ReferenceBinding)thisJoinPointStaticPartDec.type;
receiver.receiverType = receiver.actualReceiverType =
receiver.resolvedType = thisJoinPointStaticPartType;
call.setActualReceiverType(thisJoinPointStaticPartType);
AstUtil.replaceMethodBinding(call, getEquivalentStaticBinding(call.binding));
}
private MethodBinding getEquivalentStaticBinding(MethodBinding template) {
ReferenceBinding b = (ReferenceBinding)thisJoinPointStaticPartDec.type;
return b.getExactMethod(template.selector, template.parameters);
}
public int removeUnusedExtraArguments() {
int extraArgumentFlags = 0;
this.computeJoinPointParams();
MethodBinding binding = method.binding;
int index = binding.parameters.length - 3;
if (needsStaticEnclosing) {
extraArgumentFlags |= Advice.ThisEnclosingJoinPointStaticPart;
} else {
removeParameter(index+2);
}
if (needsDynamic) {
extraArgumentFlags |= Advice.ThisJoinPoint;
} else {
removeParameter(index+1);
}
if (needsStatic) {
extraArgumentFlags |= Advice.ThisJoinPointStaticPart;
} else {
removeParameter(index+0);
}
return extraArgumentFlags;
}
private void removeParameter(int indexToRemove) {
// TypeBinding[] parameters = method.binding.parameters;
method.scope.locals = removeLocalBinding(indexToRemove, method.scope.locals);
method.scope.localIndex -= 1;
method.binding.parameters = removeParameter(indexToRemove, method.binding.parameters);
}
private static TypeBinding[] removeParameter(int index, TypeBinding[] bindings) {
int len = bindings.length;
TypeBinding[] ret = new TypeBinding[len-1];
System.arraycopy(bindings, 0, ret, 0, index);
System.arraycopy(bindings, index+1, ret, index, len-index-1);
return ret;
}
private static LocalVariableBinding[] removeLocalBinding(int index, LocalVariableBinding[] bindings) {
int len = bindings.length;
//??? for performance we should do this in-place
LocalVariableBinding[] ret = new LocalVariableBinding[len-1];
System.arraycopy(bindings, 0, ret, 0, index);
System.arraycopy(bindings, index+1, ret, index, len-index-1);
return ret;
}
}
|
73,334
|
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
|
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
|
resolved fixed
|
b133299
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:40:02Z
| 2004-09-06T17:00:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/AjLookupEnvironment.java
|
/* *******************************************************************
* 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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.lookup;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration;
import org.aspectj.ajdt.internal.compiler.ast.PointcutDeclaration;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.WeaveMessage;
import org.aspectj.weaver.AsmRelationshipProvider;
import org.aspectj.weaver.ConcreteTypeMunger;
import org.aspectj.weaver.ResolvedTypeMunger;
import org.aspectj.weaver.ResolvedTypeX;
import org.aspectj.weaver.TypeX;
import org.aspectj.weaver.WeaverStateInfo;
import org.aspectj.weaver.World;
import org.aspectj.weaver.bcel.LazyClassGen;
import org.aspectj.weaver.patterns.DeclareParents;
import org.eclipse.jdt.core.compiler.CharOperation;
import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration;
import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration;
import org.eclipse.jdt.internal.compiler.env.IBinaryType;
import org.eclipse.jdt.internal.compiler.env.INameEnvironment;
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
import org.eclipse.jdt.internal.compiler.impl.ITypeRequestor;
import org.eclipse.jdt.internal.compiler.lookup.BinaryTypeBinding;
import org.eclipse.jdt.internal.compiler.lookup.ClassScope;
import org.eclipse.jdt.internal.compiler.lookup.CompilationUnitScope;
import org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment;
import org.eclipse.jdt.internal.compiler.lookup.PackageBinding;
import org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding;
import org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding;
import org.eclipse.jdt.internal.compiler.problem.ProblemReporter;
/**
* Overrides the default eclipse LookupEnvironment for two purposes.
*
* 1. To provide some additional phases to <code>completeTypeBindings</code>
* that weave declare parents and inter-type declarations at the correct time.
*
* 2. To intercept the loading of new binary types to ensure the they will have
* declare parents and inter-type declarations woven when appropriate.
*
* @author Jim Hugunin
*/
public class AjLookupEnvironment extends LookupEnvironment {
public EclipseFactory factory = null;
// private boolean builtInterTypesAndPerClauses = false;
private List pendingTypesToWeave = new ArrayList();
private Map dangerousInterfaces = new HashMap();
public AjLookupEnvironment(
ITypeRequestor typeRequestor,
CompilerOptions options,
ProblemReporter problemReporter,
INameEnvironment nameEnvironment) {
super(typeRequestor, options, problemReporter, nameEnvironment);
}
//??? duplicates some of super's code
public void completeTypeBindings() {
// builtInterTypesAndPerClauses = false;
//pendingTypesToWeave = new ArrayList();
stepCompleted = BUILD_TYPE_HIERARCHY;
for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) {
units[i].scope.checkAndSetImports();
}
stepCompleted = CHECK_AND_SET_IMPORTS;
for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) {
units[i].scope.connectTypeHierarchy();
}
stepCompleted = CONNECT_TYPE_HIERARCHY;
for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) {
units[i].scope.buildFieldsAndMethods();
}
// would like to gather up all TypeDeclarations at this point and put them in the factory
for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) {
SourceTypeBinding[] b = units[i].scope.topLevelTypes;
for (int j = 0; j < b.length; j++) {
factory.addSourceTypeBinding(b[j]);
}
}
// need to build inter-type declarations for all AspectDeclarations at this point
for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) {
SourceTypeBinding[] b = units[i].scope.topLevelTypes;
for (int j = 0; j < b.length; j++) {
buildInterTypeAndPerClause(b[j].scope);
addCrosscuttingStructures(b[j].scope);
}
}
factory.finishTypeMungers();
// now do weaving
Collection typeMungers = factory.getTypeMungers();
Collection declareParents = factory.getDeclareParents();
doPendingWeaves();
for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) {
weaveInterTypeDeclarations(units[i].scope, typeMungers, declareParents);
}
for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) {
SourceTypeBinding[] b = units[i].scope.topLevelTypes;
for (int j = 0; j < b.length; j++) {
resolvePointcutDeclarations(b[j].scope);
}
}
for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) {
SourceTypeBinding[] b = units[i].scope.topLevelTypes;
for (int j = 0; j < b.length; j++) {
addAdviceLikeDeclares(b[j].scope);
}
}
for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) {
units[i] = null; // release unnecessary reference to the parsed unit
}
stepCompleted = BUILD_FIELDS_AND_METHODS;
lastCompletedUnitIndex = lastUnitIndex;
}
private void doPendingWeaves() {
for (Iterator i = pendingTypesToWeave.iterator(); i.hasNext(); ) {
SourceTypeBinding t = (SourceTypeBinding)i.next();
weaveInterTypeDeclarations(t);
}
pendingTypesToWeave.clear();
}
private void addAdviceLikeDeclares(ClassScope s) {
TypeDeclaration dec = s.referenceContext;
if (dec instanceof AspectDeclaration) {
ResolvedTypeX typeX = factory.fromEclipse(dec.binding);
factory.getWorld().getCrosscuttingMembersSet().addAdviceLikeDeclares(typeX);
}
SourceTypeBinding sourceType = s.referenceContext.binding;
ReferenceBinding[] memberTypes = sourceType.memberTypes;
for (int i = 0, length = memberTypes.length; i < length; i++) {
addAdviceLikeDeclares(((SourceTypeBinding) memberTypes[i]).scope);
}
}
private void addCrosscuttingStructures(ClassScope s) {
TypeDeclaration dec = s.referenceContext;
if (dec instanceof AspectDeclaration) {
ResolvedTypeX typeX = factory.fromEclipse(dec.binding);
factory.getWorld().getCrosscuttingMembersSet().addOrReplaceAspect(typeX);
if (typeX.getSuperclass().isAspect() && !typeX.getSuperclass().isExposedToWeaver()) {
factory.getWorld().getCrosscuttingMembersSet().addOrReplaceAspect(typeX.getSuperclass());
}
}
SourceTypeBinding sourceType = s.referenceContext.binding;
ReferenceBinding[] memberTypes = sourceType.memberTypes;
for (int i = 0, length = memberTypes.length; i < length; i++) {
addCrosscuttingStructures(((SourceTypeBinding) memberTypes[i]).scope);
}
}
private void resolvePointcutDeclarations(ClassScope s) {
TypeDeclaration dec = s.referenceContext;
SourceTypeBinding sourceType = s.referenceContext.binding;
boolean hasPointcuts = false;
AbstractMethodDeclaration[] methods = dec.methods;
boolean initializedMethods = false;
if (methods != null) {
for (int i=0; i < methods.length; i++) {
if (methods[i] instanceof PointcutDeclaration) {
hasPointcuts = true;
if (!initializedMethods) {
sourceType.methods(); //force initialization
initializedMethods = true;
}
((PointcutDeclaration)methods[i]).resolvePointcut(s);
}
}
}
if (hasPointcuts || dec instanceof AspectDeclaration) {
ResolvedTypeX.Name name = (ResolvedTypeX.Name)factory.fromEclipse(sourceType);
EclipseSourceType eclipseSourceType = (EclipseSourceType)name.getDelegate();
eclipseSourceType.checkPointcutDeclarations();
}
ReferenceBinding[] memberTypes = sourceType.memberTypes;
for (int i = 0, length = memberTypes.length; i < length; i++) {
resolvePointcutDeclarations(((SourceTypeBinding) memberTypes[i]).scope);
}
}
private void buildInterTypeAndPerClause(ClassScope s) {
TypeDeclaration dec = s.referenceContext;
if (dec instanceof AspectDeclaration) {
((AspectDeclaration)dec).buildInterTypeAndPerClause(s);
}
SourceTypeBinding sourceType = s.referenceContext.binding;
// test classes don't extend aspects
if (sourceType.superclass != null) {
ResolvedTypeX parent = factory.fromEclipse(sourceType.superclass);
if (parent.isAspect() && !(dec instanceof AspectDeclaration)) {
factory.showMessage(IMessage.ERROR, "class \'" + new String(sourceType.sourceName) +
"\' can not extend aspect \'" + parent.getName() + "\'",
factory.fromEclipse(sourceType).getSourceLocation(), null);
}
}
ReferenceBinding[] memberTypes = sourceType.memberTypes;
for (int i = 0, length = memberTypes.length; i < length; i++) {
buildInterTypeAndPerClause(((SourceTypeBinding) memberTypes[i]).scope);
}
}
private void weaveInterTypeDeclarations(CompilationUnitScope unit, Collection typeMungers, Collection declareParents) {
for (int i = 0, length = unit.topLevelTypes.length; i < length; i++) {
weaveInterTypeDeclarations(unit.topLevelTypes[i], typeMungers, declareParents, false);
}
}
private void weaveInterTypeDeclarations(SourceTypeBinding sourceType) {
if (!factory.areTypeMungersFinished()) {
if (!pendingTypesToWeave.contains(sourceType)) pendingTypesToWeave.add(sourceType);
} else {
weaveInterTypeDeclarations(sourceType, factory.getTypeMungers(), factory.getDeclareParents(), true);
}
}
private void weaveInterTypeDeclarations(SourceTypeBinding sourceType, Collection typeMungers, Collection declareParents, boolean skipInners) {
ResolvedTypeX onType = factory.fromEclipse(sourceType);
WeaverStateInfo info = onType.getWeaverState();
if (info != null && !info.isOldStyle()) {
Collection mungers =
onType.getWeaverState().getTypeMungers(onType);
//System.out.println(onType + " mungers: " + mungers);
for (Iterator i = mungers.iterator(); i.hasNext(); ) {
ConcreteTypeMunger m = (ConcreteTypeMunger)i.next();
EclipseTypeMunger munger = factory.makeEclipseTypeMunger(m);
if (munger.munge(sourceType)) {
if (onType.isInterface() &&
munger.getMunger().needsAccessToTopmostImplementor())
{
if (!onType.getWorld().getCrosscuttingMembersSet().containsAspect(munger.getAspectType())) {
dangerousInterfaces.put(onType,
"implementors of " + onType + " must be woven by " +
munger.getAspectType());
}
}
}
}
return;
}
//System.out.println("dangerousInterfaces: " + dangerousInterfaces);
for (Iterator i = dangerousInterfaces.entrySet().iterator(); i.hasNext();) {
Map.Entry entry = (Map.Entry) i.next();
ResolvedTypeX interfaceType = (ResolvedTypeX)entry.getKey();
if (onType.isTopmostImplementor(interfaceType)) {
factory.showMessage(IMessage.ERROR,
onType + ": " + entry.getValue(),
onType.getSourceLocation(), null);
}
}
boolean needOldStyleWarning = (info != null && info.isOldStyle());
onType.clearInterTypeMungers();
for (Iterator i = declareParents.iterator(); i.hasNext();) {
doDeclareParents((DeclareParents)i.next(), sourceType);
}
for (Iterator i = typeMungers.iterator(); i.hasNext();) {
EclipseTypeMunger munger = (EclipseTypeMunger) i.next();
if (munger.matches(onType)) {
if (needOldStyleWarning) {
factory.showMessage(IMessage.WARNING,
"The class for " + onType + " should be recompiled with ajc-1.1.1 for best results",
onType.getSourceLocation(), null);
needOldStyleWarning = false;
}
onType.addInterTypeMunger(munger);
//TODO: Andy Should be done at weave time.
// Unfortunately we can't do it at weave time unless the type mungers remember where
// they came from. Thats why we do it here during complation because at this time
// they do know their source location. I've put a flag in ResolvedTypeMunger that
// records whether type mungers are currently set to remember their source location.
// The flag is currently set to false, it should be set to true when we do the
// work to version all AspectJ attributes.
// (When done at weave time, it is done by invoking addRelationship() on
// AsmRelationshipProvider (see BCELTypeMunger)
if (!ResolvedTypeMunger.persistSourceLocation) // Do it up front if we bloody have to
AsmInterTypeRelationshipProvider.getDefault().addRelationship(onType, munger);
}
}
//???onType.checkInterTypeMungers();
onType.checkInterTypeMungers();
for (Iterator i = onType.getInterTypeMungers().iterator(); i.hasNext();) {
EclipseTypeMunger munger = (EclipseTypeMunger) i.next();
//System.out.println("applying: " + munger + " to " + new String(sourceType.sourceName));
munger.munge(sourceType);
}
if (skipInners) return;
ReferenceBinding[] memberTypes = sourceType.memberTypes;
for (int i = 0, length = memberTypes.length; i < length; i++) {
if (memberTypes[i] instanceof SourceTypeBinding) {
weaveInterTypeDeclarations((SourceTypeBinding) memberTypes[i], typeMungers, declareParents, false);
}
}
}
private void doDeclareParents(DeclareParents declareParents, SourceTypeBinding sourceType) {
List newParents = declareParents.findMatchingNewParents(factory.fromEclipse(sourceType));
if (!newParents.isEmpty()) {
for (Iterator i = newParents.iterator(); i.hasNext(); ) {
ResolvedTypeX parent = (ResolvedTypeX)i.next();
if (dangerousInterfaces.containsKey(parent)) {
ResolvedTypeX onType = factory.fromEclipse(sourceType);
factory.showMessage(IMessage.ERROR,
onType + ": " + dangerousInterfaces.get(parent),
onType.getSourceLocation(), null);
}
AsmRelationshipProvider.getDefault().addDeclareParentsRelationship(declareParents.getSourceLocation(),factory.fromEclipse(sourceType), newParents);
addParent(sourceType, parent);
}
}
}
private void reportDeclareParentsMessage(WeaveMessage.WeaveMessageKind wmk,SourceTypeBinding sourceType,ResolvedTypeX parent) {
if (!factory.getWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)) {
String filename = new String(sourceType.getFileName());
int takefrom = filename.lastIndexOf('/');
if (takefrom == -1 ) takefrom = filename.lastIndexOf('\\');
filename = filename.substring(takefrom+1);
factory.getWorld().getMessageHandler().handleMessage(
WeaveMessage.constructWeavingMessage(wmk,
new String[]{CharOperation.toString(sourceType.compoundName),
filename,
parent.getClassName(),
getShortname(parent.getSourceLocation().getSourceFile().getPath())}));
}
}
private String getShortname(String path) {
int takefrom = path.lastIndexOf('/');
if (takefrom == -1) {
takefrom = path.lastIndexOf('\\');
}
return path.substring(takefrom+1);
}
private void addParent(SourceTypeBinding sourceType, ResolvedTypeX parent) {
ReferenceBinding parentBinding = (ReferenceBinding)factory.makeTypeBinding(parent);
if (parentBinding.isClass()) {
sourceType.superclass = parentBinding;
// TAG: WeavingMessage DECLARE PARENTS: EXTENDS
// Compiler restriction: Can't do EXTENDS at weave time
// So, only see this message if doing a source compilation
reportDeclareParentsMessage(WeaveMessage.WEAVEMESSAGE_DECLAREPARENTSEXTENDS,sourceType,parent);
} else {
ReferenceBinding[] oldI = sourceType.superInterfaces;
ReferenceBinding[] newI;
if (oldI == null) {
newI = new ReferenceBinding[1];
newI[0] = parentBinding;
} else {
int n = oldI.length;
newI = new ReferenceBinding[n+1];
System.arraycopy(oldI, 0, newI, 0, n);
newI[n] = parentBinding;
}
sourceType.superInterfaces = newI;
warnOnAddedInterface(factory.fromEclipse(sourceType),parent);
// TAG: WeavingMessage DECLARE PARENTS: IMPLEMENTS
// This message will come out of BcelTypeMunger.munge if doing a binary weave
reportDeclareParentsMessage(WeaveMessage.WEAVEMESSAGE_DECLAREPARENTSIMPLEMENTS,sourceType,parent);
}
}
public void warnOnAddedInterface (ResolvedTypeX type, ResolvedTypeX parent) {
World world = factory.getWorld();
ResolvedTypeX serializable = world.getCoreType(TypeX.SERIALIZABLE);
if (serializable.isAssignableFrom(type)
&& !serializable.isAssignableFrom(parent)
&& !LazyClassGen.hasSerialVersionUIDField(type)) {
world.getLint().needsSerialVersionUIDField.signal(
new String[] {
type.getName().toString(),
"added interface " + parent.getName().toString()
},
null,
null);
}
}
private List pendingTypesToFinish = new ArrayList();
boolean inBinaryTypeCreationAndWeaving = false;
boolean processingTheQueue = false;
public BinaryTypeBinding createBinaryTypeFrom(
IBinaryType binaryType,
PackageBinding packageBinding,
boolean needFieldsAndMethods)
{
if (inBinaryTypeCreationAndWeaving) {
BinaryTypeBinding ret = super.createBinaryTypeFrom(
binaryType,
packageBinding,
needFieldsAndMethods);
pendingTypesToFinish.add(ret);
return ret;
}
inBinaryTypeCreationAndWeaving = true;
try {
BinaryTypeBinding ret = super.createBinaryTypeFrom(
binaryType,
packageBinding,
needFieldsAndMethods);
weaveInterTypeDeclarations(ret);
return ret;
} finally {
inBinaryTypeCreationAndWeaving = false;
// Start processing the list...
if (pendingTypesToFinish.size()>0) {
processingTheQueue = true;
while (!pendingTypesToFinish.isEmpty()) {
BinaryTypeBinding nextVictim = (BinaryTypeBinding)pendingTypesToFinish.remove(0);
// During this call we may recurse into this method and add
// more entries to the pendingTypesToFinish list.
weaveInterTypeDeclarations(nextVictim);
}
processingTheQueue = false;
}
}
}
}
|
73,334
|
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
|
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
|
resolved fixed
|
b133299
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:40:02Z
| 2004-09-06T17:00:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/AjTypeConstants.java
|
/* *******************************************************************
* 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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.lookup;
import org.eclipse.jdt.internal.compiler.ast.QualifiedTypeReference;
import org.eclipse.jdt.internal.compiler.ast.TypeReference;
import org.eclipse.jdt.internal.compiler.lookup.MethodBinding;
import org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding;
import org.eclipse.jdt.internal.compiler.lookup.Scope;
import org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
public class AjTypeConstants {
public static final char[] ORG = "org".toCharArray();
public static final char[] ASPECTJ = "aspectj".toCharArray();
public static final char[] RUNTIME = "runtime".toCharArray();
public static final char[] LANG = "lang".toCharArray();
public static final char[] INTERNAL = "internal".toCharArray();
// Constant compound names
public static final char[][] ORG_ASPECTJ_LANG_JOINPOINT =
new char[][] {ORG, ASPECTJ, LANG, "JoinPoint".toCharArray()};
public static final char[][] ORG_ASPECTJ_LANG_JOINPOINT_STATICPART =
new char[][] {ORG, ASPECTJ, LANG, "JoinPoint".toCharArray(), "StaticPart".toCharArray()};
public static final char[][] ORG_ASPECTJ_RUNTIME_INTERNAL_AROUNDCLOSURE =
new char[][] {ORG, ASPECTJ, RUNTIME, INTERNAL, "AroundClosure".toCharArray()};
public static final char[][] ORG_ASPECTJ_RUNTIME_INTERNAL_CONVERSIONS =
new char[][] {ORG, ASPECTJ, RUNTIME, INTERNAL, "Conversions".toCharArray()};
public static TypeReference getJoinPointType() {
return new QualifiedTypeReference(ORG_ASPECTJ_LANG_JOINPOINT, new long[10]);
}
public static TypeReference getJoinPointStaticPartType() {
return new QualifiedTypeReference(ORG_ASPECTJ_LANG_JOINPOINT_STATICPART, new long[10]);
}
public static TypeReference getAroundClosureType() {
return new QualifiedTypeReference(ORG_ASPECTJ_RUNTIME_INTERNAL_AROUNDCLOSURE, new long[10]);
}
public static ReferenceBinding getConversionsType(Scope scope) {
return (ReferenceBinding)scope.getType(ORG_ASPECTJ_RUNTIME_INTERNAL_CONVERSIONS);
}
public static MethodBinding getConversionMethodToObject(Scope scope, TypeBinding fromType) {
String name = new String(fromType.sourceName()) + "Object";
return getConversionsType(scope).getMethods(name.toCharArray())[0];
}
public static MethodBinding getConversionMethodFromObject(Scope scope, TypeBinding toType) {
String name = new String(toType.sourceName()) + "Value";
return getConversionsType(scope).getMethods(name.toCharArray())[0];
}
}
|
73,334
|
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
|
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
|
resolved fixed
|
b133299
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:40:02Z
| 2004-09-06T17:00:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/EclipseFactory.java
|
/* *******************************************************************
* 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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* Mik Kersten 2004-07-26 extended to allow overloading of
* hierarchy builder
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.lookup;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration;
import org.aspectj.ajdt.internal.compiler.ast.AstUtil;
import org.aspectj.ajdt.internal.core.builder.AjBuildManager;
import org.aspectj.ajdt.internal.core.builder.AsmHierarchyBuilder;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.IMessage.Kind;
import org.aspectj.weaver.ConcreteTypeMunger;
import org.aspectj.weaver.IHasPosition;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedTypeX;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.TypeX;
import org.aspectj.weaver.World;
import org.eclipse.jdt.core.compiler.CharOperation;
import org.eclipse.jdt.internal.compiler.ast.ASTNode;
import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration;
import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration;
import org.eclipse.jdt.internal.compiler.ast.EmptyStatement;
import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration;
import org.eclipse.jdt.internal.compiler.impl.Constant;
import org.eclipse.jdt.internal.compiler.impl.ReferenceContext;
import org.eclipse.jdt.internal.compiler.lookup.BaseTypes;
import org.eclipse.jdt.internal.compiler.lookup.FieldBinding;
import org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment;
import org.eclipse.jdt.internal.compiler.lookup.MethodBinding;
import org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding;
import org.eclipse.jdt.internal.compiler.lookup.Scope;
import org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding;
import org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
/**
* @author Jim Hugunin
*/
public class EclipseFactory {
public static boolean DEBUG = false;
private AjBuildManager buildManager;
private LookupEnvironment lookupEnvironment;
private boolean xSerializableAspects;
private World world;
private AsmHierarchyBuilder asmHierarchyBuilder;
private Map/*TypeX, TypeBinding*/ typexToBinding = new HashMap();
//XXX currently unused
// private Map/*TypeBinding, ResolvedTypeX*/ bindingToResolvedTypeX = new HashMap();
public static EclipseFactory fromLookupEnvironment(LookupEnvironment env) {
AjLookupEnvironment aenv = (AjLookupEnvironment)env;
return aenv.factory;
}
public static EclipseFactory fromScopeLookupEnvironment(Scope scope) {
return fromLookupEnvironment(AstUtil.getCompilationUnitScope(scope).environment);
}
public EclipseFactory(LookupEnvironment lookupEnvironment,AjBuildManager buildManager) {
this.lookupEnvironment = lookupEnvironment;
this.buildManager = buildManager;
this.world = buildManager.getWorld();
this.xSerializableAspects = buildManager.buildConfig.isXserializableAspects();
}
public EclipseFactory(LookupEnvironment lookupEnvironment, World world, boolean xSer) {
this.lookupEnvironment = lookupEnvironment;
this.world = world;
this.xSerializableAspects = xSer;
this.buildManager = null;
}
public World getWorld() {
return world;
}
public void showMessage(
Kind kind,
String message,
ISourceLocation loc1,
ISourceLocation loc2)
{
getWorld().showMessage(kind, message, loc1, loc2);
}
public ResolvedTypeX fromEclipse(ReferenceBinding binding) {
if (binding == null) return ResolvedTypeX.MISSING;
//??? this seems terribly inefficient
//System.err.println("resolving: " + binding.getClass() + ", name = " + getName(binding));
ResolvedTypeX ret = getWorld().resolve(fromBinding(binding));
//System.err.println(" got: " + ret);
return ret;
}
public ResolvedTypeX[] fromEclipse(ReferenceBinding[] bindings) {
if (bindings == null) {
return ResolvedTypeX.NONE;
}
int len = bindings.length;
ResolvedTypeX[] ret = new ResolvedTypeX[len];
for (int i=0; i < len; i++) {
ret[i] = fromEclipse(bindings[i]);
}
return ret;
}
private static String getName(TypeBinding binding) {
if (binding instanceof ReferenceBinding) {
return new String(
CharOperation.concatWith(((ReferenceBinding)binding).compoundName, '.'));
}
String packageName = new String(binding.qualifiedPackageName());
String className = new String(binding.qualifiedSourceName()).replace('.', '$');
if (packageName.length() > 0) {
className = packageName + "." + className;
}
//XXX doesn't handle arrays correctly (or primitives?)
return new String(className);
}
//??? going back and forth between strings and bindings is a waste of cycles
public static TypeX fromBinding(TypeBinding binding) {
if (binding instanceof HelperInterfaceBinding) {
return ((HelperInterfaceBinding) binding).getTypeX();
}
if (binding == null || binding.qualifiedSourceName() == null) {
return ResolvedTypeX.MISSING;
}
return TypeX.forName(getName(binding));
}
public static TypeX[] fromBindings(TypeBinding[] bindings) {
if (bindings == null) return TypeX.NONE;
int len = bindings.length;
TypeX[] ret = new TypeX[len];
for (int i=0; i<len; i++) {
ret[i] = fromBinding(bindings[i]);
}
return ret;
}
public static ASTNode astForLocation(IHasPosition location) {
return new EmptyStatement(location.getStart(), location.getEnd());
}
public Collection getDeclareParents() {
return getWorld().getDeclareParents();
}
public Collection finishedTypeMungers = null;
public boolean areTypeMungersFinished() {
return finishedTypeMungers != null;
}
public void finishTypeMungers() {
// make sure that type mungers are
Collection ret = new ArrayList();
Collection baseTypeMungers =
getWorld().getCrosscuttingMembersSet().getTypeMungers();
for (Iterator i = baseTypeMungers.iterator(); i.hasNext(); ) {
ConcreteTypeMunger munger = (ConcreteTypeMunger) i.next();
EclipseTypeMunger etm = makeEclipseTypeMunger(munger);
if (etm != null) ret.add(etm);
}
finishedTypeMungers = ret;
}
public EclipseTypeMunger makeEclipseTypeMunger(ConcreteTypeMunger concrete) {
//System.err.println("make munger: " + concrete);
//!!! can't do this if we want incremental to work right
//if (concrete instanceof EclipseTypeMunger) return (EclipseTypeMunger)concrete;
//System.err.println(" was not eclipse");
if (concrete.getMunger() != null && EclipseTypeMunger.supportsKind(concrete.getMunger().getKind())) {
AbstractMethodDeclaration method = null;
if (concrete instanceof EclipseTypeMunger) {
method = ((EclipseTypeMunger)concrete).getSourceMethod();
}
EclipseTypeMunger ret =
new EclipseTypeMunger(this, concrete.getMunger(), concrete.getAspectType(), method);
if (ret.getSourceLocation() == null) {
ret.setSourceLocation(concrete.getSourceLocation());
}
return ret;
} else {
return null;
}
}
public Collection getTypeMungers() {
//??? assert finishedTypeMungers != null
return finishedTypeMungers;
}
public static ResolvedMember makeResolvedMember(MethodBinding binding) {
return makeResolvedMember(binding, binding.declaringClass);
}
public static ResolvedMember makeResolvedMember(MethodBinding binding, TypeBinding declaringType) {
//System.err.println("member for: " + binding + ", " + new String(binding.declaringClass.sourceName));
ResolvedMember ret = new ResolvedMember(
binding.isConstructor() ? Member.CONSTRUCTOR : Member.METHOD,
fromBinding(declaringType),
binding.modifiers,
fromBinding(binding.returnType),
new String(binding.selector),
fromBindings(binding.parameters),
fromBindings(binding.thrownExceptions));
return ret;
}
public static ResolvedMember makeResolvedMember(FieldBinding binding) {
return makeResolvedMember(binding, binding.declaringClass);
}
public static ResolvedMember makeResolvedMember(FieldBinding binding, TypeBinding receiverType) {
return new ResolvedMember(
Member.FIELD,
fromBinding(receiverType),
binding.modifiers,
fromBinding(binding.type),
new String(binding.name),
TypeX.NONE);
}
public TypeBinding makeTypeBinding(TypeX typeX) {
TypeBinding ret = (TypeBinding)typexToBinding.get(typeX);
if (ret == null) {
ret = makeTypeBinding1(typeX);
typexToBinding.put(typeX, ret);
}
if (ret == null) {
System.out.println("can't find: " + typeX);
}
return ret;
}
private TypeBinding makeTypeBinding1(TypeX typeX) {
if (typeX.isPrimitive()) {
if (typeX == ResolvedTypeX.BOOLEAN) return BaseTypes.BooleanBinding;
if (typeX == ResolvedTypeX.BYTE) return BaseTypes.ByteBinding;
if (typeX == ResolvedTypeX.CHAR) return BaseTypes.CharBinding;
if (typeX == ResolvedTypeX.DOUBLE) return BaseTypes.DoubleBinding;
if (typeX == ResolvedTypeX.FLOAT) return BaseTypes.FloatBinding;
if (typeX == ResolvedTypeX.INT) return BaseTypes.IntBinding;
if (typeX == ResolvedTypeX.LONG) return BaseTypes.LongBinding;
if (typeX == ResolvedTypeX.SHORT) return BaseTypes.ShortBinding;
if (typeX == ResolvedTypeX.VOID) return BaseTypes.VoidBinding;
throw new RuntimeException("weird primitive type " + typeX);
} else if (typeX.isArray()) {
int dim = 0;
while (typeX.isArray()) {
dim++;
typeX = typeX.getComponentType();
}
return lookupEnvironment.createArrayType(makeTypeBinding(typeX), dim);
} else {
String n = typeX.getName();
char[][] name = CharOperation.splitOn('.', n.toCharArray());
return lookupEnvironment.getType(name);
}
}
public TypeBinding[] makeTypeBindings(TypeX[] types) {
int len = types.length;
TypeBinding[] ret = new TypeBinding[len];
for (int i = 0; i < len; i++) {
ret[i] = makeTypeBinding(types[i]);
}
return ret;
}
// just like the code above except it returns an array of ReferenceBindings
private ReferenceBinding[] makeReferenceBindings(TypeX[] types) {
int len = types.length;
ReferenceBinding[] ret = new ReferenceBinding[len];
for (int i = 0; i < len; i++) {
ret[i] = (ReferenceBinding)makeTypeBinding(types[i]);
}
return ret;
}
public FieldBinding makeFieldBinding(ResolvedMember member) {
return new FieldBinding(member.getName().toCharArray(),
makeTypeBinding(member.getReturnType()),
member.getModifiers(),
(ReferenceBinding)makeTypeBinding(member.getDeclaringType()),
Constant.NotAConstant);
}
public MethodBinding makeMethodBinding(ResolvedMember member) {
return new MethodBinding(member.getModifiers(),
member.getName().toCharArray(),
makeTypeBinding(member.getReturnType()),
makeTypeBindings(member.getParameterTypes()),
makeReferenceBindings(member.getExceptions()),
(ReferenceBinding)makeTypeBinding(member.getDeclaringType()));
}
public MethodBinding makeMethodBindingForCall(Member member) {
return new MethodBinding(member.getCallsiteModifiers(),
member.getName().toCharArray(),
makeTypeBinding(member.getReturnType()),
makeTypeBindings(member.getParameterTypes()),
new ReferenceBinding[0],
(ReferenceBinding)makeTypeBinding(member.getDeclaringType()));
}
public void finishedCompilationUnit(CompilationUnitDeclaration unit) {
if ((buildManager != null) && buildManager.doGenerateModel()) {
AjBuildManager.getAsmHierarchyBuilder().buildStructureForCompilationUnit(unit, buildManager.getStructureModel(), buildManager.buildConfig);
}
}
public void addTypeBinding(TypeBinding binding) {
typexToBinding.put(fromBinding(binding), binding);
}
public Shadow makeShadow(ASTNode location, ReferenceContext context) {
return EclipseShadow.makeShadow(this, location, context);
}
public Shadow makeShadow(ReferenceContext context) {
return EclipseShadow.makeShadow(this, (ASTNode) context, context);
}
public void addSourceTypeBinding(SourceTypeBinding binding) {
TypeDeclaration decl = binding.scope.referenceContext;
ResolvedTypeX.Name name = getWorld().lookupOrCreateName(TypeX.forName(getName(binding)));
EclipseSourceType t = new EclipseSourceType(name, this, binding, decl);
name.setDelegate(t);
if (decl instanceof AspectDeclaration) {
((AspectDeclaration)decl).typeX = name;
((AspectDeclaration)decl).concreteName = t;
}
ReferenceBinding[] memberTypes = binding.memberTypes;
for (int i = 0, length = memberTypes.length; i < length; i++) {
addSourceTypeBinding((SourceTypeBinding) memberTypes[i]);
}
}
// XXX this doesn't feel like it belongs here, but it breaks a hard dependency on
// exposing AjBuildManager (needed by AspectDeclaration).
public boolean isXSerializableAspects() {
return xSerializableAspects;
}
}
|
73,334
|
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
|
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
|
resolved fixed
|
b133299
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:40:02Z
| 2004-09-06T17:00:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/EclipseScope.java
|
/* *******************************************************************
* 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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.lookup;
import java.util.ArrayList;
import java.util.List;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.IMessageHandler;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.Message;
import org.aspectj.weaver.IHasPosition;
import org.aspectj.weaver.ResolvedTypeX;
import org.aspectj.weaver.TypeX;
import org.aspectj.weaver.World;
import org.aspectj.weaver.patterns.*;
import org.aspectj.weaver.patterns.FormalBinding;
import org.aspectj.weaver.patterns.IScope;
import org.eclipse.jdt.internal.compiler.lookup.ClassScope;
import org.eclipse.jdt.internal.compiler.lookup.CompilationUnitScope;
import org.eclipse.jdt.internal.compiler.lookup.ImportBinding;
import org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding;
import org.eclipse.jdt.internal.compiler.lookup.Scope;
import org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
import org.eclipse.jdt.core.compiler.CharOperation;
/**
* Adaptor from org.eclipse.jdt.internal.compiler.lookup.Scope to org.aspectj.weaver.IScope
*
* @author Jim Hugunin
*/
public class EclipseScope implements IScope {
private Scope scope;
private EclipseFactory world;
private ResolvedTypeX enclosingType;
private FormalBinding[] bindings;
private String[] importedPrefixes = null;
private String[] importedNames = null;
public EclipseScope(FormalBinding[] bindings, Scope scope) {
this.bindings = bindings;
this.scope = scope;
this.world = EclipseFactory.fromScopeLookupEnvironment(scope);
this.enclosingType = world.fromEclipse(scope.enclosingSourceType());
}
public TypeX lookupType(String name, IHasPosition location) {
TypeBinding b = scope.getType(WildTypePattern.splitNames(name));
//FIXME need reasonable error handling...
if (!b.isValidBinding()) {
return ResolvedTypeX.MISSING;
}
//System.err.println("binding: " + b);
// Binding(tokens, bits & RestrictiveFlagMASK, this)
return EclipseFactory.fromBinding(b);
/*
computeImports();
// System.out.println("lookup: " + name + " in " +
// Arrays.asList(importedPrefixes));
ResolvedTypeX ret = null;
String dotName = "." + name;
for (int i=0; i<importedNames.length; i++) {
String importedName = importedNames[i];
//??? can this be right
if (importedName.endsWith(name) &&
((importedName.length() == name.length()) ||
(importedName.endsWith(dotName))))
{
ResolvedTypeX found = resolveVisible(importedName);
if (found == ResolvedTypeX.MISSING) continue;
if (ret != null) {
message(IMessage.ERROR, location,
"ambiguous type reference, both " + ret.getName() + " and " + importedName);
return ResolvedTypeX.MISSING;
} else {
ret = found;
}
}
}
if (ret != null) return ret;
//XXX need to handle ambiguous references here
for (int i=0; i<importedPrefixes.length; i++) {
String importedPrefix = importedPrefixes[i];
ResolvedTypeX tryType = resolveVisible(importedPrefix + name);
if (tryType != ResolvedTypeX.MISSING) {
return tryType;
}
}
return resolveVisible(name);
*/
}
// private ResolvedTypeX resolveVisible(String name) {
// ResolvedTypeX found = world.getWorld().resolve(TypeX.forName(name), true);
// if (found == ResolvedTypeX.MISSING) return found;
// if (ResolvedTypeX.isVisible(found.getModifiers(), found, enclosingType)) return found;
// return ResolvedTypeX.MISSING;
// }
// public TypeX lookupType(String name, IHasPosition location) {
// char[][] namePieces = CharOperation.splitOn('.', name.toCharArray());
// TypeBinding binding;
// if (namePieces.length == 1) {
// binding = scope.getType(namePieces[0]);
// } else {
// binding = scope.getType(namePieces);
// }
//
//
// if (!binding.isValidBinding()) {
// //XXX do we do this always or sometimes
// System.err.println("error: " + binding);
// scope.problemReporter().invalidType(EclipseWorld.astForLocation(location), binding);
// return ResolvedTypeX.MISSING;
// }
// //??? do we want this too
//// if (AstNode.isTypeUseDeprecated(binding, scope))
//// scope.problemReporter().deprecatedType(binding, EclipseWorld.astForLocation(location));
//
// return EclipseWorld.fromBinding(binding);
// }
private void computeImports() {
if (importedNames != null) return;
List importedNamesList = new ArrayList();
List importedPrefixesList = new ArrayList();
Scope currentScope = scope;
//add any enclosing types to this list
while (!(currentScope instanceof CompilationUnitScope)) {
if (currentScope == null) {
throw new RuntimeException("unimplemented");
}
if (currentScope instanceof ClassScope) {
addClassAndParentsToPrefixes(((ClassScope)currentScope).referenceType().binding, importedPrefixesList);
}
currentScope = currentScope.parent;
}
CompilationUnitScope cuScope = (CompilationUnitScope)currentScope;
String packageName =
new String(CharOperation.concatWith(cuScope.currentPackageName, '.'));
//System.err.println("package: " + packageName);
if (packageName.length() > 0) {
importedPrefixesList.add(packageName + ".");
}
ImportBinding[] imports = cuScope.imports;
for (int i = 0; i < imports.length; i++) {
ImportBinding importBinding = imports[i];
String importName =
new String(CharOperation.concatWith(importBinding.compoundName, '.'));
//XXX wrong behavior for java.util.Map.*
if (importBinding.onDemand) {
importedPrefixesList.add(importName + ".");
} else {
importedNamesList.add(importName);
}
}
TypeBinding[] topTypes = cuScope.topLevelTypes;
for (int i = 0; i < topTypes.length; i++) {
importedNamesList.add(EclipseFactory.fromBinding(topTypes[i]).getName());
}
importedNames =
(String[])importedNamesList.toArray(new String[importedNamesList.size()]);
importedPrefixes =
(String[])importedPrefixesList.toArray(new String[importedPrefixesList.size()]);
}
private void addClassAndParentsToPrefixes(
ReferenceBinding binding,
List importedPrefixesList)
{
if (binding == null) return;
importedPrefixesList.add(EclipseFactory.fromBinding(binding).getName()+"$");
addClassAndParentsToPrefixes(binding.superclass(), importedPrefixesList);
ReferenceBinding[] superinterfaces = binding.superInterfaces();
if (superinterfaces != null) {
for (int i = 0; i < superinterfaces.length; i++) {
addClassAndParentsToPrefixes(superinterfaces[i], importedPrefixesList);
}
}
}
public String[] getImportedNames() {
computeImports();
return importedNames;
}
public String[] getImportedPrefixes() {
computeImports();
//System.err.println("prefixes: " + Arrays.asList(importedPrefixes));
return importedPrefixes;
}
//XXX add good errors when would bind to extra parameters
public FormalBinding lookupFormal(String name) {
for (int i = 0, len = bindings.length; i < len; i++) {
if (bindings[i].getName().equals(name)) return bindings[i];
}
return null;
}
public FormalBinding getFormal(int i) {
return bindings[i];
}
public int getFormalCount() {
return bindings.length;
}
public ISourceLocation makeSourceLocation(IHasPosition location) {
return new EclipseSourceLocation(scope.problemReporter().referenceContext.compilationResult(),
location.getStart(), location.getEnd());
}
public IMessageHandler getMessageHandler() {
return world.getWorld().getMessageHandler();
}
public void message(
IMessage.Kind kind,
IHasPosition location1,
IHasPosition location2,
String message) {
message(kind, location1, message);
message(kind, location2, message);
}
public void message(
IMessage.Kind kind,
IHasPosition location,
String message) {
//System.out.println("message: " + message + " loc: " + makeSourceLocation(location));
getMessageHandler()
.handleMessage(new Message(message, kind, null, makeSourceLocation(location)));
}
public World getWorld() {
return world.getWorld();
}
public ResolvedTypeX getEnclosingType() {
return enclosingType;
}
}
|
73,334
|
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
|
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
|
resolved fixed
|
b133299
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:40:02Z
| 2004-09-06T17:00:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/EclipseShadow.java
|
/* *******************************************************************
* 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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.lookup;
import org.aspectj.ajdt.internal.compiler.ast.*;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.weaver.*;
import org.aspectj.weaver.ast.Var;
import org.eclipse.jdt.internal.compiler.ast.*;
import org.eclipse.jdt.internal.compiler.impl.ReferenceContext;
/**
* This is only used for declare soft right now.
*
* It might be used for other compile-time matching, but in all such cases
* this and target pcds can't be used. We might not behave correctly in
* such cases.
*/
public class EclipseShadow extends Shadow {
EclipseFactory world;
ASTNode astNode;
ReferenceContext context;
//AbstractMethodDeclaration enclosingMethod;
public EclipseShadow(EclipseFactory world, Kind kind, Member signature, ASTNode astNode,
ReferenceContext context)
{
super(kind, signature, null);
this.world = world;
this.astNode = astNode;
this.context = context;
}
public World getIWorld() {
return world.getWorld();
}
public TypeX getEnclosingType() {
if (context instanceof TypeDeclaration) {
return EclipseFactory.fromBinding(((TypeDeclaration)context).binding);
} else if (context instanceof AbstractMethodDeclaration) {
return EclipseFactory.fromBinding(((AbstractMethodDeclaration)context).binding.declaringClass);
} else {
return ResolvedTypeX.MISSING;
}
}
public ISourceLocation getSourceLocation() {
//XXX need to fill this in ASAP
return null;
}
public Member getEnclosingCodeSignature() {
if (context instanceof TypeDeclaration) {
return new Member(Member.STATIC_INITIALIZATION, getEnclosingType(), 0,
ResolvedTypeX.VOID, "<clinit>", TypeX.NONE);
} else if (context instanceof AbstractMethodDeclaration) {
return EclipseFactory.makeResolvedMember(((AbstractMethodDeclaration)context).binding);
} else {
return null;
}
}
// -- all below here are only used for implementing, not in matching
// -- we should probably pull out a super-interface to capture this in type system
public Var getThisVar() {
throw new RuntimeException("unimplemented");
}
public Var getTargetVar() {
throw new RuntimeException("unimplemented");
}
public Var getArgVar(int i) {
throw new RuntimeException("unimplemented");
}
public Var getThisJoinPointVar() {
throw new RuntimeException("unimplemented");
}
public Var getThisJoinPointStaticPartVar() {
throw new RuntimeException("unimplemented");
}
public Var getThisEnclosingJoinPointStaticPartVar() {
throw new RuntimeException("unimplemented");
}
// --- factory methods
public static EclipseShadow makeShadow(EclipseFactory world, ASTNode astNode,
ReferenceContext context)
{
//XXX make sure we're getting the correct declaring type at call-site
if (astNode instanceof AllocationExpression) {
AllocationExpression e = (AllocationExpression)astNode;
return new EclipseShadow(world, Shadow.ConstructorCall,
EclipseFactory.makeResolvedMember(e.binding), astNode, context);
} else if (astNode instanceof MessageSend) {
MessageSend e = (MessageSend)astNode;
if (e.isSuperAccess()) return null; // super calls don't have shadows
return new EclipseShadow(world, Shadow.MethodCall,
EclipseFactory.makeResolvedMember(e.binding), astNode, context);
} else if (astNode instanceof ExplicitConstructorCall) {
//??? these should be ignored, they don't have shadows
return null;
} else if (astNode instanceof AbstractMethodDeclaration) {
AbstractMethodDeclaration e = (AbstractMethodDeclaration)astNode;
Shadow.Kind kind;
if (e instanceof AdviceDeclaration) {
kind = Shadow.AdviceExecution;
} else if (e instanceof InterTypeMethodDeclaration) {
return new EclipseShadow(world, Shadow.MethodExecution,
((InterTypeDeclaration)e).getSignature(), astNode, context);
} else if (e instanceof InterTypeConstructorDeclaration) {
return new EclipseShadow(world, Shadow.ConstructorExecution,
((InterTypeDeclaration)e).getSignature(), astNode, context);
} else if (e instanceof InterTypeFieldDeclaration) {
return null;
} else if (e instanceof MethodDeclaration) {
kind = Shadow.MethodExecution;
} else if (e instanceof ConstructorDeclaration) {
kind = Shadow.ConstructorExecution;
} else if (e instanceof Clinit) {
kind = Shadow.StaticInitialization;
} else {
return null;
//throw new RuntimeException("unimplemented: " + e);
}
return new EclipseShadow(world, kind,
EclipseFactory.makeResolvedMember(e.binding), astNode, context);
} else if (astNode instanceof TypeDeclaration) {
return new EclipseShadow(world, Shadow.StaticInitialization,
new Member(Member.STATIC_INITIALIZATION,
EclipseFactory.fromBinding(((TypeDeclaration)astNode).binding), 0,
ResolvedTypeX.VOID, "<clinit>", TypeX.NONE),
astNode, context);
} else {
return null;
//throw new RuntimeException("unimplemented: " + astNode);
}
}
}
|
73,334
|
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
|
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
|
resolved fixed
|
b133299
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:40:02Z
| 2004-09-06T17:00:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/EclipseSourceLocation.java
|
/* *******************************************************************
* 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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.lookup;
import java.io.File;
import org.aspectj.ajdt.internal.core.builder.EclipseAdapterUtils;
import org.aspectj.bridge.ISourceLocation;
import org.eclipse.jdt.internal.compiler.env.ICompilationUnit;
import org.eclipse.jdt.core.compiler.IProblem;
import org.eclipse.jdt.internal.compiler.CompilationResult;
import org.eclipse.jdt.internal.compiler.problem.ProblemHandler;
public class EclipseSourceLocation implements ISourceLocation {
private static String NO_CONTEXT = "USE_NULL--NO_CONTEXT_AVAILABLE";
CompilationResult result;
int startPos, endPos;
// lazy but final
File file;
int startLine = -1;
int endLine = -1;
int column = -1;
String context;
public EclipseSourceLocation(CompilationResult result, int startPos, int endPos) {
super();
this.result = result;
this.startPos = startPos;
this.endPos = endPos;
}
public CompilationResult getCompilationResult() {
return result;
}
public int getStartPos() {
return startPos;
}
public int getEndPos() {
return endPos;
}
public File getSourceFile() {
if (null == file) {
if ((null == result)
|| (null == result.fileName)
|| (0 == result.fileName.length)) {
file = ISourceLocation.NO_FILE;
} else {
file = new File(new String(result.fileName));
}
}
return file;
}
public int getLine() {
if (-1 == startLine) {
startLine = ProblemHandler.searchLineNumber(result.lineSeparatorPositions, startPos);
}
return startLine;
}
public int getColumn() {
if (-1 == column) {
int lineNumber = getLine();
// JJH added check that lineNumber is in legal range to avoid exceptions
if (0 < lineNumber && lineNumber < result.lineSeparatorPositions.length) {
int lineStart = result.lineSeparatorPositions[lineNumber];
int col = startPos - lineStart; // 1-based
if (0 <= col) {
column = col;
} else {
column = 0;
}
}
}
return column;
}
public int getEndLine() {
if (-1 == endLine) {
endLine = ProblemHandler.searchLineNumber(result.lineSeparatorPositions, endPos);
}
return endLine;
}
public String getContext() {
if (null == context) {
ICompilationUnit compilationUnit = result.compilationUnit;
IProblem[] problems = result.problems;
if ((null == compilationUnit) || (null == problems)
|| (1 != problems.length)) { // ?? which of n>1 problems?
context = NO_CONTEXT;
} else {
context = EclipseAdapterUtils.makeLocationContext(compilationUnit, problems[0]);
}
}
return (NO_CONTEXT == context ? null : context);
}
/** @return String {file:}line{:column} */
public String toString() {
StringBuffer sb = new StringBuffer();
if (getSourceFile() != ISourceLocation.NO_FILE) {
sb.append(getSourceFile().getPath());
sb.append(":");
}
sb.append("" + getLine());
if (getColumn() != 0) {
sb.append(":" + getColumn());
}
return sb.toString();
}
}
|
73,334
|
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
|
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
|
resolved fixed
|
b133299
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:40:02Z
| 2004-09-06T17:00:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/EclipseSourceType.java
|
/* *******************************************************************
* 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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.lookup;
import java.util.*;
import org.aspectj.ajdt.internal.compiler.ast.*;
import org.aspectj.ajdt.internal.core.builder.EclipseSourceContext;
import org.aspectj.bridge.IMessage;
//import org.aspectj.bridge.ISourceLocation;
import org.aspectj.weaver.*;
import org.aspectj.weaver.patterns.PerClause;
import org.aspectj.weaver.patterns.PerSingleton;
import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration;
import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration;
import org.eclipse.jdt.internal.compiler.lookup.*;
/**
* Supports viewing eclipse TypeDeclarations/SourceTypeBindings as a ResolvedTypeX
*
* @author Jim Hugunin
*/
public class EclipseSourceType extends ResolvedTypeX.ConcreteName {
protected ResolvedPointcutDefinition[] declaredPointcuts = null;
protected ResolvedMember[] declaredMethods = null;
protected ResolvedMember[] declaredFields = null;
public List declares = new ArrayList();
public List typeMungers = new ArrayList();
private EclipseFactory factory;
private SourceTypeBinding binding;
private TypeDeclaration declaration;
protected EclipseFactory eclipseWorld() {
return factory;
}
public EclipseSourceType(ResolvedTypeX.Name resolvedTypeX, EclipseFactory factory,
SourceTypeBinding binding, TypeDeclaration declaration)
{
super(resolvedTypeX, true);
this.factory = factory;
this.binding = binding;
this.declaration = declaration;
resolvedTypeX.setSourceContext(new EclipseSourceContext(declaration.compilationResult));
resolvedTypeX.setStartPos(declaration.sourceStart);
resolvedTypeX.setEndPos(declaration.sourceEnd);
}
public boolean isAspect() {
return declaration instanceof AspectDeclaration;
}
public WeaverStateInfo getWeaverState() {
return null;
}
public ResolvedTypeX getSuperclass() {
if (binding.isInterface()) return getResolvedTypeX().getWorld().getCoreType(TypeX.OBJECT);
//XXX what about java.lang.Object
return eclipseWorld().fromEclipse(binding.superclass());
}
public ResolvedTypeX[] getDeclaredInterfaces() {
return eclipseWorld().fromEclipse(binding.superInterfaces());
}
protected void fillDeclaredMembers() {
List declaredPointcuts = new ArrayList();
List declaredMethods = new ArrayList();
List declaredFields = new ArrayList();
binding.methods(); // the important side-effect of this call is to make sure bindings are completed
AbstractMethodDeclaration[] methods = declaration.methods;
if (methods != null) {
for (int i=0, len=methods.length; i < len; i++) {
AbstractMethodDeclaration amd = methods[i];
if (amd == null || amd.ignoreFurtherInvestigation) continue;
if (amd instanceof PointcutDeclaration) {
PointcutDeclaration d = (PointcutDeclaration)amd;
ResolvedPointcutDefinition df = d.makeResolvedPointcutDefinition();
declaredPointcuts.add(df);
} else if (amd instanceof InterTypeDeclaration) {
// these are handled in a separate pass
continue;
} else if (amd instanceof DeclareDeclaration) {
// these are handled in a separate pass
continue;
} else if (amd instanceof AdviceDeclaration) {
// these are ignored during compilation and only used during weaving
continue;
} else {
if (amd.binding == null || !amd.binding.isValidBinding()) continue;
declaredMethods.add(EclipseFactory.makeResolvedMember(amd.binding));
}
}
}
FieldBinding[] fields = binding.fields();
for (int i=0, len=fields.length; i < len; i++) {
FieldBinding f = fields[i];
declaredFields.add(EclipseFactory.makeResolvedMember(f));
}
this.declaredPointcuts = (ResolvedPointcutDefinition[])
declaredPointcuts.toArray(new ResolvedPointcutDefinition[declaredPointcuts.size()]);
this.declaredMethods = (ResolvedMember[])
declaredMethods.toArray(new ResolvedMember[declaredMethods.size()]);
this.declaredFields = (ResolvedMember[])
declaredFields.toArray(new ResolvedMember[declaredFields.size()]);
}
public ResolvedMember[] getDeclaredFields() {
if (declaredFields == null) fillDeclaredMembers();
return declaredFields;
}
public ResolvedMember[] getDeclaredMethods() {
if (declaredMethods == null) fillDeclaredMembers();
return declaredMethods;
}
public ResolvedMember[] getDeclaredPointcuts() {
if (declaredPointcuts == null) fillDeclaredMembers();
return declaredPointcuts;
}
public int getModifiers() {
// only return the real Java modifiers, not the extra eclipse ones
return binding.modifiers & CompilerModifiers.AccJustFlag;
}
public String toString() {
return "EclipseSourceType(" + new String(binding.sourceName()) + ")";
}
//XXX make sure this is applied to classes and interfaces
public void checkPointcutDeclarations() {
ResolvedMember[] pointcuts = getDeclaredPointcuts();
boolean sawError = false;
for (int i=0, len=pointcuts.length; i < len; i++) {
if (pointcuts[i].isAbstract()) {
if (!this.isAspect()) {
eclipseWorld().showMessage(IMessage.ERROR,
"abstract pointcut only allowed in aspect" + pointcuts[i].getName(),
pointcuts[i].getSourceLocation(), null);
sawError = true;
} else if (!binding.isAbstract()) {
eclipseWorld().showMessage(IMessage.ERROR,
"abstract pointcut in concrete aspect" + pointcuts[i],
pointcuts[i].getSourceLocation(), null);
sawError = true;
}
}
for (int j=i+1; j < len; j++) {
if (pointcuts[i].getName().equals(pointcuts[j].getName())) {
eclipseWorld().showMessage(IMessage.ERROR,
"duplicate pointcut name: " + pointcuts[j].getName(),
pointcuts[i].getSourceLocation(), pointcuts[j].getSourceLocation());
sawError = true;
}
}
}
//now check all inherited pointcuts to be sure that they're handled reasonably
if (sawError || !isAspect()) return;
// find all pointcuts that override ones from super and check override is legal
// i.e. same signatures and greater or equal visibility
// find all inherited abstract pointcuts and make sure they're concretized if I'm concrete
// find all inherited pointcuts and make sure they don't conflict
getResolvedTypeX().getExposedPointcuts(); //??? this is an odd construction
}
//???
// public CrosscuttingMembers collectCrosscuttingMembers() {
// return crosscuttingMembers;
// }
// public ISourceLocation getSourceLocation() {
// TypeDeclaration dec = binding.scope.referenceContext;
// return new EclipseSourceLocation(dec.compilationResult, dec.sourceStart, dec.sourceEnd);
// }
public boolean isInterface() {
return binding.isInterface();
}
public PerClause getPerClause() {
//should probably be: ((AspectDeclaration)declaration).perClause;
// but we don't need this level of detail, and working with real per clauses
// at this stage of compilation is not worth the trouble
return new PerSingleton();
}
protected Collection getDeclares() {
return declares;
}
protected Collection getPrivilegedAccesses() {
return Collections.EMPTY_LIST;
}
protected Collection getTypeMungers() {
return typeMungers;
}
public boolean doesNotExposeShadowMungers() {
return true;
}
}
|
73,334
|
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
|
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
|
resolved fixed
|
b133299
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:40:02Z
| 2004-09-06T17:00:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/EclipseTypeMunger.java
|
/* *******************************************************************
* 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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.lookup;
import java.lang.reflect.Modifier;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.weaver.ConcreteTypeMunger;
import org.aspectj.weaver.NewConstructorTypeMunger;
import org.aspectj.weaver.NewFieldTypeMunger;
import org.aspectj.weaver.NewMethodTypeMunger;
import org.aspectj.weaver.ResolvedTypeMunger;
import org.aspectj.weaver.ResolvedTypeX;
//import org.aspectj.weaver.TypeX;
import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration;
import org.eclipse.jdt.internal.compiler.lookup.FieldBinding;
import org.eclipse.jdt.internal.compiler.lookup.MethodBinding;
//import org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding;
import org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding;
public class EclipseTypeMunger extends ConcreteTypeMunger {
private ResolvedTypeX targetTypeX;
//protected ReferenceBinding targetBinding = null;
private AbstractMethodDeclaration sourceMethod;
private EclipseFactory world;
private ISourceLocation sourceLocation;
public EclipseTypeMunger(EclipseFactory world, ResolvedTypeMunger munger, ResolvedTypeX aspectType,
AbstractMethodDeclaration sourceMethod)
{
super(munger, aspectType);
this.world = world;
this.sourceMethod = sourceMethod;
if (sourceMethod != null) {
this.sourceLocation =
new EclipseSourceLocation(sourceMethod.compilationResult,
sourceMethod.sourceStart, sourceMethod.sourceEnd);
// Piece of magic that tells type mungers where they came from.
// Won't be persisted unless ResolvedTypeMunger.persistSourceLocation is true.
munger.setSourceLocation(sourceLocation);
}
targetTypeX = munger.getSignature().getDeclaringType().resolve(world.getWorld());
//targetBinding = (ReferenceBinding)world.makeTypeBinding(targetTypeX);
}
public static boolean supportsKind(ResolvedTypeMunger.Kind kind) {
return kind == ResolvedTypeMunger.Field
|| kind == ResolvedTypeMunger.Method
|| kind == ResolvedTypeMunger.Constructor;
}
public String toString() {
return "(EclipseTypeMunger " + getMunger() + ")";
}
/**
* Modifies signatures of a TypeBinding through its ClassScope,
* i.e. adds Method|FieldBindings, plays with inheritance, ...
*/
public boolean munge(SourceTypeBinding sourceType) {
if (!world.fromEclipse(sourceType).equals(targetTypeX)) return false; //??? move this test elsewhere
//System.out.println("munging: " + sourceType);
// System.out.println("match: " + world.fromEclipse(sourceType) +
// " with " + targetTypeX);
if (munger.getKind() == ResolvedTypeMunger.Field) {
mungeNewField(sourceType, (NewFieldTypeMunger)munger);
} else if (munger.getKind() == ResolvedTypeMunger.Method) {
mungeNewMethod(sourceType, (NewMethodTypeMunger)munger);
} else if (munger.getKind() == ResolvedTypeMunger.Constructor) {
mungeNewConstructor(sourceType, (NewConstructorTypeMunger)munger);
} else {
throw new RuntimeException("unimplemented: " + munger.getKind());
}
return true;
}
private void mungeNewMethod(SourceTypeBinding sourceType, NewMethodTypeMunger munger) {
// if (shouldTreatAsPublic()) {
// MethodBinding binding = world.makeMethodBinding(munger.getSignature());
// findOrCreateInterTypeMemberFinder(classScope).addInterTypeMethod(binding);
// //classScope.referenceContext.binding.addMethod(binding);
// } else {
InterTypeMethodBinding binding =
new InterTypeMethodBinding(world, munger.getSignature(), aspectType, sourceMethod);
findOrCreateInterTypeMemberFinder(sourceType).addInterTypeMethod(binding);
// }
}
private void mungeNewConstructor(SourceTypeBinding sourceType, NewConstructorTypeMunger munger) {
if (shouldTreatAsPublic()) {
MethodBinding binding = world.makeMethodBinding(munger.getSignature());
findOrCreateInterTypeMemberFinder(sourceType).addInterTypeMethod(binding);
//classScope.referenceContext.binding.addMethod(binding);
} else {
InterTypeMethodBinding binding =
new InterTypeMethodBinding(world, munger.getSignature(), aspectType, sourceMethod);
findOrCreateInterTypeMemberFinder(sourceType).addInterTypeMethod(binding);
}
}
private void mungeNewField(SourceTypeBinding sourceType, NewFieldTypeMunger munger) {
if (shouldTreatAsPublic() && !targetTypeX.isInterface()) {
FieldBinding binding = world.makeFieldBinding(munger.getSignature());
findOrCreateInterTypeMemberFinder(sourceType).addInterTypeField(binding);
//classScope.referenceContext.binding.addField(binding);
} else {
InterTypeFieldBinding binding =
new InterTypeFieldBinding(world, munger.getSignature(), aspectType, sourceMethod);
findOrCreateInterTypeMemberFinder(sourceType).addInterTypeField(binding);
}
}
private boolean shouldTreatAsPublic() {
//??? this is where we could fairly easily choose to treat package-protected
//??? introductions like public ones when the target type and the aspect
//??? are in the same package
return Modifier.isPublic(munger.getSignature().getModifiers());
}
private InterTypeMemberFinder findOrCreateInterTypeMemberFinder(SourceTypeBinding sourceType) {
InterTypeMemberFinder finder =
(InterTypeMemberFinder)sourceType.memberFinder;
if (finder == null) {
finder = new InterTypeMemberFinder();
sourceType.memberFinder = finder;
finder.sourceTypeBinding = sourceType;
}
return finder;
}
public ISourceLocation getSourceLocation() {
return sourceLocation;
}
public void setSourceLocation(ISourceLocation sourceLocation) {
this.sourceLocation = sourceLocation;
}
/**
* @return AbstractMethodDeclaration
*/
public AbstractMethodDeclaration getSourceMethod() {
return sourceMethod;
}
}
|
73,334
|
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
|
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
|
resolved fixed
|
b133299
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:40:02Z
| 2004-09-06T17:00:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/HelperInterfaceBinding.java
|
/* *******************************************************************
* 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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.lookup;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.TypeX;
import org.eclipse.jdt.internal.compiler.ClassFile;
import org.eclipse.jdt.internal.compiler.CompilationResult;
import org.eclipse.jdt.internal.compiler.lookup.ClassScope;
import org.eclipse.jdt.internal.compiler.lookup.FieldBinding;
import org.eclipse.jdt.internal.compiler.lookup.MethodBinding;
import org.eclipse.jdt.internal.compiler.lookup.PackageBinding;
import org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding;
import org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding;
public class HelperInterfaceBinding extends SourceTypeBinding {
private TypeX typeX;
SourceTypeBinding enclosingType;
List methods = new ArrayList();
public HelperInterfaceBinding(SourceTypeBinding enclosingType, TypeX typeX) {
super();
this.fPackage = enclosingType.fPackage;
//this.fileName = scope.referenceCompilationUnit().getFileName();
this.modifiers = AccPublic | AccInterface;
this.sourceName = enclosingType.scope.referenceContext.name;
this.enclosingType = enclosingType;
this.typeX = typeX;
this.scope = enclosingType.scope;
}
public HelperInterfaceBinding(
char[][] compoundName,
PackageBinding fPackage,
ClassScope scope) {
super(compoundName, fPackage, scope);
}
public char[] getFileName() {
return enclosingType.getFileName();
}
public TypeX getTypeX() {
return typeX;
}
public void addMethod(EclipseFactory world , ResolvedMember member) {
MethodBinding binding = world.makeMethodBinding(member);
this.methods.add(binding);
}
public FieldBinding[] fields() { return new FieldBinding[0]; }
public MethodBinding[] methods() { return new MethodBinding[0]; }
public char[] constantPoolName() {
String sig = typeX.getSignature();
return sig.substring(1, sig.length()-1).toCharArray();
}
public void generateClass(CompilationResult result, ClassFile enclosingClassFile) {
ClassFile classFile = new ClassFile(this, enclosingClassFile, false);
classFile.addFieldInfos();
classFile.setForMethodInfos();
for (Iterator i = methods.iterator(); i.hasNext(); ) {
MethodBinding b = (MethodBinding)i.next();
generateMethod(classFile, b);
}
classFile.addAttributes();
result.record(this.constantPoolName(), classFile);
}
private void generateMethod(ClassFile classFile, MethodBinding binding) {
classFile.generateMethodInfoHeader(binding);
int methodAttributeOffset = classFile.contentsOffset;
int attributeNumber = classFile.generateMethodInfoAttribute(binding);
classFile.completeMethodInfo(methodAttributeOffset, attributeNumber);
}
public ReferenceBinding[] superInterfaces() {
return new ReferenceBinding[0];
}
}
|
73,334
|
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
|
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
|
resolved fixed
|
b133299
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:40:02Z
| 2004-09-06T17:00:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/InlineAccessFieldBinding.java
|
/* *******************************************************************
* 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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.lookup;
import org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration;
import org.aspectj.weaver.AjcMemberMaker;
import org.aspectj.weaver.ResolvedMember;
import org.eclipse.jdt.internal.compiler.ast.ASTNode;
import org.eclipse.jdt.internal.compiler.lookup.FieldBinding;
import org.eclipse.jdt.internal.compiler.lookup.InvocationSite;
import org.eclipse.jdt.internal.compiler.lookup.Scope;
import org.eclipse.jdt.internal.compiler.lookup.SyntheticAccessMethodBinding;
import org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
/**
* Used for field references within the body of an around advice
* to force the use of public access methods. This makes it possible
* for around advice to be inlined into any shadow to which it applies.
*
* ??? this is very similar to PrivilegedFieldBinding and is somewhat related
* to InterTypeFieldBinding. Maybe they have a common supertype?
*
* @author Jim Hugunin
*/
public class InlineAccessFieldBinding extends FieldBinding {
public SimpleSyntheticAccessMethodBinding reader;
public SimpleSyntheticAccessMethodBinding writer;
public FieldBinding baseField;
public InlineAccessFieldBinding(AspectDeclaration inAspect, FieldBinding baseField, ResolvedMember resolvedField) {
super(baseField, baseField.declaringClass);
this.reader = new SimpleSyntheticAccessMethodBinding(
inAspect.factory.makeMethodBinding(
AjcMemberMaker.inlineAccessMethodForFieldGet(
inAspect.typeX, resolvedField
)));
this.writer = new SimpleSyntheticAccessMethodBinding(inAspect.factory.makeMethodBinding(
AjcMemberMaker.inlineAccessMethodForFieldSet(
inAspect.typeX, resolvedField
)));
this.constant = ASTNode.NotAConstant;
this.baseField = baseField;
}
public boolean canBeSeenBy(TypeBinding receiverType, InvocationSite invocationSite, Scope scope) {
return true;
}
public SyntheticAccessMethodBinding getAccessMethod(boolean isReadAccess) {
if (isReadAccess) return reader;
else return writer;
}
public boolean alwaysNeedsAccessMethod(boolean isReadAccess) { return true; }
public FieldBinding getFieldBindingForLookup() { return baseField; }
public String toString() { return "InlineAccess(" + baseField + ")"; }
}
|
73,334
|
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
|
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
|
resolved fixed
|
b133299
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:40:02Z
| 2004-09-06T17:00:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/InterTypeFieldBinding.java
|
/* *******************************************************************
* 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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.lookup;
import org.aspectj.weaver.AjcMemberMaker;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.TypeX;
import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration;
import org.eclipse.jdt.internal.compiler.lookup.FieldBinding;
import org.eclipse.jdt.internal.compiler.lookup.InvocationSite;
import org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding;
import org.eclipse.jdt.internal.compiler.lookup.Scope;
import org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding;
import org.eclipse.jdt.internal.compiler.lookup.SyntheticAccessMethodBinding;
import org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
public class InterTypeFieldBinding extends FieldBinding {
public ReferenceBinding targetType;
public SyntheticAccessMethodBinding reader;
public SyntheticAccessMethodBinding writer;
public AbstractMethodDeclaration sourceMethod;
public InterTypeFieldBinding(EclipseFactory world, ResolvedMember signature, TypeX withinType,
AbstractMethodDeclaration sourceMethod)
{
super(world.makeFieldBinding(signature), null);
this.sourceMethod = sourceMethod;
targetType = (ReferenceBinding)world.makeTypeBinding(signature.getDeclaringType());
this.declaringClass = (ReferenceBinding)world.makeTypeBinding(withinType);
reader = new SimpleSyntheticAccessMethodBinding(world.makeMethodBinding(
AjcMemberMaker.interFieldGetDispatcher(signature, withinType)
));
writer = new SimpleSyntheticAccessMethodBinding(world.makeMethodBinding(
AjcMemberMaker.interFieldSetDispatcher(signature, withinType)
));
}
public boolean canBeSeenBy(TypeBinding receiverType, InvocationSite invocationSite, Scope scope) {
scope.compilationUnitScope().recordTypeReference(declaringClass);
//System.err.println("canBeSeenBy: " + this + ", " + isPublic());
if (isPublic()) return true;
SourceTypeBinding invocationType = scope.invocationType();
//System.out.println("receiver: " + receiverType + ", " + invocationType);
if (invocationType == declaringClass) return true;
// if (invocationType.isPrivileged) {
// System.out.println("privileged access to: " + this);
// return true;
// }
if (isProtected()) {
throw new RuntimeException("unimplemented");
}
//XXX make sure this walks correctly
if (isPrivate()) {
// answer true if the receiverType is the declaringClass
// AND the invocationType and the declaringClass have a common enclosingType
if (receiverType != declaringClass) return false;
if (invocationType != declaringClass) {
ReferenceBinding outerInvocationType = invocationType;
ReferenceBinding temp = outerInvocationType.enclosingType();
while (temp != null) {
outerInvocationType = temp;
temp = temp.enclosingType();
}
ReferenceBinding outerDeclaringClass = declaringClass;
temp = outerDeclaringClass.enclosingType();
while (temp != null) {
outerDeclaringClass = temp;
temp = temp.enclosingType();
}
if (outerInvocationType != outerDeclaringClass) return false;
}
return true;
}
// isDefault()
if (invocationType.fPackage == declaringClass.fPackage) return true;
return false;
}
public SyntheticAccessMethodBinding getAccessMethod(boolean isReadAccess) {
if (isReadAccess) return reader;
else return writer;
}
public boolean alwaysNeedsAccessMethod(boolean isReadAccess) { return true; }
public ReferenceBinding getTargetType() {
return targetType;
}
}
|
73,334
|
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
|
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
|
resolved fixed
|
b133299
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:40:02Z
| 2004-09-06T17:00:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/InterTypeMemberFinder.java
|
/* *******************************************************************
* 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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.lookup;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.eclipse.jdt.internal.compiler.lookup.FieldBinding;
import org.eclipse.jdt.internal.compiler.lookup.IMemberFinder;
import org.eclipse.jdt.internal.compiler.lookup.InvocationSite;
import org.eclipse.jdt.internal.compiler.lookup.MethodBinding;
import org.eclipse.jdt.internal.compiler.lookup.ProblemFieldBinding;
import org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding;
import org.eclipse.jdt.internal.compiler.lookup.Scope;
import org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding;
import org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
import org.eclipse.jdt.internal.compiler.problem.ProblemReporter;
import org.eclipse.jdt.core.compiler.CharOperation;
public class InterTypeMemberFinder implements IMemberFinder {
private List interTypeFields = new ArrayList();
private List interTypeMethods = new ArrayList();
public SourceTypeBinding sourceTypeBinding;
public FieldBinding getField(
SourceTypeBinding sourceTypeBinding,
char[] fieldName,
InvocationSite site,
Scope scope)
{
FieldBinding retField = sourceTypeBinding.getFieldBase(fieldName, true); // XXX may need to get the correct value for second parameter in the future (see #55341)
if (interTypeFields.isEmpty()) return retField;
int fieldLength = fieldName.length;
for (int i=0, len=interTypeFields.size(); i < len; i++) {
FieldBinding field = (FieldBinding)interTypeFields.get(i);
if (field.name.length == fieldLength && CharOperation.prefixEquals(field.name, fieldName)) {
retField = resolveConflicts(sourceTypeBinding, retField, field, site, scope);
}
}
return retField;
}
private FieldBinding resolveConflicts(
SourceTypeBinding sourceTypeBinding,
FieldBinding retField,
FieldBinding field,
InvocationSite site,
Scope scope)
{
if (retField == null) return field;
if (site != null) {
if (!field.canBeSeenBy(sourceTypeBinding, site, scope)) return retField;
if (!retField.canBeSeenBy(sourceTypeBinding, site, scope)) return field;
}
//XXX need dominates check on aspects
return new ProblemFieldBinding(retField.declaringClass, retField.name, ProblemReporter.Ambiguous);
}
// private void reportConflicts(SourceTypeBinding sourceTypeBinding,
// MethodBinding m1, MethodBinding m2)
// {
// if (m1 == m2) {
// System.err.println("odd that we're ecomparing the same: " + m1);
// return;
// }
//
// if (!m1.areParametersEqual(m2)) return;
// if (m1 instanceof InterTypeMethodBinding) {
// if (m2 instanceof InterTypeMethodBinding) {
// reportConflictsBoth(sourceTypeBinding,
// (InterTypeMethodBinding)m1,
// (InterTypeMethodBinding)m2);
// } else {
// reportConflictsOne(sourceTypeBinding,
// (InterTypeMethodBinding)m1,
// m2);
// }
// } else if (m2 instanceof InterTypeMethodBinding) {
// reportConflictsOne(sourceTypeBinding,
// (InterTypeMethodBinding)m2,
// m1);
// } else {
// reportConflictsNone(sourceTypeBinding,
// m2,
// m1);
// }
// }
// private void reportConflicts(
// SourceTypeBinding sourceTypeBinding,
// MethodBinding m1,
// MethodBinding m2)
// {
// //System.err.println("compare: " + m1 + " with " + m2);
//
// if (m1 == m2) {
// System.err.println("odd that we're ecomparing the same: " + m1);
// return;
// }
//
// if (!m1.areParametersEqual(m2)) return;
//
// //System.err.println("t1: " + getTargetType(m1) + ", " + getTargetType(m2));
//
// if (getTargetType(m1) != getTargetType(m2)) return;
//
// if (m1.declaringClass == m2.declaringClass) {
// duplicateMethodBinding(m1, m2);
// return;
// }
//
//
// if (m1.isPublic() || m2.isPublic()) {
// duplicateMethodBinding(m1, m2);
// return;
// }
//
// // handle the wierd case where the aspect is a subtype of the target
// if (m2.isProtected()) {
// if (m2.declaringClass.isSuperclassOf(m1.declaringClass)) {
// duplicateMethodBinding(m1, m2);
// }
// // don't return because we also want to do the package test
// }
//
// if (!m1.isPrivate() || !m2.isPrivate()) {
// // at least package visible
// if (m1.declaringClass.getPackage() == m2.declaringClass.getPackage()) {
// duplicateMethodBinding(m1, m2);
// }
// return;
// }
//
// //XXX think about inner types some day
// }
////
private boolean isVisible(MethodBinding m1, ReferenceBinding s) {
if (m1.declaringClass == s) return true;
if (m1.isPublic()) return true;
//don't need to handle protected
//if (m1.isProtected()) {
if (!m1.isPrivate()) {
// at least package visible
return (m1.declaringClass.getPackage() == s.getPackage());
}
return false;
}
//
// private void duplicateMethodBinding(MethodBinding m1, MethodBinding m2) {
// ReferenceBinding t1 = m1.declaringClass;
// ReferenceBinding t2 = m2.declaringClass;
//
//
//
//
//
//
// if (!(t1 instanceof SourceTypeBinding) || !(t2 instanceof SourceTypeBinding)) {
// throw new RuntimeException("unimplemented");
// }
//
// SourceTypeBinding s1 = (SourceTypeBinding)t1;
// SourceTypeBinding s2 = (SourceTypeBinding)t2;
//
// if (m1.sourceMethod() != null) {
// s1.scope.problemReporter().duplicateMethodInType(s2, m1.sourceMethod());
// }
// if (m2.sourceMethod() != null) {
// s2.scope.problemReporter().duplicateMethodInType(s1, m2.sourceMethod());
// }
// }
// private void reportConflictsNone(
// SourceTypeBinding sourceTypeBinding,
// MethodBinding m2,
// MethodBinding m1)
// {
// throw new RuntimeException("not possible");
// }
// ReferenceBinding t1 = getDeclaringClass(m1);
// //.declaringClass;
// ReferenceBinding t2 = getDeclaringClass(m2);
// //.declaringClass;
//
// if (t1 == t2) {
// AbstractMethodDeclaration methodDecl = m2.sourceMethod(); // cannot be retrieved after binding is lost
// System.err.println("duplicate: " + t1 + ", " + t2);
// sourceTypeBinding.scope.problemReporter().duplicateMethodInType(sourceTypeBinding, methodDecl);
// methodDecl.binding = null;
// //methods[m] = null; //XXX duplicate problem reports
// return;
// }
//
// if (!(t1 instanceof SourceTypeBinding) || !(t2 instanceof SourceTypeBinding)) {
// throw new RuntimeException("unimplemented");
// }
//
// SourceTypeBinding s1 = (SourceTypeBinding)t1;
// SourceTypeBinding s2 = (SourceTypeBinding)t2;
//
//
// if (m1.canBeSeenBy(s1, null, s2.scope) || m2.canBeSeenBy(s2, null, s1.scope)) {
// s1.scope.problemReporter().duplicateMethodInType(s2, m1.sourceMethod());
// s2.scope.problemReporter().duplicateMethodInType(s1, m2.sourceMethod());
// }
// }
// private ReferenceBinding getTargetType(MethodBinding m2) {
// if (m2 instanceof InterTypeMethodBinding) {
// return ((InterTypeMethodBinding)m2).getTargetType();
// }
//
// return m2.declaringClass;
// }
//XXX conflicts
public MethodBinding[] getMethods(
SourceTypeBinding sourceTypeBinding,
char[] selector) {
// System.err.println("getMethods: " + new String(sourceTypeBinding.signature()) +
// ", " + new String(selector));
MethodBinding[] orig = sourceTypeBinding.getMethodsBase(selector);
if (interTypeMethods.isEmpty()) return orig;
List ret = new ArrayList(Arrays.asList(orig));
// System.err.println("declared method: " + ret + " inters = " + interTypeMethods);
for (int i=0, len=interTypeMethods.size(); i < len; i++) {
MethodBinding method = (MethodBinding)interTypeMethods.get(i);
if (CharOperation.equals(selector, method.selector)) {
ret.add(method);
}
}
if (ret.isEmpty()) return SourceTypeBinding.NoMethods;
// System.err.println("method: " + ret);
// check for conflicts
// int len = ret.size();
// if (len > 1) {
// for (int i=0; i <len; i++) {
// MethodBinding m1 = (MethodBinding)ret.get(i);
// for (int j=i+1; j < len; j++) {
// MethodBinding m2 = (MethodBinding)ret.get(j);
// //reportConflicts(sourceTypeBinding, m1, m2);
// }
// }
// }
//System.err.println("got methods: " + ret + " on " + sourceTypeBinding);
return (MethodBinding[])ret.toArray(new MethodBinding[ret.size()]);
}
public MethodBinding getExactMethod(
SourceTypeBinding sourceTypeBinding,
char[] selector,
TypeBinding[] argumentTypes)
{
MethodBinding ret = sourceTypeBinding.getExactMethodBase(selector, argumentTypes);
// An intertype declaration may override an inherited member (Bug#50776)
for (int i=0, len=interTypeMethods.size(); i < len; i++) {
MethodBinding im =
(MethodBinding)interTypeMethods.get(i);
if (matches(im, selector, argumentTypes)) {
return im;
}
}
return ret;
}
// if (isVisible(im, sourceTypeBinding)) {
// if (ret == null) {
// ret = im;
// } else {
// ret = resolveOverride(ret, im);
// }
// }
// }
// }
// return ret;
// }
// private MethodBinding resolveOverride(MethodBinding m1, MethodBinding m2) {
// ReferenceBinding t1 = getTargetType(m1);
// ReferenceBinding t2 = getTargetType(m2);
// if (t1 == t2) {
// //XXX also need a test for completely matching sigs
// if (m1.isAbstract()) return m2;
// else if (m2.isAbstract()) return m1;
//
//
// if (m1 instanceof InterTypeMethodBinding) {
// //XXX need to handle dominates here
// EclipseWorld world = EclipseWorld.fromScopeLookupEnvironment(sourceTypeBinding.scope);
// int cmp = compareAspectPrecedence(world.fromEclipse(m1.declaringClass),
// world.fromEclipse(m2.declaringClass));
// if (cmp < 0) return m2;
// else if (cmp > 0) return m1;
// }
//
// duplicateMethodBinding(m1, m2);
// return null;
// }
// if (t1.isSuperclassOf(t2)) {
// return m2;
// }
// if (t2.isSuperclassOf(t1)) {
// return m1;
// }
//
// duplicateMethodBinding(m1, m2);
// return null;
// }
// private int compareAspectPrecedence(ResolvedTypeX a1, ResolvedTypeX a2) {
// World world = a1.getWorld();
// int ret = world.compareByDominates(a1, a2);
// if (ret == 0) {
// if (a1.isAssignableFrom(a2)) return -1;
// if (a2.isAssignableFrom(a1)) return +1;
// }
// return ret;
// }
//
private boolean matches(MethodBinding m1, MethodBinding m2) {
return matches(m1, m2.selector, m2.parameters);
// &&
// (isVisible(m1, m2.declaringClass) || isVisible(m2, m1.declaringClass));
}
private boolean matches(MethodBinding method, char[] selector, TypeBinding[] argumentTypes) {
if (!CharOperation.equals(selector, method.selector)) return false;
int argCount = argumentTypes.length;
if (method.parameters.length != argCount) return false;
TypeBinding[] toMatch = method.parameters;
for (int p = 0; p < argCount; p++) {
if (toMatch[p] != argumentTypes[p]) return false;
}
return true;
}
public void addInterTypeField(FieldBinding binding) {
//System.err.println("adding: " + binding + " to " + this);
interTypeFields.add(binding);
}
public void addInterTypeMethod(MethodBinding binding) {
// check for conflicts with existing methods, should really check type as well...
//System.err.println("adding: " + binding + " to " + sourceTypeBinding);
if (isVisible(binding, sourceTypeBinding)) {
MethodBinding[] baseMethods = sourceTypeBinding.methods;
for (int i=0, len=baseMethods.length; i < len; i++) {
MethodBinding b = baseMethods[i];
if (matches(binding, b)) {
// this always means we should remove the existing method
if (b.sourceMethod() != null) {
b.sourceMethod().binding = null;
}
sourceTypeBinding.removeMethod(i);
//System.err.println(" left: " + Arrays.asList(sourceTypeBinding.methods));
break;
}
}
}
interTypeMethods.add(binding);
}
}
|
73,334
|
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
|
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
|
resolved fixed
|
b133299
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:40:02Z
| 2004-09-06T17:00:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/InterTypeMethodBinding.java
|
/* *******************************************************************
* 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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.lookup;
import org.aspectj.weaver.AjcMemberMaker;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.TypeX;
import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration;
import org.eclipse.jdt.internal.compiler.lookup.InvocationSite;
import org.eclipse.jdt.internal.compiler.lookup.MethodBinding;
import org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding;
import org.eclipse.jdt.internal.compiler.lookup.Scope;
import org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding;
import org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
public class InterTypeMethodBinding extends MethodBinding {
private ReferenceBinding targetType;
private MethodBinding syntheticMethod;
public MethodBinding postDispatchMethod;
public AbstractMethodDeclaration sourceMethod;
public InterTypeMethodBinding(EclipseFactory world, ResolvedMember signature, TypeX withinType,
AbstractMethodDeclaration sourceMethod)
{
super(world.makeMethodBinding(signature), null);
this.sourceMethod = sourceMethod;
targetType = (ReferenceBinding)world.makeTypeBinding(signature.getDeclaringType());
this.declaringClass = (ReferenceBinding)world.makeTypeBinding(withinType);
if (signature.getKind() == Member.METHOD) {
syntheticMethod =
world.makeMethodBinding(AjcMemberMaker.interMethodDispatcher(signature, withinType));
postDispatchMethod =
world.makeMethodBinding(AjcMemberMaker.interMethodBody(signature, withinType));
} else {
syntheticMethod = world.makeMethodBinding(
AjcMemberMaker.interConstructor(world.getWorld().resolve(signature.getDeclaringType()),
signature, withinType));
postDispatchMethod = syntheticMethod;
}
}
//XXX this is identical to InterTypeFieldBinding
public boolean canBeSeenBy(TypeBinding receiverType, InvocationSite invocationSite, Scope scope) {
scope.compilationUnitScope().recordTypeReference(declaringClass);
if (isPublic()) return true;
SourceTypeBinding invocationType = scope.invocationType();
//System.out.println("receiver: " + receiverType + ", " + invocationType);
if (invocationType == declaringClass) return true;
// if (invocationType.isPrivileged) {
// System.out.println("privileged access to: " + this);
// return true;
// }
if (isProtected()) {
throw new RuntimeException("unimplemented");
}
//XXX make sure this walks correctly
if (isPrivate()) {
// answer true if the receiverType is the declaringClass
// AND the invocationType and the declaringClass have a common enclosingType
//if (receiverType != declaringClass) return false;
if (invocationType != declaringClass) {
ReferenceBinding outerInvocationType = invocationType;
ReferenceBinding temp = outerInvocationType.enclosingType();
while (temp != null) {
outerInvocationType = temp;
temp = temp.enclosingType();
}
ReferenceBinding outerDeclaringClass = declaringClass;
temp = outerDeclaringClass.enclosingType();
while (temp != null) {
outerDeclaringClass = temp;
temp = temp.enclosingType();
}
//System.err.println("outer dec: " +
if (outerInvocationType != outerDeclaringClass) return false;
}
return true;
}
// isDefault()
if (invocationType.fPackage == declaringClass.fPackage) return true;
return false;
}
public MethodBinding getAccessMethod(boolean staticReference) {
if (staticReference) return postDispatchMethod;
else return syntheticMethod;
}
public boolean alwaysNeedsAccessMethod() { return true; }
public AbstractMethodDeclaration sourceMethod() {
return sourceMethod;
}
public ReferenceBinding getTargetType() {
return targetType;
}
public String toString() {
return "InterTypeMethodBinding(" + super.toString() + ", " + getTargetType() +")";
}
}
|
73,334
|
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
|
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
|
resolved fixed
|
b133299
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:40:02Z
| 2004-09-06T17:00:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/InterTypeScope.java
|
/* *******************************************************************
* 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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.lookup;
import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration;
import org.eclipse.jdt.internal.compiler.lookup.ClassScope;
import org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding;
import org.eclipse.jdt.internal.compiler.lookup.Scope;
import org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding;
public class InterTypeScope extends ClassScope {
ReferenceBinding onType;
public InterTypeScope(Scope parent, ReferenceBinding onType) {
super(parent, null);
referenceContext = new TypeDeclaration(null);
referenceContext.binding = makeSourceTypeBinding(onType);
this.onType = onType;
}
// this method depends on the fact that BinaryTypeBinding extends SourceTypeBinding
private SourceTypeBinding makeSourceTypeBinding(ReferenceBinding onType) {
if (onType instanceof SourceTypeBinding) return (SourceTypeBinding)onType;
else throw new RuntimeException("can't handle: " + onType);
}
public SourceTypeBinding invocationType() {
return parent.enclosingSourceType();
}
public int addDepth() {
return 0;
}
}
|
73,334
|
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
|
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
|
resolved fixed
|
b133299
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:40:02Z
| 2004-09-06T17:00:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/PointcutBinding.java
|
/* *******************************************************************
* 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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.lookup;
import org.eclipse.jdt.internal.compiler.lookup.Binding;
/**
*/
public class PointcutBinding extends Binding {
/**
* @see org.eclipse.jdt.internal.compiler.lookup.Binding#bindingType()
*/
public int bindingType() {
return 0;
}
/**
* @see org.eclipse.jdt.internal.compiler.lookup.Binding#readableName()
*/
public char[] readableName() {
return null;
}
}
|
73,334
|
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
|
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
|
resolved fixed
|
b133299
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:40:02Z
| 2004-09-06T17:00:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/PrivilegedFieldBinding.java
|
/* *******************************************************************
* 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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.lookup;
import org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration;
import org.aspectj.weaver.AjcMemberMaker;
import org.eclipse.jdt.internal.compiler.ast.ASTNode;
import org.eclipse.jdt.internal.compiler.lookup.FieldBinding;
import org.eclipse.jdt.internal.compiler.lookup.InvocationSite;
import org.eclipse.jdt.internal.compiler.lookup.Scope;
import org.eclipse.jdt.internal.compiler.lookup.SyntheticAccessMethodBinding;
import org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
public class PrivilegedFieldBinding extends FieldBinding {
public SimpleSyntheticAccessMethodBinding reader;
public SimpleSyntheticAccessMethodBinding writer;
public FieldBinding baseField;
public PrivilegedFieldBinding(AspectDeclaration inAspect, FieldBinding baseField) {
super(baseField, baseField.declaringClass);
this.reader = new SimpleSyntheticAccessMethodBinding(
inAspect.factory.makeMethodBinding(
AjcMemberMaker.privilegedAccessMethodForFieldGet(
inAspect.typeX, EclipseFactory.makeResolvedMember(baseField)
)));
this.writer = new SimpleSyntheticAccessMethodBinding(inAspect.factory.makeMethodBinding(
AjcMemberMaker.privilegedAccessMethodForFieldSet(
inAspect.typeX, EclipseFactory.makeResolvedMember(baseField)
)));
this.constant = ASTNode.NotAConstant;
this.baseField = baseField;
}
public boolean canBeSeenBy(TypeBinding receiverType, InvocationSite invocationSite, Scope scope) {
return true;
}
public SyntheticAccessMethodBinding getAccessMethod(boolean isReadAccess) {
if (baseField.alwaysNeedsAccessMethod(isReadAccess)) {
return baseField.getAccessMethod(isReadAccess);
}
if (isReadAccess) return reader;
else return writer;
}
public boolean alwaysNeedsAccessMethod(boolean isReadAccess) { return true; }
public FieldBinding getFieldBindingForLookup() { return baseField; }
public String toString() { return "PrivilegedWrapper(" + baseField + ")"; }
// public ReferenceBinding getTargetType() {
// return introducedField.declaringClass;
// }
}
|
73,334
|
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
|
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
|
resolved fixed
|
b133299
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:40:02Z
| 2004-09-06T17:00:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/PrivilegedHandler.java
|
/* *******************************************************************
* 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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.lookup;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration;
import org.aspectj.ajdt.internal.compiler.ast.AstUtil;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.weaver.AjcMemberMaker;
import org.aspectj.weaver.Lint;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedTypeX;
import org.aspectj.weaver.TypeX;
import org.aspectj.weaver.World;
import org.eclipse.jdt.internal.compiler.ast.ASTNode;
import org.eclipse.jdt.internal.compiler.lookup.FieldBinding;
import org.eclipse.jdt.internal.compiler.lookup.IPrivilegedHandler;
import org.eclipse.jdt.internal.compiler.lookup.MethodBinding;
import org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding;
public class PrivilegedHandler implements IPrivilegedHandler {
private AspectDeclaration inAspect;
private Map accessors = new HashMap();
public PrivilegedHandler(AspectDeclaration inAspect) {
this.inAspect = inAspect;
}
public FieldBinding getPrivilegedAccessField(FieldBinding baseField, ASTNode location) {
ResolvedMember key = EclipseFactory.makeResolvedMember(baseField);
if (accessors.containsKey(key)) return (FieldBinding)accessors.get(key);
FieldBinding ret = new PrivilegedFieldBinding(inAspect, baseField);
checkWeaveAccess(key.getDeclaringType(), location);
if (!baseField.alwaysNeedsAccessMethod(true)) accessors.put(key, ret);
return ret;
}
public MethodBinding getPrivilegedAccessMethod(MethodBinding baseMethod, ASTNode location) {
if (baseMethod.alwaysNeedsAccessMethod()) return baseMethod;
ResolvedMember key = EclipseFactory.makeResolvedMember(baseMethod);
if (accessors.containsKey(key)) return (MethodBinding)accessors.get(key);
MethodBinding ret;
if (baseMethod.isConstructor()) {
ret = new MethodBinding(baseMethod, baseMethod.declaringClass);
ret.modifiers = AstUtil.makePublic(ret.modifiers);
} else {
ret = inAspect.factory.makeMethodBinding(
AjcMemberMaker.privilegedAccessMethodForMethod(inAspect.typeX, key)
);
}
checkWeaveAccess(key.getDeclaringType(), location);
//System.err.println(ret);
//Thread.dumpStack();
accessors.put(key, ret);
return ret;
}
public void notePrivilegedTypeAccess(ReferenceBinding type, ASTNode location) {
ResolvedMember key =
new ResolvedMember(Member.STATIC_INITIALIZATION,
inAspect.factory.fromEclipse(type), 0, ResolvedTypeX.VOID, "", TypeX.NONE);
checkWeaveAccess(key.getDeclaringType(), location);
accessors.put(key, key);
}
private void checkWeaveAccess(TypeX typeX, ASTNode location) {
World world = inAspect.factory.getWorld();
Lint.Kind check = world.getLint().typeNotExposedToWeaver;
if (check.isEnabled()) {
if (!world.resolve(typeX).isExposedToWeaver()) {
ISourceLocation loc = null;
if (location != null) {
loc = new EclipseSourceLocation(inAspect.compilationResult,
location.sourceStart, location.sourceEnd);
}
check.signal(typeX.getName() + " (needed for privileged access)",
loc);
}
}
}
public ResolvedMember[] getMembers() {
Collection m = accessors.keySet();
int len = m.size();
ResolvedMember[] ret = new ResolvedMember[len];
int index = 0;
for (Iterator i = m.iterator(); i.hasNext(); ) {
ret[index++] = (ResolvedMember)i.next();
}
return ret;
}
}
|
73,334
|
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
|
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
|
resolved fixed
|
b133299
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:40:02Z
| 2004-09-06T17:00:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/SimpleSyntheticAccessMethodBinding.java
|
/* *******************************************************************
* 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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.lookup;
import org.eclipse.jdt.internal.compiler.lookup.MethodBinding;
import org.eclipse.jdt.internal.compiler.lookup.SyntheticAccessMethodBinding;
public class SimpleSyntheticAccessMethodBinding extends SyntheticAccessMethodBinding {
public SimpleSyntheticAccessMethodBinding(MethodBinding method) {
super(method);
this.declaringClass = method.declaringClass;
// this.selector = method.selector;
// this.modifiers = method.modifiers;
// this.parameters = method.parameters;
// this.returnType = method.returnType;
}
}
|
73,334
|
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
|
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
|
resolved fixed
|
b133299
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:40:02Z
| 2004-09-06T17:00:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/parser/DeclarationFactory.java
|
/*******************************************************************************
* Copyright (c) 2002,2003 Palo Alto Research Center, Incorporated (PARC).
* Copyright (c) 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* IBM Corporation
*******************************************************************************/
package org.aspectj.ajdt.internal.compiler.parser;
import org.aspectj.ajdt.internal.compiler.ast.AdviceDeclaration;
import org.aspectj.ajdt.internal.compiler.ast.AjConstructorDeclaration;
import org.aspectj.ajdt.internal.compiler.ast.AjMethodDeclaration;
import org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration;
import org.aspectj.ajdt.internal.compiler.ast.DeclareDeclaration;
import org.aspectj.ajdt.internal.compiler.ast.IfPseudoToken;
import org.aspectj.ajdt.internal.compiler.ast.InterTypeConstructorDeclaration;
import org.aspectj.ajdt.internal.compiler.ast.InterTypeDeclaration;
import org.aspectj.ajdt.internal.compiler.ast.InterTypeFieldDeclaration;
import org.aspectj.ajdt.internal.compiler.ast.InterTypeMethodDeclaration;
import org.aspectj.ajdt.internal.compiler.ast.PointcutDeclaration;
import org.aspectj.ajdt.internal.compiler.ast.PointcutDesignator;
import org.aspectj.ajdt.internal.compiler.ast.Proceed;
import org.aspectj.ajdt.internal.compiler.ast.PseudoToken;
import org.aspectj.ajdt.internal.compiler.ast.PseudoTokens;
import org.aspectj.ajdt.internal.core.builder.EclipseSourceContext;
import org.aspectj.weaver.AdviceKind;
import org.aspectj.weaver.patterns.Declare;
import org.eclipse.jdt.internal.compiler.CompilationResult;
import org.eclipse.jdt.internal.compiler.ast.ASTNode;
import org.eclipse.jdt.internal.compiler.ast.Argument;
import org.eclipse.jdt.internal.compiler.ast.ConstructorDeclaration;
import org.eclipse.jdt.internal.compiler.ast.Expression;
import org.eclipse.jdt.internal.compiler.ast.MessageSend;
import org.eclipse.jdt.internal.compiler.ast.MethodDeclaration;
import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration;
import org.eclipse.jdt.internal.compiler.ast.TypeReference;
import org.eclipse.jdt.internal.compiler.parser.Parser;
import org.eclipse.jdt.internal.compiler.parser.Parser.IDeclarationFactory;
/**
* @author colyer
*
* To change the template for this generated type comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
public class DeclarationFactory implements IDeclarationFactory {
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.compiler.parser.Parser.IDeclarationFactory#createMethodDeclaration(org.eclipse.jdt.internal.compiler.CompilationResult)
*/
public MethodDeclaration createMethodDeclaration(CompilationResult result) {
return new AjMethodDeclaration(result);
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.compiler.parser.Parser.IDeclarationFactory#createConstructorDeclaration(org.eclipse.jdt.internal.compiler.CompilationResult)
*/
public ConstructorDeclaration createConstructorDeclaration(CompilationResult result) {
return new AjConstructorDeclaration(result);
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.compiler.parser.Parser.IDeclarationFactory#createProceed(org.eclipse.jdt.internal.compiler.ast.MessageSend)
*/
public MessageSend createProceed(MessageSend m) {
return new Proceed(m);
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.compiler.parser.Parser.IDeclarationFactory#createAspect(org.eclipse.jdt.internal.compiler.CompilationResult)
*/
public TypeDeclaration createAspect(CompilationResult result) {
return new AspectDeclaration(result);
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.compiler.parser.Parser.IDeclarationFactory#setPrivileged(org.eclipse.jdt.internal.compiler.ast.TypeDeclaration, boolean)
*/
public void setPrivileged(TypeDeclaration aspectDecl, boolean isPrivileged) {
((AspectDeclaration)aspectDecl).isPrivileged = isPrivileged;
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.compiler.parser.Parser.IDeclarationFactory#setPerClauseFrom(org.eclipse.jdt.internal.compiler.ast.TypeDeclaration, org.eclipse.jdt.internal.compiler.ast.ASTNode)
*/
public void setPerClauseFrom(TypeDeclaration aspectDecl, ASTNode pseudoTokens, Parser parser) {
AspectDeclaration aspect = (AspectDeclaration) aspectDecl;
PseudoTokens tok = (PseudoTokens) pseudoTokens;
aspect.perClause = tok.parsePerClause(parser);
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.compiler.parser.Parser.IDeclarationFactory#setDominatesPatternFrom(org.eclipse.jdt.internal.compiler.ast.TypeDeclaration, org.eclipse.jdt.internal.compiler.ast.ASTNode)
*/
public void setDominatesPatternFrom(TypeDeclaration aspectDecl, ASTNode pseudoTokens, Parser parser) {
AspectDeclaration aspect = (AspectDeclaration) aspectDecl;
PseudoTokens tok = (PseudoTokens) pseudoTokens;
aspect.dominatesPattern = tok.maybeParseDominatesPattern(parser);
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.compiler.parser.Parser.IDeclarationFactory#createPseudoTokensFrom(org.eclipse.jdt.internal.compiler.ast.ASTNode[], org.eclipse.jdt.internal.compiler.CompilationResult)
*/
public ASTNode createPseudoTokensFrom(ASTNode[] tokens, CompilationResult result) {
PseudoToken[] psts = new PseudoToken[tokens.length];
for (int i = 0; i < psts.length; i++) {
psts[i] = (PseudoToken)tokens[i];
}
return new PseudoTokens(psts,new EclipseSourceContext(result));
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.compiler.parser.Parser.IDeclarationFactory#createPointcutDeclaration(org.eclipse.jdt.internal.compiler.CompilationResult)
*/
public MethodDeclaration createPointcutDeclaration(CompilationResult result) {
return new PointcutDeclaration(result);
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.compiler.parser.Parser.IDeclarationFactory#createAroundAdviceDeclaration(org.eclipse.jdt.internal.compiler.CompilationResult)
*/
public MethodDeclaration createAroundAdviceDeclaration(CompilationResult result) {
return new AdviceDeclaration(result,AdviceKind.Around);
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.compiler.parser.Parser.IDeclarationFactory#createAfterAdviceDeclaration(org.eclipse.jdt.internal.compiler.CompilationResult)
*/
public MethodDeclaration createAfterAdviceDeclaration(CompilationResult result) {
return new AdviceDeclaration(result,AdviceKind.After);
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.compiler.parser.Parser.IDeclarationFactory#createBeforeAdviceDeclaration(org.eclipse.jdt.internal.compiler.CompilationResult)
*/
public MethodDeclaration createBeforeAdviceDeclaration(CompilationResult result) {
return new AdviceDeclaration(result,AdviceKind.Before);
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.compiler.parser.Parser.IDeclarationFactory#createPointcutDesignator(org.eclipse.jdt.internal.compiler.parser.Parser, org.eclipse.jdt.internal.compiler.ast.ASTNode)
*/
public ASTNode createPointcutDesignator(Parser parser, ASTNode pseudoTokens) {
return new PointcutDesignator(parser,(PseudoTokens)pseudoTokens);
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.compiler.parser.Parser.IDeclarationFactory#setPointcutDesignator(org.eclipse.jdt.internal.compiler.ast.MethodDeclaration, org.eclipse.jdt.internal.compiler.ast.ASTNode)
*/
public void setPointcutDesignatorOnAdvice(MethodDeclaration adviceDecl, ASTNode des) {
((AdviceDeclaration)adviceDecl).pointcutDesignator = (PointcutDesignator)des;
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.compiler.parser.Parser.IDeclarationFactory#setPointcutDesignator(org.eclipse.jdt.internal.compiler.ast.MethodDeclaration, org.eclipse.jdt.internal.compiler.ast.ASTNode)
*/
public void setPointcutDesignatorOnPointcut(MethodDeclaration pcutDecl, ASTNode des) {
((PointcutDeclaration)pcutDecl).pointcutDesignator = (PointcutDesignator)des;
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.compiler.parser.Parser.IDeclarationFactory#setExtraArgument(org.eclipse.jdt.internal.compiler.ast.MethodDeclaration, org.eclipse.jdt.internal.compiler.ast.Argument)
*/
public void setExtraArgument(MethodDeclaration adviceDeclaration, Argument arg) {
((AdviceDeclaration)adviceDeclaration).extraArgument = arg;
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.compiler.parser.Parser.IDeclarationFactory#isAfterAdvice(org.eclipse.jdt.internal.compiler.ast.MethodDeclaration)
*/
public boolean isAfterAdvice(MethodDeclaration adviceDecl) {
return ((AdviceDeclaration)adviceDecl).kind != AdviceKind.After;
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.compiler.parser.Parser.IDeclarationFactory#setAfterThrowingAdviceKind(org.eclipse.jdt.internal.compiler.ast.MethodDeclaration)
*/
public void setAfterThrowingAdviceKind(MethodDeclaration adviceDecl) {
((AdviceDeclaration)adviceDecl).kind = AdviceKind.AfterThrowing;
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.compiler.parser.Parser.IDeclarationFactory#setAfterReturningAdviceKind(org.eclipse.jdt.internal.compiler.ast.MethodDeclaration)
*/
public void setAfterReturningAdviceKind(MethodDeclaration adviceDecl) {
((AdviceDeclaration)adviceDecl).kind = AdviceKind.AfterReturning;
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.compiler.parser.Parser.IDeclarationFactory#createDeclareDeclaration(org.eclipse.jdt.internal.compiler.CompilationResult, org.eclipse.jdt.internal.compiler.ast.ASTNode)
*/
public MethodDeclaration createDeclareDeclaration(CompilationResult result, ASTNode pseudoTokens, Parser parser) {
Declare declare = ((PseudoTokens)pseudoTokens).parseDeclare(parser);
return new DeclareDeclaration(result,declare);
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.compiler.parser.Parser.IDeclarationFactory#createInterTypeFieldDeclaration(org.eclipse.jdt.internal.compiler.CompilationResult, org.eclipse.jdt.internal.compiler.ast.TypeReference)
*/
public MethodDeclaration createInterTypeFieldDeclaration(CompilationResult result, TypeReference onType) {
return new InterTypeFieldDeclaration(result,onType);
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.compiler.parser.Parser.IDeclarationFactory#createInterTypeMethodDeclaration(org.eclipse.jdt.internal.compiler.CompilationResult)
*/
public MethodDeclaration createInterTypeMethodDeclaration(CompilationResult result) {
return new InterTypeMethodDeclaration(result,null);
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.compiler.parser.Parser.IDeclarationFactory#createInterTypeConstructorDeclaration(org.eclipse.jdt.internal.compiler.CompilationResult)
*/
public MethodDeclaration createInterTypeConstructorDeclaration(CompilationResult result) {
return new InterTypeConstructorDeclaration(result,null);
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.compiler.parser.Parser.IDeclarationFactory#setSelector(org.eclipse.jdt.internal.compiler.ast.MethodDeclaration, char[])
*/
public void setSelector(MethodDeclaration interTypeDecl, char[] selector) {
((InterTypeDeclaration)interTypeDecl).setSelector(selector);
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.compiler.parser.Parser.IDeclarationFactory#setDeclaredModifiers(org.eclipse.jdt.internal.compiler.ast.MethodDeclaration, int)
*/
public void setDeclaredModifiers(MethodDeclaration interTypeDecl, int modifiers) {
((InterTypeDeclaration)interTypeDecl).setDeclaredModifiers(modifiers); }
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.compiler.parser.Parser.IDeclarationFactory#setInitialization(org.eclipse.jdt.internal.compiler.ast.MethodDeclaration, org.eclipse.jdt.internal.compiler.ast.Expression)
*/
public void setInitialization(MethodDeclaration itdFieldDecl, Expression initialization) {
((InterTypeFieldDeclaration)itdFieldDecl).setInitialization(initialization);
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.compiler.parser.Parser.IDeclarationFactory#setOnType(org.eclipse.jdt.internal.compiler.ast.MethodDeclaration, org.eclipse.jdt.internal.compiler.ast.TypeReference)
*/
public void setOnType(MethodDeclaration interTypeDecl, TypeReference onType) {
((InterTypeDeclaration)interTypeDecl).onType = onType;
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.compiler.parser.Parser.IDeclarationFactory#createPseudoToken(org.eclipse.jdt.internal.compiler.parser.Parser, java.lang.String, boolean)
*/
public ASTNode createPseudoToken(Parser parser, String value, boolean isIdentifier) {
return new PseudoToken(parser,value,isIdentifier);
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.compiler.parser.Parser.IDeclarationFactory#createIfPseudoToken(org.eclipse.jdt.internal.compiler.parser.Parser, org.eclipse.jdt.internal.compiler.ast.Expression)
*/
public ASTNode createIfPseudoToken(Parser parser, Expression expr) {
return new IfPseudoToken(parser,expr);
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.compiler.parser.Parser.IDeclarationFactory#setLiteralKind(org.eclipse.jdt.internal.compiler.ast.ASTNode, java.lang.String)
*/
public void setLiteralKind(ASTNode pseudoToken, String string) {
((PseudoToken)pseudoToken).literalKind = string;
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.compiler.parser.Parser.IDeclarationFactory#shouldTryToRecover(org.eclipse.jdt.internal.compiler.ast.ASTNode)
*/
public boolean shouldTryToRecover(ASTNode node) {
return !(node instanceof AspectDeclaration ||
node instanceof PointcutDeclaration ||
node instanceof AdviceDeclaration) ;
}
}
|
73,334
|
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
|
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
|
resolved fixed
|
b133299
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:40:02Z
| 2004-09-06T17:00:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/problem/AjProblemReporter.java
|
/* *******************************************************************
* 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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.problem;
import java.lang.reflect.Modifier;
import java.util.Iterator;
import org.aspectj.ajdt.internal.compiler.ast.AdviceDeclaration;
import org.aspectj.ajdt.internal.compiler.ast.PointcutDeclaration;
import org.aspectj.ajdt.internal.compiler.ast.Proceed;
import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory;
import org.aspectj.util.FuzzyBoolean;
import org.aspectj.weaver.AjcMemberMaker;
import org.aspectj.weaver.ConcreteTypeMunger;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedTypeX;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.patterns.DeclareSoft;
import org.eclipse.jdt.internal.compiler.CompilationResult;
import org.eclipse.jdt.internal.compiler.IErrorHandlingPolicy;
import org.eclipse.jdt.internal.compiler.IProblemFactory;
import org.eclipse.jdt.internal.compiler.ast.ASTNode;
import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration;
import org.eclipse.jdt.internal.compiler.ast.Argument;
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
import org.eclipse.jdt.internal.compiler.impl.ReferenceContext;
import org.eclipse.jdt.internal.compiler.lookup.MethodBinding;
import org.eclipse.jdt.internal.compiler.lookup.MethodScope;
import org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding;
import org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding;
import org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
import org.eclipse.jdt.internal.compiler.problem.ProblemReporter;
import org.eclipse.jdt.core.compiler.CharOperation;
import org.eclipse.jdt.core.compiler.IProblem;
/**
* Extends problem reporter to support compiler-side implementation of declare soft.
* Also overrides error reporting for the need to implement abstract methods to
* account for inter-type declarations and pointcut declarations. This second
* job might be better done directly in the SourceTypeBinding/ClassScope classes.
*
* @author Jim Hugunin
*/
public class AjProblemReporter extends ProblemReporter {
private static final boolean DUMP_STACK = false;
public EclipseFactory factory;
public AjProblemReporter(
IErrorHandlingPolicy policy,
CompilerOptions options,
IProblemFactory problemFactory) {
super(policy, options, problemFactory);
}
public void unhandledException(
TypeBinding exceptionType,
ASTNode location)
{
if (!factory.getWorld().getDeclareSoft().isEmpty()) {
Shadow callSite = factory.makeShadow(location, referenceContext);
Shadow enclosingExec = factory.makeShadow(referenceContext);
// System.err.println("about to show error for unhandled exception: " + new String(exceptionType.sourceName()) +
// " at " + location + " in " + referenceContext);
for (Iterator i = factory.getWorld().getDeclareSoft().iterator(); i.hasNext(); ) {
DeclareSoft d = (DeclareSoft)i.next();
// We need the exceptionType to match the type in the declare soft statement
// This means it must either be the same type or a subtype
ResolvedTypeX throwException = factory.fromEclipse((ReferenceBinding)exceptionType);
FuzzyBoolean isExceptionTypeOrSubtype =
d.getException().matchesInstanceof(throwException);
if (!isExceptionTypeOrSubtype.alwaysTrue() ) continue;
if (callSite != null) {
FuzzyBoolean match = d.getPointcut().match(callSite);
if (match.alwaysTrue()) {
//System.err.println("matched callSite: " + callSite + " with " + d);
return;
} else if (!match.alwaysFalse()) {
//!!! need this check to happen much sooner
//throw new RuntimeException("unimplemented, shouldn't have fuzzy match here");
}
}
if (enclosingExec != null) {
FuzzyBoolean match = d.getPointcut().match(enclosingExec);
if (match.alwaysTrue()) {
//System.err.println("matched enclosingExec: " + enclosingExec + " with " + d);
return;
} else if (!match.alwaysFalse()) {
//!!! need this check to happen much sooner
//throw new RuntimeException("unimplemented, shouldn't have fuzzy match here");
}
}
}
}
//??? is this always correct
if (location instanceof Proceed) {
return;
}
super.unhandledException(exceptionType, location);
}
private boolean isPointcutDeclaration(MethodBinding binding) {
return CharOperation.prefixEquals(PointcutDeclaration.mangledPrefix, binding.selector);
}
public void abstractMethodCannotBeOverridden(
SourceTypeBinding type,
MethodBinding concreteMethod)
{
if (isPointcutDeclaration(concreteMethod)) {
return;
}
super.abstractMethodCannotBeOverridden(type, concreteMethod);
}
public void abstractMethodMustBeImplemented(
SourceTypeBinding type,
MethodBinding abstractMethod)
{
// if this is a PointcutDeclaration then there is no error
if (isPointcutDeclaration(abstractMethod)) {
return;
}
if (CharOperation.prefixEquals("ajc$interField".toCharArray(), abstractMethod.selector)) {
//??? think through how this could go wrong
return;
}
// if we implemented this method by an inter-type declaration, then there is no error
//??? be sure this is always right
ResolvedTypeX onTypeX = factory.fromEclipse(type); //abstractMethod.declaringClass);
for (Iterator i = onTypeX.getInterTypeMungersIncludingSupers().iterator(); i.hasNext(); ) {
ConcreteTypeMunger m = (ConcreteTypeMunger)i.next();
ResolvedMember sig = m.getSignature();
if (!Modifier.isAbstract(sig.getModifiers())) {
if (ResolvedTypeX
.matches(
AjcMemberMaker.interMethod(
sig,
m.getAspectType(),
sig.getDeclaringType().isInterface(
factory.getWorld())),
EclipseFactory.makeResolvedMember(abstractMethod))) {
return;
}
}
}
super.abstractMethodMustBeImplemented(type, abstractMethod);
}
public void handle(
int problemId,
String[] problemArguments,
String[] messageArguments,
int severity,
int problemStartPosition,
int problemEndPosition,
ReferenceContext referenceContext,
CompilationResult unitResult)
{
if (severity != Ignore && DUMP_STACK) {
Thread.dumpStack();
}
super.handle(
problemId,
problemArguments,
messageArguments,
severity,
problemStartPosition,
problemEndPosition,
referenceContext,
unitResult);
}
// PR71076
public void javadocMissingParamTag(Argument arg, int modifiers) {
boolean reportIt = true;
if (arg.binding!=null && (arg.binding.declaringScope instanceof MethodScope) ) {
MethodScope ms = (MethodScope) arg.binding.declaringScope;
if (ms.referenceContext!=null && (ms.referenceContext instanceof AdviceDeclaration)) {
AdviceDeclaration adviceDecl = (AdviceDeclaration)ms.referenceContext;
if (arg.name!=null) {
if (adviceDecl.selector.length>4 &&
adviceDecl.selector[0] == 'a' &&
adviceDecl.selector[1] == 'j' &&
adviceDecl.selector[2] == 'c' &&
adviceDecl.selector[3] == '$') {
String stringArgName = new String(arg.name);
if (stringArgName.equals("thisJoinPoint")) reportIt = false;
if (stringArgName.equals("thisJoinPointStaticPart")) reportIt = false;
if (stringArgName.equals("thisEnclosingJoinPointStaticPart")) reportIt = false;
if (arg.type.toString().indexOf("AroundClosure")!=-1) reportIt = false;
}
}
}
}
if (arg.name!=null && new String(arg.name).startsWith("ajc$")) reportIt = false;
if (reportIt)
super.javadocMissingParamTag(arg, modifiers);
}
public void abstractMethodInAbstractClass(SourceTypeBinding type, AbstractMethodDeclaration methodDecl) {
String abstractMethodName = new String(methodDecl.selector);
if (abstractMethodName.startsWith("ajc$pointcut")) {
// This will already have been reported, see: PointcutDeclaration.postParse()
return;
}
String[] arguments = new String[] {new String(type.sourceName()), abstractMethodName};
super.handle(
IProblem.AbstractMethodInAbstractClass,
arguments,
arguments,
methodDecl.sourceStart,
methodDecl.sourceEnd,this.referenceContext,
this.referenceContext == null ? null : this.referenceContext.compilationResult());
}
}
|
73,334
|
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
|
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
|
resolved fixed
|
b133299
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:40:02Z
| 2004-09-06T17:00:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AjBatchImageBuilder.java
|
/*******************************************************************************
* Copyright (c) 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.aspectj.ajdt.internal.core.builder;
import org.eclipse.jdt.internal.compiler.CompilationResult;
import org.eclipse.jdt.internal.core.builder.BatchImageBuilder;
import org.eclipse.jdt.internal.core.builder.SourceFile;
/**
* @author colyer
*
* BatchImageBuilder used by IDEs (AJDT)
*/
public class AjBatchImageBuilder extends BatchImageBuilder {
public AjBatchImageBuilder(AspectJBuilder builder) {
super(builder);
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.compiler.ICompilerRequestor#acceptResult(org.eclipse.jdt.internal.compiler.CompilationResult)
*/
public void acceptResult(CompilationResult result) {
if ((result.getCompilationUnit() != null) && (result.getCompilationUnit() instanceof SourceFile)) {
super.acceptResult(result);
} else {
// it's a file originating from binary source...
// we need to handle it ourselves
// TODO handle binary source output
}
}
}
|
73,334
|
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
|
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
|
resolved fixed
|
b133299
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:40:02Z
| 2004-09-06T17:00:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AjBuildManager.java
|
/* *******************************************************************
* 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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.core.builder;
import java.io.*;
import java.util.*;
import java.util.jar.*;
import java.util.zip.ZipEntry;
import org.aspectj.ajdt.internal.compiler.AjCompilerAdapter;
import org.aspectj.ajdt.internal.compiler.IBinarySourceProvider;
import org.aspectj.ajdt.internal.compiler.IIntermediateResultsRequestor;
import org.aspectj.ajdt.internal.compiler.IOutputClassFileNameProvider;
import org.aspectj.ajdt.internal.compiler.InterimCompilationResult;
import org.aspectj.ajdt.internal.compiler.lookup.*;
import org.aspectj.ajdt.internal.compiler.problem.AjProblemReporter;
import org.aspectj.asm.*;
//import org.aspectj.asm.internal.*;
import org.aspectj.asm.internal.ProgramElement;
import org.aspectj.bridge.*;
import org.aspectj.util.FileUtil;
import org.aspectj.weaver.Dump;
import org.aspectj.weaver.World;
import org.aspectj.weaver.bcel.*;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.jdt.core.compiler.*;
import org.eclipse.jdt.internal.compiler.*;
import org.eclipse.jdt.internal.compiler.batch.*;
import org.eclipse.jdt.internal.compiler.batch.FileSystem;
import org.eclipse.jdt.internal.compiler.env.*;
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
import org.eclipse.jdt.internal.compiler.parser.Parser;
import org.eclipse.jdt.internal.compiler.problem.AbortCompilation;
import org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory;
//import org.eclipse.jdt.internal.compiler.util.HashtableOfObject;
public class AjBuildManager implements IOutputClassFileNameProvider,IBinarySourceProvider,ICompilerAdapterFactory {
private static final String CANT_WRITE_RESULT = "unable to write compilation result";
private static final String MANIFEST_NAME = "META-INF/MANIFEST.MF";
static final boolean COPY_INPATH_DIR_RESOURCES = false;
static final boolean FAIL_IF_RUNTIME_NOT_FOUND = false;
private static final FileFilter binarySourceFilter =
new FileFilter() {
public boolean accept(File f) {
return f.getName().endsWith(".class");
}};
/**
* This builder is static so that it can be subclassed and reset. However, note
* that there is only one builder present, so if two extendsion reset it, only
* the latter will get used.
*/
private static AsmHierarchyBuilder asmHierarchyBuilder = new AsmHierarchyBuilder();
private IProgressListener progressListener = null;
private int compiledCount;
private int sourceFileCount;
private JarOutputStream zos;
private boolean batchCompile = true;
private INameEnvironment environment;
private Map /* String -> List<UCF>*/ binarySourcesForTheNextCompile = new HashMap();
private IHierarchy structureModel;
public AjBuildConfig buildConfig;
AjState state = new AjState(this);
BcelWeaver bcelWeaver;
public BcelWorld bcelWorld;
public CountingMessageHandler handler;
public AjBuildManager(IMessageHandler holder) {
super();
this.handler = CountingMessageHandler.makeCountingMessageHandler(holder);
}
/** @return true if we should generate a model as a side-effect */
public boolean doGenerateModel() {
return buildConfig.isGenerateModelMode();
}
public boolean batchBuild(
AjBuildConfig buildConfig,
IMessageHandler baseHandler)
throws IOException, AbortException {
return doBuild(buildConfig, baseHandler, true);
}
public boolean incrementalBuild(
AjBuildConfig buildConfig,
IMessageHandler baseHandler)
throws IOException, AbortException {
return doBuild(buildConfig, baseHandler, false);
}
/** @throws AbortException if check for runtime fails */
protected boolean doBuild(
AjBuildConfig buildConfig,
IMessageHandler baseHandler,
boolean batch) throws IOException, AbortException {
boolean ret = true;
batchCompile = batch;
try {
if (batch) {
this.state = new AjState(this);
}
boolean canIncremental = state.prepareForNextBuild(buildConfig);
if (!canIncremental && !batch) { // retry as batch?
return doBuild(buildConfig, baseHandler, true);
}
this.handler =
CountingMessageHandler.makeCountingMessageHandler(baseHandler);
// XXX duplicate, no? remove?
String check = checkRtJar(buildConfig);
if (check != null) {
if (FAIL_IF_RUNTIME_NOT_FOUND) {
MessageUtil.error(handler, check);
return false;
} else {
MessageUtil.warn(handler, check);
}
}
// if (batch) {
setBuildConfig(buildConfig);
//}
if (batch || !AsmManager.attemptIncrementalModelRepairs) {
// if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) {
setupModel(buildConfig);
// }
}
if (batch) {
initBcelWorld(handler);
}
if (handler.hasErrors()) {
return false;
}
if (buildConfig.getOutputJar() != null) {
if (!openOutputStream(buildConfig.getOutputJar())) return false;
}
if (batch) {
// System.err.println("XXXX batch: " + buildConfig.getFiles());
if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) {
bcelWorld.setModel(AsmManager.getDefault().getHierarchy());
// in incremental build, only get updated model?
}
binarySourcesForTheNextCompile = state.getBinaryFilesToCompile(true);
performCompilation(buildConfig.getFiles());
if (handler.hasErrors()) {
return false;
}
if (AsmManager.isReporting())
AsmManager.getDefault().reportModelInfo("After a batch build");
} else {
// done already?
// if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) {
// bcelWorld.setModel(StructureModelManager.INSTANCE.getStructureModel());
// }
// System.err.println("XXXX start inc ");
binarySourcesForTheNextCompile = state.getBinaryFilesToCompile(true);
List files = state.getFilesToCompile(true);
if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode())
if (AsmManager.attemptIncrementalModelRepairs)
AsmManager.getDefault().processDelta(files,state.addedFiles,state.deletedFiles);
boolean hereWeGoAgain = !(files.isEmpty() && binarySourcesForTheNextCompile.isEmpty());
for (int i = 0; (i < 5) && hereWeGoAgain; i++) {
// System.err.println("XXXX inc: " + files);
performCompilation(files);
if (handler.hasErrors() || (progressListener!=null && progressListener.isCancelledRequested())) {
return false;
}
binarySourcesForTheNextCompile = state.getBinaryFilesToCompile(false);
files = state.getFilesToCompile(false);
hereWeGoAgain = !(files.isEmpty() && binarySourcesForTheNextCompile.isEmpty());
// TODO Andy - Needs some thought here...
// I think here we might want to pass empty addedFiles/deletedFiles as they were
// dealt with on the first call to processDelta - we are going through this loop
// again because in compiling something we found something else we needed to
// rebuild. But what case causes this?
if (hereWeGoAgain)
if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode())
if (AsmManager.attemptIncrementalModelRepairs)
AsmManager.getDefault().processDelta(files,state.addedFiles,state.deletedFiles);
}
if (!files.isEmpty()) {
return batchBuild(buildConfig, baseHandler);
} else {
if (AsmManager.isReporting())
AsmManager.getDefault().reportModelInfo("After an incremental build");
}
}
// XXX not in Mik's incremental
if (buildConfig.isEmacsSymMode()) {
new org.aspectj.ajdt.internal.core.builder.EmacsStructureModelManager().externalizeModel();
}
// have to tell state we succeeded or next is not incremental
state.successfulCompile(buildConfig);
copyResourcesToDestination();
/*boolean weaved = *///weaveAndGenerateClassFiles();
// if not weaved, then no-op build, no model changes
// but always returns true
// XXX weaved not in Mik's incremental
if (buildConfig.isGenerateModelMode()) {
AsmManager.getDefault().fireModelUpdated();
}
} finally {
if (zos != null) {
closeOutputStream(buildConfig.getOutputJar());
}
ret = !handler.hasErrors();
// bug 59895, don't release reference to handler as may be needed by a nested call
//handler = null;
}
return ret;
}
private boolean openOutputStream(File outJar) {
try {
OutputStream os = FileUtil.makeOutputStream(buildConfig.getOutputJar());
zos = new JarOutputStream(os,bcelWeaver.getManifest(true));
} catch (IOException ex) {
IMessage message =
new Message("Unable to open outjar "
+ outJar.getPath()
+ "(" + ex.getMessage()
+ ")",
new SourceLocation(outJar,0),
true);
handler.handleMessage(message);
return false;
}
return true;
}
private void closeOutputStream(File outJar) {
try {
if (zos != null) zos.close();
zos = null;
/* Ensure we don't write an incomplete JAR bug-71339 */
if (handler.hasErrors()) {
outJar.delete();
}
} catch (IOException ex) {
IMessage message =
new Message("Unable to write outjar "
+ outJar.getPath()
+ "(" + ex.getMessage()
+ ")",
new SourceLocation(outJar,0),
true);
handler.handleMessage(message);
}
}
private void copyResourcesToDestination() throws IOException {
// resources that we need to copy are contained in the injars and inpath only
for (Iterator i = buildConfig.getInJars().iterator(); i.hasNext(); ) {
File inJar = (File)i.next();
copyResourcesFromJarFile(inJar);
}
for (Iterator i = buildConfig.getInpath().iterator(); i.hasNext(); ) {
File inPathElement = (File)i.next();
if (inPathElement.isDirectory()) {
copyResourcesFromDirectory(inPathElement);
} else {
copyResourcesFromJarFile(inPathElement);
}
}
if (buildConfig.getSourcePathResources() != null) {
for (Iterator i = buildConfig.getSourcePathResources().keySet().iterator(); i.hasNext(); ) {
String resource = (String)i.next();
File from = (File)buildConfig.getSourcePathResources().get(resource);
copyResourcesFromFile(from,resource,from);
}
}
writeManifest();
}
private void copyResourcesFromJarFile(File jarFile) throws IOException {
JarInputStream inStream = null;
try {
inStream = new JarInputStream(new FileInputStream(jarFile));
while (true) {
ZipEntry entry = inStream.getNextEntry();
if (entry == null) break;
String filename = entry.getName();
// System.out.println("? copyResourcesFromJarFile() filename='" + filename +"'");
if (!entry.isDirectory() && acceptResource(filename)) {
byte[] bytes = FileUtil.readAsByteArray(inStream);
writeResource(filename,bytes,jarFile);
}
inStream.closeEntry();
}
} finally {
if (inStream != null) inStream.close();
}
}
private void copyResourcesFromDirectory(File dir) throws IOException {
if (!COPY_INPATH_DIR_RESOURCES) return;
// Get a list of all files (i.e. everything that isnt a directory)
File[] files = FileUtil.listFiles(dir,new FileFilter() {
public boolean accept(File f) {
boolean accept = !(f.isDirectory() || f.getName().endsWith(".class")) ;
return accept;
}
});
// For each file, add it either as a real .class file or as a resource
for (int i = 0; i < files.length; i++) {
// ASSERT: files[i].getAbsolutePath().startsWith(inFile.getAbsolutePath()
// or we are in trouble...
String filename = files[i].getAbsolutePath().substring(
dir.getAbsolutePath().length()+1);
copyResourcesFromFile(files[i],filename,dir);
}
}
private void copyResourcesFromFile(File f,String filename,File src) throws IOException {
if (!acceptResource(filename)) return;
FileInputStream fis = null;
try {
fis = new FileInputStream(f);
byte[] bytes = FileUtil.readAsByteArray(fis);
// String relativePath = files[i].getPath();
writeResource(filename,bytes,src);
} finally {
if (fis != null) fis.close();
}
}
private void writeResource(String filename, byte[] content, File srcLocation) throws IOException {
if (state.resources.contains(filename)) {
IMessage msg = new Message("duplicate resource: '" + filename + "'",
IMessage.WARNING,
null,
new SourceLocation(srcLocation,0));
handler.handleMessage(msg);
return;
}
if (zos != null) {
ZipEntry newEntry = new ZipEntry(filename); //??? get compression scheme right
zos.putNextEntry(newEntry);
zos.write(content);
zos.closeEntry();
} else {
OutputStream fos =
FileUtil.makeOutputStream(new File(buildConfig.getOutputDir(),filename));
fos.write(content);
fos.close();
}
state.resources.add(filename);
}
/*
* If we are writing to an output directory copy the manifest but only
* if we already have one
*/
private void writeManifest () throws IOException {
Manifest manifest = bcelWeaver.getManifest(false);
if (manifest != null && zos == null) {
OutputStream fos =
FileUtil.makeOutputStream(new File(buildConfig.getOutputDir(),MANIFEST_NAME));
manifest.write(fos);
fos.close();
}
}
private boolean acceptResource(String resourceName) {
if (
(resourceName.startsWith("CVS/")) ||
(resourceName.indexOf("/CVS/") != -1) ||
(resourceName.endsWith("/CVS")) ||
(resourceName.endsWith(".class")) ||
(resourceName.toUpperCase().equals(MANIFEST_NAME))
)
{
return false;
} else {
return true;
}
}
// public static void dumprels() {
// IRelationshipMap irm = AsmManager.getDefault().getRelationshipMap();
// int ctr = 1;
// Set entries = irm.getEntries();
// for (Iterator iter = entries.iterator(); iter.hasNext();) {
// String hid = (String) iter.next();
// List rels = irm.get(hid);
// for (Iterator iterator = rels.iterator(); iterator.hasNext();) {
// IRelationship ir = (IRelationship) iterator.next();
// List targets = ir.getTargets();
// for (Iterator iterator2 = targets.iterator();
// iterator2.hasNext();
// ) {
// String thid = (String) iterator2.next();
// System.err.println("Hid:"+(ctr++)+":(targets="+targets.size()+") "+hid+" ("+ir.getName()+") "+thid);
// }
// }
// }
// }
/**
* Responsible for managing the ASM model between builds. Contains the policy for
* maintaining the persistance of elements in the model.
*
* TODO: implement incremental policy.
*/
private void setupModel(AjBuildConfig config) {
IHierarchy model = AsmManager.getDefault().getHierarchy();
String rootLabel = "<root>";
AsmManager.getDefault().getRelationshipMap().clear();
IProgramElement.Kind kind = IProgramElement.Kind.FILE_JAVA;
if (buildConfig.getConfigFile() != null) {
rootLabel = buildConfig.getConfigFile().getName();
model.setConfigFile(
buildConfig.getConfigFile().getAbsolutePath()
);
kind = IProgramElement.Kind.FILE_LST;
}
model.setRoot(new ProgramElement(rootLabel, kind, new ArrayList()));
model.setFileMap(new HashMap());
setStructureModel(model);
}
//
// private void dumplist(List l) {
// System.err.println("---- "+l.size());
// for (int i =0 ;i<l.size();i++) System.err.println(i+"\t "+l.get(i));
// }
// private void accumulateFileNodes(IProgramElement ipe,List store) {
// if (ipe.getKind()==IProgramElement.Kind.FILE_JAVA ||
// ipe.getKind()==IProgramElement.Kind.FILE_ASPECTJ) {
// if (!ipe.getName().equals("<root>")) {
// store.add(ipe);
// return;
// }
// }
// for (Iterator i = ipe.getChildren().iterator();i.hasNext();) {
// accumulateFileNodes((IProgramElement)i.next(),store);
// }
// }
/** init only on initial batch compile? no file-specific options */
private void initBcelWorld(IMessageHandler handler) throws IOException {
List cp = buildConfig.getBootclasspath();
cp.addAll(buildConfig.getClasspath());
bcelWorld = new BcelWorld(cp, handler, null);
bcelWorld.setXnoInline(buildConfig.isXnoInline());
bcelWorld.setXlazyTjp(buildConfig.isXlazyTjp());
bcelWeaver = new BcelWeaver(bcelWorld);
state.binarySourceFiles = new HashMap();
for (Iterator i = buildConfig.getAspectpath().iterator(); i.hasNext();) {
File f = (File) i.next();
bcelWeaver.addLibraryJarFile(f);
}
// String lintMode = buildConfig.getLintMode();
if (buildConfig.getLintMode().equals(AjBuildConfig.AJLINT_DEFAULT)) {
bcelWorld.getLint().loadDefaultProperties();
} else {
bcelWorld.getLint().setAll(buildConfig.getLintMode());
}
if (buildConfig.getLintSpecFile() != null) {
bcelWorld.getLint().setFromProperties(buildConfig.getLintSpecFile());
}
//??? incremental issues
for (Iterator i = buildConfig.getInJars().iterator(); i.hasNext(); ) {
File inJar = (File)i.next();
List unwovenClasses = bcelWeaver.addJarFile(inJar, buildConfig.getOutputDir(),false);
state.binarySourceFiles.put(inJar.getPath(), unwovenClasses);
}
for (Iterator i = buildConfig.getInpath().iterator(); i.hasNext(); ) {
File inPathElement = (File)i.next();
if (!inPathElement.isDirectory()) {
// its a jar file on the inpath
// the weaver method can actually handle dirs, but we don't call it, see next block
List unwovenClasses = bcelWeaver.addJarFile(inPathElement,buildConfig.getOutputDir(),true);
state.binarySourceFiles.put(inPathElement.getPath(),unwovenClasses);
} else {
// add each class file in an in-dir individually, this gives us the best error reporting
// (they are like 'source' files then), and enables a cleaner incremental treatment of
// class file changes in indirs.
File[] binSrcs = FileUtil.listFiles(inPathElement, binarySourceFilter);
for (int j = 0; j < binSrcs.length; j++) {
UnwovenClassFile ucf =
bcelWeaver.addClassFile(binSrcs[j], inPathElement, buildConfig.getOutputDir());
List ucfl = new ArrayList();
ucfl.add(ucf);
state.binarySourceFiles.put(binSrcs[j].getPath(),ucfl);
}
}
}
bcelWeaver.setReweavableMode(buildConfig.isXreweavable(),buildConfig.getXreweavableCompressClasses());
//check for org.aspectj.runtime.JoinPoint
bcelWorld.resolve("org.aspectj.lang.JoinPoint");
}
public World getWorld() {
return bcelWorld;
}
void addAspectClassFilesToWeaver(List addedClassFiles) throws IOException {
for (Iterator i = addedClassFiles.iterator(); i.hasNext(); ) {
UnwovenClassFile classFile = (UnwovenClassFile) i.next();
bcelWeaver.addClassFile(classFile);
}
}
// public boolean weaveAndGenerateClassFiles() throws IOException {
// handler.handleMessage(MessageUtil.info("weaving"));
// if (progressListener != null) progressListener.setText("weaving aspects");
// bcelWeaver.setProgressListener(progressListener, 0.5, 0.5/state.addedClassFiles.size());
// //!!! doesn't provide intermediate progress during weaving
// // XXX add all aspects even during incremental builds?
// addAspectClassFilesToWeaver(state.addedClassFiles);
// if (buildConfig.isNoWeave()) {
// if (buildConfig.getOutputJar() != null) {
// bcelWeaver.dumpUnwoven(buildConfig.getOutputJar());
// } else {
// bcelWeaver.dumpUnwoven();
// bcelWeaver.dumpResourcesToOutPath();
// }
// } else {
// if (buildConfig.getOutputJar() != null) {
// bcelWeaver.weave(buildConfig.getOutputJar());
// } else {
// bcelWeaver.weave();
// bcelWeaver.dumpResourcesToOutPath();
// }
// }
// if (progressListener != null) progressListener.setProgress(1.0);
// return true;
// //return messageAdapter.getErrorCount() == 0; //!javaBuilder.notifier.anyErrors();
// }
public FileSystem getLibraryAccess(String[] classpaths, String[] filenames) {
String defaultEncoding = buildConfig.getOptions().defaultEncoding;
if ("".equals(defaultEncoding)) //$NON-NLS-1$
defaultEncoding = null; //$NON-NLS-1$
// Bug 46671: We need an array as long as the number of elements in the classpath - *even though* not every
// element of the classpath is likely to be a directory. If we ensure every element of the array is set to
// only look for BINARY, then we make sure that for any classpath element that is a directory, we won't build
// a classpathDirectory object that will attempt to look for source when it can't find binary.
int[] classpathModes = new int[classpaths.length];
for (int i =0 ;i<classpaths.length;i++) classpathModes[i]=ClasspathDirectory.BINARY;
return new FileSystem(classpaths, filenames, defaultEncoding,classpathModes);
}
public IProblemFactory getProblemFactory() {
return new DefaultProblemFactory(Locale.getDefault());
}
/*
* Build the set of compilation source units
*/
public CompilationUnit[] getCompilationUnits(String[] filenames, String[] encodings) {
int fileCount = filenames.length;
CompilationUnit[] units = new CompilationUnit[fileCount];
// HashtableOfObject knownFileNames = new HashtableOfObject(fileCount);
String defaultEncoding = buildConfig.getOptions().defaultEncoding;
if ("".equals(defaultEncoding)) //$NON-NLS-1$
defaultEncoding = null; //$NON-NLS-1$
for (int i = 0; i < fileCount; i++) {
String encoding = encodings[i];
if (encoding == null)
encoding = defaultEncoding;
units[i] = new CompilationUnit(null, filenames[i], encoding);
}
return units;
}
public String extractDestinationPathFromSourceFile(CompilationResult result) {
ICompilationUnit compilationUnit = result.compilationUnit;
if (compilationUnit != null) {
char[] fileName = compilationUnit.getFileName();
int lastIndex = CharOperation.lastIndexOf(java.io.File.separatorChar, fileName);
if (lastIndex == -1) {
return System.getProperty("user.dir"); //$NON-NLS-1$
}
return new String(CharOperation.subarray(fileName, 0, lastIndex));
}
return System.getProperty("user.dir"); //$NON-NLS-1$
}
public void performCompilation(List files) {
if (progressListener != null) {
compiledCount = 0;
sourceFileCount = files.size();
progressListener.setText("compiling source files");
}
//System.err.println("got files: " + files);
String[] filenames = new String[files.size()];
String[] encodings = new String[files.size()];
//System.err.println("filename: " + this.filenames);
for (int i=0; i < files.size(); i++) {
filenames[i] = ((File)files.get(i)).getPath();
}
List cps = buildConfig.getFullClasspath();
Dump.saveFullClasspath(cps);
String[] classpaths = new String[cps.size()];
for (int i=0; i < cps.size(); i++) {
classpaths[i] = (String)cps.get(i);
}
//System.out.println("compiling");
environment = getLibraryAccess(classpaths, filenames);
if (!state.classesFromName.isEmpty()) {
environment = new StatefulNameEnvironment(environment, state.classesFromName);
}
org.eclipse.jdt.internal.compiler.Compiler.setCompilerAdapterFactory(this);
org.eclipse.jdt.internal.compiler.Compiler compiler =
new org.eclipse.jdt.internal.compiler.Compiler(environment,
DefaultErrorHandlingPolicies.proceedWithAllProblems(),
buildConfig.getOptions().getMap(),
getBatchRequestor(),
getProblemFactory());
CompilerOptions options = compiler.options;
options.produceReferenceInfo = true; //TODO turn off when not needed
try {
compiler.compile(getCompilationUnits(filenames, encodings));
} catch (OperationCanceledException oce) {
handler.handleMessage(new Message("build cancelled:"+oce.getMessage(),IMessage.WARNING,null,null));
}
// cleanup
environment.cleanup();
environment = null;
}
/*
* Answer the component to which will be handed back compilation results from the compiler
*/
public IIntermediateResultsRequestor getInterimResultRequestor() {
return new IIntermediateResultsRequestor() {
int lineDelta = 0;
public void acceptResult(InterimCompilationResult result) {
if (progressListener != null) {
compiledCount++;
progressListener.setProgress((compiledCount/2.0)/sourceFileCount);
progressListener.setText("compiled: " + result.fileName());
}
state.noteResult(result);
if (progressListener!=null && progressListener.isCancelledRequested()) {
throw new AbortCompilation(true,
new OperationCanceledException("Compilation cancelled as requested"));
}
}
};
}
public ICompilerRequestor getBatchRequestor() {
return new ICompilerRequestor() {
public void acceptResult(CompilationResult unitResult) {
// end of compile, must now write the results to the output destination
// this is either a jar file or a file in a directory
if (!(unitResult.hasErrors() && !proceedOnError())) {
Enumeration classFiles = unitResult.compiledTypes.elements();
while (classFiles.hasMoreElements()) {
ClassFile classFile = (ClassFile) classFiles.nextElement();
String filename = new String(classFile.fileName());
filename = filename.replace('/', File.separatorChar) + ".class";
try {
if (buildConfig.getOutputJar() == null) {
writeDirectoryEntry(unitResult, classFile,filename);
} else {
writeZipEntry(classFile,filename);
}
} catch (IOException ex) {
IMessage message = EclipseAdapterUtils.makeErrorMessage(
new String(unitResult.fileName),
CANT_WRITE_RESULT,
ex);
handler.handleMessage(message);
}
}
}
if (unitResult.hasProblems() || unitResult.hasTasks()) {
IProblem[] problems = unitResult.getAllProblems();
for (int i=0; i < problems.length; i++) {
IMessage message =
EclipseAdapterUtils.makeMessage(unitResult.compilationUnit, problems[i]);
handler.handleMessage(message);
}
}
}
private void writeDirectoryEntry(
CompilationResult unitResult,
ClassFile classFile,
String filename)
throws IOException {
File destinationPath = buildConfig.getOutputDir();
String outFile;
if (destinationPath == null) {
outFile = new File(filename).getName();
outFile = new File(extractDestinationPathFromSourceFile(unitResult), outFile).getPath();
} else {
outFile = new File(destinationPath, filename).getPath();
}
BufferedOutputStream os =
FileUtil.makeOutputStream(new File(outFile));
os.write(classFile.getBytes());
os.close();
}
private void writeZipEntry(ClassFile classFile, String name)
throws IOException {
name = name.replace(File.separatorChar,'/');
ZipEntry newEntry = new ZipEntry(name); //??? get compression scheme right
zos.putNextEntry(newEntry);
zos.write(classFile.getBytes());
zos.closeEntry();
}
};
}
protected boolean proceedOnError() {
return true; //???
}
// public void noteClassFiles(AjCompiler.InterimResult result) {
// if (result == null) return;
// CompilationResult unitResult = result.result;
// String sourceFileName = result.fileName();
// if (!(unitResult.hasErrors() && !proceedOnError())) {
// List unwovenClassFiles = new ArrayList();
// Enumeration classFiles = unitResult.compiledTypes.elements();
// while (classFiles.hasMoreElements()) {
// ClassFile classFile = (ClassFile) classFiles.nextElement();
// String filename = new String(classFile.fileName());
// filename = filename.replace('/', File.separatorChar) + ".class";
//
// File destinationPath = buildConfig.getOutputDir();
// if (destinationPath == null) {
// filename = new File(filename).getName();
// filename = new File(extractDestinationPathFromSourceFile(unitResult), filename).getPath();
// } else {
// filename = new File(destinationPath, filename).getPath();
// }
//
// //System.out.println("classfile: " + filename);
// unwovenClassFiles.add(new UnwovenClassFile(filename, classFile.getBytes()));
// }
// state.noteClassesFromFile(unitResult, sourceFileName, unwovenClassFiles);
//// System.out.println("file: " + sourceFileName);
//// for (int i=0; i < unitResult.simpleNameReferences.length; i++) {
//// System.out.println("simple: " + new String(unitResult.simpleNameReferences[i]));
//// }
//// for (int i=0; i < unitResult.qualifiedReferences.length; i++) {
//// System.out.println("qualified: " +
//// new String(CharOperation.concatWith(unitResult.qualifiedReferences[i], '/')));
//// }
// } else {
// state.noteClassesFromFile(null, sourceFileName, Collections.EMPTY_LIST);
// }
// }
//
private void setBuildConfig(AjBuildConfig buildConfig) {
this.buildConfig = buildConfig;
handler.reset();
}
String makeClasspathString() {
if (buildConfig == null || buildConfig.getFullClasspath() == null) return "";
StringBuffer buf = new StringBuffer();
boolean first = true;
for (Iterator it = buildConfig.getFullClasspath().iterator(); it.hasNext(); ) {
if (first) { first = false; }
else { buf.append(File.pathSeparator); }
buf.append(it.next().toString());
}
return buf.toString();
}
/**
* This will return null if aspectjrt.jar is present and has the correct version.
* Otherwise it will return a string message indicating the problem.
*/
public String checkRtJar(AjBuildConfig buildConfig) {
// omitting dev info
if (Version.text.equals(Version.DEVELOPMENT)) {
// in the development version we can't do this test usefully
// MessageUtil.info(holder, "running development version of aspectj compiler");
return null;
}
if (buildConfig == null || buildConfig.getFullClasspath() == null) return "no classpath specified";
for (Iterator it = buildConfig.getFullClasspath().iterator(); it.hasNext(); ) {
File p = new File( (String)it.next() );
if (p.isFile() && p.getName().equals("aspectjrt.jar")) {
try {
String version = null;
Manifest manifest = new JarFile(p).getManifest();
if (manifest == null) {
return "no manifest found in " + p.getAbsolutePath() +
", expected " + Version.text;
}
Attributes attr = manifest.getAttributes("org/aspectj/lang/");
if (null != attr) {
version = attr.getValue(Attributes.Name.IMPLEMENTATION_VERSION);
if (null != version) {
version = version.trim();
}
}
// assume that users of development aspectjrt.jar know what they're doing
if (Version.DEVELOPMENT.equals(version)) {
// MessageUtil.info(holder,
// "running with development version of aspectjrt.jar in " +
// p.getAbsolutePath());
return null;
} else if (!Version.text.equals(version)) {
return "bad version number found in " + p.getAbsolutePath() +
" expected " + Version.text + " found " + version;
}
} catch (IOException ioe) {
return "bad jar file found in " + p.getAbsolutePath() + " error: " + ioe;
}
return null;
} else {
// might want to catch other classpath errors
}
}
return "couldn't find aspectjrt.jar on classpath, checked: " + makeClasspathString();
}
public String toString() {
StringBuffer buf = new StringBuffer();
buf.append("AjBuildManager(");
buf.append(")");
return buf.toString();
}
public void setStructureModel(IHierarchy structureModel) {
this.structureModel = structureModel;
}
/**
* Returns null if there is no structure model
*/
public IHierarchy getStructureModel() {
return structureModel;
}
public IProgressListener getProgressListener() {
return progressListener;
}
public void setProgressListener(IProgressListener progressListener) {
this.progressListener = progressListener;
}
/* (non-Javadoc)
* @see org.aspectj.ajdt.internal.compiler.AjCompiler.IOutputClassFileNameProvider#getOutputClassFileName(char[])
*/
public String getOutputClassFileName(char[] eclipseClassFileName, CompilationResult result) {
String filename = new String(eclipseClassFileName);
filename = filename.replace('/', File.separatorChar) + ".class";
File destinationPath = buildConfig.getOutputDir();
String outFile;
if (destinationPath == null) {
outFile = new File(filename).getName();
outFile = new File(extractDestinationPathFromSourceFile(result), outFile).getPath();
} else {
outFile = new File(destinationPath, filename).getPath();
}
return outFile;
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.compiler.ICompilerAdapterFactory#getAdapter(org.eclipse.jdt.internal.compiler.Compiler)
*/
public ICompilerAdapter getAdapter(org.eclipse.jdt.internal.compiler.Compiler forCompiler) {
// complete compiler config and return a suitable adapter...
AjProblemReporter pr =
new AjProblemReporter(DefaultErrorHandlingPolicies.proceedWithAllProblems(),
forCompiler.options, getProblemFactory());
forCompiler.problemReporter = pr;
AjLookupEnvironment le =
new AjLookupEnvironment(forCompiler, forCompiler.options, pr, environment);
EclipseFactory factory = new EclipseFactory(le,this);
le.factory = factory;
pr.factory = factory;
forCompiler.lookupEnvironment = le;
forCompiler.parser =
new Parser(
pr,
forCompiler.options.parseLiteralExpressionsAsConstants);
return new AjCompilerAdapter(forCompiler,batchCompile,bcelWorld,bcelWeaver,
factory,
getInterimResultRequestor(),
progressListener,
this, // IOutputFilenameProvider
this, // IBinarySourceProvider
state.binarySourceFiles,
state.resultsFromFile.values(),
buildConfig.isNoWeave());
}
/* (non-Javadoc)
* @see org.aspectj.ajdt.internal.compiler.IBinarySourceProvider#getBinarySourcesForThisWeave()
*/
public Map getBinarySourcesForThisWeave() {
return binarySourcesForTheNextCompile;
}
public static AsmHierarchyBuilder getAsmHierarchyBuilder() {
return asmHierarchyBuilder;
}
/**
* Override the the default hierarchy builder.
*/
public static void setAsmHierarchyBuilder(AsmHierarchyBuilder newBuilder) {
asmHierarchyBuilder = newBuilder;
}
public AjState getState() {
return state;
}
} // class AjBuildManager
|
73,334
|
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
|
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
|
resolved fixed
|
b133299
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:40:02Z
| 2004-09-06T17:00:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AjBuildNotifier.java
|
/*******************************************************************************
* Copyright (c) 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.aspectj.ajdt.internal.core.builder;
import org.aspectj.bridge.IProgressListener;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jdt.internal.core.builder.BuildNotifier;
/**
* @author colyer
*
* Build progress notification inside Eclipse
*/
public class AjBuildNotifier extends BuildNotifier implements IProgressListener {
/**
* @param monitor
* @param project
*/
public AjBuildNotifier(IProgressMonitor monitor, IProject project) {
super(monitor, project);
}
/* (non-Javadoc)
* @see org.aspectj.bridge.IProgressListener#setText(java.lang.String)
*/
public void setText(String text) {
subTask(text);
}
/* (non-Javadoc)
* @see org.aspectj.bridge.IProgressListener#setProgress(double)
*/
public void setProgress(double percentDone) {
updateProgress((float)(percentDone/100.0f));
}
/* (non-Javadoc)
* @see org.aspectj.bridge.IProgressListener#setCancelledRequested(boolean)
*/
public void setCancelledRequested(boolean cancelRequested) {
// no-op
}
/* (non-Javadoc)
* @see org.aspectj.bridge.IProgressListener#isCancelledRequested()
*/
public boolean isCancelledRequested() {
// can't delegate to super methods as they throw exception, which is not what we want inside weaver
boolean cancelRequested = cancelling;
if (monitor != null) {
cancelRequested = cancelRequested || monitor.isCanceled();
}
return cancelRequested;
}
}
|
73,334
|
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
|
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
|
resolved fixed
|
b133299
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:40:02Z
| 2004-09-06T17:00:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AjCompilerOptions.java
|
/* *******************************************************************
* 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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.core.builder;
import java.util.Map;
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
/**
* Compiler options used by Eclipse integration (AJDT)
*/
public class AjCompilerOptions extends CompilerOptions {
// AspectJ Lint options
public static final String OPTION_ReportInvalidAbsoluteTypeName = "org.aspectj.ajdt.core.compiler.lint.InvalidAbsoluteTypeName";
public static final String OPTION_ReportInvalidWildcardTypeName = "org.aspectj.ajdt.core.compiler.lint.WildcardTypeName";
public static final String OPTION_ReportUnresolvableMember = "org.aspectj.ajdt.core.compiler.lint.UnresolvableMember";
public static final String OPTION_ReportTypeNotExposedToWeaver = "org.aspectj.ajdt.core.compiler.lint.TypeNotExposedToWeaver";
public static final String OPTION_ReportShadowNotInStructure = "org.aspectj.ajdt.core.compiler.lint.ShadowNotInStructure";
public static final String OPTION_ReportUnmatchedSuperTypeInCall = "org.aspectj.ajdt.core.compiler.list.UnmatchedSuperTypeInCall";
public static final String OPTION_ReportCannotImplementLazyTJP = "org.aspectj.ajdt.core.compiler.lint.CannotImplementLazyTJP";
public static final String OPTION_ReportNeedSerialVersionUIDField = "org.aspectj.ajdt.core.compiler.lint.NeedSerialVersionUIDField";
public static final String OPTION_ReportIncompatibleSerialVersion = "org.aspectj.ajdt.core.compiler.lint.BrokeSerialVersionCompatibility";
// General AspectJ Compiler options (excludes paths etc, these are handled separately)
public static final String OPTION_NoWeave = "org.aspectj.ajdt.core.compiler.weaver.NoWeave";
public static final String OPTION_XSerializableAspects = "org.aspectj.ajdt.core.compiler.weaver.XSerializableAspects";
public static final String OPTION_XLazyThisJoinPoint = "org.aspectj.ajdt.core.compiler.weaver.XLazyThisJoinPoint";
public static final String OPTION_XNoInline = "org.aspectj.ajdt.core.compiler.weaver.XNoInline";
public static final String OPTION_XReweavable = "org.aspectj.ajdt.core.compiler.weaver.XReweavable";
public static final String OPTION_XReweavableCompress = "org.aspectj.ajdt.core.compiler.weaver.XReweavableCompress";
// these next three not exposed by IDEs
public static final String OPTION_GenerateModel = "org.aspectj.ajdt.core.compiler.model.GenerateModel";
public static final String OPTION_GenerateJavaDocsInModel = "org.aspectj.ajdt.core.compiler.model.GenerateJavaDocsInModel";
public static final String OPTION_Emacssym = "org.aspectj.ajdt.core.compiler.model.Emacssym";
// constants for irritant levels
public static final long InvalidAbsoluteTypeName = 0x20000000000L;
public static final long InvalidWildCardTypeName = 0x40000000000L;
public static final long UnresolvableMember = 0x80000000000L;
public static final long TypeNotExposedToWeaver = 0x100000000000L;
public static final long ShadowNotInStructure = 0x200000000000L;
public static final long UnmatchedSuperTypeInCall = 0x400000000000L;
public static final long CannotImplementLazyTJP = 0x800000000000L;
public static final long NeedSerialVersionUIDField = 0x1000000000000L;
public static final long IncompatibleSerialVersion = 0x2000000000000L;
public boolean noWeave = false;
public boolean xSerializableAspects = false;
public boolean xLazyThisJoinPoint = false;
public boolean xNoInline = false;
public boolean xReweavable = false;
public boolean xReweavableCompress = false;
public boolean showWeavingInformation = false;
// these next three not exposed by IDEs
public boolean generateModel = false;
public boolean generateJavaDocsInModel = false;
public boolean generateEmacsSymFiles = false;
/**
* Initializing the compiler options with defaults
*/
public AjCompilerOptions(){
super();
setAspectJWarningDefaults();
}
/**
* Initializing the compiler options with external settings
* @param settings
*/
public AjCompilerOptions(Map settings){
setAspectJWarningDefaults();
if (settings == null) return;
set(settings);
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.compiler.impl.CompilerOptions#getMap()
*/
public Map getMap() {
Map map = super.getMap();
// now add AspectJ additional options
map.put(OPTION_ReportInvalidAbsoluteTypeName,getSeverityString(InvalidAbsoluteTypeName));
map.put(OPTION_ReportInvalidWildcardTypeName,getSeverityString(InvalidWildCardTypeName));
map.put(OPTION_ReportUnresolvableMember,getSeverityString(UnresolvableMember));
map.put(OPTION_ReportTypeNotExposedToWeaver,getSeverityString(TypeNotExposedToWeaver));
map.put(OPTION_ReportShadowNotInStructure,getSeverityString(ShadowNotInStructure));
map.put(OPTION_ReportUnmatchedSuperTypeInCall,getSeverityString(UnmatchedSuperTypeInCall));
map.put(OPTION_ReportCannotImplementLazyTJP,getSeverityString(CannotImplementLazyTJP));
map.put(OPTION_ReportNeedSerialVersionUIDField,getSeverityString(NeedSerialVersionUIDField));
map.put(OPTION_ReportIncompatibleSerialVersion,getSeverityString(IncompatibleSerialVersion));
map.put(OPTION_NoWeave, this.noWeave ? ENABLED : DISABLED);
map.put(OPTION_XSerializableAspects,this.xSerializableAspects ? ENABLED : DISABLED);
map.put(OPTION_XLazyThisJoinPoint,this.xLazyThisJoinPoint ? ENABLED : DISABLED);
map.put(OPTION_XNoInline,this.xNoInline ? ENABLED : DISABLED);
map.put(OPTION_XReweavable,this.xReweavable ? ENABLED : DISABLED);
map.put(OPTION_XReweavableCompress,this.xReweavableCompress ? ENABLED : DISABLED);
map.put(OPTION_GenerateModel,this.generateModel ? ENABLED : DISABLED);
map.put(OPTION_GenerateJavaDocsInModel,this.generateJavaDocsInModel ? ENABLED : DISABLED);
map.put(OPTION_Emacssym,this.generateEmacsSymFiles ? ENABLED : DISABLED);
return map;
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.compiler.impl.CompilerOptions#set(java.util.Map)
*/
public void set(Map optionsMap) {
super.set(optionsMap);
Object optionValue;
if ((optionValue = optionsMap.get(OPTION_ReportInvalidAbsoluteTypeName)) != null) updateSeverity(InvalidAbsoluteTypeName, optionValue);
if ((optionValue = optionsMap.get(OPTION_ReportInvalidWildcardTypeName)) != null) updateSeverity(InvalidWildCardTypeName, optionValue);
if ((optionValue = optionsMap.get(OPTION_ReportUnresolvableMember)) != null) updateSeverity(UnresolvableMember, optionValue);
if ((optionValue = optionsMap.get(OPTION_ReportTypeNotExposedToWeaver)) != null) updateSeverity(TypeNotExposedToWeaver, optionValue);
if ((optionValue = optionsMap.get(OPTION_ReportShadowNotInStructure)) != null) updateSeverity(ShadowNotInStructure, optionValue);
if ((optionValue = optionsMap.get(OPTION_ReportUnmatchedSuperTypeInCall)) != null) updateSeverity(UnmatchedSuperTypeInCall, optionValue);
if ((optionValue = optionsMap.get(OPTION_ReportCannotImplementLazyTJP)) != null) updateSeverity(CannotImplementLazyTJP, optionValue);
if ((optionValue = optionsMap.get(OPTION_ReportNeedSerialVersionUIDField)) != null) updateSeverity(NeedSerialVersionUIDField, optionValue);
if ((optionValue = optionsMap.get(OPTION_ReportIncompatibleSerialVersion)) != null) updateSeverity(IncompatibleSerialVersion, optionValue);
if ((optionValue = optionsMap.get(OPTION_NoWeave)) != null) {
if (ENABLED.equals(optionValue)) {
this.noWeave = true;
} else if (DISABLED.equals(optionValue)) {
this.noWeave = false;
}
}
if ((optionValue = optionsMap.get(OPTION_XSerializableAspects)) != null) {
if (ENABLED.equals(optionValue)) {
this.xSerializableAspects = true;
} else if (DISABLED.equals(optionValue)) {
this.xSerializableAspects = false;
}
}
if ((optionValue = optionsMap.get(OPTION_XLazyThisJoinPoint)) != null) {
if (ENABLED.equals(optionValue)) {
this.xLazyThisJoinPoint = true;
} else if (DISABLED.equals(optionValue)) {
this.xLazyThisJoinPoint = false;
}
}
if ((optionValue = optionsMap.get(OPTION_XNoInline)) != null) {
if (ENABLED.equals(optionValue)) {
this.xNoInline = true;
} else if (DISABLED.equals(optionValue)) {
this.xNoInline = false;
}
}
if ((optionValue = optionsMap.get(OPTION_XReweavable)) != null) {
if (ENABLED.equals(optionValue)) {
this.xReweavable = true;
} else if (DISABLED.equals(optionValue)) {
this.xReweavable = false;
}
}
if ((optionValue = optionsMap.get(OPTION_XReweavableCompress)) != null) {
if (ENABLED.equals(optionValue)) {
this.xReweavableCompress = true;
} else if (DISABLED.equals(optionValue)) {
this.xReweavableCompress = false;
}
}
if ((optionValue = optionsMap.get(OPTION_GenerateModel)) != null) {
if (ENABLED.equals(optionValue)) {
this.generateModel = true;
} else if (DISABLED.equals(optionValue)) {
this.generateModel = false;
}
}
if ((optionValue = optionsMap.get(OPTION_GenerateJavaDocsInModel)) != null) {
if (ENABLED.equals(optionValue)) {
this.generateJavaDocsInModel = true;
} else if (DISABLED.equals(optionValue)) {
this.generateJavaDocsInModel = false;
}
}
if ((optionValue = optionsMap.get(OPTION_Emacssym)) != null) {
if (ENABLED.equals(optionValue)) {
this.generateEmacsSymFiles = true;
} else if (DISABLED.equals(optionValue)) {
this.generateEmacsSymFiles = false;
}
}
}
/**
* Add these warnings to the default set...
*/
private void setAspectJWarningDefaults() {
super.warningThreshold =
super.warningThreshold |
InvalidAbsoluteTypeName |
UnresolvableMember |
TypeNotExposedToWeaver |
UnmatchedSuperTypeInCall |
CannotImplementLazyTJP;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
public String toString() {
StringBuffer buf = new StringBuffer( super.toString() );
// now add AspectJ additional options
buf.append("\n\tAspectJ Specific Options:");
buf.append("\n\t- no weave: ").append(this.noWeave ? ENABLED : DISABLED); //$NON-NLS-1$
buf.append("\n\t- no inline (X option): ").append(this.xNoInline ? ENABLED : DISABLED); //$NON-NLS-1$
buf.append("\n\t- generate serializable aspects (X option): ").append(this.xSerializableAspects ? ENABLED : DISABLED); //$NON-NLS-1$
buf.append("\n\t- lazy thisJoinPoint (X option): ").append(this.xLazyThisJoinPoint ? ENABLED : DISABLED); //$NON-NLS-1$
buf.append("\n\t- generate reweavable class files (X option): ").append(this.xReweavable ? ENABLED : DISABLED); //$NON-NLS-1$
buf.append("\n\t- compress reweavable class files (X option): ").append(this.xReweavableCompress ? ENABLED : DISABLED); //$NON-NLS-1$
buf.append("\n\t- generate AJDE model: ").append(this.generateModel ? ENABLED : DISABLED); //$NON-NLS-1$
buf.append("\n\t- generate Javadocs in AJDE model: ").append(this.generateJavaDocsInModel ? ENABLED : DISABLED); //$NON-NLS-1$
buf.append("\n\t- generate Emacs symbol files: ").append(this.generateEmacsSymFiles ? ENABLED : DISABLED); //$NON-NLS-1$
buf.append("\n\t- invalid absolute type name (XLint): ").append(getSeverityString(InvalidAbsoluteTypeName)); //$NON-NLS-1$
buf.append("\n\t- invalid wildcard type name (XLint): ").append(getSeverityString(InvalidWildCardTypeName)); //$NON-NLS-1$
buf.append("\n\t- unresolvable member (XLint): ").append(getSeverityString(UnresolvableMember)); //$NON-NLS-1$
buf.append("\n\t- type not exposed to weaver (XLint): ").append(getSeverityString(TypeNotExposedToWeaver)); //$NON-NLS-1$
buf.append("\n\t- shadow not in structure (XLint): ").append(getSeverityString(ShadowNotInStructure)); //$NON-NLS-1$
buf.append("\n\t- unmatched super type in call (XLint): ").append(getSeverityString(UnmatchedSuperTypeInCall)); //$NON-NLS-1$
buf.append("\n\t- cannot implement lazy thisJoinPoint (XLint): ").append(getSeverityString(CannotImplementLazyTJP)); //$NON-NLS-1$
buf.append("\n\t- need serialVersionUID field (XLint): ").append(getSeverityString(NeedSerialVersionUIDField)); //$NON-NLS-1$
buf.append("\n\t- incompatible serial version (XLint): ").append(getSeverityString(IncompatibleSerialVersion)); //$NON-NLS-1$
return buf.toString();
}
}
|
73,334
|
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
|
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
|
resolved fixed
|
b133299
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-09-06T15:40:02Z
| 2004-09-06T17:00:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AjIncrementalImageBuilder.java
|
/*******************************************************************************
* Copyright (c) 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.aspectj.ajdt.internal.core.builder;
import org.eclipse.jdt.internal.compiler.CompilationResult;
import org.eclipse.jdt.internal.core.builder.IncrementalImageBuilder;
import org.eclipse.jdt.internal.core.builder.SourceFile;
/**
* @author colyer
*
* Incremental builder used by IDE support (AJDT)
*/
public class AjIncrementalImageBuilder extends IncrementalImageBuilder {
public AjIncrementalImageBuilder(AspectJBuilder builder) {
super(builder);
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.compiler.ICompilerRequestor#acceptResult(org.eclipse.jdt.internal.compiler.CompilationResult)
*/
public void acceptResult(CompilationResult result) {
if ((result.getCompilationUnit() != null) && (result.getCompilationUnit() instanceof SourceFile)) {
super.acceptResult(result);
} else {
// it's a file originating from binary source...
// we need to handle it ourselves
// TODO handle binary source output
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.