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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
41,254
|
Bug 41254 revise asm and create interfaces
| null |
resolved fixed
|
f1deb9c
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2003-08-08T11:02:53Z
| 2003-08-07T12:40:00Z
|
asm/src/org/aspectj/asm/StructureModel.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.asm;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.*;
import org.aspectj.bridge.SourceLocation;
/**
* @author Mik Kersten
*/
public class StructureModel implements Serializable {
protected StructureNode root = null;
protected String configFile = null;
private Map fileMap = null;
public static final ProgramElementNode NO_STRUCTURE = new ProgramElementNode("<build to view structure>", ProgramElementNode.Kind.ERROR, null);
public StructureNode getRoot() {
return root;
}
public void setRoot(StructureNode root) {
this.root = root;
}
private Map getFileMap() {
return fileMap;
}
public void addToFileMap( Object key, Object value ){
fileMap.put( key, value );
}
public Object findInFileMap( Object key ) {
return fileMap.get(key);
}
public void setFileMap(HashMap fileMap) {
this.fileMap = fileMap;
}
public Set getFileMapEntrySet() {
return fileMap.entrySet();
}
public boolean isValid() {
return root != null && fileMap != null;
}
/**
* Returns the first match
*
* @param parent
* @param kind not null
* @param decErrLabel
* @return null if not found
*/
public ProgramElementNode findNode(ProgramElementNode parent, ProgramElementNode.Kind kind, String name) {
for (Iterator it = parent.getChildren().iterator(); it.hasNext(); ) {
ProgramElementNode node = (ProgramElementNode)it.next();
if (node.getProgramElementKind().equals(kind)
&& name.equals(node.getName())) {
return node;
} else {
ProgramElementNode childSearch = findNode(node, kind, name);
if (childSearch != null) return childSearch;
}
}
return null;
}
/**
* @param packageName if null default package is searched
* @param className can't be null
*/
public ProgramElementNode findNodeForClass(String packageName, String className) {
StructureNode packageNode = null;
if (packageName == null) {
packageNode = root;
} else {
for (Iterator it = root.getChildren().iterator(); it.hasNext(); ) {
StructureNode node = (StructureNode)it.next();
if (packageName.equals(node.getName())) {
packageNode = node;
}
}
if (packageNode == null) return null;
}
// this searches each file for a class
for (Iterator it = packageNode.getChildren().iterator(); it.hasNext(); ) {
ProgramElementNode fileNode = (ProgramElementNode)it.next();
ProgramElementNode ret = findClassInNodes(fileNode.getChildren(), className);
if (ret != null) return ret;
}
return null;
}
private ProgramElementNode findClassInNodes(Collection nodes, String name) {
String baseName;
String innerName;
int dollar = name.indexOf('$');
if (dollar == -1) {
baseName = name;
innerName = null;
} else {
baseName = name.substring(0, dollar);
innerName = name.substring(dollar+1);
}
for (Iterator j = nodes.iterator(); j.hasNext(); ) {
ProgramElementNode classNode = (ProgramElementNode)j.next();
// System.err.println("checking: " + classNode + " for " + baseName);
// System.err.println("children: " + classNode.getChildren());
if (baseName.equals(classNode.getName())) {
if (innerName == null) return classNode;
else return findClassInNodes(classNode.getChildren(), innerName);
} else if (name.equals(classNode.getName())) {
return classNode;
}
}
return null;
}
/**
* @param sourceFilePath modified to '/' delimited path for consistency
* @return a new structure node for the file if it was not found in the model
*/
public StructureNode findRootNodeForSourceFile(String sourceFile) {
try {
if (!isValid() || sourceFile == null) {
return StructureModel.NO_STRUCTURE;
} else {
String correctedPath = new File(sourceFile).getCanonicalPath();//.replace('\\', '/');
//StructureNode node = (StructureNode)getFileMap().get(correctedPath);//findFileNode(filePath, model);
StructureNode node = (StructureNode)findInFileMap(correctedPath);//findFileNode(filePath, model);
if (node != null) {
return node;
} else {
return createFileStructureNode(correctedPath);
}
}
} catch (Exception e) {
return StructureModel.NO_STRUCTURE;
}
}
/**
* Never returns null
*
* @param sourceFilePath canonicalized path for consistency
* @param lineNumber if 0 or 1 the corresponding file node will be returned
* @return a new structure node for the file if it was not found in the model
*/
public StructureNode findNodeForSourceLine(String sourceFilePath, int lineNumber) {
String correctedPath = sourceFilePath;//.replace('\\', '/');
StructureNode node = findNodeForSourceLineHelper(root, correctedPath, lineNumber);
if (node != null) {
return node;
} else {
return createFileStructureNode(sourceFilePath);
}
}
private StructureNode createFileStructureNode(String sourceFilePath) {
String fileName = new File(sourceFilePath).getName();
ProgramElementNode fileNode = new ProgramElementNode(fileName, ProgramElementNode.Kind.FILE_JAVA, null);
fileNode.setSourceLocation(new SourceLocation(new File(sourceFilePath), 1, 1));
fileNode.addChild(NO_STRUCTURE);
return fileNode;
}
private StructureNode findNodeForSourceLineHelper(StructureNode node, String sourceFilePath, int lineNumber) {
if (matches(node, sourceFilePath, lineNumber)
&& !hasMoreSpecificChild(node, sourceFilePath, lineNumber)) {
return node;
}
if (node != null && node.getChildren() != null) {
for (Iterator it = node.getChildren().iterator(); it.hasNext(); ) {
StructureNode foundNode = findNodeForSourceLineHelper(
(StructureNode)it.next(),
sourceFilePath,
lineNumber);
if (foundNode != null) return foundNode;
}
}
return null;
}
private boolean matches(StructureNode node, String sourceFilePath, int lineNumber) {
try {
// if (node != null && node.getSourceLocation() != null)
// System.err.println("====\n1: " +
// sourceFilePath + "\n2: " +
// node.getSourceLocation().getSourceFile().getCanonicalPath().equals(sourceFilePath)
// );
return node != null
&& node.getSourceLocation() != null
&& node.getSourceLocation().getSourceFile().getCanonicalPath().equals(sourceFilePath)
&& ((node.getSourceLocation().getLine() <= lineNumber
&& node.getSourceLocation().getEndLine() >= lineNumber)
||
(lineNumber <= 1
&& node instanceof ProgramElementNode
&& ((ProgramElementNode)node).getProgramElementKind().isSourceFileKind())
);
} catch (IOException ioe) {
return false;
}
}
private boolean hasMoreSpecificChild(StructureNode node, String sourceFilePath, int lineNumber) {
for (Iterator it = node.getChildren().iterator(); it.hasNext(); ) {
ProgramElementNode child = (ProgramElementNode)it.next();
if (matches(child, sourceFilePath, lineNumber)) return true;
}
return false;
}
public String getConfigFile() {
return configFile;
}
public void setConfigFile(String configFile) {
this.configFile = configFile;
}
}
|
41,254
|
Bug 41254 revise asm and create interfaces
| null |
resolved fixed
|
f1deb9c
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2003-08-08T11:02:53Z
| 2003-08-07T12:40:00Z
|
asm/src/org/aspectj/asm/StructureModelListener.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.asm;
import java.util.EventListener;
/**
* Compiler listeners get notified of structure model update events.
*
* @author Mik Kersten
*/
public interface StructureModelListener extends EventListener {
public void modelUpdated(StructureModel rootNode);
}
|
41,254
|
Bug 41254 revise asm and create interfaces
| null |
resolved fixed
|
f1deb9c
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2003-08-08T11:02:53Z
| 2003-08-07T12:40:00Z
|
asm/src/org/aspectj/asm/StructureModelManager.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.asm;
import java.util.*;
import java.io.*;
import org.aspectj.bridge.ISourceLocation;
/**
* @author Mik Kersten
*/
public class StructureModelManager {
/**
* @deprecated use getDefault() method instead
*/
public static StructureModelManager INSTANCE = new StructureModelManager();
private boolean shouldSaveModel = true;
protected StructureModel model = new StructureModel();
private List structureListeners = new ArrayList();
private List associations = new ArrayList();
protected StructureModelManager() {
associations.add(new AdviceAssociation());
associations.add(new IntroductionAssociation());
associations.add(new InheritanceAssociation());
associations.add(new ReferenceAssociation());
}
public StructureModel getStructureModel() {
return model;
}
public void fireModelUpdated() {
notifyListeners();
if (model.getConfigFile() != null) {
writeStructureModel(model.getConfigFile());
}
}
/**
* Constructs map each time it's called.
*/
public HashMap getInlineAnnotations(
String sourceFile,
boolean showSubMember,
boolean showMemberAndType) {
if (!model.isValid()) return null;
HashMap annotations = new HashMap();
StructureNode node = model.findRootNodeForSourceFile(sourceFile);
if (node == StructureModel.NO_STRUCTURE) {
return null;
} else {
ProgramElementNode fileNode = (ProgramElementNode)node;
ArrayList peNodes = new ArrayList();
getAllStructureChildren(fileNode, peNodes, showSubMember, showMemberAndType);
for (Iterator it = peNodes.iterator(); it.hasNext(); ) {
ProgramElementNode peNode = (ProgramElementNode)it.next();
List entries = new ArrayList();
entries.add(peNode);
ISourceLocation sourceLoc = peNode.getSourceLocation();
if (null != sourceLoc) {
Integer hash = new Integer(sourceLoc.getLine());
List existingEntry = (List)annotations.get(hash);
if (existingEntry != null) {
entries.addAll(existingEntry);
}
annotations.put(hash, entries);
}
}
return annotations;
}
}
private void getAllStructureChildren(ProgramElementNode node, List result, boolean showSubMember, boolean showMemberAndType) {
List children = node.getChildren();
for (Iterator it = children.iterator(); it.hasNext(); ) {
StructureNode next = (StructureNode)it.next();
if (next instanceof ProgramElementNode) {
ProgramElementNode pNode = (ProgramElementNode)next;
if (pNode != null
&& ((pNode.isCode() && showSubMember) || (!pNode.isCode() && showMemberAndType))
&& pNode.getRelations() != null
&& pNode.getRelations().size() > 0) {
result.add(next);
}
getAllStructureChildren((ProgramElementNode)next, result, showSubMember, showMemberAndType);
}
}
}
public void addListener(StructureModelListener listener) {
structureListeners.add(listener);
}
public void removeStructureListener(StructureModelListener listener) {
structureListeners.remove(listener);
}
private void notifyListeners() {
for (Iterator it = structureListeners.iterator(); it.hasNext(); ) {
((StructureModelListener)it.next()).modelUpdated(model);
}
}
public List getAssociations() {
return associations;
}
/**
* Fails silently.
*/
public void writeStructureModel(String configFilePath) {
try {
String filePath = genExternFilePath(configFilePath);
ObjectOutputStream s = new ObjectOutputStream(new FileOutputStream(filePath));
s.writeObject(model);
s.flush();
} catch (Exception e) {
// ignore
}
}
/**
* @todo add proper handling of bad paths/suffixes/etc
* @param configFilePath path to an ".lst" file
*/
public void readStructureModel(String configFilePath) {
try {
if (configFilePath == null) {
model.setRoot(StructureModel.NO_STRUCTURE);
} else {
String filePath = genExternFilePath(configFilePath);
FileInputStream in = new FileInputStream(filePath);
ObjectInputStream s = new ObjectInputStream(in);
model = (StructureModel)s.readObject();
}
} catch (Exception e) {
//System.err.println("AJDE Message: could not read structure model: " + e);
model.setRoot(StructureModel.NO_STRUCTURE);
} finally {
notifyListeners();
}
}
private String genExternFilePath(String configFilePath) {
return configFilePath.substring(0, configFilePath.lastIndexOf(".lst")) + ".ajsym";
}
public void setShouldSaveModel(boolean shouldSaveModel) {
this.shouldSaveModel = shouldSaveModel;
}
public static StructureModelManager getDefault() {
return INSTANCE;
}
}
|
41,254
|
Bug 41254 revise asm and create interfaces
| null |
resolved fixed
|
f1deb9c
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2003-08-08T11:02:53Z
| 2003-08-07T12:40:00Z
|
asm/src/org/aspectj/asm/StructureNode.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.asm;
import java.util.*;
import java.io.*;
import org.aspectj.bridge.*;
import org.aspectj.bridge.IMessage;
/**
* Children are non-repeating making the parent-child structure a strict
* tree.
*
* !!! relies on a java.io.Serializable implementation of ISourceLocation
*
* @author Mik Kersten
*/
public abstract class StructureNode implements Serializable, Comparable {
protected StructureNode parent = null;
protected String name = "";
protected String kind = "";
// children.listIterator() should support remove() operation
protected List children = new ArrayList();
protected IMessage message = null;
protected ISourceLocation sourceLocation = null;
/**
* Used during serialization.
*/
public StructureNode() { }
public StructureNode(String name, String kind, List children) {
this.name = name;
this.kind = kind;
if (children != null) {
this.children = children;
}
setParents();
}
public StructureNode(String name, String kind) {
this.name = name;
this.kind = kind;
}
public String toLongString() {
final StringBuffer buffer = new StringBuffer();
ModelWalker walker = new ModelWalker() {
private int depth = 0;
public void preProcess(StructureNode node) {
for (int i = 0; i < depth; i++) buffer.append(' ');
buffer.append(node.toString());
buffer.append('\n');
depth += 2;
}
public void postProcess(StructureNode node) {
depth -= 2;
}
};
walker.process(this);
return buffer.toString();
}
public String toString() {
return name;
}
public String getKind() {
return kind;
}
public List getChildren() {
return children;
}
public void addChild(StructureNode child) {
if (children == null) {
children = new ArrayList();
}
children.add(child);
child.setParent(this);
}
public void addChild(int position, StructureNode child) {
if (children == null) {
children = new ArrayList();
}
children.add(position, child);
child.setParent(this);
}
public boolean removeChild(StructureNode child) {
child.setParent(null);
return children.remove(child);
}
public StructureNode walk(ModelWalker walker) {
for (Iterator it = children.iterator(); it.hasNext(); ) {
StructureNode child = (StructureNode)it.next();
walker.process(child);
}
return this;
}
// public boolean equals(Object o) {
// if (!(o instanceof StructureNode)) return false;
// StructureNode sn = (StructureNode)o;
// return objectEqual(sn.getName(), this.getName())
// && objectEqual(sn.getKind(), this.getKind())
// && objectEqual(sn.getChildren(), this.getChildren());
// }
//
// protected boolean objectEqual(Object o1, Object o2) {
// return (o1 == null && o2 == null) || (o1 != null && o1.equals(o2));
// }
/**
* Comparison is string-name based only.
*/
public int compareTo(Object o) throws ClassCastException {
if (this == o) {
return 0;
} else {
StructureNode sn = (StructureNode)o;
return this.getName().compareTo(sn.getName());
}
}
public String getName() {
return name;
}
public ISourceLocation getSourceLocation() {
return sourceLocation;
}
public void setSourceLocation(ISourceLocation sourceLocation) {
this.sourceLocation = sourceLocation;
}
public IMessage getMessage() {
return message;
}
public void setMessage(IMessage message) {
this.message = message;
}
public StructureNode getParent() {
return parent;
}
public void setParent(StructureNode parent) {
this.parent = parent;
}
private void setParents() {
if (children == null) return;
for (Iterator it = children.iterator(); it.hasNext(); ) {
((StructureNode)it.next()).setParent(this);
}
}
//
// /**
// * Creates and returns a copy of this object.
// */
// public Object clone() {
// List cloneChildren = new ArrayList();
// for (Iterator it = children.iterator(); it.hasNext(); ) {
// cloneChildren.add(((StructureNode)it.next()).clone());
// }
// StructureNode cloneNode = new StructureNode(name, kind, cloneChildren);
// return cloneNode;
// }
public void setName(String string) {
name = string;
}
}
// private void writeObject(ObjectOutputStream s) throws IOException {
// s.defaultWriteObject();
// // customized serialization code
// }
//
// private void readObject(ObjectInputStream s) throws IOException {
// s.defaultReadObject();
// // customized deserialization code
// ...
// // followed by code to update the object, if necessary
// }
// public void writeExternal(ObjectOutput out) throws IOException {
// if (this instanceof ProgramElementNode) {
// out.writeInt(1);
// writeString(name, out);
// writeString(kind, out);
// ((ProgramElementNode)this).writeExternal(out);
// } if (this instanceof RelationNode) {
// out.writeInt(1);
// writeString(name, out);
// writeString(kind, out);
// ((RelationNode)this).writeExternal(out);
// } if (this instanceof LinkNode) {
// out.writeInt(3);
// writeString(name, out);
// writeString(kind, out);
// ((LinkNode)this).writeExternal(out);
// } else {
// out.writeInt(0);
// writeString(name, out);
// writeString(kind, out);
// }
// }
//
// public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
// int kindint = in.readInt();
// name = readString(in);
// kind = readString(in);
//
// switch (kindint) {
// case 1:
// ((StructureNode)it.next()).readExternal(in);
// break;
// case 2:
// ((RelationNode)it.next()).readExternal(in);
// break;
// case 3:
// ((LinkNode)it.next()).readExternal(in);
// break;
// }
// }
//
// protected void writeString(String s, ObjectOutput out) throws IOException {
// out.writeInt(s.length());
// out.write(s.getBytes());
// }
//
// protected String readString(ObjectInput in) throws IOException {
// int length = in.readInt();
// byte[] nameArray = new byte[length];
// in.read(nameArray, 0, length);
// return new String(nameArray);
// }
//
|
41,254
|
Bug 41254 revise asm and create interfaces
| null |
resolved fixed
|
f1deb9c
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2003-08-08T11:02:53Z
| 2003-08-07T12:40:00Z
|
asm/src/org/aspectj/asm/StructureNodeFactory.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.asm;
import java.util.Hashtable;
import java.util.List;
/**
* @author Mik Kersten
*/
public class StructureNodeFactory {
private static Hashtable programElementNodes = new Hashtable();
private static final ProgramElementNode UNRESOLVED_LINK_NODE = new ProgramElementNode("<error: unresolved link>", ProgramElementNode.Kind.ERROR, null, null, "", "", "", null, null, null, false);
public static void clear() {
programElementNodes.clear();
}
public static ProgramElementNode makeNode(List relations, List children) {
return makeNode(relations, children, false);
}
public static LinkNode makeLink(boolean terminal) {
ProgramElementNode peNode = null;
if (terminal) {
peNode = makeNode(null, null, false);
} else {
peNode = makeNode(null, null, true);
}
if (peNode == null) {
return new LinkNode(UNRESOLVED_LINK_NODE);
} else {
return new LinkNode(peNode);
}
}
private static ProgramElementNode makeNode(List relations, List children, boolean resolve) {
// if (resolve) {
// if (astObject instanceof InitializerDec) {
// InitializerDec initDec = (InitializerDec)astObject;
// return (ProgramElementNode)programElementNodes.get(initDec.getDeclaringType().getTypeDec());
// } else if (astObject instanceof Decs) {
// Decs decs = (Decs)astObject;
// return (ProgramElementNode)programElementNodes.get(decs.getDeclaringType().getTypeDec());
// } else {
// ProgramElementNode peNode = (ProgramElementNode)programElementNodes.get(astObject);
// if (peNode == null) {
// return makeNode(astObject, null, null, false);
// } else {
// return peNode;
// }
// }
// } else {
// String declaringType = "";
// if (astObject.getDeclaringType() != null) {
// declaringType = astObject.getDeclaringType().toShortString();
// }
//
// org.aspectj.asm.SourceLocation sourceLocation = new org.aspectj.asm.SourceLocation(
// astObject.getSourceLocation().getSourceFileName(),
// astObject.getSourceLocation().getBeginLine(),
// astObject.getSourceLocation().getEndLine(),
// astObject.getSourceLocation().getBeginColumn());
//
// ProgramElementNode newNode = new ProgramElementNode(
// genSignature(astObject).trim(),
// genKind(astObject),
// genModifiers(astObject),
// genAccessibility(astObject),
// declaringType,
// genPackageName(astObject),
// genFormalComment(astObject),
// sourceLocation,
// relations,
// children,
// isMemberKind(astObject),
// astObject);
// programElementNodes.put(astObject, newNode);
// newNode.setRunnable(genIsRunnable(newNode));
// setSpecifiers(astObject, newNode);
//
// return newNode;
// }
return null;
}
// private static void setSpecifiers(ASTObject astObject, ProgramElementNode node) {
// if (astObject instanceof MethodDec) {
// Method method = ((MethodDec)astObject).getMethod();
// for (Iterator it = method.getDeclaringType().getDirectSuperTypes().iterator(); it.hasNext(); ) {
// NameType type = (NameType)it.next();
// SemanticObject so = type.findMatchingSemanticObject(method);
//
// if (so != null && so instanceof Method) {
//
// Method superMethod = (Method)so;
// if (so.isAbstract()) {
// node.setImplementor(true);
// } else {
// node.setOverrider(true);
// }
// }
// }
// }
// }
//
// private static boolean genIsRunnable(ProgramElementNode node) {
// if (node.getModifiers().contains(ProgramElementNode.Modifiers.STATIC)
// && node.getAccessibility().equals(ProgramElementNode.Accessibility.PUBLIC)
// && node.getSignature().equals("main(String[])")) {
// return true;
// } else {
// return false;
// }
// }
//
// private static boolean genIsStmntKind(ASTObject astObject) {
// return astObject instanceof CatchClause
// || astObject instanceof SOLink
// || astObject instanceof BasicAssignExpr;
// }
//
// private static List genModifiers(ASTObject astObject) {
// List modifiers = new ArrayList();
// if (astObject instanceof Dec) {
// Dec dec = (Dec)astObject;
// if (dec.getModifiers().isStrict()) modifiers.add(ProgramElementNode.Modifiers.STRICTFP);
// if (dec.getModifiers().isAbstract()) modifiers.add(ProgramElementNode.Modifiers.ABSTRACT);
// if (dec.getModifiers().isSynchronized()) modifiers.add(ProgramElementNode.Modifiers.SYNCHRONIZED);
// if (dec.getModifiers().isNative()) modifiers.add(ProgramElementNode.Modifiers.NATIVE);
// if (dec.getModifiers().isFinal()) modifiers.add(ProgramElementNode.Modifiers.FINAL);
// if (dec.getModifiers().isTransient()) modifiers.add(ProgramElementNode.Modifiers.TRANSIENT);
// if (dec.getModifiers().isStatic()) modifiers.add(ProgramElementNode.Modifiers.STATIC);
// if (dec.getModifiers().isVolatile()) modifiers.add(ProgramElementNode.Modifiers.VOLATILE);
// }
// return modifiers;
// }
//
// private static ProgramElementNode.Accessibility genAccessibility(ASTObject astObject) {
// //List modifiers = new ArrayList();
// if (astObject instanceof Dec) {
// Dec dec = (Dec)astObject;
// if (dec.getModifiers().isPublic()) return ProgramElementNode.Accessibility.PUBLIC;
// if (dec.getModifiers().isProtected()) return ProgramElementNode.Accessibility.PROTECTED;
// if (dec.getModifiers().isPrivileged()) return ProgramElementNode.Accessibility.PRIVILEGED;
// if (dec.getModifiers().isPackagePrivate()) return ProgramElementNode.Accessibility.PACKAGE;
// if (dec.getModifiers().isPrivate()) return ProgramElementNode.Accessibility.PRIVATE;
// }
// return ProgramElementNode.Accessibility.PUBLIC;
// }
//
// /**
// * @todo special cases should be fixes to AST nodes, this should have no instanceof tests.
// */
// private static ProgramElementNode.Kind genKind(ASTObject astObject) {
// if (astObject instanceof CompilationUnit) {
// return ProgramElementNode.Kind.FILE_JAVA;
// } else if (genIsStmntKind(astObject)) {
// return ProgramElementNode.Kind.CODE;
// } else if (astObject instanceof Dec) {
// String kindString = ((Dec)astObject).getKind();
// return ProgramElementNode.Kind.getKindForString(kindString);
// } else {
// return ProgramElementNode.Kind.ERROR;
// }
// }
//
// private static boolean isMemberKind(ASTObject astObject) {
// if (astObject instanceof Dec) {
// Dec dec = (Dec)astObject;
// return dec.getDeclaringType() != null && !dec.getDeclaringType().equals(dec.getName());
// } else {
// return false;
// }
// }
//
// private static String genPackageName(ASTObject astObject) {
// if (astObject instanceof TypeDec) {
// return ((TypeDec)astObject).getPackageName();
// } else if (astObject instanceof CompilationUnit) {
// return ((CompilationUnit)astObject).getPackageName();
// } else if (astObject.getDeclaringType() != null) {
// return astObject.getDeclaringType().getPackageName();
// } else {
// return "";
// }
// }
//
// private static String genDeclaringType(ASTObject astObject) {
// if (astObject != null && astObject.getDeclaringType() != null) {
// return astObject.getDeclaringType().toShortString();
// } else {
// return null;
// }
// }
//
// /**
// * Tries to return the ajdoc generated comment, otherwise returns the raw comment.
// */
// private static String genFormalComment(ASTObject astObject) {
// try {
// return (String)astObject.getComment().getClass().getMethod("commentText", new Class[]{}).invoke(astObject.getComment(), new Object[]{});
// } catch (Throwable t) {
// if (astObject != null) {
// return astObject.getFormalComment();
// } else {
// return "";
// }
// }
// }
//
// /**
// * Specialized signature generation for nodes in the structure model.
// *
// * @todo the compiler should generate these names, doing it this way is atrocious
// */
// private static String genSignature(ASTObject astObject) {
// String name = "";
// if (astObject instanceof CompilationUnit) {
// return astObject.getSourceFile().getName();
// } else if (astObject instanceof MethodDec) {
// Method method = ((MethodDec)astObject).getMethod();
// return method.getName() + method.getFormals().toShortString();
// } else if (astObject instanceof TypeDec) {
// return ((TypeDec)astObject).getSourceExtendedId();
// } else if (astObject instanceof FieldDec) {
// return ((FieldDec)astObject).getName();
// } else if (astObject instanceof ConstructorDec) {
// ConstructorDec constructorDec = (ConstructorDec)astObject;
// return constructorDec.getDeclaringType().getSourceExtendedId() + constructorDec.getFormals().toShortString();
// } else if (astObject instanceof IntroducedDec) {
// IntroducedDec introDec = (IntroducedDec)astObject;
// return introDec.getTargets().toShortString() + '.' + genSignature(introDec.getDec());
//// introDec.toShortString();
// } else if (astObject instanceof PointcutDec) {
// PointcutDec pointcutDec = (PointcutDec)astObject;
// return pointcutDec.getName() + pointcutDec.getFormals().toShortString();
//// } else if (astObject instanceof CallExpr) {
//// CallExpr call = (CallExpr)astObject;
//// name = call.get;
// } else if (astObject instanceof ShowErrorDec) {
// ShowErrorDec errorDec = (ShowErrorDec)astObject;
// return errorDec.toShortString();
// } else if (astObject instanceof SoftThrowableDec) {
// SoftThrowableDec softThrowableDec = (SoftThrowableDec)astObject;
// return softThrowableDec.toShortString();
// } else if (astObject instanceof IntroducedSuperDec) {
// IntroducedSuperDec introducedSuperDec = (IntroducedSuperDec)astObject;
// return introducedSuperDec.toShortString();
// } else if (astObject instanceof AdviceDec) {
// AdviceDec adviceDec = (AdviceDec)astObject;
// return adviceDec.toShortString();
// } else if (astObject instanceof SOLink) {
// SOLink soLink = (SOLink)astObject;
// return genSignature(soLink.getTarget().getCorrespondingDec());
// } else if (astObject instanceof CatchClause) {
// CatchClause catchClause = (CatchClause)astObject;
// return catchClause.getFormal().getType().getSourceExtendedId();
// } else if (astObject instanceof BasicAssignExpr) {
// return astObject.unparse();
//// } else if (genIsStmntKind(astObject)) {
//// name = astObject.unparse();
//// name = name.replace('/', ' ');
//// name = name.replace('*', ' ');
//// name = name.replace('\n', ' ');
//// name.trim();
//// java.util.StringTokenizer st = new java.util.StringTokenizer(name, " ");
//// String s = "";
//// while (st.hasMoreElements()) {
//// s += ((String)st.nextElement()).trim() + " ";
//// }
//// name = s;
//// int endIndex = name.indexOf(')');
//// if (endIndex != -1) {
//// name = name.substring(0, endIndex+1);
//// }
//// if (name.startsWith("this.")) {
//// name = name.substring(5);
//// }
// } else {
// return "? " + astObject.toShortString();
// }
// }
}
|
41,254
|
Bug 41254 revise asm and create interfaces
| null |
resolved fixed
|
f1deb9c
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2003-08-08T11:02:53Z
| 2003-08-07T12:40:00Z
|
asm/src/org/aspectj/asm/internal/ProgramElement.java
| |
41,254
|
Bug 41254 revise asm and create interfaces
| null |
resolved fixed
|
f1deb9c
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2003-08-08T11:02:53Z
| 2003-08-07T12:40:00Z
|
asm/src/org/aspectj/asm/internal/Relationship.java
| |
41,254
|
Bug 41254 revise asm and create interfaces
| null |
resolved fixed
|
f1deb9c
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2003-08-08T11:02:53Z
| 2003-08-07T12:40: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
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.lookup;
import java.util.*;
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.AsmBuilder;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.IMessage.Kind;
import org.aspectj.weaver.*;
import org.eclipse.jdt.internal.compiler.ast.*;
import org.eclipse.jdt.internal.compiler.impl.Constant;
import org.eclipse.jdt.internal.compiler.impl.ReferenceContext;
import org.eclipse.jdt.internal.compiler.lookup.*;
import org.eclipse.jdt.core.compiler.CharOperation;
/**
*
* @author Jim Hugunin
*/
public class EclipseFactory {
public static boolean DEBUG = false;
public AjBuildManager buildManager;
private LookupEnvironment lookupEnvironment;
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) {
this.lookupEnvironment = lookupEnvironment;
}
public World getWorld() {
return buildManager.getWorld();
}
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) {
//System.err.println("member for: " + binding + ", " + new String(binding.declaringClass.sourceName));
ResolvedMember ret = new ResolvedMember(
binding.isConstructor() ? Member.CONSTRUCTOR : Member.METHOD,
fromBinding(binding.declaringClass),
binding.modifiers,
fromBinding(binding.returnType),
new String(binding.selector),
fromBindings(binding.parameters),
fromBindings(binding.thrownExceptions));
return ret;
}
public static ResolvedMember makeResolvedMember(FieldBinding binding) {
return new ResolvedMember(
Member.FIELD,
fromBinding(binding.declaringClass),
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.doGenerateModel()) {
AsmBuilder.build(unit, buildManager.getStructureModel());
}
}
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]);
}
}
}
|
41,254
|
Bug 41254 revise asm and create interfaces
| null |
resolved fixed
|
f1deb9c
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2003-08-08T11:02:53Z
| 2003-08-07T12:40: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.File;
import java.io.IOException;
import java.util.*;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import org.aspectj.ajdt.internal.compiler.AjCompiler;
import org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment;
import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory;
import org.aspectj.ajdt.internal.compiler.parser.AjParser;
import org.aspectj.ajdt.internal.compiler.problem.AjProblemReporter;
import org.aspectj.asm.ProgramElementNode;
import org.aspectj.asm.StructureModel;
import org.aspectj.asm.StructureModelManager;
import org.aspectj.bridge.*;
import org.aspectj.weaver.World;
import org.aspectj.weaver.bcel.BcelWeaver;
import org.aspectj.weaver.bcel.BcelWorld;
import org.aspectj.weaver.bcel.UnwovenClassFile;
import org.eclipse.jdt.core.compiler.CharOperation;
import org.eclipse.jdt.core.compiler.IProblem;
import org.eclipse.jdt.internal.compiler.*;
import org.eclipse.jdt.internal.compiler.batch.CompilationUnit;
import org.eclipse.jdt.internal.compiler.batch.FileSystem;
import org.eclipse.jdt.internal.compiler.env.ICompilationUnit;
import org.eclipse.jdt.internal.compiler.env.INameEnvironment;
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
import org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory;
import org.eclipse.jdt.internal.compiler.util.HashtableOfObject;
public class AjBuildManager {
static final boolean FAIL_IF_RUNTIME_NOT_FOUND = false;
private IProgressListener progressListener = null;
private int compiledCount;
private int sourceFileCount;
private StructureModel 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 {
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);
//}
setupModel();
if (batch) {
initBcelWorld(handler);
}
if (handler.hasErrors()) {
return false;
}
if (batch) {
// System.err.println("XXXX batch: " + buildConfig.getFiles());
if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) {
bcelWorld.setModel(StructureModelManager.getDefault().getStructureModel());
// in incremental build, only get updated model?
}
performCompilation(buildConfig.getFiles());
if (handler.hasErrors()) {
return false;
}
} else {
// done already?
// if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) {
// bcelWorld.setModel(StructureModelManager.INSTANCE.getStructureModel());
// }
// System.err.println("XXXX start inc ");
List files = state.getFilesToCompile(true);
for (int i = 0; (i < 5) && !files.isEmpty(); i++) {
// System.err.println("XXXX inc: " + files);
performCompilation(files);
if (handler.hasErrors()) {
return false;
}
files = state.getFilesToCompile(false);
}
if (!files.isEmpty()) {
return batchBuild(buildConfig, baseHandler);
}
}
// 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);
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()) {
StructureModelManager.getDefault().fireModelUpdated();
}
return !handler.hasErrors();
} finally {
handler = null;
}
}
private void setupModel() {
String rootLabel = "<root>";
StructureModel model = StructureModelManager.getDefault().getStructureModel();
ProgramElementNode.Kind kind = ProgramElementNode.Kind.FILE_JAVA;
if (buildConfig.getConfigFile() != null) {
rootLabel = buildConfig.getConfigFile().getName();
model.setConfigFile(
buildConfig.getConfigFile().getAbsolutePath()
);
kind = ProgramElementNode.Kind.FILE_LST;
}
model.setRoot(new ProgramElementNode(rootLabel, kind, new ArrayList()));
HashMap modelFileMap = new HashMap();
model.setFileMap(new HashMap());
setStructureModel(model);
}
/** init only on initial batch compile? no file-specific options */
private void initBcelWorld(IMessageHandler handler) throws IOException {
bcelWorld = new BcelWorld(buildConfig.getClasspath(), handler);
bcelWorld.setXnoInline(buildConfig.isXnoInline());
bcelWeaver = new BcelWeaver(bcelWorld);
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();
bcelWeaver.addJarFile(inJar, buildConfig.getOutputDir());
}
if (buildConfig.getSourcePathResources() != null) {
for (Iterator i = buildConfig.getSourcePathResources().keySet().iterator(); i.hasNext(); ) {
// File resource = (File)i.next();
String resource = (String)i.next();
bcelWeaver.addResource(resource, (File)buildConfig.getSourcePathResources().get(resource), buildConfig.getOutputDir());
// bcelWeaver.addResource(resource, buildConfig.getOutputDir());
}
}
//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();
}
} else {
if (buildConfig.getOutputJar() != null) {
bcelWeaver.weave(buildConfig.getOutputJar());
} else {
bcelWeaver.weave();
}
}
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 = (String) buildConfig.getJavaOptions().get(CompilerOptions.OPTION_Encoding);
if ("".equals(defaultEncoding)) //$NON-NLS-1$
defaultEncoding = null; //$NON-NLS-1$
return new FileSystem(classpaths, filenames, defaultEncoding);
}
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 = (String) buildConfig.getJavaOptions().get(CompilerOptions.OPTION_Encoding);
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();
String[] classpaths = new String[cps.size()];
for (int i=0; i < cps.size(); i++) {
classpaths[i] = (String)cps.get(i);
}
//System.out.println("compiling");
INameEnvironment environment = getLibraryAccess(classpaths, filenames);
if (!state.classesFromName.isEmpty()) {
environment = new StatefulNameEnvironment(environment, state.classesFromName);
}
AjCompiler compiler = new AjCompiler(
environment,
DefaultErrorHandlingPolicies.proceedWithAllProblems(),
buildConfig.getJavaOptions(),
getBatchRequestor(),
getProblemFactory());
AjProblemReporter pr =
new AjProblemReporter(DefaultErrorHandlingPolicies.proceedWithAllProblems(),
compiler.options, getProblemFactory());
compiler.problemReporter = pr;
AjLookupEnvironment le =
new AjLookupEnvironment(compiler, compiler.options, pr, environment);
EclipseFactory factory = new EclipseFactory(le);
// ew.setLint(bcelWorld.getLint());
// ew.setXnoInline(buildConfig.isXnoInline());
le.factory = factory;
pr.world = factory;
le.factory.buildManager = this;
compiler.lookupEnvironment = le;
compiler.parser =
new AjParser(
pr,
compiler.options.parseLiteralExpressionsAsConstants,
compiler.options.sourceLevel >= CompilerOptions.JDK1_4);
CompilerOptions options = compiler.options;
options.produceReferenceInfo(true); //TODO turn off when not needed
compiler.compile(getCompilationUnits(filenames, encodings));
// cleanup
environment.cleanup();
}
/*
* Answer the component to which will be handed back compilation results from the compiler
*/
public ICompilerRequestor getBatchRequestor() {
return new ICompilerRequestor() {
int lineDelta = 0;
public void acceptResult(CompilationResult compilationResult) {
if (progressListener != null) {
compiledCount++;
progressListener.setProgress((compiledCount/2.0)/sourceFileCount);
progressListener.setText("compiled: " + new String(compilationResult.getFileName()));
}
if (compilationResult.hasProblems() || compilationResult.hasTasks()) {
IProblem[] problems = compilationResult.getAllProblems();
for (int i=0; i < problems.length; i++) {
IMessage message =
EclipseAdapterUtils.makeMessage(compilationResult.compilationUnit, problems[i]);
handler.handleMessage(message);
}
}
outputClassFiles(compilationResult);
}
};
}
private boolean proceedOnError() {
return true; //???
}
public void outputClassFiles(CompilationResult unitResult) {
if (unitResult == null) return;
String sourceFileName = new String(unitResult.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(StructureModel structureModel) {
this.structureModel = structureModel;
}
/**
* Returns null if there is no structure model
*/
public StructureModel getStructureModel() {
return structureModel;
}
public IProgressListener getProgressListener() {
return progressListener;
}
public void setProgressListener(IProgressListener progressListener) {
this.progressListener = progressListener;
}
} // class AjBuildManager
|
41,254
|
Bug 41254 revise asm and create interfaces
| null |
resolved fixed
|
f1deb9c
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2003-08-08T11:02:53Z
| 2003-08-07T12:40:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AsmBuilder.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 org.aspectj.ajdt.internal.compiler.ast.*;
import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory;
import org.aspectj.asm.*;
import org.aspectj.bridge.*;
import org.aspectj.util.LangUtil;
import org.aspectj.weaver.*;
import org.aspectj.weaver.patterns.*;
import org.eclipse.jdt.internal.compiler.*;
import org.eclipse.jdt.internal.compiler.ast.*;
import org.eclipse.jdt.internal.compiler.lookup.*;
import org.eclipse.jdt.internal.compiler.problem.ProblemHandler;
public class AsmBuilder extends AbstractSyntaxTreeVisitorAdapter {
public static void build(
CompilationUnitDeclaration unit,
StructureModel structureModel) {
LangUtil.throwIaxIfNull(unit, "unit");
new AsmBuilder(unit.compilationResult()).internalBuild(unit, structureModel);
}
private final Stack stack;
private final CompilationResult currCompilationResult;
private AsmNodeFormatter formatter = new AsmNodeFormatter();
protected AsmBuilder(CompilationResult result) {
LangUtil.throwIaxIfNull(result, "result");
currCompilationResult = result;
stack = new Stack();
}
/**
* Called only by
* build(CompilationUnitDeclaration unit, StructureModel structureModel)
*/
private void internalBuild(
CompilationUnitDeclaration unit,
StructureModel structureModel) {
LangUtil.throwIaxIfNull(structureModel, "structureModel");
if (!currCompilationResult.equals(unit.compilationResult())) {
throw new IllegalArgumentException("invalid unit: " + unit);
}
// ---- summary
// add unit to package (or root if no package),
// first removing any duplicate (XXX? removes children if 3 classes in same file?)
// push the node on the stack
// and traverse
// -- create node to add
final File file = new File(new String(unit.getFileName()));
final ProgramElementNode cuNode;
{
// AMC - use the source start and end from the compilation unit decl
int startLine = getStartLine(unit);
int endLine = getEndLine(unit);
ISourceLocation sourceLocation
= new SourceLocation(file, startLine, endLine);
cuNode = new ProgramElementNode(
new String(file.getName()),
ProgramElementNode.Kind.FILE_JAVA,
sourceLocation,
0,
"",
new ArrayList());
}
// -- get node (package or root) to add to
final StructureNode addToNode;
{
ImportReference currentPackage = unit.currentPackage;
if (null == currentPackage) {
addToNode = structureModel.getRoot();
} else {
String pkgName;
{
StringBuffer nameBuffer = new StringBuffer();
final char[][] importName = currentPackage.getImportName();
final int last = importName.length-1;
for (int i = 0; i < importName.length; i++) {
nameBuffer.append(new String(importName[i]));
if (i < last) {
nameBuffer.append('.');
}
}
pkgName = nameBuffer.toString();
}
ProgramElementNode pkgNode = null;
for (Iterator it = structureModel.getRoot().getChildren().iterator();
it.hasNext(); ) {
ProgramElementNode currNode = (ProgramElementNode)it.next();
if (pkgName.equals(currNode.getName())) {
pkgNode = currNode;
break; // any reason not to quit when found?
}
}
if (pkgNode == null) {
// note packages themselves have no source location
pkgNode = new ProgramElementNode(
pkgName,
ProgramElementNode.Kind.PACKAGE,
new ArrayList());
structureModel.getRoot().addChild(pkgNode);
}
addToNode = pkgNode;
}
}
// -- remove duplicates before adding (XXX use them instead?)
for (ListIterator itt = addToNode.getChildren().listIterator(); itt.hasNext(); ) {
ProgramElementNode child = (ProgramElementNode)itt.next();
ISourceLocation childLoc = child.getSourceLocation();
if (null == childLoc) {
// XXX ok, packages have null source locations
// signal others?
} else if (childLoc.getSourceFile().equals(file)) {
itt.remove();
}
}
// -- add and traverse
addToNode.addChild(cuNode);
stack.push(cuNode);
unit.traverse(this, unit.scope);
// -- update file map (XXX do this before traversal?)
try {
structureModel.addToFileMap(file.getCanonicalPath(), cuNode);
} catch (IOException e) {
System.err.println("IOException " + e.getMessage()
+ " creating path for " + file );
// XXX signal IOException when canonicalizing file path
}
}
public boolean visit(TypeDeclaration typeDeclaration, CompilationUnitScope scope) {
String name = new String(typeDeclaration.name);
ProgramElementNode.Kind kind = ProgramElementNode.Kind.CLASS;
if (typeDeclaration instanceof AspectDeclaration) kind = ProgramElementNode.Kind.ASPECT;
else if (typeDeclaration.isInterface()) kind = ProgramElementNode.Kind.INTERFACE;
ProgramElementNode peNode = new ProgramElementNode(
name,
kind,
makeLocation(typeDeclaration),
typeDeclaration.modifiers, "",
new ArrayList());
// peNode.setFullSignature(typeDeclaration.());
((StructureNode)stack.peek()).addChild(peNode);
stack.push(peNode);
return true;
}
public void endVisit(TypeDeclaration typeDeclaration, CompilationUnitScope scope) {
stack.pop();
}
// ??? share impl with visit(TypeDeclaration, ..) ?
public boolean visit(MemberTypeDeclaration memberTypeDeclaration, ClassScope scope) {
String name = new String(memberTypeDeclaration.name);
//System.err.println("member type with name: " + name);
ProgramElementNode.Kind kind = ProgramElementNode.Kind.CLASS;
if (memberTypeDeclaration instanceof AspectDeclaration) kind = ProgramElementNode.Kind.ASPECT;
else if (memberTypeDeclaration.isInterface()) kind = ProgramElementNode.Kind.INTERFACE;
ProgramElementNode peNode = new ProgramElementNode(
name,
kind,
makeLocation(memberTypeDeclaration),
memberTypeDeclaration.modifiers,
"",
new ArrayList());
peNode.setFullSignature(memberTypeDeclaration.toString());
((StructureNode)stack.peek()).addChild(peNode);
stack.push(peNode);
return true;
}
public void endVisit(MemberTypeDeclaration memberTypeDeclaration, ClassScope scope) {
stack.pop();
}
public boolean visit(LocalTypeDeclaration memberTypeDeclaration, BlockScope scope) {
String name = new String(memberTypeDeclaration.name);
String fullName = "<undefined>";
if (memberTypeDeclaration.binding != null
&& memberTypeDeclaration.binding.constantPoolName() != null) {
fullName = new String(memberTypeDeclaration.binding.constantPoolName());
}
int dollar = fullName.indexOf('$');
fullName = fullName.substring(dollar+1);
//
// System.err.println("member type with name: " + name + ", " +
// new String(fullName));
ProgramElementNode.Kind kind = ProgramElementNode.Kind.CLASS;
if (memberTypeDeclaration.isInterface()) kind = ProgramElementNode.Kind.INTERFACE;
ProgramElementNode peNode = new ProgramElementNode(
fullName,
kind,
makeLocation(memberTypeDeclaration),
memberTypeDeclaration.modifiers,
"",
new ArrayList());
//??? we add this to the compilation unit
findEnclosingClass(stack).addChild(peNode);
stack.push(peNode);
return true;
}
public void endVisit(LocalTypeDeclaration memberTypeDeclaration, BlockScope scope) {
stack.pop();
}
public boolean visit(AnonymousLocalTypeDeclaration memberTypeDeclaration, BlockScope scope) {
return visit((LocalTypeDeclaration)memberTypeDeclaration, scope);
}
public void endVisit(AnonymousLocalTypeDeclaration memberTypeDeclaration, BlockScope scope) {
stack.pop();
}
private StructureNode findEnclosingClass(Stack stack) {
for (int i = stack.size()-1; i >= 0; i--) {
ProgramElementNode pe = (ProgramElementNode)stack.get(i);
if (pe.getProgramElementKind() == ProgramElementNode.Kind.CLASS) {
return pe;
}
}
return (StructureNode)stack.peek();
}
public boolean visit(MethodDeclaration methodDeclaration, ClassScope scope) {
ProgramElementNode peNode = new ProgramElementNode(
"",
ProgramElementNode.Kind.ERROR,
makeLocation(methodDeclaration),
methodDeclaration.modifiers,
"",
new ArrayList());
formatter.genLabelAndKind(methodDeclaration, peNode);
genBytecodeInfo(methodDeclaration, peNode);
// TODO: should improve determining what the main method is
if (peNode.getProgramElementKind().equals(ProgramElementNode.Kind.METHOD)) {
if (peNode.getName().equals("main")) {
((ProgramElementNode)stack.peek()).setRunnable(true);
}
}
stack.push(peNode);
return true;
}
private void genBytecodeInfo(MethodDeclaration methodDeclaration, ProgramElementNode peNode) {
if (methodDeclaration.binding != null) {
String memberName = "";
String memberBytecodeSignature = "";
try {
Member member = EclipseFactory.makeResolvedMember(methodDeclaration.binding);
memberName = member.getName();
memberBytecodeSignature = member.getSignature();
} catch (NullPointerException npe) {
memberName = "<undefined>";
}
peNode.setBytecodeName(memberName);
peNode.setBytecodeSignature(memberBytecodeSignature);
}
((StructureNode)stack.peek()).addChild(peNode);
}
public void endVisit(MethodDeclaration methodDeclaration, ClassScope scope) {
stack.pop();
}
public boolean visit(FieldDeclaration fieldDeclaration, MethodScope scope) {
ProgramElementNode peNode = new ProgramElementNode(
new String(fieldDeclaration.name),
ProgramElementNode.Kind.FIELD,
makeLocation(fieldDeclaration),
fieldDeclaration.modifiers,
"",
new ArrayList());
((StructureNode)stack.peek()).addChild(peNode);
stack.push(peNode);
return true;
}
public void endVisit(FieldDeclaration fieldDeclaration, MethodScope scope) {
stack.pop();
}
// public boolean visit(ImportReference importRef, CompilationUnitScope scope) {
// ProgramElementNode peNode = new ProgramElementNode(
// new String(importRef.toString()),
// ProgramElementNode.Kind.,
// makeLocation(importRef),
// 0,
// "",
// new ArrayList());
// ((StructureNode)stack.peek()).addChild(0, peNode);
// stack.push(peNode);
// return true;
// }
// public void endVisit(ImportReference importRef,CompilationUnitScope scope) {
// stack.pop();
// }
public boolean visit(ConstructorDeclaration constructorDeclaration, ClassScope scope) {
if (constructorDeclaration.isDefaultConstructor) {
stack.push(null); // a little wierd but does the job
return true;
}
ProgramElementNode peNode = new ProgramElementNode(
new String(constructorDeclaration.selector),
ProgramElementNode.Kind.CONSTRUCTOR,
makeLocation(constructorDeclaration),
constructorDeclaration.modifiers,
"",
new ArrayList());
((StructureNode)stack.peek()).addChild(peNode);
stack.push(peNode);
return true;
}
public void endVisit(ConstructorDeclaration constructorDeclaration, ClassScope scope) {
stack.pop();
}
// public boolean visit(Clinit clinit, ClassScope scope) {
// ProgramElementNode peNode = new ProgramElementNode(
// "<clinit>",
// ProgramElementNode.Kind.INITIALIZER,
// makeLocation(clinit),
// clinit.modifiers,
// "",
// new ArrayList());
// ((StructureNode)stack.peek()).addChild(peNode);
// stack.push(peNode);
// return false;
// }
// public void endVisit(Clinit clinit, ClassScope scope) {
// stack.pop();
// }
/** This method works-around an odd traverse implementation on Initializer
*/
private Initializer inInitializer = null;
public boolean visit(Initializer initializer, MethodScope scope) {
if (initializer == inInitializer) return false;
inInitializer = initializer;
ProgramElementNode peNode = new ProgramElementNode(
"...",
ProgramElementNode.Kind.INITIALIZER,
makeLocation(initializer),
initializer.modifiers,
"",
new ArrayList());
((StructureNode)stack.peek()).addChild(peNode);
stack.push(peNode);
initializer.block.traverse(this, scope);
stack.pop();
return false;
}
// ??? handle non-existant files
private ISourceLocation makeLocation(AstNode node) {
String fileName = "";
if (currCompilationResult.getFileName() != null) {
fileName = new String(currCompilationResult.getFileName());
}
// AMC - different strategies based on node kind
int startLine = getStartLine(node);
int endLine = getEndLine(node);
ISourceLocation loc = null;
if ( startLine <= endLine ) {
// found a valid end line for this node...
loc = new SourceLocation(new File(fileName), startLine, endLine);
} else {
loc = new SourceLocation(new File(fileName), startLine);
}
return loc;
}
// AMC - overloaded set of methods to get start and end lines for
// various ASTNode types. They have no common ancestor in the
// hierarchy!!
private int getStartLine( AstNode n){
// if ( n instanceof AbstractVariableDeclaration ) return getStartLine( (AbstractVariableDeclaration)n);
// if ( n instanceof AbstractMethodDeclaration ) return getStartLine( (AbstractMethodDeclaration)n);
// if ( n instanceof TypeDeclaration ) return getStartLine( (TypeDeclaration)n);
return ProblemHandler.searchLineNumber(
currCompilationResult.lineSeparatorPositions,
n.sourceStart);
}
// AMC - overloaded set of methods to get start and end lines for
// various ASTNode types. They have no common ancestor in the
// hierarchy!!
private int getEndLine( AstNode n){
if ( n instanceof AbstractVariableDeclaration ) return getEndLine( (AbstractVariableDeclaration)n);
if ( n instanceof AbstractMethodDeclaration ) return getEndLine( (AbstractMethodDeclaration)n);
if ( n instanceof TypeDeclaration ) return getEndLine( (TypeDeclaration)n);
return ProblemHandler.searchLineNumber(
currCompilationResult.lineSeparatorPositions,
n.sourceEnd);
}
// AMC - overloaded set of methods to get start and end lines for
// various ASTNode types. They have no common ancestor in the
// hierarchy!!
private int getStartLine( AbstractVariableDeclaration avd ) {
return ProblemHandler.searchLineNumber(
currCompilationResult.lineSeparatorPositions,
avd.declarationSourceStart);
}
// AMC - overloaded set of methods to get start and end lines for
// various ASTNode types. They have no common ancestor in the
// hierarchy!!
private int getEndLine( AbstractVariableDeclaration avd ){
return ProblemHandler.searchLineNumber(
currCompilationResult.lineSeparatorPositions,
avd.declarationSourceEnd);
}
// AMC - overloaded set of methods to get start and end lines for
// various ASTNode types. They have no common ancestor in the
// hierarchy!!
private int getStartLine( AbstractMethodDeclaration amd ){
return ProblemHandler.searchLineNumber(
currCompilationResult.lineSeparatorPositions,
amd.declarationSourceStart);
}
// AMC - overloaded set of methods to get start and end lines for
// various ASTNode types. They have no common ancestor in the
// hierarchy!!
private int getEndLine( AbstractMethodDeclaration amd) {
return ProblemHandler.searchLineNumber(
currCompilationResult.lineSeparatorPositions,
amd.declarationSourceEnd);
}
// AMC - overloaded set of methods to get start and end lines for
// various ASTNode types. They have no common ancestor in the
// hierarchy!!
private int getStartLine( TypeDeclaration td ){
return ProblemHandler.searchLineNumber(
currCompilationResult.lineSeparatorPositions,
td.declarationSourceStart);
}
// AMC - overloaded set of methods to get start and end lines for
// various ASTNode types. They have no common ancestor in the
// hierarchy!!
private int getEndLine( TypeDeclaration td){
return ProblemHandler.searchLineNumber(
currCompilationResult.lineSeparatorPositions,
td.declarationSourceEnd);
}
}
|
41,254
|
Bug 41254 revise asm and create interfaces
| null |
resolved fixed
|
f1deb9c
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2003-08-08T11:02:53Z
| 2003-08-07T12:40:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AsmHierarchyBuilder.java
| |
41,254
|
Bug 41254 revise asm and create interfaces
| null |
resolved fixed
|
f1deb9c
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2003-08-08T11:02:53Z
| 2003-08-07T12:40:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AsmNodeFormatter.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
*
* ******************************************************************/
package org.aspectj.ajdt.internal.core.builder;
import java.util.Iterator;
import org.aspectj.ajdt.internal.compiler.ast.*;
import org.aspectj.asm.ProgramElementNode;
import org.aspectj.weaver.*;
import org.aspectj.weaver.patterns.*;
import org.eclipse.jdt.internal.compiler.ast.*;
public class AsmNodeFormatter {
public static final String DECLARE_PRECEDENCE = "precedence: ";
public static final String DECLARE_SOFT = "soft: ";
public static final String DECLARE_PARENTS = "parents: ";
public static final String DECLARE_WARNING = "warning: ";
public static final String DECLARE_ERROR = "error: ";
public static final String DECLARE_UNKNONWN = "<unknown declare>";
public static final String POINTCUT_ABSTRACT = "<abstract pointcut>";
public static final String POINTCUT_ANONYMOUS = "<anonymous pointcut>";
public static final int MAX_MESSAGE_LENGTH = 18;
public static final String DEC_LABEL = "declare";
public void genLabelAndKind(MethodDeclaration methodDeclaration, ProgramElementNode node) {
if (methodDeclaration instanceof AdviceDeclaration) {
AdviceDeclaration ad = (AdviceDeclaration)methodDeclaration;
node.setKind( ProgramElementNode.Kind.ADVICE);
String label = "";
label += ad.kind.toString();
label += "(" + genArguments(ad) + "): ";
if (ad.kind == AdviceKind.Around) {
node.setReturnType(ad.returnTypeToString(0));
}
if (ad.pointcutDesignator != null) {
if (ad.pointcutDesignator.getPointcut() instanceof ReferencePointcut) {
ReferencePointcut rp = (ReferencePointcut)ad.pointcutDesignator.getPointcut();
label += rp.name + "..";
} else if (ad.pointcutDesignator.getPointcut() instanceof AndPointcut) {
AndPointcut ap = (AndPointcut)ad.pointcutDesignator.getPointcut();
if (ap.getLeft() instanceof ReferencePointcut) {
label += ap.getLeft().toString() + "..";
} else {
label += POINTCUT_ANONYMOUS + "..";
}
} else if (ad.pointcutDesignator.getPointcut() instanceof OrPointcut) {
OrPointcut op = (OrPointcut)ad.pointcutDesignator.getPointcut();
if (op.getLeft() instanceof ReferencePointcut) {
label += op.getLeft().toString() + "..";
} else {
label += POINTCUT_ANONYMOUS + "..";
}
} else {
label += POINTCUT_ANONYMOUS;
}
} else {
label += POINTCUT_ABSTRACT;
}
node.setName(label);
} else if (methodDeclaration instanceof PointcutDeclaration) {
PointcutDeclaration pd = (PointcutDeclaration)methodDeclaration;
node.setKind( ProgramElementNode.Kind.POINTCUT);
String label = translatePointcutName(new String(methodDeclaration.selector));
label += "(" + genArguments(pd) + ")";
node.setName(label);
} else if (methodDeclaration instanceof DeclareDeclaration) {
DeclareDeclaration declare = (DeclareDeclaration)methodDeclaration;
String label = DEC_LABEL + " ";
if (declare.declare instanceof DeclareErrorOrWarning) {
DeclareErrorOrWarning deow = (DeclareErrorOrWarning)declare.declare;
if (deow.isError()) {
node.setKind( ProgramElementNode.Kind.DECLARE_ERROR);
label += DECLARE_ERROR;
} else {
node.setKind( ProgramElementNode.Kind.DECLARE_WARNING);
label += DECLARE_WARNING;
}
node.setName(label + "\"" + genDeclareMessage(deow.getMessage()) + "\"") ;
} else if (declare.declare instanceof DeclareParents) {
node.setKind( ProgramElementNode.Kind.DECLARE_PARENTS);
DeclareParents dp = (DeclareParents)declare.declare;
node.setName(label + DECLARE_PARENTS + genTypePatternLabel(dp.getChild()));
} else if (declare.declare instanceof DeclareSoft) {
node.setKind( ProgramElementNode.Kind.DECLARE_SOFT);
DeclareSoft ds = (DeclareSoft)declare.declare;
node.setName(label + DECLARE_SOFT + genTypePatternLabel(ds.getException()));
} else if (declare.declare instanceof DeclarePrecedence) {
node.setKind( ProgramElementNode.Kind.DECLARE_PRECEDENCE);
DeclarePrecedence ds = (DeclarePrecedence)declare.declare;
node.setName(label + DECLARE_PRECEDENCE + genPrecedenceListLabel(ds.getPatterns()));
} else {
node.setKind( ProgramElementNode.Kind.ERROR);
node.setName(DECLARE_UNKNONWN);
}
} else if (methodDeclaration instanceof InterTypeDeclaration) {
InterTypeDeclaration itd = (InterTypeDeclaration)methodDeclaration;
String label = itd.onType.toString() + "." + new String(itd.getDeclaredSelector());
if (methodDeclaration instanceof InterTypeFieldDeclaration) {
node.setKind(ProgramElementNode.Kind.INTER_TYPE_FIELD);
} else if (methodDeclaration instanceof InterTypeMethodDeclaration) {
node.setKind(ProgramElementNode.Kind.INTER_TYPE_METHOD);
InterTypeMethodDeclaration itmd = (InterTypeMethodDeclaration)methodDeclaration;
label += "(" + genArguments(itd) + ")";
} else if (methodDeclaration instanceof InterTypeConstructorDeclaration) {
node.setKind(ProgramElementNode.Kind.INTER_TYPE_CONSTRUCTOR);
InterTypeConstructorDeclaration itcd = (InterTypeConstructorDeclaration)methodDeclaration;
} else {
node.setKind(ProgramElementNode.Kind.ERROR);
}
node.setName(label);
node.setReturnType(itd.returnType.toString());
} else {
node.setKind(ProgramElementNode.Kind.METHOD);
node.setName(new String(methodDeclaration.selector));
}
}
private String genPrecedenceListLabel(TypePatternList list) {
String tpList = "";
for (int i = 0; i < list.size(); i++) {
tpList += genTypePatternLabel(list.get(i));
if (i < list.size()-1) tpList += ", ";
}
return tpList;
}
private String genArguments(MethodDeclaration md) {
String args = "";
Argument[] argArray = md.arguments;
if (argArray == null) return args;
for (int i = 0; i < argArray.length; i++) {
String argName = new String(argArray[i].name);
String argType = argArray[i].type.toString();
// TODO: fix this way of determing ajc-added arguments, make subtype of Argument with extra info
if (!argName.startsWith("ajc$this_")
&& !argType.equals("org.aspectj.lang.JoinPoint.StaticPart")
&& !argType.equals("org.aspectj.lang.JoinPoint")
&& !argType.equals("org.aspectj.runtime.internal.AroundClosure")) {
args += argType + ", ";
}
}
int lastSepIndex = args.lastIndexOf(',');
if (lastSepIndex != -1 && args.endsWith(", ")) args = args.substring(0, lastSepIndex);
return args;
}
public String genTypePatternLabel(TypePattern tp) {
final String TYPE_PATTERN_LITERAL = "<type pattern>";
String label;
TypeX typeX = tp.getExactType();
if (typeX != ResolvedTypeX.MISSING) {
label = typeX.getName();
if (tp.isIncludeSubtypes()) label += "+";
} else {
label = TYPE_PATTERN_LITERAL;
}
return label;
}
public String genDeclareMessage(String message) {
int length = message.length();
if (length < MAX_MESSAGE_LENGTH) {
return message;
} else {
return message.substring(0, MAX_MESSAGE_LENGTH-1) + "..";
}
}
// // TODO:
// private String translateAdviceName(String label) {
// if (label.indexOf("before") != -1) return "before";
// if (label.indexOf("returning") != -1) return "after returning";
// if (label.indexOf("after") != -1) return "after";
// if (label.indexOf("around") != -1) return "around";
// else return "<advice>";
// }
// // !!! move or replace
// private String translateDeclareName(String name) {
// int colonIndex = name.indexOf(":");
// if (colonIndex != -1) {
// return name.substring(0, colonIndex);
// } else {
// return name;
// }
// }
// !!! move or replace
// private String translateInterTypeDecName(String name) {
// int index = name.lastIndexOf('$');
// if (index != -1) {
// return name.substring(index+1);
// } else {
// return name;
// }
// }
// !!! move or replace
private String translatePointcutName(String name) {
int index = name.indexOf("$$")+2;
int endIndex = name.lastIndexOf('$');
if (index != -1 && endIndex != -1) {
return name.substring(index, endIndex);
} else {
return name;
}
}
}
|
41,254
|
Bug 41254 revise asm and create interfaces
| null |
resolved fixed
|
f1deb9c
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2003-08-08T11:02:53Z
| 2003-08-07T12:40:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/EmacsStructureModelManager.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:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.core.builder;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.aspectj.asm.AdviceAssociation;
import org.aspectj.asm.IntroductionAssociation;
import org.aspectj.asm.LinkNode;
import org.aspectj.asm.ProgramElementNode;
import org.aspectj.asm.RelationNode;
import org.aspectj.asm.StructureModelManager;
//import org.aspectj.ajde.compiler.AjdeCompiler;
/**
* @author Mik Kersten
*/
public class EmacsStructureModelManager {
private static final String EXTERN_FILE_SUFFIX = ".ajesym";
public EmacsStructureModelManager() {
super();
}
public void externalizeModel() {
if (!StructureModelManager.getDefault().getStructureModel().isValid()) return;
try {
//Set fileSet = StructureModelManager.INSTANCE.getStructureModel().getFileMap().entrySet();
Set fileSet = StructureModelManager.getDefault().getStructureModel().getFileMapEntrySet();
for (Iterator it = fileSet.iterator(); it.hasNext(); ) {
ProgramElementNode peNode = (ProgramElementNode)((Map.Entry)it.next()).getValue();
dumpStructureToFile(peNode);
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
// private void dumpStructureToFile(ProgramElementNode node) throws IOException {
// String sourceName = node.getSourceLocation().getSourceFilePath();
// String fileName = sourceName.substring(0, sourceName.lastIndexOf(".")) + EXTERN_FILE_SUFFIX;
// BufferedWriter writer = new BufferedWriter(new FileWriter(new File(fileName)));
// new SExpressionPrinter(writer).printDecls(node);
// writer.flush();
// }
private void dumpStructureToFile(ProgramElementNode node) throws IOException {
String s = node.getKind();
if (! (s.equals(ProgramElementNode.Kind.FILE_ASPECTJ.toString())
|| s.equals(ProgramElementNode.Kind.FILE_JAVA.toString()))) {
throw new IllegalArgumentException("externalize file, not " + node);
}
// source files have source locations
String sourceName = node.getSourceLocation().getSourceFile().getAbsolutePath();
String fileName = sourceName.substring(0, sourceName.lastIndexOf(".")) + EXTERN_FILE_SUFFIX;
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(new File(fileName)));
new SExpressionPrinter(writer).printDecls(node);
writer.flush();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {} // ignore
}
}
}
/**
* This class was not written in an OO style.
*/
private static class SExpressionPrinter {
private BufferedWriter writer = null;
public SExpressionPrinter(BufferedWriter writer) {
this.writer = writer;
}
private void printDecls(ProgramElementNode node) {
print("(");
for (Iterator it = node.getChildren().iterator(); it.hasNext(); ) {
// this ignores relations on the compile unit
Object nodeObject = it.next();
if (nodeObject instanceof ProgramElementNode) {
ProgramElementNode child = (ProgramElementNode)nodeObject;
printDecl(child, true);
} else if (nodeObject instanceof LinkNode) {
LinkNode child = (LinkNode)nodeObject;
printDecl(child.getProgramElementNode(), false);
}
}
print(") ");
}
private void printDecls(RelationNode node) {
for (Iterator it = node.getChildren().iterator(); it.hasNext(); ) {
// this ignores relations on the compile unit
Object nodeObject = it.next();
if (nodeObject instanceof LinkNode) {
LinkNode child = (LinkNode)nodeObject;
if (//!child.getProgramElementNode().getKind().equals("stmnt") &&
!child.getProgramElementNode().getKind().equals("<undefined>")) {
printDecl(child.getProgramElementNode(), false);
// printDecl(child.getProgramElementNode(), false);
}
}
}
}
/**
* @param structureNode can be a ProgramElementNode or a LinkNode
*/
private void printDecl(ProgramElementNode node, boolean recurse) {
if (node == null || node.getSourceLocation() == null) return;
String kind = node.getKind().toLowerCase();
print("(");
print("(" + node.getSourceLocation().getLine() + " . " + node.getSourceLocation().getColumn() + ") ");
print("(" + node.getSourceLocation().getLine() + " . " + node.getSourceLocation().getColumn() + ") ");
print(kind + " "); //2
// HACK:
String displayName = node.toString().replace('\"', ' ');
print("\"" + displayName + "\" ");
if (node.getSourceLocation().getSourceFile().getAbsolutePath() != null) {
print("\"" + fixFilename(node.getSourceLocation().getSourceFile().getAbsolutePath()) + "\""); //4
} else {
print("nil");
}
if (node.getSignature() != null) {
print("\"" + node.getDeclaringType() + "\" "); //5
} else {
print("nil");
}
if (!recurse) {
print("nil");
print("nil");
print("nil");
} else {
print("(");
if (node instanceof ProgramElementNode) {
java.util.List relations = ((ProgramElementNode)node).getRelations();
if (relations != null) {
for (Iterator it = relations.iterator(); it.hasNext(); ) {
RelationNode relNode = (RelationNode)it.next();
if (relNode.getRelation().getAssociationName().equals(AdviceAssociation.NAME) ||
relNode.getRelation().getAssociationName().equals(IntroductionAssociation.NAME)) {
printDecls(relNode); // 6
}
}
}
}
print(") ");
print("(");
print(") ");
print("(");
Iterator it3 = node.getChildren().iterator();
if (it3.hasNext()) {
while (it3.hasNext()) {
// this ignores relations on the compile unit
Object nodeObject = it3.next();
if (nodeObject instanceof ProgramElementNode) {
ProgramElementNode currNode = (ProgramElementNode)nodeObject;
if (//!currNode.isStmntKind() &&
!currNode.getKind().equals("<undefined>")) {
printDecl(currNode, true);
}
}
}
}
print(") ");
}
print(node.getKind().equals("class") ? "t " : "nil "); // 9
// print(node.getKind().equals("introduction") ? "t " : "nil "); // 10
print(node.getKind().equals("introduction") ? "nil " : "nil "); // 10
print("nil "); // 11
print("nil "); // 12
print(")");
}
String fixFilename(String filename) {
return subst("\\\\", "\\", filename);
}
private void print(String string) {
try {
writer.write(string + "\n");
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
private String subst(String n, String o, String in) {
int pos = in.indexOf(o);
if (pos == -1)
return in;
return in.substring(0, pos) +
n +
subst(n, o, (in.substring(pos + o.length())));
}
private void lose(Error e) {
try {
print("(ERROR \"" + e.toString() + "\")");
}
catch(Error ex) { }
}
}
}
|
41,254
|
Bug 41254 revise asm and create interfaces
| null |
resolved fixed
|
f1deb9c
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2003-08-08T11:02:53Z
| 2003-08-07T12:40:00Z
|
org.aspectj.ajdt.core/testsrc/org/aspectj/ajdt/internal/core/builder/AsmBuilderTest.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:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.core.builder;
import java.util.EmptyStackException;
import junit.framework.*;
import org.eclipse.jdt.internal.compiler.CompilationResult;
import org.eclipse.jdt.internal.compiler.ast.LocalTypeDeclaration;
import org.eclipse.jdt.internal.compiler.env.*;
import org.eclipse.jdt.internal.compiler.lookup.BlockScope;
public class AsmBuilderTest extends TestCase {
public static Test suite() {
TestSuite suite = new TestSuite(AsmBuilderTest.class.getName());
//$JUnit-BEGIN$
suite.addTestSuite(AsmBuilderTest.class);
//$JUnit-END$
return suite;
}
/**
* Test for bug#39626
*/
public void testNullHandlingOfVisit() {
ICompilationUnit cu = new ICompilationUnit() {
public char[] getContents() {
return null;
}
public char[] getMainTypeName() {
return null;
}
public char[][] getPackageName() {
return null;
}
public char[] getFileName() {
return null;
}
};
LocalTypeDeclaration local = new LocalTypeDeclaration(new CompilationResult(cu, 0, 0, 0));
local.name = new char[2];
BlockScope scope = null;
try {
new AsmBuilder(new CompilationResult(cu, 0, 0, 0)).visit(local, scope);
} catch (Exception e) {
assertTrue(e instanceof EmptyStackException);
}
}
}
|
41,254
|
Bug 41254 revise asm and create interfaces
| null |
resolved fixed
|
f1deb9c
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2003-08-08T11:02:53Z
| 2003-08-07T12:40:00Z
|
testing/src/org/aspectj/testing/ajde/CompileCommand.java
|
/* *******************************************************************
* Copyright (c) 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:
* Wes Isberg initial implementation
* ******************************************************************/
package org.aspectj.testing.ajde;
import java.awt.Frame;
import java.io.*;
import java.lang.reflect.*;
import java.util.*;
import java.util.List;
import org.aspectj.ajde.*;
import org.aspectj.ajde.ui.*;
import org.aspectj.ajde.ui.internal.*;
import org.aspectj.ajde.ui.swing.*;
import org.aspectj.asm.StructureNode;
import org.aspectj.bridge.*;
import org.aspectj.util.*;
import org.aspectj.util.FileUtil;
/**
* This re-uses the same config file to setup ajde
* so that recompiles appear to be of the same configuration.
* @since Java 1.3 (uses dynamic proxies)
*/
public class CompileCommand implements ICommand {
// time out waiting for build at three minutes
long MAX_TIME = 180 * 1000;
// this proxy ignores calls
InvocationHandler proxy = new VoidInvocationHandler();
InvocationHandler loggingProxy = new LoggingInvocationHandler();
MyTaskListManager myHandler = new MyTaskListManager();
long endTime;
boolean buildNextFresh;
File tempDir;
/**
* Clients call this before repeatCommand as a one-shot
* request for a full rebuild of the same configuration.
* (Requires a downcast from ICommand to CompileCommand.)
*/
public void buildNextFresh() {
buildNextFresh = true;
}
// --------- ICommand interface
public boolean runCommand(String[] args, IMessageHandler handler) {
setup(args);
myHandler.start();
long startTime = System.currentTimeMillis();
try {
Ajde.getDefault().getBuildManager().buildFresh();
// System.err.println("compiling " + Arrays.asList(args));
waitForCompletion(startTime);
} finally {
myHandler.finish(handler);
runCommandCleanup();
}
return !myHandler.hasError();
}
public boolean repeatCommand(IMessageHandler handler) {
myHandler.start();
long startTime = System.currentTimeMillis();
// System.err.println("recompiling...");
if (buildNextFresh) {
buildNextFresh = false;
Ajde.getDefault().getBuildManager().buildFresh();
} else {
Ajde.getDefault().getBuildManager().build();
}
waitForCompletion(startTime);
myHandler.finish(handler);
return !myHandler.hasError();
}
void runCommandCleanup() {
if (null != tempDir) {
FileUtil.deleteContents(tempDir);
tempDir.delete();
}
}
// set by build progress monitor when done
void setEndTime(long endTime) {
this.endTime = endTime;
}
private void waitForCompletion(long startTime) {
long maxTime = startTime + MAX_TIME;
while ((startTime > endTime)
&& (maxTime > System.currentTimeMillis())) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
}
}
private void setup(String[] args) {
File config = writeConfig(args);
if (null == config) {
throw new Error("unable to write config file");
}
EditorAdapter editorAdapter =
(EditorAdapter) makeProxy(EditorAdapter.class);
TaskListManager taskListManager = myHandler;
BuildProgressMonitor buildProgressMonitor =
new DefaultBuildProgressMonitor(new Frame()) {
public void finish() {
super.finish();
setEndTime(System.currentTimeMillis());
}
};
String classesDir = "../testing/bin/classes";
for (int i = 0; i < args.length; i++) {
if ("-d".equals(args[i]) && ((1 +i) < args.length)) {
classesDir = args[1 + i];
break;
}
}
ProjectPropertiesAdapter projectPropertiesAdapter =
new ProjectProperties(classesDir);
// neither of these are in the true classpath
// new NullIdeProperties(""); // in testsrc
// = new BrowserProperties(); // in ajbrowser
BuildOptionsAdapter buildOptionsAdapter =
new AjcBuildOptions(new UserPreferencesStore(false));
IdeUIAdapter ideUIAdapter =
(IdeUIAdapter) makeProxy(IdeUIAdapter.class);
ErrorHandler errorHandler =
(ErrorHandler) makeProxy(ErrorHandler.class);
AbstractIconRegistry iconRegistry = new AbstractIconRegistry() {
protected AbstractIcon createIcon(String path) {
return new AbstractIcon(new Object());
}
};
StructureViewNodeFactory structureViewNodeFactory =
new StructureViewNodeFactory(iconRegistry) {
protected StructureViewNode createConcreteNode(
StructureNode node,
AbstractIcon icon,
List children) {
return new SwingTreeViewNode(node, icon, children);
}
};
Ajde.init(
editorAdapter,
taskListManager,
buildProgressMonitor,
projectPropertiesAdapter,
buildOptionsAdapter,
structureViewNodeFactory,
ideUIAdapter,
errorHandler);
Ajde.getDefault().getConfigurationManager().setActiveConfigFile(
config.getAbsolutePath());
}
private File writeConfig(String[] args) {
tempDir = FileUtil.getTempDir("CompileCommand");
File result = new File(tempDir, "config.lst");
OutputStream out = null;
try {
out = new FileOutputStream(result);
PrintStream outs = new PrintStream(out, true);
for (int i = 0; i < args.length; i++) {
outs.println(args[i]);
}
return result;
} catch (IOException e) {
return null;
} finally {
try {
out.close();
} catch (IOException e) {
}
}
}
private Object makeLoggingProxy(Class interfac) {
return Proxy.newProxyInstance(
interfac.getClassLoader(),
new Class[] { interfac },
loggingProxy);
}
private Object makeProxy(Class interfac) {
return Proxy.newProxyInstance(
interfac.getClassLoader(),
new Class[] { interfac },
proxy);
}
}
class MyTaskListManager
extends MessageHandler
implements TaskListManager {
boolean hasError;
boolean hasWarning;
MyTaskListManager() {
super(true);
}
public void addProjectTask(String message, IMessage.Kind kind) {
maintainHasWarning(kind);
}
public void addSourcelineTask(IMessage message) {
maintainHasWarning(message.getKind());
handleMessage(message);
}
public void addSourcelineTask(
String message,
ISourceLocation sourceLocation,
IMessage.Kind kind) {
addSourcelineTask(
new Message(message, kind, null, sourceLocation));
}
public void clearTasks() {
if (hasWarning) {
hasWarning = false;
}
if (hasError) {
hasError = false;
}
init(true);
}
public boolean hasWarning() {
return hasWarning;
}
boolean hasError() {
return hasError;
}
void start() {
clearTasks();
}
void finish(IMessageHandler copyTo) {
if (copyTo == this) {
return;
}
IMessage[] messages = getMessages(null, true);
for (int i = 0; i < messages.length; i++) {
copyTo.handleMessage(messages[i]);
}
}
private void maintainHasWarning(IMessage.Kind kind) {
if (!hasError) {
if (IMessage.ERROR.isSameOrLessThan(kind)) {
hasError = true;
hasWarning = true;
}
}
if (!hasWarning && IMessage.WARNING.isSameOrLessThan(kind)) {
hasWarning = true;
}
}
}
class VoidInvocationHandler implements InvocationHandler {
public Object invoke(Object me, Method method, Object[] args)
throws Throwable {
// System.err.println("Proxying"
// // don't call toString on self b/c proxied
// // + " me=" + me.getClass().getName()
// + " method=" + method
// + " args=" + (LangUtil.isEmpty(args)
// ? "[]" : Arrays.asList(args).toString()));
return null;
}
}
class LoggingInvocationHandler implements InvocationHandler {
public Object invoke(Object me, Method method, Object[] args)
throws Throwable {
System.err.println("Proxying " + render(method, args));
return null;
}
public static String render(Class c) {
if (null == c) {
return "(Class) null";
}
String result = c.getName();
if (result.startsWith("java")) {
int loc = result.lastIndexOf(".");
if (-1 != loc) {
result = result.substring(loc+1);
}
}
return result;
}
public static String render(Method method, Object[] args) {
StringBuffer sb = new StringBuffer();
sb.append(render(method.getReturnType()));
sb.append(" ");
sb.append(method.getName());
sb.append("(");
Class[] parmTypes = method.getParameterTypes();
int parmTypesLength = (null == parmTypes ? 0 : parmTypes.length);
int argsLength = (null == args ? 0 : args.length);
boolean doType = (parmTypesLength == argsLength);
for (int i = 0; i < argsLength; i++) {
if (i > 0) {
sb.append(", ");
}
if (doType) {
sb.append("(");
sb.append(render(parmTypes[i]));
sb.append(") ");
}
if (null == args[i]) {
sb.append("null");
} else { // also don't recurse into proxied toString?
sb.append(args[i].toString());
}
}
sb.append(")");
return sb.toString();
}
}
class ProjectProperties implements ProjectPropertiesAdapter {
final private static String PREFIX
= ProjectProperties.class.getName() + ": ";
final private String outputDir;
private Set inJars;
private Set sourceRoots;
private Set aspectPath;
private String outJar;
public ProjectProperties(String outputDir) {
this.outputDir = outputDir;
}
// known used, per logging proxy
public String getDefaultBuildConfigFile() { return null; }
public void setInJars(Set input) { inJars = input; }
public Set getInJars( ) { return inJars; }
public void setSourceRoots(Set input) { sourceRoots = input; }
public Set getSourceRoots() { return sourceRoots; }
public void setAspectPath(Set path) { aspectPath = path; }
public Set getAspectPath() { return aspectPath; }
public String getClasspath() { return "../lib/test/aspectjrt.jar"; }
public String getBootClasspath() { return null; }
public void setOutJar(String input){ outJar = input; }
public String getOutJar() { return outJar; }
public String getOutputPath() { return outputDir; }
// not known if used - log any calls to it
public List getBuildConfigFiles() { return logs("buildConfigFiles"); }
public String getLastActiveBuildConfigFile() { return log("lastActiveBuildConfigFile"); }
public String getProjectName() { return log("projectName"); }
public String getRootProjectDir() { return log("rootProjectDir"); }
public List getProjectSourceFiles() { return logs("projectSourceFiles"); }
public String getProjectSourcePath() { return log("projectSourcePath"); }
public String getAjcWorkingDir() { return log("ajcWorkingDir"); }
public String getClassToExecute() { return log("classToExecute"); }
public String getExecutionArgs() { return log("executionArgs"); }
public String getVmArgs() { return log("vmArgs"); }
private String log(String s) {
System.out.println(PREFIX + s);
return null;
}
private List logs(String s) {
log(s);
return null;
}
public Map getSourcePathResources() {
return null;
}
}
|
41,254
|
Bug 41254 revise asm and create interfaces
| null |
resolved fixed
|
f1deb9c
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2003-08-08T11:02:53Z
| 2003-08-07T12:40:00Z
|
weaver/src/org/aspectj/weaver/AsmAdaptor.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.util.ArrayList;
import java.util.Iterator;
import org.aspectj.asm.AdviceAssociation;
import org.aspectj.asm.LinkNode;
import org.aspectj.asm.ProgramElementNode;
import org.aspectj.asm.Relation;
import org.aspectj.asm.RelationNode;
import org.aspectj.asm.StructureModel;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.SourceLocation;
public class AsmAdaptor {
public static void noteMunger(StructureModel model, Shadow shadow, ShadowMunger munger) {
if (munger instanceof Advice) {
Advice a = (Advice)munger;
if (a.getKind().isPerEntry() || a.getKind().isCflow()) {
// ??? might want to show these in the future
return;
}
// System.out.println("--------------------------");
ProgramElementNode targetNode = getNode(model, shadow);
ProgramElementNode adviceNode = getNode(model, a);
Relation relation;
if (shadow.getKind().equals(Shadow.FieldGet) || shadow.getKind().equals(Shadow.FieldSet)) {
relation = AdviceAssociation.FIELD_ACCESS_RELATION;
} else if (shadow.getKind().equals(Shadow.Initialization) || shadow.getKind().equals(Shadow.StaticInitialization)) {
relation = AdviceAssociation.INITIALIZER_RELATION;
} else if (shadow.getKind().equals(Shadow.ExceptionHandler)) {
relation = AdviceAssociation.HANDLER_RELATION;
} else if (shadow.getKind().equals(Shadow.MethodCall)) {
relation = AdviceAssociation.METHOD_CALL_SITE_RELATION;
} else if (shadow.getKind().equals(Shadow.ConstructorCall)) {
relation = AdviceAssociation.CONSTRUCTOR_CALL_SITE_RELATION;
} else if (shadow.getKind().equals(Shadow.MethodExecution) || shadow.getKind().equals(Shadow.AdviceExecution)) {
relation = AdviceAssociation.METHOD_RELATION;
} else if (shadow.getKind().equals(Shadow.ConstructorExecution)) {
relation = AdviceAssociation.CONSTRUCTOR_RELATION;
} else if (shadow.getKind().equals(Shadow.PreInitialization)) {
// TODO: someone should check that this behaves reasonably in the IDEs
relation = AdviceAssociation.INITIALIZER_RELATION;
} else {
System.err.println("> unmatched relation: " + shadow.getKind());
relation = AdviceAssociation.METHOD_RELATION;
}
// System.out.println("> target: " + targetNode + ", advice: " + adviceNode);
createAppropriateLinks(targetNode, adviceNode, relation);
}
}
private static void createAppropriateLinks(
ProgramElementNode target,
ProgramElementNode advice,
Relation relation)
{
if (target == null || advice == null) return;
addLink(target, new LinkNode(advice), relation, true);
addLink(advice, new LinkNode(target), relation, false);
// System.out.println(">> added target: " + target.getProgramElementKind() + ", advice: " + advice);
// System.out.println(">> target: " + target + ", advice: " + target.getSourceLocation());
}
private static void addLink(
ProgramElementNode onNode,
LinkNode linkNode,
Relation relation,
boolean isBack)
{
RelationNode node = null;
String relationName = isBack ? relation.getBackNavigationName() : relation.getForwardNavigationName();
//System.err.println("on: " + onNode + " relationName: " + relationName + " existin: " + onNode.getRelations());
for (Iterator i = onNode.getRelations().iterator(); i.hasNext();) {
RelationNode relationNode = (RelationNode) i.next();
if (relationName.equals(relationNode.getName())) {
node = relationNode;
break;
}
}
if (node == null) {
node = new RelationNode(relation, relationName, new ArrayList());
onNode.getRelations().add(node);
}
node.getChildren().add(linkNode);
}
private static ProgramElementNode getNode(StructureModel model, Advice a) {
//ResolvedTypeX inAspect = a.getConcreteAspect();
Member member = a.getSignature();
if (a.getSignature() == null) return null;
return lookupMember(model, member);
}
private static ProgramElementNode getNode(StructureModel model, Shadow shadow) {
Member enclosingMember = shadow.getEnclosingCodeSignature();
ProgramElementNode enclosingNode = lookupMember(model, enclosingMember);
if (enclosingNode == null) {
Lint.Kind err = shadow.getIWorld().getLint().shadowNotInStructure;
if (err.isEnabled()) {
err.signal(shadow.toString(), shadow.getSourceLocation());
}
return null;
}
Member shadowSig = shadow.getSignature();
if (!shadowSig.equals(enclosingMember)) {
ProgramElementNode bodyNode = findOrCreateBodyNode(enclosingNode, shadowSig, shadow);
return bodyNode;
} else {
return enclosingNode;
}
}
private static ProgramElementNode findOrCreateBodyNode(
ProgramElementNode enclosingNode,
Member shadowSig, Shadow shadow)
{
for (Iterator it = enclosingNode.getChildren().iterator(); it.hasNext(); ) {
ProgramElementNode node = (ProgramElementNode)it.next();
if (shadowSig.getName().equals(node.getBytecodeName()) &&
shadowSig.getSignature().equals(node.getBytecodeSignature()))
{
return node;
}
}
ISourceLocation sl = shadow.getSourceLocation();
ProgramElementNode peNode = new ProgramElementNode(
shadow.toString(),
ProgramElementNode.Kind.CODE,
//XXX why not use shadow file? new SourceLocation(sl.getSourceFile(), sl.getLine()),
new SourceLocation(enclosingNode.getSourceLocation().getSourceFile(), sl.getLine()),
// enclosingNode.getSourceLocation(),
0,
"",
new ArrayList());
//System.err.println(peNode.getSourceLocation());
peNode.setBytecodeName(shadowSig.getName());
peNode.setBytecodeSignature(shadowSig.getSignature());
enclosingNode.addChild(peNode);
return peNode;
}
public static ProgramElementNode lookupMember(StructureModel model, Member member) {
TypeX declaringType = member.getDeclaringType();
ProgramElementNode classNode =
model.findNodeForClass(declaringType.getPackageName(), declaringType.getClassName());
return findMemberInClass(classNode, member);
}
private static ProgramElementNode findMemberInClass(
ProgramElementNode classNode,
Member member)
{
if (classNode == null) return null; // XXX remove this check
for (Iterator it = classNode.getChildren().iterator(); it.hasNext(); ) {
ProgramElementNode node = (ProgramElementNode)it.next();
//System.err.println("checking: " + member.getName() + " with " + node.getBytecodeName() + ", " + node.getBytecodeSignature());
if (member.getName().equals(node.getBytecodeName()) &&
member.getSignature().equals(node.getBytecodeSignature()))
{
return node;
}
}
// if we can't find the member, we'll just put it in the class
return classNode;
}
}
|
39,436
|
Bug 39436 [Tasks] No summary shown in status line
|
build I20030625 The old tasks view showed a summary of the number of tasks, errors, warnings and infos in the status line. This is missing in the reworked view.
|
verified fixed
|
d90acdc
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2003-08-21T16:02:53Z
| 2003-06-27T18:53:20Z
|
weaver/src/org/aspectj/weaver/bcel/LazyMethodGen.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.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
import org.apache.bcel.Constants;
import org.apache.bcel.classfile.Attribute;
import org.apache.bcel.classfile.ConstantPool;
import org.apache.bcel.classfile.Method;
import org.apache.bcel.classfile.Synthetic;
import org.apache.bcel.generic.BranchHandle;
import org.apache.bcel.generic.BranchInstruction;
import org.apache.bcel.generic.CPInstruction;
import org.apache.bcel.generic.ClassGenException;
import org.apache.bcel.generic.CodeExceptionGen;
import org.apache.bcel.generic.ConstantPoolGen;
import org.apache.bcel.generic.Instruction;
import org.apache.bcel.generic.InstructionHandle;
import org.apache.bcel.generic.InstructionList;
import org.apache.bcel.generic.InstructionTargeter;
import org.apache.bcel.generic.LineNumberGen;
import org.apache.bcel.generic.LocalVariableGen;
import org.apache.bcel.generic.LocalVariableInstruction;
import org.apache.bcel.generic.MethodGen;
import org.apache.bcel.generic.ObjectType;
import org.apache.bcel.generic.Select;
import org.apache.bcel.generic.Type;
import org.aspectj.bridge.IMessage;
import org.aspectj.weaver.AjAttribute;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.ISourceContext;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.ResolvedTypeX;
/**
* A LazyMethodGen should be treated as a MethodGen. It's our way of abstracting over the
* low-level Method objects. It converts through {@link MethodGen} to create
* and to serialize, but that's it.
*
* <p> At any rate, there are two ways to create LazyMethodGens.
* One is from a method, which
* does work through MethodGen to do the correct thing.
* The other is the creation of a completely empty
* LazyMethodGen, and it is used when we're constructing code from scratch.
*
* <p> We stay away from targeters for rangey things like Shadows and Exceptions.
*/
public final class LazyMethodGen {
private int accessFlags;
private final Type returnType;
private final String name;
private final Type[] argumentTypes;
//private final String[] argumentNames;
private final String[] declaredExceptions;
private final InstructionList body; // leaving null for abstracts
private final Attribute[] attributes;
private final LazyClassGen enclosingClass;
private final BcelMethod memberView;
private int maxLocals;
private boolean canInline = true;
private boolean hasExceptionHandlers;
private boolean isSynthetic = false;
/**
* only used by {@link BcelClassWeaver}
*/
List /*ShadowMungers*/ matchedShadows;
// Used for interface introduction
// this is the type of the interface the method is technically on
public ResolvedTypeX definingType = null;
public LazyMethodGen(
int accessFlags,
Type returnType,
String name,
Type[] paramTypes,
String[] declaredExceptions,
LazyClassGen enclosingClass)
{
this.memberView = null; // ??? should be okay, since constructed ones aren't woven into
this.accessFlags = accessFlags;
this.returnType = returnType;
this.name = name;
this.argumentTypes = paramTypes;
//this.argumentNames = Utility.makeArgNames(paramTypes.length);
this.declaredExceptions = declaredExceptions;
if (!Modifier.isAbstract(accessFlags)) {
body = new InstructionList();
setMaxLocals(calculateMaxLocals());
} else {
body = null;
}
this.attributes = new Attribute[0];
this.enclosingClass = enclosingClass;
assertGoodBody();
}
private int calculateMaxLocals() {
int ret = 0;
if (!Modifier.isStatic(accessFlags)) ret++;
for (int i = 0, len = argumentTypes.length; i < len; i++) {
ret += argumentTypes[i].getSize();
}
return ret;
}
// build from an existing method
public LazyMethodGen(Method m, LazyClassGen enclosingClass) {
this.enclosingClass = enclosingClass;
if (!(m.isAbstract() || m.isNative()) && m.getCode() == null) {
throw new RuntimeException("bad non-abstract method with no code: " + m + " on " + enclosingClass);
}
if ((m.isAbstract() || m.isNative()) && m.getCode() != null) {
throw new RuntimeException("bad abstract method with code: " + m + " on " + enclosingClass);
}
MethodGen gen = new MethodGen(m, enclosingClass.getName(), enclosingClass.getConstantPoolGen());
this.memberView = new BcelMethod(enclosingClass.getBcelObjectType(), m);
this.accessFlags = gen.getAccessFlags();
this.returnType = gen.getReturnType();
this.name = gen.getName();
this.argumentTypes = gen.getArgumentTypes();
//this.argumentNames = gen.getArgumentNames();
this.declaredExceptions = gen.getExceptions();
this.attributes = gen.getAttributes();
this.maxLocals = gen.getMaxLocals();
if (gen.isAbstract() || gen.isNative()) {
body = null;
} else {
body = gen.getInstructionList();
unpackHandlers(gen);
unpackLineNumbers(gen);
unpackLocals(gen);
}
assertGoodBody();
}
// XXX we're relying on the javac promise I've just made up that we won't have an early exception
// in the list mask a later exception: That is, for two exceptions E and F,
// if E preceeds F, then either E \cup F = {}, or E \nonstrictsubset F. So when we add F,
// we add it on the _OUTSIDE_ of any handlers that share starts or ends with it.
// with that in mind, we merrily go adding ranges for exceptions.
private void unpackHandlers(MethodGen gen) {
CodeExceptionGen[] exns = gen.getExceptionHandlers();
if (exns != null) {
int len = exns.length;
if (len > 0) hasExceptionHandlers = true;
int priority = len - 1;
for (int i = 0; i < len; i++, priority--) {
CodeExceptionGen exn = exns[i];
InstructionHandle start =
Range.genStart(
body,
getOutermostExceptionStart(exn.getStartPC()));
InstructionHandle end = Range.genEnd(body, getOutermostExceptionEnd(exn.getEndPC()));
// this doesn't necessarily handle overlapping correctly!!!
ExceptionRange er =
new ExceptionRange(
body,
exn.getCatchType() == null
? null
: BcelWorld.fromBcel(exn.getCatchType()),
priority);
er.associateWithTargets(start, end, exn.getHandlerPC());
exn.setStartPC(null); // also removes from target
exn.setEndPC(null); // also removes from target
exn.setHandlerPC(null); // also removes from target
}
gen.removeExceptionHandlers();
}
}
private InstructionHandle getOutermostExceptionStart(InstructionHandle ih) {
while (true) {
if (ExceptionRange.isExceptionStart(ih.getPrev())) {
ih = ih.getPrev();
} else {
return ih;
}
}
}
private InstructionHandle getOutermostExceptionEnd(InstructionHandle ih) {
while (true) {
if (ExceptionRange.isExceptionEnd(ih.getNext())) {
ih = ih.getNext();
} else {
return ih;
}
}
}
private void unpackLineNumbers(MethodGen gen) {
LineNumberTag lr = null;
for (InstructionHandle ih = body.getStart(); ih != null; ih = ih.getNext()) {
InstructionTargeter[] targeters = ih.getTargeters();
if (targeters != null) {
for (int i = targeters.length - 1; i >= 0; i--) {
InstructionTargeter targeter = targeters[i];
if (targeter instanceof LineNumberGen) {
LineNumberGen lng = (LineNumberGen) targeter;
lng.updateTarget(ih, null);
lr = new LineNumberTag(lng.getSourceLine());
}
}
}
if (lr != null) {
ih.addTargeter(lr);
}
}
gen.removeLineNumbers();
}
private void unpackLocals(MethodGen gen) {
Set locals = new HashSet();
for (InstructionHandle ih = body.getStart(); ih != null; ih = ih.getNext()) {
InstructionTargeter[] targeters = ih.getTargeters();
List ends = new ArrayList(0);
if (targeters != null) {
for (int i = targeters.length - 1; i >= 0; i--) {
InstructionTargeter targeter = targeters[i];
if (targeter instanceof LocalVariableGen) {
LocalVariableGen lng = (LocalVariableGen) targeter;
LocalVariableTag lr = new LocalVariableTag(BcelWorld.fromBcel(lng.getType()), lng.getName(), lng.getIndex());
if (lng.getStart() == ih) {
lng.setStart(null);
locals.add(lr);
} else {
lng.setEnd(null);
ends.add(lr);
}
}
}
}
for (Iterator i = locals.iterator(); i.hasNext(); ) {
ih.addTargeter((LocalVariableTag) i.next());
}
locals.removeAll(ends);
}
gen.removeLocalVariables();
}
// ===============
public int allocateLocal(Type type) {
return allocateLocal(type.getSize());
}
public int allocateLocal(int slots) {
int max = getMaxLocals();
setMaxLocals(max + slots);
return max;
}
public Method getMethod() {
try {
MethodGen gen = pack();
return gen.getMethod();
} catch (ClassGenException e) {
enclosingClass.getBcelObjectType().getResolvedTypeX().getWorld().showMessage(
IMessage.ERROR, "problem generating method " +
this.getClassName() + "." + this.getName() + ": " + e.getMessage(),
this.getMemberView() == null ? null : this.getMemberView().getSourceLocation(), null);
throw e;
}
}
// =============================
public String toString() {
return toLongString();
}
public String toShortString() {
org.apache.bcel.classfile.Utility util = null; // EVIL!
String access = util.accessToString(getAccessFlags());
StringBuffer buf = new StringBuffer();
if (!access.equals("")) {
buf.append(access);
buf.append(" ");
}
buf.append(util.signatureToString(getReturnType().getSignature(), true));
buf.append(" ");
buf.append(getName());
buf.append("(");
{
int len = argumentTypes.length;
if (len > 0) {
buf.append(util.signatureToString(argumentTypes[0].getSignature(), true));
for (int i = 1; i < argumentTypes.length; i++) {
buf.append(", ");
buf.append(util.signatureToString(argumentTypes[i].getSignature(), true));
}
}
}
buf.append(")");
{
int len = declaredExceptions != null ? declaredExceptions.length : 0;
if (len > 0) {
buf.append(" throws ");
buf.append(declaredExceptions[0]);
for (int i = 1; i < declaredExceptions.length; i++) {
buf.append(", ");
buf.append(declaredExceptions[i]);
}
}
}
return buf.toString();
}
public String toLongString() {
ByteArrayOutputStream s = new ByteArrayOutputStream();
print(new PrintStream(s));
return new String(s.toByteArray());
}
public void print() {
print(System.out);
}
public void print(PrintStream out) {
out.print(" " + toShortString());
printAspectAttributes(out);
InstructionList body = getBody();
if (body == null) {
out.println(";");
return;
}
out.println(":");
new BodyPrinter(out).run();
out.println(" end " + toShortString());
}
private void printAspectAttributes(PrintStream out) {
ISourceContext context = null;
if (enclosingClass != null && enclosingClass.getType() != null) {
context = enclosingClass.getType().getSourceContext();
}
List as = BcelAttributes.readAjAttributes(attributes, context);
if (! as.isEmpty()) {
out.println(" " + as.get(0)); // XXX assuming exactly one attribute, munger...
}
}
private class BodyPrinter {
Map prefixMap = new HashMap();
Map suffixMap = new HashMap();
Map labelMap = new HashMap();
InstructionList body;
PrintStream out;
ConstantPool pool;
List ranges;
BodyPrinter(PrintStream out) {
this.pool = enclosingClass.getConstantPoolGen().getConstantPool();
this.body = getBody();
this.out = out;
}
void run() {
//killNops();
assignLabels();
print();
}
// label assignment
void assignLabels() {
LinkedList exnTable = new LinkedList();
String pendingLabel = null;
// boolean hasPendingTargeters = false;
int lcounter = 0;
for (InstructionHandle ih = body.getStart(); ih != null; ih = ih.getNext()) {
InstructionTargeter[] targeters = ih.getTargeters();
if (targeters != null) {
for (int i = targeters.length - 1; i >= 0; i--) {
InstructionTargeter t = targeters[i];
if (t instanceof ExceptionRange) {
// assert isRangeHandle(h);
ExceptionRange r = (ExceptionRange) t;
if (r.getStart() == ih) {
insertHandler(r, exnTable);
}
} else if (t instanceof BranchInstruction) {
if (pendingLabel == null) {
pendingLabel = "L" + lcounter++;
}
} else {
// assert isRangeHandle(h)
}
}
}
if (pendingLabel != null) {
labelMap.put(ih, pendingLabel);
if (! Range.isRangeHandle(ih)) {
pendingLabel = null;
}
}
}
int ecounter = 0;
for (Iterator i = exnTable.iterator(); i.hasNext();) {
ExceptionRange er = (ExceptionRange) i.next();
String exceptionLabel = "E" + ecounter++;
labelMap.put(Range.getRealStart(er.getHandler()), exceptionLabel);
labelMap.put(er.getHandler(), exceptionLabel);
}
}
// printing
void print() {
int depth = 0;
int currLine = -1;
bodyPrint:
for (InstructionHandle ih = body.getStart(); ih != null; ih = ih.getNext()) {
if (Range.isRangeHandle(ih)) {
Range r = Range.getRange(ih);
// don't print empty ranges, that is, ranges who contain no actual instructions
for (InstructionHandle xx = r.getStart(); Range.isRangeHandle(xx); xx = xx.getNext()) {
if (xx == r.getEnd()) continue bodyPrint;
}
// doesn't handle nested: if (r.getStart().getNext() == r.getEnd()) continue;
if (r.getStart() == ih) {
printRangeString(r, depth++);
} else {
if (r.getEnd() != ih) throw new RuntimeException("bad");
printRangeString(r, --depth);
}
} else {
printInstruction(ih, depth);
int line = getLineNumber(ih, currLine);
if (line != currLine) {
currLine = line;
out.println(" (line " + line + ")");
} else {
out.println();
}
}
}
}
void printRangeString(Range r, int depth) {
printDepth(depth);
out.println(getRangeString(r, labelMap));
}
String getRangeString(Range r, Map labelMap) {
if (r instanceof ExceptionRange) {
ExceptionRange er = (ExceptionRange) r;
return er.toString() + " -> " + labelMap.get(er.getHandler());
//
// + " PRI " + er.getPriority();
} else {
return r.toString();
}
}
void printDepth(int depth) {
pad(BODY_INDENT);
while (depth > 0) {
out.print("| ");
depth--;
}
}
void printLabel(String s, int depth) {
int space = Math.max(CODE_INDENT - depth * 2, 0);
if (s == null) {
pad(space);
} else {
space = Math.max(space - (s.length() + 2), 0);
pad(space);
out.print(s);
out.print(": ");
}
}
void printInstruction(InstructionHandle h, int depth) {
printDepth(depth);
printLabel((String) labelMap.get(h), depth);
Instruction inst = h.getInstruction();
if (inst instanceof CPInstruction) {
CPInstruction cpinst = (CPInstruction) inst;
out.print(Constants.OPCODE_NAMES[cpinst.getOpcode()].toUpperCase());
out.print(" ");
out.print(pool.constantToString(pool.getConstant(cpinst.getIndex())));
} else if (inst instanceof Select) {
Select sinst = (Select) inst;
out.println(Constants.OPCODE_NAMES[sinst.getOpcode()].toUpperCase());
int[] matches = sinst.getMatchs();
InstructionHandle[] targets = sinst.getTargets();
InstructionHandle defaultTarget = sinst.getTarget();
for (int i = 0, len = matches.length; i < len; i++) {
printDepth(depth);
printLabel(null, depth);
out.print(" ");
out.print(matches[i]);
out.print(": \t");
out.println(labelMap.get(targets[i]));
}
printDepth(depth);
printLabel(null, depth);
out.print(" ");
out.print("default: \t");
out.print(labelMap.get(defaultTarget));
} else if (inst instanceof BranchInstruction) {
BranchInstruction brinst = (BranchInstruction) inst;
out.print(Constants.OPCODE_NAMES[brinst.getOpcode()].toUpperCase());
out.print(" ");
out.print(labelMap.get(brinst.getTarget()));
} else if (inst instanceof LocalVariableInstruction) {
LocalVariableInstruction lvinst = (LocalVariableInstruction) inst;
out.print(inst.toString(false).toUpperCase());
int index = lvinst.getIndex();
LocalVariableTag tag = getLocalVariableTag(h, index);
if (tag != null) {
out.print(" // ");
out.print(tag.getType());
out.print(" ");
out.print(tag.getName());
}
} else {
out.print(inst.toString(false).toUpperCase());
}
}
static final int BODY_INDENT = 4;
static final int CODE_INDENT = 16;
void pad(int size) {
for (int i = 0; i < size; i++) {
out.print(" ");
}
}
}
static LocalVariableTag getLocalVariableTag(
InstructionHandle ih,
int index)
{
InstructionTargeter[] targeters = ih.getTargeters();
if (targeters == null) return null;
for (int i = targeters.length - 1; i >= 0; i--) {
InstructionTargeter t = targeters[i];
if (t instanceof LocalVariableTag) {
LocalVariableTag lvt = (LocalVariableTag) t;
if (lvt.getSlot() == index) return lvt;
}
}
return null;
}
static int getLineNumber(
InstructionHandle ih,
int prevLine)
{
InstructionTargeter[] targeters = ih.getTargeters();
if (targeters == null) return prevLine;
for (int i = targeters.length - 1; i >= 0; i--) {
InstructionTargeter t = targeters[i];
if (t instanceof LineNumberTag) {
return ((LineNumberTag)t).getLineNumber();
}
}
return prevLine;
}
public boolean isStatic() {
return Modifier.isStatic(getAccessFlags());
}
public boolean isAbstract() {
return Modifier.isAbstract(getAccessFlags());
}
public void addExceptionHandler(
InstructionHandle start,
InstructionHandle end,
InstructionHandle handlerStart,
ObjectType catchType,
boolean highPriority) {
InstructionHandle start1 = Range.genStart(body, start);
InstructionHandle end1 = Range.genEnd(body, end);
ExceptionRange er =
new ExceptionRange(body, BcelWorld.fromBcel(catchType), highPriority);
er.associateWithTargets(start1, end1, handlerStart);
}
public int getAccessFlags() {
return accessFlags;
}
public Type[] getArgumentTypes() {
return argumentTypes;
}
// public String[] getArgumentNames() {
// return argumentNames;
// }
public LazyClassGen getEnclosingClass() {
return enclosingClass;
}
public int getMaxLocals() {
return maxLocals;
}
public String getName() {
return name;
}
public Type getReturnType() {
return returnType;
}
public void setMaxLocals(int maxLocals) {
this.maxLocals = maxLocals;
}
public InstructionList getBody() {
return body;
}
public boolean hasBody() { return body != null; }
public Attribute[] getAttributes() {
return attributes;
}
public String[] getDeclaredExceptions() {
return declaredExceptions;
}
public String getClassName() {
return enclosingClass.getName();
}
// ---- packing!
public MethodGen pack() {
//killNops();
MethodGen gen =
new MethodGen(
getAccessFlags(),
getReturnType(),
getArgumentTypes(),
null, //getArgumentNames(),
getName(),
getEnclosingClass().getName(),
new InstructionList(),
getEnclosingClass().getConstantPoolGen());
for (int i = 0, len = declaredExceptions.length; i < len; i++) {
gen.addException(declaredExceptions[i]);
}
for (int i = 0, len = attributes.length; i < len; i++) {
gen.addAttribute(attributes[i]);
}
if (isSynthetic) {
ConstantPoolGen cpg = gen.getConstantPool();
int index = cpg.addUtf8("Synthetic");
gen.addAttribute(new Synthetic(index, 0, new byte[0], cpg.getConstantPool()));
}
if (hasBody()) {
packBody(gen);
gen.setMaxLocals();
gen.setMaxStack();
} else {
gen.setInstructionList(null);
}
return gen;
}
public void makeSynthetic() {
isSynthetic = true;
}
/** fill the newly created method gen with our body,
* inspired by InstructionList.copy()
*/
public void packBody(MethodGen gen) {
HashMap map = new HashMap();
InstructionList fresh = gen.getInstructionList();
/* Make copies of all instructions, append them to the new list
* and associate old instruction references with the new ones, i.e.,
* a 1:1 mapping.
*/
for (InstructionHandle ih = getBody().getStart(); ih != null; ih = ih.getNext()) {
if (Range.isRangeHandle(ih)) {
continue;
}
Instruction i = ih.getInstruction();
Instruction c = Utility.copyInstruction(i);
if (c instanceof BranchInstruction)
map.put(ih, fresh.append((BranchInstruction) c));
else
map.put(ih, fresh.append(c));
}
// at this point, no rangeHandles are in fresh. Let's use that...
/* Update branch targets and insert various attributes.
* Insert our exceptionHandlers
* into a sorted list, so they can be added in order later.
*/
InstructionHandle ih = getBody().getStart();
InstructionHandle jh = fresh.getStart();
LinkedList exnList = new LinkedList();
// map from localvariabletag to instruction handle
Map localVariableStarts = new HashMap();
Map localVariableEnds = new HashMap();
int currLine = -1;
while (ih != null) {
if (map.get(ih) == null) {
// we're a range instruction
Range r = Range.getRange(ih);
if (r instanceof ExceptionRange) {
ExceptionRange er = (ExceptionRange) r;
if (er.getStart() == ih) {
//System.err.println("er " + er);
if (!er.isEmpty()){
// order is important, insert handlers in order of start
insertHandler(er, exnList);
}
}
} else {
// we must be a shadow range or something equally useless,
// so forget about doing anything
}
// just increment ih.
ih = ih.getNext();
} else {
// assert map.get(ih) == jh
Instruction i = ih.getInstruction();
Instruction j = jh.getInstruction();
if (i instanceof BranchInstruction) {
BranchInstruction bi = (BranchInstruction) i;
BranchInstruction bj = (BranchInstruction) j;
InstructionHandle itarget = bi.getTarget(); // old target
// try {
// New target is in hash map
bj.setTarget(remap(itarget, map));
// } catch (NullPointerException e) {
// print();
// System.out.println("Was trying to remap " + bi);
// System.out.println("who's target was supposedly " + itarget);
// throw e;
// }
if (bi instanceof Select) {
// Either LOOKUPSWITCH or TABLESWITCH
InstructionHandle[] itargets = ((Select) bi).getTargets();
InstructionHandle[] jtargets = ((Select) bj).getTargets();
for (int k = itargets.length - 1; k >= 0; k--) {
// Update all targets
jtargets[k] = remap(itargets[k], map);
jtargets[k].addTargeter(bj);
}
}
}
// now deal with line numbers
// and store up info for local variables
InstructionTargeter[] targeters = ih.getTargeters();
if (targeters != null) {
for (int k = targeters.length - 1; k >= 0; k--) {
InstructionTargeter targeter = targeters[k];
if (targeter instanceof LineNumberTag) {
int line = ((LineNumberTag)targeter).getLineNumber();
if (line != currLine) {
gen.addLineNumber(jh, line);
currLine = line;
}
} else if (targeter instanceof LocalVariableTag) {
LocalVariableTag lvt = (LocalVariableTag) targeter;
if (i instanceof LocalVariableInstruction) {
int index = ((LocalVariableInstruction)i).getIndex();
if (lvt.getSlot() == index) {
if (localVariableStarts.get(lvt) == null) {
localVariableStarts.put(lvt, jh);
}
localVariableEnds.put(lvt, jh);
}
}
}
}
}
// now continue
ih = ih.getNext();
jh = jh.getNext();
}
}
// now add exception handlers
for (Iterator iter = exnList.iterator(); iter.hasNext();) {
ExceptionRange r = (ExceptionRange) iter.next();
if (r.isEmpty()) continue;
gen.addExceptionHandler(
remap(r.getRealStart(), map),
remap(r.getRealEnd(), map),
remap(r.getHandler(), map),
(r.getCatchType() == null)
? null
: (ObjectType) BcelWorld.makeBcelType(r.getCatchType()));
}
// now add local variables
gen.removeLocalVariables();
// BCEL sometimes creates extra local variables with the same name. We now
// remove them and add back to the gen.
Map duplicatedLocalMap = new HashMap();
List keys = new ArrayList();
keys.addAll(localVariableStarts.keySet());
Collections.sort(keys,new Comparator() {
public int compare(Object a,Object b) {
LocalVariableTag taga = (LocalVariableTag)a;
LocalVariableTag tagb = (LocalVariableTag)b;
return taga.getName().compareTo(tagb.getName());
}});
for (Iterator iter = keys.iterator(); iter.hasNext(); ) {
LocalVariableTag tag = (LocalVariableTag) iter.next();
// have we already added one with the same slot number and start location?
// if so, just continue.
InstructionHandle start = (InstructionHandle) localVariableStarts.get(tag);
Set slots = (Set) duplicatedLocalMap.get(start);
if (slots == null) {
slots = new HashSet();
duplicatedLocalMap.put(start, slots);
}
if (slots.contains(new Integer(tag.getSlot()))) {
// we already have a var starting at this tag with this slot
continue;
}
slots.add(new Integer(tag.getSlot()));
gen.addLocalVariable(
tag.getName(),
BcelWorld.makeBcelType(tag.getType()),
tag.getSlot(),
(InstructionHandle) localVariableStarts.get(tag),
(InstructionHandle) localVariableEnds.get(tag));
}
}
/** This proedure should not currently be used.
*/
// public void killNops() {
// InstructionHandle curr = body.getStart();
// while (true) {
// if (curr == null) break;
// InstructionHandle next = curr.getNext();
// if (curr.getInstruction() instanceof NOP) {
// InstructionTargeter[] targeters = curr.getTargeters();
// if (targeters != null) {
// for (int i = 0, len = targeters.length; i < len; i++) {
// InstructionTargeter targeter = targeters[i];
// targeter.updateTarget(curr, next);
// }
// }
// try {
// body.delete(curr);
// } catch (TargetLostException e) {
// }
// }
// curr = next;
// }
// }
private static InstructionHandle remap(InstructionHandle ih, Map map) {
while (true) {
Object ret = map.get(ih);
if (ret == null) {
ih = ih.getNext();
} else {
return (InstructionHandle) ret;
}
}
}
// exception ordering.
// What we should be doing is dealing with priority inversions way earlier than we are
// and counting on the tree structure. In which case, the below code is in fact right.
// XXX THIS COMMENT BELOW IS CURRENTLY WRONG.
// An exception A preceeds an exception B in the exception table iff:
// * A and B were in the original method, and A preceeded B in the original exception table
// * If A has a higher priority than B, than it preceeds B.
// * If A and B have the same priority, then the one whose START happens EARLIEST has LEAST priority.
// in short, the outermost exception has least priority.
// we implement this with a LinkedList. We could possibly implement this with a java.util.SortedSet,
// but I don't trust the only implementation, TreeSet, to do the right thing.
private static void insertHandler(ExceptionRange fresh, LinkedList l) {
// for (ListIterator iter = l.listIterator(); iter.hasNext();) {
// ExceptionRange r = (ExceptionRange) iter.next();
// if (fresh.getPriority() >= r.getPriority()) {
// iter.previous();
// iter.add(fresh);
// return;
// }
// }
l.add(0, fresh);
}
public boolean isPrivate() {
return Modifier.isPrivate(getAccessFlags());
}
// ----
/** A good body is a body with the following properties:
*
* <ul>
* <li> For each branch instruction S in body, target T of S is in body.
* <li> For each branch instruction S in body, target T of S has S as a targeter.
* <li> For each instruction T in body, for each branch instruction S that is a
* targeter of T, S is in body.
* <li> For each non-range-handle instruction T in body, for each instruction S
* that is a targeter of T, S is
* either a branch instruction, an exception range or a tag
* <li> For each range-handle instruction T in body, there is exactly one targeter S
* that is a range.
* <li> For each range-handle instruction T in body, the range R targeting T is in body.
* <li> For each instruction T in body, for each exception range R targeting T, R is
* in body.
* <li> For each exception range R in body, let T := R.handler. T is in body, and R is one
* of T's targeters
* <li> All ranges are properly nested: For all ranges Q and R, if Q.start preceeds
* R.start, then R.end preceeds Q.end.
* </ul>
*
* Where the shorthand "R is in body" means "R.start is in body, R.end is in body, and
* any InstructionHandle stored in a field of R (such as an exception handle) is in body".
*/
public void assertGoodBody() {
// XXX this is REALLY slow since we get the string first...
assertGoodBody(getBody(), toString());
}
// XXX we might not want to release with any calls to this incredibly inefficient method.
public static void assertGoodBody(InstructionList il, String from) {
if (true) return;
if (il == null) return;
Set body = new HashSet();
Stack ranges = new Stack();
for (InstructionHandle ih = il.getStart(); ih != null; ih = ih.getNext()) {
body.add(ih);
if (ih.getInstruction() instanceof BranchInstruction) {
body.add(ih.getInstruction());
}
}
for (InstructionHandle ih = il.getStart(); ih != null; ih = ih.getNext()) {
assertGoodHandle(ih, body, ranges, from);
InstructionTargeter[] ts = ih.getTargeters();
if (ts != null) {
for (int i = ts.length - 1; i >= 0; i--) {
assertGoodTargeter(ts[i], ih, body, from);
}
}
}
}
private static void assertGoodHandle(InstructionHandle ih, Set body, Stack ranges, String from) {
Instruction inst = ih.getInstruction();
if ((inst instanceof BranchInstruction) ^ (ih instanceof BranchHandle)) {
throw new BCException("bad instruction/handle pair in " + from);
}
if (Range.isRangeHandle(ih)) {
assertGoodRangeHandle(ih, body, ranges, from);
} else if (inst instanceof BranchInstruction) {
assertGoodBranchInstruction((BranchHandle) ih, (BranchInstruction) inst, body, ranges, from);
}
}
private static void assertGoodBranchInstruction(
BranchHandle ih,
BranchInstruction inst,
Set body,
Stack ranges,
String from)
{
if (ih.getTarget() != inst.getTarget()) {
throw new BCException("bad branch instruction/handle pair in " + from);
}
InstructionHandle target = ih.getTarget();
assertInBody(target, body, from);
assertTargetedBy(target, inst, from);
if (inst instanceof Select) {
Select sel = (Select) inst;
InstructionHandle[] itargets = sel.getTargets();
for (int k = itargets.length - 1; k >= 0; k--) {
assertInBody(itargets[k], body, from);
assertTargetedBy(itargets[k], inst, from);
}
}
}
/** ih is an InstructionHandle or a BranchInstruction */
private static void assertInBody(Object ih, Set body, String from) {
if (! body.contains(ih)) throw new BCException("thing not in body in " + from);
}
private static void assertGoodRangeHandle(InstructionHandle ih, Set body, Stack ranges, String from) {
Range r = getRangeAndAssertExactlyOne(ih, from);
assertGoodRange(r, body, from);
if (r.getStart() == ih) {
ranges.push(r);
} else if (r.getEnd() == ih) {
if (ranges.peek() != r) throw new BCException("bad range inclusion in " + from);
ranges.pop();
}
}
private static void assertGoodRange(Range r, Set body, String from) {
assertInBody(r.getStart(), body, from);
assertRangeHandle(r.getStart(), from);
assertTargetedBy(r.getStart(), r, from);
assertInBody(r.getEnd(), body, from);
assertRangeHandle(r.getEnd(), from);
assertTargetedBy(r.getEnd(), r, from);
if (r instanceof ExceptionRange) {
ExceptionRange er = (ExceptionRange) r;
assertInBody(er.getHandler(), body, from);
assertTargetedBy(er.getHandler(), r, from);
}
}
private static void assertRangeHandle(InstructionHandle ih, String from) {
if (! Range.isRangeHandle(ih)) throw new BCException("bad range handle " + ih + " in " + from);
}
private static void assertTargetedBy(
InstructionHandle target,
InstructionTargeter targeter,
String from)
{
InstructionTargeter[] ts = target.getTargeters();
if (ts == null) throw new BCException("bad targeting relationship in " + from);
for (int i = ts.length - 1; i >= 0; i--) {
if (ts[i] == targeter) return;
}
throw new RuntimeException("bad targeting relationship in " + from);
}
private static void assertTargets(InstructionTargeter targeter, InstructionHandle target, String from) {
if (targeter instanceof Range) {
Range r = (Range) targeter;
if (r.getStart() == target || r.getEnd() == target) return;
if (r instanceof ExceptionRange) {
if (((ExceptionRange)r).getHandler() == target) return;
}
} else if (targeter instanceof BranchInstruction) {
BranchInstruction bi = (BranchInstruction) targeter;
if (bi.getTarget() == target) return;
if (targeter instanceof Select) {
Select sel = (Select) targeter;
InstructionHandle[] itargets = sel.getTargets();
for (int k = itargets.length - 1; k >= 0; k--) {
if (itargets[k] == target) return;
}
}
} else if (targeter instanceof Tag) {
return;
}
throw new BCException(targeter + " doesn't target " + target + " in " + from );
}
private static Range getRangeAndAssertExactlyOne(InstructionHandle ih, String from) {
Range ret = null;
InstructionTargeter[] ts = ih.getTargeters();
if (ts == null) throw new BCException("range handle with no range in " + from);
for (int i = ts.length - 1; i >= 0; i--) {
if (ts[i] instanceof Range) {
if (ret != null) throw new BCException("range handle with multiple ranges in " + from);
ret = (Range) ts[i];
}
}
if (ret == null) throw new BCException("range handle with no range in " + from);
return ret;
}
private static void assertGoodTargeter(
InstructionTargeter t,
InstructionHandle ih,
Set body,
String from)
{
assertTargets(t, ih, from);
if (t instanceof Range) {
assertGoodRange((Range) t, body, from);
} else if (t instanceof BranchInstruction) {
assertInBody(t, body, from);
}
}
// ----
boolean isAdviceMethod() {
return memberView.getAssociatedShadowMunger() != null;
}
boolean isAjSynthetic() {
if (memberView == null) return true;
return memberView.isAjSynthetic();
}
public AjAttribute.EffectiveSignatureAttribute getEffectiveSignature() {
//if (memberView == null) return null;
return memberView.getEffectiveSignature();
}
public String getSignature() {
return Member.typesToSignature(BcelWorld.fromBcel(getReturnType()),
BcelWorld.fromBcel(getArgumentTypes()));
}
public BcelMethod getMemberView() {
return memberView;
}
public void forcePublic() {
accessFlags = Utility.makePublic(accessFlags);
}
public boolean getCanInline() {
return canInline;
}
public void setCanInline(boolean canInline) {
this.canInline = canInline;
}
public boolean hasExceptionHandlers() {
return hasExceptionHandlers;
}
}
|
41,888
|
Bug 41888 call PCD fails when given subtype of defining type
| null |
resolved wontfix
|
9df9062
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2003-08-23T04:22:23Z
| 2003-08-23T03:40:00Z
|
tests/bugs/CallReference.java
| |
41,359
|
Bug 41359 percflow aspects compiled from jars share one instance for all entry points
|
When a percflow aspect is woven into source code from a jar using the aspectPath compiler option, it produces only one instance of the aspect for each entrypoint defined in the source code.
|
resolved fixed
|
5a07dce
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2003-08-28T21:44:55Z
| 2003-08-09T14:40: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.Clinit;
import org.eclipse.jdt.internal.compiler.ast.MemberTypeDeclaration;
import org.eclipse.jdt.internal.compiler.codegen.CodeStream;
import org.eclipse.jdt.internal.compiler.codegen.Label;
import org.eclipse.jdt.internal.compiler.lookup.*;
// making all aspects member types avoids a nasty hierarchy pain
public class AspectDeclaration extends MemberTypeDeclaration {
//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
// 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;
}
if (concreteName != null) concreteName.checkPointcutDeclarations();
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.buildManager.buildConfig.isXserializableAspects()) {
if (world.getWorld().resolve(TypeX.SERIALIZABLE).isAssignableFrom(myType)) {
scope.problemReporter().signalError(sourceStart, sourceEnd,
"aspects may not implement Serializable");
ignoreFurtherInvestigation = true;
return;
}
if (world.getWorld().resolve(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;
}
}
}
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()) {
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);
} else if (perClause.getKind() == PerClause.PERCFLOW) {
binding.addField(
factory.makeFieldBinding(
AjcMemberMaker.perCflowField(
typeX)));
methods[0] = new AspectClinit((Clinit)methods[0], compilationResult, true, false);
} 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(0));
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.entrySet().iterator(); i.hasNext(); ) {
Map.Entry e = (Map.Entry)i.next();
generateSuperAccessMethod(classFile, (MethodBinding)e.getValue(), (ResolvedMember)e.getKey());
}
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) {
EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
classFile.generateMethodInfoHeader(methodBinding);
int methodAttributeOffset = classFile.contentsOffset;
int attributeNumber = classFile.generateMethodInfoAttribute(methodBinding, AstUtil.getAjSyntheticAttribute());
int codeAttributeOffset = classFile.contentsOffset;
classFile.generateCodeAttributeHeader();
CodeStream codeStream = classFile.codeStream;
codeStream.init(classFile);
codeStream.initializeMaxLocals(methodBinding);
// 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(
world.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(
world.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(world.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) {
// 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.new_(world.makeTypeBinding(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION));
codeStream.dup();
codeStream.invokespecial(world.makeMethodBindingForCall(
AjcMemberMaker.noAspectBoundExceptionInit()
));
codeStream.athrow();
// 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(
world.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,
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,
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,
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) {
if (binding instanceof SourceTypeBinding && !(binding instanceof BinaryTypeBinding)) {
SourceTypeBinding sourceSc = (SourceTypeBinding)binding;
if (sourceSc.scope.referenceContext instanceof AspectDeclaration) {
PerClause perClause = ((AspectDeclaration)sourceSc.scope.referenceContext).perClause;
if (perClause == null) return lookupPerClauseKind(binding.superclass());
else return perClause.getKind();
} else {
return null;
}
} else {
//XXX need to handle this too
return null;
}
}
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);
}
}
}
//??? timing is weird
factory.getWorld().getCrosscuttingMembersSet().addOrReplaceAspect(typeX);
if (typeX.getSuperclass().isAspect() && !typeX.getSuperclass().isExposedToWeaver()) {
factory.getWorld().getCrosscuttingMembersSet().addOrReplaceAspect(typeX.getSuperclass());
}
}
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 String toStringHeader() {
String s = ""; //$NON-NLS-1$
if (modifiers != AccDefault) {
s += modifiersString(modifiers);
}
s += "aspect " + new String(name);//$NON-NLS-1$ //$NON-NLS-2$
if (superclass != null)
s += " extends " + superclass.toString(0); //$NON-NLS-1$
if (superInterfaces != null && superInterfaces.length > 0) {
s += (isInterface() ? " extends " : " implements ");//$NON-NLS-2$ //$NON-NLS-1$
for (int i = 0; i < superInterfaces.length; i++) {
s += superInterfaces[i].toString(0);
if (i != superInterfaces.length - 1)
s += ", "; //$NON-NLS-1$
};
};
return s;
}
}
|
41,359
|
Bug 41359 percflow aspects compiled from jars share one instance for all entry points
|
When a percflow aspect is woven into source code from a jar using the aspectPath compiler option, it produces only one instance of the aspect for each entrypoint defined in the source code.
|
resolved fixed
|
5a07dce
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2003-08-28T21:44:55Z
| 2003-08-09T14:40:00Z
|
tests/bugs/perCflowAndJar/PerCFlowCompileFromJar.java
| |
41,359
|
Bug 41359 percflow aspects compiled from jars share one instance for all entry points
|
When a percflow aspect is woven into source code from a jar using the aspectPath compiler option, it produces only one instance of the aspect for each entrypoint defined in the source code.
|
resolved fixed
|
5a07dce
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2003-08-28T21:44:55Z
| 2003-08-09T14:40:00Z
|
tests/bugs/perCflowAndJar/PerCFlowCompileFromJarTest.java
| |
42,539
|
Bug 42539 throw derivative pointcuts not advised.
|
Given the following point cut and advice: public aspect ExceptionAspect { pointcut exceptionThrower() : execution(public * ExceptionBugTest.*(..) throws Exception+); declare warning : exceptionThrower() : "throws Exception+"; } And the to be aspected code: public class ExceptionBugTest { class MyException extends Exception { } public void method1() throws Exception { } public void method2() throws MyException { } } listing file default.lst: C:\temp\AJC Bug\ExceptionAspect.aj C:\temp\AJC Bug\ExceptionBugTest.java AJC does not advise ExceptionBugTest.method2(). The output from the compilation is the following: C:\temp\AJC Bug>ajc -argfile default.lst -classpath %ASPECTJ_HOME%\lib\aspectjrt.jar C:\eclipse\workspace\AJC Bug\ExceptionBugTest.java:11 throws Exception+ From the aspect-j mailing list, contributed by Jim Hugunin: <detail>The bug was caused because the code for ThrowsPattern mistakenly used the internal protected method TypePattern.matchesExactly instead of the external public method TypePattern.matchesStatically. Because the classes were in the same package, Java's accessibility rules allowed this. It would be nice if there was an easy way to specifiy that a method could only be accessed from subtypes.</detail>
|
resolved fixed
|
8660cc1
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2003-09-04T15:49:08Z
| 2003-09-04T15:40:00Z
|
tests/bugs/throwsSignature/ExceptionAspect.java
| |
42,539
|
Bug 42539 throw derivative pointcuts not advised.
|
Given the following point cut and advice: public aspect ExceptionAspect { pointcut exceptionThrower() : execution(public * ExceptionBugTest.*(..) throws Exception+); declare warning : exceptionThrower() : "throws Exception+"; } And the to be aspected code: public class ExceptionBugTest { class MyException extends Exception { } public void method1() throws Exception { } public void method2() throws MyException { } } listing file default.lst: C:\temp\AJC Bug\ExceptionAspect.aj C:\temp\AJC Bug\ExceptionBugTest.java AJC does not advise ExceptionBugTest.method2(). The output from the compilation is the following: C:\temp\AJC Bug>ajc -argfile default.lst -classpath %ASPECTJ_HOME%\lib\aspectjrt.jar C:\eclipse\workspace\AJC Bug\ExceptionBugTest.java:11 throws Exception+ From the aspect-j mailing list, contributed by Jim Hugunin: <detail>The bug was caused because the code for ThrowsPattern mistakenly used the internal protected method TypePattern.matchesExactly instead of the external public method TypePattern.matchesStatically. Because the classes were in the same package, Java's accessibility rules allowed this. It would be nice if there was an easy way to specifiy that a method could only be accessed from subtypes.</detail>
|
resolved fixed
|
8660cc1
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2003-09-04T15:49:08Z
| 2003-09-04T15:40:00Z
|
tests/bugs/throwsSignature/ExceptionBugTest.java
| |
42,539
|
Bug 42539 throw derivative pointcuts not advised.
|
Given the following point cut and advice: public aspect ExceptionAspect { pointcut exceptionThrower() : execution(public * ExceptionBugTest.*(..) throws Exception+); declare warning : exceptionThrower() : "throws Exception+"; } And the to be aspected code: public class ExceptionBugTest { class MyException extends Exception { } public void method1() throws Exception { } public void method2() throws MyException { } } listing file default.lst: C:\temp\AJC Bug\ExceptionAspect.aj C:\temp\AJC Bug\ExceptionBugTest.java AJC does not advise ExceptionBugTest.method2(). The output from the compilation is the following: C:\temp\AJC Bug>ajc -argfile default.lst -classpath %ASPECTJ_HOME%\lib\aspectjrt.jar C:\eclipse\workspace\AJC Bug\ExceptionBugTest.java:11 throws Exception+ From the aspect-j mailing list, contributed by Jim Hugunin: <detail>The bug was caused because the code for ThrowsPattern mistakenly used the internal protected method TypePattern.matchesExactly instead of the external public method TypePattern.matchesStatically. Because the classes were in the same package, Java's accessibility rules allowed this. It would be nice if there was an easy way to specifiy that a method could only be accessed from subtypes.</detail>
|
resolved fixed
|
8660cc1
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2003-09-04T15:49:08Z
| 2003-09-04T15:40:00Z
|
weaver/src/org/aspectj/weaver/patterns/ThrowsPattern.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.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import org.aspectj.weaver.ISourceContext;
import org.aspectj.weaver.ResolvedTypeX;
import org.aspectj.weaver.TypeX;
import org.aspectj.weaver.World;
public class ThrowsPattern extends PatternNode {
private TypePatternList required;
private TypePatternList forbidden;
public static final ThrowsPattern ANY =
new ThrowsPattern(TypePatternList.EMPTY, TypePatternList.EMPTY);
public ThrowsPattern(TypePatternList required, TypePatternList forbidden) {
this.required = required;
this.forbidden = forbidden;
}
public String toString() {
if (this == ANY) return "";
String ret = "throws " + required.toString();
if (forbidden.size() > 0) {
ret = ret + " !(" + forbidden.toString() + ")";
}
return ret;
}
public boolean equals(Object other) {
if (!(other instanceof ThrowsPattern)) return false;
ThrowsPattern o = (ThrowsPattern)other;
return o.required.equals(this.required) &&
o.forbidden.equals(this.forbidden);
}
public int hashCode() {
int result = 17;
result = 37*result + required.hashCode();
result = 37*result + forbidden.hashCode();
return result;
}
public ThrowsPattern resolveBindings(IScope scope, Bindings bindings) {
if (this == ANY) return this;
required = required.resolveBindings(scope, bindings, false, false);
forbidden = forbidden.resolveBindings(scope, bindings, false, false);
return this;
}
public boolean matches(TypeX[] tys, World world) {
if (this == ANY) return true;
//System.out.println("matching: " + this + " with " + Arrays.asList(tys));
ResolvedTypeX[] types = world.resolve(tys);
int len = types.length;
for (int j=0, lenj = required.size(); j < lenj; j++) {
if (! matchesAny(required.get(j), types)) {
return false;
}
}
for (int j=0, lenj = forbidden.size(); j < lenj; j++) {
if (matchesAny(forbidden.get(j), types)) {
return false;
}
}
return true;
}
private boolean matchesAny(
TypePattern typePattern,
ResolvedTypeX[] types)
{
for (int i = types.length - 1; i >= 0; i--) {
if (typePattern.matchesExactly(types[i])) return true;
}
return false;
}
public static ThrowsPattern read(DataInputStream s, ISourceContext context) throws IOException {
TypePatternList required = TypePatternList.read(s, context);
TypePatternList forbidden = TypePatternList.read(s, context);
if (required.size() == 0 && forbidden.size() == 0) return ANY;
ThrowsPattern ret = new ThrowsPattern(required, forbidden);
//XXXret.readLocation(context, s);
return ret;
}
public void write(DataOutputStream s) throws IOException {
required.write(s);
forbidden.write(s);
//XXXwriteLocation(s);
}
}
|
42,740
|
Bug 42740 declare error fails on pointcuts composed from multiple classes
|
This error occurs in both 1.1.0 and in the head of CVS as of 9/8/03. The compiler crash output from the CVS head version is at the end. It may be related to 42739, but they may be distinct problems. Sample source: /* * Created on Sep 8, 2003 * * Copyright (c) 2003 New Aspects of Security. All Rights Reserved. */ aspect Library { public pointcut executionsThrowingChecked() : execution(* *(..) throws (Exception+ && !RuntimeException)); } public aspect SampleExceptionHandling { public pointcut scope() : within(org.atrack.model..*); public pointcut executionsThrowingChecked() : Library.executionsThrowingChecked() && scope(); declare error : executionsThrowingChecked(): "no checked exceptions"; } sample compile: C:\eclipse\workspace\atrack>ajc src\SampleExceptionHandling.java java.lang.Exception: Stack trace at java.lang.Thread.dumpStack(Thread.java:1071) at org.aspectj.weaver.patterns.ReferencePointcut.concretize1 (ReferencePo intcut.java:215) at org.aspectj.weaver.patterns.AndPointcut.concretize1 (AndPointcut.java: 88) at org.aspectj.weaver.patterns.ReferencePointcut.concretize1 (ReferencePo intcut.java:272) at org.aspectj.weaver.patterns.AndPointcut.concretize1 (AndPointcut.java: 88) at org.aspectj.weaver.patterns.ReferencePointcut.concretize1 (ReferencePo intcut.java:272) at org.aspectj.weaver.patterns.Pointcut.concretize(Pointcut.java:127) at org.aspectj.weaver.patterns.Pointcut.concretize(Pointcut.java:120) at org.aspectj.weaver.Checker.concretize(Checker.java:37) at org.aspectj.weaver.CrosscuttingMembers.addShadowMunger (CrosscuttingMe mbers.java:78) at org.aspectj.weaver.CrosscuttingMembers.addDeclare (CrosscuttingMembers .java:102) at org.aspectj.weaver.CrosscuttingMembers.addDeclares (CrosscuttingMember s.java:92) at org.aspectj.weaver.ResolvedTypeX.collectCrosscuttingMembers (ResolvedT ypeX.java:332) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (Crosscut tingMembersSet.java:50) at org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration.buildInterTy peAndPerClause(AspectDeclaration.java:754) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.buildIn terTypeAndPerClause(AjLookupEnvironment.java:124) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.complet eTypeBindings(AjLookupEnvironment.java:91) at org.eclipse.jdt.internal.compiler.Compiler.beginToCompile (Compiler.ja va:310) at org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:324) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilat ion(AjBuildManager.java:373) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuild Manager.java:125) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBu ildManager.java:70) at org.aspectj.ajdt.ajc.AjdtCommand.doCommand(AjdtCommand.java:99) at org.aspectj.ajdt.ajc.AjdtCommand.runCommand(AjdtCommand.java:53) at org.aspectj.tools.ajc.Main.run(Main.java:217) at org.aspectj.tools.ajc.Main.runMain(Main.java:155) at org.aspectj.tools.ajc.Main.main(Main.java:72) C:\eclipse\workspace\atrack\src\SampleExceptionHandling.java:15 circular pointcu t declaration involving: executionsThrowingChecked() 1 error
|
resolved fixed
|
d78d9ed
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2003-09-10T00:35:18Z
| 2003-09-09T04: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.Clinit;
import org.eclipse.jdt.internal.compiler.ast.MemberTypeDeclaration;
import org.eclipse.jdt.internal.compiler.codegen.CodeStream;
import org.eclipse.jdt.internal.compiler.codegen.Label;
import org.eclipse.jdt.internal.compiler.lookup.*;
// making all aspects member types avoids a nasty hierarchy pain
public class AspectDeclaration extends MemberTypeDeclaration {
//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
// 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;
}
if (concreteName != null) concreteName.checkPointcutDeclarations();
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.buildManager.buildConfig.isXserializableAspects()) {
if (world.getWorld().resolve(TypeX.SERIALIZABLE).isAssignableFrom(myType)) {
scope.problemReporter().signalError(sourceStart, sourceEnd,
"aspects may not implement Serializable");
ignoreFurtherInvestigation = true;
return;
}
if (world.getWorld().resolve(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;
}
}
}
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()) {
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);
} else if (perClause.getKind() == PerClause.PERCFLOW) {
binding.addField(
factory.makeFieldBinding(
AjcMemberMaker.perCflowField(
typeX)));
methods[0] = new AspectClinit((Clinit)methods[0], compilationResult, true, false);
} 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(0));
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.entrySet().iterator(); i.hasNext(); ) {
Map.Entry e = (Map.Entry)i.next();
generateSuperAccessMethod(classFile, (MethodBinding)e.getValue(), (ResolvedMember)e.getKey());
}
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) {
EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
classFile.generateMethodInfoHeader(methodBinding);
int methodAttributeOffset = classFile.contentsOffset;
int attributeNumber = classFile.generateMethodInfoAttribute(methodBinding, AstUtil.getAjSyntheticAttribute());
int codeAttributeOffset = classFile.contentsOffset;
classFile.generateCodeAttributeHeader();
CodeStream codeStream = classFile.codeStream;
codeStream.init(classFile);
codeStream.initializeMaxLocals(methodBinding);
// 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(
world.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(
world.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(world.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) {
// 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.new_(world.makeTypeBinding(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION));
codeStream.dup();
codeStream.invokespecial(world.makeMethodBindingForCall(
AjcMemberMaker.noAspectBoundExceptionInit()
));
codeStream.athrow();
// 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(
world.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,
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,
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,
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);
}
}
}
//??? timing is weird
factory.getWorld().getCrosscuttingMembersSet().addOrReplaceAspect(typeX);
if (typeX.getSuperclass().isAspect() && !typeX.getSuperclass().isExposedToWeaver()) {
factory.getWorld().getCrosscuttingMembersSet().addOrReplaceAspect(typeX.getSuperclass());
}
}
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 String toStringHeader() {
String s = ""; //$NON-NLS-1$
if (modifiers != AccDefault) {
s += modifiersString(modifiers);
}
s += "aspect " + new String(name);//$NON-NLS-1$ //$NON-NLS-2$
if (superclass != null)
s += " extends " + superclass.toString(0); //$NON-NLS-1$
if (superInterfaces != null && superInterfaces.length > 0) {
s += (isInterface() ? " extends " : " implements ");//$NON-NLS-2$ //$NON-NLS-1$
for (int i = 0; i < superInterfaces.length; i++) {
s += superInterfaces[i].toString(0);
if (i != superInterfaces.length - 1)
s += ", "; //$NON-NLS-1$
};
};
return s;
}
}
|
42,740
|
Bug 42740 declare error fails on pointcuts composed from multiple classes
|
This error occurs in both 1.1.0 and in the head of CVS as of 9/8/03. The compiler crash output from the CVS head version is at the end. It may be related to 42739, but they may be distinct problems. Sample source: /* * Created on Sep 8, 2003 * * Copyright (c) 2003 New Aspects of Security. All Rights Reserved. */ aspect Library { public pointcut executionsThrowingChecked() : execution(* *(..) throws (Exception+ && !RuntimeException)); } public aspect SampleExceptionHandling { public pointcut scope() : within(org.atrack.model..*); public pointcut executionsThrowingChecked() : Library.executionsThrowingChecked() && scope(); declare error : executionsThrowingChecked(): "no checked exceptions"; } sample compile: C:\eclipse\workspace\atrack>ajc src\SampleExceptionHandling.java java.lang.Exception: Stack trace at java.lang.Thread.dumpStack(Thread.java:1071) at org.aspectj.weaver.patterns.ReferencePointcut.concretize1 (ReferencePo intcut.java:215) at org.aspectj.weaver.patterns.AndPointcut.concretize1 (AndPointcut.java: 88) at org.aspectj.weaver.patterns.ReferencePointcut.concretize1 (ReferencePo intcut.java:272) at org.aspectj.weaver.patterns.AndPointcut.concretize1 (AndPointcut.java: 88) at org.aspectj.weaver.patterns.ReferencePointcut.concretize1 (ReferencePo intcut.java:272) at org.aspectj.weaver.patterns.Pointcut.concretize(Pointcut.java:127) at org.aspectj.weaver.patterns.Pointcut.concretize(Pointcut.java:120) at org.aspectj.weaver.Checker.concretize(Checker.java:37) at org.aspectj.weaver.CrosscuttingMembers.addShadowMunger (CrosscuttingMe mbers.java:78) at org.aspectj.weaver.CrosscuttingMembers.addDeclare (CrosscuttingMembers .java:102) at org.aspectj.weaver.CrosscuttingMembers.addDeclares (CrosscuttingMember s.java:92) at org.aspectj.weaver.ResolvedTypeX.collectCrosscuttingMembers (ResolvedT ypeX.java:332) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (Crosscut tingMembersSet.java:50) at org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration.buildInterTy peAndPerClause(AspectDeclaration.java:754) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.buildIn terTypeAndPerClause(AjLookupEnvironment.java:124) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.complet eTypeBindings(AjLookupEnvironment.java:91) at org.eclipse.jdt.internal.compiler.Compiler.beginToCompile (Compiler.ja va:310) at org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:324) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilat ion(AjBuildManager.java:373) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuild Manager.java:125) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBu ildManager.java:70) at org.aspectj.ajdt.ajc.AjdtCommand.doCommand(AjdtCommand.java:99) at org.aspectj.ajdt.ajc.AjdtCommand.runCommand(AjdtCommand.java:53) at org.aspectj.tools.ajc.Main.run(Main.java:217) at org.aspectj.tools.ajc.Main.runMain(Main.java:155) at org.aspectj.tools.ajc.Main.main(Main.java:72) C:\eclipse\workspace\atrack\src\SampleExceptionHandling.java:15 circular pointcu t declaration involving: executionsThrowingChecked() 1 error
|
resolved fixed
|
d78d9ed
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2003-09-10T00:35:18Z
| 2003-09-09T04: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.MethodDeclaration;
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 MethodDeclaration {
public static final char[] mangledPrefix = "ajc$pointcut$".toCharArray();
public PointcutDesignator pointcutDesignator;
private int declaredModifiers;
private String declaredName;
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 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());
}
super.resolveStatements();
}
public ResolvedPointcutDefinition makeResolvedPointcutDefinition() {
//System.out.println("pc: " + getPointcut());
ResolvedPointcutDefinition ret = new ResolvedPointcutDefinition(
EclipseFactory.fromBinding(this.binding.declaringClass),
declaredModifiers,
declaredName,
EclipseFactory.fromBindings(this.binding.parameters),
getPointcut());
ret.setPosition(sourceStart, sourceEnd);
ret.setSourceContext(new EclipseSourceContext(compilationResult));
return ret;
}
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 String toString(int tab) {
StringBuffer buf = new StringBuffer();
buf.append(tabString(tab));
if (modifiers != 0) {
buf.append(modifiersString(modifiers));
}
buf.append("pointcut ");
buf.append(new String(selector));
buf.append("(");
if (arguments != null) {
for (int i = 0; i < arguments.length; i++) {
if (i > 0) buf.append(", ");
buf.append(arguments[i].toString(0));
};
};
buf.append("): ");
buf.append(getPointcut());
buf.append(";");
return buf.toString();
}
}
|
42,740
|
Bug 42740 declare error fails on pointcuts composed from multiple classes
|
This error occurs in both 1.1.0 and in the head of CVS as of 9/8/03. The compiler crash output from the CVS head version is at the end. It may be related to 42739, but they may be distinct problems. Sample source: /* * Created on Sep 8, 2003 * * Copyright (c) 2003 New Aspects of Security. All Rights Reserved. */ aspect Library { public pointcut executionsThrowingChecked() : execution(* *(..) throws (Exception+ && !RuntimeException)); } public aspect SampleExceptionHandling { public pointcut scope() : within(org.atrack.model..*); public pointcut executionsThrowingChecked() : Library.executionsThrowingChecked() && scope(); declare error : executionsThrowingChecked(): "no checked exceptions"; } sample compile: C:\eclipse\workspace\atrack>ajc src\SampleExceptionHandling.java java.lang.Exception: Stack trace at java.lang.Thread.dumpStack(Thread.java:1071) at org.aspectj.weaver.patterns.ReferencePointcut.concretize1 (ReferencePo intcut.java:215) at org.aspectj.weaver.patterns.AndPointcut.concretize1 (AndPointcut.java: 88) at org.aspectj.weaver.patterns.ReferencePointcut.concretize1 (ReferencePo intcut.java:272) at org.aspectj.weaver.patterns.AndPointcut.concretize1 (AndPointcut.java: 88) at org.aspectj.weaver.patterns.ReferencePointcut.concretize1 (ReferencePo intcut.java:272) at org.aspectj.weaver.patterns.Pointcut.concretize(Pointcut.java:127) at org.aspectj.weaver.patterns.Pointcut.concretize(Pointcut.java:120) at org.aspectj.weaver.Checker.concretize(Checker.java:37) at org.aspectj.weaver.CrosscuttingMembers.addShadowMunger (CrosscuttingMe mbers.java:78) at org.aspectj.weaver.CrosscuttingMembers.addDeclare (CrosscuttingMembers .java:102) at org.aspectj.weaver.CrosscuttingMembers.addDeclares (CrosscuttingMember s.java:92) at org.aspectj.weaver.ResolvedTypeX.collectCrosscuttingMembers (ResolvedT ypeX.java:332) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (Crosscut tingMembersSet.java:50) at org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration.buildInterTy peAndPerClause(AspectDeclaration.java:754) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.buildIn terTypeAndPerClause(AjLookupEnvironment.java:124) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.complet eTypeBindings(AjLookupEnvironment.java:91) at org.eclipse.jdt.internal.compiler.Compiler.beginToCompile (Compiler.ja va:310) at org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:324) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilat ion(AjBuildManager.java:373) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuild Manager.java:125) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBu ildManager.java:70) at org.aspectj.ajdt.ajc.AjdtCommand.doCommand(AjdtCommand.java:99) at org.aspectj.ajdt.ajc.AjdtCommand.runCommand(AjdtCommand.java:53) at org.aspectj.tools.ajc.Main.run(Main.java:217) at org.aspectj.tools.ajc.Main.runMain(Main.java:155) at org.aspectj.tools.ajc.Main.main(Main.java:72) C:\eclipse\workspace\atrack\src\SampleExceptionHandling.java:15 circular pointcu t declaration involving: executionsThrowingChecked() 1 error
|
resolved fixed
|
d78d9ed
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2003-09-10T00:35:18Z
| 2003-09-09T04: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.*;
import org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration;
import org.aspectj.asm.*;
import org.aspectj.asm.IProgramElement;
import org.aspectj.asm.internal.Relationship;
import org.aspectj.bridge.IMessage;
import org.aspectj.weaver.*;
import org.aspectj.weaver.patterns.*;
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.*;
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);
}
}
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);
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 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);
AsmInterTypeRelationshipProvider.addRelationship(onType, munger);
}
}
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);
}
addParent(sourceType, parent);
}
}
}
private void addParent(SourceTypeBinding sourceType, ResolvedTypeX parent) {
ReferenceBinding parentBinding = (ReferenceBinding)factory.makeTypeBinding(parent);
if (parentBinding.isClass()) {
sourceType.superclass = parentBinding;
} 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;
}
}
private List pendingTypesToFinish = new ArrayList();
boolean inBinaryTypeCreation = false;
public BinaryTypeBinding createBinaryTypeFrom(
IBinaryType binaryType,
PackageBinding packageBinding,
boolean needFieldsAndMethods)
{
if (inBinaryTypeCreation) {
BinaryTypeBinding ret = super.createBinaryTypeFrom(
binaryType,
packageBinding,
needFieldsAndMethods);
pendingTypesToFinish.add(ret);
return ret;
}
inBinaryTypeCreation = true;
try {
BinaryTypeBinding ret = super.createBinaryTypeFrom(
binaryType,
packageBinding,
needFieldsAndMethods);
weaveInterTypeDeclarations(ret);
return ret;
} finally {
inBinaryTypeCreation = false;
if (!pendingTypesToFinish.isEmpty()) {
for (Iterator i = pendingTypesToFinish.iterator(); i.hasNext(); ) {
weaveInterTypeDeclarations((BinaryTypeBinding)i.next());
}
pendingTypesToFinish.clear();
}
}
}
}
|
42,740
|
Bug 42740 declare error fails on pointcuts composed from multiple classes
|
This error occurs in both 1.1.0 and in the head of CVS as of 9/8/03. The compiler crash output from the CVS head version is at the end. It may be related to 42739, but they may be distinct problems. Sample source: /* * Created on Sep 8, 2003 * * Copyright (c) 2003 New Aspects of Security. All Rights Reserved. */ aspect Library { public pointcut executionsThrowingChecked() : execution(* *(..) throws (Exception+ && !RuntimeException)); } public aspect SampleExceptionHandling { public pointcut scope() : within(org.atrack.model..*); public pointcut executionsThrowingChecked() : Library.executionsThrowingChecked() && scope(); declare error : executionsThrowingChecked(): "no checked exceptions"; } sample compile: C:\eclipse\workspace\atrack>ajc src\SampleExceptionHandling.java java.lang.Exception: Stack trace at java.lang.Thread.dumpStack(Thread.java:1071) at org.aspectj.weaver.patterns.ReferencePointcut.concretize1 (ReferencePo intcut.java:215) at org.aspectj.weaver.patterns.AndPointcut.concretize1 (AndPointcut.java: 88) at org.aspectj.weaver.patterns.ReferencePointcut.concretize1 (ReferencePo intcut.java:272) at org.aspectj.weaver.patterns.AndPointcut.concretize1 (AndPointcut.java: 88) at org.aspectj.weaver.patterns.ReferencePointcut.concretize1 (ReferencePo intcut.java:272) at org.aspectj.weaver.patterns.Pointcut.concretize(Pointcut.java:127) at org.aspectj.weaver.patterns.Pointcut.concretize(Pointcut.java:120) at org.aspectj.weaver.Checker.concretize(Checker.java:37) at org.aspectj.weaver.CrosscuttingMembers.addShadowMunger (CrosscuttingMe mbers.java:78) at org.aspectj.weaver.CrosscuttingMembers.addDeclare (CrosscuttingMembers .java:102) at org.aspectj.weaver.CrosscuttingMembers.addDeclares (CrosscuttingMember s.java:92) at org.aspectj.weaver.ResolvedTypeX.collectCrosscuttingMembers (ResolvedT ypeX.java:332) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (Crosscut tingMembersSet.java:50) at org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration.buildInterTy peAndPerClause(AspectDeclaration.java:754) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.buildIn terTypeAndPerClause(AjLookupEnvironment.java:124) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.complet eTypeBindings(AjLookupEnvironment.java:91) at org.eclipse.jdt.internal.compiler.Compiler.beginToCompile (Compiler.ja va:310) at org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:324) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilat ion(AjBuildManager.java:373) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuild Manager.java:125) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBu ildManager.java:70) at org.aspectj.ajdt.ajc.AjdtCommand.doCommand(AjdtCommand.java:99) at org.aspectj.ajdt.ajc.AjdtCommand.runCommand(AjdtCommand.java:53) at org.aspectj.tools.ajc.Main.run(Main.java:217) at org.aspectj.tools.ajc.Main.runMain(Main.java:155) at org.aspectj.tools.ajc.Main.main(Main.java:72) C:\eclipse\workspace\atrack\src\SampleExceptionHandling.java:15 circular pointcu t declaration involving: executionsThrowingChecked() 1 error
|
resolved fixed
|
d78d9ed
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2003-09-10T00:35:18Z
| 2003-09-09T04:00:00Z
|
tests/bugs/declareBinding/SampleExceptionHandling1.java
| |
42,740
|
Bug 42740 declare error fails on pointcuts composed from multiple classes
|
This error occurs in both 1.1.0 and in the head of CVS as of 9/8/03. The compiler crash output from the CVS head version is at the end. It may be related to 42739, but they may be distinct problems. Sample source: /* * Created on Sep 8, 2003 * * Copyright (c) 2003 New Aspects of Security. All Rights Reserved. */ aspect Library { public pointcut executionsThrowingChecked() : execution(* *(..) throws (Exception+ && !RuntimeException)); } public aspect SampleExceptionHandling { public pointcut scope() : within(org.atrack.model..*); public pointcut executionsThrowingChecked() : Library.executionsThrowingChecked() && scope(); declare error : executionsThrowingChecked(): "no checked exceptions"; } sample compile: C:\eclipse\workspace\atrack>ajc src\SampleExceptionHandling.java java.lang.Exception: Stack trace at java.lang.Thread.dumpStack(Thread.java:1071) at org.aspectj.weaver.patterns.ReferencePointcut.concretize1 (ReferencePo intcut.java:215) at org.aspectj.weaver.patterns.AndPointcut.concretize1 (AndPointcut.java: 88) at org.aspectj.weaver.patterns.ReferencePointcut.concretize1 (ReferencePo intcut.java:272) at org.aspectj.weaver.patterns.AndPointcut.concretize1 (AndPointcut.java: 88) at org.aspectj.weaver.patterns.ReferencePointcut.concretize1 (ReferencePo intcut.java:272) at org.aspectj.weaver.patterns.Pointcut.concretize(Pointcut.java:127) at org.aspectj.weaver.patterns.Pointcut.concretize(Pointcut.java:120) at org.aspectj.weaver.Checker.concretize(Checker.java:37) at org.aspectj.weaver.CrosscuttingMembers.addShadowMunger (CrosscuttingMe mbers.java:78) at org.aspectj.weaver.CrosscuttingMembers.addDeclare (CrosscuttingMembers .java:102) at org.aspectj.weaver.CrosscuttingMembers.addDeclares (CrosscuttingMember s.java:92) at org.aspectj.weaver.ResolvedTypeX.collectCrosscuttingMembers (ResolvedT ypeX.java:332) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (Crosscut tingMembersSet.java:50) at org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration.buildInterTy peAndPerClause(AspectDeclaration.java:754) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.buildIn terTypeAndPerClause(AjLookupEnvironment.java:124) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.complet eTypeBindings(AjLookupEnvironment.java:91) at org.eclipse.jdt.internal.compiler.Compiler.beginToCompile (Compiler.ja va:310) at org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:324) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilat ion(AjBuildManager.java:373) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuild Manager.java:125) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBu ildManager.java:70) at org.aspectj.ajdt.ajc.AjdtCommand.doCommand(AjdtCommand.java:99) at org.aspectj.ajdt.ajc.AjdtCommand.runCommand(AjdtCommand.java:53) at org.aspectj.tools.ajc.Main.run(Main.java:217) at org.aspectj.tools.ajc.Main.runMain(Main.java:155) at org.aspectj.tools.ajc.Main.main(Main.java:72) C:\eclipse\workspace\atrack\src\SampleExceptionHandling.java:15 circular pointcu t declaration involving: executionsThrowingChecked() 1 error
|
resolved fixed
|
d78d9ed
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2003-09-10T00:35:18Z
| 2003-09-09T04:00:00Z
|
tests/bugs/declareSoftWithin/test/NoSoftener.java
| |
42,740
|
Bug 42740 declare error fails on pointcuts composed from multiple classes
|
This error occurs in both 1.1.0 and in the head of CVS as of 9/8/03. The compiler crash output from the CVS head version is at the end. It may be related to 42739, but they may be distinct problems. Sample source: /* * Created on Sep 8, 2003 * * Copyright (c) 2003 New Aspects of Security. All Rights Reserved. */ aspect Library { public pointcut executionsThrowingChecked() : execution(* *(..) throws (Exception+ && !RuntimeException)); } public aspect SampleExceptionHandling { public pointcut scope() : within(org.atrack.model..*); public pointcut executionsThrowingChecked() : Library.executionsThrowingChecked() && scope(); declare error : executionsThrowingChecked(): "no checked exceptions"; } sample compile: C:\eclipse\workspace\atrack>ajc src\SampleExceptionHandling.java java.lang.Exception: Stack trace at java.lang.Thread.dumpStack(Thread.java:1071) at org.aspectj.weaver.patterns.ReferencePointcut.concretize1 (ReferencePo intcut.java:215) at org.aspectj.weaver.patterns.AndPointcut.concretize1 (AndPointcut.java: 88) at org.aspectj.weaver.patterns.ReferencePointcut.concretize1 (ReferencePo intcut.java:272) at org.aspectj.weaver.patterns.AndPointcut.concretize1 (AndPointcut.java: 88) at org.aspectj.weaver.patterns.ReferencePointcut.concretize1 (ReferencePo intcut.java:272) at org.aspectj.weaver.patterns.Pointcut.concretize(Pointcut.java:127) at org.aspectj.weaver.patterns.Pointcut.concretize(Pointcut.java:120) at org.aspectj.weaver.Checker.concretize(Checker.java:37) at org.aspectj.weaver.CrosscuttingMembers.addShadowMunger (CrosscuttingMe mbers.java:78) at org.aspectj.weaver.CrosscuttingMembers.addDeclare (CrosscuttingMembers .java:102) at org.aspectj.weaver.CrosscuttingMembers.addDeclares (CrosscuttingMember s.java:92) at org.aspectj.weaver.ResolvedTypeX.collectCrosscuttingMembers (ResolvedT ypeX.java:332) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (Crosscut tingMembersSet.java:50) at org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration.buildInterTy peAndPerClause(AspectDeclaration.java:754) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.buildIn terTypeAndPerClause(AjLookupEnvironment.java:124) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.complet eTypeBindings(AjLookupEnvironment.java:91) at org.eclipse.jdt.internal.compiler.Compiler.beginToCompile (Compiler.ja va:310) at org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:324) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilat ion(AjBuildManager.java:373) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuild Manager.java:125) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBu ildManager.java:70) at org.aspectj.ajdt.ajc.AjdtCommand.doCommand(AjdtCommand.java:99) at org.aspectj.ajdt.ajc.AjdtCommand.runCommand(AjdtCommand.java:53) at org.aspectj.tools.ajc.Main.run(Main.java:217) at org.aspectj.tools.ajc.Main.runMain(Main.java:155) at org.aspectj.tools.ajc.Main.main(Main.java:72) C:\eclipse\workspace\atrack\src\SampleExceptionHandling.java:15 circular pointcu t declaration involving: executionsThrowingChecked() 1 error
|
resolved fixed
|
d78d9ed
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2003-09-10T00:35:18Z
| 2003-09-09T04:00:00Z
|
weaver/src/org/aspectj/weaver/ResolvedPointcutDefinition.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 org.aspectj.weaver.patterns.Pointcut;
public class ResolvedPointcutDefinition extends ResolvedMember {
private Pointcut pointcut;
public ResolvedPointcutDefinition(
TypeX declaringType,
int modifiers,
String name,
TypeX[] parameterTypes,
Pointcut pointcut)
{
super(
POINTCUT,
declaringType,
modifiers,
ResolvedTypeX.VOID,
name,
parameterTypes);
this.pointcut = pointcut;
//XXXpointcut.assertState(Pointcut.RESOLVED);
checkedExceptions = TypeX.NONE;
}
// ----
public void write(DataOutputStream s) throws IOException {
getDeclaringType().write(s);
s.writeInt(getModifiers());
s.writeUTF(getName());
TypeX.writeArray(getParameterTypes(), s);
pointcut.write(s);
}
public static ResolvedPointcutDefinition read(DataInputStream s, ISourceContext context) throws IOException {
return new ResolvedPointcutDefinition(
TypeX.read(s),
s.readInt(),
s.readUTF(),
TypeX.readArray(s),
Pointcut.read(s, context));
}
public String toString() {
StringBuffer buf = new StringBuffer();
buf.append("pointcut ");
buf.append(getDeclaringType().getName());
buf.append(".");
buf.append(getName());
buf.append("(");
for (int i=0; i < getParameterTypes().length; i++) {
if (i > 0) buf.append(", ");
buf.append(getParameterTypes()[i].toString());
}
buf.append(")");
//buf.append(pointcut);
return buf.toString();
}
public Pointcut getPointcut() {
return pointcut;
}
public boolean isAjSynthetic() {
return true;
}
// for testing
public static final ResolvedPointcutDefinition DUMMY =
new ResolvedPointcutDefinition(TypeX.OBJECT, 0, "missing",
TypeX.NONE, Pointcut.makeMatchesNothing(Pointcut.RESOLVED));
}
|
42,993
|
Bug 42993 Language regression, or possible language improvement?
|
The file AspectBug.java: public aspect AspectBug extends AbstractCaching perthis(execution(ContainerLoader+.new(..))) { declare parents: ContainerDescriptor implements AbstractCaching.Key; protected pointcut loadExecutions( Key key ): ContainerLoader.containerLoads( *, key ); } abstract aspect AbstractCaching { interface Key {} protected abstract pointcut loadExecutions(Key key); } class Key { } class ContainerDescriptor { } class ActiveContainer { } class ContainerLoader { public ActiveContainer createContainer(ContainerDescriptor c) { return null; } public pointcut containerLoads(ContainerLoader loader, ContainerDescriptor containerDesc ): this(loader) && args(containerDesc) && execution(ActiveContainer ContainerLoader.createContainer (ContainerDescriptor)); } First, here are the versions of AspectJ I'm using (this is a bash shell under cygwin on Windows XP): ~> CLASSPATH='C:\aspectj1.0\lib\aspectjrt.jar' /cygdrive/c/aspectj1.0/bin/ajc - version ajc version 1.0.6 (built Jul 24, 2002 6:21 PM PST) running on java 1.4.1_02 ~> CLASSPATH='C:\aspectj1.1\lib\aspectjrt.jar' /cygdrive/c/aspectj1.1/bin/ajc - version AspectJ Compiler 1.1.0 ~> CLASSPATH='C:\aspectj1.1.1rc1 \lib\aspectjrt.jar' /cygdrive/c/aspectj1.1.1rc1/bin/ajc -version AspectJ Compiler 1.1.1rc1 ~> CLASSPATH='C:\aspectj1.1.1 \lib\aspectjrt.jar' /cygdrive/c/aspectj1.1.1/bin/ajc -version AspectJ Compiler 1.1.1 For all four of these compilers, I give them the AspectBug.java file (which is attached): ~> CLASSPATH='C:\aspectj1.0\lib\aspectjrt.jar' /cygdrive/c/aspectj1.0/bin/ajc AspectBug.java ~> CLASSPATH='C:\aspectj1.1\lib\aspectjrt.jar' /cygdrive/c/aspectj1.1/bin/ajc AspectBug.java ~> CLASSPATH='C:\aspectj1.1.1rc1 \lib\aspectjrt.jar' /cygdrive/c/aspectj1.1.1rc1/bin/ajc AspectBug.java ~> CLASSPATH='C:\aspectj1.1.1 \lib\aspectjrt.jar' /cygdrive/c/aspectj1.1.1/bin/ajc AspectBug.java C:\Documents and Settings\Macneil Shonle\AspectBug.java:7 incompatible type, expected ContainerDescriptor found BindingTypePattern(AbstractCaching$Key, 0) 1 error As you can see, only the final run (with the Sept 11 build of ajc) do we see the "incompatible type" error. If this is not a regression but a desirable result, how should the code be ported?
|
resolved fixed
|
b512738
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2003-09-12T16:49:58Z
| 2003-09-12T09:46:40Z
|
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.*;
import org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration;
import org.aspectj.ajdt.internal.compiler.ast.DeclareDeclaration;
import org.aspectj.ajdt.internal.compiler.ast.PointcutDeclaration;
import org.aspectj.asm.*;
import org.aspectj.asm.IProgramElement;
import org.aspectj.asm.internal.Relationship;
import org.aspectj.bridge.IMessage;
import org.aspectj.weaver.*;
import org.aspectj.weaver.patterns.*;
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.*;
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);
}
}
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++) {
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);
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 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;
AbstractMethodDeclaration[] methods = dec.methods;
boolean initializedMethods = false;
if (methods != null) {
for (int i=0; i < methods.length; i++) {
if (methods[i] instanceof PointcutDeclaration) {
if (!initializedMethods) {
sourceType.methods(); //force initialization
initializedMethods = true;
}
((PointcutDeclaration)methods[i]).resolvePointcut(s);
}
}
}
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);
AsmInterTypeRelationshipProvider.addRelationship(onType, munger);
}
}
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);
}
addParent(sourceType, parent);
}
}
}
private void addParent(SourceTypeBinding sourceType, ResolvedTypeX parent) {
ReferenceBinding parentBinding = (ReferenceBinding)factory.makeTypeBinding(parent);
if (parentBinding.isClass()) {
sourceType.superclass = parentBinding;
} 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;
}
}
private List pendingTypesToFinish = new ArrayList();
boolean inBinaryTypeCreation = false;
public BinaryTypeBinding createBinaryTypeFrom(
IBinaryType binaryType,
PackageBinding packageBinding,
boolean needFieldsAndMethods)
{
if (inBinaryTypeCreation) {
BinaryTypeBinding ret = super.createBinaryTypeFrom(
binaryType,
packageBinding,
needFieldsAndMethods);
pendingTypesToFinish.add(ret);
return ret;
}
inBinaryTypeCreation = true;
try {
BinaryTypeBinding ret = super.createBinaryTypeFrom(
binaryType,
packageBinding,
needFieldsAndMethods);
weaveInterTypeDeclarations(ret);
return ret;
} finally {
inBinaryTypeCreation = false;
if (!pendingTypesToFinish.isEmpty()) {
for (Iterator i = pendingTypesToFinish.iterator(); i.hasNext(); ) {
weaveInterTypeDeclarations((BinaryTypeBinding)i.next());
}
pendingTypesToFinish.clear();
}
}
}
}
|
42,993
|
Bug 42993 Language regression, or possible language improvement?
|
The file AspectBug.java: public aspect AspectBug extends AbstractCaching perthis(execution(ContainerLoader+.new(..))) { declare parents: ContainerDescriptor implements AbstractCaching.Key; protected pointcut loadExecutions( Key key ): ContainerLoader.containerLoads( *, key ); } abstract aspect AbstractCaching { interface Key {} protected abstract pointcut loadExecutions(Key key); } class Key { } class ContainerDescriptor { } class ActiveContainer { } class ContainerLoader { public ActiveContainer createContainer(ContainerDescriptor c) { return null; } public pointcut containerLoads(ContainerLoader loader, ContainerDescriptor containerDesc ): this(loader) && args(containerDesc) && execution(ActiveContainer ContainerLoader.createContainer (ContainerDescriptor)); } First, here are the versions of AspectJ I'm using (this is a bash shell under cygwin on Windows XP): ~> CLASSPATH='C:\aspectj1.0\lib\aspectjrt.jar' /cygdrive/c/aspectj1.0/bin/ajc - version ajc version 1.0.6 (built Jul 24, 2002 6:21 PM PST) running on java 1.4.1_02 ~> CLASSPATH='C:\aspectj1.1\lib\aspectjrt.jar' /cygdrive/c/aspectj1.1/bin/ajc - version AspectJ Compiler 1.1.0 ~> CLASSPATH='C:\aspectj1.1.1rc1 \lib\aspectjrt.jar' /cygdrive/c/aspectj1.1.1rc1/bin/ajc -version AspectJ Compiler 1.1.1rc1 ~> CLASSPATH='C:\aspectj1.1.1 \lib\aspectjrt.jar' /cygdrive/c/aspectj1.1.1/bin/ajc -version AspectJ Compiler 1.1.1 For all four of these compilers, I give them the AspectBug.java file (which is attached): ~> CLASSPATH='C:\aspectj1.0\lib\aspectjrt.jar' /cygdrive/c/aspectj1.0/bin/ajc AspectBug.java ~> CLASSPATH='C:\aspectj1.1\lib\aspectjrt.jar' /cygdrive/c/aspectj1.1/bin/ajc AspectBug.java ~> CLASSPATH='C:\aspectj1.1.1rc1 \lib\aspectjrt.jar' /cygdrive/c/aspectj1.1.1rc1/bin/ajc AspectBug.java ~> CLASSPATH='C:\aspectj1.1.1 \lib\aspectjrt.jar' /cygdrive/c/aspectj1.1.1/bin/ajc AspectBug.java C:\Documents and Settings\Macneil Shonle\AspectBug.java:7 incompatible type, expected ContainerDescriptor found BindingTypePattern(AbstractCaching$Key, 0) 1 error As you can see, only the final run (with the Sept 11 build of ajc) do we see the "incompatible type" error. If this is not a regression but a desirable result, how should the code be ported?
|
resolved fixed
|
b512738
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2003-09-12T16:49:58Z
| 2003-09-12T09:46:40Z
|
tests/bugs/ParentsAndPointcuts.java
| |
42,993
|
Bug 42993 Language regression, or possible language improvement?
|
The file AspectBug.java: public aspect AspectBug extends AbstractCaching perthis(execution(ContainerLoader+.new(..))) { declare parents: ContainerDescriptor implements AbstractCaching.Key; protected pointcut loadExecutions( Key key ): ContainerLoader.containerLoads( *, key ); } abstract aspect AbstractCaching { interface Key {} protected abstract pointcut loadExecutions(Key key); } class Key { } class ContainerDescriptor { } class ActiveContainer { } class ContainerLoader { public ActiveContainer createContainer(ContainerDescriptor c) { return null; } public pointcut containerLoads(ContainerLoader loader, ContainerDescriptor containerDesc ): this(loader) && args(containerDesc) && execution(ActiveContainer ContainerLoader.createContainer (ContainerDescriptor)); } First, here are the versions of AspectJ I'm using (this is a bash shell under cygwin on Windows XP): ~> CLASSPATH='C:\aspectj1.0\lib\aspectjrt.jar' /cygdrive/c/aspectj1.0/bin/ajc - version ajc version 1.0.6 (built Jul 24, 2002 6:21 PM PST) running on java 1.4.1_02 ~> CLASSPATH='C:\aspectj1.1\lib\aspectjrt.jar' /cygdrive/c/aspectj1.1/bin/ajc - version AspectJ Compiler 1.1.0 ~> CLASSPATH='C:\aspectj1.1.1rc1 \lib\aspectjrt.jar' /cygdrive/c/aspectj1.1.1rc1/bin/ajc -version AspectJ Compiler 1.1.1rc1 ~> CLASSPATH='C:\aspectj1.1.1 \lib\aspectjrt.jar' /cygdrive/c/aspectj1.1.1/bin/ajc -version AspectJ Compiler 1.1.1 For all four of these compilers, I give them the AspectBug.java file (which is attached): ~> CLASSPATH='C:\aspectj1.0\lib\aspectjrt.jar' /cygdrive/c/aspectj1.0/bin/ajc AspectBug.java ~> CLASSPATH='C:\aspectj1.1\lib\aspectjrt.jar' /cygdrive/c/aspectj1.1/bin/ajc AspectBug.java ~> CLASSPATH='C:\aspectj1.1.1rc1 \lib\aspectjrt.jar' /cygdrive/c/aspectj1.1.1rc1/bin/ajc AspectBug.java ~> CLASSPATH='C:\aspectj1.1.1 \lib\aspectjrt.jar' /cygdrive/c/aspectj1.1.1/bin/ajc AspectBug.java C:\Documents and Settings\Macneil Shonle\AspectBug.java:7 incompatible type, expected ContainerDescriptor found BindingTypePattern(AbstractCaching$Key, 0) 1 error As you can see, only the final run (with the Sept 11 build of ajc) do we see the "incompatible type" error. If this is not a regression but a desirable result, how should the code be ported?
|
resolved fixed
|
b512738
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2003-09-12T16:49:58Z
| 2003-09-12T09:46:40Z
|
weaver/src/org/aspectj/weaver/CrosscuttingMembersSet.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.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* This holds on to all CrosscuttingMembers for a world. It handles
* management of change.
*
* @author Jim Hugunin
*/
public class CrosscuttingMembersSet {
private World world;
private Map members = new HashMap();
private List shadowMungers = null;
private List typeMungers = null;
private List declareSofts = null;
private List declareParents = null;
private List declareDominates = null;
public CrosscuttingMembersSet(World world) {
this.world = world;
}
/**
* @return whether or not that was a change to the global signature
* XXX for efficiency we will need a richer representation than this
*/
public boolean addOrReplaceAspect(ResolvedTypeX aspectType) {
CrosscuttingMembers xcut = (CrosscuttingMembers)members.get(aspectType);
if (xcut == null) {
members.put(aspectType, aspectType.collectCrosscuttingMembers());
clearCaches();
return true;
} else {
if (xcut.replaceWith(aspectType.collectCrosscuttingMembers())) {
clearCaches();
return true;
} else {
return false;
}
}
}
public boolean deleteAspect(TypeX aspectType) {
boolean isAspect = members.remove(aspectType) != null;
clearCaches();
return isAspect;
}
public boolean containsAspect(TypeX aspectType) {
return members.containsKey(aspectType);
}
//XXX only for testing
public void addFixedCrosscuttingMembers(ResolvedTypeX aspectType) {
members.put(aspectType, aspectType.crosscuttingMembers);
clearCaches();
}
private void clearCaches() {
shadowMungers = null;
typeMungers = null;
declareSofts = null;
declareParents = null;
declareDominates = null;
}
public List getShadowMungers() {
if (shadowMungers == null) {
ArrayList ret = new ArrayList();
for (Iterator i = members.values().iterator(); i.hasNext(); ) {
ret.addAll(((CrosscuttingMembers)i.next()).getShadowMungers());
}
shadowMungers = ret;
}
return shadowMungers;
}
public List getTypeMungers() {
if (typeMungers == null) {
ArrayList ret = new ArrayList();
for (Iterator i = members.values().iterator(); i.hasNext(); ) {
ret.addAll(((CrosscuttingMembers)i.next()).getTypeMungers());
}
typeMungers = ret;
}
return typeMungers;
}
public List getDeclareSofts() {
if (declareSofts == null) {
ArrayList ret = new ArrayList();
for (Iterator i = members.values().iterator(); i.hasNext(); ) {
ret.addAll(((CrosscuttingMembers)i.next()).getDeclareSofts());
}
declareSofts = ret;
}
return declareSofts;
}
public List getDeclareParents() {
if (declareParents == null) {
ArrayList ret = new ArrayList();
for (Iterator i = members.values().iterator(); i.hasNext(); ) {
ret.addAll(((CrosscuttingMembers)i.next()).getDeclareParents());
}
declareParents = ret;
}
return declareParents;
}
public List getDeclareDominates() {
if (declareDominates == null) {
ArrayList ret = new ArrayList();
for (Iterator i = members.values().iterator(); i.hasNext(); ) {
ret.addAll(((CrosscuttingMembers)i.next()).getDeclareDominates());
}
declareDominates = ret;
}
return declareDominates;
}
}
|
42,993
|
Bug 42993 Language regression, or possible language improvement?
|
The file AspectBug.java: public aspect AspectBug extends AbstractCaching perthis(execution(ContainerLoader+.new(..))) { declare parents: ContainerDescriptor implements AbstractCaching.Key; protected pointcut loadExecutions( Key key ): ContainerLoader.containerLoads( *, key ); } abstract aspect AbstractCaching { interface Key {} protected abstract pointcut loadExecutions(Key key); } class Key { } class ContainerDescriptor { } class ActiveContainer { } class ContainerLoader { public ActiveContainer createContainer(ContainerDescriptor c) { return null; } public pointcut containerLoads(ContainerLoader loader, ContainerDescriptor containerDesc ): this(loader) && args(containerDesc) && execution(ActiveContainer ContainerLoader.createContainer (ContainerDescriptor)); } First, here are the versions of AspectJ I'm using (this is a bash shell under cygwin on Windows XP): ~> CLASSPATH='C:\aspectj1.0\lib\aspectjrt.jar' /cygdrive/c/aspectj1.0/bin/ajc - version ajc version 1.0.6 (built Jul 24, 2002 6:21 PM PST) running on java 1.4.1_02 ~> CLASSPATH='C:\aspectj1.1\lib\aspectjrt.jar' /cygdrive/c/aspectj1.1/bin/ajc - version AspectJ Compiler 1.1.0 ~> CLASSPATH='C:\aspectj1.1.1rc1 \lib\aspectjrt.jar' /cygdrive/c/aspectj1.1.1rc1/bin/ajc -version AspectJ Compiler 1.1.1rc1 ~> CLASSPATH='C:\aspectj1.1.1 \lib\aspectjrt.jar' /cygdrive/c/aspectj1.1.1/bin/ajc -version AspectJ Compiler 1.1.1 For all four of these compilers, I give them the AspectBug.java file (which is attached): ~> CLASSPATH='C:\aspectj1.0\lib\aspectjrt.jar' /cygdrive/c/aspectj1.0/bin/ajc AspectBug.java ~> CLASSPATH='C:\aspectj1.1\lib\aspectjrt.jar' /cygdrive/c/aspectj1.1/bin/ajc AspectBug.java ~> CLASSPATH='C:\aspectj1.1.1rc1 \lib\aspectjrt.jar' /cygdrive/c/aspectj1.1.1rc1/bin/ajc AspectBug.java ~> CLASSPATH='C:\aspectj1.1.1 \lib\aspectjrt.jar' /cygdrive/c/aspectj1.1.1/bin/ajc AspectBug.java C:\Documents and Settings\Macneil Shonle\AspectBug.java:7 incompatible type, expected ContainerDescriptor found BindingTypePattern(AbstractCaching$Key, 0) 1 error As you can see, only the final run (with the Sept 11 build of ajc) do we see the "incompatible type" error. If this is not a regression but a desirable result, how should the code be ported?
|
resolved fixed
|
b512738
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2003-09-12T16:49:58Z
| 2003-09-12T09:46:40Z
|
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.MessageUtil;
import org.aspectj.weaver.bcel.BcelObjectType;
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());
crosscuttingMembers.addPrivilegedAccesses(getPrivilegedAccesses());
//System.err.println("collected cc members: " + this + ", " + collectDeclares());
return crosscuttingMembers;
}
private final Collection collectDeclares() {
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 (!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.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;
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.resolve(CLONEABLE),
world.resolve(SERIALIZABLE)
};
}
public final ResolvedMember[] getDeclaredPointcuts() {
return ResolvedMember.NONE;
}
public final ResolvedTypeX getSuperclass() {
return world.resolve(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;
}
/**
* 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.resolve(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();
if (conflictingSignature(existingMember, munger.getSignature())) {
//System.err.println("conflict: " + existingMember + " with " + 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("inter-type declaration from " + munger.getAspectType().getName() +
" conflicts with existing member: " + existingMember,
munger.getSourceLocation())
);
}
} else {
//interTypeMungers.add(munger);
}
//return;
}
}
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,
"can't override " + parent +
" with " + child + " return types don't match",
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,
"can't override " + parent +
" with " + child + " parameter types don't match",
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,
"can't override " + parent +
" with " + child + " visibility is reduced",
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, "overriden method doesn't throw "
+ childExceptions[i].getName(), child.getSourceLocation(), null);
return false;
}
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,
"intertype declaration from "
+ m1.getAspectType().getName()
+ " conflicts with intertype declaration: "
+ m2.getSignature()
+ " from "
+ 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 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,
"inherited abstract " + inherited +
" is not made concrete in " + 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,
"conflicting inherited pointcuts in "
+ 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;
}
}
|
43,194
|
Bug 43194 java.lang.VerifyError in generated code
|
See the attached file VerifyBug.jar for the source files. You won't need anything else to compiler and reproduce this bug: ~/bug> ls AbstractCaching.java TreeNode.java VerifyBug.jar ContainerCaching.java TreeNodeFolding.java WorkspaceGroup.java ContainerLoader.java TreePanel.java WorkspaceNode.java Makefile TreeWorkspace.java ~/bug> gmake /cygdrive/c/aspectj1.1.1/bin/ajc -classpath "C:\aspectj1.1.1 \lib\aspectjrt.jar" -version AspectJ Compiler 1.1.1 /cygdrive/c/aspectj1.1.1/bin/ajc -classpath "C:\aspectj1.1.1\lib\aspectjrt.jar" *.java java -classpath "C:\aspectj1.1.1\lib\aspectjrt.jar;." TreeNode java.lang.VerifyError: (class: TreeNode, method: doShowAction signature: ()V) Unable to pop operand off an empty stack Exception in thread "main" make: *** [all] Error 1
|
resolved fixed
|
fc0d2af
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2003-09-18T18:38:14Z
| 2003-09-17T03:40:00Z
|
tests/bugs/AdviceInteraction.java
| |
43,194
|
Bug 43194 java.lang.VerifyError in generated code
|
See the attached file VerifyBug.jar for the source files. You won't need anything else to compiler and reproduce this bug: ~/bug> ls AbstractCaching.java TreeNode.java VerifyBug.jar ContainerCaching.java TreeNodeFolding.java WorkspaceGroup.java ContainerLoader.java TreePanel.java WorkspaceNode.java Makefile TreeWorkspace.java ~/bug> gmake /cygdrive/c/aspectj1.1.1/bin/ajc -classpath "C:\aspectj1.1.1 \lib\aspectjrt.jar" -version AspectJ Compiler 1.1.1 /cygdrive/c/aspectj1.1.1/bin/ajc -classpath "C:\aspectj1.1.1\lib\aspectjrt.jar" *.java java -classpath "C:\aspectj1.1.1\lib\aspectjrt.jar;." TreeNode java.lang.VerifyError: (class: TreeNode, method: doShowAction signature: ()V) Unable to pop operand off an empty stack Exception in thread "main" make: *** [all] Error 1
|
resolved fixed
|
fc0d2af
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2003-09-18T18:38:14Z
| 2003-09-17T03:40:00Z
|
weaver/src/org/aspectj/weaver/patterns/ReferencePointcut.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.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.lang.reflect.Modifier;
import org.apache.bcel.classfile.JavaClass;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.util.FuzzyBoolean;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.ISourceContext;
import org.aspectj.weaver.IntMap;
import org.aspectj.weaver.ResolvedPointcutDefinition;
import org.aspectj.weaver.ResolvedTypeX;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.TypeX;
import org.aspectj.weaver.ast.Test;
/**
*/
//XXX needs check that arguments contains no WildTypePatterns
public class ReferencePointcut extends Pointcut {
public TypeX onType;
public TypePattern onTypeSymbolic;
public String name;
public TypePatternList arguments;
//public ResolvedPointcut binding;
public ReferencePointcut(TypePattern onTypeSymbolic, String name, TypePatternList arguments) {
this.onTypeSymbolic = onTypeSymbolic;
this.name = name;
this.arguments = arguments;
}
public ReferencePointcut(TypeX onType, String name, TypePatternList arguments) {
this.onType = onType;
this.name = name;
this.arguments = arguments;
}
//??? do either of these match methods make any sense???
public FuzzyBoolean fastMatch(ResolvedTypeX type) {
return FuzzyBoolean.MAYBE;
}
/**
* Do I really match this shadow?
*/
public FuzzyBoolean match(Shadow shadow) {
return FuzzyBoolean.NO;
}
public String toString() {
StringBuffer buf = new StringBuffer();
if (onType != null) {
buf.append(onType);
buf.append(".");
// for (int i=0, len=fromType.length; i < len; i++) {
// buf.append(fromType[i]);
// buf.append(".");
// }
}
buf.append(name);
buf.append(arguments.toString());
return buf.toString();
}
public void write(DataOutputStream s) throws IOException {
//XXX ignores onType
s.writeByte(Pointcut.REFERENCE);
if (onType != null) {
s.writeBoolean(true);
onType.write(s);
} else {
s.writeBoolean(false);
}
s.writeUTF(name);
arguments.write(s);
writeLocation(s);
}
public static Pointcut read(DataInputStream s, ISourceContext context) throws IOException {
TypeX onType = null;
if (s.readBoolean()) {
onType = TypeX.read(s);
}
ReferencePointcut ret = new ReferencePointcut(onType, s.readUTF(),
TypePatternList.read(s, context));
ret.readLocation(context, s);
return ret;
}
public void resolveBindings(IScope scope, Bindings bindings) {
if (onTypeSymbolic != null) {
onType = onTypeSymbolic.resolveExactType(scope, bindings);
// in this case we've already signalled an error
if (onType == ResolvedTypeX.MISSING) return;
}
ResolvedTypeX searchType;
if (onType != null) {
searchType = scope.getWorld().resolve(onType);
} else {
searchType = scope.getEnclosingType();
}
arguments.resolveBindings(scope, bindings, true, true);
//XXX ensure that arguments has no ..'s in it
// check that I refer to a real pointcut declaration and that I match
ResolvedPointcutDefinition pointcutDef = searchType.findPointcut(name);
// if we're not a static reference, then do a lookup of outers
if (pointcutDef == null && onType == null) {
while (true) {
TypeX declaringType = searchType.getDeclaringType();
if (declaringType == null) break;
searchType = declaringType.resolve(scope.getWorld());
pointcutDef = searchType.findPointcut(name);
if (pointcutDef != null) {
// make this a static reference
onType = searchType;
break;
}
}
}
if (pointcutDef == null) {
scope.message(IMessage.ERROR, this, "can't find referenced pointcut");
return;
}
// check visibility
if (!pointcutDef.isVisible(scope.getEnclosingType())) {
scope.message(IMessage.ERROR, this, "pointcut declaration " + pointcutDef + " is not accessible");
return;
}
if (Modifier.isAbstract(pointcutDef.getModifiers())) {
if (onType != null) {
scope.message(IMessage.ERROR, this,
"can't make static reference to abstract pointcut");
return;
} else if (!searchType.isAbstract()) {
scope.message(IMessage.ERROR, this,
"can't use abstract pointcut in concrete context");
return;
}
}
ResolvedTypeX[] parameterTypes =
scope.getWorld().resolve(pointcutDef.getParameterTypes());
if (parameterTypes.length != arguments.size()) {
scope.message(IMessage.ERROR, this, "incompatible number of arguments to pointcut, expected " +
parameterTypes.length + " found " + arguments.size());
return;
}
for (int i=0,len=arguments.size(); i < len; i++) {
TypePattern p = arguments.get(i);
//we are allowed to bind to pointcuts which use subtypes as this is type safe
if (p == TypePattern.NO) {
scope.message(IMessage.ERROR, this,
"bad parameter to pointcut reference");
return;
}
if (!p.matchesSubtypes(parameterTypes[i]) &&
!p.getExactType().equals(TypeX.OBJECT))
{
scope.message(IMessage.ERROR, p, "incompatible type, expected " +
parameterTypes[i].getName() + " found " + p);
return;
}
}
}
public void postRead(ResolvedTypeX enclosingType) {
arguments.postRead(enclosingType);
}
public Test findResidue(Shadow shadow, ExposedState state) {
throw new RuntimeException("shouldn't happen");
}
//??? This is not thread safe, but this class is not designed for multi-threading
private boolean concretizing = false;
public Pointcut concretize1(ResolvedTypeX searchStart, IntMap bindings) {
if (concretizing) {
//Thread.currentThread().dumpStack();
searchStart.getWorld().getMessageHandler().handleMessage(
MessageUtil.error("circular pointcut declaration involving: " + this,
getSourceLocation()));
return Pointcut.makeMatchesNothing(Pointcut.CONCRETE);
}
try {
concretizing = true;
ResolvedPointcutDefinition pointcutDec;
if (onType != null) {
searchStart = onType.resolve(searchStart.getWorld());
if (searchStart == ResolvedTypeX.MISSING) {
return Pointcut.makeMatchesNothing(Pointcut.CONCRETE);
}
}
pointcutDec = searchStart.findPointcut(name);
if (pointcutDec == null) {
searchStart.getWorld().getMessageHandler().handleMessage(
MessageUtil.error("can't find pointcut \'" + name + "\' on " + searchStart.getName(),
getSourceLocation())
);
return Pointcut.makeMatchesNothing(Pointcut.CONCRETE);
}
if (pointcutDec.isAbstract()) {
//Thread.currentThread().dumpStack();
searchStart.getWorld().showMessage(IMessage.ERROR,
pointcutDec + " is abstract",
getSourceLocation(), bindings.getEnclosingAdvice().getSourceLocation());
return Pointcut.makeMatchesNothing(Pointcut.CONCRETE);
}
//System.err.println("start: " + searchStart);
ResolvedTypeX[] parameterTypes = searchStart.getWorld().resolve(pointcutDec.getParameterTypes());
arguments = arguments.resolveReferences(bindings);
IntMap newBindings = new IntMap();
for (int i=0,len=arguments.size(); i < len; i++) {
TypePattern p = arguments.get(i);
//we are allowed to bind to pointcuts which use subtypes as this is type safe
if (!p.matchesSubtypes(parameterTypes[i]) &&
!p.getExactType().equals(TypeX.OBJECT))
{
throw new BCException("illegal change to pointcut declaration: " + this);
}
if (p instanceof BindingTypePattern) {
newBindings.put(i, ((BindingTypePattern)p).getFormalIndex());
}
}
newBindings.copyContext(bindings);
newBindings.pushEnclosingDefinition(pointcutDec);
try {
return pointcutDec.getPointcut().concretize1(searchStart, newBindings);
} finally {
newBindings.popEnclosingDefinitition();
}
} finally {
concretizing = false;
}
}
public boolean equals(Object other) {
if (!(other instanceof ReferencePointcut)) return false;
ReferencePointcut o = (ReferencePointcut)other;
return o.name.equals(name) && o.arguments.equals(arguments)
&& ((o.onType == null) ? (onType == null) : o.onType.equals(onType));
}
public int hashCode() {
int result = 17;
result = 37*result + ((onType == null) ? 0 : onType.hashCode());
result = 37*result + arguments.hashCode();
result = 37*result + name.hashCode();
return result;
}
}
|
43,033
|
Bug 43033 Compiler crash in ajc head (post 1.1.1 rc1) on erroneous program
| null |
resolved fixed
|
5357086
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2003-09-19T08:16:17Z
| 2003-09-12T18:06:40Z
|
tests/bugs/concretizeNpe/base/ExceptionHandling.java
| |
43,033
|
Bug 43033 Compiler crash in ajc head (post 1.1.1 rc1) on erroneous program
| null |
resolved fixed
|
5357086
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2003-09-19T08:16:17Z
| 2003-09-12T18:06:40Z
|
tests/bugs/concretizeNpe/model/ModelExceptionHandling.java
| |
43,033
|
Bug 43033 Compiler crash in ajc head (post 1.1.1 rc1) on erroneous program
| null |
resolved fixed
|
5357086
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2003-09-19T08:16:17Z
| 2003-09-12T18:06:40Z
|
weaver/src/org/aspectj/weaver/patterns/ReferencePointcut.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.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.lang.reflect.Modifier;
import org.apache.bcel.classfile.JavaClass;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.util.FuzzyBoolean;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.ISourceContext;
import org.aspectj.weaver.IntMap;
import org.aspectj.weaver.ResolvedPointcutDefinition;
import org.aspectj.weaver.ResolvedTypeX;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.TypeX;
import org.aspectj.weaver.ast.Test;
/**
*/
//XXX needs check that arguments contains no WildTypePatterns
public class ReferencePointcut extends Pointcut {
public TypeX onType;
public TypePattern onTypeSymbolic;
public String name;
public TypePatternList arguments;
//public ResolvedPointcut binding;
public ReferencePointcut(TypePattern onTypeSymbolic, String name, TypePatternList arguments) {
this.onTypeSymbolic = onTypeSymbolic;
this.name = name;
this.arguments = arguments;
}
public ReferencePointcut(TypeX onType, String name, TypePatternList arguments) {
this.onType = onType;
this.name = name;
this.arguments = arguments;
}
//??? do either of these match methods make any sense???
public FuzzyBoolean fastMatch(ResolvedTypeX type) {
return FuzzyBoolean.MAYBE;
}
/**
* Do I really match this shadow?
*/
public FuzzyBoolean match(Shadow shadow) {
return FuzzyBoolean.NO;
}
public String toString() {
StringBuffer buf = new StringBuffer();
if (onType != null) {
buf.append(onType);
buf.append(".");
// for (int i=0, len=fromType.length; i < len; i++) {
// buf.append(fromType[i]);
// buf.append(".");
// }
}
buf.append(name);
buf.append(arguments.toString());
return buf.toString();
}
public void write(DataOutputStream s) throws IOException {
//XXX ignores onType
s.writeByte(Pointcut.REFERENCE);
if (onType != null) {
s.writeBoolean(true);
onType.write(s);
} else {
s.writeBoolean(false);
}
s.writeUTF(name);
arguments.write(s);
writeLocation(s);
}
public static Pointcut read(DataInputStream s, ISourceContext context) throws IOException {
TypeX onType = null;
if (s.readBoolean()) {
onType = TypeX.read(s);
}
ReferencePointcut ret = new ReferencePointcut(onType, s.readUTF(),
TypePatternList.read(s, context));
ret.readLocation(context, s);
return ret;
}
public void resolveBindings(IScope scope, Bindings bindings) {
if (onTypeSymbolic != null) {
onType = onTypeSymbolic.resolveExactType(scope, bindings);
// in this case we've already signalled an error
if (onType == ResolvedTypeX.MISSING) return;
}
ResolvedTypeX searchType;
if (onType != null) {
searchType = scope.getWorld().resolve(onType);
} else {
searchType = scope.getEnclosingType();
}
arguments.resolveBindings(scope, bindings, true, true);
//XXX ensure that arguments has no ..'s in it
// check that I refer to a real pointcut declaration and that I match
ResolvedPointcutDefinition pointcutDef = searchType.findPointcut(name);
// if we're not a static reference, then do a lookup of outers
if (pointcutDef == null && onType == null) {
while (true) {
TypeX declaringType = searchType.getDeclaringType();
if (declaringType == null) break;
searchType = declaringType.resolve(scope.getWorld());
pointcutDef = searchType.findPointcut(name);
if (pointcutDef != null) {
// make this a static reference
onType = searchType;
break;
}
}
}
if (pointcutDef == null) {
scope.message(IMessage.ERROR, this, "can't find referenced pointcut");
return;
}
// check visibility
if (!pointcutDef.isVisible(scope.getEnclosingType())) {
scope.message(IMessage.ERROR, this, "pointcut declaration " + pointcutDef + " is not accessible");
return;
}
if (Modifier.isAbstract(pointcutDef.getModifiers())) {
if (onType != null) {
scope.message(IMessage.ERROR, this,
"can't make static reference to abstract pointcut");
return;
} else if (!searchType.isAbstract()) {
scope.message(IMessage.ERROR, this,
"can't use abstract pointcut in concrete context");
return;
}
}
ResolvedTypeX[] parameterTypes =
scope.getWorld().resolve(pointcutDef.getParameterTypes());
if (parameterTypes.length != arguments.size()) {
scope.message(IMessage.ERROR, this, "incompatible number of arguments to pointcut, expected " +
parameterTypes.length + " found " + arguments.size());
return;
}
for (int i=0,len=arguments.size(); i < len; i++) {
TypePattern p = arguments.get(i);
//we are allowed to bind to pointcuts which use subtypes as this is type safe
if (p == TypePattern.NO) {
scope.message(IMessage.ERROR, this,
"bad parameter to pointcut reference");
return;
}
if (!p.matchesSubtypes(parameterTypes[i]) &&
!p.getExactType().equals(TypeX.OBJECT))
{
scope.message(IMessage.ERROR, p, "incompatible type, expected " +
parameterTypes[i].getName() + " found " + p);
return;
}
}
}
public void postRead(ResolvedTypeX enclosingType) {
arguments.postRead(enclosingType);
}
public Test findResidue(Shadow shadow, ExposedState state) {
throw new RuntimeException("shouldn't happen");
}
//??? This is not thread safe, but this class is not designed for multi-threading
private boolean concretizing = false;
public Pointcut concretize1(ResolvedTypeX searchStart, IntMap bindings) {
if (concretizing) {
//Thread.currentThread().dumpStack();
searchStart.getWorld().getMessageHandler().handleMessage(
MessageUtil.error("circular pointcut declaration involving: " + this,
getSourceLocation()));
return Pointcut.makeMatchesNothing(Pointcut.CONCRETE);
}
try {
concretizing = true;
ResolvedPointcutDefinition pointcutDec;
if (onType != null) {
searchStart = onType.resolve(searchStart.getWorld());
if (searchStart == ResolvedTypeX.MISSING) {
return Pointcut.makeMatchesNothing(Pointcut.CONCRETE);
}
}
pointcutDec = searchStart.findPointcut(name);
if (pointcutDec == null) {
searchStart.getWorld().getMessageHandler().handleMessage(
MessageUtil.error("can't find pointcut \'" + name + "\' on " + searchStart.getName(),
getSourceLocation())
);
return Pointcut.makeMatchesNothing(Pointcut.CONCRETE);
}
if (pointcutDec.isAbstract()) {
//Thread.currentThread().dumpStack();
searchStart.getWorld().showMessage(IMessage.ERROR,
pointcutDec + " is abstract",
getSourceLocation(), bindings.getEnclosingAdvice().getSourceLocation());
return Pointcut.makeMatchesNothing(Pointcut.CONCRETE);
}
//System.err.println("start: " + searchStart);
ResolvedTypeX[] parameterTypes = searchStart.getWorld().resolve(pointcutDec.getParameterTypes());
TypePatternList arguments = this.arguments.resolveReferences(bindings);
IntMap newBindings = new IntMap();
for (int i=0,len=arguments.size(); i < len; i++) {
TypePattern p = arguments.get(i);
//we are allowed to bind to pointcuts which use subtypes as this is type safe
if (!p.matchesSubtypes(parameterTypes[i]) &&
!p.getExactType().equals(TypeX.OBJECT))
{
throw new BCException("illegal change to pointcut declaration: " + this);
}
if (p instanceof BindingTypePattern) {
newBindings.put(i, ((BindingTypePattern)p).getFormalIndex());
}
}
newBindings.copyContext(bindings);
newBindings.pushEnclosingDefinition(pointcutDec);
try {
return pointcutDec.getPointcut().concretize1(searchStart, newBindings);
} finally {
newBindings.popEnclosingDefinitition();
}
} finally {
concretizing = false;
}
}
public boolean equals(Object other) {
if (!(other instanceof ReferencePointcut)) return false;
ReferencePointcut o = (ReferencePointcut)other;
return o.name.equals(name) && o.arguments.equals(arguments)
&& ((o.onType == null) ? (onType == null) : o.onType.equals(onType));
}
public int hashCode() {
int result = 17;
result = 37*result + ((onType == null) ? 0 : onType.hashCode());
result = 37*result + arguments.hashCode();
result = 37*result + name.hashCode();
return result;
}
}
|
43,709
|
Bug 43709 structure view crash when extending library aspects
|
I have an library with an aspect that includes advice, which I compile into an outjar. In my client project I extend it, and make a concrete pointcut that results in the library aspect affecting parts of my system. There is a bug and an enhancement request here: 1) A bug: when you look at the structure view for affected classes, there is a problem if you try to navigate from calls to advice (in AJDT, it results in an NPE). Here is the stack trace in AJDT: java.lang.NullPointerException at org.aspectj.asm.internal.ProgramElement.toLinkLabelString (ProgramElement.java:403) at org.eclipse.ajdt.internal.core.AJDTStructureViewNode.getLabel (AJDTStructureViewNode.java:171) at org.eclipse.ajdt.internal.core.AJDTStructureViewNodeAdapter.getLabel (AJDTStructureViewNodeAdapter.java:89) at org.eclipse.ui.model.WorkbenchLabelProvider.getText (WorkbenchLabelProvider.java:142) at org.eclipse.jface.viewers.TreeViewer.doUpdateItem(TreeViewer.java:95) at org.eclipse.jface.viewers.AbstractTreeViewer$UpdateItemSafeRunnable.run (AbstractTreeViewer.java:87) at org.eclipse.core.internal.runtime.InternalPlatform.run (InternalPlatform.java:1006) at org.eclipse.core.runtime.Platform.run(Platform.java:413) at org.eclipse.jface.viewers.AbstractTreeViewer.doUpdateItem (AbstractTreeViewer.java:406) at org.eclipse.jface.viewers.StructuredViewer$UpdateItemSafeRunnable.run (StructuredViewer.java:119) at org.eclipse.core.internal.runtime.InternalPlatform.run (InternalPlatform.java:1006) at org.eclipse.core.runtime.Platform.run(Platform.java:413) at org.eclipse.jface.viewers.StructuredViewer.updateItem (StructuredViewer.java:1271) at org.eclipse.jface.viewers.AbstractTreeViewer.createTreeItem (AbstractTreeViewer.java:320) at org.eclipse.jface.viewers.AbstractTreeViewer$1.run (AbstractTreeViewer.java:303) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:69) at org.eclipse.jface.viewers.AbstractTreeViewer.createChildren (AbstractTreeViewer.java:289) at org.eclipse.jface.viewers.AbstractTreeViewer.handleTreeExpand (AbstractTreeViewer.java:697) at org.eclipse.jface.viewers.AbstractTreeViewer$4.treeExpanded (AbstractTreeViewer.java:709) at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:175) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:81) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:840) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:865) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:849) at org.eclipse.swt.widgets.Tree.wmNotifyChild(Tree.java:1909) at org.eclipse.swt.widgets.Control.WM_NOTIFY(Control.java:3815) at org.eclipse.swt.widgets.Composite.WM_NOTIFY(Composite.java:642) at org.eclipse.swt.widgets.Control.windowProc(Control.java:2816) at org.eclipse.swt.widgets.Display.windowProc(Display.java:2361) at org.eclipse.swt.internal.win32.OS.CallWindowProcW(Native Method) at org.eclipse.swt.internal.win32.OS.CallWindowProc(OS.java:1236) at org.eclipse.swt.widgets.Tree.callWindowProc(Tree.java:156) at org.eclipse.swt.widgets.Tree.WM_LBUTTONDOWN(Tree.java:1517) at org.eclipse.swt.widgets.Control.windowProc(Control.java:2799) at org.eclipse.swt.widgets.Display.windowProc(Display.java:2361) at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method) at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.java:1303) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1543) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1402) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1385) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:858) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.eclipse.core.launcher.Main.basicRun(Main.java:291) at org.eclipse.core.launcher.Main.run(Main.java:747) at org.eclipse.core.launcher.Main.main(Main.java:583) 2) The enhancement request: the concrete aspect that applies the advice should also show what is affected in the project. Of course, it would also be nice to see how a given concrete library aspect in the aspect path affects your project too.
|
resolved fixed
|
426d89b
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2003-09-26T05:24:49Z
| 2003-09-25T22:46:40Z
|
asm/src/org/aspectj/asm/internal/ProgramElement.java
|
/* *******************************************************************
* Copyright (c) 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:
* Mik Kersten initial implementation
* ******************************************************************/
package org.aspectj.asm.internal;
import java.io.*;
import java.util.*;
import org.aspectj.asm.*;
import org.aspectj.bridge.*;
/**
* @author Mik Kersten
*/
public class ProgramElement implements IProgramElement {
static final String ID_DELIM = "|";
protected IProgramElement parent = null;
protected String name = "";
// children.listIterator() should support remove() operation
protected List children = new ArrayList();
protected IMessage message = null;
protected ISourceLocation sourceLocation = null;
private List modifiers = new ArrayList();
private List relations = new ArrayList();
private Kind kind;
private Accessibility accessibility;
private String declaringType = "";
private String formalComment = "";
private String packageName = null;
private boolean runnable = false;
private boolean implementor = false;
private boolean overrider = false;
private String bytecodeName;
private String bytecodeSignature;
private String fullSignature;
private String returnType;
private List parameterNames = null;
private List parameterTypes = null;
private String details = null;
/**
* Used during de-externalization.
*/
public ProgramElement() { }
/**
* Use to create program element nodes that do not correspond to source locations.
*/
public ProgramElement(
String name,
Kind kind,
List children) {
this.name = name;
this.kind = kind;
setChildren(children);
// System.err.println("> created: " + name + ", children: " + children);
}
public ProgramElement(
String name,
IProgramElement.Kind kind,
ISourceLocation sourceLocation,
int modifiers,
String formalComment,
List children)
{
this(name, kind, children);
this.sourceLocation = sourceLocation;
this.kind = kind;
this.formalComment = formalComment;
this.modifiers = genModifiers(modifiers);
this.accessibility = genAccessibility(modifiers);
cacheByHandle();
}
/**
* Use to create program element nodes that correspond to source locations.
*/
public ProgramElement(
String name,
Kind kind,
int modifiers,
Accessibility accessibility,
String declaringType,
String packageName,
String formalComment,
ISourceLocation sourceLocation,
List relations,
List children,
boolean member) {
this(name, kind, children);
this.sourceLocation = sourceLocation;
this.kind = kind;
this.modifiers = genModifiers(modifiers);
this.accessibility = accessibility;
this.declaringType = declaringType;
this.packageName = packageName;
this.formalComment = formalComment;
this.relations = relations;
cacheByHandle();
}
public List getModifiers() {
return modifiers;
}
public Accessibility getAccessibility() {
return accessibility;
}
public String getDeclaringType() {
return declaringType;
}
public String getPackageName() {
if (kind == Kind.PACKAGE) return getName();
if (getParent() == null || !(getParent() instanceof IProgramElement)) {
return "";
}
return ((IProgramElement)getParent()).getPackageName();
}
public Kind getKind() {
return kind;
}
public boolean isCode() {
return kind.equals(Kind.CODE);
}
public ISourceLocation getSourceLocation() {
return sourceLocation;
}
public void setSourceLocation(ISourceLocation sourceLocation) {
this.sourceLocation = sourceLocation;
}
public IMessage getMessage() {
return message;
}
public void setMessage(IMessage message) {
this.message = message;
}
public IProgramElement getParent() {
return parent;
}
public void setParent(IProgramElement parent) {
this.parent = parent;
}
public boolean isMemberKind() {
return kind.isMemberKind();
}
public void setRunnable(boolean value) {
this.runnable = value;
}
public boolean isRunnable() {
return runnable;
}
public boolean isImplementor() {
return implementor;
}
public void setImplementor(boolean value) {
this.implementor = value;
}
public boolean isOverrider() {
return overrider;
}
public void setOverrider(boolean value) {
this.overrider = value;
}
public List getRelations() {
return relations;
}
public void setRelations(List relations) {
if (relations.size() > 0) {
this.relations = relations;
}
}
public String getFormalComment() {
return formalComment;
}
public String toString() {
return toLabelString();
}
private static List genModifiers(int modifiers) {
List modifiersList = new ArrayList();
if ((modifiers & AccStatic) != 0) modifiersList.add(IProgramElement.Modifiers.STATIC);
if ((modifiers & AccFinal) != 0) modifiersList.add(IProgramElement.Modifiers.FINAL);
if ((modifiers & AccSynchronized) != 0) modifiersList.add(IProgramElement.Modifiers.SYNCHRONIZED);
if ((modifiers & AccVolatile) != 0) modifiersList.add(IProgramElement.Modifiers.VOLATILE);
if ((modifiers & AccTransient) != 0) modifiersList.add(IProgramElement.Modifiers.TRANSIENT);
if ((modifiers & AccNative) != 0) modifiersList.add(IProgramElement.Modifiers.NATIVE);
if ((modifiers & AccAbstract) != 0) modifiersList.add(IProgramElement.Modifiers.ABSTRACT);
return modifiersList;
}
public static IProgramElement.Accessibility genAccessibility(int modifiers) {
if ((modifiers & AccPublic) != 0) return IProgramElement.Accessibility.PUBLIC;
if ((modifiers & AccPrivate) != 0) return IProgramElement.Accessibility.PRIVATE;
if ((modifiers & AccProtected) != 0) return IProgramElement.Accessibility.PROTECTED;
if ((modifiers & AccPrivileged) != 0) return IProgramElement.Accessibility.PRIVILEGED;
else return IProgramElement.Accessibility.PACKAGE;
}
// XXX these names and values are from org.eclipse.jdt.internal.compiler.env.IConstants
private static int AccPublic = 0x0001;
private static int AccPrivate = 0x0002;
private static int AccProtected = 0x0004;
private static int AccPrivileged = 0x0006; // XXX is this right?
private static int AccStatic = 0x0008;
private static int AccFinal = 0x0010;
private static int AccSynchronized = 0x0020;
private static int AccVolatile = 0x0040;
private static int AccTransient = 0x0080;
private static int AccNative = 0x0100;
private static int AccInterface = 0x0200;
private static int AccAbstract = 0x0400;
private static int AccStrictfp = 0x0800;
public String getBytecodeName() {
return bytecodeName;
}
public String getBytecodeSignature() {
return bytecodeSignature;
}
public void setBytecodeName(String bytecodeName) {
this.bytecodeName = bytecodeName;
}
public void setBytecodeSignature(String bytecodeSignature) {
this.bytecodeSignature = bytecodeSignature;
}
// public String getFullSignature() {
// return fullSignature;
// }
//
// public void setFullSignature(String string) {
// fullSignature = string;
// }
public void setKind(Kind kind) {
this.kind = kind;
}
public void setReturnType(String returnType) {
this.returnType = returnType;
}
public String getReturnType() {
return returnType;
}
public String getName() {
return name;
}
public List getChildren() {
return children;
}
public void setChildren(List children) {
this.children = children;
if (children == null) return;
for (Iterator it = children.iterator(); it.hasNext(); ) {
((IProgramElement)it.next()).setParent(this);
}
}
public void addChild(IProgramElement child) {
if (children == null) {
children = new ArrayList();
}
children.add(child);
child.setParent(this);
}
public void addChild(int position, IProgramElement child) {
if (children == null) {
children = new ArrayList();
}
children.add(position, child);
child.setParent(this);
}
public boolean removeChild(IProgramElement child) {
child.setParent(null);
return children.remove(child);
}
public void setName(String string) {
name = string;
}
// private void setParents() {
//// System.err.println(">> setting parents on: " + name);
// if (children == null) return;
// for (Iterator it = children.iterator(); it.hasNext(); ) {
// ((IProgramElement)it.next()).setParent(this);
// }
// }
public IProgramElement walk(HierarchyWalker walker) {
for (Iterator it = children.iterator(); it.hasNext(); ) {
IProgramElement child = (IProgramElement)it.next();
walker.process(child);
}
return this;
}
public String toLongString() {
final StringBuffer buffer = new StringBuffer();
HierarchyWalker walker = new HierarchyWalker() {
private int depth = 0;
public void preProcess(IProgramElement node) {
for (int i = 0; i < depth; i++) buffer.append(' ');
buffer.append(node.toString());
buffer.append('\n');
depth += 2;
}
public void postProcess(IProgramElement node) {
depth -= 2;
}
};
walker.process(this);
return buffer.toString();
}
public void setModifiers(int i) {
this.modifiers = genModifiers(i);
}
public String toSignatureString() {
StringBuffer sb = new StringBuffer();
sb.append(name);
if (parameterTypes != null ) {
sb.append('(');
for (Iterator it = parameterTypes.iterator(); it.hasNext(); ) {
sb.append((String)it.next());
if (it.hasNext()) sb.append(", ");
}
sb.append(')');
}
return sb.toString();
}
public String toLinkLabelString() {
String label;
if (kind == Kind.CODE || kind == Kind.INITIALIZER) {
label = parent.getParent().getName() + ": ";
} else if (kind.isInterTypeMemberKind()) {
int dotIndex = name.indexOf('.');
if (dotIndex != -1) {
return parent.getName() + ": " + toLabelString().substring(dotIndex+1);
} else {
label = parent.getName() + '.';
}
} else if (kind == Kind.CLASS || kind == Kind.ASPECT) {
label = "";
} else {
label = parent.getName() + '.';
}
label += toLabelString();
return label;
}
public String toLabelString() {
String label = toSignatureString();
if (details != null) {
label += ": " + details;
}
return label;
}
public static String createHandleIdentifier(File sourceFile, int line,int column) {
StringBuffer sb = new StringBuffer();
sb.append(AsmManager.getDefault().getCanonicalFilePath(sourceFile));
sb.append(ID_DELIM);
sb.append(line);
sb.append(ID_DELIM);
sb.append(column);
return sb.toString();
}
private String handle = null;
public String getHandleIdentifier() {
if (null == handle) {
if (sourceLocation != null) {
StringBuffer sb = new StringBuffer();
sb.append(AsmManager.getDefault()
.getCanonicalFilePath(sourceLocation.getSourceFile()));
sb.append(ID_DELIM);
sb.append(sourceLocation.getLine());
sb.append(ID_DELIM);
sb.append(sourceLocation.getColumn());
handle = sb.toString();
}
}
return handle;
}
public List getParameterNames() {
return parameterNames;
}
public List getParameterTypes() {
return parameterTypes;
}
public void setParameterNames(List list) {
parameterNames = list;
}
public void setParameterTypes(List list) {
parameterTypes = list;
}
public String getDetails() {
return details;
}
public void setDetails(String string) {
details = string;
}
/** AMC added to speed up findByHandle lookups in AspectJElementHierarchy */
private void cacheByHandle() {
String handle = getHandleIdentifier();
if (handle != null) {
AspectJElementHierarchy hierarchy = (AspectJElementHierarchy)
AsmManager.getDefault().getHierarchy();
hierarchy.cache(handle,this);
}
}
}
|
44,117
|
Bug 44117 NPE on compile
|
java.lang.NullPointerException at org.aspectj.weaver.AsmRelationshipProvider.checkerMunger (AsmRelationshipProvider.java:51) at org.aspectj.weaver.Checker.match(Checker.java:58) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:985) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:791) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:291) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:77) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:417) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:390) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:316) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.weaveAndGenerateClassFile s(AjBuildManager.java:256) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:156) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBuildManager.java:70) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:103) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:165)
|
resolved fixed
|
3117255
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2003-10-16T15:15:45Z
| 2003-10-03T05:46:40Z
|
weaver/src/org/aspectj/weaver/AsmRelationshipProvider.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.util.ArrayList;
import java.util.Iterator;
import org.aspectj.asm.*;
import org.aspectj.asm.internal.ProgramElement;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.SourceLocation;
public class AsmRelationshipProvider {
public static final String ADVISES = "advises";
public static final String ADVISED_BY = "advised by";
public static final String DECLARES_ON = "declares on";
public static final String DECLAREDY_BY = "declared by";
public static final String MATCHED_BY = "matched by";
public static final String MATCHES_DECLARE = "matches declare";
public static void checkerMunger(IHierarchy model, Shadow shadow, Checker checker) {
if (shadow.getSourceLocation() == null || checker.getSourceLocation() == null) return;
String sourceHandle = ProgramElement.createHandleIdentifier(
checker.getSourceLocation().getSourceFile(),
checker.getSourceLocation().getLine(),
checker.getSourceLocation().getColumn());
String targetHandle = ProgramElement.createHandleIdentifier(
shadow.getSourceLocation().getSourceFile(),
shadow.getSourceLocation().getLine(),
shadow.getSourceLocation().getColumn());
IRelationshipMap mapper = AsmManager.getDefault().getRelationshipMap();
if (sourceHandle != null && targetHandle != null) {
IRelationship foreward = mapper.get(sourceHandle, IRelationship.Kind.DECLARE, MATCHED_BY);
foreward.getTargets().add(targetHandle);
IRelationship back = mapper.get(targetHandle, IRelationship.Kind.DECLARE, MATCHES_DECLARE);
back.getTargets().add(sourceHandle);
}
}
public static void adviceMunger(IHierarchy model, Shadow shadow, ShadowMunger munger) {
if (munger instanceof Advice) {
Advice advice = (Advice)munger;
if (advice.getKind().isPerEntry() || advice.getKind().isCflow()) {
// TODO: might want to show these in the future
return;
}
IRelationshipMap mapper = AsmManager.getDefault().getRelationshipMap();
IProgramElement targetNode = getNode(AsmManager.getDefault().getHierarchy(), shadow);
String adviceHandle = advice.getHandle();
if (adviceHandle != null && targetNode != null) {
if (targetNode != null) {
String targetHandle = targetNode.getHandleIdentifier();
IRelationship foreward = mapper.get(adviceHandle, IRelationship.Kind.ADVICE, ADVISES);
if (foreward != null) foreward.getTargets().add(targetHandle);
IRelationship back = mapper.get(targetHandle, IRelationship.Kind.ADVICE, ADVISED_BY);
if (back != null) back.getTargets().add(adviceHandle);
}
}
}
}
private static IProgramElement getNode(IHierarchy model, Shadow shadow) {
Member enclosingMember = shadow.getEnclosingCodeSignature();
IProgramElement enclosingNode = lookupMember(model, enclosingMember);
if (enclosingNode == null) {
Lint.Kind err = shadow.getIWorld().getLint().shadowNotInStructure;
if (err.isEnabled()) {
err.signal(shadow.toString(), shadow.getSourceLocation());
}
return null;
}
Member shadowSig = shadow.getSignature();
if (!shadowSig.equals(enclosingMember)) {
IProgramElement bodyNode = findOrCreateCodeNode(enclosingNode, shadowSig, shadow);
return bodyNode;
} else {
return enclosingNode;
}
}
private static IProgramElement findOrCreateCodeNode(IProgramElement enclosingNode, Member shadowSig, Shadow shadow)
{
for (Iterator it = enclosingNode.getChildren().iterator(); it.hasNext(); ) {
IProgramElement node = (IProgramElement)it.next();
if (shadowSig.getName().equals(node.getBytecodeName()) &&
shadowSig.getSignature().equals(node.getBytecodeSignature()))
{
return node;
}
}
ISourceLocation sl = shadow.getSourceLocation();
IProgramElement peNode = new ProgramElement(
shadow.toString(),
IProgramElement.Kind.CODE,
//XXX why not use shadow file? new SourceLocation(sl.getSourceFile(), sl.getLine()),
new SourceLocation(enclosingNode.getSourceLocation().getSourceFile(), sl.getLine()),
0,
"",
new ArrayList());
peNode.setBytecodeName(shadowSig.getName());
peNode.setBytecodeSignature(shadowSig.getSignature());
enclosingNode.addChild(peNode);
return peNode;
}
private static IProgramElement lookupMember(IHierarchy model, Member member) {
TypeX declaringType = member.getDeclaringType();
IProgramElement classNode =
model.findElementForType(declaringType.getPackageName(), declaringType.getClassName());
return findMemberInClass(classNode, member);
}
private static IProgramElement findMemberInClass(
IProgramElement classNode,
Member member)
{
if (classNode == null) return null; // XXX remove this check
for (Iterator it = classNode.getChildren().iterator(); it.hasNext(); ) {
IProgramElement node = (IProgramElement)it.next();
if (member.getName().equals(node.getBytecodeName()) &&
member.getSignature().equals(node.getBytecodeSignature()))
{
return node;
}
}
// if we can't find the member, we'll just put it in the class
return classNode;
}
// private static IProgramElement.Kind genShadowKind(Shadow shadow) {
// IProgramElement.Kind shadowKind;
// if (shadow.getKind() == Shadow.MethodCall
// || shadow.getKind() == Shadow.ConstructorCall
// || shadow.getKind() == Shadow.FieldGet
// || shadow.getKind() == Shadow.FieldSet
// || shadow.getKind() == Shadow.ExceptionHandler) {
// return IProgramElement.Kind.CODE;
//
// } else if (shadow.getKind() == Shadow.MethodExecution) {
// return IProgramElement.Kind.METHOD;
//
// } else if (shadow.getKind() == Shadow.ConstructorExecution) {
// return IProgramElement.Kind.CONSTRUCTOR;
//
// } else if (shadow.getKind() == Shadow.PreInitialization
// || shadow.getKind() == Shadow.Initialization) {
// return IProgramElement.Kind.CLASS;
//
// } else if (shadow.getKind() == Shadow.AdviceExecution) {
// return IProgramElement.Kind.ADVICE;
//
// } else {
// return IProgramElement.Kind.ERROR;
// }
// }
}
|
43,783
|
Bug 43783 AJDT not very stable when confronted with java/aspect errors.
|
AJDT is not very stable when an eclipse project contains errors like missing classes, wrong package statements etc. etc. This may occurs when refactoring a project (sometimes by changing the source outside eclipse). Note I am using Eclipse 2.1.1, AJDT 1.1.4 + incremental compilation. Generally a lot of exceptions will occur (mostly nullpointer). Here are some of them: I: java.lang.NullPointerException at org.aspectj.asm.internal.ProgramElement.toLinkLabelString (ProgramElement.java:403) at org.eclipse.ajdt.internal.core.AJDTStructureViewNode.getLabel (AJDTStructureViewNode.java:171) at org.eclipse.ajdt.internal.core.AJDTStructureViewNodeAdapter.getLabel (AJDTStructureViewNodeAdapter.java:89) at org.eclipse.ui.model.WorkbenchLabelProvider.getText (WorkbenchLabelProvider.java:142) II: java.lang.NullPointerException at org.eclipse.ajdt.internal.ui.editor.AspectJEditor$1.run (AspectJEditor.java:242) at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java:35) III: java.lang.NullPointerException at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:79) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:165) !
|
resolved fixed
|
3e4b59a
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2003-10-22T15:24:59Z
| 2003-09-26T23:46:40Z
|
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 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) {
init();
try {
AjBuildConfig buildConfig = genBuildConfig(configFile);
buildConfig.setGenerateModelMode(buildModel);
if (null == buildConfig) {
return false;
}
currNotifier = new BuildNotifierAdapter(progressMonitor);
buildManager.setProgressListener(currNotifier);
messageHandler.setBuildNotifierAdapter(currNotifier);
String rtInfo = buildManager.checkRtJar(buildConfig); // !!! will get called twice
if (rtInfo != null) {
signalWarning(
"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) {
signalWarning("build cancelled by user");
return false;
} catch (AbortException e) {
final IMessage message = e.getIMessage();
if (null == message) {
signalThrown(e);
} else if (null != message.getMessage()) {
signalWarning(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()) {
signalError("Config file \"" + configFile + "\" does not exist.");
return null;
}
String[] args = new String[] { "@" + configFile.getAbsolutePath() };
CountingMessageHandler handler
= CountingMessageHandler.makeCountingMessageHandler(messageHandler);
BuildArgParser parser = new BuildArgParser();
AjBuildConfig config = parser.genBuildConfig(args, handler, false, configFile);
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, 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.getJavaOptions().putAll(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) {
Ajde.getDefault().getErrorHandler().handleError(text);
}
/** signal warning text to user */
protected void signalWarning(String text) {
Ajde.getDefault().getErrorHandler().handleWarning(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 javaOptions = config.getJavaOptions();
LangUtil.throwIaxIfNull(javaOptions, "javaOptions");
if (options.getSourceOnePointFourMode()) {
javaOptions.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_4);
javaOptions.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_4);
}
String enc = options.getCharacterEncoding();
if (!LangUtil.isEmpty(enc)) {
javaOptions.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;
}
javaOptions.put(CompilerOptions.OPTION_Compliance, version );
javaOptions.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) javaOptions.get( CompilerOptions.OPTION_Compliance);
if ( ! (setCompliance.equals( CompilerOptions.VERSION_1_4 )
&& slVersion.equals(CompilerOptions.VERSION_1_3)) ) {
javaOptions.put(CompilerOptions.OPTION_Source, slVersion);
}
}
Set warnings = options.getWarnings();
if (!LangUtil.isEmpty(warnings)) {
// turn off all warnings
disableWarnings( javaOptions );
// then selectively enable those in the set
enableWarnings( javaOptions, 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) javaOptions.put(CompilerOptions.OPTION_SourceFileAttribute,
CompilerOptions.GENERATE);
if (varAttr) javaOptions.put(CompilerOptions.OPTION_LocalVariableAttribute,
CompilerOptions.GENERATE);
if (lineNo) javaOptions.put(CompilerOptions.OPTION_LineNumberAttribute,
CompilerOptions.GENERATE);
}
if ( options.getNoImportError() ) {
javaOptions.put( CompilerOptions.OPTION_ReportInvalidImport,
CompilerOptions.WARNING);
}
if ( options.getPreserveAllLocals() ) {
javaOptions.put( CompilerOptions.OPTION_PreserveUnusedLocal,
CompilerOptions.PRESERVE);
}
if ( !config.isIncrementalMode()
&& options.getIncrementalMode() ) {
config.setIncrementalMode(true);
}
config.setJavaOptions( javaOptions );
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 );
}
}
}
/**
* 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;
}
StringTokenizer tok = new StringTokenizer( nonStdOptions );
String[] args = new String[ tok.countTokens() ];
int argCount = 0;
while ( tok.hasMoreTokens() ) {
args[argCount++] = tok.nextToken();
}
// 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,
* for classpath, aspectpath, injars, 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());
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;
}
}
}
|
47,318
|
Bug 47318 org.aspectj.asm.IRelationship.Kind.ALL does not contain all kinds
|
org.aspectj.asm.IRelationship.Kind.ALL is an array that should contain all kinds that an IRelationship may have. There are three possible kinds defined in IRelationship.java: ADVICE, DECLARE and DECLARE_INTER_TYPE. The Kind[] ALL does only contain ADVICE and DECLARE. This can lead to an ArrayIndexOutOfBoundsException.
|
resolved fixed
|
bdc79f1
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2003-11-23T21:32:30Z
| 2003-11-23T20:40:00Z
|
asm/src/org/aspectj/asm/IRelationship.java
|
/* *******************************************************************
* Copyright (c) 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:
* Mik Kersten initial implementation
* ******************************************************************/
package org.aspectj.asm;
import java.io.*;
import java.util.List;
/**
* @author Mik Kersten
*/
public interface IRelationship extends Serializable {
public String getName();
public List/*String*/ getTargets();
public String getSourceHandle();
public Kind getKind();
/**
* Uses "typesafe enum" pattern.
*/
public static class Kind implements Serializable {
public static final Kind ADVICE = new Kind("advice");
public static final Kind DECLARE = new Kind("declare");
public static final Kind DECLARE_INTER_TYPE = new Kind("inter-type declaration");
public static final Kind[] ALL = { ADVICE, DECLARE };
private final String name;
private Kind(String name) {
this.name = name;
}
public String toString() {
return name;
}
// The 4 declarations below are necessary for serialization
private static int nextOrdinal = 0;
private final int ordinal = nextOrdinal++;
private Object readResolve() throws ObjectStreamException {
return ALL[ordinal];
}
}
}
|
49,457
|
Bug 49457 No error on overloaded pointcuts unless binding variables
|
The compiler might not be detecting overloaded pointcut names when parameters are not bound, and/or might not be implementing the pointcut correctly. Below is the context from my reply to Ron Bodkin on aspectj-dev "Proper behavior of overloaded pointcut definitions". (I have not checked this code recently or submitted a test case, nor have I evaluated whether my code below actually replicates Ron's bug.) ---- context from the email The programming guide says, It is an error for two pointcuts to be named with the same name in the same class or aspect declaration. When I compile with overloaded pointcut names, I do get an error. pointcut pc(Runnable r) : target(r) && call(void run()); pointcut pc(SubRunnable r) : target(r) && call(void run()); $ aspectj-1.1.1 -classpath $ajrt11 OverloadedPointcut.java ...\OverloadedPointcut.java:14 duplicate pointcut name: pc ...\OverloadedPointcut.java:15 duplicate pointcut name: pc ... When I use these pointcuts with bound parameters, I get an error. before(Runnable r) : pc(r) { log("pc(Runnable r)"); } before(SubRunnable r) : pc(r) { log("pc(SubRunnable r)"); } When I use these pointcuts with type parameters, I get no errors. before() : pc(Runnable) { log("pc(Runnable)"); } before() : pc(SubRunnable) { log("pc(SubRunnable)"); } before() : pc(*) { log("pc(*)"); } [...] ---- my code public class OverloadedPointcut { public static void main(String[] args) { new C().run(); } } class C { public void run() {} } aspect A { declare parents: C implements Runnable; declare parents: C implements SubRunnable; interface SubRunnable extends Runnable {} pointcut pc(Runnable r) : target(r) && call(void run()); pointcut pc(SubRunnable r) : target(r) && call(void run()); before(Runnable r) : pc(r) { log("pc(Runnable r)"); } before(SubRunnable r) : pc(r) { log("pc(SubRunnable r)"); } before() : pc(Runnable) { log("pc(Runnable)"); } before() : pc(SubRunnable) { log("pc(SubRunnable)"); } before() : pc(*) { log("pc(*)"); } void log(String s) { System.out.println(s); } } ---- Ron's code [...] the following program compiles with no warnings, produces no output when run under AspectJ 1.1.1. It appears to behave as if the more specific definition is the only definition of the pointcut [...] Here is a simple program that illustrates the question and odd behavior: package lib; public class RunnablePointcuts { public pointcut runnableCalls(Runnable runnable, Object caller) : call(* run(..)) && target(runnable) && this(caller); //public pointcut specialRunnableCalls(SpecialRunnable runnable, Object caller) : public pointcut runnableCalls(SpecialRunnable runnable, Object caller) : call(* run(..)) && target(runnable) && this(caller); } --- package lib; public interface SpecialRunnable extends Runnable { } --- package client; import lib.RunnablePointcuts; import lib.SpecialRunnable; public aspect Use { before(Object caller) : RunnablePointcuts.runnableCalls(*, caller) && target(MyRunnable) { System.out.println("my runnable called from "+caller); } public static void main(String args[]) { Use.aspectOf().doIt(); } public void doIt() { new MyRunnable().run(); } } // the advice will run if you make this implement SpecialRunnable //class MyRunnable implements SpecialRunnable { class MyRunnable implements Runnable { public void run() {} }
|
resolved fixed
|
c517e85
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-07T13:10:07Z
| 2004-01-02T05:06:40Z
|
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.Clinit;
import org.eclipse.jdt.internal.compiler.ast.MemberTypeDeclaration;
import org.eclipse.jdt.internal.compiler.codegen.CodeStream;
import org.eclipse.jdt.internal.compiler.codegen.Label;
import org.eclipse.jdt.internal.compiler.lookup.*;
// making all aspects member types avoids a nasty hierarchy pain
public class AspectDeclaration extends MemberTypeDeclaration {
//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
// 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;
}
if (concreteName != null) concreteName.checkPointcutDeclarations();
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.buildManager.buildConfig.isXserializableAspects()) {
if (world.getWorld().resolve(TypeX.SERIALIZABLE).isAssignableFrom(myType)) {
scope.problemReporter().signalError(sourceStart, sourceEnd,
"aspects may not implement Serializable");
ignoreFurtherInvestigation = true;
return;
}
if (world.getWorld().resolve(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;
}
}
}
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()) {
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);
} else if (perClause.getKind() == PerClause.PERCFLOW) {
binding.addField(
factory.makeFieldBinding(
AjcMemberMaker.perCflowField(
typeX)));
methods[0] = new AspectClinit((Clinit)methods[0], compilationResult, true, false);
} 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(0));
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.entrySet().iterator(); i.hasNext(); ) {
Map.Entry e = (Map.Entry)i.next();
generateSuperAccessMethod(classFile, (MethodBinding)e.getValue(), (ResolvedMember)e.getKey());
}
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) {
EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
classFile.generateMethodInfoHeader(methodBinding);
int methodAttributeOffset = classFile.contentsOffset;
int attributeNumber = classFile.generateMethodInfoAttribute(methodBinding, AstUtil.getAjSyntheticAttribute());
int codeAttributeOffset = classFile.contentsOffset;
classFile.generateCodeAttributeHeader();
CodeStream codeStream = classFile.codeStream;
codeStream.init(classFile);
codeStream.initializeMaxLocals(methodBinding);
// 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(
world.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(
world.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(world.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) {
// 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.new_(world.makeTypeBinding(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION));
codeStream.dup();
codeStream.invokespecial(world.makeMethodBindingForCall(
AjcMemberMaker.noAspectBoundExceptionInit()
));
codeStream.athrow();
// 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(
world.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,
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,
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,
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 String toStringHeader() {
String s = ""; //$NON-NLS-1$
if (modifiers != AccDefault) {
s += modifiersString(modifiers);
}
s += "aspect " + new String(name);//$NON-NLS-1$ //$NON-NLS-2$
if (superclass != null)
s += " extends " + superclass.toString(0); //$NON-NLS-1$
if (superInterfaces != null && superInterfaces.length > 0) {
s += (isInterface() ? " extends " : " implements ");//$NON-NLS-2$ //$NON-NLS-1$
for (int i = 0; i < superInterfaces.length; i++) {
s += superInterfaces[i].toString(0);
if (i != superInterfaces.length - 1)
s += ", "; //$NON-NLS-1$
};
};
return s;
}
}
|
49,457
|
Bug 49457 No error on overloaded pointcuts unless binding variables
|
The compiler might not be detecting overloaded pointcut names when parameters are not bound, and/or might not be implementing the pointcut correctly. Below is the context from my reply to Ron Bodkin on aspectj-dev "Proper behavior of overloaded pointcut definitions". (I have not checked this code recently or submitted a test case, nor have I evaluated whether my code below actually replicates Ron's bug.) ---- context from the email The programming guide says, It is an error for two pointcuts to be named with the same name in the same class or aspect declaration. When I compile with overloaded pointcut names, I do get an error. pointcut pc(Runnable r) : target(r) && call(void run()); pointcut pc(SubRunnable r) : target(r) && call(void run()); $ aspectj-1.1.1 -classpath $ajrt11 OverloadedPointcut.java ...\OverloadedPointcut.java:14 duplicate pointcut name: pc ...\OverloadedPointcut.java:15 duplicate pointcut name: pc ... When I use these pointcuts with bound parameters, I get an error. before(Runnable r) : pc(r) { log("pc(Runnable r)"); } before(SubRunnable r) : pc(r) { log("pc(SubRunnable r)"); } When I use these pointcuts with type parameters, I get no errors. before() : pc(Runnable) { log("pc(Runnable)"); } before() : pc(SubRunnable) { log("pc(SubRunnable)"); } before() : pc(*) { log("pc(*)"); } [...] ---- my code public class OverloadedPointcut { public static void main(String[] args) { new C().run(); } } class C { public void run() {} } aspect A { declare parents: C implements Runnable; declare parents: C implements SubRunnable; interface SubRunnable extends Runnable {} pointcut pc(Runnable r) : target(r) && call(void run()); pointcut pc(SubRunnable r) : target(r) && call(void run()); before(Runnable r) : pc(r) { log("pc(Runnable r)"); } before(SubRunnable r) : pc(r) { log("pc(SubRunnable r)"); } before() : pc(Runnable) { log("pc(Runnable)"); } before() : pc(SubRunnable) { log("pc(SubRunnable)"); } before() : pc(*) { log("pc(*)"); } void log(String s) { System.out.println(s); } } ---- Ron's code [...] the following program compiles with no warnings, produces no output when run under AspectJ 1.1.1. It appears to behave as if the more specific definition is the only definition of the pointcut [...] Here is a simple program that illustrates the question and odd behavior: package lib; public class RunnablePointcuts { public pointcut runnableCalls(Runnable runnable, Object caller) : call(* run(..)) && target(runnable) && this(caller); //public pointcut specialRunnableCalls(SpecialRunnable runnable, Object caller) : public pointcut runnableCalls(SpecialRunnable runnable, Object caller) : call(* run(..)) && target(runnable) && this(caller); } --- package lib; public interface SpecialRunnable extends Runnable { } --- package client; import lib.RunnablePointcuts; import lib.SpecialRunnable; public aspect Use { before(Object caller) : RunnablePointcuts.runnableCalls(*, caller) && target(MyRunnable) { System.out.println("my runnable called from "+caller); } public static void main(String args[]) { Use.aspectOf().doIt(); } public void doIt() { new MyRunnable().run(); } } // the advice will run if you make this implement SpecialRunnable //class MyRunnable implements SpecialRunnable { class MyRunnable implements Runnable { public void run() {} }
|
resolved fixed
|
c517e85
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-07T13:10:07Z
| 2004-01-02T05:06:40Z
|
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.*;
import org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration;
import org.aspectj.ajdt.internal.compiler.ast.DeclareDeclaration;
import org.aspectj.ajdt.internal.compiler.ast.PointcutDeclaration;
import org.aspectj.asm.*;
import org.aspectj.asm.IProgramElement;
import org.aspectj.asm.internal.Relationship;
import org.aspectj.bridge.IMessage;
import org.aspectj.weaver.*;
import org.aspectj.weaver.patterns.*;
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.*;
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++) {
addCrosscuttingStructures(((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;
AbstractMethodDeclaration[] methods = dec.methods;
boolean initializedMethods = false;
if (methods != null) {
for (int i=0; i < methods.length; i++) {
if (methods[i] instanceof PointcutDeclaration) {
if (!initializedMethods) {
sourceType.methods(); //force initialization
initializedMethods = true;
}
((PointcutDeclaration)methods[i]).resolvePointcut(s);
}
}
}
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);
AsmInterTypeRelationshipProvider.addRelationship(onType, munger);
}
}
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);
}
addParent(sourceType, parent);
}
}
}
private void addParent(SourceTypeBinding sourceType, ResolvedTypeX parent) {
ReferenceBinding parentBinding = (ReferenceBinding)factory.makeTypeBinding(parent);
if (parentBinding.isClass()) {
sourceType.superclass = parentBinding;
} 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;
}
}
private List pendingTypesToFinish = new ArrayList();
boolean inBinaryTypeCreation = false;
public BinaryTypeBinding createBinaryTypeFrom(
IBinaryType binaryType,
PackageBinding packageBinding,
boolean needFieldsAndMethods)
{
if (inBinaryTypeCreation) {
BinaryTypeBinding ret = super.createBinaryTypeFrom(
binaryType,
packageBinding,
needFieldsAndMethods);
pendingTypesToFinish.add(ret);
return ret;
}
inBinaryTypeCreation = true;
try {
BinaryTypeBinding ret = super.createBinaryTypeFrom(
binaryType,
packageBinding,
needFieldsAndMethods);
weaveInterTypeDeclarations(ret);
return ret;
} finally {
inBinaryTypeCreation = false;
if (!pendingTypesToFinish.isEmpty()) {
for (Iterator i = pendingTypesToFinish.iterator(); i.hasNext(); ) {
weaveInterTypeDeclarations((BinaryTypeBinding)i.next());
}
pendingTypesToFinish.clear();
}
}
}
}
|
49,457
|
Bug 49457 No error on overloaded pointcuts unless binding variables
|
The compiler might not be detecting overloaded pointcut names when parameters are not bound, and/or might not be implementing the pointcut correctly. Below is the context from my reply to Ron Bodkin on aspectj-dev "Proper behavior of overloaded pointcut definitions". (I have not checked this code recently or submitted a test case, nor have I evaluated whether my code below actually replicates Ron's bug.) ---- context from the email The programming guide says, It is an error for two pointcuts to be named with the same name in the same class or aspect declaration. When I compile with overloaded pointcut names, I do get an error. pointcut pc(Runnable r) : target(r) && call(void run()); pointcut pc(SubRunnable r) : target(r) && call(void run()); $ aspectj-1.1.1 -classpath $ajrt11 OverloadedPointcut.java ...\OverloadedPointcut.java:14 duplicate pointcut name: pc ...\OverloadedPointcut.java:15 duplicate pointcut name: pc ... When I use these pointcuts with bound parameters, I get an error. before(Runnable r) : pc(r) { log("pc(Runnable r)"); } before(SubRunnable r) : pc(r) { log("pc(SubRunnable r)"); } When I use these pointcuts with type parameters, I get no errors. before() : pc(Runnable) { log("pc(Runnable)"); } before() : pc(SubRunnable) { log("pc(SubRunnable)"); } before() : pc(*) { log("pc(*)"); } [...] ---- my code public class OverloadedPointcut { public static void main(String[] args) { new C().run(); } } class C { public void run() {} } aspect A { declare parents: C implements Runnable; declare parents: C implements SubRunnable; interface SubRunnable extends Runnable {} pointcut pc(Runnable r) : target(r) && call(void run()); pointcut pc(SubRunnable r) : target(r) && call(void run()); before(Runnable r) : pc(r) { log("pc(Runnable r)"); } before(SubRunnable r) : pc(r) { log("pc(SubRunnable r)"); } before() : pc(Runnable) { log("pc(Runnable)"); } before() : pc(SubRunnable) { log("pc(SubRunnable)"); } before() : pc(*) { log("pc(*)"); } void log(String s) { System.out.println(s); } } ---- Ron's code [...] the following program compiles with no warnings, produces no output when run under AspectJ 1.1.1. It appears to behave as if the more specific definition is the only definition of the pointcut [...] Here is a simple program that illustrates the question and odd behavior: package lib; public class RunnablePointcuts { public pointcut runnableCalls(Runnable runnable, Object caller) : call(* run(..)) && target(runnable) && this(caller); //public pointcut specialRunnableCalls(SpecialRunnable runnable, Object caller) : public pointcut runnableCalls(SpecialRunnable runnable, Object caller) : call(* run(..)) && target(runnable) && this(caller); } --- package lib; public interface SpecialRunnable extends Runnable { } --- package client; import lib.RunnablePointcuts; import lib.SpecialRunnable; public aspect Use { before(Object caller) : RunnablePointcuts.runnableCalls(*, caller) && target(MyRunnable) { System.out.println("my runnable called from "+caller); } public static void main(String args[]) { Use.aspectOf().doIt(); } public void doIt() { new MyRunnable().run(); } } // the advice will run if you make this implement SpecialRunnable //class MyRunnable implements SpecialRunnable { class MyRunnable implements Runnable { public void run() {} }
|
resolved fixed
|
c517e85
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-07T13:10:07Z
| 2004-01-02T05:06:40Z
|
tests/bugs/OverloadedPointcutsInAspect.java
| |
49,457
|
Bug 49457 No error on overloaded pointcuts unless binding variables
|
The compiler might not be detecting overloaded pointcut names when parameters are not bound, and/or might not be implementing the pointcut correctly. Below is the context from my reply to Ron Bodkin on aspectj-dev "Proper behavior of overloaded pointcut definitions". (I have not checked this code recently or submitted a test case, nor have I evaluated whether my code below actually replicates Ron's bug.) ---- context from the email The programming guide says, It is an error for two pointcuts to be named with the same name in the same class or aspect declaration. When I compile with overloaded pointcut names, I do get an error. pointcut pc(Runnable r) : target(r) && call(void run()); pointcut pc(SubRunnable r) : target(r) && call(void run()); $ aspectj-1.1.1 -classpath $ajrt11 OverloadedPointcut.java ...\OverloadedPointcut.java:14 duplicate pointcut name: pc ...\OverloadedPointcut.java:15 duplicate pointcut name: pc ... When I use these pointcuts with bound parameters, I get an error. before(Runnable r) : pc(r) { log("pc(Runnable r)"); } before(SubRunnable r) : pc(r) { log("pc(SubRunnable r)"); } When I use these pointcuts with type parameters, I get no errors. before() : pc(Runnable) { log("pc(Runnable)"); } before() : pc(SubRunnable) { log("pc(SubRunnable)"); } before() : pc(*) { log("pc(*)"); } [...] ---- my code public class OverloadedPointcut { public static void main(String[] args) { new C().run(); } } class C { public void run() {} } aspect A { declare parents: C implements Runnable; declare parents: C implements SubRunnable; interface SubRunnable extends Runnable {} pointcut pc(Runnable r) : target(r) && call(void run()); pointcut pc(SubRunnable r) : target(r) && call(void run()); before(Runnable r) : pc(r) { log("pc(Runnable r)"); } before(SubRunnable r) : pc(r) { log("pc(SubRunnable r)"); } before() : pc(Runnable) { log("pc(Runnable)"); } before() : pc(SubRunnable) { log("pc(SubRunnable)"); } before() : pc(*) { log("pc(*)"); } void log(String s) { System.out.println(s); } } ---- Ron's code [...] the following program compiles with no warnings, produces no output when run under AspectJ 1.1.1. It appears to behave as if the more specific definition is the only definition of the pointcut [...] Here is a simple program that illustrates the question and odd behavior: package lib; public class RunnablePointcuts { public pointcut runnableCalls(Runnable runnable, Object caller) : call(* run(..)) && target(runnable) && this(caller); //public pointcut specialRunnableCalls(SpecialRunnable runnable, Object caller) : public pointcut runnableCalls(SpecialRunnable runnable, Object caller) : call(* run(..)) && target(runnable) && this(caller); } --- package lib; public interface SpecialRunnable extends Runnable { } --- package client; import lib.RunnablePointcuts; import lib.SpecialRunnable; public aspect Use { before(Object caller) : RunnablePointcuts.runnableCalls(*, caller) && target(MyRunnable) { System.out.println("my runnable called from "+caller); } public static void main(String args[]) { Use.aspectOf().doIt(); } public void doIt() { new MyRunnable().run(); } } // the advice will run if you make this implement SpecialRunnable //class MyRunnable implements SpecialRunnable { class MyRunnable implements Runnable { public void run() {} }
|
resolved fixed
|
c517e85
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-07T13:10:07Z
| 2004-01-02T05:06:40Z
|
tests/bugs/OverloadedPointcutsInClass.java
| |
49,250
|
Bug 49250 alias getCause for getWrappedThrowable in SoftException
|
SoftException should implement getCause(): public Throwable getCause() { return inner; } (As pointed out by Ramnivas, misc mail messages, code comments...) Using getCause() means the chain should print as expected in 1.4+, esp. when SoftException is itself wrapped as a RemoteException. Since getCause() replicates getWrappedThrowable(), we could deprecate that, but we must continue to support it to maintain upwards binary compatibility in the runtime classes.
|
resolved fixed
|
eac16ae
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-07T13:30:26Z
| 2003-12-21T20:53:20Z
|
runtime/src/org/aspectj/lang/SoftException.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.lang;
/**
* Wrapper for checked exceptions matched by a 'declare soft'.
* You can soften checked exceptions at join points by using
* the form <code>declare soft: TypePattern: Pointcut</code>.
* At the join points, any exceptions thrown which match
* TypePattern will be wrapped in <code>SoftException</code>
* and rethrown. You can get the original exception using
* <code>getWrappedThrowable()</code>.
*/
public class SoftException extends RuntimeException {
Throwable inner;
public SoftException(Throwable inner) {
super();
this.inner = inner;
}
public Throwable getWrappedThrowable() { return inner; }
//XXX should add a getCause() method to parallel j2se 1.4's new
//XXX chained exception mechanism
}
|
47,754
|
Bug 47754 illegal method modifier
|
the attached example throws this at class load time. please note that this bug results in a different exception when happens in a different setup, and when the class is loaded by JBoss. (more cryptic, talking about generic class format error) Exception in thread "main" java.lang.ClassFormatError: com/netvisor/nvsr/client/InvalidByteCodeBug$Test$ITest (Illegal method modifiers: 0x409) at java.lang.ClassLoader.defineClass0(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:537) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java: 123) at java.net.URLClassLoader.defineClass(URLClassLoader.java:251) at java.net.URLClassLoader.access$100(URLClassLoader.java:55) at java.net.URLClassLoader$1.run(URLClassLoader.java:194) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:187) at java.lang.ClassLoader.loadClass(ClassLoader.java:289) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:274) at java.lang.ClassLoader.loadClass(ClassLoader.java:235) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:302) at java.lang.ClassLoader.defineClass0(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:537) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java: 123) at java.net.URLClassLoader.defineClass(URLClassLoader.java:251) at java.net.URLClassLoader.access$100(URLClassLoader.java:55) at java.net.URLClassLoader$1.run(URLClassLoader.java:194) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:187) at java.lang.ClassLoader.loadClass(ClassLoader.java:289) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:274) at java.lang.ClassLoader.loadClass(ClassLoader.java:235) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:302) at com.netvisor.nvsr.client.InvalidByteCodeBug.run(InvalidByteCodeBug. java:15) at com.netvisor.nvsr.client.InvalidByteCodeBug.main(InvalidByteCodeBug. java:8)
|
resolved fixed
|
7322131
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-07T15:57:25Z
| 2003-11-29T10: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.*;
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.FlowContext;
import org.eclipse.jdt.internal.compiler.flow.FlowInfo;
import org.eclipse.jdt.internal.compiler.flow.InitializationFlowContext;
import org.eclipse.jdt.internal.compiler.lookup.*;
import org.eclipse.jdt.internal.compiler.parser.Parser;
/**
* 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 (!Modifier.isAbstract(declaredModifiers)) super.resolveStatements();
}
public EclipseTypeMunger build(ClassScope classScope) {
EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(classScope);
resolveOnType(classScope);
if (ignoreFurtherInvestigation) return null;
binding = classScope.referenceContext.binding.resolveTypesFor(binding);
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;
}
}
|
47,754
|
Bug 47754 illegal method modifier
|
the attached example throws this at class load time. please note that this bug results in a different exception when happens in a different setup, and when the class is loaded by JBoss. (more cryptic, talking about generic class format error) Exception in thread "main" java.lang.ClassFormatError: com/netvisor/nvsr/client/InvalidByteCodeBug$Test$ITest (Illegal method modifiers: 0x409) at java.lang.ClassLoader.defineClass0(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:537) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java: 123) at java.net.URLClassLoader.defineClass(URLClassLoader.java:251) at java.net.URLClassLoader.access$100(URLClassLoader.java:55) at java.net.URLClassLoader$1.run(URLClassLoader.java:194) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:187) at java.lang.ClassLoader.loadClass(ClassLoader.java:289) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:274) at java.lang.ClassLoader.loadClass(ClassLoader.java:235) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:302) at java.lang.ClassLoader.defineClass0(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:537) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java: 123) at java.net.URLClassLoader.defineClass(URLClassLoader.java:251) at java.net.URLClassLoader.access$100(URLClassLoader.java:55) at java.net.URLClassLoader$1.run(URLClassLoader.java:194) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:187) at java.lang.ClassLoader.loadClass(ClassLoader.java:289) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:274) at java.lang.ClassLoader.loadClass(ClassLoader.java:235) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:302) at com.netvisor.nvsr.client.InvalidByteCodeBug.run(InvalidByteCodeBug. java:15) at com.netvisor.nvsr.client.InvalidByteCodeBug.main(InvalidByteCodeBug. java:8)
|
resolved fixed
|
7322131
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-07T15:57:25Z
| 2003-11-29T10:00:00Z
|
tests/bugs/StaticInterfaceMethods.java
| |
41,952
|
Bug 41952 XLint warning for call PCD's using subtype of defining type
| null |
resolved fixed
|
97ab1e9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-07T17:00:52Z
| 2003-08-26T09:26:40Z
|
bridge/src/org/aspectj/bridge/IMessage.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.bridge;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* Wrap message with any associated throwable or source location.
*/
public interface IMessage {
/** no messages */
public static final IMessage[] RA_IMessage = new IMessage[0];
// int values must sync with KINDS order below
public static final Kind INFO = new Kind("info", 10);
public static final Kind DEBUG = new Kind("debug", 20);
public static final Kind WARNING = new Kind("warning", 30);
public static final Kind ERROR = new Kind("error", 40);
public static final Kind FAIL = new Kind("fail", 50);
public static final Kind ABORT = new Kind("abort", 60);
// XXX prefer another Kind to act as selector for "any",
// but can't prohibit creating messages with it.
//public static final Kind ANY = new Kind("any-selector", 0);
/** list of Kind in precedence order. 0 is less than
* IMessage.Kind.COMPARATOR.compareTo(KINDS.get(i), KINDS.get(i + 1))
*/
public static final List KINDS =
Collections.unmodifiableList(
Arrays.asList(
new Kind[] { INFO, DEBUG, WARNING, ERROR, FAIL, ABORT }));
/** @return non-null String with simple message */
String getMessage();
/** @return the kind of this message */
Kind getKind();
/** @return true if this is an error */
boolean isError();
/** @return true if this is a warning */
boolean isWarning();
/** @return true if this is an internal debug message */
boolean isDebug();
/** @return true if this is information for the user */
boolean isInfo();
/** @return true if the process is aborting */
boolean isAbort(); // XXX ambiguous
/** @return true if something failed */
boolean isFailed();
/** @return Throwable associated with this message, or null if none */
Throwable getThrown();
/** @return source location associated with this message, or null if none */
ISourceLocation getSourceLocation();
public static final class Kind implements Comparable {
public static final Comparator COMPARATOR = new Comparator() {
public int compare(Object o1, Object o2) {
Kind one = (Kind) o1;
Kind two = (Kind) o2;
if (null == one) {
return (null == two ? 0 : -1);
} else if (null == two) {
return 1;
} else if (one == two) {
return 0;
} else {
return (one.precedence - two.precedence);
}
}
};
/**
* @param kind the Kind floor
* @return false if kind is null or this
* has less precedence than kind,
* true otherwise.
*/
public boolean isSameOrLessThan(Kind kind) {
return (0 >= COMPARATOR.compare(this, kind));
}
public int compareTo(Object other) {
return COMPARATOR.compare(this, other);
}
private final int precedence;
private final String name;
private Kind(String name, int precedence) {
this.name = name;
this.precedence = precedence;
}
public String toString() {
return name;
}
}
/**
* @return Detailed information about the message. For example, for declare
* error/warning messages this returns information about the corresponding
* join point's static part.
*/
public String getDetails();
}
|
41,952
|
Bug 41952 XLint warning for call PCD's using subtype of defining type
| null |
resolved fixed
|
97ab1e9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-07T17:00:52Z
| 2003-08-26T09:26:40Z
|
bridge/src/org/aspectj/bridge/Message.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.bridge;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.InvocationTargetException;
/**
* Implement messages.
* This implementation is immutable if ISourceLocation is immutable.
*/
public class Message implements IMessage { // XXX toString or renderer?
private final String message;
private final IMessage.Kind kind;
private final Throwable thrown;
private final ISourceLocation sourceLocation;
private final String details;
/** convenience for constructing failure messages */
public static Message fail(String message, Throwable thrown) {
return new Message(message, IMessage.FAIL, thrown, null);
}
/**
* Create a (compiler) error or warning message
* @param message the String used as the underlying message
* @param sourceLocation the ISourceLocation, if any, associated with this message
* @param isError if true, use IMessage.ERROR; else use IMessage.WARNING
*/
public Message(String message, ISourceLocation location, boolean isError) {
this(message, (isError ? IMessage.ERROR : IMessage.WARNING), null,
location);
}
/**
* Create a message, handling null values for message and kind
* if thrown is not null.
* @param message the String used as the underlying message
* @param kind the IMessage.Kind of message - not null
* @param thrown the Throwable, if any, associated with this message
* @param sourceLocation the ISourceLocation, if any, associated with this message
* @param details descriptive information about the message
* @throws IllegalArgumentException if message is null and
* thrown is null or has a null message, or if kind is null
* and thrown is null.
*/
public Message(String message, String details, IMessage.Kind kind,
ISourceLocation sourceLocation) {
this.details = details;
this.message = message;
this.kind = kind;
this.sourceLocation = sourceLocation;
this.thrown = null;
if (null == message) {
if (null != thrown) {
message = thrown.getMessage();
}
if (null == message) {
throw new IllegalArgumentException("null message");
}
}
if (null == kind) {
throw new IllegalArgumentException("null kind");
}
}
/**
* Create a message, handling null values for message and kind
* if thrown is not null.
* @param message the String used as the underlying message
* @param kind the IMessage.Kind of message - not null
* @param thrown the Throwable, if any, associated with this message
* @param sourceLocation the ISourceLocation, if any, associated with this message
* @throws IllegalArgumentException if message is null and
* thrown is null or has a null message, or if kind is null
* and thrown is null.
*/
public Message(String message, IMessage.Kind kind, Throwable thrown,
ISourceLocation sourceLocation) {
this.message = message;
this.kind = kind;
this.thrown = thrown;
this.sourceLocation = sourceLocation;
this.details = "";
if (null == message) {
if (null != thrown) {
message = thrown.getMessage();
}
if (null == message) {
throw new IllegalArgumentException("null message");
}
}
if (null == kind) {
throw new IllegalArgumentException("null kind");
}
}
/** @return the kind of this message */
public IMessage.Kind getKind() {
return kind;
}
/** @return true if kind == IMessage.ERROR */
public boolean isError() {
return kind == IMessage.ERROR;
}
/** @return true if kind == IMessage.WARNING */
public boolean isWarning() {
return kind == IMessage.WARNING;
}
/** @return true if kind == IMessage.DEBUG */
public boolean isDebug() {
return kind == IMessage.DEBUG;
}
/**
* @return true if kind == IMessage.INFO
*/
public boolean isInfo() {
return kind == IMessage.INFO;
}
/** @return true if kind == IMessage.ABORT */
public boolean isAbort() {
return kind == IMessage.ABORT;
}
/**
* @return true if kind == IMessage.FAIL
*/
public boolean isFailed() {
return kind == IMessage.FAIL;
}
/** @return non-null String with simple message */
final public String getMessage() {
return message;
}
/** @return Throwable associated with this message, or null if none */
final public Throwable getThrown() {
return thrown;
}
/** @return ISourceLocation associated with this message, or null if none */
final public ISourceLocation getSourceLocation() {
return sourceLocation;
}
public String toString() {
return Message.renderToString(this);
}
public static String renderToString(IMessage message) {
ISourceLocation loc = message.getSourceLocation();
String locString = (null == loc ? "" : " at " + loc);
Throwable thrown = message.getThrown();
return message.getKind() + locString + ": " + message.getMessage()
+ (null == thrown ? "" : render(thrown));
}
public static String render(Throwable thrown) { // XXX cf LangUtil.debugStr
if (null == thrown) return "null throwable";
Throwable t = null;
if (thrown instanceof InvocationTargetException) {
t = ((InvocationTargetException)thrown).getTargetException();
} else if (thrown instanceof ClassNotFoundException) {
t = ((ClassNotFoundException) thrown).getException();
}
if (null != t) {
return render(t);
}
StringWriter buf = new StringWriter();
PrintWriter writer = new PrintWriter(buf);
writer.println(" Message rendering thrown=" + thrown.getClass().getName());
writer.println(thrown.getMessage());
thrown.printStackTrace(writer);
try { buf.close(); }
catch (IOException ioe) {}
return buf.getBuffer().toString();
}
public String getDetails() {
return details;
}
}
|
41,952
|
Bug 41952 XLint warning for call PCD's using subtype of defining type
| null |
resolved fixed
|
97ab1e9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-07T17:00:52Z
| 2003-08-26T09:26:40Z
|
bridge/src/org/aspectj/bridge/MessageUtil.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.bridge;
import java.io.*;
import java.util.*;
import org.aspectj.bridge.IMessage.Kind;
import org.aspectj.util.*;
/**
* Convenience API's for constructing, printing, and sending messages.
*/
public class MessageUtil {
// ------ some constant, content-less messages
// no variants for "info" or "debug", which should always have content
public static final IMessage ABORT_NOTHING_TO_RUN
= new Message("aborting - nothing to run", IMessage.ABORT, null, null);
public static final IMessage FAIL_INCOMPLETE
= new Message("run not completed", IMessage.FAIL, null, null);
public static final IMessage ABORT_NOMESSAGE
= new Message("", IMessage.ABORT, null, null);
public static final IMessage FAIL_NOMESSAGE
= new Message("", IMessage.FAIL, null, null);
public static final IMessage ERROR_NOMESSAGE
= new Message("", IMessage.ERROR, null, null);
public static final IMessage WARNING_NOMESSAGE
= new Message("", IMessage.WARNING, null, null);
/** handle abort message (ignored if handler is null) */
public static boolean abort(IMessageHandler handler, String message) {
return ((null != handler)
&& handler.handleMessage(abort(message)));
}
/** create and handle exception message (ignored if handler is null) */
public static boolean abort(IMessageHandler handler, String message, Throwable t) {
if (handler != null) return handler.handleMessage(abort(message, t));
return false;
}
/** create and handle fail message (ignored if handler is null) */
public static boolean fail(IMessageHandler handler, String message) {
return ((null != handler)
&& handler.handleMessage(fail(message)));
}
/** create and handle fail message from reader (ignored if handler is null) */
public static boolean fail(IMessageHandler handler, String message, LineReader reader) {
return ((null != handler)
&& handler.handleMessage(fail(message, reader)));
}
/** create and handle fail message (ignored if handler is null) */
public static boolean fail(IMessageHandler handler, String message, Throwable thrown) {
return ((null != handler)
&& handler.handleMessage(fail(message, thrown)));
}
/** create and handle error message (ignored if handler is null) */
public static boolean error(IMessageHandler handler, String message) {
return ((null != handler)
&& handler.handleMessage(error(message)));
}
/** create and handle warn message (ignored if handler is null) */
public static boolean warn(IMessageHandler handler, String message) {
return ((null != handler)
&& handler.handleMessage(warn(message)));
}
/** create and handle debug message (ignored if handler is null) */
public static boolean debug(IMessageHandler handler, String message) {
return ((null != handler)
&& handler.handleMessage(debug(message)));
}
/** create and handle info message (ignored if handler is null) */
public static boolean info(IMessageHandler handler, String message) {
return ((null != handler)
&& handler.handleMessage(info(message)));
}
/** @return ABORT_NOMESSAGE if message is empty or IMessage otherwise */ //
public static IMessage abort(String message) {
if (LangUtil.isEmpty(message)) {
return ABORT_NOMESSAGE;
} else {
return new Message(message, IMessage.ABORT, null, null);
}
}
/** @return abort IMessage with thrown and message o
* ABORT_NOMESSAGE if both are empty/null */ //
public static IMessage abort(String message, Throwable thrown) {
if (!LangUtil.isEmpty(message)) {
return new Message(message, IMessage.ABORT, thrown, null);
} else if (null == thrown) {
return ABORT_NOMESSAGE;
} else {
return new Message(thrown.getMessage(), IMessage.ABORT, thrown, null);
}
}
/** @return FAIL_NOMESSAGE if message is empty or IMessage otherwise */
public static IMessage fail(String message) {
if (LangUtil.isEmpty(message)) {
return FAIL_NOMESSAGE;
} else {
return fail(message, (LineReader) null);
}
}
/**
* Create fail message.
* If message is empty but thrown is not, use thrown.getMessage() as the message.
* If message is empty and thrown is null, return FAIL_NOMESSAGE.
* @return FAIL_NOMESSAGE if thrown is null and message is empty
* or IMessage FAIL with message and thrown otherwise
*/
public static IMessage fail(String message, Throwable thrown) {
if (LangUtil.isEmpty(message)) {
if (null == thrown) {
return FAIL_NOMESSAGE;
} else {
return new Message(thrown.getMessage(), IMessage.FAIL, thrown, null);
}
} else {
return new Message(message, IMessage.FAIL, thrown, null);
}
}
/**
* @return IMessage with IMessage.Kind FAIL and message as text
* and soure location from reader
*/
public static IMessage fail(String message, LineReader reader) {
ISourceLocation loc = null;
if (null == reader) {
loc = ISourceLocation.EMPTY;
} else {
int line = (null == reader ? 0 : reader.getLineNumber());
if (0 < line) {
line = 0;
}
loc = new SourceLocation(reader.getFile(), line, line, 0);
}
return new Message(message, IMessage.FAIL, null, loc);
}
/** @return ERROR_NOMESSAGE if message is empty or IMessage otherwise */ //
public static IMessage error(String message, ISourceLocation location) {
if (LangUtil.isEmpty(message)) {
return ERROR_NOMESSAGE;
} else {
return new Message(message, IMessage.ERROR, null, location);
}
}
/** @return ERROR_NOMESSAGE if message is empty or IMessage otherwise */ //
public static IMessage error(String message) {
if (LangUtil.isEmpty(message)) {
return ERROR_NOMESSAGE;
} else {
return new Message(message, IMessage.ERROR, null, null);
}
}
/** @return WARNING_NOMESSAGE if message is empty or IMessage otherwise */ //
public static IMessage warn(String message) {
if (LangUtil.isEmpty(message)) {
return WARNING_NOMESSAGE;
} else {
return new Message(message, IMessage.WARNING, null, null);
}
}
/** @return IMessage.DEBUG message with message content */
public static IMessage debug(String message) {
return new Message(message, IMessage.DEBUG, null, null);
}
/** @return IMessage.INFO message with message content */
public static IMessage info(String message) {
return new Message(message, IMessage.INFO, null, null);
}
/** @return ISourceLocation with the current File/line of the reader */
public static ISourceLocation makeSourceLocation(LineReader reader) {
LangUtil.throwIaxIfNull(reader, "reader");
int line = reader.getLineNumber();
if (0 < line) {
line = 0;
}
return new SourceLocation(reader.getFile(), line, line, 0);
}
// ------------------------ printing messages
/**
* Print total counts message to the print stream, starting each on a new line
* @param messageHolder
* @param out
*/
public static void printMessageCounts(PrintStream out, IMessageHolder messageHolder) {
if ((null == out) || (null == messageHolder)) {
return;
}
printMessageCounts(out, messageHolder, "");
}
public static void printMessageCounts(PrintStream out, IMessageHolder holder, String prefix) {
out.println(prefix + "MessageHolder: " + MessageUtil.renderCounts(holder));
}
/**
* Print all message to the print stream, starting each on a new line
* @param messageHolder
* @param out
* @see #print(PrintStream, String, IMessageHolder, IMessageRenderer, IMessageHandler)
*/
public static void print(PrintStream out, IMessageHolder messageHolder) {
print(out, messageHolder, (String) null, (IMessageRenderer) null, (IMessageHandler) null);
}
/**
* Print all message to the print stream, starting each on a new line,
* with a prefix.
* @param messageHolder
* @param out
* @see #print(PrintStream, String, IMessageHolder, IMessageRenderer, IMessageHandler)
*/
public static void print(PrintStream out, IMessageHolder holder, String prefix) {
print(out, holder, prefix, (IMessageRenderer) null, (IMessageHandler) null);
}
/**
* Print all message to the print stream, starting each on a new line,
* with a prefix and using a renderer.
* @param messageHolder
* @param out
* @param renderer IMessageRender to render result - use MESSAGE_LINE if null
* @see #print(PrintStream, String, IMessageHolder, IMessageRenderer, IMessageHandler)
*/
public static void print(PrintStream out, IMessageHolder holder, String prefix,
IMessageRenderer renderer) {
print(out, holder, prefix, renderer, (IMessageHandler) null);
}
/**
* Print all message to the print stream, starting each on a new line,
* with a prefix and using a renderer.
* The first line renders a summary: {prefix}MessageHolder: {summary}
* Each message line has the following form:
* <pre>{prefix}[{kind} {index}]: {rendering}</pre>
* (where "{index}" (length 3) is the position within
* the set of like-kinded messages, ignoring selector omissions.
* Renderers are free to render multi-line output.
* @param out the PrintStream sink - return silently if null
* @param messageHolder the IMessageHolder with the messages to print
* @param renderer IMessageRender to render result - use MESSAGE_ALL if null
* @param selector IMessageHandler to select messages to render - if null, do all non-null
*/
public static void print(PrintStream out, IMessageHolder holder, String prefix,
IMessageRenderer renderer, IMessageHandler selector) {
print(out, holder, prefix, renderer, selector, true);
}
public static void print(PrintStream out, IMessageHolder holder, String prefix,
IMessageRenderer renderer, IMessageHandler selector, boolean printSummary) {
if ((null == out) || (null == holder)) {
return;
}
if (null == renderer) {
renderer = MESSAGE_ALL;
}
if (null == selector) {
selector = PICK_ALL;
}
if (printSummary) {
out.println(prefix + "MessageHolder: " + MessageUtil.renderCounts(holder));
}
for (Iterator iter = IMessage.KINDS.iterator(); iter.hasNext();) {
IMessage.Kind kind = (IMessage.Kind) iter.next();
if (!selector.isIgnoring(kind)) {
IMessage[] messages = holder.getMessages(kind, IMessageHolder.EQUAL);
for (int i = 0; i < messages.length; i++) {
if (selector.handleMessage(messages[i])) {
String label = (null == prefix
? ""
: prefix + "[" + kind + " " + LangUtil.toSizedString(i, 3) + "]: ");
out.println(label + renderer.renderToString(messages[i]));
}
}
}
}
}
public static String toShortString(IMessage message) {
if (null == message) {
return "null";
}
String m = message.getMessage();
Throwable t = message.getThrown();
return (message.getKind() + (null == m ? "" : ": " + m)
+ (null == t ? "" : ": " + LangUtil.unqualifiedClassName(t)));
}
/** @return int number of message of this kind (optionally or greater) in list */
public static int numMessages(ArrayList messages, Kind kind, boolean orGreater) {
if (LangUtil.isEmpty(messages)) {
return 0;
}
IMessageHandler selector = makeSelector(kind, orGreater, null);
IMessage[] result = visitMessages(messages, selector, true, false);
return result.length;
}
/**
* Select all messages in holder except those of the same
* kind (optionally or greater).
* If kind is null, then all messages are rejected,
* so an empty list is returned.
* @return unmodifiable list of specified IMessage
*/
public static IMessage[] getMessagesExcept(IMessageHolder holder,
final IMessage.Kind kind, final boolean orGreater) {
if ((null == holder) || (null == kind)) {
return new IMessage[0];
}
IMessageHandler selector = new IMessageHandler(){
public boolean handleMessage(IMessage message) {
IMessage.Kind test = message.getKind();
return (!(orGreater
? kind.isSameOrLessThan(test)
: kind == test));
}
public boolean isIgnoring(Kind kind) {
return false;
}
};
return visitMessages(holder, selector, true, false);
}
/** @return unmodifiable list of IMessage complying with parameters */
public static List getMessages(IMessageHolder holder,
IMessage.Kind kind, boolean orGreater, String infix) { // XXX untested
if (null == holder) {
return Collections.EMPTY_LIST;
}
if ((null == kind) && LangUtil.isEmpty(infix)) {
return holder.getUnmodifiableListView();
}
IMessageHandler selector = makeSelector(kind, orGreater, infix);
IMessage[] messages = visitMessages(holder, selector, true, false);
if (LangUtil.isEmpty(messages)) {
return Collections.EMPTY_LIST;
}
return Collections.unmodifiableList(Arrays.asList(messages));
}
/**
* Extract messages of type kind from the input list.
*
* @param messages if null, return EMPTY_LIST
* @param kind if null, return messages
* @see MessageHandler#getMessages(Kind)
*/
public static List getMessages(List messages, IMessage.Kind kind) {
if (null == messages) {
return Collections.EMPTY_LIST;
}
if (null == kind) {
return messages;
}
ArrayList result = new ArrayList();
for (Iterator iter = messages.iterator(); iter.hasNext();) {
IMessage element = (IMessage) iter.next();
if (kind == element.getKind()) {
result.add(element);
}
}
if (0 == result.size()) {
return Collections.EMPTY_LIST;
}
return result;
}
/**
* Map to the kind of messages associated with this string key.
* @param kind the String representing the kind of message (IMessage.Kind.toString())
* @return Kind the associated IMessage.Kind, or null if not found
*/
public static IMessage.Kind getKind(String kind) {
if (null != kind) {
kind = kind.toLowerCase();
for (Iterator iter = IMessage.KINDS.iterator(); iter.hasNext();) {
IMessage.Kind k = (IMessage.Kind) iter.next();
if (kind.equals(k.toString())) {
return k;
}
}
}
return null;
}
/**
* Run visitor over the set of messages in holder,
* optionally accumulating those accepted by the visitor
*/
public static IMessage[] visitMessages(IMessageHolder holder,
IMessageHandler visitor, boolean accumulate, boolean abortOnFail) {
if (null == holder) {
return IMessage.RA_IMessage;
} else {
return visitMessages(holder.getUnmodifiableListView(), visitor, accumulate, abortOnFail);
}
}
/**
* Run visitor over the set of messages in holder,
* optionally accumulating those accepted by the visitor
*/
public static IMessage[] visitMessages(IMessage[] messages,
IMessageHandler visitor, boolean accumulate, boolean abortOnFail) {
if (LangUtil.isEmpty(messages)) {
return IMessage.RA_IMessage;
} else {
return visitMessages(Arrays.asList(messages), visitor, accumulate, abortOnFail);
}
}
/**
* Run visitor over a collection of messages,
* optionally accumulating those accepted by the visitor
* @param messages if null or empty, return IMessage.RA_IMessage
* @param visitor run visitor.handleMessage(message) on each
* message - if null and messages not empty, IllegalArgumentException
* @param accumulate if true, then return accepted IMessage[]
* @param abortOnFail if true and visitor returns false, stop visiting
* @return IMessage.RA_IMessage if collection is empty, if not accumulate,
* or if visitor accepted no IMessage,
* or IMessage[] of accepted messages otherwise
* @throws IllegalArgumentException if any in collection are not instanceof IMessage
*/
public static IMessage[] visitMessages(Collection /*IMessage*/ messages,
IMessageHandler visitor, final boolean accumulate, final boolean abortOnFail) {
if (LangUtil.isEmpty(messages)) {
return IMessage.RA_IMessage;
}
LangUtil.throwIaxIfNull(visitor, "visitor");
ArrayList result = (accumulate ? new ArrayList() : null);
for (Iterator iter = messages.iterator(); iter.hasNext();) {
Object o = iter.next();
LangUtil.throwIaxIfFalse(o instanceof IMessage, "expected IMessage, got " + o);
IMessage m = (IMessage) o;
if (visitor.handleMessage(m)) {
if (accumulate) {
result.add(m);
}
} else if (abortOnFail) {
break;
}
}
if (!accumulate || (0 == result.size())) {
return IMessage.RA_IMessage;
} else {
return (IMessage[]) result.toArray(IMessage.RA_IMessage);
}
}
/**
* Make an IMessageHandler that handles IMessage if they have the right kind
* (or greater) and contain some infix String.
* @param kind the IMessage.Kind required of the message
* @param orGreater if true, also accept messages with greater kinds, as
* defined by IMessage.Kind.COMPARATOR
* @param infix the String text to require in the message - may be null or empty
* to accept any message with the specified kind.
* @return IMessageHandler selector that works to param specs
*/
public static IMessageHandler makeSelector(IMessage.Kind kind, boolean orGreater, String infix) {
if (!orGreater && LangUtil.isEmpty(infix)) {
if (kind == IMessage.ABORT) {
return PICK_ABORT;
} else if (kind == IMessage.DEBUG) {
return PICK_DEBUG;
} else if (kind == IMessage.DEBUG) {
return PICK_DEBUG;
} else if (kind == IMessage.ERROR) {
return PICK_ERROR;
} else if (kind == IMessage.FAIL) {
return PICK_FAIL;
} else if (kind == IMessage.INFO) {
return PICK_INFO;
} else if (kind == IMessage.WARNING) {
return PICK_WARNING;
}
}
return new KindSelector(kind, orGreater, infix);
}
// ------------------ visitors to select messages
public static final IMessageHandler PICK_ALL = new KindSelector((IMessage.Kind) null);
public static final IMessageHandler PICK_ABORT = new KindSelector(IMessage.ABORT);
public static final IMessageHandler PICK_DEBUG = new KindSelector(IMessage.DEBUG);
public static final IMessageHandler PICK_ERROR = new KindSelector(IMessage.ERROR);
public static final IMessageHandler PICK_FAIL = new KindSelector(IMessage.FAIL);
public static final IMessageHandler PICK_INFO = new KindSelector(IMessage.INFO);
public static final IMessageHandler PICK_WARNING = new KindSelector(IMessage.WARNING);
public static final IMessageHandler PICK_ABORT_PLUS = new KindSelector(IMessage.ABORT, true);
public static final IMessageHandler PICK_DEBUG_PLUS = new KindSelector(IMessage.DEBUG, true);
public static final IMessageHandler PICK_ERROR_PLUS = new KindSelector(IMessage.ERROR, true);
public static final IMessageHandler PICK_FAIL_PLUS = new KindSelector(IMessage.FAIL, true);
public static final IMessageHandler PICK_INFO_PLUS = new KindSelector(IMessage.INFO, true);
public static final IMessageHandler PICK_WARNING_PLUS = new KindSelector(IMessage.WARNING, true);
/** implementation for PICK_... constants */
private static class KindSelector implements IMessageHandler {
final IMessage.Kind sought;
final boolean floor;
final String infix;
KindSelector(IMessage.Kind sought) {
this(sought, false);
}
KindSelector(IMessage.Kind sought, boolean floor) {
this(sought, floor, null);
}
KindSelector(IMessage.Kind sought, boolean floor, String infix) {
this.sought = sought;
this.floor = floor;
this.infix = (LangUtil.isEmpty(infix) ? null : infix);
}
/** @return false if this message is null,
* of true if we seek any kind (null)
* or if this has the exact kind we seek
* and this has any text sought
*/
public boolean handleMessage(IMessage message) {
return ((null != message) && !isIgnoring(message.getKind())
&& textIn(message));
}
/** @return true if handleMessage would return false for a message of this kind */
public boolean isIgnoring(IMessage.Kind kind) {
if (!floor) {
return ((null != sought) && (sought != kind));
} else if (null == sought) {
return false;
} else {
return (0 < IMessage.Kind.COMPARATOR.compare(sought, kind));
}
}
private boolean textIn(IMessage message) {
if (null == infix) {
return true;
}
String text = message.getMessage();
return ((null != message) && (-1 != text.indexOf(infix)));
}
}
// ------------------ components to render messages
/** parameterize rendering behavior for messages */
public static interface IMessageRenderer {
String renderToString(IMessage message);
}
/** render message more verbosely if it is worse */
public static final IMessageRenderer MESSAGE_SCALED = new IMessageRenderer() {
public String toString() { return "MESSAGE_SCALED"; }
public String renderToString(IMessage message) {
if (null == message) {
return "((IMessage) null)";
}
IMessage.Kind kind = message.getKind();
int level = 3;
if ((kind == IMessage.ABORT) || (kind == IMessage.FAIL)) {
level = 1;
} else if ((kind == IMessage.ERROR) || (kind == IMessage.WARNING)) {
level = 2;
} else {
level = 3;
}
String result = null;
switch (level) {
case (1) :
result = MESSAGE_TOSTRING.renderToString(message);
break;
case (2) :
result = MESSAGE_LINE.renderToString(message);
break;
case (3) :
result = MESSAGE_SHORT.renderToString(message);
break;
}
Throwable thrown = message.getThrown();
if (null != thrown) {
if (level == 3) {
result += "Thrown: \n" + LangUtil.renderExceptionShort(thrown);
} else {
result += "Thrown: \n" + LangUtil.renderException(thrown);
}
}
return result;
}
};
/** render message as label, i.e., less than 33 char */
public static final IMessageRenderer MESSAGE_LABEL = new IMessageRenderer() {
public String toString() { return "MESSAGE_LABEL"; }
public String renderToString(IMessage message) {
if (null == message) {
return "((IMessage) null)";
}
return renderMessageLine(message, 5, 5, 32);
}
};
/** render message as label, i.e., less than 33 char, with no source location */
public static final IMessageRenderer MESSAGE_LABEL_NOLOC = new IMessageRenderer() {
public String toString() { return "MESSAGE_LABEL_NOLOC"; }
public String renderToString(IMessage message) {
if (null == message) {
return "((IMessage) null)";
}
return renderMessageLine(message, 10, 0, 32);
}
};
/** render message as line, i.e., less than 75 char, no internal line sep */
public static final IMessageRenderer MESSAGE_LINE = new IMessageRenderer() {
public String toString() { return "MESSAGE_LINE"; }
public String renderToString(IMessage message) {
if (null == message) {
return "((IMessage) null)";
}
return renderMessageLine(message, 8, 2, 74);
}
};
/** render message as line, i.e., less than 75 char, no internal line sep,
* trying to trim text as needed to end with a full source location */
public static final IMessageRenderer MESSAGE_LINE_FORCE_LOC = new IMessageRenderer() {
public String toString() { return "MESSAGE_LINE_FORCE_LOC"; }
public String renderToString(IMessage message) {
if (null == message) {
return "((IMessage) null)";
}
return renderMessageLine(message, 2, 40, 74);
}
};
/** render message without restriction, up to 10K, including throwable */
public static final IMessageRenderer MESSAGE_ALL = new IMessageRenderer() {
public String toString() { return "MESSAGE_ALL"; }
public String renderToString(IMessage message) {
return renderMessage(message);
}
};
// /** render message without restriction, up to 10K, including (but eliding) throwable */
// public static final IMessageRenderer MESSAGE_ALL_ELIDED= new IMessageRenderer() {
// public String toString() { return "MESSAGE_ALL_ELIDED"; }
// public String renderToString(IMessage message) {
// return renderMessage(message, true);
// }
// };
/** render message without restriction, except any Throwable thrown */
public static final IMessageRenderer MESSAGE_MOST = new IMessageRenderer() {
public String toString() { return "MESSAGE_MOST"; }
public String renderToString(IMessage message) {
if (null == message) {
return "((IMessage) null)";
}
return renderMessageLine(message, 1, 1, 10000);
}
};
/** render message as wide line, i.e., less than 256 char, no internal line sep,
* except any Throwable thrown
*/
public static final IMessageRenderer MESSAGE_WIDELINE = new IMessageRenderer() {
public String toString() { return "MESSAGE_WIDELINE"; }
public String renderToString(IMessage message) {
if (null == message) {
return "((IMessage) null)";
}
return renderMessageLine(message, 8, 2, 255); // XXX revert to 256
}
};
/** render message using its toString() or "((IMessage) null)" */
public static final IMessageRenderer MESSAGE_TOSTRING = new IMessageRenderer() {
public String toString() { return "MESSAGE_TOSTRING"; }
public String renderToString(IMessage message) {
if (null == message) {
return "((IMessage) null)";
}
return message.toString();
}
};
/** render message using toShortString(IMessage)" */
public static final IMessageRenderer MESSAGE_SHORT = new IMessageRenderer() {
public String toString() { return "MESSAGE_SHORT"; }
public String renderToString(IMessage message) {
return toShortString(message);
}
};
/**
* This renders IMessage as String, ignoring empty elements
* and eliding any thrown stack traces.
* @return "((IMessage) null)" if null or String rendering otherwise,
* including everything (esp. throwable stack trace)
* @see renderSourceLocation(ISourceLocation loc)
*/
public static String renderMessage(IMessage message) {
return renderMessage(message, true);
}
/**
* This renders IMessage as String, ignoring empty elements
* and eliding any thrown.
* @return "((IMessage) null)" if null or String rendering otherwise,
* including everything (esp. throwable stack trace)
* @see renderSourceLocation(ISourceLocation loc)
*/
public static String renderMessage(IMessage message, boolean elide) {
if (null == message) {
return "((IMessage) null)";
}
StringBuffer result = new StringBuffer();
result.append(message.getKind().toString());
result.append(" ");
String messageString = message.getMessage();
if (!LangUtil.isEmpty(messageString)) {
result.append(messageString);
result.append(" ");
}
ISourceLocation loc = message.getSourceLocation();
if ((null != loc) && (loc != ISourceLocation.EMPTY)) {
result.append("at " + renderSourceLocation(loc));
}
Throwable thrown = message.getThrown();
if (null != thrown) {
result.append(" -- " + LangUtil.renderExceptionShort(thrown));
result.append("\n" + LangUtil.renderException(thrown, elide));
}
return result.toString();
}
/**
* Render ISourceLocation to String, ignoring empty elements
* (null or ISourceLocation.NO_FILE or ISourceLocation.NO_COLUMN
* (though implementations may return 0 from getColumn() when
* passed NO_COLUMN as input)).
* @return "((ISourceLocation) null)" if null or String rendering
* <pre>{file:}line{:column}</pre>
*
*/
public static String renderSourceLocation(ISourceLocation loc) {
if (null == loc) {
return "((ISourceLocation) null)";
}
StringBuffer sb = new StringBuffer();
File sourceFile = loc.getSourceFile();
if (sourceFile != ISourceLocation.NO_FILE) {
sb.append(sourceFile.getPath());
sb.append(":");
}
int line = loc.getLine();
sb.append("" + line);
int column = loc.getColumn();
if (column != ISourceLocation.NO_COLUMN) {
sb.append(":" + column);
}
return sb.toString();
}
/**
* Render message in a line.
* IMessage.Kind is always printed, then any unqualified exception class,
* then the remainder of text and location according to their relative scale,
* all to fit in max characters or less.
* This does not render thrown except for the unqualified class name
* @param max the number of characters - forced to 32..10000
* @param textScale relative proportion to spend on message and/or exception
* message, relative to source location - if 0, message is suppressed
* @param locScale relative proportion to spend on source location
* suppressed if 0
* @return "((IMessage) null)" or message per spec
*/
public static String renderMessageLine(
IMessage message,
int textScale,
int locScale,
int max) {
if (null == message) {
return "((IMessage) null)";
}
if (max < 32) {
max = 32;
} else if (max > 10000) {
max = 10000;
}
if (0 > textScale) {
textScale = -textScale;
}
if (0 > locScale) {
locScale = -locScale;
}
String text = message.getMessage();
Throwable thrown = message.getThrown();
ISourceLocation sl = message.getSourceLocation();
IMessage.Kind kind = message.getKind();
StringBuffer result = new StringBuffer();
result.append(kind.toString());
result.append(": ");
if (null != thrown) {
result.append(LangUtil.unqualifiedClassName(thrown) + " ");
if ((null == text) || ("".equals(text))) {
text = thrown.getMessage();
}
}
if (0 == textScale) {
text = "";
} else if ((null != text) && (null != thrown)) {
// decide between message and exception text?
String s = thrown.getMessage();
if ((null != s) && (0 < s.length())) {
text += " - " + s;
}
}
String loc = "";
if ((0 != locScale) && (null != sl)) {
File f = sl.getSourceFile();
if (f == ISourceLocation.NO_FILE) {
f = null;
}
if (null != f) {
loc = f.getName();
}
int line = sl.getLine();
int col = sl.getColumn();
int end = sl.getEndLine();
if ((0 == line) && (0 == col) && (0 == end)) {
// ignore numbers if default
} else {
loc += ":" + line + (col == 0 ? "" : ":" + col);
if (line != end) { // XXX consider suppressing nonstandard...
loc += ":" + end;
}
}
if (!LangUtil.isEmpty(loc)) {
loc = "@[" + loc; // matching "]" added below after clipping
}
}
// now budget between text and loc
float totalScale = locScale + textScale;
float remainder = max - result.length() - 4;
if ((remainder > 0) && (0 < totalScale)) {
int textSize = (int) (remainder * textScale/totalScale);
int locSize = (int) (remainder * locScale/totalScale);
// adjust for underutilization
int extra = locSize - loc.length();
if (0 < extra) {
locSize = loc.length();
textSize += extra;
}
extra = textSize - text.length();
if (0 < extra) {
textSize = text.length();
if (locSize < loc.length()) {
locSize += extra;
}
}
if (locSize > loc.length()) {
locSize = loc.length();
}
if (textSize > text.length()) {
textSize = text.length();
}
if (0 < textSize) {
result.append(text.substring(0, textSize));
}
if (0 < locSize) {
if (0 < textSize) {
result.append(" ");
}
result.append(loc.substring(0, locSize) + "]");
}
}
return result.toString();
}
/** @return String of the form "{(# {type}) }.." for message kinds, skipping 0 */
public static String renderCounts(IMessageHolder holder) {
if (0 == holder.numMessages(null, false)) {
return "(0 messages)";
}
StringBuffer sb = new StringBuffer();
for (Iterator iter = IMessage.KINDS.iterator(); iter.hasNext();) {
IMessage.Kind kind = (IMessage.Kind) iter.next();
int num = holder.numMessages(kind, false);
if (0 < num) {
sb.append(" (" + num + " " + kind + ") ");
}
}
return sb.toString();
}
/**
* Factory for handler adapted to PrintStream
* XXX weak - only handles println(String)
* @param handler the IMessageHandler sink for the messages generated
* @param kind the IMessage.Kind of message to create
* @param overage the OuputStream for text not captured by the handler
* (if null, System.out used)
* @throws IllegalArgumentException if kind or handler is null
*/
public static PrintStream handlerPrintStream(final IMessageHandler handler,
final IMessage.Kind kind, final OutputStream overage, final String prefix) {
LangUtil.throwIaxIfNull(handler, "handler");
LangUtil.throwIaxIfNull(kind, "kind");
class HandlerPrintStream extends PrintStream {
HandlerPrintStream() {
super(null == overage ? System.out : overage);
}
public void println() {
println("");
}
public void println(Object o) {
println(null == o ? "null" : o.toString());
}
public void println(String input) {
String textMessage = (null == prefix ? input : prefix + input);
IMessage m = new Message(textMessage, kind, null, null);
handler.handleMessage(m);
}
}
return new HandlerPrintStream();
}
/** utility class */
private MessageUtil() {}
/**
* Handle all messages in the second handler using the first
* @param handler the IMessageHandler sink for all messages in source
* @param holder the IMessageHolder source for all messages to handle
* @param fastFail if true, stop on first failure
* @return false if any sink.handleMessage(..) failed
*/
public static boolean handleAll(
IMessageHandler sink,
IMessageHolder source,
boolean fastFail) {
return handleAll(sink, source, null, true, fastFail);
}
/**
* Handle messages in the second handler using the first
* @param handler the IMessageHandler sink for all messages in source
* @param holder the IMessageHolder source for all messages to handle
* @param kind the IMessage.Kind to select, if not null
* @param orGreater if true, also accept greater kinds
* @param fastFail if true, stop on first failure
* @return false if any sink.handleMessage(..) failed
*/
public static boolean handleAll(
IMessageHandler sink,
IMessageHolder source,
IMessage.Kind kind,
boolean orGreater,
boolean fastFail) {
LangUtil.throwIaxIfNull(sink, "sink");
LangUtil.throwIaxIfNull(source, "source");
return handleAll(sink, source.getMessages(kind, orGreater), fastFail);
}
/**
* Handle messages in the second handler using the first
* if they are NOT of this kind (optionally, or greater).
* If you pass null as the kind, then all messages are
* ignored and this returns true.
* @param handler the IMessageHandler sink for all messages in source
* @param holder the IMessageHolder source for all messages to handle
* @param kind the IMessage.Kind to reject, if not null
* @param orGreater if true, also reject greater kinds
* @param fastFail if true, stop on first failure
* @return false if any sink.handleMessage(..) failed
*/
public static boolean handleAllExcept(
IMessageHandler sink,
IMessageHolder source,
IMessage.Kind kind,
boolean orGreater,
boolean fastFail) {
LangUtil.throwIaxIfNull(sink, "sink");
LangUtil.throwIaxIfNull(source, "source");
if (null == kind) {
return true;
}
IMessage[] messages = getMessagesExcept(source, kind, orGreater);
return handleAll(sink, messages, fastFail);
}
/**
* Handle messages in the sink.
* @param handler the IMessageHandler sink for all messages in source
* @param sources the IMessage[] messages to handle
* @param fastFail if true, stop on first failure
* @return false if any sink.handleMessage(..) failed
* @throws IllegalArgumentException if sink is null
*/
public static boolean handleAll(
IMessageHandler sink,
IMessage[] sources,
boolean fastFail) {
LangUtil.throwIaxIfNull(sink, "sink");
if (LangUtil.isEmpty(sources)) {
return true;
}
boolean result = true;
for (int i = 0; i < sources.length; i++) {
if (!sink.handleMessage(sources[i])) {
if (fastFail) {
return false;
}
if (result) {
result = false;
}
}
}
return result;
}
}
|
41,952
|
Bug 41952 XLint warning for call PCD's using subtype of defining type
| null |
resolved fixed
|
97ab1e9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-07T17:00:52Z
| 2003-08-26T09:26:40Z
|
bridge/src/org/aspectj/bridge/SourceLocation.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.bridge;
import java.io.File;
import org.aspectj.util.LangUtil;
/**
* Immutable source location.
* This guarantees that the source file is not null
* and that the numeric values are positive and line <= endLine.
* @see org.aspectj.lang.reflect.SourceLocation
* @see org.aspectj.compiler.base.parser.SourceInfo
* @see org.aspectj.tools.ide.SourceLine
* @see org.aspectj.testing.harness.ErrorLine
*/
public class SourceLocation implements ISourceLocation, java.io.Serializable {
/** used when SourceLocation is not available */
public static final ISourceLocation UNKNOWN
= new SourceLocation(ISourceLocation.NO_FILE, 0, 0, 0);
/** @throws IllegalArgumentException if the input would not be a valid line */
public static final void validLine(int line) {
if (line < 0) {
throw new IllegalArgumentException("negative line: " + line);
} else if (line > ISourceLocation.MAX_LINE) {
throw new IllegalArgumentException("line too large: " + line);
}
}
/** @throws IllegalArgumentException if the input would not be a valid column */
public static final void validColumn(int column) {
if (column < 0) {
throw new IllegalArgumentException("negative column: " + column);
} else if (column > ISourceLocation.MAX_COLUMN) {
throw new IllegalArgumentException("column too large: " + column);
}
}
private final File sourceFile;
private final int startLine;
private final int column;
private final int endLine;
private final String context;
private boolean noColumn;
/**
* Same as SourceLocation(file, line, line, 0),
* except that column is not rendered during toString()
*/
public SourceLocation(File file, int line) {
this(file, line, line, NO_COLUMN);
}
/** same as SourceLocation(file, line, endLine, ISourceLocation.NO_COLUMN) */
public SourceLocation(File file, int line, int endLine) {
this(file, line, endLine, ISourceLocation.NO_COLUMN);
}
/**
* @param file File of the source; if null, use ISourceLocation.NO_FILE, not null
* @param line int starting line of the location - positive number
* @param endLine int ending line of the location - <= starting line
* @param column int character position of starting location - positive number
*/
public SourceLocation(File file, int line, int endLine, int column) {
this(file, line, endLine, column, (String) null);
}
public SourceLocation(File file, int line, int endLine, int column, String context) {
if (column == NO_COLUMN) {
column = 0;
noColumn = true;
}
if (null == file) {
file = ISourceLocation.NO_FILE;
}
validLine(line);
validLine(endLine);
LangUtil.throwIaxIfFalse(line <= endLine , line + " > " + endLine);
LangUtil.throwIaxIfFalse(column >= 0, "negative column: " + column);
this.sourceFile = file;
this.startLine = line;
this.column = column;
this.endLine = endLine;
this.context = context;
}
public File getSourceFile() {
return sourceFile;
}
public int getLine() {
return startLine;
}
/**
* @return int actual column or 0 if not available per constructor treatment
* of ISourceLocation.NO_COLUMN
*/
public int getColumn() {
return column;
}
public int getEndLine() {
return endLine;
}
/** @return null String or application-specific context */
public String getContext() {
return context;
}
/** @return String {context\n}{file:}line{:column} */
public String toString() {
StringBuffer sb = new StringBuffer();
if (null != context) {
sb.append(context);
sb.append(LangUtil.EOL);
}
if (sourceFile != ISourceLocation.NO_FILE) {
sb.append(sourceFile.getPath());
sb.append(":");
}
sb.append("" + startLine + "-" + endLine);
if (!noColumn) {
sb.append(":" + column);
}
return sb.toString();
}
}
|
41,952
|
Bug 41952 XLint warning for call PCD's using subtype of defining type
| null |
resolved fixed
|
97ab1e9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-07T17:00:52Z
| 2003-08-26T09:26:40Z
|
org.aspectj.ajdt.core/src/org/aspectj/tools/ajc/Main.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.tools.ajc;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.List;
import org.aspectj.bridge.AbortException;
import org.aspectj.bridge.ICommand;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.IMessageHandler;
import org.aspectj.bridge.IMessageHolder;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.Message;
import org.aspectj.bridge.MessageHandler;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.bridge.ReflectionFactory;
import org.aspectj.bridge.Version;
import org.aspectj.util.FileUtil;
import org.aspectj.util.LangUtil;
/**
* Programmatic and command-line interface to AspectJ compiler.
* The compiler is an ICommand obtained by reflection.
* Not thread-safe.
* By default, messages are printed as they are emitted;
* info messages go to the output stream, and
* warnings and errors go to the error stream.
* <p>
* Clients can handle all messages by registering a holder:
* <pre>Main main = new Main();
* IMessageHolder holder = new MessageHandler();
* main.setHolder(holder);</pre>
* Clients can get control after each command completes
* by installing a Runnable:
* <pre>main.setCompletionRunner(new Runnable() {..});</pre>
*
*/
public class Main {
/** Header used when rendering exceptions for users */
public static final String THROWN_PREFIX
= "Exception thrown from AspectJ "+ Version.text + LangUtil.EOL
+ ""+ LangUtil.EOL
+ "This might be logged as a bug already -- find current bugs at" + LangUtil.EOL
+ " http://bugs.eclipse.org/bugs/buglist.cgi?product=AspectJ&component=Compiler" + LangUtil.EOL
+ "" + LangUtil.EOL
+ "Bugs for exceptions thrown have titles File:line from the top stack, " + LangUtil.EOL
+ "e.g., \"SomeFile.java:243\"" + LangUtil.EOL
+ "" + LangUtil.EOL
+ "If you don't find the exception below in a bug, please add a new bug" + LangUtil.EOL
+ "at http://bugs.eclipse.org/bugs/enter_bug.cgi?product=AspectJ" + LangUtil.EOL
+ "To make the bug a priority, please include a test program" + LangUtil.EOL
+ "that can reproduce this exception." + LangUtil.EOL;
/** @param args the String[] of command-line arguments */
public static void main(String[] args) throws IOException {
new Main().runMain(args, true);
}
/**
* @return String rendering throwable as compiler error for user/console,
* including information on how to report as a bug.
* @throws NullPointerException if thrown is null
*/
public static String renderExceptionForUser(Throwable thrown) {
String m = thrown.getMessage();
return THROWN_PREFIX
+ (null != m ? m + "\n": "")
+ LangUtil.renderException(thrown, true);
}
/** append nothing if numItems is 0,
* numItems + label + (numItems > 1? "s" : "") otherwise,
* prefixing with " " if sink has content
*/
private static void appendNLabel(StringBuffer sink, String label, int numItems) {
if (0 == numItems) {
return;
}
if (0 < sink.length()) {
sink.append(", ");
}
sink.append(numItems + " ");
if (!LangUtil.isEmpty(label)) {
sink.append(label);
}
if (1 < numItems) {
sink.append("s");
}
}
/** control iteration/continuation for command (compiler) */
protected CommandController controller;
/** ReflectionFactory identifier for command (compiler) */
protected String commandName;
/** client-set message sink */
private IMessageHolder clientHolder;
/** internally-set message sink */
protected final MessageHandler ourHandler;
private int lastFails;
private int lastErrors;
/** if not null, run this synchronously after each compile completes */
private Runnable completionRunner;
public Main() {
controller = new CommandController();
commandName = ReflectionFactory.ECLIPSE;
ourHandler = new MessageHandler(true);
}
/**
* Run without throwing exceptions but optionally using System.exit(..).
* This sets up a message handler which emits messages immediately,
* so report(boolean, IMessageHandler) only reports total number
* of errors or warnings.
* @param args the String[] command line for the compiler
* @param useSystemExit if true, use System.exit(int) to complete
* unless one of the args is -noExit.
* and signal result (0 no exceptions/error, <0 exceptions, >0 compiler errors).
*/
public void runMain(String[] args, boolean useSystemExit) {
boolean verbose = (-1 != ("" + LangUtil.arrayAsList(args)).indexOf("-verbose"));
IMessageHolder holder = clientHolder;
if (null == holder) {
holder = ourHandler;
if (verbose) {
ourHandler.setInterceptor(MessagePrinter.VERBOSE);
} else {
ourHandler.ignore(IMessage.INFO);
ourHandler.setInterceptor(MessagePrinter.TERSE);
}
}
run(args, holder);
boolean skipExit = false;
if (useSystemExit && !LangUtil.isEmpty(args)) { // sigh - pluck -noExit
for (int i = 0; i < args.length; i++) {
if ("-noExit".equals(args[i])) {
skipExit = true;
break;
}
}
}
if (useSystemExit && !skipExit) {
systemExit(holder);
}
}
/**
* Run without using System.exit(..), putting all messages in holder:
* <ul>
* <li>ERROR: compiler error</li>
* <li>WARNING: compiler warning</li>
* <li>FAIL: command error (bad arguments, exception thrown)</li>
* </ul>
* This handles incremental behavior:
* <ul>
* <li>If args include "-incremental", repeat for every input char
* until 'q' is entered.<li>
* <li>If args include "-incrementalTagFile {file}", repeat every time
* we detect that {file} modification time has changed. </li>
* <li>Either way, list files recompiled each time if args includes "-verbose".</li>
* <li>Exit when the commmand/compiler throws any Throwable.</li>
* </ul>
* When complete, this contains all the messages of the final
* run of the command and/or any FAIL messages produced in running
* the command, including any Throwable thrown by the command itself.
*
* @param args the String[] command line for the compiler
* @param holder the MessageHandler sink for messages.
*/
public void run(String[] args, IMessageHolder holder) {
if (LangUtil.isEmpty(args)) {
args = new String[] { "-help" };
} else if (Arrays.asList(args).contains("-version")) {
System.out.println("AspectJ Compiler " + Version.text);
System.out.println();
return;
} else if (controller.running()) {
fail(holder, "already running with controller: " + controller, null);
return;
}
args = controller.init(args, holder);
if (0 < holder.numMessages(IMessage.ERROR, true)) {
return;
}
ICommand command = ReflectionFactory.makeCommand(commandName, holder);
if (0 < holder.numMessages(IMessage.ERROR, true)) {
return;
}
try {
boolean verbose = (-1 != ("" + Arrays.asList(args)).indexOf("-verbose"));
outer:
while (true) {
boolean passed = command.runCommand(args, holder);
if (report(passed, holder) && controller.incremental()) {
final boolean onCommandLine = controller.commandLineIncremental();
while (controller.doRepeatCommand()) {
holder.clearMessages();
if (controller.buildFresh()) {
continue outer;
} else {
passed = command.repeatCommand(holder);
}
if (!report(passed, holder)) {
break;
}
}
}
break;
}
} catch (AbortException ae) {
if (ae.isSilent()) {
quit();
} else {
IMessage message = ae.getIMessage();
Throwable thrown = ae.getThrown();
if (null == thrown) { // toss AbortException wrapper
if (null != message) {
holder.handleMessage(message);
} else {
fail(holder, "abort without message", ae);
}
} else if (null == message) {
fail(holder, "aborted", thrown);
} else {
String mssg = MessageUtil.MESSAGE_MOST.renderToString(message);
fail(holder, mssg, thrown);
}
}
} catch (Throwable t) {
fail(holder, "unexpected exception", t);
}
}
/** call this to stop after the next iteration of incremental compile */
public void quit() {
controller.quit();
}
/**
* Set holder to be passed all messages.
* When holder is set, messages will not be printed by default.
* @param holder the IMessageHolder sink for all messages
* (use null to restore default behavior)
*/
public void setHolder(IMessageHolder holder) {
clientHolder = holder;
}
/**
* Install a Runnable to be invoked synchronously
* after each compile completes.
* @param runner the Runnable to invoke - null to disable
*/
public void setCompletionRunner(Runnable runner) {
this.completionRunner = runner;
}
/**
* Call System.exit(int) with values derived from the number
* of failures/aborts or errors in messages.
* @param messages the IMessageHolder to interrogate.
* @param messages
*/
protected void systemExit(IMessageHolder messages) {
int num = lastFails; // messages.numMessages(IMessage.FAIL, true);
if (0 < num) {
System.exit(-num);
}
num = lastErrors; // messages.numMessages(IMessage.ERROR, false);
if (0 < num) {
System.exit(num);
}
System.exit(0);
}
/** Messages to the user */
protected void outMessage(String message) { // XXX coordinate with MessagePrinter
System.out.print(message);
System.out.flush();
}
/**
* Report results from a (possibly-incremental) compile run.
* This delegates to any reportHandler or otherwise
* prints summary counts of errors/warnings to System.err (if any errors)
* or System.out (if only warnings).
* WARNING: this silently ignores other messages like FAIL,
* but clears the handler of all messages when returning true. XXX false
*
* This implementation ignores the pass parameter but
* clears the holder after reporting
* on the assumption messages were handled/printed already.
* (ignoring UnsupportedOperationException from holder.clearMessages()).
* @param pass true result of the command
* @param holder IMessageHolder with messages from the command
* @see reportCommandResults(IMessageHolder)
* @return false if the process should abort
*/
protected boolean report(boolean pass, IMessageHolder holder) {
lastFails = holder.numMessages(IMessage.FAIL, true);
boolean result = (0 == lastFails);
final Runnable runner = completionRunner;
if (null != runner) {
runner.run();
}
if (holder == ourHandler) {
lastErrors = holder.numMessages(IMessage.ERROR, false);
int warnings = holder.numMessages(IMessage.WARNING, false);
StringBuffer sb = new StringBuffer();
appendNLabel(sb, "fail|abort", lastFails);
appendNLabel(sb, "error", lastErrors);
appendNLabel(sb, "warning", warnings);
if (0 < sb.length()) {
PrintStream out = (0 < (lastErrors + lastFails)
? System.err
: System.out);
out.println(""); // XXX "wrote class file" messages no eol?
out.println(sb.toString());
}
}
return result;
}
/** convenience API to make fail messages (without MessageUtils's fail prefix) */
protected static void fail(IMessageHandler handler, String message, Throwable thrown) {
handler.handleMessage(new Message(message, IMessage.FAIL, thrown, null));
}
/**
* interceptor IMessageHandler to print as we go.
* This formats all messages to the user.
*/
public static class MessagePrinter implements IMessageHandler {
public static final IMessageHandler VERBOSE
= new MessagePrinter(true);
public static final IMessageHandler TERSE
= new MessagePrinter(false);
final boolean verbose;
protected MessagePrinter(boolean verbose) {
this.verbose = verbose;
}
/**
* Print errors and warnings to System.err,
* and optionally info to System.out,
* rendering message String only.
* @return false always
*/
public boolean handleMessage(IMessage message) {
if (null != message) {
PrintStream out = getStreamFor(message.getKind());
if (null != out) {
out.println(render(message));
}
}
return false;
}
/**
* Render message differently.
* If abort, then prefix stack trace with feedback request.
* If the actual message is empty, then use toString on the whole.
* Prefix message part with file:line;
* If it has context, suffix message with context.
* @param message the IMessage to render
* @return String rendering IMessage (never null)
*/
protected String render(IMessage message) {
IMessage.Kind kind = message.getKind();
StringBuffer sb = new StringBuffer();
String text = message.getMessage();
if (text.equals(AbortException.NO_MESSAGE_TEXT)) {
text = null;
}
boolean toString = (LangUtil.isEmpty(text));
if (toString) {
text = message.toString();
}
ISourceLocation loc = message.getSourceLocation();
String context = null;
if (null != loc) {
File file = loc.getSourceFile();
if (null != file) {
String name = file.getName();
if (!toString || (-1 == text.indexOf(name))) {
sb.append(FileUtil.getBestPath(file));
sb.append(":" + loc.getLine());
int col = loc.getColumn();
if (0 < col) {
sb.append(":" + col);
}
sb.append(" ");
}
}
context = loc.getContext();
}
sb.append(text);
if (null != context) {
sb.append(LangUtil.EOL);
sb.append(context);
}
Throwable thrown = message.getThrown();
if (null != thrown) {
sb.append(LangUtil.EOL);
sb.append(Main.renderExceptionForUser(thrown));
}
return sb.toString();
}
public boolean isIgnoring(IMessage.Kind kind) {
return (null != getStreamFor(kind));
}
/** @return System.err for FAIL, ABORT, ERROR, and WARNING,
* System.out for INFO if verbose.
*/
protected PrintStream getStreamFor(IMessage.Kind kind) {
if (IMessage.WARNING.isSameOrLessThan(kind)) {
return System.err;
} else if (verbose && IMessage.INFO.equals(kind)) {
return System.out;
} else {
return null;
}
}
}
/** controller for repeatable command delays until input or file changed or removed */
public static class CommandController {
public static String TAG_FILE_OPTION = "-XincrementalFile";
public static String INCREMENTAL_OPTION = "-incremental";
/** maximum 10-minute delay between filesystem checks */
public static long MAX_DELAY = 1000 * 600;
/** default 5-second delay between filesystem checks */
public static long DEFAULT_DELAY = 1000 * 5;
/** @see init(String[]) */
private static String[][] OPTIONS = new String[][]
{ new String[] { INCREMENTAL_OPTION },
new String[] { TAG_FILE_OPTION, null } };
/** true between init(String[]) and doRepeatCommand() that returns false */
private boolean running;
/** true after quit() called */
private boolean quit;
/** true if incremental mode, waiting for input other than 'q' */
private boolean incremental;
/** true if incremental mode, waiting for file to change (repeat) or disappear (quit) */
private File tagFile;
/** last modification time for tagFile as of last command - 0 to start */
private long fileModTime;
/** delay between filesystem checks for tagFile modification time */
private long delay;
/** true just after user types 'r' for rebuild */
private boolean buildFresh;
public CommandController() {
delay = DEFAULT_DELAY;
}
/**
* @param argList read and strip incremental args from this
* @param sink IMessageHandler for error messages
* @return String[] remainder of args
*/
public String[] init(String[] args, IMessageHandler sink) {
running = true;
String[] unused;
if (!LangUtil.isEmpty(args)) {
String[][] options = LangUtil.copyStrings(OPTIONS);
unused = LangUtil.extractOptions(args, options);
incremental = (null != options[0][0]);
if (null != options[1][0]) {
File file = new File(options[1][1]);
if (!file.exists()) {
MessageUtil.abort(sink, "tag file does not exist: " + file);
} else {
tagFile = file;
fileModTime = tagFile.lastModified();
}
}
}
return args;
}
/** @return true if init(String[]) called but doRepeatCommand has not
* returned false */
public boolean running() {
return running;
}
/** @param delay milliseconds between filesystem checks */
public void setDelay(long delay) {
if ((delay > -1) && (delay < MAX_DELAY)) {
this.delay = delay;
}
}
/** @return true if INCREMENTAL_OPTION or TAG_FILE_OPTION was in args */
public boolean incremental() {
return (incremental || (null != tagFile));
}
/** @return true if INCREMENTAL_OPTION was in args */
public boolean commandLineIncremental() {
return incremental;
}
public void quit() {
if (!quit) {
quit = true;
}
}
/** @return true just after user typed 'r' */
boolean buildFresh() {
return buildFresh;
}
/** @return false if we should quit, true to do another command */
boolean doRepeatCommand() {
if (!running) {
return false;
}
boolean result = false;
if (quit) {
result = false;
} else if (incremental) {
try {
if (buildFresh) { // reset before input request
buildFresh = false;
}
System.out.println(" press enter to recompile, r to rebuild, q to quit: ");
System.out.flush();
boolean doMore = false;
// seek for one q or a series of [\n\r]...
do {
int input = System.in.read();
if ('q' == input) {
break; // result = false;
} else if ('r' == input) {
buildFresh = true;
result = true;
} else if (('\n' == input) || ('\r' == input)) {
result = true;
} // else eat anything else
} while (!result);
System.in.skip(Integer.MAX_VALUE);
} catch (IOException e) { // XXX silence for error?
result = false;
}
} else if (null != tagFile) {
long curModTime;
while (true) {
if (!tagFile.exists()) {
result = false;
break;
} else if (fileModTime == (curModTime = tagFile.lastModified())) {
fileCheckDelay();
} else {
fileModTime = curModTime;
result = true;
break;
}
}
} // else, not incremental - false
if (!result && running) {
running = false;
}
return result;
}
/** delay between filesystem checks, returning if quit is set */
protected void fileCheckDelay() {
final Thread thread = Thread.currentThread();
long targetTime = System.currentTimeMillis() + delay;
long curTime;
while (targetTime > (curTime = System.currentTimeMillis())) {
if (quit) {
return;
}
try { Thread.sleep(300); } // 1/3-second delta for quit check
catch (InterruptedException e) {}
}
}
}
}
|
41,952
|
Bug 41952 XLint warning for call PCD's using subtype of defining type
| null |
resolved fixed
|
97ab1e9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-07T17:00:52Z
| 2003-08-26T09:26:40Z
|
testing/src/org/aspectj/testing/xml/SoftMessage.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.testing.xml;
import java.io.File;
import java.util.Iterator;
import java.util.List;
import org.aspectj.bridge.*;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.bridge.SourceLocation;
import org.aspectj.util.LangUtil;
/**
* Implement messages.
* This implementation is immutable if ISourceLocation is immutable.
*/
public class SoftMessage implements IMessage { // XXX mutable dup of Message
public static String XMLNAME = "message";
public static final File NO_FILE = ISourceLocation.NO_FILE;
private String message;
private IMessage.Kind kind;
private Throwable thrown;
private ISourceLocation sourceLocation;
private String details;
//private ISourceLocation pseudoSourceLocation; // set directly
// collapse enclosed source location for shorter, property-based xml
private String file;
private int line = Integer.MAX_VALUE;
/** convenience for constructing failure messages */
public static SoftMessage fail(String message, Throwable thrown) {
return new SoftMessage(message, IMessage.FAIL, thrown, null);
}
/**
* Print messages.
* @param messages List of IMessage
*/
public static void writeXml(XMLWriter out, IMessageHolder messages) {
if ((null == out) || (null == messages)
|| (0 == messages.numMessages(null, true))) {
return;
}
List list = messages.getUnmodifiableListView();
for (Iterator iter = list.iterator(); iter.hasNext();) {
writeXml(out, (IMessage) iter.next());
}
}
/**
* Print messages.
* @param messages IMessage[]
*/
public static void writeXml(XMLWriter out, IMessage[] messages) {
if ((null == out) || (null == messages)) {
return;
}
for (int i = 0; i < messages.length; i++) {
writeXml(out, messages[i]);
}
}
/** print message as an element
* @throws IllegalArgumentException if message.getThrown() is not null
*/
public static void writeXml(XMLWriter out, IMessage message) { // XXX short form only, no files
if ((null == out) || (null == message)) {
return;
}
Throwable thrown = message.getThrown();
if (null != thrown) {
String m = "unable to write " + message + " thrown not permitted";
throw new IllegalArgumentException(m);
}
final String elementName = XMLNAME;
out.startElement(elementName, false);
out.printAttribute("kind", message.getKind().toString());
String value = message.getMessage();
if (null != value) {
out.printAttribute("message", value);
}
ISourceLocation sl = message.getSourceLocation();
if (null != sl) {
out.endAttributes();
SoftSourceLocation.writeXml(out, sl);
}
out.endElement(elementName);
}
public SoftMessage() {} // XXX programmatic only
/**
* Create a (compiler) error or warning message
* @param message the String used as the underlying message
* @param sourceLocation the ISourceLocation, if any, associated with this message
* @param isError if true, use IMessage.ERROR; else use IMessage.WARNING
*/
public SoftMessage(String message, ISourceLocation location, boolean isError) {
this(message, (isError ? IMessage.ERROR : IMessage.WARNING), null,
location);
}
/**
* Create a message, handling null values for message and kind
* if thrown is not null.
* @param message the String used as the underlying message
* @param kind the IMessage.Kind of message - not null
* @param thrown the Throwable, if any, associated with this message
* @param sourceLocation the ISourceLocation, if any, associated with this message
* @throws IllegalArgumentException if message is null and
* thrown is null or has a null message, or if kind is null
* and thrown is null.
*/
public SoftMessage(String message, IMessage.Kind kind, Throwable thrown,
ISourceLocation sourceLocation) {
this.message = message;
this.kind = kind;
this.thrown = thrown;
this.sourceLocation = sourceLocation;
if (null == message) {
if (null != thrown) {
message = thrown.getMessage();
}
if (null == message) {
throw new IllegalArgumentException("null message");
}
}
if (null == kind) {
throw new IllegalArgumentException("null kind");
}
}
/** @return the kind of this message */
public IMessage.Kind getKind() {
return kind;
}
/** @return true if kind == IMessage.ERROR */
public boolean isError() {
return kind == IMessage.ERROR;
}
/** @return true if kind == IMessage.WARNING */
public boolean isWarning() {
return kind == IMessage.WARNING;
}
/** @return true if kind == IMessage.DEBUG */
public boolean isDebug() {
return kind == IMessage.DEBUG;
}
/**
* @return true if kind == IMessage.INFO
*/
public boolean isInfo() {
return kind == IMessage.INFO;
}
/** @return true if kind == IMessage.ABORT */
public boolean isAbort() {
return kind == IMessage.ABORT;
}
/**
* @return true if kind == IMessage.FAIL
*/
public boolean isFailed() {
return kind == IMessage.FAIL;
}
/** @return non-null String with simple message */
final public String getMessage() {
return message;
}
/** @return Throwable associated with this message, or null if none */
final public Throwable getThrown() {
return thrown;
}
/**
* This returns any ISourceLocation set or a mock-up
* if file and/or line were set.
* @return ISourceLocation associated with this message,
* a mock-up if file or line is available, or null if none
*/
final public ISourceLocation getSourceLocation() {
if ((null == sourceLocation)
&& ((null != file) || (line != Integer.MAX_VALUE))) {
File f = (null == file ? NO_FILE : new File(file));
int line = (this.line == Integer.MAX_VALUE ? 0 : this.line);
sourceLocation = new SourceLocation(f, line);
}
return sourceLocation;
}
/** set the kind of this message */
public void setMessageKind(IMessage.Kind kind) {
this.kind = (null == kind ? IMessage.ERROR : kind);
}
/** set the file for the underlying source location of this message
* @throws IllegalStateException if source location was set directly
* or indirectly by calling getSourceLocation after setting
* file or line.
*/
public void setFile(String path) {
LangUtil.throwIaxIfFalse(!LangUtil.isEmpty(path), "empty path");
if (null != sourceLocation) {
throw new IllegalStateException("cannot set line after creating source location");
}
this.file = path;
}
/** set the kind of this message */
public void setKindAsString(String kind) {
setMessageKind(MessageUtil.getKind(kind));
}
public void setSourceLocation(ISourceLocation sourceLocation) {
this.sourceLocation = sourceLocation;
}
/**
* Set the line for the underlying source location.
* @throws IllegalStateException if source location was set directly
* or indirectly by calling getSourceLocation after setting
* file or line.
*/
public void setLineAsString(String line) {
if (null != sourceLocation) {
throw new IllegalStateException("cannot set line after creating source location");
}
this.line = Integer.valueOf(line).intValue();
SourceLocation.validLine(this.line);
}
public void setText(String text) {
this.message = (null == text ? "" : text);
}
public String toString() {
StringBuffer result = new StringBuffer();
result.append(getKind().toString());
String messageString = getMessage();
if (!LangUtil.isEmpty(messageString)) {
result.append(messageString);
}
ISourceLocation loc = getSourceLocation();
if ((null != loc) && (loc != ISourceLocation.NO_FILE)) {
result.append(" at " + loc);
}
if (null != thrown) {
result.append(" -- " + LangUtil.renderExceptionShort(thrown));
}
return result.toString();
}
public String getDetails() {
return details;
}
public void setDetails(String string) {
details = string;
}
}
|
41,952
|
Bug 41952 XLint warning for call PCD's using subtype of defining type
| null |
resolved fixed
|
97ab1e9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-07T17:00:52Z
| 2003-08-26T09:26:40Z
|
tests/bugs/DeclaringTypeWarning.java
| |
41,952
|
Bug 41952 XLint warning for call PCD's using subtype of defining type
| null |
resolved fixed
|
97ab1e9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-07T17:00:52Z
| 2003-08-26T09:26:40Z
|
tests/new/CallTypesI.java
|
import org.aspectj.testing.Tester;
import java.util.*;
public class CallTypesI {
public static void main(String[] args) {
C1a c1a = new C1a();
preTest("c1a.mI()");
c1a.mI();
test("static c1a, static i0, static i1a, instanceof c0, instanceof c1a, instanceof i0, instanceof i1a, ");
preTest("c1a.mC()");
c1a.mC();
test("static c0, static c1a, instanceof c0, instanceof c1a, instanceof i0, instanceof i1a, ");
C0 c0 = c1a;
preTest("(C c = c1a).mC()");
c0.mC();
test("static c0, instanceof c0, instanceof c1a, instanceof i0, instanceof i1a, ");
}
public static void preTest(String str) {
A.noteAdvice = A.noteAdviceStar = "";
msg = str;
}
static String msg;
public static void test(String t1) {
test(t1, t1);
}
public static void test(String baseString, String starString) {
Tester.checkEqual(sort(A.noteAdvice), sort(baseString), "base: "+msg);
//Tester.checkEqual(sort(A.noteAdviceStar), sort(starString), "star: "+msg);
}
private final static Collection sort(String str) {
SortedSet sort = new TreeSet();
for (StringTokenizer t = new StringTokenizer(str, ",", false);
t.hasMoreTokens();) {
String s = t.nextToken().trim();
if (s.length() > 0) sort.add(s);
}
return sort;
}
}
interface I0 {
public void mI();
}
interface I1a extends I0 { }
interface I1b extends I0 { }
interface I2 extends I1a, I1b {}
class C0 {
public void mC() { }
}
class C1a extends C0 implements I1a {
public void mI() { }
}
class C1b extends C0 implements I1b {
public void mI() { }
}
aspect A {
static String noteAdvice = "";
static String noteAdviceStar = "";
before(): call(void C0.mC()) {
noteAdvice += "static c0, ";
}
before(): call(void C1a.mC()) || call(void C1a.mI()) {
noteAdvice += "static c1a, ";
}
before(): call(void C1b.mC()) || call(void C1b.mI()) {
noteAdvice += "static c1b, ";
}
before(): call(void I0.mI()) {
noteAdvice += "static i0, ";
}
before(): call(void I1a.mI()) {
noteAdvice += "static i1a, ";
}
before(): call(void I1b.mI()) {
noteAdvice += "static i1b, ";
}
before(): target(C0) && call(* *(..)) { noteAdvice += "instanceof c0, "; }
before(): target(C1a) && call(* *(..)) { noteAdvice += "instanceof c1a, "; }
before(): target(C1b) && call(* *(..)) { noteAdvice += "instanceof c1b, "; }
before(): target(I0) && call(* *(..)) { noteAdvice += "instanceof i0, "; }
before(): target(I1a) && call(* *(..)) { noteAdvice += "instanceof i1a, "; }
before(): target(I1b) && call(* *(..)) { noteAdvice += "instanceof i1b, "; }
}
|
41,952
|
Bug 41952 XLint warning for call PCD's using subtype of defining type
| null |
resolved fixed
|
97ab1e9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-07T17:00:52Z
| 2003-08-26T09:26:40Z
|
tests/new/IndeterminateArg.java
|
import org.aspectj.testing.Tester;
import org.aspectj.lang.*;
import org.aspectj.lang.reflect.*;
import java.util.Arrays;
/** @testcase PR#764 binding args with single indeterminate prefix and suffix */
public class IndeterminateArg {
public static void main (String[] args) {
Object o1 = new OObject("o1");
Object o2 = new OObject("o2");
Object o3 = new OObject("o3");
String s1 = "s1";
String s2 = "s2";
String s3 = "s3";
SClass c;
c = new SClass();
c = new SClass(s1);
c = new SClass(s1, s2);
c = new SClass(s1, s2, s3);
c.f();
c.f(s1);
c.f(s1, s2);
c.f(s1, s2, s3);
OClass o;
o = new OClass();
o = new OClass(o1);
o = new OClass(s1);
o = new OClass(o1, o2);
o = new OClass(o1, s2);
o = new OClass(s1, o2);
o = new OClass(s1, s2);
o = new OClass(o1, o2, o3);
o = new OClass(o1, o2, s3);
o = new OClass(o1, s2, o3);
o = new OClass(o1, s2, s3);
o = new OClass(s1, o2, o3);
o = new OClass(s1, o2, s3);
o = new OClass(s1, s2, o3);
o = new OClass(s1, s2, s3);
o.f();
o.f(o1);
o.f(s1);
o.f(o1, o2);
o.f(o1, s2);
o.f(s1, o2);
o.f(s1, s2);
o.f(o1, o2, o3);
o.f(o1, o2, s3);
o.f(o1, s2, o3);
o.f(o1, s2, s3);
o.f(s1, o2, o3);
o.f(s1, o2, s3);
o.f(s1, s2, o3);
o.f(s1, s2, s3);
Tester.checkEventsFromFile("IndeterminateArg.events");
}
}
class OObject {
final String s;
OObject(String s) { this.s = s; }
public String toString() { return s; }
}
class T {
static void e(String s) {
Tester.event(s);
}
}
interface C {}
class SClass implements C {
SClass() { T.e("SClass()"); }
SClass(String s1) { T.e("SClass(" + s1 + ")"); }
SClass(String s1, String s2) { T.e("SClass(" + s1 + ", " + s2 + ")"); }
SClass(String s1, String s2, String s3) { T.e("SClass(" + s1 + ", " + s2 + ", " + s3 + ")"); }
void f() { T.e("SClass.f()"); }
void f(String s1) { T.e("SClass.f(" + s1 + ")"); }
void f(String s1, String s2) { T.e("SClass.f(" + s1 + ", " + s2 + ")"); }
void f(String s1, String s2, String s3) { T.e("SClass.f(" + s1 + ", " + s2 + ", " + s3 + ")"); }
}
class OClass implements C {
OClass() { T.e("OClass()"); }
OClass(Object s1) { T.e("OClass(" + s1 + ")"); }
OClass(Object s1, Object s2) { T.e("OClass(" + s1 + ", " + s2 + ")"); }
OClass(Object s1, Object s2, Object s3) { T.e("OClass(" + s1 + ", " + s2 + ", " + s3 + ")"); }
void f() { T.e("OClass.f()"); }
void f(Object s1) { T.e("OClass.f(" + s1 + ")"); }
void f(Object s1, Object s2) { T.e("OClass.f(" + s1 + ", " + s2 + ")"); }
void f(Object s1, Object s2, Object s3) { T.e("OClass.f(" + s1 + ", " + s2 + ", " + s3 + ")"); }
}
aspect A {
String actualTypes(JoinPoint jp) { // XXX gather as utility
Object[] types = jp.getArgs();
StringBuffer sb = new StringBuffer();
sb.append("[");
for (int i = 0; i < types.length; i++) {
sb.append(types[i].getClass().getName());
if ((1+i) < types.length) {
sb.append(", ");
}
}
sb.append("]");
return sb.toString();
}
void check(String pc, JoinPoint jp) {
Class[] types = ((CodeSignature) jp.getSignature()).getParameterTypes();
String name = jp.toLongString() + " " + actualTypes(jp) + ": " + pc;
T.e(name);
}
pointcut safe() : (call(C+.new(..)) || call(* C+.*(..)));
// XXX should encode slots, range: a0o1 = args(Object); a3o2Start = args(Object, Object, *)
pointcut none() : args();
pointcut o1() : args(Object);
pointcut o2() : args(Object, Object);
pointcut o3() : args(Object, Object, Object);
pointcut o1Start() : args(Object,*);
pointcut o1End() : args(*,Object);
pointcut o2Start() : args(Object, Object,*);
pointcut o2End() : args(*,Object, Object);
pointcut s1() : args(String);
pointcut s2() : args(String, String);
pointcut s3() : args(String, String, String);
pointcut s1Start() : args(String,*);
pointcut s1End() : args(*,String);
pointcut s2Start() : args(String, String,*);
pointcut s2End() : args(*,String, String);
// bind
pointcut bo1(Object o1) : args(o1);
pointcut bo2(Object o1, Object o2) : args(o1, o2);
pointcut bo3(Object o1, Object o2, Object o3) : args(o1, o2, o3);
pointcut bo1Start(Object o1) : args(o1,*);
pointcut bo1End(Object o1) : args(*,o1);
pointcut bo2Start(Object o1, Object o2) : args(o1, o2,*);
pointcut bo2End(Object o1, Object o2) : args(*,o1, o2);
pointcut bs1(String s1) : args(s1);
pointcut bs2(String s1, String s2) : args(s1, s2);
pointcut bs3(String s1, String s2, String s3) : args(s1, s2, s3);
pointcut bs1Start(String s1) : args(s1,*);
pointcut bs1End(String s1) : args(*,s1);
pointcut bs2Start(String s1, String s2) : args(s1, s2,*);
pointcut bs2End(String s1, String s2) : args(*,s1, s2);
before() : safe() && none() { check ("none()", thisJoinPoint); }
before() : safe() && o1() { check ("o1()", thisJoinPoint); }
before() : safe() && o2() { check ("o2()", thisJoinPoint); }
before() : safe() && o3() { check ("o3()", thisJoinPoint); }
before() : safe() && o1Start() { check ("o1Start()", thisJoinPoint); }
before() : safe() && o1End() { check ("o1End()", thisJoinPoint); }
before() : safe() && o2Start() { check ("o2Start()", thisJoinPoint); }
before() : safe() && o2End() { check ("o2End()", thisJoinPoint); }
before() : safe() && s1() { check ("s1()", thisJoinPoint); }
before() : safe() && s2() { check ("s2()", thisJoinPoint); }
before() : safe() && s3() { check ("s3()", thisJoinPoint); }
before() : safe() && s1Start() { check ("s1Start()", thisJoinPoint); }
before() : safe() && s1End() { check ("s1End()", thisJoinPoint); }
before() : safe() && s2Start() { check ("s2Start()", thisJoinPoint); }
before() : safe() && s2End() { check ("s2End()", thisJoinPoint); }
before(Object o1) : safe() && bo1(o1) { check ("bo1()", thisJoinPoint); }
before(Object o1, Object o2) : safe() && bo2(o1, o2) { check ("bo2()", thisJoinPoint); }
before(Object o1, Object o2, Object o3) : safe() && bo3(o1, o2, o3) { check ("bo3()", thisJoinPoint); }
before(Object o1) : safe() && bo1Start(o1) { check ("bo1Start()", thisJoinPoint); }
before(Object o1) : safe() && bo1End(o1) { check ("bo1End()", thisJoinPoint); }
before(Object o1, Object o2) : safe() && bo2Start(o1, o2) { check ("bo2Start()", thisJoinPoint); }
before(Object o1, Object o2) : safe() && bo2End(o1, o2) { check ("bo2End()", thisJoinPoint); }
before(String s1) : safe() && bs1(s1) { check ("bs1()", thisJoinPoint); }
before(String s1, String s2) : safe() && bs2(s1, s2) { check ("bs2()", thisJoinPoint); }
before(String s1, String s2, String s3) : safe() && bs3(s1, s2, s3) { check ("bs3()", thisJoinPoint); }
before(String s1) : safe() && bs1Start(s1) { check ("bs1Start()", thisJoinPoint); }
before(String s1) : safe() && bs1End(s1) { check ("bs1End()", thisJoinPoint); }
before(String s1, String s2) : safe() && bs2Start(s1, s2) { check ("bs2Start()", thisJoinPoint); }
before(String s1, String s2) : safe() && bs2End(s1, s2) { check ("bs2End()", thisJoinPoint); }
}
|
41,952
|
Bug 41952 XLint warning for call PCD's using subtype of defining type
| null |
resolved fixed
|
97ab1e9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-07T17:00:52Z
| 2003-08-26T09:26:40Z
|
tests/new/IndeterminateArgType.java
|
import org.aspectj.testing.Tester;
import org.aspectj.lang.*;
import org.aspectj.lang.reflect.*;
import java.util.Arrays;
/** @testcase PR#764 check arg types with indeterminate prefix and suffix */
public class IndeterminateArgType {
public static void main (String[] args) {
OTarget o;
STarget c;
// both pointcuts pick out args 1..3; neither picks out args 0
// both actual Object and String match
c = new STarget();
c = new STarget("s1");
c = new STarget("s1", "s2");
c = new STarget("s1", "s2", "s3");
c.f();
c.f("s1");
c.f("s1", "s2");
c.f("s1", "s2", "s3");
// String pointcut should match even though declared type is Object
o = new OTarget();
o = new OTarget("o1");
o = new OTarget("o1", "o2");
o = new OTarget("o1", "o2", "o3");
o.f();
o.f("o1");
o.f("o1", "o2");
o.f("o1", "o2", "o3");
// only actual Object types match these
Object input = new Object();
o = new OTarget();
o = new OTarget(input);
o = new OTarget(input, input);
o = new OTarget(input, input, input);
o.f();
o.f(input);
o.f(input, input);
o.f(input, input, input);
Tester.checkEventsFromFile("IndeterminateArgType.events");
}
}
interface Safe {}
class OTarget implements Safe {
OTarget() { }
OTarget(Object s1) { }
OTarget(Object s1, Object s2) { }
OTarget(Object s1, Object s2, Object s3) { }
void f() { }
void f(Object s1) { }
void f(Object s1, Object s2) { }
void f(Object s1, Object s2, Object s3) { }
}
class STarget implements Safe {
STarget() { }
STarget(String s1) { }
STarget(String s1, String s2) { }
STarget(String s1, String s2, String s3) { }
void f() { }
void f(String s1) { }
void f(String s1, String s2) { }
void f(String s1, String s2, String s3) { }
}
class T {
static void e(String s) {
Tester.event(s);
}
}
aspect A {
String actualTypes(JoinPoint jp) { // XXX gather as utility
Object[] types = jp.getArgs();
StringBuffer sb = new StringBuffer();
sb.append("[");
for (int i = 0; i < types.length; i++) {
sb.append(types[i].getClass().getName());
if ((1+i) < types.length) {
sb.append(", ");
}
}
sb.append("]");
return sb.toString();
}
void check(String pc, JoinPoint jp) {
Class[] types = ((CodeSignature) jp.getSignature()).getParameterTypes();
String name = jp.toLongString() + " " + actualTypes(jp) + ": " + pc;
T.e(name);
}
pointcut safe() : call(Safe+.new(..)) || call(* Safe+.*(..));
pointcut o1End() : args(.., Object);
pointcut s1End() : args(.., String);
pointcut o1Start() : args(Object, ..);
pointcut s1Start() : args(String, ..);
before() : safe() && o1Start() { check ("o1Start()", thisJoinPoint); }
before() : safe() && o1End() { check ("o1End()", thisJoinPoint); }
before() : safe() && s1Start() { check ("s1Start()", thisJoinPoint); }
before() : safe() && s1End() { check ("s1End()", thisJoinPoint); }
}
|
41,952
|
Bug 41952 XLint warning for call PCD's using subtype of defining type
| null |
resolved fixed
|
97ab1e9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-07T17:00:52Z
| 2003-08-26T09:26:40Z
|
weaver/src/org/aspectj/weaver/Checker.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.util.*;
import org.aspectj.bridge.*;
import org.aspectj.weaver.patterns.*;
public class Checker extends ShadowMunger {
private String msg;
private boolean isError;
public Checker(DeclareErrorOrWarning deow) {
super(deow.getPointcut(), deow.getStart(), deow.getEnd(), deow.getSourceContext());
this.msg = deow.getMessage();
this.isError = deow.isError();
}
public ShadowMunger concretize(ResolvedTypeX fromType, World world, PerClause clause) {
pointcut = pointcut.concretize(fromType, 0, this);
return this;
}
public void specializeOn(Shadow shadow) {
throw new RuntimeException("illegal state");
}
public void implementOn(Shadow shadow) {
throw new RuntimeException("illegal state");
}
public boolean match(Shadow shadow, World world) {
if (super.match(shadow, world)) {
IMessage message = new Message(
msg,
shadow.toString(),
isError ? IMessage.ERROR : IMessage.WARNING,
shadow.getSourceLocation());
world.getMessageHandler().handleMessage(message);
AsmRelationshipProvider.checkerMunger(world.getModel(), shadow, this);
}
return false;
}
public int compareTo(Object other) {
return 0;
}
public Collection getThrownExceptions() { return Collections.EMPTY_LIST; }
public boolean isError() {
return isError;
}
}
|
41,952
|
Bug 41952 XLint warning for call PCD's using subtype of defining type
| null |
resolved fixed
|
97ab1e9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-07T17:00:52Z
| 2003-08-26T09:26:40Z
|
weaver/src/org/aspectj/weaver/Lint.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.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.Message;
import org.aspectj.bridge.MessageUtil;
public class Lint {
/* private */ Map kinds = new HashMap();
/* private */ World world;
public final Kind invalidAbsoluteTypeName =
new Kind("invalidAbsoluteTypeName", "no match for this type name: {0}");
public final Kind invalidWildcardTypeName =
new Kind("invalidWildcardTypeName", "no match for this type pattern: {0}");
public final Kind unresolvableMember =
new Kind("unresolvableMember", "can not resolve this member: {0}");
public final Kind typeNotExposedToWeaver =
new Kind("typeNotExposedToWeaver", "this affected type is not exposed to the weaver: {0}");
public final Kind shadowNotInStructure =
new Kind("shadowNotInStructure", "the shadow for this join point is not exposed in the structure model: {0}");
public Lint(World world) {
this.world = world;
}
public void setAll(String messageKind) {
setAll(getMessageKind(messageKind));
}
private void setAll(IMessage.Kind messageKind) {
for (Iterator i = kinds.values().iterator(); i.hasNext(); ) {
Kind kind = (Kind)i.next();
kind.setKind(messageKind);
}
}
public void setFromProperties(File file) {
try {
InputStream s = new FileInputStream(file);
setFromProperties(s);
} catch (IOException ioe) {
MessageUtil.error(world.getMessageHandler(), "problem loading Xlint properties file: " +
file.getPath() + ", " + ioe.getMessage());
}
}
public void loadDefaultProperties() {
InputStream s = getClass().getResourceAsStream("XlintDefault.properties");
if (s == null) {
MessageUtil.warn(world.getMessageHandler(), "couldn't load XlintDefault.properties");
return;
}
try {
setFromProperties(s);
} catch (IOException ioe) {
MessageUtil.error(world.getMessageHandler(), "problem loading XlintDefault.properties, " +
ioe.getMessage());
}
}
private void setFromProperties(InputStream s) throws IOException {
Properties p = new Properties();
p.load(s);
setFromProperties(p);
}
public void setFromProperties(Properties properties) {
for (Iterator i = properties.entrySet().iterator(); i.hasNext(); ) {
Map.Entry entry = (Map.Entry)i.next();
Kind kind = (Kind)kinds.get(entry.getKey());
if (kind == null) {
MessageUtil.error(world.getMessageHandler(), "invalid Xlint key: " + entry.getKey());
} else {
kind.setKind(getMessageKind((String)entry.getValue()));
}
}
}
private IMessage.Kind getMessageKind(String v) {
if (v.equals("ignore")) return null;
else if (v.equals("warning")) return IMessage.WARNING;
else if (v.equals("error")) return IMessage.ERROR;
MessageUtil.error(world.getMessageHandler(),
"invalid Xlint message kind (must be one of ignore, warning, error): " + v);
return null;
}
public class Kind {
private String name;
private String message;
private IMessage.Kind kind = IMessage.WARNING;
public Kind(String name, String message) {
this.name = name;
this.message = message;
kinds.put(this.name, this);
}
public boolean isEnabled() {
return kind != null;
}
public IMessage.Kind getKind() {
return kind;
}
public void setKind(IMessage.Kind kind) {
this.kind = kind;
}
public void signal(String info, ISourceLocation location) {
if (kind == null) return;
String text = MessageFormat.format(message, new Object[] {info} );
text += " [Xlint:" + name + "]";
world.getMessageHandler().handleMessage(new Message(text, kind, null, location));
}
}
}
|
41,952
|
Bug 41952 XLint warning for call PCD's using subtype of defining type
| null |
resolved fixed
|
97ab1e9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-07T17:00:52Z
| 2003-08-26T09:26:40Z
|
weaver/src/org/aspectj/weaver/patterns/AndPointcut.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.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import org.aspectj.util.FuzzyBoolean;
import org.aspectj.weaver.ISourceContext;
import org.aspectj.weaver.IntMap;
import org.aspectj.weaver.ResolvedTypeX;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.ast.Test;
public class AndPointcut extends Pointcut {
Pointcut left, right; // exposed for testing
public AndPointcut(Pointcut left, Pointcut right) {
super();
this.left = left;
this.right = right;
setLocation(left.getSourceContext(), left.getStart(), right.getEnd());
}
public FuzzyBoolean fastMatch(ResolvedTypeX type) {
return left.fastMatch(type).and(right.fastMatch(type));
}
public FuzzyBoolean match(Shadow shadow) {
return left.match(shadow).and(right.match(shadow));
}
public String toString() {
return "(" + left.toString() + " && " + right.toString() + ")";
}
public boolean equals(Object other) {
if (!(other instanceof AndPointcut)) return false;
AndPointcut o = (AndPointcut)other;
return o.left.equals(left) && o.right.equals(right);
}
public int hashCode() {
int result = 19;
result = 37*result + left.hashCode();
result = 37*result + right.hashCode();
return result;
}
public void resolveBindings(IScope scope, Bindings bindings) {
left.resolveBindings(scope, bindings);
right.resolveBindings(scope, bindings);
}
public void write(DataOutputStream s) throws IOException {
s.writeByte(Pointcut.AND);
left.write(s);
right.write(s);
writeLocation(s);
}
public static Pointcut read(DataInputStream s, ISourceContext context) throws IOException {
AndPointcut ret = new AndPointcut(Pointcut.read(s, context), Pointcut.read(s, context));
ret.readLocation(context, s);
return ret;
}
public Test findResidue(Shadow shadow, ExposedState state) {
return Test.makeAnd(left.findResidue(shadow, state), right.findResidue(shadow, state));
}
public Pointcut concretize1(ResolvedTypeX inAspect, IntMap bindings) {
return new AndPointcut(left.concretize1(inAspect, bindings),
right.concretize1(inAspect, bindings));
}
public Pointcut getLeft() {
return left;
}
public Pointcut getRight() {
return right;
}
}
|
41,952
|
Bug 41952 XLint warning for call PCD's using subtype of defining type
| null |
resolved fixed
|
97ab1e9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-07T17:00:52Z
| 2003-08-26T09:26:40Z
|
weaver/src/org/aspectj/weaver/patterns/ExactTypePattern.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.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import org.aspectj.util.FuzzyBoolean;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.ISourceContext;
import org.aspectj.weaver.ResolvedTypeX;
import org.aspectj.weaver.TypeX;
public class ExactTypePattern extends TypePattern {
protected TypeX type;
public ExactTypePattern(TypeX type, boolean includeSubtypes) {
super(includeSubtypes);
this.type = type;
}
protected boolean matchesExactly(ResolvedTypeX matchType) {
return this.type.equals(matchType);
}
public TypeX getType() { return type; }
public FuzzyBoolean matchesInstanceof(ResolvedTypeX matchType) {
// in our world, Object is assignable from anything
if (type.equals(ResolvedTypeX.OBJECT)) return FuzzyBoolean.YES;
if (type.isAssignableFrom(matchType, matchType.getWorld())) {
return FuzzyBoolean.YES;
}
return matchType.isCoerceableFrom(type) ? FuzzyBoolean.MAYBE : FuzzyBoolean.NO;
}
public boolean equals(Object other) {
if (!(other instanceof ExactTypePattern)) return false;
ExactTypePattern o = (ExactTypePattern)other;
return o.type.equals(this.type);
}
public int hashCode() {
return type.hashCode();
}
public void write(DataOutputStream out) throws IOException {
out.writeByte(TypePattern.EXACT);
type.write(out);
out.writeBoolean(includeSubtypes);
writeLocation(out);
}
public static TypePattern read(DataInputStream s, ISourceContext context) throws IOException {
TypePattern ret = new ExactTypePattern(TypeX.read(s), s.readBoolean());
ret.readLocation(context, s);
return ret;
}
public String toString() {
//Thread.currentThread().dumpStack();
return "ExactTypePattern(" + type.toString() + (includeSubtypes ? "+" : "") + ")";
}
public TypePattern resolveBindings(IScope scope, Bindings bindings,
boolean allowBinding, boolean requireExactType)
{
throw new BCException("trying to re-resolve");
}
}
|
41,952
|
Bug 41952 XLint warning for call PCD's using subtype of defining type
| null |
resolved fixed
|
97ab1e9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-07T17:00:52Z
| 2003-08-26T09:26:40Z
|
weaver/src/org/aspectj/weaver/patterns/KindedPointcut.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.util.FuzzyBoolean;
import org.aspectj.weaver.*;
import org.aspectj.weaver.ast.Literal;
import org.aspectj.weaver.ast.Test;
public class KindedPointcut extends Pointcut {
Shadow.Kind kind;
SignaturePattern signature;
public KindedPointcut(
Shadow.Kind kind,
SignaturePattern signature) {
this.kind = kind;
this.signature = signature;
}
public FuzzyBoolean fastMatch(ResolvedTypeX type) {
return FuzzyBoolean.MAYBE;
}
public FuzzyBoolean match(Shadow shadow) {
if (shadow.getKind() != kind) return FuzzyBoolean.NO;
if (!signature.matches(shadow.getSignature(), shadow.getIWorld())) return FuzzyBoolean.NO;
return FuzzyBoolean.YES;
}
public boolean equals(Object other) {
if (!(other instanceof KindedPointcut)) return false;
KindedPointcut o = (KindedPointcut)other;
return o.kind == this.kind && o.signature.equals(this.signature);
}
public int hashCode() {
int result = 17;
result = 37*result + kind.hashCode();
result = 37*result + signature.hashCode();
return result;
}
public String toString() {
StringBuffer buf = new StringBuffer();
buf.append(kind.getSimpleName());
buf.append("(");
buf.append(signature.toString());
buf.append(")");
return buf.toString();
}
public void postRead(ResolvedTypeX enclosingType) {
signature.postRead(enclosingType);
}
public void write(DataOutputStream s) throws IOException {
s.writeByte(Pointcut.KINDED);
kind.write(s);
signature.write(s);
writeLocation(s);
}
public static Pointcut read(DataInputStream s, ISourceContext context) throws IOException {
Shadow.Kind kind = Shadow.Kind.read(s);
SignaturePattern sig = SignaturePattern.read(s, context);
KindedPointcut ret = new KindedPointcut(kind, sig);
ret.readLocation(context, s);
return ret;
}
// XXX note: there is no namebinding in any kinded pointcut.
// still might want to do something for better error messages
// We want to do something here to make sure we don't sidestep the parameter
// list in capturing type identifiers.
public void resolveBindings(IScope scope, Bindings bindings) {
if (kind == Shadow.Initialization) {
// scope.getMessageHandler().handleMessage(
// MessageUtil.error(
// "initialization unimplemented in 1.1beta1",
// this.getSourceLocation()));
}
signature = signature.resolveBindings(scope, bindings);
}
public Test findResidue(Shadow shadow, ExposedState state) {
return match(shadow).alwaysTrue() ? Literal.TRUE : Literal.FALSE;
}
public Pointcut concretize1(ResolvedTypeX inAspect, IntMap bindings) {
return new KindedPointcut(kind, signature);
}
public Shadow.Kind getKind() {
return kind;
}
}
|
41,952
|
Bug 41952 XLint warning for call PCD's using subtype of defining type
| null |
resolved fixed
|
97ab1e9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-07T17:00:52Z
| 2003-08-26T09:26:40Z
|
weaver/src/org/aspectj/weaver/patterns/NotPointcut.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.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import org.aspectj.util.FuzzyBoolean;
import org.aspectj.weaver.ISourceContext;
import org.aspectj.weaver.IntMap;
import org.aspectj.weaver.ResolvedTypeX;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.ast.Test;
public class NotPointcut extends Pointcut {
private Pointcut body;
public NotPointcut(Pointcut left) {
super();
this.body = left;
}
public NotPointcut(Pointcut pointcut, int startPos) {
this(pointcut);
setLocation(pointcut.getSourceContext(), startPos, pointcut.getEnd());
}
public FuzzyBoolean fastMatch(ResolvedTypeX type) {
return body.fastMatch(type).not();
}
public FuzzyBoolean match(Shadow shadow) {
return body.match(shadow).not();
}
public String toString() {
return "!" + body.toString();
}
public boolean equals(Object other) {
if (!(other instanceof NotPointcut)) return false;
NotPointcut o = (NotPointcut)other;
return o.body.equals(body);
}
public int hashCode() {
return 37*23 + body.hashCode();
}
public void resolveBindings(IScope scope, Bindings bindings) {
//Bindings old = bindings.copy();
//Bindings newBindings = new Bindings(bindings.size());
body.resolveBindings(scope, null);
//newBindings.checkEmpty(scope, "negation does not allow binding");
//bindings.checkEquals(old, scope);
}
public void write(DataOutputStream s) throws IOException {
s.writeByte(Pointcut.NOT);
body.write(s);
writeLocation(s);
}
public static Pointcut read(DataInputStream s, ISourceContext context) throws IOException {
NotPointcut ret = new NotPointcut(Pointcut.read(s, context));
ret.readLocation(context, s);
return ret;
}
public Test findResidue(Shadow shadow, ExposedState state) {
return Test.makeNot(body.findResidue(shadow, state));
}
public Pointcut concretize1(ResolvedTypeX inAspect, IntMap bindings) {
return new NotPointcut(body.concretize1(inAspect, bindings));
}
}
|
41,952
|
Bug 41952 XLint warning for call PCD's using subtype of defining type
| null |
resolved fixed
|
97ab1e9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-07T17:00:52Z
| 2003-08-26T09:26:40Z
|
weaver/src/org/aspectj/weaver/patterns/OrPointcut.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.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import org.aspectj.util.FuzzyBoolean;
import org.aspectj.weaver.ISourceContext;
import org.aspectj.weaver.IntMap;
import org.aspectj.weaver.ResolvedTypeX;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.ast.Test;
public class OrPointcut extends Pointcut {
private Pointcut left, right;
public OrPointcut(Pointcut left, Pointcut right) {
super();
this.left = left;
this.right = right;
setLocation(left.getSourceContext(), left.getStart(), right.getEnd());
}
public FuzzyBoolean fastMatch(ResolvedTypeX type) {
return left.fastMatch(type).or(right.fastMatch(type));
}
public FuzzyBoolean match(Shadow shadow) {
return left.match(shadow).or(right.match(shadow));
}
public String toString() {
return "(" + left.toString() + " || " + right.toString() + ")";
}
public boolean equals(Object other) {
if (!(other instanceof OrPointcut)) return false;
OrPointcut o = (OrPointcut)other;
return o.left.equals(left) && o.right.equals(right);
}
public int hashCode() {
int result = 31;
result = 37*result + left.hashCode();
result = 37*result + right.hashCode();
return result;
}
/**
* @see org.aspectj.weaver.patterns.Pointcut#resolveBindings(IScope, Bindings)
*/
public void resolveBindings(IScope scope, Bindings bindings) {
Bindings old = bindings == null ? null : bindings.copy();
left.resolveBindings(scope, bindings);
right.resolveBindings(scope, old);
if (bindings != null) bindings.checkEquals(old, scope);
}
public void write(DataOutputStream s) throws IOException {
s.writeByte(Pointcut.OR);
left.write(s);
right.write(s);
writeLocation(s);
}
public static Pointcut read(DataInputStream s, ISourceContext context) throws IOException {
OrPointcut ret = new OrPointcut(Pointcut.read(s, context), Pointcut.read(s, context));
ret.readLocation(context, s);
return ret;
}
public Test findResidue(Shadow shadow, ExposedState state) {
return Test.makeOr(left.findResidue(shadow, state), right.findResidue(shadow, state));
}
public Pointcut concretize1(ResolvedTypeX inAspect, IntMap bindings) {
return new OrPointcut(left.concretize1(inAspect, bindings),
right.concretize1(inAspect, bindings));
}
public Pointcut getLeft() {
return left;
}
public Pointcut getRight() {
return right;
}
}
|
41,952
|
Bug 41952 XLint warning for call PCD's using subtype of defining type
| null |
resolved fixed
|
97ab1e9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-07T17:00:52Z
| 2003-08-26T09:26:40Z
|
weaver/src/org/aspectj/weaver/patterns/Pointcut.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.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import org.aspectj.util.FuzzyBoolean;
import org.aspectj.util.TypeSafeEnum;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.ISourceContext;
import org.aspectj.weaver.IntMap;
import org.aspectj.weaver.ResolvedTypeX;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.ShadowMunger;
import org.aspectj.weaver.ast.Literal;
import org.aspectj.weaver.ast.Test;
/**
* The lifecycle of Pointcuts is modeled by Pointcut.State. It has three things:
*
* <p>Creation -- SYMBOLIC -- then resolve(IScope) -- RESOLVED -- concretize(...) -- CONCRETE
*
* @author Erik Hilsdale
* @author Jim Hugunin
*/
public abstract class Pointcut extends PatternNode {
public static final class State extends TypeSafeEnum {
public State(String name, int key) {
super(name, key);
}
}
public static final State SYMBOLIC = new State("symbolic", 0);
public static final State RESOLVED = new State("resolved", 1);
public static final State CONCRETE = new State("concrete", 2);
public State state;
/**
* Constructor for Pattern.
*/
public Pointcut() {
super();
this.state = SYMBOLIC;
}
/**
* Could I match any shadows in the code defined within this type?
*/
public abstract FuzzyBoolean fastMatch(ResolvedTypeX type);
/**
* Do I really match this shadow?
* XXX implementors need to handle state
*/
public abstract FuzzyBoolean match(Shadow shadow);
public static final byte KINDED = 1;
public static final byte WITHIN = 2;
public static final byte THIS_OR_TARGET = 3;
public static final byte ARGS = 4;
public static final byte AND = 5;
public static final byte OR = 6;
public static final byte NOT = 7;
public static final byte REFERENCE = 8;
public static final byte IF = 9;
public static final byte CFLOW = 10;
public static final byte WITHINCODE = 12;
public static final byte HANDLER = 13;
public static final byte NONE = 20;
// internal, only called from resolve
protected abstract void resolveBindings(IScope scope, Bindings bindings);
/**
* Returns this pointcut mutated
*/
public Pointcut resolve(IScope scope) {
assertState(SYMBOLIC);
Bindings bindingTable = new Bindings(scope.getFormalCount());
this.resolveBindings(scope, bindingTable);
bindingTable.checkAllBound(scope);
this.state = RESOLVED;
return this;
}
/**
* Returns a new pointcut
*/
public Pointcut concretize(ResolvedTypeX inAspect, int arity) {
return concretize(inAspect, IntMap.idMap(arity));
}
//XXX this is the signature we're moving to
public Pointcut concretize(ResolvedTypeX inAspect, int arity, ShadowMunger advice) {
//if (state == CONCRETE) return this; //???
IntMap map = IntMap.idMap(arity);
map.setEnclosingAdvice(advice);
map.setConcreteAspect(inAspect);
return concretize(inAspect, map);
}
public Pointcut concretize(ResolvedTypeX inAspect, IntMap bindings) {
assertState(RESOLVED);
Pointcut ret = this.concretize1(inAspect, bindings);
ret.state = CONCRETE;
return ret;
}
/**
* Resolves and removes ReferencePointcuts, replacing with basic ones
*
* @param inAspect the aspect to resolve relative to
* @param bindings a Map from formal index in the current lexical context
* -> formal index in the concrete advice that will run
*
* This must always return a new Pointcut object (even if the concretized
* Pointcut is identical to the resolved one). That behavior is
* assumed in many places.
* XXX fix implementors to handle state
*/
protected abstract Pointcut concretize1(ResolvedTypeX inAspect, IntMap bindings);
//XXX implementors need to handle state
/**
* This can be called from NotPointcut even for Pointcuts that
* don't match the shadow
*/
public abstract Test findResidue(Shadow shadow, ExposedState state);
//XXX we're not sure whether or not this is needed
//XXX currently it's unused we're keeping it around as a stub
public void postRead(ResolvedTypeX enclosingType) {}
public static Pointcut read(DataInputStream s, ISourceContext context) throws IOException {
byte kind = s.readByte();
Pointcut ret;
switch(kind) {
case KINDED: ret = KindedPointcut.read(s, context); break;
case WITHIN: ret = WithinPointcut.read(s, context); break;
case THIS_OR_TARGET: ret = ThisOrTargetPointcut.read(s, context); break;
case ARGS: ret = ArgsPointcut.read(s, context); break;
case AND: ret = AndPointcut.read(s, context); break;
case OR: ret = OrPointcut.read(s, context); break;
case NOT: ret = NotPointcut.read(s, context); break;
case REFERENCE: ret = ReferencePointcut.read(s, context); break;
case IF: ret = IfPointcut.read(s, context); break;
case CFLOW: ret = CflowPointcut.read(s, context); break;
case WITHINCODE: ret = WithincodePointcut.read(s, context); break;
case HANDLER: ret = HandlerPointcut.read(s, context); break;
case NONE: ret = makeMatchesNothing(RESOLVED); break;
default:
throw new BCException("unknown kind: " + kind);
}
ret.state = RESOLVED;
return ret;
}
//public void prepare(Shadow shadow) {}
// ---- test method
public static Pointcut fromString(String str) {
PatternParser parser = new PatternParser(str);
return parser.parsePointcut();
}
private static class MatchesNothingPointcut extends Pointcut {
public Test findResidue(Shadow shadow, ExposedState state) {
return Literal.FALSE; // can only get here if an earlier error occurred
}
public FuzzyBoolean fastMatch(ResolvedTypeX type) {
return FuzzyBoolean.NO;
}
public FuzzyBoolean match(Shadow shadow) {
return FuzzyBoolean.NO;
}
public void resolveBindings(IScope scope, Bindings bindings) {
}
public void postRead(ResolvedTypeX enclosingType) {
}
public Pointcut concretize1(
ResolvedTypeX inAspect,
IntMap bindings) {
return makeMatchesNothing(state);
}
public void write(DataOutputStream s) throws IOException {
s.writeByte(NONE);
}
public String toString() { return ""; }
}
//public static Pointcut MatchesNothing = new MatchesNothingPointcut();
//??? there could possibly be some good optimizations to be done at this point
public static Pointcut makeMatchesNothing(State state) {
Pointcut ret = new MatchesNothingPointcut();
ret.state = state;
return ret;
}
public void assertState(State state) {
if (this.state != state) {
throw new BCException("expected state: " + state + " got: " + this.state);
}
}
}
|
41,952
|
Bug 41952 XLint warning for call PCD's using subtype of defining type
| null |
resolved fixed
|
97ab1e9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-07T17:00:52Z
| 2003-08-26T09:26:40Z
|
weaver/src/org/aspectj/weaver/patterns/ReferencePointcut.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.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.lang.reflect.Modifier;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.util.FuzzyBoolean;
import org.aspectj.weaver.ShadowMunger;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.ISourceContext;
import org.aspectj.weaver.IntMap;
import org.aspectj.weaver.ResolvedPointcutDefinition;
import org.aspectj.weaver.ResolvedTypeX;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.TypeX;
import org.aspectj.weaver.ast.Test;
/**
*/
//XXX needs check that arguments contains no WildTypePatterns
public class ReferencePointcut extends Pointcut {
public TypeX onType;
public TypePattern onTypeSymbolic;
public String name;
public TypePatternList arguments;
//public ResolvedPointcut binding;
public ReferencePointcut(TypePattern onTypeSymbolic, String name, TypePatternList arguments) {
this.onTypeSymbolic = onTypeSymbolic;
this.name = name;
this.arguments = arguments;
}
public ReferencePointcut(TypeX onType, String name, TypePatternList arguments) {
this.onType = onType;
this.name = name;
this.arguments = arguments;
}
//??? do either of these match methods make any sense???
public FuzzyBoolean fastMatch(ResolvedTypeX type) {
return FuzzyBoolean.MAYBE;
}
/**
* Do I really match this shadow?
*/
public FuzzyBoolean match(Shadow shadow) {
return FuzzyBoolean.NO;
}
public String toString() {
StringBuffer buf = new StringBuffer();
if (onType != null) {
buf.append(onType);
buf.append(".");
// for (int i=0, len=fromType.length; i < len; i++) {
// buf.append(fromType[i]);
// buf.append(".");
// }
}
buf.append(name);
buf.append(arguments.toString());
return buf.toString();
}
public void write(DataOutputStream s) throws IOException {
//XXX ignores onType
s.writeByte(Pointcut.REFERENCE);
if (onType != null) {
s.writeBoolean(true);
onType.write(s);
} else {
s.writeBoolean(false);
}
s.writeUTF(name);
arguments.write(s);
writeLocation(s);
}
public static Pointcut read(DataInputStream s, ISourceContext context) throws IOException {
TypeX onType = null;
if (s.readBoolean()) {
onType = TypeX.read(s);
}
ReferencePointcut ret = new ReferencePointcut(onType, s.readUTF(),
TypePatternList.read(s, context));
ret.readLocation(context, s);
return ret;
}
public void resolveBindings(IScope scope, Bindings bindings) {
if (onTypeSymbolic != null) {
onType = onTypeSymbolic.resolveExactType(scope, bindings);
// in this case we've already signalled an error
if (onType == ResolvedTypeX.MISSING) return;
}
ResolvedTypeX searchType;
if (onType != null) {
searchType = scope.getWorld().resolve(onType);
} else {
searchType = scope.getEnclosingType();
}
arguments.resolveBindings(scope, bindings, true, true);
//XXX ensure that arguments has no ..'s in it
// check that I refer to a real pointcut declaration and that I match
ResolvedPointcutDefinition pointcutDef = searchType.findPointcut(name);
// if we're not a static reference, then do a lookup of outers
if (pointcutDef == null && onType == null) {
while (true) {
TypeX declaringType = searchType.getDeclaringType();
if (declaringType == null) break;
searchType = declaringType.resolve(scope.getWorld());
pointcutDef = searchType.findPointcut(name);
if (pointcutDef != null) {
// make this a static reference
onType = searchType;
break;
}
}
}
if (pointcutDef == null) {
scope.message(IMessage.ERROR, this, "can't find referenced pointcut");
return;
}
// check visibility
if (!pointcutDef.isVisible(scope.getEnclosingType())) {
scope.message(IMessage.ERROR, this, "pointcut declaration " + pointcutDef + " is not accessible");
return;
}
if (Modifier.isAbstract(pointcutDef.getModifiers())) {
if (onType != null) {
scope.message(IMessage.ERROR, this,
"can't make static reference to abstract pointcut");
return;
} else if (!searchType.isAbstract()) {
scope.message(IMessage.ERROR, this,
"can't use abstract pointcut in concrete context");
return;
}
}
ResolvedTypeX[] parameterTypes =
scope.getWorld().resolve(pointcutDef.getParameterTypes());
if (parameterTypes.length != arguments.size()) {
scope.message(IMessage.ERROR, this, "incompatible number of arguments to pointcut, expected " +
parameterTypes.length + " found " + arguments.size());
return;
}
for (int i=0,len=arguments.size(); i < len; i++) {
TypePattern p = arguments.get(i);
//we are allowed to bind to pointcuts which use subtypes as this is type safe
if (p == TypePattern.NO) {
scope.message(IMessage.ERROR, this,
"bad parameter to pointcut reference");
return;
}
if (!p.matchesSubtypes(parameterTypes[i]) &&
!p.getExactType().equals(TypeX.OBJECT))
{
scope.message(IMessage.ERROR, p, "incompatible type, expected " +
parameterTypes[i].getName() + " found " + p);
return;
}
}
}
public void postRead(ResolvedTypeX enclosingType) {
arguments.postRead(enclosingType);
}
public Test findResidue(Shadow shadow, ExposedState state) {
throw new RuntimeException("shouldn't happen");
}
//??? This is not thread safe, but this class is not designed for multi-threading
private boolean concretizing = false;
public Pointcut concretize1(ResolvedTypeX searchStart, IntMap bindings) {
if (concretizing) {
//Thread.currentThread().dumpStack();
searchStart.getWorld().getMessageHandler().handleMessage(
MessageUtil.error("circular pointcut declaration involving: " + this,
getSourceLocation()));
return Pointcut.makeMatchesNothing(Pointcut.CONCRETE);
}
try {
concretizing = true;
ResolvedPointcutDefinition pointcutDec;
if (onType != null) {
searchStart = onType.resolve(searchStart.getWorld());
if (searchStart == ResolvedTypeX.MISSING) {
return Pointcut.makeMatchesNothing(Pointcut.CONCRETE);
}
}
pointcutDec = searchStart.findPointcut(name);
if (pointcutDec == null) {
searchStart.getWorld().getMessageHandler().handleMessage(
MessageUtil.error("can't find pointcut \'" + name + "\' on " + searchStart.getName(),
getSourceLocation())
);
return Pointcut.makeMatchesNothing(Pointcut.CONCRETE);
}
if (pointcutDec.isAbstract()) {
//Thread.currentThread().dumpStack();
ShadowMunger enclosingAdvice = bindings.getEnclosingAdvice();
searchStart.getWorld().showMessage(IMessage.ERROR,
pointcutDec + " is abstract",
getSourceLocation(),
(null == enclosingAdvice) ? null : enclosingAdvice.getSourceLocation());
return Pointcut.makeMatchesNothing(Pointcut.CONCRETE);
}
//System.err.println("start: " + searchStart);
ResolvedTypeX[] parameterTypes = searchStart.getWorld().resolve(pointcutDec.getParameterTypes());
TypePatternList arguments = this.arguments.resolveReferences(bindings);
IntMap newBindings = new IntMap();
for (int i=0,len=arguments.size(); i < len; i++) {
TypePattern p = arguments.get(i);
//we are allowed to bind to pointcuts which use subtypes as this is type safe
if (!p.matchesSubtypes(parameterTypes[i]) &&
!p.getExactType().equals(TypeX.OBJECT))
{
throw new BCException("illegal change to pointcut declaration: " + this);
}
if (p instanceof BindingTypePattern) {
newBindings.put(i, ((BindingTypePattern)p).getFormalIndex());
}
}
newBindings.copyContext(bindings);
newBindings.pushEnclosingDefinition(pointcutDec);
try {
return pointcutDec.getPointcut().concretize1(searchStart, newBindings);
} finally {
newBindings.popEnclosingDefinitition();
}
} finally {
concretizing = false;
}
}
public boolean equals(Object other) {
if (!(other instanceof ReferencePointcut)) return false;
ReferencePointcut o = (ReferencePointcut)other;
return o.name.equals(name) && o.arguments.equals(arguments)
&& ((o.onType == null) ? (onType == null) : o.onType.equals(onType));
}
public int hashCode() {
int result = 17;
result = 37*result + ((onType == null) ? 0 : onType.hashCode());
result = 37*result + arguments.hashCode();
result = 37*result + name.hashCode();
return result;
}
}
|
41,952
|
Bug 41952 XLint warning for call PCD's using subtype of defining type
| null |
resolved fixed
|
97ab1e9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-07T17:00:52Z
| 2003-08-26T09:26:40Z
|
weaver/src/org/aspectj/weaver/patterns/SignaturePattern.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.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;
import org.aspectj.weaver.ISourceContext;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.NameMangler;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedTypeX;
import org.aspectj.weaver.TypeX;
import org.aspectj.weaver.World;
public class SignaturePattern extends PatternNode {
private Member.Kind kind;
private ModifiersPattern modifiers;
private TypePattern returnType;
private TypePattern declaringType;
private NamePattern name;
private TypePatternList parameterTypes;
private ThrowsPattern throwsPattern;
public SignaturePattern(Member.Kind kind, ModifiersPattern modifiers,
TypePattern returnType, TypePattern declaringType,
NamePattern name, TypePatternList parameterTypes,
ThrowsPattern throwsPattern) {
this.kind = kind;
this.modifiers = modifiers;
this.returnType = returnType;
this.name = name;
this.declaringType = declaringType;
this.parameterTypes = parameterTypes;
this.throwsPattern = throwsPattern;
}
public SignaturePattern resolveBindings(IScope scope, Bindings bindings) {
if (returnType != null) {
returnType = returnType.resolveBindings(scope, bindings, false, false);
}
if (declaringType != null) {
declaringType = declaringType.resolveBindings(scope, bindings, false, false);
}
if (parameterTypes != null) {
parameterTypes = parameterTypes.resolveBindings(scope, bindings, false, false);
}
if (throwsPattern != null) {
throwsPattern = throwsPattern.resolveBindings(scope, bindings);
}
return this;
}
public void postRead(ResolvedTypeX enclosingType) {
if (returnType != null) {
returnType.postRead(enclosingType);
}
if (declaringType != null) {
declaringType.postRead(enclosingType);
}
if (parameterTypes != null) {
parameterTypes.postRead(enclosingType);
}
}
public boolean matches(Member member, World world) {
//XXX performance gains would come from matching on name before resolving
// to fail fast
ResolvedMember sig = member.resolve(world);
if (sig == null) {
//XXX
if (member.getName().startsWith(NameMangler.PREFIX)) {
return false;
}
world.getLint().unresolvableMember.signal(member.toString(), getSourceLocation());
return false;
}
// This check should only matter when used from WithincodePointcut as KindedPointcut
// has already effectively checked this with the shadows kind.
if (kind != member.getKind()) {
return false;
}
if (kind == Member.ADVICE) return true;
if (!modifiers.matches(sig.getModifiers())) return false;
if (kind == Member.STATIC_INITIALIZATION) {
//System.err.println("match static init: " + sig.getDeclaringType() + " with " + this);
return declaringType.matchesStatically(sig.getDeclaringType().resolve(world));
} else if (kind == Member.FIELD) {
if (!returnType.matchesStatically(sig.getReturnType().resolve(world))) return false;
if (!name.matches(sig.getName())) return false;
boolean ret = declaringTypeMatch(member.getDeclaringType(), member, world);
//System.out.println(" ret: " + ret);
return ret;
} else if (kind == Member.METHOD) {
if (!returnType.matchesStatically(sig.getReturnType().resolve(world))) return false;
if (!name.matches(sig.getName())) return false;
if (!parameterTypes.matches(world.resolve(sig.getParameterTypes()), TypePattern.STATIC).alwaysTrue()) {
return false;
}
if (!throwsPattern.matches(sig.getExceptions(), world)) return false;
return declaringTypeMatch(member.getDeclaringType(), member, world);
} else if (kind == Member.CONSTRUCTOR) {
if (!parameterTypes.matches(world.resolve(sig.getParameterTypes()), TypePattern.STATIC).alwaysTrue()) {
return false;
}
if (!throwsPattern.matches(sig.getExceptions(), world)) return false;
return declaringType.matchesStatically(member.getDeclaringType().resolve(world));
//return declaringTypeMatch(member.getDeclaringType(), member, world);
}
return false;
}
private boolean declaringTypeMatch(TypeX onTypeUnresolved, Member member, World world) {
ResolvedTypeX onType = onTypeUnresolved.resolve(world);
// fastmatch
if (declaringType.matchesStatically(onType)) return true;
Collection declaringTypes = member.getDeclaringTypes(world);
for (Iterator i = declaringTypes.iterator(); i.hasNext(); ) {
ResolvedTypeX type = (ResolvedTypeX)i.next();
if (declaringType.matchesStatically(type)) return true;
}
return false;
}
public NamePattern getName() { return name; }
public TypePattern getDeclaringType() { return declaringType; }
public Member.Kind getKind() {
return kind;
}
public String toString() {
StringBuffer buf = new StringBuffer();
if (modifiers != ModifiersPattern.ANY) {
buf.append(modifiers.toString());
buf.append(' ');
}
if (kind == Member.STATIC_INITIALIZATION) {
buf.append(declaringType.toString());
buf.append(".<clinit>()");
} else if (kind == Member.HANDLER) {
buf.append("handler(");
buf.append(parameterTypes.get(0));
buf.append(")");
} else {
if (!(kind == Member.CONSTRUCTOR)) {
buf.append(returnType.toString());
buf.append(' ');
}
if (declaringType != TypePattern.ANY) {
buf.append(declaringType.toString());
buf.append('.');
}
if (kind == Member.CONSTRUCTOR) {
buf.append("new");
} else {
buf.append(name.toString());
}
if (kind == Member.METHOD || kind == Member.CONSTRUCTOR) {
buf.append(parameterTypes.toString());
}
}
return buf.toString();
}
public boolean equals(Object other) {
if (!(other instanceof SignaturePattern)) return false;
SignaturePattern o = (SignaturePattern)other;
return o.kind.equals(this.kind)
&& o.modifiers.equals(this.modifiers)
&& o.returnType.equals(this.returnType)
&& o.declaringType.equals(this.declaringType)
&& o.name.equals(this.name)
&& o.parameterTypes.equals(this.parameterTypes);
}
public int hashCode() {
int result = 17;
result = 37*result + kind.hashCode();
result = 37*result + modifiers.hashCode();
result = 37*result + returnType.hashCode();
result = 37*result + declaringType.hashCode();
result = 37*result + name.hashCode();
result = 37*result + parameterTypes.hashCode();
return result;
}
public void write(DataOutputStream s) throws IOException {
kind.write(s);
modifiers.write(s);
returnType.write(s);
declaringType.write(s);
name.write(s);
parameterTypes.write(s);
throwsPattern.write(s);
writeLocation(s);
}
public static SignaturePattern read(DataInputStream s, ISourceContext context) throws IOException {
Member.Kind kind = Member.Kind.read(s);
ModifiersPattern modifiers = ModifiersPattern.read(s);
TypePattern returnType = TypePattern.read(s, context);
TypePattern declaringType = TypePattern.read(s, context);
NamePattern name = NamePattern.read(s);
TypePatternList parameterTypes = TypePatternList.read(s, context);
ThrowsPattern throwsPattern = ThrowsPattern.read(s, context);
SignaturePattern ret = new SignaturePattern(kind, modifiers, returnType, declaringType,
name, parameterTypes, throwsPattern);
ret.readLocation(context, s);
return ret;
}
}
|
49,638
|
Bug 49638 exception logging: after() throwing advice can't convert Throwable obj to string and ajc aborts
| null |
resolved fixed
|
7b081f2
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-09T09:21:03Z
| 2004-01-07T18:26:40Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/parser/AjParser.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.parser;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.List;
import org.aspectj.ajdt.internal.compiler.ast.AdviceDeclaration;
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.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.ISourceContext;
import org.aspectj.weaver.patterns.Declare;
import org.eclipse.jdt.internal.compiler.CompilationResult;
import org.eclipse.jdt.internal.compiler.ast.Argument;
import org.eclipse.jdt.internal.compiler.ast.AstNode;
import org.eclipse.jdt.internal.compiler.ast.ExplicitConstructorCall;
import org.eclipse.jdt.internal.compiler.ast.Expression;
import org.eclipse.jdt.internal.compiler.ast.Literal;
import org.eclipse.jdt.internal.compiler.ast.MessageSend;
import org.eclipse.jdt.internal.compiler.ast.OperatorExpression;
import org.eclipse.jdt.internal.compiler.ast.TypeReference;
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
import org.eclipse.jdt.internal.compiler.parser.Parser;
import org.eclipse.jdt.internal.compiler.parser.RecoveredType;
import org.eclipse.jdt.internal.compiler.problem.ProblemReporter;
import org.eclipse.jdt.internal.compiler.problem.ProblemSeverities;
import org.eclipse.jdt.core.compiler.CharOperation;
import org.eclipse.jdt.internal.core.util.CharArrayOps;
public class AjParser extends Parser {
//===DATA===DATA===DATA===DATA===DATA===DATA===//
public final static byte rhs[] = {0,
2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
2,2,2,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,2,2,1,1,1,1,1,1,1,1,1,
1,1,1,1,3,1,1,1,3,4,0,1,2,1,1,
1,1,1,1,1,1,1,5,1,2,1,2,2,2,1,
1,2,2,2,4,1,1,1,1,2,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,2,4,3,5,0,2,1,3,1,2,0,2,
1,3,5,4,1,1,2,5,4,2,6,3,3,4,3,
1,0,1,3,1,1,1,1,2,4,6,2,2,3,5,
7,0,4,1,3,3,1,2,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,4,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,2,3,3,2,2,1,3,1,3,1,2,1,
1,1,3,0,3,1,1,1,1,1,1,1,4,1,3,
3,7,0,0,0,0,0,2,1,1,1,2,2,4,4,
5,4,4,2,1,2,3,3,3,1,3,3,1,3,1,
4,0,2,1,2,2,4,1,1,2,5,5,7,7,7,
7,2,2,3,2,2,3,1,2,1,2,1,1,2,2,
1,1,1,1,1,3,3,4,1,3,4,0,1,2,1,
1,1,1,2,3,4,0,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,3,3,2,1,1,1,1,1,1,1,5,7,7,6,
2,3,3,4,1,2,2,1,2,3,2,5,5,7,9,
9,1,1,1,1,3,3,5,2,3,2,3,3,3,5,
1,3,4,1,2,5,2,1,1,1,1,1,1,1,3,
1,1,3,3,3,3,3,1,1,5,6,8,7,2,0,
2,0,1,3,3,4,3,4,1,2,3,2,1,1,2,
2,3,3,4,6,6,4,4,4,1,1,1,1,2,2,
0,1,1,3,3,1,3,3,1,3,3,1,6,6,5,
0,0,1,3,3,3,1,3,3,1,3,3,3,1,3,
3,3,3,3,1,3,3,1,3,1,3,1,3,1,3,
1,3,1,5,1,1,3,3,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,0,1,0,1,0,1,0,
1,0,1,0,1,0,2,0,1,0,1,0,1,0,1,
0,1,0,1,0,1,0,2,0,0,1,0,1,0,1,
0,1
};
public static char asbStatic[] = null;
public static char asrStatic[] = null;
public static char symbol_indexStatic[] = null;
public final static String name[] = { null,
"++",
"--",
"==",
"<=",
">=",
"!=",
"<<",
">>",
">>>",
"+=",
"-=",
"*=",
"/=",
"&=",
"|=",
"^=",
"%=",
"<<=",
">>=",
">>>=",
"||",
"&&",
"+",
"-",
"!",
"%",
"^",
"&",
"*",
"|",
"~",
"/",
">",
"<",
"(",
")",
"{",
"}",
"[",
"]",
";",
"?",
":",
",",
".",
"=",
"",
"$empty",
"Identifier",
"abstract",
"assert",
"boolean",
"break",
"byte",
"case",
"catch",
"char",
"class",
"continue",
"default",
"do",
"double",
"else",
"extends",
"false",
"final",
"finally",
"float",
"for",
"if",
"implements",
"import",
"instanceof",
"int",
"interface",
"long",
"native",
"new",
"null",
"package",
"private",
"protected",
"public",
"return",
"short",
"static",
"strictfp",
"super",
"switch",
"synchronized",
"this",
"throw",
"throws",
"transient",
"true",
"try",
"void",
"volatile",
"while",
"aspect",
"pointcut",
"around",
"before",
"after",
"declare",
"privileged",
"IntegerLiteral",
"LongLiteral",
"FloatingPointLiteral",
"DoubleLiteral",
"CharacterLiteral",
"StringLiteral",
UNEXPECTED_EOF,
"Invalid Character",
"Goal",
"MethodBody",
"ConstructorBody",
"StaticInitializer",
"Initializer",
"Headers",
"BlockStatements",
"MethodPushModifiersHeader",
"CatchHeader",
"FieldDeclaration",
"ImportDeclaration",
"PackageDeclaration",
"TypeDeclaration",
"GenericMethodDeclaration",
"ClassBodyDeclaration",
"Expression",
"JavaIdentifier",
"AjSimpleName",
"JavaIdentifierNoAround",
"AjSimpleNameNoAround",
"Type",
"PrimitiveType",
"ReferenceType",
"ClassOrInterfaceType",
"ArrayType",
"Name",
"Dims",
"ClassType",
"NameOrAj",
"AjName",
"SimpleName",
"Header",
"ClassHeader",
"InterfaceHeader",
"MethodHeader",
"ConstructorHeader",
"FormalParameter",
"ImportDeclarations",
"TypeDeclarations",
"PackageDeclarationName",
"SingleTypeImportDeclarationNam" +
"e",
"TypeImportOnDemandDeclarationN" +
"ame",
"Modifiers",
"Modifier",
"InterfaceMemberDeclaration",
"AspectHeader",
"AspectBody",
"AspectHeaderName",
"AspectHeaderRestStart",
"PseudoTokens",
"AspectBodyDeclarations",
"AspectBodyDeclaration",
"PointcutHeader",
"MethodHeaderParameters",
"AroundHeader",
"AroundHeaderName",
"BasicAdviceHeader",
"BasicAdviceHeaderName",
"OnType",
"InterTypeMethodHeader",
"InterTypeMethodHeaderName",
"InterTypeConstructorHeader",
"InterTypeConstructorHeaderName",
"VariableInitializer",
"DeclareHeader",
"PseudoToken",
"ClassBody",
"ClassHeaderName",
"InterfaceTypeList",
"InterfaceType",
"ClassBodyDeclarations",
"Block",
"VariableDeclarators",
"VariableDeclarator",
"VariableDeclaratorId",
"ArrayInitializer",
"MethodHeaderName",
"MethodPushModifiersHeaderName",
"ClassTypeList",
"ConstructorHeaderName",
"FormalParameterList",
"ClassTypeElt",
"StaticOnly",
"ExplicitConstructorInvocation",
"Primary",
"InterfaceBody",
"InterfaceHeaderName",
"InterfaceMemberDeclarations",
"VariableInitializers",
"BlockStatement",
"Statement",
"LocalVariableDeclaration",
"StatementWithoutTrailingSubsta" +
"tement",
"StatementNoShortIf",
"StatementExpression",
"PostIncrementExpression",
"PostDecrementExpression",
"MethodInvocation",
"ClassInstanceCreationExpressio" +
"n",
"SwitchBlock",
"SwitchBlockStatements",
"SwitchLabels",
"SwitchBlockStatement",
"SwitchLabel",
"ConstantExpression",
"StatementExpressionList",
"OnlySynchronized",
"Catches",
"Finally",
"CatchClause",
"PushLPAREN",
"PushRPAREN",
"PrimaryNoNewArray",
"ArrayCreationWithArrayInitiali" +
"zer",
"ClassInstanceCreationExpressio" +
"nName",
"ArgumentList",
"DimWithOrWithOutExprs",
"DimWithOrWithOutExpr",
"DimsLoop",
"OneDimLoop",
"PostfixExpression",
"UnaryExpression",
"UnaryExpressionNotPlusMinus",
"MultiplicativeExpression",
"AdditiveExpression",
"ShiftExpression",
"RelationalExpression",
"EqualityExpression",
"AndExpression",
"ExclusiveOrExpression",
"InclusiveOrExpression",
"ConditionalAndExpression",
"ConditionalOrExpression",
"ConditionalExpression",
"AssignmentExpression",
"AssignmentOperator"
};
public static short check_tableStatic[] = null;
public static char lhsStatic[] = null;
public static char actionStatic[] = lhsStatic;
protected void initData() {
rhsInst = rhs;
asb = asbStatic;
asr = asrStatic;
symbol_index = symbol_indexStatic;
nameInst = name;
check_table = check_tableStatic;
lhs = lhsStatic;
action = actionStatic;
}
static {
try{
initAjTables(AjParser.class);
} catch(java.io.IOException ex){
throw new ExceptionInInitializerError(ex.getMessage());
}
}
public final static void initAjTables(Class parserClass)
throws java.io.IOException {
final String prefix = FILEPREFIX;
int i = 0;
lhsStatic = readTable(parserClass, prefix + (++i) + ".rsc"); //$NON-NLS-1$
char[] chars = readTable(parserClass, prefix + (++i) + ".rsc"); //$NON-NLS-1$
check_tableStatic = new short[chars.length];
for (int c = chars.length; c-- > 0;) {
check_tableStatic[c] = (short) (chars[c] - 32768);
}
asbStatic = readTable(parserClass, prefix + (++i) + ".rsc"); //$NON-NLS-1$
asrStatic = readTable(parserClass, prefix + (++i) + ".rsc"); //$NON-NLS-1$
symbol_indexStatic = readTable(parserClass, prefix + (++i) + ".rsc"); //$NON-NLS-1$
actionStatic = lhsStatic;
}
public void initializeScanner(){
CompilerOptions options = this.problemReporter.options;
this.scanner = new AjScanner(
false /*comment*/,
false /*whitespace*/,
options.getSeverity(CompilerOptions.NonExternalizedString) != ProblemSeverities.Ignore /*nls*/,
this.assertMode /*assert*/,
options.taskTags/*taskTags*/,
options.taskPriorites/*taskPriorities*/);
}
//*************New display debugging method
private static final boolean AJ_DEBUG = false;
void println(Object o) {
if (AJ_DEBUG) System.out.println(o);
}
private void printStack(Object[] s, int p) {
List list = Arrays.asList(s);
System.out.println(" " + list.subList(0, p+1));
}
private void printStack(int[] s, int p) {
StringBuffer buf = new StringBuffer("[");
for (int i=0; i<p+1; i++) {
if (i > 0) buf.append(", ");
buf.append(Integer.toString(s[i]));
}
buf.append("]");
System.out.println(" " + buf);
}
private void printStack(long[] s, int p) {
StringBuffer buf = new StringBuffer("[");
for (int i=0; i<p+1; i++) {
if (i > 0) buf.append(", ");
buf.append(Long.toString(s[i]));
}
buf.append("]");
System.out.println(" " + buf);
}
private void printStack(char[][] s, int p) {
StringBuffer buf = new StringBuffer("[");
for (int i=0; i<p+1; i++) {
if (i > 0) buf.append(", ");
buf.append(new String(s[i]));
}
buf.append("]");
System.out.println(" " + buf);
}
public void display() {
if (!AJ_DEBUG) return;
System.out.print("astStack: ");
printStack(astStack, astPtr);
System.out.print("astLengthStack: ");
printStack(astLengthStack, astLengthPtr);
System.out.print("expressionStack: ");
printStack(expressionStack, expressionPtr);
System.out.print("expressionLengthStack: ");
printStack(expressionLengthStack, expressionLengthPtr);
System.out.print("identifierStack: ");
printStack(identifierStack, identifierPtr);
System.out.print("identifierLengthStack: ");
printStack(identifierLengthStack, identifierLengthPtr);
System.out.print("identifierPositionStack: ");
printStack(identifierPositionStack, identifierPtr);
System.out.print("intStack:");
printStack(intStack, intPtr);
System.out.println();
}
//************** Overriding behavior for standard Java rules
protected void consumeMethodInvocationName() {
super.consumeMethodInvocationName();
MessageSend m = (MessageSend)expressionStack[expressionPtr];
if (CharArrayOps.equals(m.selector, "proceed".toCharArray())) {
expressionStack[expressionPtr] = new Proceed(m);
}
}
protected void consumeToken(int type) {
currentTokenStart = scanner.startPosition;
super.consumeToken(type);
switch (type) {
case TokenNameaspect : // pseudo keyword
case TokenNameprivileged : // pseudo keyword
case TokenNamepointcut : // pseudo keyword
case TokenNamebefore : // pseudo keyword
case TokenNameafter : // pseudo keyword
case TokenNamearound : // pseudo keyword
case TokenNamedeclare : // pseudo keyword
pushIdentifier();
scanner.commentPtr = -1;
break;
}
}
//************New AspectJ rules
protected void consumeAspectDeclaration() {
// AspectDeclaration ::= AspectHeader AspectBody
consumeClassDeclaration();
//??? post parsing step here
}
protected void consumeAspectHeader() {
// AspectHeader ::= AspectHeaderName ClassHeaderExtendsopt ClassHeaderImplementsopt AspectHeaderRest
consumeClassHeader();
}
protected void consumeAspectHeaderName(boolean isPrivileged) {
// (isPrivileged == false) -> AspectHeaderName ::= Modifiersopt 'aspect' 'Identifier'
// (isPrivileged == true) -> AspectHeaderName ::= Modifiersopt 'privileged' Modifiersopt 'aspect' 'Identifier'
AspectDeclaration aspectDecl =
new AspectDeclaration(this.compilationUnit.compilationResult);
println("aspect header name: ");
this.display();
//highlight the name of the type
long pos = identifierPositionStack[identifierPtr];
aspectDecl.sourceEnd = (int) pos;
aspectDecl.sourceStart = (int) (pos >>> 32);
aspectDecl.name = identifierStack[identifierPtr--];
identifierLengthPtr--;
// pop the aspect pseudo-token
eatIdentifier();
// handle modifiers, only without privileged for now
if (isPrivileged) {
pos = eatIdentifier(); // eat the privileged
int end = (int) pos;
int start = (int) (pos >>> 32);
aspectDecl.isPrivileged = true;
//problemReporter().signalError(start, end, "privileged is unimplemented in 1.1alpha1");
}
aspectDecl.modifiersSourceStart = intStack[intPtr--];
aspectDecl.modifiers = intStack[intPtr--];
if (aspectDecl.modifiersSourceStart >= 0) {
aspectDecl.declarationSourceStart = aspectDecl.modifiersSourceStart;
}
println("modifiers: " + aspectDecl.modifiers);
aspectDecl.bodyStart = aspectDecl.sourceEnd + 1;
pushOnAstStack(aspectDecl);
listLength = 0; // will be updated when reading super-interfaces
// recovery
if (currentElement != null) {
lastCheckPoint = aspectDecl.bodyStart;
currentElement = currentElement.add(aspectDecl, 0);
lastIgnoredToken = -1;
}
this.display();
}
private long eatIdentifier() {
long pos = identifierPositionStack[identifierPtr];
identifierPtr--;
identifierLengthPtr--;
return pos;
}
protected void consumeAspectHeaderRest() {
//--[dominates TypePattern] [persingleton() | percflow(PCD) | perthis(PCD) | pertarget(PCD)]
//AspectHeaderRest ::= AspectHeaderRestStart PseudoTokens
concatNodeLists();
this.display();
PseudoTokens pseudoTokens = popPseudoTokens("{");
println("pseudo: " + pseudoTokens);
AspectDeclaration aspectDecl = (AspectDeclaration) astStack[astPtr];
aspectDecl.dominatesPattern = pseudoTokens.maybeParseDominatesPattern(this);
aspectDecl.perClause = pseudoTokens.parsePerClause(this);
// XXX handle dominates
}
protected void consumePointcutDeclaration() {
consumePointcutDesignatorOnDeclaration();
}
protected void consumeEmptyPointcutDeclaration() {
//??? set pcd to non-null
}
protected void consumePointcutHeader() {
//PointcutDeclaration ::= Modifiersopt 'pointcut' JavaIdentifier '('
PointcutDeclaration ret = new PointcutDeclaration(compilationUnit.compilationResult);
//the name
long pos = identifierPositionStack[identifierPtr];
int sourceEnd = (int) pos;
ret.sourceStart = (int) (pos >>> 32);
ret.selector = identifierStack[identifierPtr--];
identifierLengthPtr--;
// pop the 'pointcut' keyword
eatIdentifier();
// modifiers
ret.declarationSourceStart = intStack[intPtr--];
ret.modifiers = intStack[intPtr--];
pushOnAstStack(ret);
}
protected void consumeAroundDeclaration() {
// AroundDeclaration ::= AroundHeader MethodBody
consumeMethodDeclaration(true);
}
protected void consumeAroundHeader() {
consumePointcutDesignatorOnAdvice();
}
protected void consumeAroundHeaderName() {
// AroundHeaderName ::= Modifiersopt Type 'around' '('
AdviceDeclaration adviceDecl =
new AdviceDeclaration(compilationUnit.compilationResult, AdviceKind.Around);
// skip the name of the advice
long pos = eatIdentifier();
adviceDecl.sourceStart = (int) (pos >>> 32);
TypeReference returnType = getTypeReference(intStack[intPtr--]);
//modifiers
adviceDecl.declarationSourceStart = intStack[intPtr--];
adviceDecl.modifiers = intStack[intPtr--];
adviceDecl.returnType = returnType;
//XXX get some locations right
pushOnAstStack(adviceDecl);
}
protected void consumePointcutDesignatorOnAdvice() {
PointcutDesignator des = popPointcutDesignator("{");
AdviceDeclaration adviceDecl = (AdviceDeclaration)astStack[astPtr];
adviceDecl.pointcutDesignator = des;
adviceDecl.sourceEnd = des.sourceEnd;
adviceDecl.bodyStart = des.sourceEnd+1;
}
protected void consumePointcutDesignatorOnDeclaration() {
PointcutDesignator des = popPointcutDesignator(";");
PointcutDeclaration adviceDecl = (PointcutDeclaration)astStack[astPtr];
adviceDecl.pointcutDesignator = des;
adviceDecl.sourceEnd = des.sourceEnd;
adviceDecl.bodyStart = des.sourceEnd+1;
}
protected void consumeBasicAdviceDeclaration() {
// BasicAdviceDeclaration ::= BasicAdviceHeader MethodBody
consumeMethodDeclaration(true);
}
protected void consumeBasicAdviceHeader() {
// BasicAdviceHeader ::= BasicAdviceHeaderName MethodHeaderParameters ExtraParamopt MethodHeaderThrowsClauseopt ':' PseudoTokens
consumePointcutDesignatorOnAdvice();
}
protected void consumeBasicAdviceHeaderName(boolean isAfter) {
// BasicAdviceHeaderName ::= 'before'|'after '('
AdviceDeclaration adviceDecl =
new AdviceDeclaration(compilationUnit.compilationResult, isAfter ? AdviceKind.After : AdviceKind.Before);
// skip the name of the advice
long pos = eatIdentifier();
adviceDecl.sourceStart = (int) (pos >>> 32);
//modifiers
adviceDecl.declarationSourceStart = intStack[intPtr--];
adviceDecl.modifiers = intStack[intPtr--];
//??? get more locations right
pushOnAstStack(adviceDecl);
}
protected void consumeExtraParameterWithFormal() {
Argument arg = (Argument)astStack[astPtr--];
astLengthPtr--;
((AdviceDeclaration)astStack[astPtr]).extraArgument = arg;
consumeExtraParameterNoFormal();
}
protected void consumeExtraParameterNoFormal() {
long pos = identifierPositionStack[identifierPtr];
int end = (int) pos;
int start = (int) (pos >>> 32);
char[] name = identifierStack[identifierPtr--];
identifierLengthPtr--;
//System.out.println("extra parameter: " + new String(name));
AdviceDeclaration adviceDecl = (AdviceDeclaration)astStack[astPtr];
if (adviceDecl.kind != AdviceKind.After) {
//XXX error, extra param makes no sense here
}
if (CharOperation.equals(name, "throwing".toCharArray())) {
adviceDecl.kind = AdviceKind.AfterThrowing;
} else if (CharOperation.equals(name, "returning".toCharArray())) {
adviceDecl.kind = AdviceKind.AfterReturning;
} else {
//XXX illegal name here
}
}
protected void consumeClassBodyDeclarationInAspect() { }
protected void consumeDeclareDeclaration() {
concatNodeLists();
PseudoTokens tokens = popPseudoTokens(";");
Declare declare = tokens.parseDeclare(this);
println("parsed declare: " + declare);
display();
pushOnAstStack(new DeclareDeclaration(this.compilationUnit.compilationResult, declare));
}
protected void consumeDeclareHeader() {
consumePseudoTokenIdentifier(); // name
consumePseudoTokenIdentifier(); // declare
swapAstStack();
consumePseudoTokens();
consumePseudoToken(":", 0, false);
consumePseudoTokens();
println(">>>>>>>>>>>>>>>>>>>>>>>declare header");
display();
}
protected void consumeInterTypeFieldDeclaration() {
// InterTypeFieldDeclaration ::= Modifiersopt Type OnType '.' JavaIdentifier InterTypeFieldBody ';'
println("about to consume field");
this.display();
// FieldDeclaration field = new FieldDeclaration();
Expression initialization = null;
if (expressionPtr >= 0) {
expressionLengthPtr--;
initialization = expressionStack[expressionPtr--];
}
long pos = identifierPositionStack[identifierPtr];
int end = (int) pos;
int start = (int) (pos >>> 32);
char[] name = identifierStack[identifierPtr--];
identifierLengthPtr--;
// field.name = name;
// field.sourceStart = start;
// field.sourceEnd = end;
TypeReference onType = getTypeReference(0);
TypeReference returnType = getTypeReference(intStack[intPtr--]);
this.display();
int decSourceStart = intStack[intPtr--];
int modifiers = intStack[intPtr--];
InterTypeFieldDeclaration dec =
new InterTypeFieldDeclaration(
this.compilationUnit.compilationResult,
onType);
dec.returnType = returnType;
dec.sourceStart = start;
dec.sourceEnd = end;
dec.setSelector(name);
dec.declarationSourceStart = decSourceStart;
dec.setDeclaredModifiers(modifiers);
dec.setInitialization(initialization);
pushOnAstStack(dec);
println("consumed field: " + dec);
this.display();
}
protected void consumeInterTypeMethodDeclaration(boolean isNotAbstract) {
consumeMethodDeclaration(isNotAbstract);
}
protected void consumeInterTypeMethodHeader() {
consumeMethodHeader();
}
protected void consumeInterTypeConstructorDeclaration() {
consumeMethodDeclaration(true);
}
protected void consumeInterTypeConstructorHeader() {
consumeMethodHeader();
}
protected void consumeInterTypeMethodHeaderName() {
//InterTypeMethodHeaderName ::= Modifiersopt Type OnType '.' JavaIdentifier '('
this.display();
InterTypeMethodDeclaration md =
new InterTypeMethodDeclaration(
this.compilationUnit.compilationResult,
null);
//identifier
char[] name = identifierStack[identifierPtr];
long selectorSource = identifierPositionStack[identifierPtr--];
identifierLengthPtr--;
//onType
md.onType = getTypeReference(0);
//type
md.returnType = getTypeReference(intStack[intPtr--]);
//modifiers
md.declarationSourceStart = intStack[intPtr--];
md.setDeclaredModifiers(intStack[intPtr--]);
//highlight starts at selector start
md.sourceStart = (int) (selectorSource >>> 32);
pushOnAstStack(md);
md.sourceEnd = lParenPos;
md.bodyStart = lParenPos + 1;
md.setSelector(name);
listLength = 0;
// initialize listLength before reading parameters/throws
// recovery
if (currentElement != null) {
if (currentElement instanceof RecoveredType
//|| md.modifiers != 0
|| (scanner.getLineNumber(md.returnType.sourceStart)
== scanner.getLineNumber(md.sourceStart))) {
lastCheckPoint = md.bodyStart;
currentElement = currentElement.add(md, 0);
lastIgnoredToken = -1;
} else {
lastCheckPoint = md.sourceStart;
restartRecovery = true;
}
}
}
protected void consumeInterTypeConstructorHeaderName() {
//InterTypeConstructorHeaderName ::= Modifiersopt Name '.' 'new' '('
this.display();
InterTypeConstructorDeclaration md =
new InterTypeConstructorDeclaration(
this.compilationUnit.compilationResult,
null);
//identifier
// md.selector = identifierStack[identifierPtr];
// long selectorSource = identifierPositionStack[identifierPtr--];
//// identifierLengthPtr--;
//onType
md.onType = getTypeReference(0);
println("got onType: " + md.onType);
this.display();
intPtr--; // pop new info
//type
md.returnType = TypeReference.baseTypeReference(T_void, 0); //getTypeReference(intStack[intPtr--]);
//modifiers
md.declarationSourceStart = intStack[intPtr--];
md.setDeclaredModifiers(intStack[intPtr--]);
//md.modifiers = intStack[intPtr--];
//highlight starts at selector start
//md.sourceStart = (int) (selectorSource >>> 32);
md.sourceStart = md.onType.sourceStart;
pushOnAstStack(md);
md.sourceEnd = lParenPos;
md.bodyStart = lParenPos + 1;
listLength = 0;
// initialize listLength before reading parameters/throws
md.setSelector(
(new String(CharOperation.concatWith(md.onType.getTypeName(), '_')) + "_new").
toCharArray());
// recovery
if (currentElement != null) {
if (currentElement instanceof RecoveredType
//|| md.modifiers != 0
//|| (scanner.getLineNumber(md.returnType.sourceStart)
// == scanner.getLineNumber(md.sourceStart))
) {
//lastCheckPoint = md.bodyStart;
currentElement = currentElement.add(md, 0);
lastIgnoredToken = -1;
} else {
lastCheckPoint = md.sourceStart;
restartRecovery = true;
}
}
}
//*********************************************************
protected void consumePseudoToken(String value) {
consumePseudoToken(value, 0, false);
}
protected void consumePseudoToken(
String value,
int popFromIntStack,
boolean isIdentifier) {
intPtr -= popFromIntStack;
int start = currentTokenStart;
int end = start + value.length() - 1;
PseudoToken tok = new PseudoToken(this, value, isIdentifier);
tok.sourceStart = start;
tok.sourceEnd = end;
pushOnAstStack(tok);
}
protected void consumePseudoTokenIdentifier() {
long pos = identifierPositionStack[identifierPtr];
int end = (int) pos;
int start = (int) (pos >>> 32);
char[] name = identifierStack[identifierPtr--];
identifierLengthPtr--;
PseudoToken tok = new PseudoToken(this, new String(name), true);
tok.sourceStart = start;
tok.sourceEnd = end;
pushOnAstStack(tok);
}
protected void consumePseudoTokenIf() {
//this.display();
Expression expr = (Expression) expressionStack[expressionPtr--];
expressionLengthPtr--;
println("expr: " + expr);
int start = intStack[intPtr--];
PseudoToken tok = new IfPseudoToken(this, expr);
tok.sourceStart = start;
tok.sourceEnd = this.rParenPos;
pushOnAstStack(tok);
}
protected void consumePseudoTokenLiteral() {
Literal literal = (Literal) expressionStack[expressionPtr--];
expressionLengthPtr--;
//System.out.println("literal: " + new String(literal.source()));
PseudoToken tok =
new PseudoToken(this, new String(literal.source()), false);
tok.literalKind = "string";
tok.sourceStart = literal.sourceStart;
tok.sourceEnd = literal.sourceEnd;
pushOnAstStack(tok);
}
protected void consumePseudoTokenModifier() {
//int modifier = modifiers;
consumePseudoToken(Modifier.toString(modifiers), 0, true);
modifiers = AccDefault;
}
protected void consumePseudoTokenPrimitiveType() {
TypeReference type = getTypeReference(0);
PseudoToken tok = new PseudoToken(this, type.toString(), true);
tok.sourceStart = type.sourceStart;
tok.sourceEnd = type.sourceEnd;
pushOnAstStack(tok);
}
protected void consumePseudoTokens() {
optimizedConcatNodeLists();
}
// Helpers
protected PointcutDesignator popPointcutDesignator(String terminator) {
PseudoTokens tokens = popPseudoTokens(terminator);
return new PointcutDesignator(this, tokens);
}
protected PseudoTokens popPseudoTokens(String terminator) {
consumePseudoToken(terminator);
consumePseudoTokens();
//System.out.println("next token is: " + new String(scanner.getCurrentTokenSource()));
int length = astLengthStack[astLengthPtr--];
astPtr -= length;
//arguments
PseudoToken[] tokens = new PseudoToken[length];
System.arraycopy(astStack, astPtr + 1, tokens, 0, length);
//md.bodyStart = rParenPos+1;
listLength = 0; // reset listLength after having read all parameters
return new PseudoTokens(tokens, makeSourceContext(this.compilationUnit.compilationResult()));
}
private ISourceContext makeSourceContext(CompilationResult compilationResult) {
return new EclipseSourceContext(compilationResult);
}
private void swapAstStack() {
AstNode top = astStack[astPtr];
AstNode next = astStack[astPtr-1];
astStack[astPtr] = next;
astStack[astPtr-1] = top;
}
// This method is part of an automatic generation : do NOT edit-modify
// This method is part of an automatic generation : do NOT edit-modify
protected void consumeRule(int act) {
switch ( act ) {
case 33 : // System.out.println("Type ::= PrimitiveType");
consumePrimitiveType();
break ;
case 47 : // System.out.println("ReferenceType ::= ClassOrInterfaceType");
consumeReferenceType();
break ;
case 65 : // System.out.println("AjQualifiedName ::= AjName DOT SimpleName");
consumeQualifiedName();
break ;
case 69 : // System.out.println("QualifiedName ::= Name DOT JavaIdentifier");
consumeQualifiedName();
break ;
case 70 : // System.out.println("CompilationUnit ::= EnterCompilationUnit PackageDeclarationopt ImportDeclarationsopt");
consumeCompilationUnit();
break ;
case 71 : // System.out.println("EnterCompilationUnit ::=");
consumeEnterCompilationUnit();
break ;
case 83 : // System.out.println("CatchHeader ::= catch LPAREN FormalParameter RPAREN LBRACE");
consumeCatchHeader();
break ;
case 85 : // System.out.println("ImportDeclarations ::= ImportDeclarations ImportDeclaration");
consumeImportDeclarations();
break ;
case 87 : // System.out.println("TypeDeclarations ::= TypeDeclarations TypeDeclaration");
consumeTypeDeclarations();
break ;
case 88 : // System.out.println("PackageDeclaration ::= PackageDeclarationName SEMICOLON");
consumePackageDeclaration();
break ;
case 89 : // System.out.println("PackageDeclarationName ::= package Name");
consumePackageDeclarationName();
break ;
case 92 : // System.out.println("SingleTypeImportDeclaration ::= SingleTypeImportDeclarationName SEMICOLON");
consumeSingleTypeImportDeclaration();
break ;
case 93 : // System.out.println("SingleTypeImportDeclarationName ::= import Name");
consumeSingleTypeImportDeclarationName();
break ;
case 94 : // System.out.println("TypeImportOnDemandDeclaration ::= TypeImportOnDemandDeclarationName SEMICOLON");
consumeTypeImportOnDemandDeclaration();
break ;
case 95 : // System.out.println("TypeImportOnDemandDeclarationName ::= import Name DOT MULTIPLY");
consumeTypeImportOnDemandDeclarationName();
break ;
case 98 : // System.out.println("TypeDeclaration ::= SEMICOLON");
consumeEmptyTypeDeclaration();
break ;
case 124 : // System.out.println("AspectDeclaration ::= AspectHeader AspectBody");
consumeAspectDeclaration();
break ;
case 125 : // System.out.println("AspectHeader ::= AspectHeaderName ClassHeaderExtendsopt ClassHeaderImplementsopt...");
consumeAspectHeader();
break ;
case 126 : // System.out.println("AspectHeaderName ::= Modifiersopt aspect Identifier");
consumeAspectHeaderName(false);
break ;
case 127 : // System.out.println("AspectHeaderName ::= Modifiersopt privileged Modifiersopt aspect Identifier");
consumeAspectHeaderName(true);
break ;
case 129 : // System.out.println("AspectHeaderRest ::= AspectHeaderRestStart PseudoTokens");
consumeAspectHeaderRest();
break ;
case 130 : // System.out.println("AspectHeaderRestStart ::= Identifier");
consumePseudoTokenIdentifier();
break ;
case 133 : // System.out.println("AspectBodyDeclarations ::= AspectBodyDeclarations AspectBodyDeclaration");
consumeClassBodyDeclarations();
break ;
case 134 : // System.out.println("AspectBodyDeclarationsopt ::=");
consumeEmptyClassBodyDeclarationsopt();
break ;
case 135 : // System.out.println("AspectBodyDeclarationsopt ::= NestedType AspectBodyDeclarations");
consumeClassBodyDeclarationsopt();
break ;
case 136 : // System.out.println("AspectBodyDeclaration ::= ClassBodyDeclaration");
consumeClassBodyDeclarationInAspect();
break ;
case 137 : // System.out.println("PointcutDeclaration ::= PointcutHeader MethodHeaderParameters SEMICOLON");
consumeEmptyPointcutDeclaration();
break ;
case 138 : // System.out.println("PointcutDeclaration ::= PointcutHeader MethodHeaderParameters COLON PseudoTokens...");
consumePointcutDeclaration();
break ;
case 139 : // System.out.println("PointcutHeader ::= Modifiersopt pointcut JavaIdentifier LPAREN");
consumePointcutHeader();
break ;
case 142 : // System.out.println("AroundDeclaration ::= AroundHeader MethodBody");
consumeAroundDeclaration();
break ;
case 143 : // System.out.println("AroundHeader ::= AroundHeaderName MethodHeaderParameters...");
consumeAroundHeader();
break ;
case 144 : // System.out.println("AroundHeaderName ::= Modifiersopt Type around LPAREN");
consumeAroundHeaderName();
break ;
case 145 : // System.out.println("BasicAdviceDeclaration ::= BasicAdviceHeader MethodBody");
consumeBasicAdviceDeclaration();
break ;
case 146 : // System.out.println("BasicAdviceHeader ::= BasicAdviceHeaderName MethodHeaderParameters ExtraParamopt...");
consumeBasicAdviceHeader();
break ;
case 147 : // System.out.println("BasicAdviceHeaderName ::= Modifiersopt before LPAREN");
consumeBasicAdviceHeaderName(false);
break ;
case 148 : // System.out.println("BasicAdviceHeaderName ::= Modifiersopt after LPAREN");
consumeBasicAdviceHeaderName(true);
break ;
case 149 : // System.out.println("ExtraParamopt ::= Identifier LPAREN FormalParameter RPAREN");
consumeExtraParameterWithFormal();
break ;
case 150 : // System.out.println("ExtraParamopt ::= Identifier LPAREN RPAREN");
consumeExtraParameterNoFormal();
break ;
case 151 : // System.out.println("ExtraParamopt ::= Identifier");
consumeExtraParameterNoFormal();
break ;
case 154 : // System.out.println("OnType ::= OnType DOT JavaIdentifier");
consumeQualifiedName();
break ;
case 159 : // System.out.println("InterTypeMethodDeclaration ::= InterTypeMethodHeader MethodBody");
// set to true to consume a method with a body
consumeInterTypeMethodDeclaration(true);
break ;
case 160 : // System.out.println("InterTypeMethodHeader ::= InterTypeMethodHeaderName MethodHeaderParameters...");
consumeInterTypeMethodHeader();
break ;
case 161 : // System.out.println("InterTypeMethodHeaderName ::= Modifiersopt Type OnType DOT JavaIdentifier LPAREN");
consumeInterTypeMethodHeaderName();
break ;
case 162 : // System.out.println("AbstractInterTypeMethodDeclaration ::= InterTypeMethodHeader SEMICOLON");
// set to false to consume a method without body
consumeInterTypeMethodDeclaration(false);
break ;
case 163 : // System.out.println("InterTypeConstructorDeclaration ::= InterTypeConstructorHeader ConstructorBody");
// set to true to consume a method with a body
consumeInterTypeConstructorDeclaration();
break ;
case 164 : // System.out.println("InterTypeConstructorHeader ::= InterTypeConstructorHeaderName...");
consumeInterTypeConstructorHeader();
break ;
case 165 : // System.out.println("InterTypeConstructorHeaderName ::= Modifiersopt Name DOT new LPAREN");
consumeInterTypeConstructorHeaderName();
break ;
case 166 : // System.out.println("InterTypeFieldDeclaration ::= Modifiersopt Type OnType DOT JavaIdentifier...");
consumeInterTypeFieldDeclaration();
break ;
case 170 : // System.out.println("DeclareDeclaration ::= DeclareHeader PseudoTokens SEMICOLON");
consumeDeclareDeclaration();
break ;
case 171 : // System.out.println("DeclareHeader ::= declare Identifier COLON");
consumeDeclareHeader();
break ;
case 173 : // System.out.println("PseudoTokens ::= PseudoTokens PseudoToken");
consumePseudoTokens();
break ;
case 174 : // System.out.println("PseudoToken ::= JavaIdentifier");
consumePseudoTokenIdentifier();
break ;
case 175 : // System.out.println("PseudoToken ::= LPAREN");
consumePseudoToken("(");
break ;
case 176 : // System.out.println("PseudoToken ::= RPAREN");
consumePseudoToken(")");
break ;
case 177 : // System.out.println("PseudoToken ::= DOT");
consumePseudoToken(".");
break ;
case 178 : // System.out.println("PseudoToken ::= MULTIPLY");
consumePseudoToken("*");
break ;
case 179 : // System.out.println("PseudoToken ::= PLUS");
consumePseudoToken("+");
break ;
case 180 : // System.out.println("PseudoToken ::= AND_AND");
consumePseudoToken("&&");
break ;
case 181 : // System.out.println("PseudoToken ::= OR_OR");
consumePseudoToken("||");
break ;
case 182 : // System.out.println("PseudoToken ::= NOT");
consumePseudoToken("!");
break ;
case 183 : // System.out.println("PseudoToken ::= COLON");
consumePseudoToken(":");
break ;
case 184 : // System.out.println("PseudoToken ::= COMMA");
consumePseudoToken(",");
break ;
case 185 : // System.out.println("PseudoToken ::= LBRACKET");
consumePseudoToken("[");
break ;
case 186 : // System.out.println("PseudoToken ::= RBRACKET");
consumePseudoToken("]");
break ;
case 187 : // System.out.println("PseudoToken ::= PrimitiveType");
consumePseudoTokenPrimitiveType();
break ;
case 188 : // System.out.println("PseudoToken ::= Modifier");
consumePseudoTokenModifier();
break ;
case 189 : // System.out.println("PseudoToken ::= Literal");
consumePseudoTokenLiteral();
break ;
case 190 : // System.out.println("PseudoToken ::= this");
consumePseudoToken("this", 1, true);
break ;
case 191 : // System.out.println("PseudoToken ::= super");
consumePseudoToken("super", 1, true);
break ;
case 192 : // System.out.println("PseudoToken ::= if LPAREN Expression RPAREN");
consumePseudoTokenIf();
break ;
case 193 : // System.out.println("PseudoToken ::= assert");
consumePseudoToken("assert", 1, true);
break ;
case 194 : // System.out.println("PseudoToken ::= import");
consumePseudoToken("import", 1, true);
break ;
case 195 : // System.out.println("PseudoToken ::= package");
consumePseudoToken("package", 1, true);
break ;
case 196 : // System.out.println("PseudoToken ::= throw");
consumePseudoToken("throw", 1, true);
break ;
case 197 : // System.out.println("PseudoToken ::= new");
consumePseudoToken("new", 1, true);
break ;
case 198 : // System.out.println("PseudoToken ::= do");
consumePseudoToken("do", 1, true);
break ;
case 199 : // System.out.println("PseudoToken ::= for");
consumePseudoToken("for", 1, true);
break ;
case 200 : // System.out.println("PseudoToken ::= switch");
consumePseudoToken("switch", 1, true);
break ;
case 201 : // System.out.println("PseudoToken ::= try");
consumePseudoToken("try", 1, true);
break ;
case 202 : // System.out.println("PseudoToken ::= while");
consumePseudoToken("while", 1, true);
break ;
case 203 : // System.out.println("PseudoToken ::= break");
consumePseudoToken("break", 1, true);
break ;
case 204 : // System.out.println("PseudoToken ::= continue");
consumePseudoToken("continue", 1, true);
break ;
case 205 : // System.out.println("PseudoToken ::= return");
consumePseudoToken("return", 1, true);
break ;
case 206 : // System.out.println("PseudoToken ::= case");
consumePseudoToken("case", 1, true);
break ;
case 207 : // System.out.println("PseudoToken ::= catch");
consumePseudoToken("catch", 0, true);
break ;
case 208 : // System.out.println("PseudoToken ::= instanceof");
consumePseudoToken("instanceof", 0, true);
break ;
case 209 : // System.out.println("PseudoToken ::= else");
consumePseudoToken("else", 0, true);
break ;
case 210 : // System.out.println("PseudoToken ::= extends");
consumePseudoToken("extends", 0, true);
break ;
case 211 : // System.out.println("PseudoToken ::= finally");
consumePseudoToken("finally", 0, true);
break ;
case 212 : // System.out.println("PseudoToken ::= implements");
consumePseudoToken("implements", 0, true);
break ;
case 213 : // System.out.println("PseudoToken ::= throws");
consumePseudoToken("throws", 0, true);
break ;
case 214 : // System.out.println("ClassDeclaration ::= ClassHeader ClassBody");
consumeClassDeclaration();
break ;
case 215 : // System.out.println("ClassHeader ::= ClassHeaderName ClassHeaderExtendsopt ClassHeaderImplementsopt");
consumeClassHeader();
break ;
case 216 : // System.out.println("ClassHeaderName ::= Modifiersopt class JavaIdentifier");
consumeClassHeaderName();
break ;
case 217 : // System.out.println("ClassHeaderExtends ::= extends ClassType");
consumeClassHeaderExtends();
break ;
case 218 : // System.out.println("ClassHeaderImplements ::= implements InterfaceTypeList");
consumeClassHeaderImplements();
break ;
case 220 : // System.out.println("InterfaceTypeList ::= InterfaceTypeList COMMA InterfaceType");
consumeInterfaceTypeList();
break ;
case 221 : // System.out.println("InterfaceType ::= ClassOrInterfaceType");
consumeInterfaceType();
break ;
case 224 : // System.out.println("ClassBodyDeclarations ::= ClassBodyDeclarations ClassBodyDeclaration");
consumeClassBodyDeclarations();
break ;
case 228 : // System.out.println("ClassBodyDeclaration ::= Diet NestedMethod Block");
consumeClassBodyDeclaration();
break ;
case 229 : // System.out.println("Diet ::=");
consumeDiet();
break ;
case 230 : // System.out.println("Initializer ::= Diet NestedMethod Block");
consumeClassBodyDeclaration();
break ;
case 237 : // System.out.println("ClassMemberDeclaration ::= SEMICOLON");
consumeEmptyClassMemberDeclaration();
break ;
case 238 : // System.out.println("FieldDeclaration ::= Modifiersopt Type VariableDeclarators SEMICOLON");
consumeFieldDeclaration();
break ;
case 240 : // System.out.println("VariableDeclarators ::= VariableDeclarators COMMA VariableDeclarator");
consumeVariableDeclarators();
break ;
case 243 : // System.out.println("EnterVariable ::=");
consumeEnterVariable();
break ;
case 244 : // System.out.println("ExitVariableWithInitialization ::=");
consumeExitVariableWithInitialization();
break ;
case 245 : // System.out.println("ExitVariableWithoutInitialization ::=");
consumeExitVariableWithoutInitialization();
break ;
case 246 : // System.out.println("ForceNoDiet ::=");
consumeForceNoDiet();
break ;
case 247 : // System.out.println("RestoreDiet ::=");
consumeRestoreDiet();
break ;
case 252 : // System.out.println("MethodDeclaration ::= MethodHeader MethodBody");
// set to true to consume a method with a body
consumeMethodDeclaration(true);
break ;
case 253 : // System.out.println("AbstractMethodDeclaration ::= MethodHeader SEMICOLON");
// set to false to consume a method without body
consumeMethodDeclaration(false);
break ;
case 254 : // System.out.println("MethodHeader ::= MethodHeaderName MethodHeaderParameters MethodHeaderExtendedDims");
consumeMethodHeader();
break ;
case 255 : // System.out.println("MethodPushModifiersHeader ::= MethodPushModifiersHeaderName MethodHeaderParameters");
consumeMethodHeader();
break ;
case 256 : // System.out.println("MethodPushModifiersHeaderName ::= Modifiers Type PushModifiers...");
consumeMethodPushModifiersHeaderName();
break ;
case 257 : // System.out.println("MethodPushModifiersHeaderName ::= Type PushModifiers JavaIdentifierNoAround LPAREN");
consumeMethodPushModifiersHeaderName();
break ;
case 258 : // System.out.println("MethodHeaderName ::= Modifiersopt Type JavaIdentifierNoAround LPAREN");
consumeMethodHeaderName();
break ;
case 259 : // System.out.println("MethodHeaderParameters ::= FormalParameterListopt RPAREN");
consumeMethodHeaderParameters();
break ;
case 260 : // System.out.println("MethodHeaderExtendedDims ::= Dimsopt");
consumeMethodHeaderExtendedDims();
break ;
case 261 : // System.out.println("MethodHeaderThrowsClause ::= throws ClassTypeList");
consumeMethodHeaderThrowsClause();
break ;
case 262 : // System.out.println("ConstructorHeader ::= ConstructorHeaderName MethodHeaderParameters...");
consumeConstructorHeader();
break ;
case 263 : // System.out.println("ConstructorHeaderName ::= Modifiersopt Identifier LPAREN");
consumeConstructorHeaderName();
break ;
case 264 : // System.out.println("ConstructorHeaderName ::= Modifiersopt aspect LPAREN");
consumeConstructorHeaderName();
break ;
case 266 : // System.out.println("FormalParameterList ::= FormalParameterList COMMA FormalParameter");
consumeFormalParameterList();
break ;
case 267 : // System.out.println("FormalParameter ::= Modifiersopt Type VariableDeclaratorId");
// the boolean is used to know if the modifiers should be reset
consumeFormalParameter();
break ;
case 269 : // System.out.println("ClassTypeList ::= ClassTypeList COMMA ClassTypeElt");
consumeClassTypeList();
break ;
case 270 : // System.out.println("ClassTypeElt ::= ClassType");
consumeClassTypeElt();
break ;
case 271 : // System.out.println("MethodBody ::= NestedMethod LBRACE BlockStatementsopt RBRACE");
consumeMethodBody();
break ;
case 272 : // System.out.println("NestedMethod ::=");
consumeNestedMethod();
break ;
case 273 : // System.out.println("StaticInitializer ::= StaticOnly Block");
consumeStaticInitializer();
break ;
case 274 : // System.out.println("StaticOnly ::= static");
consumeStaticOnly();
break ;
case 275 : // System.out.println("ConstructorDeclaration ::= ConstructorHeader ConstructorBody");
consumeConstructorDeclaration() ;
break ;
case 276 : // System.out.println("ConstructorDeclaration ::= ConstructorHeader SEMICOLON");
consumeInvalidConstructorDeclaration() ;
break ;
case 277 : // System.out.println("ConstructorBody ::= NestedMethod LBRACE ConstructorBlockStatementsopt RBRACE");
consumeConstructorBody();
break ;
case 280 : // System.out.println("ConstructorBlockStatementsopt ::= ExplicitConstructorInvocation BlockStatements");
consumeConstructorBlockStatements();
break ;
case 281 : // System.out.println("ExplicitConstructorInvocation ::= this LPAREN ArgumentListopt RPAREN SEMICOLON");
consumeExplicitConstructorInvocation(0,ExplicitConstructorCall.This);
break ;
case 282 : // System.out.println("ExplicitConstructorInvocation ::= super LPAREN ArgumentListopt RPAREN SEMICOLON");
consumeExplicitConstructorInvocation(0,ExplicitConstructorCall.Super);
break ;
case 283 : // System.out.println("ExplicitConstructorInvocation ::= Primary DOT super LPAREN ArgumentListopt RPAREN");
consumeExplicitConstructorInvocation(1, ExplicitConstructorCall.Super);
break ;
case 284 : // System.out.println("ExplicitConstructorInvocation ::= Name DOT super LPAREN ArgumentListopt RPAREN...");
consumeExplicitConstructorInvocation(2, ExplicitConstructorCall.Super);
break ;
case 285 : // System.out.println("ExplicitConstructorInvocation ::= Primary DOT this LPAREN ArgumentListopt RPAREN...");
consumeExplicitConstructorInvocation(1, ExplicitConstructorCall.This);
break ;
case 286 : // System.out.println("ExplicitConstructorInvocation ::= Name DOT this LPAREN ArgumentListopt RPAREN...");
consumeExplicitConstructorInvocation(2, ExplicitConstructorCall.This);
break ;
case 287 : // System.out.println("InterfaceDeclaration ::= InterfaceHeader InterfaceBody");
consumeInterfaceDeclaration();
break ;
case 288 : // System.out.println("InterfaceHeader ::= InterfaceHeaderName InterfaceHeaderExtendsopt");
consumeInterfaceHeader();
break ;
case 289 : // System.out.println("InterfaceHeaderName ::= Modifiersopt interface JavaIdentifier");
consumeInterfaceHeaderName();
break ;
case 291 : // System.out.println("InterfaceHeaderExtends ::= extends InterfaceTypeList");
consumeInterfaceHeaderExtends();
break ;
case 294 : // System.out.println("InterfaceMemberDeclarations ::= InterfaceMemberDeclarations...");
consumeInterfaceMemberDeclarations();
break ;
case 295 : // System.out.println("InterfaceMemberDeclaration ::= SEMICOLON");
consumeEmptyInterfaceMemberDeclaration();
break ;
case 298 : // System.out.println("InterfaceMemberDeclaration ::= InvalidMethodDeclaration");
ignoreMethodBody();
break ;
case 299 : // System.out.println("InvalidConstructorDeclaration ::= ConstructorHeader ConstructorBody");
ignoreInvalidConstructorDeclaration(true);
break ;
case 300 : // System.out.println("InvalidConstructorDeclaration ::= ConstructorHeader SEMICOLON");
ignoreInvalidConstructorDeclaration(false);
break ;
case 306 : // System.out.println("ArrayInitializer ::= LBRACE ,opt RBRACE");
consumeEmptyArrayInitializer();
break ;
case 307 : // System.out.println("ArrayInitializer ::= LBRACE VariableInitializers RBRACE");
consumeArrayInitializer();
break ;
case 308 : // System.out.println("ArrayInitializer ::= LBRACE VariableInitializers COMMA RBRACE");
consumeArrayInitializer();
break ;
case 310 : // System.out.println("VariableInitializers ::= VariableInitializers COMMA VariableInitializer");
consumeVariableInitializers();
break ;
case 311 : // System.out.println("Block ::= OpenBlock LBRACE BlockStatementsopt RBRACE");
consumeBlock();
break ;
case 312 : // System.out.println("OpenBlock ::=");
consumeOpenBlock() ;
break ;
case 314 : // System.out.println("BlockStatements ::= BlockStatements BlockStatement");
consumeBlockStatements() ;
break ;
case 318 : // System.out.println("BlockStatement ::= InvalidInterfaceDeclaration");
ignoreInterfaceDeclaration();
break ;
case 319 : // System.out.println("LocalVariableDeclarationStatement ::= LocalVariableDeclaration SEMICOLON");
consumeLocalVariableDeclarationStatement();
break ;
case 320 : // System.out.println("LocalVariableDeclaration ::= Type PushModifiers VariableDeclarators");
consumeLocalVariableDeclaration();
break ;
case 321 : // System.out.println("LocalVariableDeclaration ::= Modifiers Type PushModifiers VariableDeclarators");
consumeLocalVariableDeclaration();
break ;
case 322 : // System.out.println("PushModifiers ::=");
consumePushModifiers();
break ;
case 346 : // System.out.println("EmptyStatement ::= SEMICOLON");
consumeEmptyStatement();
break ;
case 347 : // System.out.println("LabeledStatement ::= JavaIdentifier COLON Statement");
consumeStatementLabel() ;
break ;
case 348 : // System.out.println("LabeledStatementNoShortIf ::= JavaIdentifier COLON StatementNoShortIf");
consumeStatementLabel() ;
break ;
case 349 : // System.out.println("ExpressionStatement ::= StatementExpression SEMICOLON");
consumeExpressionStatement();
break ;
case 357 : // System.out.println("IfThenStatement ::= if LPAREN Expression RPAREN Statement");
consumeStatementIfNoElse();
break ;
case 358 : // System.out.println("IfThenElseStatement ::= if LPAREN Expression RPAREN StatementNoShortIf else...");
consumeStatementIfWithElse();
break ;
case 359 : // System.out.println("IfThenElseStatementNoShortIf ::= if LPAREN Expression RPAREN StatementNoShortIf...");
consumeStatementIfWithElse();
break ;
case 360 : // System.out.println("SwitchStatement ::= switch OpenBlock LPAREN Expression RPAREN SwitchBlock");
consumeStatementSwitch() ;
break ;
case 361 : // System.out.println("SwitchBlock ::= LBRACE RBRACE");
consumeEmptySwitchBlock() ;
break ;
case 364 : // System.out.println("SwitchBlock ::= LBRACE SwitchBlockStatements SwitchLabels RBRACE");
consumeSwitchBlock() ;
break ;
case 366 : // System.out.println("SwitchBlockStatements ::= SwitchBlockStatements SwitchBlockStatement");
consumeSwitchBlockStatements() ;
break ;
case 367 : // System.out.println("SwitchBlockStatement ::= SwitchLabels BlockStatements");
consumeSwitchBlockStatement() ;
break ;
case 369 : // System.out.println("SwitchLabels ::= SwitchLabels SwitchLabel");
consumeSwitchLabels() ;
break ;
case 370 : // System.out.println("SwitchLabel ::= case ConstantExpression COLON");
consumeCaseLabel();
break ;
case 371 : // System.out.println("SwitchLabel ::= default COLON");
consumeDefaultLabel();
break ;
case 372 : // System.out.println("WhileStatement ::= while LPAREN Expression RPAREN Statement");
consumeStatementWhile() ;
break ;
case 373 : // System.out.println("WhileStatementNoShortIf ::= while LPAREN Expression RPAREN StatementNoShortIf");
consumeStatementWhile() ;
break ;
case 374 : // System.out.println("DoStatement ::= do Statement while LPAREN Expression RPAREN SEMICOLON");
consumeStatementDo() ;
break ;
case 375 : // System.out.println("ForStatement ::= for LPAREN ForInitopt SEMICOLON Expressionopt SEMICOLON...");
consumeStatementFor() ;
break ;
case 376 : // System.out.println("ForStatementNoShortIf ::= for LPAREN ForInitopt SEMICOLON Expressionopt SEMICOLON");
consumeStatementFor() ;
break ;
case 377 : // System.out.println("ForInit ::= StatementExpressionList");
consumeForInit() ;
break ;
case 381 : // System.out.println("StatementExpressionList ::= StatementExpressionList COMMA StatementExpression");
consumeStatementExpressionList() ;
break ;
case 382 : // System.out.println("AssertStatement ::= assert Expression SEMICOLON");
consumeSimpleAssertStatement() ;
break ;
case 383 : // System.out.println("AssertStatement ::= assert Expression COLON Expression SEMICOLON");
consumeAssertStatement() ;
break ;
case 384 : // System.out.println("BreakStatement ::= break SEMICOLON");
consumeStatementBreak() ;
break ;
case 385 : // System.out.println("BreakStatement ::= break Identifier SEMICOLON");
consumeStatementBreakWithLabel() ;
break ;
case 386 : // System.out.println("ContinueStatement ::= continue SEMICOLON");
consumeStatementContinue() ;
break ;
case 387 : // System.out.println("ContinueStatement ::= continue Identifier SEMICOLON");
consumeStatementContinueWithLabel() ;
break ;
case 388 : // System.out.println("ReturnStatement ::= return Expressionopt SEMICOLON");
consumeStatementReturn() ;
break ;
case 389 : // System.out.println("ThrowStatement ::= throw Expression SEMICOLON");
consumeStatementThrow();
break ;
case 390 : // System.out.println("SynchronizedStatement ::= OnlySynchronized LPAREN Expression RPAREN Block");
consumeStatementSynchronized();
break ;
case 391 : // System.out.println("OnlySynchronized ::= synchronized");
consumeOnlySynchronized();
break ;
case 392 : // System.out.println("TryStatement ::= try Block Catches");
consumeStatementTry(false);
break ;
case 393 : // System.out.println("TryStatement ::= try Block Catchesopt Finally");
consumeStatementTry(true);
break ;
case 395 : // System.out.println("Catches ::= Catches CatchClause");
consumeCatches();
break ;
case 396 : // System.out.println("CatchClause ::= catch LPAREN FormalParameter RPAREN Block");
consumeStatementCatch() ;
break ;
case 398 : // System.out.println("PushLPAREN ::= LPAREN");
consumeLeftParen();
break ;
case 399 : // System.out.println("PushRPAREN ::= RPAREN");
consumeRightParen();
break ;
case 404 : // System.out.println("PrimaryNoNewArray ::= this");
consumePrimaryNoNewArrayThis();
break ;
case 405 : // System.out.println("PrimaryNoNewArray ::= PushLPAREN Expression PushRPAREN");
consumePrimaryNoNewArray();
break ;
case 408 : // System.out.println("PrimaryNoNewArray ::= Name DOT this");
consumePrimaryNoNewArrayNameThis();
break ;
case 409 : // System.out.println("PrimaryNoNewArray ::= Name DOT super");
consumePrimaryNoNewArrayNameSuper();
break ;
case 410 : // System.out.println("PrimaryNoNewArray ::= Name DOT class");
consumePrimaryNoNewArrayName();
break ;
case 411 : // System.out.println("PrimaryNoNewArray ::= ArrayType DOT class");
consumePrimaryNoNewArrayArrayType();
break ;
case 412 : // System.out.println("PrimaryNoNewArray ::= PrimitiveType DOT class");
consumePrimaryNoNewArrayPrimitiveType();
break ;
case 415 : // System.out.println("AllocationHeader ::= new ClassType LPAREN ArgumentListopt RPAREN");
consumeAllocationHeader();
break ;
case 416 : // System.out.println("ClassInstanceCreationExpression ::= new ClassType LPAREN ArgumentListopt RPAREN...");
consumeClassInstanceCreationExpression();
break ;
case 417 : // System.out.println("ClassInstanceCreationExpression ::= Primary DOT new SimpleName LPAREN...");
consumeClassInstanceCreationExpressionQualified() ;
break ;
case 418 : // System.out.println("ClassInstanceCreationExpression ::= ClassInstanceCreationExpressionName new...");
consumeClassInstanceCreationExpressionQualified() ;
break ;
case 419 : // System.out.println("ClassInstanceCreationExpressionName ::= Name DOT");
consumeClassInstanceCreationExpressionName() ;
break ;
case 420 : // System.out.println("ClassBodyopt ::=");
consumeClassBodyopt();
break ;
case 422 : // System.out.println("EnterAnonymousClassBody ::=");
consumeEnterAnonymousClassBody();
break ;
case 424 : // System.out.println("ArgumentList ::= ArgumentList COMMA Expression");
consumeArgumentList();
break ;
case 425 : // System.out.println("ArrayCreationWithoutArrayInitializer ::= new PrimitiveType DimWithOrWithOutExprs");
consumeArrayCreationExpressionWithoutInitializer();
break ;
case 426 : // System.out.println("ArrayCreationWithArrayInitializer ::= new PrimitiveType DimWithOrWithOutExprs...");
consumeArrayCreationExpressionWithInitializer();
break ;
case 427 : // System.out.println("ArrayCreationWithoutArrayInitializer ::= new ClassOrInterfaceType...");
consumeArrayCreationExpressionWithoutInitializer();
break ;
case 428 : // System.out.println("ArrayCreationWithArrayInitializer ::= new ClassOrInterfaceType...");
consumeArrayCreationExpressionWithInitializer();
break ;
case 430 : // System.out.println("DimWithOrWithOutExprs ::= DimWithOrWithOutExprs DimWithOrWithOutExpr");
consumeDimWithOrWithOutExprs();
break ;
case 432 : // System.out.println("DimWithOrWithOutExpr ::= LBRACKET RBRACKET");
consumeDimWithOrWithOutExpr();
break ;
case 433 : // System.out.println("Dims ::= DimsLoop");
consumeDims();
break ;
case 436 : // System.out.println("OneDimLoop ::= LBRACKET RBRACKET");
consumeOneDimLoop();
break ;
case 437 : // System.out.println("FieldAccess ::= Primary DOT JavaIdentifier");
consumeFieldAccess(false);
break ;
case 438 : // System.out.println("FieldAccess ::= super DOT JavaIdentifier");
consumeFieldAccess(true);
break ;
case 439 : // System.out.println("MethodInvocation ::= NameOrAj LPAREN ArgumentListopt RPAREN");
consumeMethodInvocationName();
break ;
case 440 : // System.out.println("MethodInvocation ::= Primary DOT JavaIdentifier LPAREN ArgumentListopt RPAREN");
consumeMethodInvocationPrimary();
break ;
case 441 : // System.out.println("MethodInvocation ::= super DOT JavaIdentifier LPAREN ArgumentListopt RPAREN");
consumeMethodInvocationSuper();
break ;
case 442 : // System.out.println("ArrayAccess ::= Name LBRACKET Expression RBRACKET");
consumeArrayAccess(true);
break ;
case 443 : // System.out.println("ArrayAccess ::= PrimaryNoNewArray LBRACKET Expression RBRACKET");
consumeArrayAccess(false);
break ;
case 444 : // System.out.println("ArrayAccess ::= ArrayCreationWithArrayInitializer LBRACKET Expression RBRACKET");
consumeArrayAccess(false);
break ;
case 446 : // System.out.println("PostfixExpression ::= NameOrAj");
consumePostfixExpression();
break ;
case 449 : // System.out.println("PostIncrementExpression ::= PostfixExpression PLUS_PLUS");
consumeUnaryExpression(OperatorExpression.PLUS,true);
break ;
case 450 : // System.out.println("PostDecrementExpression ::= PostfixExpression MINUS_MINUS");
consumeUnaryExpression(OperatorExpression.MINUS,true);
break ;
case 451 : // System.out.println("PushPosition ::=");
consumePushPosition();
break ;
case 454 : // System.out.println("UnaryExpression ::= PLUS PushPosition UnaryExpression");
consumeUnaryExpression(OperatorExpression.PLUS);
break ;
case 455 : // System.out.println("UnaryExpression ::= MINUS PushPosition UnaryExpression");
consumeUnaryExpression(OperatorExpression.MINUS);
break ;
case 457 : // System.out.println("PreIncrementExpression ::= PLUS_PLUS PushPosition UnaryExpression");
consumeUnaryExpression(OperatorExpression.PLUS,false);
break ;
case 458 : // System.out.println("PreDecrementExpression ::= MINUS_MINUS PushPosition UnaryExpression");
consumeUnaryExpression(OperatorExpression.MINUS,false);
break ;
case 460 : // System.out.println("UnaryExpressionNotPlusMinus ::= TWIDDLE PushPosition UnaryExpression");
consumeUnaryExpression(OperatorExpression.TWIDDLE);
break ;
case 461 : // System.out.println("UnaryExpressionNotPlusMinus ::= NOT PushPosition UnaryExpression");
consumeUnaryExpression(OperatorExpression.NOT);
break ;
case 463 : // System.out.println("CastExpression ::= PushLPAREN PrimitiveType Dimsopt PushRPAREN InsideCastExpression");
consumeCastExpression();
break ;
case 464 : // System.out.println("CastExpression ::= PushLPAREN Name Dims PushRPAREN InsideCastExpression...");
consumeCastExpression();
break ;
case 465 : // System.out.println("CastExpression ::= PushLPAREN Expression PushRPAREN InsideCastExpressionLL1...");
consumeCastExpressionLL1();
break ;
case 466 : // System.out.println("InsideCastExpression ::=");
consumeInsideCastExpression();
break ;
case 467 : // System.out.println("InsideCastExpressionLL1 ::=");
consumeInsideCastExpressionLL1();
break ;
case 469 : // System.out.println("MultiplicativeExpression ::= MultiplicativeExpression MULTIPLY UnaryExpression");
consumeBinaryExpression(OperatorExpression.MULTIPLY);
break ;
case 470 : // System.out.println("MultiplicativeExpression ::= MultiplicativeExpression DIVIDE UnaryExpression");
consumeBinaryExpression(OperatorExpression.DIVIDE);
break ;
case 471 : // System.out.println("MultiplicativeExpression ::= MultiplicativeExpression REMAINDER UnaryExpression");
consumeBinaryExpression(OperatorExpression.REMAINDER);
break ;
case 473 : // System.out.println("AdditiveExpression ::= AdditiveExpression PLUS MultiplicativeExpression");
consumeBinaryExpression(OperatorExpression.PLUS);
break ;
case 474 : // System.out.println("AdditiveExpression ::= AdditiveExpression MINUS MultiplicativeExpression");
consumeBinaryExpression(OperatorExpression.MINUS);
break ;
case 476 : // System.out.println("ShiftExpression ::= ShiftExpression LEFT_SHIFT AdditiveExpression");
consumeBinaryExpression(OperatorExpression.LEFT_SHIFT);
break ;
case 477 : // System.out.println("ShiftExpression ::= ShiftExpression RIGHT_SHIFT AdditiveExpression");
consumeBinaryExpression(OperatorExpression.RIGHT_SHIFT);
break ;
case 478 : // System.out.println("ShiftExpression ::= ShiftExpression UNSIGNED_RIGHT_SHIFT AdditiveExpression");
consumeBinaryExpression(OperatorExpression.UNSIGNED_RIGHT_SHIFT);
break ;
case 480 : // System.out.println("RelationalExpression ::= RelationalExpression LESS ShiftExpression");
consumeBinaryExpression(OperatorExpression.LESS);
break ;
case 481 : // System.out.println("RelationalExpression ::= RelationalExpression GREATER ShiftExpression");
consumeBinaryExpression(OperatorExpression.GREATER);
break ;
case 482 : // System.out.println("RelationalExpression ::= RelationalExpression LESS_EQUAL ShiftExpression");
consumeBinaryExpression(OperatorExpression.LESS_EQUAL);
break ;
case 483 : // System.out.println("RelationalExpression ::= RelationalExpression GREATER_EQUAL ShiftExpression");
consumeBinaryExpression(OperatorExpression.GREATER_EQUAL);
break ;
case 484 : // System.out.println("RelationalExpression ::= RelationalExpression instanceof ReferenceType");
consumeInstanceOfExpression(OperatorExpression.INSTANCEOF);
break ;
case 486 : // System.out.println("EqualityExpression ::= EqualityExpression EQUAL_EQUAL RelationalExpression");
consumeEqualityExpression(OperatorExpression.EQUAL_EQUAL);
break ;
case 487 : // System.out.println("EqualityExpression ::= EqualityExpression NOT_EQUAL RelationalExpression");
consumeEqualityExpression(OperatorExpression.NOT_EQUAL);
break ;
case 489 : // System.out.println("AndExpression ::= AndExpression AND EqualityExpression");
consumeBinaryExpression(OperatorExpression.AND);
break ;
case 491 : // System.out.println("ExclusiveOrExpression ::= ExclusiveOrExpression XOR AndExpression");
consumeBinaryExpression(OperatorExpression.XOR);
break ;
case 493 : // System.out.println("InclusiveOrExpression ::= InclusiveOrExpression OR ExclusiveOrExpression");
consumeBinaryExpression(OperatorExpression.OR);
break ;
case 495 : // System.out.println("ConditionalAndExpression ::= ConditionalAndExpression AND_AND InclusiveOrExpression");
consumeBinaryExpression(OperatorExpression.AND_AND);
break ;
case 497 : // System.out.println("ConditionalOrExpression ::= ConditionalOrExpression OR_OR ConditionalAndExpression");
consumeBinaryExpression(OperatorExpression.OR_OR);
break ;
case 499 : // System.out.println("ConditionalExpression ::= ConditionalOrExpression QUESTION Expression COLON...");
consumeConditionalExpression(OperatorExpression.QUESTIONCOLON) ;
break ;
case 502 : // System.out.println("Assignment ::= PostfixExpression AssignmentOperator AssignmentExpression");
consumeAssignment();
break ;
case 504 : // System.out.println("Assignment ::= InvalidArrayInitializerAssignement");
ignoreExpressionAssignment();
break ;
case 505 : // System.out.println("AssignmentOperator ::= EQUAL");
consumeAssignmentOperator(EQUAL);
break ;
case 506 : // System.out.println("AssignmentOperator ::= MULTIPLY_EQUAL");
consumeAssignmentOperator(MULTIPLY);
break ;
case 507 : // System.out.println("AssignmentOperator ::= DIVIDE_EQUAL");
consumeAssignmentOperator(DIVIDE);
break ;
case 508 : // System.out.println("AssignmentOperator ::= REMAINDER_EQUAL");
consumeAssignmentOperator(REMAINDER);
break ;
case 509 : // System.out.println("AssignmentOperator ::= PLUS_EQUAL");
consumeAssignmentOperator(PLUS);
break ;
case 510 : // System.out.println("AssignmentOperator ::= MINUS_EQUAL");
consumeAssignmentOperator(MINUS);
break ;
case 511 : // System.out.println("AssignmentOperator ::= LEFT_SHIFT_EQUAL");
consumeAssignmentOperator(LEFT_SHIFT);
break ;
case 512 : // System.out.println("AssignmentOperator ::= RIGHT_SHIFT_EQUAL");
consumeAssignmentOperator(RIGHT_SHIFT);
break ;
case 513 : // System.out.println("AssignmentOperator ::= UNSIGNED_RIGHT_SHIFT_EQUAL");
consumeAssignmentOperator(UNSIGNED_RIGHT_SHIFT);
break ;
case 514 : // System.out.println("AssignmentOperator ::= AND_EQUAL");
consumeAssignmentOperator(AND);
break ;
case 515 : // System.out.println("AssignmentOperator ::= XOR_EQUAL");
consumeAssignmentOperator(XOR);
break ;
case 516 : // System.out.println("AssignmentOperator ::= OR_EQUAL");
consumeAssignmentOperator(OR);
break ;
case 523 : // System.out.println("Expressionopt ::=");
consumeEmptyExpression();
break ;
case 527 : // System.out.println("ImportDeclarationsopt ::=");
consumeEmptyImportDeclarationsopt();
break ;
case 528 : // System.out.println("ImportDeclarationsopt ::= ImportDeclarations");
consumeImportDeclarationsopt();
break ;
case 529 : // System.out.println("TypeDeclarationsopt ::=");
consumeEmptyTypeDeclarationsopt();
break ;
case 530 : // System.out.println("TypeDeclarationsopt ::= TypeDeclarations");
consumeTypeDeclarationsopt();
break ;
case 531 : // System.out.println("ClassBodyDeclarationsopt ::=");
consumeEmptyClassBodyDeclarationsopt();
break ;
case 532 : // System.out.println("ClassBodyDeclarationsopt ::= NestedType ClassBodyDeclarations");
consumeClassBodyDeclarationsopt();
break ;
case 533 : // System.out.println("Modifiersopt ::=");
consumeDefaultModifiers();
break ;
case 534 : // System.out.println("Modifiersopt ::= Modifiers");
consumeModifiers();
break ;
case 535 : // System.out.println("BlockStatementsopt ::=");
consumeEmptyBlockStatementsopt();
break ;
case 537 : // System.out.println("Dimsopt ::=");
consumeEmptyDimsopt();
break ;
case 539 : // System.out.println("ArgumentListopt ::=");
consumeEmptyArgumentListopt();
break ;
case 543 : // System.out.println("FormalParameterListopt ::=");
consumeFormalParameterListopt();
break ;
case 547 : // System.out.println("InterfaceMemberDeclarationsopt ::=");
consumeEmptyInterfaceMemberDeclarationsopt();
break ;
case 548 : // System.out.println("InterfaceMemberDeclarationsopt ::= NestedType InterfaceMemberDeclarations");
consumeInterfaceMemberDeclarationsopt();
break ;
case 549 : // System.out.println("NestedType ::=");
consumeNestedType();
break ;
case 550 : // System.out.println("ForInitopt ::=");
consumeEmptyForInitopt();
break ;
case 552 : // System.out.println("ForUpdateopt ::=");
consumeEmptyForUpdateopt();
break ;
case 556 : // System.out.println("Catchesopt ::=");
consumeEmptyCatchesopt();
break ;
}
}
protected void consumeSimpleAssertStatement() {
super.consumeSimpleAssertStatement();
}
public AjParser(
ProblemReporter problemReporter,
boolean optimizeStringLiterals,
boolean assertMode) {
super(problemReporter, optimizeStringLiterals, assertMode);
}
}
|
49,638
|
Bug 49638 exception logging: after() throwing advice can't convert Throwable obj to string and ajc aborts
| null |
resolved fixed
|
7b081f2
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-09T09:21:03Z
| 2004-01-07T18:26:40Z
|
tests/bugs/AfterThrowingAdviceSyntaxError.java
| |
49,814
|
Bug 49814 ConfigParser.java:132
| null |
resolved fixed
|
a4a1234
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-12T11:37:20Z
| 2004-01-10T21:26:40Z
|
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.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 BuildArgParser parser = new BuildArgParser();
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);
}
public void testDefaultClasspathAndTargetCombo() throws InvalidInputException {
String ENTRY = "1.jar;2.jar";
final String classpath = System.getProperty("java.class.path");
try {
System.setProperty("java.class.path", ENTRY); // see finally below
AjBuildConfig config = parser.genBuildConfig(new String[] { }, messageWriter);
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 = parser.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"));
config = parser.genBuildConfig(new String[] { "-1.3" }, messageWriter);
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 = parser.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);
assertTrue(
config.getClasspath().toString(),
config.getClasspath().contains("1.jar"));
assertTrue(
config.getClasspath().toString(),
config.getClasspath().contains("2.jar"));
} 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 testAjOptions() throws InvalidInputException {
AjBuildConfig config = parser.genBuildConfig(new String[] { "-Xlint" }, messageWriter);
assertTrue(
"default options",
config.getAjOptions().get(AjCompilerOptions.OPTION_Xlint).equals(
CompilerOptions.GENERATE));
}
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 = parser.genBuildConfig(new String[] {
"-aspectpath", SOURCE_JAR },
messageWriter);
assertTrue(((File)config.getAspectpath().get(0)).getName(), ((File)config.getAspectpath().get(0)).getName().equals("testclasses.jar"));
config = parser.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 = parser.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 = parser.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 = parser.genBuildConfig(new String[] {
"-injars", SOURCE_JARS },
messageWriter);
assertTrue("size: " + config.getInJars().size(), config.getInJars().size() == 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 = parser.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 = parser.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 = parser.genBuildConfig(new String[] {
"-sourceroots",
AjdtAjcTests.TESTDATA_PATH + "/mumbleDoesNotExist;"
+ AjdtAjcTests.TESTDATA_PATH + "/ajc" },
messageWriter);
assertTrue(config.getSourceRoots().toString(), config.getSourceRoots().size() == 1);
config = parser.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 = parser.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 InvalidInputException {
final String DIR = AjdtAjcTests.TESTDATA_PATH;
AjBuildConfig config = parser.genBuildConfig(new String[] {
"-extdirs", DIR },
messageWriter);
assertTrue(config.getClasspath().toString(), config.getClasspath().contains(
new File(DIR + File.separator + "testclasses.jar").getAbsolutePath()
));
}
public void testBootclasspath() throws InvalidInputException {
final String PATH = "mumble/rt.jar";
AjBuildConfig config = parser.genBuildConfig(new String[] {
"-bootclasspath", PATH },
messageWriter);
assertTrue(config.getClasspath().toString(), config.getClasspath().get(0).equals(PATH));
config = parser.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 = parser.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 = parser.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 = parser.genBuildConfig(new String[] { "-Xlint", "-target", "1.4", "-1.4" }, messageWriter);
String TARGET = "1.4";
assertTrue(
"target set",
config.getJavaOptions().get(CompilerOptions.OPTION_TargetPlatform).equals(TARGET));
assertTrue(
"Xlint option set",
config.getAjOptions().get(AjCompilerOptions.OPTION_Xlint).equals(
CompilerOptions.GENERATE));
}
public void testOutputDirectorySetting() throws InvalidInputException {
AjBuildConfig config = parser.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;2.jar";
AjBuildConfig config = parser.genBuildConfig(new String[] { "-classpath", ENTRY }, messageWriter);
assertTrue(
config.getClasspath().toString(),
config.getClasspath().contains("1.jar"));
assertTrue(
config.getClasspath().toString(),
config.getClasspath().contains("2.jar"));
}
public void testArgInConfigFile() throws InvalidInputException {
String FILE_PATH = "@" + TEST_DIR + "configWithArgs.lst";
String OUT_PATH = "bin";
AjBuildConfig config = parser.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 = parser.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 = parser.genBuildConfig(new String[] {"-Xlint"}, messageWriter);
assertTrue("", config.getLintMode().equals(AjBuildConfig.AJLINT_DEFAULT));
config = parser.genBuildConfig(new String[] {"-Xlint:warn"}, messageWriter);
assertTrue("", config.getLintMode().equals(AjBuildConfig.AJLINT_WARN));
config = parser.genBuildConfig(new String[] {"-Xlint:error"}, messageWriter);
assertTrue("", config.getLintMode().equals(AjBuildConfig.AJLINT_ERROR));
config = parser.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 = parser.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 = parser.genBuildConfig(new String[] {"-target", TARGET, "-source", TARGET}, messageWriter);
assertTrue(
"target set",
config.getJavaOptions().get(CompilerOptions.OPTION_TargetPlatform).equals(TARGET));
assertTrue(
"source set",
config.getJavaOptions().get(CompilerOptions.OPTION_Compliance).equals(CompilerOptions.VERSION_1_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 = parser.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 = parser.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 {
parser.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();
}
}
|
49,814
|
Bug 49814 ConfigParser.java:132
| null |
resolved fixed
|
a4a1234
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-12T11:37:20Z
| 2004-01-10T21:26:40Z
|
util/src/org/aspectj/util/ConfigParser.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.util;
import java.util.*;
import java.io.*;
public class ConfigParser {
Location location;
protected List files = new LinkedList();
private boolean fileParsed = false;
protected static String CONFIG_MSG = "build config error: ";
public List getFiles() { return files; }
public void parseCommandLine(String[] argsArray) throws ParseException {
location = new CommandLineLocation();
LinkedList args = new LinkedList();
for (int i = 0; i < argsArray.length; i++) {
args.add(new Arg(argsArray[i], location));
}
parseArgs(args);
}
public void parseConfigFile(File configFile) throws ParseException {
if (fileParsed == true) {
throw new ParseException(CONFIG_MSG + "The file has already been parsed.", null);
} else {
parseConfigFileHelper(configFile);
}
}
/**
* @throws ParseException if the config file has already been prased.
*/
private void parseConfigFileHelper(File configFile) {
if (!configFile.exists()) {
showError("file does not exist: " + configFile.getPath());
return;
}
LinkedList args = new LinkedList();
int lineNum = 0;
try {
BufferedReader stream =
new BufferedReader(new FileReader(configFile));
String line = null;
while ( (line = stream.readLine()) != null) {
lineNum += 1;
line = stripWhitespaceAndComments(line);
if (line.length() == 0) continue;
args.add(new Arg(line, new SourceLocation(configFile, lineNum)));
}
} catch (IOException e) {
location = new SourceLocation(configFile, lineNum);
showError("error reading config file: " + e.toString());
}
parseArgs(args);
fileParsed = true;
}
File getCurrentDir() {
return location.getDirectory();
}
String stripSingleLineComment(String s, String commentString) {
int commentStart = s.indexOf(commentString);
if (commentStart == -1) return s;
else return s.substring(0, commentStart);
}
String stripWhitespaceAndComments(String s) {
s = stripSingleLineComment(s, "//");
s = stripSingleLineComment(s, "#");
s = s.trim();
if (s.startsWith("\"") && s.endsWith("\"")) {
s = s.substring(1, s.length()-1);
}
return s;
}
/** ??? We would like to call a showNonFatalError method here
* to show all errors in config files before aborting the compilation
*/
protected void addFile(File sourceFile) {
if (!sourceFile.isFile()) {
showError("source file does not exist: " + sourceFile.getPath());
}
files.add(sourceFile);
}
void addFileOrPattern(File sourceFile) {
if (sourceFile.getName().equals("*.java")) {
addFiles(sourceFile.getParentFile(), new FileFilter() {
public boolean accept(File f) {
return f != null && f.getName().endsWith(".java");
}});
} else if (sourceFile.getName().equals("*.aj")) {
addFiles(sourceFile.getParentFile(), new FileFilter() {
public boolean accept(File f) {
return f != null && f.getName().endsWith(".aj");
}});
} else {
addFile(sourceFile);
}
}
void addFiles(File dir, FileFilter filter) {
if (dir == null) dir = new File(System.getProperty("user.dir"));
if (!dir.isDirectory()) {
showError("can't find " + dir.getPath());
}
File[] files = dir.listFiles(filter);
if (files.length == 0) {
showWarning("no matching files found in: " + dir);
}
for (int i = 0; i < files.length; i++) {
addFile(files[i]);
}
}
protected void parseOption(String arg, LinkedList args) {
showWarning("unrecognized option: " + arg);
}
protected void showWarning(String message) {
if (location != null) {
message += " at " + location.toString();
}
System.err.println(CONFIG_MSG + message);
}
protected void showError(String message) {
throw new ParseException(CONFIG_MSG + message, location);
}
void parseArgs(LinkedList args) {
while (args.size() > 0) parseOneArg(args);
}
protected Arg removeArg(LinkedList args) {
if (args.size() == 0) {
showError("value missing");
return null;
} else {
return (Arg)args.removeFirst();
}
}
protected String removeStringArg(LinkedList args) {
Arg arg = removeArg(args);
if (arg == null) return null;
return arg.getValue();
}
boolean isSourceFileName(String s) {
if (s.endsWith(".java")) return true;
if (s.endsWith(".aj")) return true;
if (s.endsWith(".ajava")) {
showWarning(".ajava is deprecated, replace with .aj or .java: " + s);
return true;
}
return false;
}
void parseOneArg(LinkedList args) {
Arg arg = removeArg(args);
String v = arg.getValue();
location = arg.getLocation();
if (v.startsWith("@")) {
parseImportedConfigFile(v.substring(1));
} else if (v.equals("-argfile")) {
parseConfigFileHelper(makeFile(removeArg(args).getValue()));
} else if (isSourceFileName(v)) {
addFileOrPattern(makeFile(v));
} else {
parseOption(arg.getValue(), args);
}
}
protected void parseImportedConfigFile(String relativeFilePath) {
parseConfigFileHelper(makeFile(relativeFilePath));
}
public File makeFile(String name) {
return makeFile(getCurrentDir(), name);
}
private File makeFile(File dir, String name) {
name = name.replace('/', File.separatorChar);
File ret = new File(name);
if (dir != null && !ret.isAbsolute()) {
ret = new File(dir, name);
}
try {
ret = ret.getCanonicalFile();
} catch (IOException ioEx) {
// proceed without canonicalization
// so nothing to do here
}
return ret;
}
protected static class Arg {
private Location location;
private String value;
public Arg(String value, Location location) {
this.value = value;
this.location = location;
}
public void setValue(String value) {
this.value = value;
}
public void setLocation(Location location) {
this.location = location;
}
public String getValue() { return value; }
public Location getLocation() { return location; }
}
static abstract class Location {
public abstract File getFile();
public abstract File getDirectory();
public abstract int getLine();
public abstract String toString();
}
static class SourceLocation extends Location {
private int line;
private File file;
public SourceLocation(File file, int line) {
this.line = line;
this.file = file;
}
public File getFile() { return file; }
public File getDirectory() { return file.getParentFile(); }
public int getLine() { return line; }
public String toString() {
return file.getPath()+":"+line;
}
}
static class CommandLineLocation extends Location {
public File getFile() {
return new File(System.getProperty("user.dir"));
}
public File getDirectory() {
return new File(System.getProperty("user.dir"));
}
public int getLine() { return -1; }
public String toString() {
return "command-line";
}
}
public static class ParseException extends RuntimeException {
private Location location;
public ParseException(String message, Location location) {
super(message);
this.location = location;
}
public int getLine() {
if (location == null) return -1;
return location.getLine();
}
public File getFile() {
if (location == null) return null;
return location.getFile();
}
}
}
|
44,586
|
Bug 44586 After throwing advice on ctors doesn't execute for inter-type decls
|
The following code doesn't work in Ajc 1.1.1, in Ajc built from CVS HEAD (as of yesterday), nor in Ajc 1.0.6: Output: C:\devel\test\excHandling>java AfterThrowingCtor Exception in thread "main" java.lang.IllegalStateException: crash at Foo.initVal(AfterThrowingCtor.java:21) at AfterThrowingCtor.ajc$interFieldInit$AfterThrowingCtor$Foo$val (AfterT hrowingCtor.java:9) at Foo.<init>(AfterThrowingCtor.java:13) at AfterThrowingCtor.main(AfterThrowingCtor.java:6) Correct Output: threw java.lang.IllegalStateException: crash at execution(Foo()) Exception in thread "main" java.lang.IllegalStateException: crash at Foo.initVal(AfterThrowingCtor.java:21) at AfterThrowingCtor.ajc$interFieldInit$AfterThrowingCtor$Foo$val (AfterT hrowingCtor.java:9) at Foo.<init>(AfterThrowingCtor.java:13) at AfterThrowingCtor.main(AfterThrowingCtor.java:6) Input source: public aspect AfterThrowingCtor { after() throwing (Throwable t) : execution(Foo.new(..)) { System.err.println("threw "+t+" at "+thisJoinPointStaticPart); } public static void main(String args[]) { new Foo(); } private Object Foo.val = Foo.initVal(); } class Foo { Foo() { } // if you uncomment this line and comment out the inter-type decl. // the advice runs correctly //private Object val = initVal(); static Object initVal() { throw new IllegalStateException("crash"); } } --- AspectJ 1.1.1 runs the after throwing advice correctly if the field is declared normally (AspectJ 1.0.6 fails to do even this).
|
resolved fixed
|
87db1e7
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-13T16:10:52Z
| 2003-10-09T17:20:00Z
|
tests/bugs/AfterThrowingCtor.java
| |
46,280
|
Bug 46280 compiler issues error on inner aspects when privilieged
|
The compiler complains that "inner aspects must be static" whenever I try to qualify an inner (and static) aspect as privileged, no matter what the enclosing type is (aspect, interface or class). I was using j2sdk1.4.0_02, AspectJ 1.1, eclipse 2.1 (with AJDT 1.1.3). Test case: ------------------ BASE CLASS: public class Capsule { private int hidden; public int visible; public Capsule(int priv, int pub) { hidden = priv; visible = pub; } public void doSomething() { System.out.println(""" + hidden + ", " + visible + """); } public static void main(String[] args) { Capsule capsule = new Capsule(1, 1); capsule.doSomething(); } } ------------------ ASPECT: public aspect Outer { static //privileged <== JUST TRY TO UNCOMMENT THIS! aspect Inner { pointcut call2doSomething(Capsule capsule): call(void Capsule.doSomething()) && target(capsule); before(Capsule capsule): call2doSomething(capsule) { capsule.visible++; //capsule.hidden++; } } } ------------------ INTERFACE: public interface Marker { static //privileged <== JUST TRY TO UNCOMMENT THIS! aspect Inner { pointcut call2doSomething(Capsule capsule): call(void Capsule.doSomething()) && target(capsule); before(Capsule capsule): call2doSomething(capsule) { capsule.visible++; //capsule.hidden++; } } }
|
resolved fixed
|
7bbd1f4
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-14T11:28:13Z
| 2003-11-07T15:46:40Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/parser/AjParser.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.parser;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.List;
import org.aspectj.ajdt.internal.compiler.ast.AdviceDeclaration;
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.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.ISourceContext;
import org.aspectj.weaver.patterns.Declare;
import org.eclipse.jdt.internal.compiler.CompilationResult;
import org.eclipse.jdt.internal.compiler.ast.Argument;
import org.eclipse.jdt.internal.compiler.ast.ASTNode;
import org.eclipse.jdt.internal.compiler.ast.ExplicitConstructorCall;
import org.eclipse.jdt.internal.compiler.ast.Expression;
import org.eclipse.jdt.internal.compiler.ast.Literal;
import org.eclipse.jdt.internal.compiler.ast.MessageSend;
import org.eclipse.jdt.internal.compiler.ast.OperatorExpression;
import org.eclipse.jdt.internal.compiler.ast.OperatorIds;
import org.eclipse.jdt.internal.compiler.ast.TypeReference;
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
import org.eclipse.jdt.internal.compiler.parser.Parser;
import org.eclipse.jdt.internal.compiler.parser.RecoveredType;
import org.eclipse.jdt.internal.compiler.problem.ProblemReporter;
import org.eclipse.jdt.internal.compiler.problem.ProblemSeverities;
import org.eclipse.jdt.core.compiler.CharOperation;
public class AjParser extends Parser {
static {
try{
initTables(AjParser.class);
} catch(java.io.IOException ex){
throw new ExceptionInInitializerError(ex.getMessage());
}
}
// public final static void initAjTables(Class parserClass)
// throws java.io.IOException {
//
// final String prefix = FILEPREFIX;
// int i = 0;
// lhsStatic = readTable(parserClass, prefix + (++i) + ".rsc"); //$NON-NLS-1$
// char[] chars = readTable(parserClass, prefix + (++i) + ".rsc"); //$NON-NLS-1$
// check_tableStatic = new short[chars.length];
// for (int c = chars.length; c-- > 0;) {
// check_tableStatic[c] = (short) (chars[c] - 32768);
// }
// asbStatic = readTable(parserClass, prefix + (++i) + ".rsc"); //$NON-NLS-1$
// asrStatic = readTable(parserClass, prefix + (++i) + ".rsc"); //$NON-NLS-1$
// symbol_indexStatic = readTable(parserClass, prefix + (++i) + ".rsc"); //$NON-NLS-1$
// actionStatic = lhsStatic;
// }
public void initializeScanner(){
this.scanner = new AjScanner(
false /*comment*/,
false /*whitespace*/,
this.options.getSeverity(CompilerOptions.NonExternalizedString) != ProblemSeverities.Ignore /*nls*/,
this.options.sourceLevel /*sourceLevel*/,
this.options.taskTags/*taskTags*/,
this.options.taskPriorites/*taskPriorities*/);
}
//*************New display debugging method
private static final boolean AJ_DEBUG = false;
void println(Object o) {
if (AJ_DEBUG) System.out.println(o);
}
private void printStack(Object[] s, int p) {
List list = Arrays.asList(s);
System.out.println(" " + list.subList(0, p+1));
}
private void printStack(int[] s, int p) {
StringBuffer buf = new StringBuffer("[");
for (int i=0; i<p+1; i++) {
if (i > 0) buf.append(", ");
buf.append(Integer.toString(s[i]));
}
buf.append("]");
System.out.println(" " + buf);
}
private void printStack(long[] s, int p) {
StringBuffer buf = new StringBuffer("[");
for (int i=0; i<p+1; i++) {
if (i > 0) buf.append(", ");
buf.append(Long.toString(s[i]));
}
buf.append("]");
System.out.println(" " + buf);
}
private void printStack(char[][] s, int p) {
StringBuffer buf = new StringBuffer("[");
for (int i=0; i<p+1; i++) {
if (i > 0) buf.append(", ");
buf.append(new String(s[i]));
}
buf.append("]");
System.out.println(" " + buf);
}
public void display() {
if (!AJ_DEBUG) return;
System.out.print("astStack: ");
printStack(astStack, astPtr);
System.out.print("astLengthStack: ");
printStack(astLengthStack, astLengthPtr);
System.out.print("expressionStack: ");
printStack(expressionStack, expressionPtr);
System.out.print("expressionLengthStack: ");
printStack(expressionLengthStack, expressionLengthPtr);
System.out.print("identifierStack: ");
printStack(identifierStack, identifierPtr);
System.out.print("identifierLengthStack: ");
printStack(identifierLengthStack, identifierLengthPtr);
System.out.print("identifierPositionStack: ");
printStack(identifierPositionStack, identifierPtr);
System.out.print("intStack:");
printStack(intStack, intPtr);
System.out.println();
}
//************** Overriding behavior for standard Java rules
protected void consumeMethodInvocationName() {
super.consumeMethodInvocationName();
MessageSend m = (MessageSend)expressionStack[expressionPtr];
if (CharOperation.equals(m.selector, "proceed".toCharArray())) {
expressionStack[expressionPtr] = new Proceed(m);
}
}
protected void consumeToken(int type) {
currentTokenStart = scanner.startPosition;
super.consumeToken(type);
switch (type) {
case TokenNameaspect : // pseudo keyword
case TokenNameprivileged : // pseudo keyword
case TokenNamepointcut : // pseudo keyword
case TokenNamebefore : // pseudo keyword
case TokenNameafter : // pseudo keyword
case TokenNamearound : // pseudo keyword
case TokenNamedeclare : // pseudo keyword
pushIdentifier();
scanner.commentPtr = -1;
break;
}
}
//************New AspectJ rules
protected void consumeAspectDeclaration() {
// AspectDeclaration ::= AspectHeader AspectBody
consumeClassDeclaration();
//??? post parsing step here
}
protected void consumeAspectHeader() {
// AspectHeader ::= AspectHeaderName ClassHeaderExtendsopt ClassHeaderImplementsopt AspectHeaderRest
consumeClassHeader();
}
protected void consumeAspectHeaderName(boolean isPrivileged) {
// (isPrivileged == false) -> AspectHeaderName ::= Modifiersopt 'aspect' 'Identifier'
// (isPrivileged == true) -> AspectHeaderName ::= Modifiersopt 'privileged' Modifiersopt 'aspect' 'Identifier'
AspectDeclaration aspectDecl =
new AspectDeclaration(this.compilationUnit.compilationResult);
println("aspect header name: ");
this.display();
//highlight the name of the type
long pos = identifierPositionStack[identifierPtr];
aspectDecl.sourceEnd = (int) pos;
aspectDecl.sourceStart = (int) (pos >>> 32);
aspectDecl.name = identifierStack[identifierPtr--];
identifierLengthPtr--;
// pop the aspect pseudo-token
eatIdentifier();
// handle modifiers, only without privileged for now
if (isPrivileged) {
pos = eatIdentifier(); // eat the privileged
int end = (int) pos;
int start = (int) (pos >>> 32);
aspectDecl.isPrivileged = true;
//problemReporter().signalError(start, end, "privileged is unimplemented in 1.1alpha1");
}
aspectDecl.modifiersSourceStart = intStack[intPtr--];
aspectDecl.modifiers = intStack[intPtr--];
if (aspectDecl.modifiersSourceStart >= 0) {
aspectDecl.declarationSourceStart = aspectDecl.modifiersSourceStart;
}
println("modifiers: " + aspectDecl.modifiers);
aspectDecl.bodyStart = aspectDecl.sourceEnd + 1;
pushOnAstStack(aspectDecl);
listLength = 0; // will be updated when reading super-interfaces
// recovery
if (currentElement != null) {
lastCheckPoint = aspectDecl.bodyStart;
currentElement = currentElement.add(aspectDecl, 0);
lastIgnoredToken = -1;
}
this.display();
}
private long eatIdentifier() {
long pos = identifierPositionStack[identifierPtr];
identifierPtr--;
identifierLengthPtr--;
return pos;
}
protected void consumeAspectHeaderRest() {
//--[dominates TypePattern] [persingleton() | percflow(PCD) | perthis(PCD) | pertarget(PCD)]
//AspectHeaderRest ::= AspectHeaderRestStart PseudoTokens
concatNodeLists();
this.display();
PseudoTokens pseudoTokens = popPseudoTokens("{");
println("pseudo: " + pseudoTokens);
AspectDeclaration aspectDecl = (AspectDeclaration) astStack[astPtr];
aspectDecl.dominatesPattern = pseudoTokens.maybeParseDominatesPattern(this);
aspectDecl.perClause = pseudoTokens.parsePerClause(this);
// XXX handle dominates
}
protected void consumePointcutDeclaration() {
consumePointcutDesignatorOnDeclaration();
}
protected void consumeEmptyPointcutDeclaration() {
//??? set pcd to non-null
}
protected void consumePointcutHeader() {
//PointcutDeclaration ::= Modifiersopt 'pointcut' JavaIdentifier '('
PointcutDeclaration ret = new PointcutDeclaration(compilationUnit.compilationResult);
//the name
long pos = identifierPositionStack[identifierPtr];
int sourceEnd = (int) pos;
ret.sourceStart = (int) (pos >>> 32);
ret.selector = identifierStack[identifierPtr--];
identifierLengthPtr--;
// pop the 'pointcut' keyword
eatIdentifier();
// modifiers
ret.declarationSourceStart = intStack[intPtr--];
ret.modifiers = intStack[intPtr--];
pushOnAstStack(ret);
}
protected void consumeAroundDeclaration() {
// AroundDeclaration ::= AroundHeader MethodBody
consumeMethodDeclaration(true);
}
protected void consumeAroundHeader() {
consumePointcutDesignatorOnAdvice();
consumeMethodHeader();
}
protected void consumeAroundHeaderName() {
// AroundHeaderName ::= Modifiersopt Type 'around' '('
AdviceDeclaration adviceDecl =
new AdviceDeclaration(compilationUnit.compilationResult, AdviceKind.Around);
// skip the name of the advice
long pos = eatIdentifier();
adviceDecl.sourceStart = (int) (pos >>> 32);
TypeReference returnType = getTypeReference(intStack[intPtr--]);
//modifiers
adviceDecl.declarationSourceStart = intStack[intPtr--];
adviceDecl.modifiers = intStack[intPtr--];
adviceDecl.returnType = returnType;
//XXX get some locations right
pushOnAstStack(adviceDecl);
}
protected void consumePointcutDesignatorOnAdvice() {
PointcutDesignator des = popPointcutDesignator("{");
AdviceDeclaration adviceDecl = (AdviceDeclaration)astStack[astPtr];
adviceDecl.pointcutDesignator = des;
adviceDecl.sourceEnd = des.sourceEnd;
adviceDecl.bodyStart = des.sourceEnd+1;
}
protected void consumePointcutDesignatorOnDeclaration() {
PointcutDesignator des = popPointcutDesignator(";");
PointcutDeclaration adviceDecl = (PointcutDeclaration)astStack[astPtr];
adviceDecl.pointcutDesignator = des;
adviceDecl.sourceEnd = des.sourceEnd;
adviceDecl.bodyStart = des.sourceEnd+1;
}
protected void consumeBasicAdviceDeclaration() {
// BasicAdviceDeclaration ::= BasicAdviceHeader MethodBody
consumeMethodDeclaration(true);
}
protected void consumeBasicAdviceHeader() {
// BasicAdviceHeader ::= BasicAdviceHeaderName MethodHeaderParameters ExtraParamopt MethodHeaderThrowsClauseopt ':' PseudoTokens
consumePointcutDesignatorOnAdvice();
consumeMethodHeader();
}
protected void consumeBasicAdviceHeaderName(boolean isAfter) {
// BasicAdviceHeaderName ::= 'before'|'after '('
AdviceDeclaration adviceDecl =
new AdviceDeclaration(compilationUnit.compilationResult, isAfter ? AdviceKind.After : AdviceKind.Before);
// skip the name of the advice
long pos = eatIdentifier();
adviceDecl.sourceStart = (int) (pos >>> 32);
//modifiers
adviceDecl.declarationSourceStart = intStack[intPtr--];
adviceDecl.modifiers = intStack[intPtr--];
//??? get more locations right
pushOnAstStack(adviceDecl);
}
protected void consumeExtraParameterWithFormal() {
Argument arg = (Argument)astStack[astPtr--];
astLengthPtr--;
((AdviceDeclaration)astStack[astPtr]).extraArgument = arg;
consumeExtraParameterNoFormal();
}
protected void consumeExtraParameterNoFormal() {
long pos = identifierPositionStack[identifierPtr];
int end = (int) pos;
int start = (int) (pos >>> 32);
char[] name = identifierStack[identifierPtr--];
identifierLengthPtr--;
//System.out.println("extra parameter: " + new String(name));
AdviceDeclaration adviceDecl = (AdviceDeclaration)astStack[astPtr];
if (adviceDecl.kind != AdviceKind.After) {
//XXX error, extra param makes no sense here
}
if (CharOperation.equals(name, "throwing".toCharArray())) {
adviceDecl.kind = AdviceKind.AfterThrowing;
} else if (CharOperation.equals(name, "returning".toCharArray())) {
adviceDecl.kind = AdviceKind.AfterReturning;
} else {
problemReporter().parseError(
start,
end,
currentToken,
name,
String.valueOf(name),
new String[] {"throwing", "returning", ":"});
}
}
protected void consumeClassBodyDeclarationInAspect() { }
protected void consumeDeclareDeclaration() {
concatNodeLists();
PseudoTokens tokens = popPseudoTokens(";");
Declare declare = tokens.parseDeclare(this);
println("parsed declare: " + declare);
display();
pushOnAstStack(new DeclareDeclaration(this.compilationUnit.compilationResult, declare));
}
protected void consumeDeclareHeader() {
consumePseudoTokenIdentifier(); // name
consumePseudoTokenIdentifier(); // declare
swapAstStack();
consumePseudoTokens();
consumePseudoToken(":", 0, false);
consumePseudoTokens();
println(">>>>>>>>>>>>>>>>>>>>>>>declare header");
display();
}
protected void consumeInterTypeFieldDeclaration() {
// InterTypeFieldDeclaration ::= Modifiersopt Type OnType '.' JavaIdentifier InterTypeFieldBody ';'
println("about to consume field");
this.display();
// FieldDeclaration field = new FieldDeclaration();
Expression initialization = null;
if (expressionPtr >= 0) {
expressionLengthPtr--;
initialization = expressionStack[expressionPtr--];
}
long pos = identifierPositionStack[identifierPtr];
int end = (int) pos;
int start = (int) (pos >>> 32);
char[] name = identifierStack[identifierPtr--];
identifierLengthPtr--;
// field.name = name;
// field.sourceStart = start;
// field.sourceEnd = end;
TypeReference onType = getTypeReference(0);
TypeReference returnType = getTypeReference(intStack[intPtr--]);
this.display();
int decSourceStart = intStack[intPtr--];
int modifiers = intStack[intPtr--];
InterTypeFieldDeclaration dec =
new InterTypeFieldDeclaration(
this.compilationUnit.compilationResult,
onType);
dec.returnType = returnType;
dec.sourceStart = start;
dec.sourceEnd = end;
dec.setSelector(name);
dec.declarationSourceStart = decSourceStart;
dec.setDeclaredModifiers(modifiers);
dec.setInitialization(initialization);
pushOnAstStack(dec);
println("consumed field: " + dec);
this.display();
}
protected void consumeInterTypeMethodDeclaration(boolean isNotAbstract) {
consumeMethodDeclaration(isNotAbstract);
}
protected void consumeInterTypeMethodHeader() {
consumeMethodHeader();
}
protected void consumeInterTypeConstructorDeclaration() {
consumeMethodDeclaration(true);
}
protected void consumeInterTypeConstructorHeader() {
consumeMethodHeader();
}
protected void consumeInterTypeMethodHeaderName() {
//InterTypeMethodHeaderName ::= Modifiersopt Type OnType '.' JavaIdentifier '('
this.display();
InterTypeMethodDeclaration md =
new InterTypeMethodDeclaration(
this.compilationUnit.compilationResult,
null);
//identifier
char[] name = identifierStack[identifierPtr];
long selectorSource = identifierPositionStack[identifierPtr--];
identifierLengthPtr--;
//onType
md.onType = getTypeReference(0);
//type
md.returnType = getTypeReference(intStack[intPtr--]);
//modifiers
md.declarationSourceStart = intStack[intPtr--];
md.setDeclaredModifiers(intStack[intPtr--]);
//highlight starts at selector start
md.sourceStart = (int) (selectorSource >>> 32);
pushOnAstStack(md);
md.sourceEnd = lParenPos;
md.bodyStart = lParenPos + 1;
md.setSelector(name);
listLength = 0;
// initialize listLength before reading parameters/throws
// recovery
if (currentElement != null) {
if (currentElement instanceof RecoveredType
//|| md.modifiers != 0
|| (scanner.getLineNumber(md.returnType.sourceStart)
== scanner.getLineNumber(md.sourceStart))) {
lastCheckPoint = md.bodyStart;
currentElement = currentElement.add(md, 0);
lastIgnoredToken = -1;
} else {
lastCheckPoint = md.sourceStart;
restartRecovery = true;
}
}
}
protected void consumeInterTypeConstructorHeaderName() {
//InterTypeConstructorHeaderName ::= Modifiersopt Name '.' 'new' '('
this.display();
InterTypeConstructorDeclaration md =
new InterTypeConstructorDeclaration(
this.compilationUnit.compilationResult,
null);
//identifier
// md.selector = identifierStack[identifierPtr];
// long selectorSource = identifierPositionStack[identifierPtr--];
//// identifierLengthPtr--;
//onType
md.onType = getTypeReference(0);
println("got onType: " + md.onType);
this.display();
intPtr--; // pop new info
//type
md.returnType = TypeReference.baseTypeReference(T_void, 0); //getTypeReference(intStack[intPtr--]);
//modifiers
md.declarationSourceStart = intStack[intPtr--];
md.setDeclaredModifiers(intStack[intPtr--]);
//md.modifiers = intStack[intPtr--];
//highlight starts at selector start
//md.sourceStart = (int) (selectorSource >>> 32);
md.sourceStart = md.onType.sourceStart;
pushOnAstStack(md);
md.sourceEnd = lParenPos;
md.bodyStart = lParenPos + 1;
listLength = 0;
// initialize listLength before reading parameters/throws
md.setSelector(
(new String(CharOperation.concatWith(md.onType.getTypeName(), '_')) + "_new").
toCharArray());
// recovery
if (currentElement != null) {
if (currentElement instanceof RecoveredType
//|| md.modifiers != 0
//|| (scanner.getLineNumber(md.returnType.sourceStart)
// == scanner.getLineNumber(md.sourceStart))
) {
//lastCheckPoint = md.bodyStart;
currentElement = currentElement.add(md, 0);
lastIgnoredToken = -1;
} else {
lastCheckPoint = md.sourceStart;
restartRecovery = true;
}
}
}
//*********************************************************
protected void consumePseudoToken(String value) {
consumePseudoToken(value, 0, false);
}
protected void consumePseudoToken(
String value,
int popFromIntStack,
boolean isIdentifier) {
intPtr -= popFromIntStack;
int start = currentTokenStart;
int end = start + value.length() - 1;
PseudoToken tok = new PseudoToken(this, value, isIdentifier);
tok.sourceStart = start;
tok.sourceEnd = end;
pushOnAstStack(tok);
}
protected void consumePseudoTokenIdentifier() {
long pos = identifierPositionStack[identifierPtr];
int end = (int) pos;
int start = (int) (pos >>> 32);
char[] name = identifierStack[identifierPtr--];
identifierLengthPtr--;
PseudoToken tok = new PseudoToken(this, new String(name), true);
tok.sourceStart = start;
tok.sourceEnd = end;
pushOnAstStack(tok);
}
protected void consumePseudoTokenIf() {
//this.display();
Expression expr = (Expression) expressionStack[expressionPtr--];
expressionLengthPtr--;
println("expr: " + expr);
int start = intStack[intPtr--];
PseudoToken tok = new IfPseudoToken(this, expr);
tok.sourceStart = start;
tok.sourceEnd = this.rParenPos;
pushOnAstStack(tok);
}
protected void consumePseudoTokenLiteral() {
Literal literal = (Literal) expressionStack[expressionPtr--];
expressionLengthPtr--;
//System.out.println("literal: " + new String(literal.source()));
PseudoToken tok =
new PseudoToken(this, new String(literal.source()), false);
tok.literalKind = "string";
tok.sourceStart = literal.sourceStart;
tok.sourceEnd = literal.sourceEnd;
pushOnAstStack(tok);
}
protected void consumePseudoTokenModifier() {
//int modifier = modifiers;
consumePseudoToken(Modifier.toString(modifiers), 0, true);
modifiers = AccDefault;
}
protected void consumePseudoTokenPrimitiveType() {
TypeReference type = getTypeReference(0);
PseudoToken tok = new PseudoToken(this, type.toString(), true);
tok.sourceStart = type.sourceStart;
tok.sourceEnd = type.sourceEnd;
pushOnAstStack(tok);
}
protected void consumePseudoTokens() {
optimizedConcatNodeLists();
}
// Helpers
protected PointcutDesignator popPointcutDesignator(String terminator) {
PseudoTokens tokens = popPseudoTokens(terminator);
return new PointcutDesignator(this, tokens);
}
protected PseudoTokens popPseudoTokens(String terminator) {
consumePseudoToken(terminator);
consumePseudoTokens();
//System.out.println("next token is: " + new String(scanner.getCurrentTokenSource()));
int length = astLengthStack[astLengthPtr--];
astPtr -= length;
//arguments
PseudoToken[] tokens = new PseudoToken[length];
System.arraycopy(astStack, astPtr + 1, tokens, 0, length);
//md.bodyStart = rParenPos+1;
listLength = 0; // reset listLength after having read all parameters
return new PseudoTokens(tokens, makeSourceContext(this.compilationUnit.compilationResult()));
}
private ISourceContext makeSourceContext(CompilationResult compilationResult) {
return new EclipseSourceContext(compilationResult);
}
private void swapAstStack() {
ASTNode top = astStack[astPtr];
ASTNode next = astStack[astPtr-1];
astStack[astPtr] = next;
astStack[astPtr-1] = top;
}
// This method is part of an automatic generation : do NOT edit-modify
protected void consumeRule(int act) {
switch ( act ) {
case 30 : // System.out.println("Type ::= PrimitiveType"); //$NON-NLS-1$
consumePrimitiveType();
break ;
case 44 : // System.out.println("ReferenceType ::= ClassOrInterfaceType"); //$NON-NLS-1$
consumeReferenceType();
break ;
case 62 : // System.out.println("AjQualifiedName ::= AjName DOT SimpleName"); //$NON-NLS-1$
consumeQualifiedName();
break ;
case 66 : // System.out.println("QualifiedName ::= Name DOT JavaIdentifier"); //$NON-NLS-1$
consumeQualifiedName();
break ;
case 67 : // System.out.println("CompilationUnit ::= EnterCompilationUnit PackageDeclarationopt..."); //$NON-NLS-1$
consumeCompilationUnit();
break ;
case 68 : // System.out.println("EnterCompilationUnit ::="); //$NON-NLS-1$
consumeEnterCompilationUnit();
break ;
case 81 : // System.out.println("CatchHeader ::= catch LPAREN FormalParameter RPAREN LBRACE"); //$NON-NLS-1$
consumeCatchHeader();
break ;
case 83 : // System.out.println("ImportDeclarations ::= ImportDeclarations ImportDeclaration"); //$NON-NLS-1$
consumeImportDeclarations();
break ;
case 85 : // System.out.println("TypeDeclarations ::= TypeDeclarations TypeDeclaration"); //$NON-NLS-1$
consumeTypeDeclarations();
break ;
case 86 : // System.out.println("PackageDeclaration ::= PackageDeclarationName SEMICOLON"); //$NON-NLS-1$
consumePackageDeclaration();
break ;
case 87 : // System.out.println("PackageDeclarationName ::= package Name"); //$NON-NLS-1$
consumePackageDeclarationName();
break ;
case 90 : // System.out.println("SingleTypeImportDeclaration ::= SingleTypeImportDeclarationName..."); //$NON-NLS-1$
consumeSingleTypeImportDeclaration();
break ;
case 91 : // System.out.println("SingleTypeImportDeclarationName ::= import Name"); //$NON-NLS-1$
consumeSingleTypeImportDeclarationName();
break ;
case 92 : // System.out.println("TypeImportOnDemandDeclaration ::= TypeImportOnDemandDeclarationName"); //$NON-NLS-1$
consumeTypeImportOnDemandDeclaration();
break ;
case 93 : // System.out.println("TypeImportOnDemandDeclarationName ::= import Name DOT MULTIPLY"); //$NON-NLS-1$
consumeTypeImportOnDemandDeclarationName();
break ;
case 96 : // System.out.println("TypeDeclaration ::= SEMICOLON"); //$NON-NLS-1$
consumeEmptyTypeDeclaration();
break ;
case 122 : // System.out.println("AspectDeclaration ::= AspectHeader AspectBody"); //$NON-NLS-1$
consumeAspectDeclaration();
break ;
case 123 : // System.out.println("AspectHeader ::= AspectHeaderName ClassHeaderExtendsopt..."); //$NON-NLS-1$
consumeAspectHeader();
break ;
case 124 : // System.out.println("AspectHeaderName ::= Modifiersopt aspect Identifier"); //$NON-NLS-1$
consumeAspectHeaderName(false);
break ;
case 125 : // System.out.println("AspectHeaderName ::= Modifiersopt privileged Modifiersopt aspect..."); //$NON-NLS-1$
consumeAspectHeaderName(true);
break ;
case 127 : // System.out.println("AspectHeaderRest ::= AspectHeaderRestStart PseudoTokens"); //$NON-NLS-1$
consumeAspectHeaderRest();
break ;
case 128 : // System.out.println("AspectHeaderRestStart ::= Identifier"); //$NON-NLS-1$
consumePseudoTokenIdentifier();
break ;
case 131 : // System.out.println("AspectBodyDeclarations ::= AspectBodyDeclarations..."); //$NON-NLS-1$
consumeClassBodyDeclarations();
break ;
case 132 : // System.out.println("AspectBodyDeclarationsopt ::="); //$NON-NLS-1$
consumeEmptyClassBodyDeclarationsopt();
break ;
case 133 : // System.out.println("AspectBodyDeclarationsopt ::= NestedType AspectBodyDeclarations"); //$NON-NLS-1$
consumeClassBodyDeclarationsopt();
break ;
case 134 : // System.out.println("AspectBodyDeclaration ::= ClassBodyDeclaration"); //$NON-NLS-1$
consumeClassBodyDeclarationInAspect();
break ;
case 135 : // System.out.println("PointcutDeclaration ::= PointcutHeader MethodHeaderParameters..."); //$NON-NLS-1$
consumeEmptyPointcutDeclaration();
break ;
case 136 : // System.out.println("PointcutDeclaration ::= PointcutHeader MethodHeaderParameters COLON"); //$NON-NLS-1$
consumePointcutDeclaration();
break ;
case 137 : // System.out.println("PointcutHeader ::= Modifiersopt pointcut JavaIdentifier LPAREN"); //$NON-NLS-1$
consumePointcutHeader();
break ;
case 140 : // System.out.println("AroundDeclaration ::= AroundHeader MethodBody"); //$NON-NLS-1$
consumeAroundDeclaration();
break ;
case 141 : // System.out.println("AroundHeader ::= AroundHeaderName MethodHeaderParameters..."); //$NON-NLS-1$
consumeAroundHeader();
break ;
case 142 : // System.out.println("AroundHeaderName ::= Modifiersopt Type around LPAREN"); //$NON-NLS-1$
consumeAroundHeaderName();
break ;
case 143 : // System.out.println("BasicAdviceDeclaration ::= BasicAdviceHeader MethodBody"); //$NON-NLS-1$
consumeBasicAdviceDeclaration();
break ;
case 144 : // System.out.println("BasicAdviceHeader ::= BasicAdviceHeaderName MethodHeaderParameters"); //$NON-NLS-1$
consumeBasicAdviceHeader();
break ;
case 145 : // System.out.println("BasicAdviceHeaderName ::= Modifiersopt before LPAREN"); //$NON-NLS-1$
consumeBasicAdviceHeaderName(false);
break ;
case 146 : // System.out.println("BasicAdviceHeaderName ::= Modifiersopt after LPAREN"); //$NON-NLS-1$
consumeBasicAdviceHeaderName(true);
break ;
case 147 : // System.out.println("ExtraParamopt ::= Identifier LPAREN FormalParameter RPAREN"); //$NON-NLS-1$
consumeExtraParameterWithFormal();
break ;
case 148 : // System.out.println("ExtraParamopt ::= Identifier LPAREN RPAREN"); //$NON-NLS-1$
consumeExtraParameterNoFormal();
break ;
case 149 : // System.out.println("ExtraParamopt ::= Identifier"); //$NON-NLS-1$
consumeExtraParameterNoFormal();
break ;
case 152 : // System.out.println("OnType ::= OnType DOT JavaIdentifier"); //$NON-NLS-1$
consumeQualifiedName();
break ;
case 157 : // System.out.println("InterTypeMethodDeclaration ::= InterTypeMethodHeader MethodBody"); //$NON-NLS-1$
// set to true to consume a method with a body
consumeInterTypeMethodDeclaration(true);
break ;
case 158 : // System.out.println("InterTypeMethodHeader ::= InterTypeMethodHeaderName..."); //$NON-NLS-1$
consumeInterTypeMethodHeader();
break ;
case 159 : // System.out.println("InterTypeMethodHeaderName ::= Modifiersopt Type OnType DOT..."); //$NON-NLS-1$
consumeInterTypeMethodHeaderName();
break ;
case 160 : // System.out.println("AbstractInterTypeMethodDeclaration ::= InterTypeMethodHeader..."); //$NON-NLS-1$
// set to false to consume a method without body
consumeInterTypeMethodDeclaration(false);
break ;
case 161 : // System.out.println("InterTypeConstructorDeclaration ::= InterTypeConstructorHeader..."); //$NON-NLS-1$
// set to true to consume a method with a body
consumeInterTypeConstructorDeclaration();
break ;
case 162 : // System.out.println("InterTypeConstructorHeader ::= InterTypeConstructorHeaderName..."); //$NON-NLS-1$
consumeInterTypeConstructorHeader();
break ;
case 163 : // System.out.println("InterTypeConstructorHeaderName ::= Modifiersopt Name DOT new LPAREN"); //$NON-NLS-1$
consumeInterTypeConstructorHeaderName();
break ;
case 164 : // System.out.println("InterTypeFieldDeclaration ::= Modifiersopt Type OnType DOT..."); //$NON-NLS-1$
consumeInterTypeFieldDeclaration();
break ;
case 168 : // System.out.println("DeclareDeclaration ::= DeclareHeader PseudoTokens SEMICOLON"); //$NON-NLS-1$
consumeDeclareDeclaration();
break ;
case 169 : // System.out.println("DeclareHeader ::= declare Identifier COLON"); //$NON-NLS-1$
consumeDeclareHeader();
break ;
case 171 : // System.out.println("PseudoTokens ::= PseudoTokens PseudoToken"); //$NON-NLS-1$
consumePseudoTokens();
break ;
case 172 : // System.out.println("PseudoToken ::= JavaIdentifier"); //$NON-NLS-1$
consumePseudoTokenIdentifier();
break ;
case 173 : // System.out.println("PseudoToken ::= LPAREN"); //$NON-NLS-1$
consumePseudoToken("(");
break ;
case 174 : // System.out.println("PseudoToken ::= RPAREN"); //$NON-NLS-1$
consumePseudoToken(")");
break ;
case 175 : // System.out.println("PseudoToken ::= DOT"); //$NON-NLS-1$
consumePseudoToken(".");
break ;
case 176 : // System.out.println("PseudoToken ::= MULTIPLY"); //$NON-NLS-1$
consumePseudoToken("*");
break ;
case 177 : // System.out.println("PseudoToken ::= PLUS"); //$NON-NLS-1$
consumePseudoToken("+");
break ;
case 178 : // System.out.println("PseudoToken ::= AND_AND"); //$NON-NLS-1$
consumePseudoToken("&&");
break ;
case 179 : // System.out.println("PseudoToken ::= OR_OR"); //$NON-NLS-1$
consumePseudoToken("||");
break ;
case 180 : // System.out.println("PseudoToken ::= NOT"); //$NON-NLS-1$
consumePseudoToken("!");
break ;
case 181 : // System.out.println("PseudoToken ::= COLON"); //$NON-NLS-1$
consumePseudoToken(":");
break ;
case 182 : // System.out.println("PseudoToken ::= COMMA"); //$NON-NLS-1$
consumePseudoToken(",");
break ;
case 183 : // System.out.println("PseudoToken ::= LBRACKET"); //$NON-NLS-1$
consumePseudoToken("[");
break ;
case 184 : // System.out.println("PseudoToken ::= RBRACKET"); //$NON-NLS-1$
consumePseudoToken("]");
break ;
case 185 : // System.out.println("PseudoToken ::= PrimitiveType"); //$NON-NLS-1$
consumePseudoTokenPrimitiveType();
break ;
case 186 : // System.out.println("PseudoToken ::= Modifier"); //$NON-NLS-1$
consumePseudoTokenModifier();
break ;
case 187 : // System.out.println("PseudoToken ::= Literal"); //$NON-NLS-1$
consumePseudoTokenLiteral();
break ;
case 188 : // System.out.println("PseudoToken ::= this"); //$NON-NLS-1$
consumePseudoToken("this", 1, true);
break ;
case 189 : // System.out.println("PseudoToken ::= super"); //$NON-NLS-1$
consumePseudoToken("super", 1, true);
break ;
case 190 : // System.out.println("PseudoToken ::= if LPAREN Expression RPAREN"); //$NON-NLS-1$
consumePseudoTokenIf();
break ;
case 191 : // System.out.println("PseudoToken ::= assert"); //$NON-NLS-1$
consumePseudoToken("assert", 1, true);
break ;
case 192 : // System.out.println("PseudoToken ::= import"); //$NON-NLS-1$
consumePseudoToken("import", 1, true);
break ;
case 193 : // System.out.println("PseudoToken ::= package"); //$NON-NLS-1$
consumePseudoToken("package", 1, true);
break ;
case 194 : // System.out.println("PseudoToken ::= throw"); //$NON-NLS-1$
consumePseudoToken("throw", 1, true);
break ;
case 195 : // System.out.println("PseudoToken ::= new"); //$NON-NLS-1$
consumePseudoToken("new", 1, true);
break ;
case 196 : // System.out.println("PseudoToken ::= do"); //$NON-NLS-1$
consumePseudoToken("do", 1, true);
break ;
case 197 : // System.out.println("PseudoToken ::= for"); //$NON-NLS-1$
consumePseudoToken("for", 1, true);
break ;
case 198 : // System.out.println("PseudoToken ::= switch"); //$NON-NLS-1$
consumePseudoToken("switch", 1, true);
break ;
case 199 : // System.out.println("PseudoToken ::= try"); //$NON-NLS-1$
consumePseudoToken("try", 1, true);
break ;
case 200 : // System.out.println("PseudoToken ::= while"); //$NON-NLS-1$
consumePseudoToken("while", 1, true);
break ;
case 201 : // System.out.println("PseudoToken ::= break"); //$NON-NLS-1$
consumePseudoToken("break", 1, true);
break ;
case 202 : // System.out.println("PseudoToken ::= continue"); //$NON-NLS-1$
consumePseudoToken("continue", 1, true);
break ;
case 203 : // System.out.println("PseudoToken ::= return"); //$NON-NLS-1$
consumePseudoToken("return", 1, true);
break ;
case 204 : // System.out.println("PseudoToken ::= case"); //$NON-NLS-1$
consumePseudoToken("case", 1, true);
break ;
case 205 : // System.out.println("PseudoToken ::= catch"); //$NON-NLS-1$
consumePseudoToken("catch", 0, true);
break ;
case 206 : // System.out.println("PseudoToken ::= instanceof"); //$NON-NLS-1$
consumePseudoToken("instanceof", 0, true);
break ;
case 207 : // System.out.println("PseudoToken ::= else"); //$NON-NLS-1$
consumePseudoToken("else", 0, true);
break ;
case 208 : // System.out.println("PseudoToken ::= extends"); //$NON-NLS-1$
consumePseudoToken("extends", 0, true);
break ;
case 209 : // System.out.println("PseudoToken ::= finally"); //$NON-NLS-1$
consumePseudoToken("finally", 0, true);
break ;
case 210 : // System.out.println("PseudoToken ::= implements"); //$NON-NLS-1$
consumePseudoToken("implements", 0, true);
break ;
case 211 : // System.out.println("PseudoToken ::= throws"); //$NON-NLS-1$
consumePseudoToken("throws", 0, true);
break ;
case 212 : // System.out.println("ClassDeclaration ::= ClassHeader ClassBody"); //$NON-NLS-1$
consumeClassDeclaration();
break ;
case 213 : // System.out.println("ClassHeader ::= ClassHeaderName ClassHeaderExtendsopt..."); //$NON-NLS-1$
consumeClassHeader();
break ;
case 214 : // System.out.println("ClassHeaderName ::= Modifiersopt class JavaIdentifier"); //$NON-NLS-1$
consumeClassHeaderName();
break ;
case 215 : // System.out.println("ClassHeaderExtends ::= extends ClassType"); //$NON-NLS-1$
consumeClassHeaderExtends();
break ;
case 216 : // System.out.println("ClassHeaderImplements ::= implements InterfaceTypeList"); //$NON-NLS-1$
consumeClassHeaderImplements();
break ;
case 218 : // System.out.println("InterfaceTypeList ::= InterfaceTypeList COMMA InterfaceType"); //$NON-NLS-1$
consumeInterfaceTypeList();
break ;
case 219 : // System.out.println("InterfaceType ::= ClassOrInterfaceType"); //$NON-NLS-1$
consumeInterfaceType();
break ;
case 222 : // System.out.println("ClassBodyDeclarations ::= ClassBodyDeclarations ClassBodyDeclaration"); //$NON-NLS-1$
consumeClassBodyDeclarations();
break ;
case 226 : // System.out.println("ClassBodyDeclaration ::= Diet NestedMethod Block"); //$NON-NLS-1$
consumeClassBodyDeclaration();
break ;
case 227 : // System.out.println("Diet ::="); //$NON-NLS-1$
consumeDiet();
break ;
case 228 : // System.out.println("Initializer ::= Diet NestedMethod Block"); //$NON-NLS-1$
consumeClassBodyDeclaration();
break ;
case 235 : // System.out.println("ClassMemberDeclaration ::= SEMICOLON"); //$NON-NLS-1$
consumeEmptyClassMemberDeclaration();
break ;
case 236 : // System.out.println("FieldDeclaration ::= Modifiersopt Type VariableDeclarators SEMICOLON"); //$NON-NLS-1$
consumeFieldDeclaration();
break ;
case 238 : // System.out.println("VariableDeclarators ::= VariableDeclarators COMMA VariableDeclarator"); //$NON-NLS-1$
consumeVariableDeclarators();
break ;
case 241 : // System.out.println("EnterVariable ::="); //$NON-NLS-1$
consumeEnterVariable();
break ;
case 242 : // System.out.println("ExitVariableWithInitialization ::="); //$NON-NLS-1$
consumeExitVariableWithInitialization();
break ;
case 243 : // System.out.println("ExitVariableWithoutInitialization ::="); //$NON-NLS-1$
consumeExitVariableWithoutInitialization();
break ;
case 244 : // System.out.println("ForceNoDiet ::="); //$NON-NLS-1$
consumeForceNoDiet();
break ;
case 245 : // System.out.println("RestoreDiet ::="); //$NON-NLS-1$
consumeRestoreDiet();
break ;
case 250 : // System.out.println("MethodDeclaration ::= MethodHeader MethodBody"); //$NON-NLS-1$
// set to true to consume a method with a body
consumeMethodDeclaration(true);
break ;
case 251 : // System.out.println("AbstractMethodDeclaration ::= MethodHeader SEMICOLON"); //$NON-NLS-1$
// set to false to consume a method without body
consumeMethodDeclaration(false);
break ;
case 252 : // System.out.println("MethodHeader ::= MethodHeaderName MethodHeaderParameters..."); //$NON-NLS-1$
consumeMethodHeader();
break ;
case 253 : // System.out.println("MethodHeaderName ::= Modifiersopt Type JavaIdentifierNoAround LPAREN"); //$NON-NLS-1$
consumeMethodHeaderName();
break ;
case 254 : // System.out.println("MethodHeaderParameters ::= FormalParameterListopt RPAREN"); //$NON-NLS-1$
consumeMethodHeaderParameters();
break ;
case 255 : // System.out.println("MethodHeaderExtendedDims ::= Dimsopt"); //$NON-NLS-1$
consumeMethodHeaderExtendedDims();
break ;
case 256 : // System.out.println("MethodHeaderThrowsClause ::= throws ClassTypeList"); //$NON-NLS-1$
consumeMethodHeaderThrowsClause();
break ;
case 257 : // System.out.println("ConstructorHeader ::= ConstructorHeaderName MethodHeaderParameters"); //$NON-NLS-1$
consumeConstructorHeader();
break ;
case 258 : // System.out.println("ConstructorHeaderName ::= Modifiersopt Identifier LPAREN"); //$NON-NLS-1$
consumeConstructorHeaderName();
break ;
case 259 : // System.out.println("ConstructorHeaderName ::= Modifiersopt aspect LPAREN"); //$NON-NLS-1$
consumeConstructorHeaderName();
break ;
case 261 : // System.out.println("FormalParameterList ::= FormalParameterList COMMA FormalParameter"); //$NON-NLS-1$
consumeFormalParameterList();
break ;
case 262 : // System.out.println("FormalParameter ::= Modifiersopt Type VariableDeclaratorId"); //$NON-NLS-1$
// the boolean is used to know if the modifiers should be reset
consumeFormalParameter();
break ;
case 264 : // System.out.println("ClassTypeList ::= ClassTypeList COMMA ClassTypeElt"); //$NON-NLS-1$
consumeClassTypeList();
break ;
case 265 : // System.out.println("ClassTypeElt ::= ClassType"); //$NON-NLS-1$
consumeClassTypeElt();
break ;
case 266 : // System.out.println("MethodBody ::= NestedMethod LBRACE BlockStatementsopt RBRACE"); //$NON-NLS-1$
consumeMethodBody();
break ;
case 267 : // System.out.println("NestedMethod ::="); //$NON-NLS-1$
consumeNestedMethod();
break ;
case 268 : // System.out.println("StaticInitializer ::= StaticOnly Block"); //$NON-NLS-1$
consumeStaticInitializer();
break ;
case 269 : // System.out.println("StaticOnly ::= static"); //$NON-NLS-1$
consumeStaticOnly();
break ;
case 270 : // System.out.println("ConstructorDeclaration ::= ConstructorHeader MethodBody"); //$NON-NLS-1$
consumeConstructorDeclaration() ;
break ;
case 271 : // System.out.println("ConstructorDeclaration ::= ConstructorHeader SEMICOLON"); //$NON-NLS-1$
consumeInvalidConstructorDeclaration() ;
break ;
case 272 : // System.out.println("ExplicitConstructorInvocation ::= this LPAREN ArgumentListopt RPAREN"); //$NON-NLS-1$
consumeExplicitConstructorInvocation(0,ExplicitConstructorCall.This);
break ;
case 273 : // System.out.println("ExplicitConstructorInvocation ::= super LPAREN ArgumentListopt..."); //$NON-NLS-1$
consumeExplicitConstructorInvocation(0,ExplicitConstructorCall.Super);
break ;
case 274 : // System.out.println("ExplicitConstructorInvocation ::= Primary DOT super LPAREN..."); //$NON-NLS-1$
consumeExplicitConstructorInvocation(1, ExplicitConstructorCall.Super);
break ;
case 275 : // System.out.println("ExplicitConstructorInvocation ::= Name DOT super LPAREN..."); //$NON-NLS-1$
consumeExplicitConstructorInvocation(2, ExplicitConstructorCall.Super);
break ;
case 276 : // System.out.println("ExplicitConstructorInvocation ::= Primary DOT this LPAREN..."); //$NON-NLS-1$
consumeExplicitConstructorInvocation(1, ExplicitConstructorCall.This);
break ;
case 277 : // System.out.println("ExplicitConstructorInvocation ::= Name DOT this LPAREN..."); //$NON-NLS-1$
consumeExplicitConstructorInvocation(2, ExplicitConstructorCall.This);
break ;
case 278 : // System.out.println("InterfaceDeclaration ::= InterfaceHeader InterfaceBody"); //$NON-NLS-1$
consumeInterfaceDeclaration();
break ;
case 279 : // System.out.println("InterfaceHeader ::= InterfaceHeaderName InterfaceHeaderExtendsopt"); //$NON-NLS-1$
consumeInterfaceHeader();
break ;
case 280 : // System.out.println("InterfaceHeaderName ::= Modifiersopt interface JavaIdentifier"); //$NON-NLS-1$
consumeInterfaceHeaderName();
break ;
case 282 : // System.out.println("InterfaceHeaderExtends ::= extends InterfaceTypeList"); //$NON-NLS-1$
consumeInterfaceHeaderExtends();
break ;
case 285 : // System.out.println("InterfaceMemberDeclarations ::= InterfaceMemberDeclarations..."); //$NON-NLS-1$
consumeInterfaceMemberDeclarations();
break ;
case 286 : // System.out.println("InterfaceMemberDeclaration ::= SEMICOLON"); //$NON-NLS-1$
consumeEmptyInterfaceMemberDeclaration();
break ;
case 289 : // System.out.println("InterfaceMemberDeclaration ::= InvalidMethodDeclaration"); //$NON-NLS-1$
ignoreMethodBody();
break ;
case 290 : // System.out.println("InvalidConstructorDeclaration ::= ConstructorHeader MethodBody"); //$NON-NLS-1$
ignoreInvalidConstructorDeclaration(true);
break ;
case 291 : // System.out.println("InvalidConstructorDeclaration ::= ConstructorHeader SEMICOLON"); //$NON-NLS-1$
ignoreInvalidConstructorDeclaration(false);
break ;
case 297 : // System.out.println("ArrayInitializer ::= LBRACE ,opt RBRACE"); //$NON-NLS-1$
consumeEmptyArrayInitializer();
break ;
case 298 : // System.out.println("ArrayInitializer ::= LBRACE VariableInitializers RBRACE"); //$NON-NLS-1$
consumeArrayInitializer();
break ;
case 299 : // System.out.println("ArrayInitializer ::= LBRACE VariableInitializers COMMA RBRACE"); //$NON-NLS-1$
consumeArrayInitializer();
break ;
case 301 : // System.out.println("VariableInitializers ::= VariableInitializers COMMA..."); //$NON-NLS-1$
consumeVariableInitializers();
break ;
case 302 : // System.out.println("Block ::= OpenBlock LBRACE BlockStatementsopt RBRACE"); //$NON-NLS-1$
consumeBlock();
break ;
case 303 : // System.out.println("OpenBlock ::="); //$NON-NLS-1$
consumeOpenBlock() ;
break ;
case 305 : // System.out.println("BlockStatements ::= BlockStatements BlockStatement"); //$NON-NLS-1$
consumeBlockStatements() ;
break ;
case 309 : // System.out.println("BlockStatement ::= InvalidInterfaceDeclaration"); //$NON-NLS-1$
ignoreInterfaceDeclaration();
break ;
case 310 : // System.out.println("LocalVariableDeclarationStatement ::= LocalVariableDeclaration..."); //$NON-NLS-1$
consumeLocalVariableDeclarationStatement();
break ;
case 311 : // System.out.println("LocalVariableDeclaration ::= Type PushModifiers VariableDeclarators"); //$NON-NLS-1$
consumeLocalVariableDeclaration();
break ;
case 312 : // System.out.println("LocalVariableDeclaration ::= Modifiers Type PushModifiers..."); //$NON-NLS-1$
consumeLocalVariableDeclaration();
break ;
case 313 : // System.out.println("PushModifiers ::="); //$NON-NLS-1$
consumePushModifiers();
break ;
case 337 : // System.out.println("EmptyStatement ::= SEMICOLON"); //$NON-NLS-1$
consumeEmptyStatement();
break ;
case 338 : // System.out.println("LabeledStatement ::= JavaIdentifier COLON Statement"); //$NON-NLS-1$
consumeStatementLabel() ;
break ;
case 339 : // System.out.println("LabeledStatementNoShortIf ::= JavaIdentifier COLON..."); //$NON-NLS-1$
consumeStatementLabel() ;
break ;
case 340 : // System.out.println("ExpressionStatement ::= StatementExpression SEMICOLON"); //$NON-NLS-1$
consumeExpressionStatement();
break ;
case 349 : // System.out.println("IfThenStatement ::= if LPAREN Expression RPAREN Statement"); //$NON-NLS-1$
consumeStatementIfNoElse();
break ;
case 350 : // System.out.println("IfThenElseStatement ::= if LPAREN Expression RPAREN..."); //$NON-NLS-1$
consumeStatementIfWithElse();
break ;
case 351 : // System.out.println("IfThenElseStatementNoShortIf ::= if LPAREN Expression RPAREN..."); //$NON-NLS-1$
consumeStatementIfWithElse();
break ;
case 352 : // System.out.println("SwitchStatement ::= switch LPAREN Expression RPAREN OpenBlock..."); //$NON-NLS-1$
consumeStatementSwitch() ;
break ;
case 353 : // System.out.println("SwitchBlock ::= LBRACE RBRACE"); //$NON-NLS-1$
consumeEmptySwitchBlock() ;
break ;
case 356 : // System.out.println("SwitchBlock ::= LBRACE SwitchBlockStatements SwitchLabels RBRACE"); //$NON-NLS-1$
consumeSwitchBlock() ;
break ;
case 358 : // System.out.println("SwitchBlockStatements ::= SwitchBlockStatements SwitchBlockStatement"); //$NON-NLS-1$
consumeSwitchBlockStatements() ;
break ;
case 359 : // System.out.println("SwitchBlockStatement ::= SwitchLabels BlockStatements"); //$NON-NLS-1$
consumeSwitchBlockStatement() ;
break ;
case 361 : // System.out.println("SwitchLabels ::= SwitchLabels SwitchLabel"); //$NON-NLS-1$
consumeSwitchLabels() ;
break ;
case 362 : // System.out.println("SwitchLabel ::= case ConstantExpression COLON"); //$NON-NLS-1$
consumeCaseLabel();
break ;
case 363 : // System.out.println("SwitchLabel ::= default COLON"); //$NON-NLS-1$
consumeDefaultLabel();
break ;
case 364 : // System.out.println("WhileStatement ::= while LPAREN Expression RPAREN Statement"); //$NON-NLS-1$
consumeStatementWhile() ;
break ;
case 365 : // System.out.println("WhileStatementNoShortIf ::= while LPAREN Expression RPAREN..."); //$NON-NLS-1$
consumeStatementWhile() ;
break ;
case 366 : // System.out.println("DoStatement ::= do Statement while LPAREN Expression RPAREN..."); //$NON-NLS-1$
consumeStatementDo() ;
break ;
case 367 : // System.out.println("ForStatement ::= for LPAREN ForInitopt SEMICOLON Expressionopt..."); //$NON-NLS-1$
consumeStatementFor() ;
break ;
case 368 : // System.out.println("ForStatementNoShortIf ::= for LPAREN ForInitopt SEMICOLON..."); //$NON-NLS-1$
consumeStatementFor() ;
break ;
case 369 : // System.out.println("ForInit ::= StatementExpressionList"); //$NON-NLS-1$
consumeForInit() ;
break ;
case 373 : // System.out.println("StatementExpressionList ::= StatementExpressionList COMMA..."); //$NON-NLS-1$
consumeStatementExpressionList() ;
break ;
case 374 : // System.out.println("AssertStatement ::= assert Expression SEMICOLON"); //$NON-NLS-1$
consumeSimpleAssertStatement() ;
break ;
case 375 : // System.out.println("AssertStatement ::= assert Expression COLON Expression SEMICOLON"); //$NON-NLS-1$
consumeAssertStatement() ;
break ;
case 376 : // System.out.println("BreakStatement ::= break SEMICOLON"); //$NON-NLS-1$
consumeStatementBreak() ;
break ;
case 377 : // System.out.println("BreakStatement ::= break Identifier SEMICOLON"); //$NON-NLS-1$
consumeStatementBreakWithLabel() ;
break ;
case 378 : // System.out.println("ContinueStatement ::= continue SEMICOLON"); //$NON-NLS-1$
consumeStatementContinue() ;
break ;
case 379 : // System.out.println("ContinueStatement ::= continue Identifier SEMICOLON"); //$NON-NLS-1$
consumeStatementContinueWithLabel() ;
break ;
case 380 : // System.out.println("ReturnStatement ::= return Expressionopt SEMICOLON"); //$NON-NLS-1$
consumeStatementReturn() ;
break ;
case 381 : // System.out.println("ThrowStatement ::= throw Expression SEMICOLON"); //$NON-NLS-1$
consumeStatementThrow();
break ;
case 382 : // System.out.println("SynchronizedStatement ::= OnlySynchronized LPAREN Expression RPAREN"); //$NON-NLS-1$
consumeStatementSynchronized();
break ;
case 383 : // System.out.println("OnlySynchronized ::= synchronized"); //$NON-NLS-1$
consumeOnlySynchronized();
break ;
case 384 : // System.out.println("TryStatement ::= try TryBlock Catches"); //$NON-NLS-1$
consumeStatementTry(false);
break ;
case 385 : // System.out.println("TryStatement ::= try TryBlock Catchesopt Finally"); //$NON-NLS-1$
consumeStatementTry(true);
break ;
case 387 : // System.out.println("ExitTryBlock ::="); //$NON-NLS-1$
consumeExitTryBlock();
break ;
case 389 : // System.out.println("Catches ::= Catches CatchClause"); //$NON-NLS-1$
consumeCatches();
break ;
case 390 : // System.out.println("CatchClause ::= catch LPAREN FormalParameter RPAREN Block"); //$NON-NLS-1$
consumeStatementCatch() ;
break ;
case 392 : // System.out.println("PushLPAREN ::= LPAREN"); //$NON-NLS-1$
consumeLeftParen();
break ;
case 393 : // System.out.println("PushRPAREN ::= RPAREN"); //$NON-NLS-1$
consumeRightParen();
break ;
case 398 : // System.out.println("PrimaryNoNewArray ::= this"); //$NON-NLS-1$
consumePrimaryNoNewArrayThis();
break ;
case 399 : // System.out.println("PrimaryNoNewArray ::= PushLPAREN Expression PushRPAREN"); //$NON-NLS-1$
consumePrimaryNoNewArray();
break ;
case 402 : // System.out.println("PrimaryNoNewArray ::= Name DOT this"); //$NON-NLS-1$
consumePrimaryNoNewArrayNameThis();
break ;
case 403 : // System.out.println("PrimaryNoNewArray ::= Name DOT super"); //$NON-NLS-1$
consumePrimaryNoNewArrayNameSuper();
break ;
case 404 : // System.out.println("PrimaryNoNewArray ::= Name DOT class"); //$NON-NLS-1$
consumePrimaryNoNewArrayName();
break ;
case 405 : // System.out.println("PrimaryNoNewArray ::= ArrayType DOT class"); //$NON-NLS-1$
consumePrimaryNoNewArrayArrayType();
break ;
case 406 : // System.out.println("PrimaryNoNewArray ::= PrimitiveType DOT class"); //$NON-NLS-1$
consumePrimaryNoNewArrayPrimitiveType();
break ;
case 409 : // System.out.println("AllocationHeader ::= new ClassType LPAREN ArgumentListopt RPAREN"); //$NON-NLS-1$
consumeAllocationHeader();
break ;
case 410 : // System.out.println("ClassInstanceCreationExpression ::= new ClassType LPAREN..."); //$NON-NLS-1$
consumeClassInstanceCreationExpression();
break ;
case 411 : // System.out.println("ClassInstanceCreationExpression ::= Primary DOT new SimpleName..."); //$NON-NLS-1$
consumeClassInstanceCreationExpressionQualified() ;
break ;
case 412 : // System.out.println("ClassInstanceCreationExpression ::=..."); //$NON-NLS-1$
consumeClassInstanceCreationExpressionQualified() ;
break ;
case 413 : // System.out.println("ClassInstanceCreationExpressionName ::= Name DOT"); //$NON-NLS-1$
consumeClassInstanceCreationExpressionName() ;
break ;
case 414 : // System.out.println("ClassBodyopt ::="); //$NON-NLS-1$
consumeClassBodyopt();
break ;
case 416 : // System.out.println("EnterAnonymousClassBody ::="); //$NON-NLS-1$
consumeEnterAnonymousClassBody();
break ;
case 418 : // System.out.println("ArgumentList ::= ArgumentList COMMA Expression"); //$NON-NLS-1$
consumeArgumentList();
break ;
case 419 : // System.out.println("ArrayCreationHeader ::= new PrimitiveType DimWithOrWithOutExprs"); //$NON-NLS-1$
consumeArrayCreationHeader();
break ;
case 420 : // System.out.println("ArrayCreationHeader ::= new ClassOrInterfaceType..."); //$NON-NLS-1$
consumeArrayCreationHeader();
break ;
case 421 : // System.out.println("ArrayCreationWithoutArrayInitializer ::= new PrimitiveType..."); //$NON-NLS-1$
consumeArrayCreationExpressionWithoutInitializer();
break ;
case 422 : // System.out.println("ArrayCreationWithArrayInitializer ::= new PrimitiveType..."); //$NON-NLS-1$
consumeArrayCreationExpressionWithInitializer();
break ;
case 423 : // System.out.println("ArrayCreationWithoutArrayInitializer ::= new ClassOrInterfaceType..."); //$NON-NLS-1$
consumeArrayCreationExpressionWithoutInitializer();
break ;
case 424 : // System.out.println("ArrayCreationWithArrayInitializer ::= new ClassOrInterfaceType..."); //$NON-NLS-1$
consumeArrayCreationExpressionWithInitializer();
break ;
case 426 : // System.out.println("DimWithOrWithOutExprs ::= DimWithOrWithOutExprs DimWithOrWithOutExpr"); //$NON-NLS-1$
consumeDimWithOrWithOutExprs();
break ;
case 428 : // System.out.println("DimWithOrWithOutExpr ::= LBRACKET RBRACKET"); //$NON-NLS-1$
consumeDimWithOrWithOutExpr();
break ;
case 429 : // System.out.println("Dims ::= DimsLoop"); //$NON-NLS-1$
consumeDims();
break ;
case 432 : // System.out.println("OneDimLoop ::= LBRACKET RBRACKET"); //$NON-NLS-1$
consumeOneDimLoop();
break ;
case 433 : // System.out.println("FieldAccess ::= Primary DOT JavaIdentifier"); //$NON-NLS-1$
consumeFieldAccess(false);
break ;
case 434 : // System.out.println("FieldAccess ::= super DOT JavaIdentifier"); //$NON-NLS-1$
consumeFieldAccess(true);
break ;
case 435 : // System.out.println("MethodInvocation ::= NameOrAj LPAREN ArgumentListopt RPAREN"); //$NON-NLS-1$
consumeMethodInvocationName();
break ;
case 436 : // System.out.println("MethodInvocation ::= Primary DOT JavaIdentifier LPAREN..."); //$NON-NLS-1$
consumeMethodInvocationPrimary();
break ;
case 437 : // System.out.println("MethodInvocation ::= super DOT JavaIdentifier LPAREN ArgumentListopt"); //$NON-NLS-1$
consumeMethodInvocationSuper();
break ;
case 438 : // System.out.println("ArrayAccess ::= Name LBRACKET Expression RBRACKET"); //$NON-NLS-1$
consumeArrayAccess(true);
break ;
case 439 : // System.out.println("ArrayAccess ::= PrimaryNoNewArray LBRACKET Expression RBRACKET"); //$NON-NLS-1$
consumeArrayAccess(false);
break ;
case 440 : // System.out.println("ArrayAccess ::= ArrayCreationWithArrayInitializer LBRACKET..."); //$NON-NLS-1$
consumeArrayAccess(false);
break ;
case 442 : // System.out.println("PostfixExpression ::= NameOrAj"); //$NON-NLS-1$
consumePostfixExpression();
break ;
case 445 : // System.out.println("PostIncrementExpression ::= PostfixExpression PLUS_PLUS"); //$NON-NLS-1$
consumeUnaryExpression(OperatorIds.PLUS,true);
break ;
case 446 : // System.out.println("PostDecrementExpression ::= PostfixExpression MINUS_MINUS"); //$NON-NLS-1$
consumeUnaryExpression(OperatorIds.MINUS,true);
break ;
case 447 : // System.out.println("PushPosition ::="); //$NON-NLS-1$
consumePushPosition();
break ;
case 450 : // System.out.println("UnaryExpression ::= PLUS PushPosition UnaryExpression"); //$NON-NLS-1$
consumeUnaryExpression(OperatorIds.PLUS);
break ;
case 451 : // System.out.println("UnaryExpression ::= MINUS PushPosition UnaryExpression"); //$NON-NLS-1$
consumeUnaryExpression(OperatorIds.MINUS);
break ;
case 453 : // System.out.println("PreIncrementExpression ::= PLUS_PLUS PushPosition UnaryExpression"); //$NON-NLS-1$
consumeUnaryExpression(OperatorIds.PLUS,false);
break ;
case 454 : // System.out.println("PreDecrementExpression ::= MINUS_MINUS PushPosition UnaryExpression"); //$NON-NLS-1$
consumeUnaryExpression(OperatorIds.MINUS,false);
break ;
case 456 : // System.out.println("UnaryExpressionNotPlusMinus ::= TWIDDLE PushPosition UnaryExpression"); //$NON-NLS-1$
consumeUnaryExpression(OperatorIds.TWIDDLE);
break ;
case 457 : // System.out.println("UnaryExpressionNotPlusMinus ::= NOT PushPosition UnaryExpression"); //$NON-NLS-1$
consumeUnaryExpression(OperatorIds.NOT);
break ;
case 459 : // System.out.println("CastExpression ::= PushLPAREN PrimitiveType Dimsopt PushRPAREN..."); //$NON-NLS-1$
consumeCastExpression();
break ;
case 460 : // System.out.println("CastExpression ::= PushLPAREN Name Dims PushRPAREN..."); //$NON-NLS-1$
consumeCastExpression();
break ;
case 461 : // System.out.println("CastExpression ::= PushLPAREN Expression PushRPAREN..."); //$NON-NLS-1$
consumeCastExpressionLL1();
break ;
case 462 : // System.out.println("InsideCastExpression ::="); //$NON-NLS-1$
consumeInsideCastExpression();
break ;
case 463 : // System.out.println("InsideCastExpressionLL1 ::="); //$NON-NLS-1$
consumeInsideCastExpressionLL1();
break ;
case 465 : // System.out.println("MultiplicativeExpression ::= MultiplicativeExpression MULTIPLY..."); //$NON-NLS-1$
consumeBinaryExpression(OperatorIds.MULTIPLY);
break ;
case 466 : // System.out.println("MultiplicativeExpression ::= MultiplicativeExpression DIVIDE..."); //$NON-NLS-1$
consumeBinaryExpression(OperatorIds.DIVIDE);
break ;
case 467 : // System.out.println("MultiplicativeExpression ::= MultiplicativeExpression REMAINDER..."); //$NON-NLS-1$
consumeBinaryExpression(OperatorIds.REMAINDER);
break ;
case 469 : // System.out.println("AdditiveExpression ::= AdditiveExpression PLUS..."); //$NON-NLS-1$
consumeBinaryExpression(OperatorIds.PLUS);
break ;
case 470 : // System.out.println("AdditiveExpression ::= AdditiveExpression MINUS..."); //$NON-NLS-1$
consumeBinaryExpression(OperatorIds.MINUS);
break ;
case 472 : // System.out.println("ShiftExpression ::= ShiftExpression LEFT_SHIFT AdditiveExpression"); //$NON-NLS-1$
consumeBinaryExpression(OperatorIds.LEFT_SHIFT);
break ;
case 473 : // System.out.println("ShiftExpression ::= ShiftExpression RIGHT_SHIFT AdditiveExpression"); //$NON-NLS-1$
consumeBinaryExpression(OperatorIds.RIGHT_SHIFT);
break ;
case 474 : // System.out.println("ShiftExpression ::= ShiftExpression UNSIGNED_RIGHT_SHIFT..."); //$NON-NLS-1$
consumeBinaryExpression(OperatorIds.UNSIGNED_RIGHT_SHIFT);
break ;
case 476 : // System.out.println("RelationalExpression ::= RelationalExpression LESS ShiftExpression"); //$NON-NLS-1$
consumeBinaryExpression(OperatorIds.LESS);
break ;
case 477 : // System.out.println("RelationalExpression ::= RelationalExpression GREATER..."); //$NON-NLS-1$
consumeBinaryExpression(OperatorIds.GREATER);
break ;
case 478 : // System.out.println("RelationalExpression ::= RelationalExpression LESS_EQUAL..."); //$NON-NLS-1$
consumeBinaryExpression(OperatorIds.LESS_EQUAL);
break ;
case 479 : // System.out.println("RelationalExpression ::= RelationalExpression GREATER_EQUAL..."); //$NON-NLS-1$
consumeBinaryExpression(OperatorIds.GREATER_EQUAL);
break ;
case 480 : // System.out.println("RelationalExpression ::= RelationalExpression instanceof..."); //$NON-NLS-1$
consumeInstanceOfExpression(OperatorIds.INSTANCEOF);
break ;
case 482 : // System.out.println("EqualityExpression ::= EqualityExpression EQUAL_EQUAL..."); //$NON-NLS-1$
consumeEqualityExpression(OperatorIds.EQUAL_EQUAL);
break ;
case 483 : // System.out.println("EqualityExpression ::= EqualityExpression NOT_EQUAL..."); //$NON-NLS-1$
consumeEqualityExpression(OperatorIds.NOT_EQUAL);
break ;
case 485 : // System.out.println("AndExpression ::= AndExpression AND EqualityExpression"); //$NON-NLS-1$
consumeBinaryExpression(OperatorIds.AND);
break ;
case 487 : // System.out.println("ExclusiveOrExpression ::= ExclusiveOrExpression XOR AndExpression"); //$NON-NLS-1$
consumeBinaryExpression(OperatorIds.XOR);
break ;
case 489 : // System.out.println("InclusiveOrExpression ::= InclusiveOrExpression OR..."); //$NON-NLS-1$
consumeBinaryExpression(OperatorIds.OR);
break ;
case 491 : // System.out.println("ConditionalAndExpression ::= ConditionalAndExpression AND_AND..."); //$NON-NLS-1$
consumeBinaryExpression(OperatorIds.AND_AND);
break ;
case 493 : // System.out.println("ConditionalOrExpression ::= ConditionalOrExpression OR_OR..."); //$NON-NLS-1$
consumeBinaryExpression(OperatorIds.OR_OR);
break ;
case 495 : // System.out.println("ConditionalExpression ::= ConditionalOrExpression QUESTION..."); //$NON-NLS-1$
consumeConditionalExpression(OperatorIds.QUESTIONCOLON) ;
break ;
case 498 : // System.out.println("Assignment ::= PostfixExpression AssignmentOperator..."); //$NON-NLS-1$
consumeAssignment();
break ;
case 500 : // System.out.println("Assignment ::= InvalidArrayInitializerAssignement"); //$NON-NLS-1$
ignoreExpressionAssignment();
break ;
case 501 : // System.out.println("AssignmentOperator ::= EQUAL"); //$NON-NLS-1$
consumeAssignmentOperator(EQUAL);
break ;
case 502 : // System.out.println("AssignmentOperator ::= MULTIPLY_EQUAL"); //$NON-NLS-1$
consumeAssignmentOperator(MULTIPLY);
break ;
case 503 : // System.out.println("AssignmentOperator ::= DIVIDE_EQUAL"); //$NON-NLS-1$
consumeAssignmentOperator(DIVIDE);
break ;
case 504 : // System.out.println("AssignmentOperator ::= REMAINDER_EQUAL"); //$NON-NLS-1$
consumeAssignmentOperator(REMAINDER);
break ;
case 505 : // System.out.println("AssignmentOperator ::= PLUS_EQUAL"); //$NON-NLS-1$
consumeAssignmentOperator(PLUS);
break ;
case 506 : // System.out.println("AssignmentOperator ::= MINUS_EQUAL"); //$NON-NLS-1$
consumeAssignmentOperator(MINUS);
break ;
case 507 : // System.out.println("AssignmentOperator ::= LEFT_SHIFT_EQUAL"); //$NON-NLS-1$
consumeAssignmentOperator(LEFT_SHIFT);
break ;
case 508 : // System.out.println("AssignmentOperator ::= RIGHT_SHIFT_EQUAL"); //$NON-NLS-1$
consumeAssignmentOperator(RIGHT_SHIFT);
break ;
case 509 : // System.out.println("AssignmentOperator ::= UNSIGNED_RIGHT_SHIFT_EQUAL"); //$NON-NLS-1$
consumeAssignmentOperator(UNSIGNED_RIGHT_SHIFT);
break ;
case 510 : // System.out.println("AssignmentOperator ::= AND_EQUAL"); //$NON-NLS-1$
consumeAssignmentOperator(AND);
break ;
case 511 : // System.out.println("AssignmentOperator ::= XOR_EQUAL"); //$NON-NLS-1$
consumeAssignmentOperator(XOR);
break ;
case 512 : // System.out.println("AssignmentOperator ::= OR_EQUAL"); //$NON-NLS-1$
consumeAssignmentOperator(OR);
break ;
case 519 : // System.out.println("Expressionopt ::="); //$NON-NLS-1$
consumeEmptyExpression();
break ;
case 523 : // System.out.println("ImportDeclarationsopt ::="); //$NON-NLS-1$
consumeEmptyImportDeclarationsopt();
break ;
case 524 : // System.out.println("ImportDeclarationsopt ::= ImportDeclarations"); //$NON-NLS-1$
consumeImportDeclarationsopt();
break ;
case 525 : // System.out.println("TypeDeclarationsopt ::="); //$NON-NLS-1$
consumeEmptyTypeDeclarationsopt();
break ;
case 526 : // System.out.println("TypeDeclarationsopt ::= TypeDeclarations"); //$NON-NLS-1$
consumeTypeDeclarationsopt();
break ;
case 527 : // System.out.println("ClassBodyDeclarationsopt ::="); //$NON-NLS-1$
consumeEmptyClassBodyDeclarationsopt();
break ;
case 528 : // System.out.println("ClassBodyDeclarationsopt ::= NestedType ClassBodyDeclarations"); //$NON-NLS-1$
consumeClassBodyDeclarationsopt();
break ;
case 529 : // System.out.println("Modifiersopt ::="); //$NON-NLS-1$
consumeDefaultModifiers();
break ;
case 530 : // System.out.println("Modifiersopt ::= Modifiers"); //$NON-NLS-1$
consumeModifiers();
break ;
case 531 : // System.out.println("BlockStatementsopt ::="); //$NON-NLS-1$
consumeEmptyBlockStatementsopt();
break ;
case 533 : // System.out.println("Dimsopt ::="); //$NON-NLS-1$
consumeEmptyDimsopt();
break ;
case 535 : // System.out.println("ArgumentListopt ::="); //$NON-NLS-1$
consumeEmptyArgumentListopt();
break ;
case 539 : // System.out.println("FormalParameterListopt ::="); //$NON-NLS-1$
consumeFormalParameterListopt();
break ;
case 543 : // System.out.println("InterfaceMemberDeclarationsopt ::="); //$NON-NLS-1$
consumeEmptyInterfaceMemberDeclarationsopt();
break ;
case 544 : // System.out.println("InterfaceMemberDeclarationsopt ::= NestedType..."); //$NON-NLS-1$
consumeInterfaceMemberDeclarationsopt();
break ;
case 545 : // System.out.println("NestedType ::="); //$NON-NLS-1$
consumeNestedType();
break ;
case 546 : // System.out.println("ForInitopt ::="); //$NON-NLS-1$
consumeEmptyForInitopt();
break ;
case 548 : // System.out.println("ForUpdateopt ::="); //$NON-NLS-1$
consumeEmptyForUpdateopt();
break ;
case 552 : // System.out.println("Catchesopt ::="); //$NON-NLS-1$
consumeEmptyCatchesopt();
break ;
}
}
protected void consumeSimpleAssertStatement() {
super.consumeSimpleAssertStatement();
}
public AjParser(
ProblemReporter problemReporter,
boolean optimizeStringLiterals) {
super(problemReporter, optimizeStringLiterals);
}
// don't try to recover if we're parsing AspectJ constructs
protected boolean shouldTryToRecover() {
int index = 0;
ASTNode node;
while (index < astStack.length && (node = astStack[index++]) != null) {
if (node instanceof AspectDeclaration ||
node instanceof PointcutDeclaration ||
node instanceof AdviceDeclaration) {
return false;
}
}
return true;
}
}
|
46,280
|
Bug 46280 compiler issues error on inner aspects when privilieged
|
The compiler complains that "inner aspects must be static" whenever I try to qualify an inner (and static) aspect as privileged, no matter what the enclosing type is (aspect, interface or class). I was using j2sdk1.4.0_02, AspectJ 1.1, eclipse 2.1 (with AJDT 1.1.3). Test case: ------------------ BASE CLASS: public class Capsule { private int hidden; public int visible; public Capsule(int priv, int pub) { hidden = priv; visible = pub; } public void doSomething() { System.out.println(""" + hidden + ", " + visible + """); } public static void main(String[] args) { Capsule capsule = new Capsule(1, 1); capsule.doSomething(); } } ------------------ ASPECT: public aspect Outer { static //privileged <== JUST TRY TO UNCOMMENT THIS! aspect Inner { pointcut call2doSomething(Capsule capsule): call(void Capsule.doSomething()) && target(capsule); before(Capsule capsule): call2doSomething(capsule) { capsule.visible++; //capsule.hidden++; } } } ------------------ INTERFACE: public interface Marker { static //privileged <== JUST TRY TO UNCOMMENT THIS! aspect Inner { pointcut call2doSomething(Capsule capsule): call(void Capsule.doSomething()) && target(capsule); before(Capsule capsule): call2doSomething(capsule) { capsule.visible++; //capsule.hidden++; } } }
|
resolved fixed
|
7bbd1f4
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-14T11:28:13Z
| 2003-11-07T15:46:40Z
|
tests/bugs/PrivilegedParsing.java
| |
44,587
|
Bug 44587 Erroneous exception conversion
| null |
resolved fixed
|
5834de9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-14T15:24:06Z
| 2003-10-09T17:20: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.lookup.ClassScope;
public class AspectClinit extends Clinit {
private boolean hasPre, hasPost;
public AspectClinit(Clinit old, CompilationResult compilationResult, boolean hasPre, boolean hasPost) {
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;
}
protected void generateSyntheticCode(
ClassScope classScope,
CodeStream codeStream)
{
if (hasPre) {
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(classScope);
codeStream.invokestatic(world.makeMethodBindingForCall(
AjcMemberMaker.ajcPreClinitMethod(
world.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(
world.fromBinding(classScope.referenceContext.binding)
)));
}
}
}
|
44,587
|
Bug 44587 Erroneous exception conversion
| null |
resolved fixed
|
5834de9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-14T15:24:06Z
| 2003-10-09T17:20: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.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
// 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.buildManager.buildConfig.isXserializableAspects()) {
if (world.getWorld().resolve(TypeX.SERIALIZABLE).isAssignableFrom(myType)) {
scope.problemReporter().signalError(sourceStart, sourceEnd,
"aspects may not implement Serializable");
ignoreFurtherInvestigation = true;
return;
}
if (world.getWorld().resolve(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;
}
}
}
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()) {
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);
} else if (perClause.getKind() == PerClause.PERCFLOW) {
binding.addField(
factory.makeFieldBinding(
AjcMemberMaker.perCflowField(
typeX)));
methods[0] = new AspectClinit((Clinit)methods[0], compilationResult, true, false);
} 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) {
EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
classFile.generateMethodInfoHeader(methodBinding);
int methodAttributeOffset = classFile.contentsOffset;
int attributeNumber = classFile.generateMethodInfoAttribute(methodBinding, AstUtil.getAjSyntheticAttribute());
int codeAttributeOffset = classFile.contentsOffset;
classFile.generateCodeAttributeHeader();
CodeStream codeStream = classFile.codeStream;
codeStream.init(classFile);
codeStream.initializeMaxLocals(methodBinding);
// 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(
world.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(
world.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(world.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) {
// 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.new_(world.makeTypeBinding(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION));
codeStream.dup();
codeStream.invokespecial(world.makeMethodBindingForCall(
AjcMemberMaker.noAspectBoundExceptionInit()
));
codeStream.athrow();
// 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(
world.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,
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,
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,
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
}
}
|
44,587
|
Bug 44587 Erroneous exception conversion
| null |
resolved fixed
|
5834de9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-14T15:24:06Z
| 2003-10-09T17:20:00Z
|
runtime/src/org/aspectj/lang/NoAspectBoundException.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.lang;
/** Thrown by the <code>aspectOf(..)</code> special method on aspect types
* when there is no aspect of that type currently bound.
*/
public class NoAspectBoundException extends RuntimeException {
}
|
44,587
|
Bug 44587 Erroneous exception conversion
| null |
resolved fixed
|
5834de9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-14T15:24:06Z
| 2003-10-09T17:20:00Z
|
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 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)
return suite;
}
public RuntimeModuleTests(String name) { super(name); }
public void testNothing() {}
}
|
44,587
|
Bug 44587 Erroneous exception conversion
| null |
resolved fixed
|
5834de9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-14T15:24:06Z
| 2003-10-09T17:20:00Z
|
tests/bugs/ErroneousExceptionConversion.java
| |
44,587
|
Bug 44587 Erroneous exception conversion
| null |
resolved fixed
|
5834de9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-14T15:24:06Z
| 2003-10-09T17:20:00Z
|
tests/bugs/ErroneousExceptionConversion1.java
| |
44,587
|
Bug 44587 Erroneous exception conversion
| null |
resolved fixed
|
5834de9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-14T15:24:06Z
| 2003-10-09T17:20:00Z
|
tests/new/ConstructorExecInitFails.java
|
import org.aspectj.testing.*;
/**
* -usejavac mode: no error
* not -usejavac mode: VerifyError
*/
public class ConstructorExecInitFails {
public static void main(String[] args) {
try {
new ConstructorExecInitFails();
} catch (ExceptionInInitializerError e) {
return;
}
Tester.checkFailed("shouldn't be able to run");
}
}
/** @testcase after returning from initialization and after executing constructor */
aspect A {
after (Object target) : execution(*.new(..)) && target(target) {
Tester.checkFailed("shouldn't be able to run");
}
after () returning (Object target) : initialization(new(..)) {
Tester.checkFailed("shouldn't be able to run");
}
}
|
44,587
|
Bug 44587 Erroneous exception conversion
| null |
resolved fixed
|
5834de9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-14T15:24:06Z
| 2003-10-09T17:20:00Z
|
weaver/src/org/aspectj/weaver/AjcMemberMaker.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;
public class AjcMemberMaker {
private static final int PUBLIC_STATIC_FINAL =
Modifier.PUBLIC | Modifier.STATIC | Modifier.FINAL;
private static final int PRIVATE_STATIC =
Modifier.PRIVATE | Modifier.STATIC;
private static final int PUBLIC_STATIC =
Modifier.PUBLIC | Modifier.STATIC;
private static final int VISIBILITY =
Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED;
public static final TypeX CFLOW_STACK_TYPE =
TypeX.forName(NameMangler.CFLOW_STACK_TYPE);
public static final TypeX AROUND_CLOSURE_TYPE =
TypeX.forName("org.aspectj.runtime.internal.AroundClosure");
public static final TypeX CONVERSIONS_TYPE =
TypeX.forName("org.aspectj.runtime.internal.Conversions");
public static final TypeX NO_ASPECT_BOUND_EXCEPTION =
TypeX.forName("org.aspectj.lang.NoAspectBoundException");
public static ResolvedMember ajcPreClinitMethod(TypeX declaringType) {
return new ResolvedMember(
Member.METHOD,
declaringType,
PRIVATE_STATIC,
NameMangler.AJC_PRE_CLINIT_NAME,
"()V");
}
public static ResolvedMember ajcPostClinitMethod(TypeX declaringType) {
return new ResolvedMember(
Member.METHOD,
declaringType,
PRIVATE_STATIC,
NameMangler.AJC_POST_CLINIT_NAME,
"()V");
}
public static Member noAspectBoundExceptionInit() {
return new ResolvedMember(
Member.METHOD,
NO_ASPECT_BOUND_EXCEPTION,
Modifier.PUBLIC,
"<init>",
"()V");
}
public static ResolvedMember perCflowPush(TypeX declaringType) {
return new ResolvedMember(
Member.METHOD,
declaringType,
PUBLIC_STATIC,
NameMangler.PERCFLOW_PUSH_METHOD,
"()V");
}
public static ResolvedMember perCflowField(TypeX declaringType) {
return new ResolvedMember(
Member.FIELD,
declaringType,
PUBLIC_STATIC_FINAL,
NameMangler.PERCFLOW_FIELD_NAME,
CFLOW_STACK_TYPE.getSignature());
}
public static ResolvedMember perSingletonField(TypeX declaringType) {
return new ResolvedMember(
Member.FIELD,
declaringType,
PUBLIC_STATIC_FINAL,
NameMangler.PERSINGLETON_FIELD_NAME,
declaringType.getSignature());
}
public static ResolvedMember perObjectField(TypeX declaringType, ResolvedTypeX aspectType) {
int modifiers = Modifier.PRIVATE;
if (!TypeX.SERIALIZABLE.isAssignableFrom(aspectType, aspectType.getWorld())) {
modifiers |= Modifier.TRANSIENT;
}
return new ResolvedMember(
Member.FIELD,
declaringType,
modifiers,
aspectType,
NameMangler.perObjectInterfaceField(aspectType),
TypeX.NONE);
}
public static ResolvedMember perObjectBind(TypeX declaringType) {
return new ResolvedMember(
Member.METHOD,
declaringType,
PUBLIC_STATIC,
NameMangler.PEROBJECT_BIND_METHOD,
"(Ljava/lang/Object;)V");
}
public static TypeX perObjectInterfaceType(TypeX aspectType) {
return TypeX.forName(aspectType.getName()+"$ajcMightHaveAspect");
}
public static ResolvedMember perObjectInterfaceGet(TypeX aspectType) {
return new ResolvedMember(
Member.METHOD,
perObjectInterfaceType(aspectType),
Modifier.PUBLIC | Modifier.ABSTRACT,
NameMangler.perObjectInterfaceGet(aspectType),
"()" + aspectType.getSignature());
}
public static ResolvedMember perObjectInterfaceSet(TypeX aspectType) {
return new ResolvedMember(
Member.METHOD,
perObjectInterfaceType(aspectType),
Modifier.PUBLIC | Modifier.ABSTRACT,
NameMangler.perObjectInterfaceSet(aspectType),
"(" + aspectType.getSignature() + ")V");
}
public static ResolvedMember perSingletonAspectOfMethod(TypeX declaringType) {
return new ResolvedMember(Member.METHOD,
declaringType, PUBLIC_STATIC, "aspectOf",
"()" + declaringType.getSignature());
}
public static ResolvedMember perSingletonHasAspectMethod(TypeX declaringType) {
return new ResolvedMember(Member.METHOD,
declaringType, PUBLIC_STATIC, "hasAspect",
"()Z");
};
public static ResolvedMember perCflowAspectOfMethod(TypeX declaringType) {
return perSingletonAspectOfMethod(declaringType);
}
public static ResolvedMember perCflowHasAspectMethod(TypeX declaringType) {
return perSingletonHasAspectMethod(declaringType);
};
public static ResolvedMember perObjectAspectOfMethod(TypeX declaringType) {
return new ResolvedMember(Member.METHOD,
declaringType, PUBLIC_STATIC, "aspectOf",
"(Ljava/lang/Object;)" + declaringType.getSignature());
}
public static ResolvedMember perObjectHasAspectMethod(TypeX declaringType) {
return new ResolvedMember(Member.METHOD,
declaringType, PUBLIC_STATIC, "hasAspect",
"(Ljava/lang/Object;)Z");
};
// -- privileged accessors
public static ResolvedMember privilegedAccessMethodForMethod(TypeX aspectType, ResolvedMember method) {
String sig;
sig = method.getSignature();
return new ResolvedMember(Member.METHOD,
method.getDeclaringType(),
Modifier.PUBLIC | (method.isStatic() ? Modifier.STATIC : 0),
NameMangler.privilegedAccessMethodForMethod(method.getName(),
method.getDeclaringType(), aspectType),
sig);
//XXX needs thrown exceptions to be correct
}
public static ResolvedMember privilegedAccessMethodForFieldGet(TypeX aspectType, Member field) {
String sig;
if (field.isStatic()) {
sig = "()" + field.getReturnType().getSignature();
} else {
sig = "(" + field.getDeclaringType().getSignature() + ")" + field.getReturnType().getSignature();
}
return new ResolvedMember(Member.METHOD,
field.getDeclaringType(),
PUBLIC_STATIC, //Modifier.PUBLIC | (field.isStatic() ? Modifier.STATIC : 0),
NameMangler.privilegedAccessMethodForFieldGet(field.getName(),
field.getDeclaringType(), aspectType),
sig);
}
public static ResolvedMember privilegedAccessMethodForFieldSet(TypeX aspectType, Member field) {
String sig;
if (field.isStatic()) {
sig = "(" + field.getReturnType().getSignature() + ")V";
} else {
sig = "(" + field.getDeclaringType().getSignature() + field.getReturnType().getSignature() + ")V";
}
return new ResolvedMember(Member.METHOD,
field.getDeclaringType(),
PUBLIC_STATIC, //Modifier.PUBLIC | (field.isStatic() ? Modifier.STATIC : 0),
NameMangler.privilegedAccessMethodForFieldSet(field.getName(),
field.getDeclaringType(), aspectType),
sig);
}
// --- inline accessors
//??? can eclipse handle a transform this weird without putting synthetics into the mix
public static ResolvedMember superAccessMethod(TypeX baseType, ResolvedMember method) {
return new ResolvedMember(Member.METHOD,
baseType,
Modifier.PUBLIC,
method.getReturnType(),
NameMangler.superDispatchMethod(baseType, method.getName()),
method.getParameterTypes(),
method.getExceptions());
}
public static ResolvedMember inlineAccessMethodForMethod(TypeX aspectType, ResolvedMember method) {
TypeX[] paramTypes = method.getParameterTypes();
if (!method.isStatic()) {
paramTypes = TypeX.insert(method.getDeclaringType(), paramTypes);
}
return new ResolvedMember(Member.METHOD,
aspectType,
PUBLIC_STATIC, //??? what about privileged and super access
//???Modifier.PUBLIC | (method.isStatic() ? Modifier.STATIC : 0),
method.getReturnType(),
NameMangler.inlineAccessMethodForMethod(method.getName(),
method.getDeclaringType(), aspectType),
paramTypes, method.getExceptions());
}
public static ResolvedMember inlineAccessMethodForFieldGet(TypeX aspectType, Member field) {
String sig;
if (field.isStatic()) {
sig = "()" + field.getReturnType().getSignature();
} else {
sig = "(" + field.getDeclaringType().getSignature() + ")" + field.getReturnType().getSignature();
}
return new ResolvedMember(Member.METHOD,
aspectType,
PUBLIC_STATIC, //Modifier.PUBLIC | (field.isStatic() ? Modifier.STATIC : 0),
NameMangler.inlineAccessMethodForFieldGet(field.getName(),
field.getDeclaringType(), aspectType),
sig);
}
public static ResolvedMember inlineAccessMethodForFieldSet(TypeX aspectType, Member field) {
String sig;
if (field.isStatic()) {
sig = "(" + field.getReturnType().getSignature() + ")V";
} else {
sig = "(" + field.getDeclaringType().getSignature() + field.getReturnType().getSignature() + ")V";
}
return new ResolvedMember(Member.METHOD,
aspectType,
PUBLIC_STATIC, //Modifier.PUBLIC | (field.isStatic() ? Modifier.STATIC : 0),
NameMangler.inlineAccessMethodForFieldSet(field.getName(),
field.getDeclaringType(), aspectType),
sig);
}
// --- runtimeLibrary api stuff
public static Member cflowStackPeekInstance() {
return new Member(
Member.METHOD,
CFLOW_STACK_TYPE,
0,
"peekInstance",
"()Ljava/lang/Object;");
}
public static Member cflowStackPushInstance() {
return new Member(
Member.METHOD,
CFLOW_STACK_TYPE,
0,
"pushInstance",
"(Ljava/lang/Object;)V");
}
public static Member cflowStackIsValid() {
return new Member(
Member.METHOD,
CFLOW_STACK_TYPE,
0,
"isValid",
"()Z");
}
public static Member cflowStackInit() {
return new Member(
Member.CONSTRUCTOR,
CFLOW_STACK_TYPE,
0,
"<init>",
"()V");
}
public static Member aroundClosurePreInitializationField() {
return new Member(
Member.FIELD,
AROUND_CLOSURE_TYPE,
0,
"preInitializationState",
"[Ljava/lang/Object;");
}
public static Member aroundClosurePreInitializationGetter() {
return new Member(
Member.METHOD,
AROUND_CLOSURE_TYPE,
0,
"getPreInitializationState",
"()[Ljava/lang/Object;");
}
public static ResolvedMember preIntroducedConstructor(
TypeX aspectType,
TypeX targetType,
TypeX[] paramTypes)
{
return new ResolvedMember(
Member.METHOD,
aspectType,
PUBLIC_STATIC_FINAL,
TypeX.OBJECTARRAY,
NameMangler.preIntroducedConstructor(aspectType, targetType),
paramTypes);
}
public static ResolvedMember postIntroducedConstructor(
TypeX aspectType,
TypeX targetType,
TypeX[] paramTypes)
{
return new ResolvedMember(
Member.METHOD,
aspectType,
PUBLIC_STATIC_FINAL,
ResolvedTypeX.VOID,
NameMangler.postIntroducedConstructor(aspectType, targetType),
TypeX.insert(targetType, paramTypes));
}
public static ResolvedMember interConstructor(ResolvedTypeX targetType, ResolvedMember constructor, TypeX aspectType) {
//
// ResolvedTypeX targetType,
// TypeX[] argTypes,
// int modifiers)
// {
ResolvedMember ret =
new ResolvedMember(
Member.CONSTRUCTOR,
targetType,
Modifier.PUBLIC,
ResolvedTypeX.VOID,
"<init>",
constructor.getParameterTypes(),
constructor.getExceptions());
//System.out.println("ret: " + ret + " mods: " + Modifier.toString(modifiers));
if (Modifier.isPublic(constructor.getModifiers()))
return ret;
while (true) {
ret = addCookieTo(ret, aspectType);
if (targetType.lookupMemberNoSupers(ret) == null)
return ret;
}
}
public static ResolvedMember interFieldInitializer(ResolvedMember field, TypeX aspectType) {
return new ResolvedMember(Member.METHOD, aspectType, PUBLIC_STATIC,
NameMangler.interFieldInitializer(aspectType, field.getDeclaringType(), field.getName()),
field.isStatic() ? "()V" : "(" + field.getDeclaringType().getSignature() + ")V"
);
}
/**
* Makes public and non-final
*/
private static int makePublicNonFinal(int modifiers) {
return (modifiers & ~VISIBILITY & ~Modifier.FINAL) | Modifier.PUBLIC;
}
/**
* This static method goes on the aspect that declares the inter-type field
*/
public static ResolvedMember interFieldSetDispatcher(ResolvedMember field, TypeX aspectType) {
return new ResolvedMember(Member.METHOD, aspectType, PUBLIC_STATIC,
ResolvedTypeX.VOID,
NameMangler.interFieldSetDispatcher(aspectType, field.getDeclaringType(), field.getName()),
field.isStatic() ? new TypeX[] {field.getReturnType()}
: new TypeX[] {field.getDeclaringType(), field.getReturnType()}
);
}
/**
* This static method goes on the aspect that declares the inter-type field
*/
public static ResolvedMember interFieldGetDispatcher(ResolvedMember field, TypeX aspectType) {
return new ResolvedMember(Member.METHOD, aspectType, PUBLIC_STATIC,
field.getReturnType(),
NameMangler.interFieldGetDispatcher(aspectType, field.getDeclaringType(), field.getName()),
field.isStatic() ? TypeX.NONE : new TypeX[] {field.getDeclaringType()},
TypeX.NONE
);
}
// private static int makeFieldModifiers(int declaredModifiers) {
// int ret = Modifier.PUBLIC;
// if (Modifier.isTransient(declaredModifiers)) ret |= Modifier.TRANSIENT;
// if (Modifier.isVolatile(declaredModifiers)) ret |= Modifier.VOLATILE;
// return ret;
// }
/**
* This field goes on the class the field
* is declared onto
*/
public static ResolvedMember interFieldClassField(ResolvedMember field, TypeX aspectType) {
return new ResolvedMember(Member.FIELD, field.getDeclaringType(),
makePublicNonFinal(field.getModifiers()),
field.getReturnType(),
NameMangler.interFieldClassField(field.getModifiers(), aspectType, field.getDeclaringType(), field.getName()),
TypeX.NONE, TypeX.NONE
);
}
/**
* This field goes on top-most implementers of the interface the field
* is declared onto
*/
public static ResolvedMember interFieldInterfaceField(ResolvedMember field, TypeX onClass, TypeX aspectType) {
return new ResolvedMember(Member.FIELD, onClass, makePublicNonFinal(field.getModifiers()),
field.getReturnType(),
NameMangler.interFieldInterfaceField(aspectType, field.getDeclaringType(), field.getName()),
TypeX.NONE, TypeX.NONE
);
}
/**
* This instance method goes on the interface the field is declared onto
* as well as its top-most implementors
*/
public static ResolvedMember interFieldInterfaceSetter(ResolvedMember field, ResolvedTypeX onType, TypeX aspectType) {
int modifiers = Modifier.PUBLIC;
if (onType.isInterface()) modifiers |= Modifier.ABSTRACT;
return new ResolvedMember(Member.METHOD, onType, modifiers,
ResolvedTypeX.VOID,
NameMangler.interFieldInterfaceSetter(aspectType, field.getDeclaringType(), field.getName()),
new TypeX[] {field.getReturnType()}, TypeX.NONE
);
}
/**
* This instance method goes on the interface the field is declared onto
* as well as its top-most implementors
*/
public static ResolvedMember interFieldInterfaceGetter(ResolvedMember field, ResolvedTypeX onType, TypeX aspectType) {
int modifiers = Modifier.PUBLIC;
if (onType.isInterface()) modifiers |= Modifier.ABSTRACT;
return new ResolvedMember(Member.METHOD, onType, modifiers,
field.getReturnType(),
NameMangler.interFieldInterfaceGetter(aspectType, field.getDeclaringType(), field.getName()),
TypeX.NONE, TypeX.NONE
);
}
/**
* This method goes on the target type of the inter-type method. (and possibly the topmost-implemeters,
* if the target type is an interface)
*/
public static ResolvedMember interMethod(ResolvedMember meth, TypeX aspectType, boolean onInterface)
{
if (Modifier.isPublic(meth.getModifiers()) && !onInterface) return meth;
int modifiers = makePublicNonFinal(meth.getModifiers());
if (onInterface) modifiers |= Modifier.ABSTRACT;
return new ResolvedMember(Member.METHOD, meth.getDeclaringType(),
modifiers,
meth.getReturnType(),
NameMangler.interMethod(meth.getModifiers(), aspectType, meth.getDeclaringType(), meth.getName()),
meth.getParameterTypes(), meth.getExceptions());
}
/**
* This static method goes on the declaring aspect of the inter-type method.
*/
public static ResolvedMember interMethodDispatcher(ResolvedMember meth, TypeX aspectType)
{
TypeX[] paramTypes = meth.getParameterTypes();
if (!meth.isStatic()) {
paramTypes = TypeX.insert(meth.getDeclaringType(), paramTypes);
}
return new ResolvedMember(Member.METHOD, aspectType, PUBLIC_STATIC,
meth.getReturnType(),
NameMangler.interMethodDispatcher(aspectType, meth.getDeclaringType(), meth.getName()),
paramTypes, meth.getExceptions());
}
/**
* This static method goes on the declaring aspect of the inter-type method.
*/
public static ResolvedMember interMethodBody(ResolvedMember meth, TypeX aspectType)
{
TypeX[] paramTypes = meth.getParameterTypes();
if (!meth.isStatic()) {
paramTypes = TypeX.insert(meth.getDeclaringType(), paramTypes);
}
int modifiers = PUBLIC_STATIC;
if (Modifier.isStrict(meth.getModifiers())) {
modifiers |= Modifier.STRICT;
}
return new ResolvedMember(Member.METHOD, aspectType, modifiers,
meth.getReturnType(),
NameMangler.interMethodBody(aspectType, meth.getDeclaringType(), meth.getName()),
paramTypes, meth.getExceptions());
}
private static ResolvedMember addCookieTo(ResolvedMember ret, TypeX aspectType) {
TypeX[] params = ret.getParameterTypes();
TypeX[] freshParams = TypeX.add(params, aspectType);
return new ResolvedMember(
ret.getKind(),
ret.getDeclaringType(),
ret.getModifiers(),
ret.getReturnType(),
ret.getName(),
freshParams, ret.getExceptions());
}
public static ResolvedMember toObjectConversionMethod(TypeX fromType) {
if (fromType.isPrimitive()) {
String name = fromType.toString() + "Object";
return new ResolvedMember(
Member.METHOD,
CONVERSIONS_TYPE,
PUBLIC_STATIC,
TypeX.OBJECT,
name,
new TypeX[] { fromType }, TypeX.NONE);
} else {
return null;
}
}
public static Member interfaceConstructor(ResolvedTypeX resolvedTypeX) {
return new ResolvedMember(
Member.CONSTRUCTOR,
resolvedTypeX,
Modifier.PUBLIC,
"<init>",
"()V");
}
}
|
44,587
|
Bug 44587 Erroneous exception conversion
| null |
resolved fixed
|
5834de9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-14T15:24:06Z
| 2003-10-09T17:20:00Z
|
weaver/src/org/aspectj/weaver/NameMangler.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 org.aspectj.weaver.bcel.LazyClassGen;
public class NameMangler {
private NameMangler() {
throw new RuntimeException("static");
}
public static final String PREFIX = "ajc$";
public static final String CFLOW_STACK_TYPE = "org.aspectj.runtime.internal.CFlowStack";
public static final String SOFT_EXCEPTION_TYPE = "org.aspectj.lang.SoftException";
public static final String PERSINGLETON_FIELD_NAME = PREFIX + "perSingletonInstance";
public static final String PERCFLOW_FIELD_NAME = PREFIX + "perCflowStack";
//public static final String PERTHIS_FIELD_NAME = PREFIX + "perSingletonInstance";
// -----
public static final String PERCFLOW_PUSH_METHOD = PREFIX + "perCflowPush";
public static final String PEROBJECT_BIND_METHOD = PREFIX + "perObjectBind";
public static final String AJC_PRE_CLINIT_NAME = PREFIX + "preClinit";
public static final String AJC_POST_CLINIT_NAME = PREFIX + "postClinit";
public static String perObjectInterfaceGet(TypeX aspectType) {
return makeName(aspectType.getNameAsIdentifier(), "perObjectGet");
}
public static String perObjectInterfaceSet(TypeX aspectType) {
return makeName(aspectType.getNameAsIdentifier(), "perObjectSet");
}
public static String perObjectInterfaceField(TypeX aspectType) {
return makeName(aspectType.getNameAsIdentifier(), "perObjectField");
}
public static String privilegedAccessMethodForMethod(String name, TypeX objectType, TypeX aspectType) {
return makeName("privMethod", aspectType.getNameAsIdentifier(),
objectType.getNameAsIdentifier(), name);
}
public static String privilegedAccessMethodForFieldGet(String name, TypeX objectType, TypeX aspectType) {
return makeName("privFieldGet", aspectType.getNameAsIdentifier(),
objectType.getNameAsIdentifier(), name);
}
public static String privilegedAccessMethodForFieldSet(String name, TypeX objectType, TypeX aspectType) {
return makeName("privFieldSet", aspectType.getNameAsIdentifier(),
objectType.getNameAsIdentifier(), name);
}
public static String inlineAccessMethodForMethod(String name, TypeX objectType, TypeX aspectType) {
return makeName("inlineAccessMethod", aspectType.getNameAsIdentifier(),
objectType.getNameAsIdentifier(), name);
}
public static String inlineAccessMethodForFieldGet(String name, TypeX objectType, TypeX aspectType) {
return makeName("inlineAccessFieldGet", aspectType.getNameAsIdentifier(),
objectType.getNameAsIdentifier(), name);
}
public static String inlineAccessMethodForFieldSet(String name, TypeX objectType, TypeX aspectType) {
return makeName("inlineAccessFieldSet", aspectType.getNameAsIdentifier(),
objectType.getNameAsIdentifier(), name);
}
/**
* The name of methods corresponding to advice declarations
*/
public static String adviceName(TypeX aspectType, AdviceKind kind, int position) {
return makeName(kind.getName(), aspectType.getNameAsIdentifier(),
Integer.toHexString(position));
}
/**
* This field goes on top-most implementers of the interface the field
* is declared onto
*/
public static String interFieldInterfaceField(TypeX aspectType, TypeX interfaceType, String name) {
return makeName("interField", aspectType.getNameAsIdentifier(),
interfaceType.getNameAsIdentifier(), name);
}
/**
* This instance method goes on the interface the field is declared onto
* as well as its top-most implementors
*/
public static String interFieldInterfaceSetter(TypeX aspectType, TypeX interfaceType, String name) {
return makeName("interFieldSet", aspectType.getNameAsIdentifier(),
interfaceType.getNameAsIdentifier(), name);
}
/**
* This instance method goes on the interface the field is declared onto
* as well as its top-most implementors
*/
public static String interFieldInterfaceGetter(TypeX aspectType, TypeX interfaceType, String name) {
return makeName("interFieldGet", aspectType.getNameAsIdentifier(),
interfaceType.getNameAsIdentifier(), name);
}
/**
* This static method goes on the aspect that declares the inter-type field
*/
public static String interFieldSetDispatcher(TypeX aspectType, TypeX onType, String name) {
return makeName("interFieldSetDispatch", aspectType.getNameAsIdentifier(),
onType.getNameAsIdentifier(), name);
}
/**
* This static method goes on the aspect that declares the inter-type field
*/
public static String interFieldGetDispatcher(TypeX aspectType, TypeX onType, String name) {
return makeName("interFieldGetDispatch", aspectType.getNameAsIdentifier(),
onType.getNameAsIdentifier(), name);
}
/**
* This field goes on the class the field
* is declared onto
*/
public static String interFieldClassField(int modifiers, TypeX aspectType, TypeX classType, String name) {
if (Modifier.isPublic(modifiers)) return name;
//??? might want to handle case where aspect and class are in same package similar to public
return makeName("interField", makeVisibilityName(modifiers, aspectType), name);
}
// /**
// * This static method goes on the aspect that declares the inter-type field
// */
// public static String classFieldSetDispatcher(TypeX aspectType, TypeX classType, String name) {
// return makeName("interFieldSetDispatch", aspectType.getNameAsIdentifier(),
// classType.getNameAsIdentifier(), name);
// }
//
// /**
// * This static method goes on the aspect that declares the inter-type field
// */
// public static String classFieldGetDispatcher(TypeX aspectType, TypeX classType, String name)
// {
// return makeName(
// "interFieldGetDispatch",
// aspectType.getNameAsIdentifier(),
// classType.getNameAsIdentifier(),
// name);
// }
/**
* This static void method goes on the aspect that declares the inter-type field and is called
* from the appropriate place (target's initializer, or clinit, or topmost implementer's inits),
* to initialize the field;
*/
public static String interFieldInitializer(TypeX aspectType, TypeX classType, String name)
{
return makeName(
"interFieldInit",
aspectType.getNameAsIdentifier(),
classType.getNameAsIdentifier(),
name);
}
// ----
/**
* This method goes on the target type of the inter-type method. (and possibly the topmost-implemeters,
* if the target type is an interface)
*/
public static String interMethod(int modifiers, TypeX aspectType, TypeX classType, String name)
{
if (Modifier.isPublic(modifiers)) return name;
//??? might want to handle case where aspect and class are in same package similar to public
return makeName("interMethodDispatch2", makeVisibilityName(modifiers, aspectType), name);
}
/**
* This static method goes on the declaring aspect of the inter-type method.
*/
public static String interMethodDispatcher(TypeX aspectType, TypeX classType, String name)
{
return makeName("interMethodDispatch1", aspectType.getNameAsIdentifier(),
classType.getNameAsIdentifier(), name);
}
/**
* This static method goes on the declaring aspect of the inter-type method.
*/
public static String interMethodBody(TypeX aspectType, TypeX classType, String name)
{
return makeName("interMethod", aspectType.getNameAsIdentifier(),
classType.getNameAsIdentifier(), name);
}
// ----
/**
* This static method goes on the declaring aspect of the inter-type constructor.
*/
public static String preIntroducedConstructor(
TypeX aspectType,
TypeX targetType)
{
return makeName("preInterConstructor", aspectType.getNameAsIdentifier(),
targetType.getNameAsIdentifier());
}
/**
* This static method goes on the declaring aspect of the inter-type constructor.
*/
public static String postIntroducedConstructor(
TypeX aspectType,
TypeX targetType)
{
return makeName("postInterConstructor", aspectType.getNameAsIdentifier(),
targetType.getNameAsIdentifier());
}
// ----
/**
* This static method goes on the target class of the inter-type method.
*/
public static String superDispatchMethod(TypeX classType, String name)
{
return makeName("superDispatch",
classType.getNameAsIdentifier(), name);
}
/**
* This static method goes on the target class of the inter-type method.
*/
public static String protectedDispatchMethod(TypeX classType, String name)
{
return makeName("protectedDispatch",
classType.getNameAsIdentifier(), name);
}
// ----
private static String makeVisibilityName(int modifiers, TypeX aspectType) {
if (Modifier.isPrivate(modifiers)) {
return aspectType.getOutermostType().getNameAsIdentifier();
} else if (Modifier.isProtected(modifiers)) {
throw new RuntimeException("protected inter-types not allowed");
} else if (Modifier.isPublic(modifiers)) {
return "";
} else {
return aspectType.getPackageNameAsIdentifier();
}
}
private static String makeName(String s1, String s2) {
return "ajc$" + s1 + "$" + s2;
}
public static String makeName(String s1, String s2, String s3) {
return "ajc$" + s1 + "$" + s2 + "$" + s3;
}
public static String makeName(String s1, String s2, String s3, String s4) {
return "ajc$" + s1 + "$" + s2 + "$" + s3 + "$" + s4;
}
public static String cflowStack(CrosscuttingMembers xcut) {
return makeName("cflowStack", Integer.toHexString(xcut.getCflowEntries().size()));
}
public static String makeClosureClassName(
TypeX enclosingType,
int index)
{
return enclosingType.getName() + "$AjcClosure" + index;
}
public static String aroundCallbackMethodName(
Member shadowSig,
LazyClassGen enclosingType)
{
String ret =
shadowSig.getExtractableName()
+ "_aroundBody"
+ enclosingType.getNewGeneratedNameTag();
return ret;
}
public static String proceedMethodName(String adviceMethodName) {
return adviceMethodName + "proceed";
}
}
|
44,587
|
Bug 44587 Erroneous exception conversion
| null |
resolved fixed
|
5834de9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-14T15:24:06Z
| 2003-10-09T17:20:00Z
|
weaver/src/org/aspectj/weaver/bcel/BcelClassWeaver.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.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.bcel.Constants;
import org.apache.bcel.generic.BranchInstruction;
import org.apache.bcel.generic.CPInstruction;
import org.apache.bcel.generic.ConstantPoolGen;
import org.apache.bcel.generic.FieldInstruction;
import org.apache.bcel.generic.INVOKESPECIAL;
import org.apache.bcel.generic.IndexedInstruction;
import org.apache.bcel.generic.Instruction;
import org.apache.bcel.generic.InstructionConstants;
import org.apache.bcel.generic.InstructionFactory;
import org.apache.bcel.generic.InstructionHandle;
import org.apache.bcel.generic.InstructionList;
import org.apache.bcel.generic.InstructionTargeter;
import org.apache.bcel.generic.InvokeInstruction;
import org.apache.bcel.generic.LocalVariableInstruction;
import org.apache.bcel.generic.NEW;
import org.apache.bcel.generic.ObjectType;
import org.apache.bcel.generic.PUTFIELD;
import org.apache.bcel.generic.PUTSTATIC;
import org.apache.bcel.generic.RET;
import org.apache.bcel.generic.ReturnInstruction;
import org.apache.bcel.generic.Select;
import org.apache.bcel.generic.Type;
import org.aspectj.bridge.IMessage;
import org.aspectj.util.PartialOrder;
import org.aspectj.weaver.AjAttribute;
import org.aspectj.weaver.AjcMemberMaker;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.ConcreteTypeMunger;
import org.aspectj.weaver.IClassWeaver;
import org.aspectj.weaver.IntMap;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.NameMangler;
import org.aspectj.weaver.NewFieldTypeMunger;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedTypeX;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.ShadowMunger;
class BcelClassWeaver implements IClassWeaver {
/**
* This is called from {@link BcelWeaver} to perform the per-class weaving process.
*/
public static boolean weave(
BcelWorld world,
LazyClassGen clazz,
List shadowMungers,
List typeMungers)
{
boolean b = new BcelClassWeaver(world, clazz, shadowMungers, typeMungers).weave();
//System.out.println(clazz.getClassName() + ", " + clazz.getType().getWeaverState());
//clazz.print();
return b;
}
// --------------------------------------------
private final LazyClassGen clazz;
private final List shadowMungers;
private final List typeMungers;
private final BcelObjectType ty; // alias of clazz.getType()
private final BcelWorld world; // alias of ty.getWorld()
private final ConstantPoolGen cpg; // alias of clazz.getConstantPoolGen()
private final InstructionFactory fact; // alias of clazz.getFactory();
private final List addedLazyMethodGens = new ArrayList();
private final Set addedDispatchTargets = new HashSet();
private List addedSuperInitializersAsList = null; // List<IfaceInitList>
private final Map addedSuperInitializers = new HashMap(); // Interface -> IfaceInitList
private List addedThisInitializers = new ArrayList(); // List<NewFieldMunger>
private List addedClassInitializers = new ArrayList(); // List<NewFieldMunger>
private BcelShadow clinitShadow = null;
/**
* This holds the initialization and pre-initialization shadows for this class
* that were actually matched by mungers (if no match, then we don't even create the
* shadows really).
*/
private final List initializationShadows = new ArrayList(1);
private BcelClassWeaver(
BcelWorld world,
LazyClassGen clazz,
List shadowMungers,
List typeMungers)
{
super();
// assert world == clazz.getType().getWorld()
this.world = world;
this.clazz = clazz;
this.shadowMungers = shadowMungers;
this.typeMungers = typeMungers;
this.ty = clazz.getBcelObjectType();
this.cpg = clazz.getConstantPoolGen();
this.fact = clazz.getFactory();
initializeSuperInitializerMap(ty.getResolvedTypeX());
}
// --------------------------------------------
private void initializeSuperInitializerMap(ResolvedTypeX child) {
ResolvedTypeX[] superInterfaces = child.getDeclaredInterfaces();
for (int i=0, len=superInterfaces.length; i < len; i++) {
if (ty.getResolvedTypeX().isTopmostImplementor(superInterfaces[i])) {
if (addSuperInitializer(superInterfaces[i])) {
initializeSuperInitializerMap(superInterfaces[i]);
}
}
}
}
private boolean addSuperInitializer(ResolvedTypeX onType) {
IfaceInitList l = (IfaceInitList) addedSuperInitializers.get(onType);
if (l != null) return false;
l = new IfaceInitList(onType);
addedSuperInitializers.put(onType, l);
return true;
}
public void addInitializer(ConcreteTypeMunger cm) {
NewFieldTypeMunger m = (NewFieldTypeMunger) cm.getMunger();
ResolvedTypeX onType = m.getSignature().getDeclaringType().resolve(world);
if (m.getSignature().isStatic()) {
addedClassInitializers.add(cm);
} else {
if (onType == ty.getResolvedTypeX()) {
addedThisInitializers.add(cm);
} else {
IfaceInitList l = (IfaceInitList) addedSuperInitializers.get(onType);
l.list.add(cm);
}
}
}
private static class IfaceInitList implements PartialOrder.PartialComparable {
final ResolvedTypeX onType;
List list = new ArrayList();
IfaceInitList(ResolvedTypeX onType) {
this.onType = onType;
}
public int compareTo(Object other) {
IfaceInitList o = (IfaceInitList)other;
if (onType.isAssignableFrom(o.onType)) return +1;
else if (o.onType.isAssignableFrom(onType)) return -1;
else return 0;
}
public int fallbackCompareTo(Object other) {
return 0;
}
}
// XXX this is being called, but the result doesn't seem to be being used
public boolean addDispatchTarget(ResolvedMember m) {
return addedDispatchTargets.add(m);
}
public void addLazyMethodGen(LazyMethodGen gen) {
addedLazyMethodGens.add(gen);
}
public void addOrReplaceLazyMethodGen(LazyMethodGen mg) {
if (alreadyDefined(clazz, mg)) return;
for (Iterator i = addedLazyMethodGens.iterator(); i.hasNext(); ) {
LazyMethodGen existing = (LazyMethodGen)i.next();
if (signaturesMatch(mg, existing)) {
if (existing.definingType == null) {
// this means existing was introduced on the class itself
return;
} else if (mg.definingType.isAssignableFrom(existing.definingType)) {
// existing is mg's subtype and dominates mg
return;
} else if (existing.definingType.isAssignableFrom(mg.definingType)) {
// mg is existing's subtype and dominates existing
i.remove();
addedLazyMethodGens.add(mg);
return;
} else {
throw new BCException("conflict between: " + mg + " and " + existing);
}
}
}
addedLazyMethodGens.add(mg);
}
private boolean alreadyDefined(LazyClassGen clazz, LazyMethodGen mg) {
for (Iterator i = clazz.getMethodGens().iterator(); i.hasNext(); ) {
LazyMethodGen existing = (LazyMethodGen)i.next();
if (signaturesMatch(mg, existing)) {
if (!mg.isAbstract() && existing.isAbstract()) {
i.remove();
return false;
}
return true;
}
}
return false;
}
private boolean signaturesMatch(LazyMethodGen mg, LazyMethodGen existing) {
return mg.getName().equals(existing.getName()) &&
mg.getSignature().equals(existing.getSignature());
}
// ----
public boolean weave() {
if (clazz.isWoven()) {
world.showMessage(IMessage.ERROR,
"class \'" + clazz.getType().getName() + "\' is already woven",
ty.getSourceLocation(), null);
return false;
}
boolean isChanged = false;
// we want to "touch" all aspects
if (clazz.getType().isAspect()) isChanged = true;
// start by munging all typeMungers
for (Iterator i = typeMungers.iterator(); i.hasNext(); ) {
Object o = i.next();
if ( !(o instanceof BcelTypeMunger) ) {
//???System.err.println("surprising: " + o);
continue;
}
BcelTypeMunger munger = (BcelTypeMunger)o;
isChanged |= munger.munge(this);
}
// XXX do major sort of stuff
// sort according to: Major: type hierarchy
// within each list: dominates
// don't forget to sort addedThisInitialiers according to dominates
addedSuperInitializersAsList = new ArrayList(addedSuperInitializers.values());
addedSuperInitializersAsList = PartialOrder.sort(addedSuperInitializersAsList);
if (addedSuperInitializersAsList == null) {
throw new BCException("circularity in inter-types");
}
// this will create a static initializer if there isn't one
// this is in just as bad taste as NOPs
LazyMethodGen staticInit = clazz.getStaticInitializer();
staticInit.getBody().insert(genInitInstructions(addedClassInitializers, true));
// now go through each method, and match against each method. This
// sets up each method's {@link LazyMethodGen#matchedShadows} field,
// and it also possibly adds to {@link #initializationShadows}.
List methodGens = new ArrayList(clazz.getMethodGens());
for (Iterator i = methodGens.iterator(); i.hasNext();) {
LazyMethodGen mg = (LazyMethodGen)i.next();
if (! mg.hasBody()) continue;
isChanged |= match(mg);
}
if (! isChanged) return false;
// now we weave all but the initialization shadows
for (Iterator i = methodGens.iterator(); i.hasNext();) {
LazyMethodGen mg = (LazyMethodGen)i.next();
if (! mg.hasBody()) continue;
implement(mg);
}
// if we matched any initialization shadows, we inline and weave
if (! initializationShadows.isEmpty()) {
inlineSelfConstructors(methodGens);
positionAndImplement(initializationShadows);
}
// finally, if we changed, we add in the introduced methods.
if (isChanged) {
clazz.getOrCreateWeaverStateInfo();
weaveInAddedMethods();
}
return isChanged;
}
private void inlineSelfConstructors(List methodGens) {
for (Iterator i = methodGens.iterator(); i.hasNext();) {
LazyMethodGen mg = (LazyMethodGen) i.next();
if (! mg.getName().equals("<init>")) continue;
InstructionHandle ih = findSuperOrThisCall(mg);
if (ih != null && isThisCall(ih)) {
LazyMethodGen donor = getCalledMethod(ih);
inlineMethod(donor, mg, ih);
}
}
}
private void positionAndImplement(List initializationShadows) {
for (Iterator i = initializationShadows.iterator(); i.hasNext(); ) {
BcelShadow s = (BcelShadow) i.next();
positionInitializationShadow(s);
//s.getEnclosingMethod().print();
s.implement();
}
}
private void positionInitializationShadow(BcelShadow s) {
LazyMethodGen mg = s.getEnclosingMethod();
InstructionHandle call = findSuperOrThisCall(mg);
InstructionList body = mg.getBody();
ShadowRange r = new ShadowRange(body);
r.associateWithShadow((BcelShadow) s);
if (s.getKind() == Shadow.PreInitialization) {
// XXX assert first instruction is an ALOAD_0.
// a pre shadow goes from AFTER the first instruction (which we believe to
// be an ALOAD_0) to just before the call to super
r.associateWithTargets(
Range.genStart(body, body.getStart().getNext()),
Range.genEnd(body, call.getPrev()));
} else {
// assert s.getKind() == Shadow.Initialization
r.associateWithTargets(
Range.genStart(body, call.getNext()),
Range.genEnd(body));
}
}
private boolean isThisCall(InstructionHandle ih) {
INVOKESPECIAL inst = (INVOKESPECIAL) ih.getInstruction();
return inst.getClassName(cpg).equals(clazz.getName());
}
/** inline a particular call in bytecode.
*
* @param donor the method we want to inline
* @param recipient the method containing the call we want to inline
* @param call the instructionHandle in recipient's body holding the call we want to
* inline.
*/
public static void inlineMethod(
LazyMethodGen donor,
LazyMethodGen recipient,
InstructionHandle call)
{
// assert recipient.contains(call)
/* Implementation notes:
*
* We allocate two slots for every tempvar so we don't screw up
* longs and doubles which may share space. This could be conservatively avoided
* (no reference to a long/double instruction, don't do it) or packed later.
* Right now we don't bother to pack.
*
* Allocate a new var for each formal param of the inlined. Fill with stack
* contents. Then copy the inlined instructions in with the appropriate remap
* table. Any framelocs used by locals in inlined are reallocated to top of
* frame,
*/
final InstructionFactory fact = recipient.getEnclosingClass().getFactory();
IntMap frameEnv = new IntMap();
// this also sets up the initial environment
InstructionList argumentStores =
genArgumentStores(donor, recipient, frameEnv, fact);
InstructionList inlineInstructions =
genInlineInstructions(donor, recipient, frameEnv, fact, false);
inlineInstructions.insert(argumentStores);
recipient.getBody().append(call, inlineInstructions);
Utility.deleteInstruction(call, recipient);
}
/** generate the instructions to be inlined.
*
* @param donor the method from which we will copy (and adjust frame and jumps)
* instructions.
* @param recipient the method the instructions will go into. Used to get the frame
* size so we can allocate new frame locations for locals in donor.
* @param frameEnv an environment to map from donor frame to recipient frame,
* initially populated with argument locations.
* @param fact an instruction factory for recipient
*/
static InstructionList genInlineInstructions(
LazyMethodGen donor,
LazyMethodGen recipient,
IntMap frameEnv,
InstructionFactory fact,
boolean keepReturns)
{
InstructionList footer = new InstructionList();
InstructionHandle end = footer.append(InstructionConstants.NOP);
InstructionList ret = new InstructionList();
InstructionList sourceList = donor.getBody();
Map srcToDest = new HashMap();
ConstantPoolGen donorCpg = donor.getEnclosingClass().getConstantPoolGen();
ConstantPoolGen recipientCpg = recipient.getEnclosingClass().getConstantPoolGen();
boolean isAcrossClass = donorCpg != recipientCpg;
// first pass: copy the instructions directly, populate the srcToDest map,
// fix frame instructions
for (InstructionHandle src = sourceList.getStart();
src != null;
src = src.getNext())
{
Instruction fresh = Utility.copyInstruction(src.getInstruction());
InstructionHandle dest;
if (fresh instanceof CPInstruction) {
// need to reset index to go to new constant pool. This is totally
// a computation leak... we're testing this LOTS of times. Sigh.
if (isAcrossClass) {
CPInstruction cpi = (CPInstruction) fresh;
cpi.setIndex(
recipientCpg.addConstant(
donorCpg.getConstant(cpi.getIndex()),
donorCpg));
}
}
if (src.getInstruction() == Range.RANGEINSTRUCTION) {
dest = ret.append(Range.RANGEINSTRUCTION);
} else if (fresh instanceof ReturnInstruction) {
if (keepReturns) {
dest = ret.append(fresh);
} else {
dest =
ret.append(InstructionFactory.createBranchInstruction(Constants.GOTO, end));
}
} else if (fresh instanceof BranchInstruction) {
dest = ret.append((BranchInstruction) fresh);
} else if (
fresh instanceof LocalVariableInstruction || fresh instanceof RET) {
IndexedInstruction indexed = (IndexedInstruction) fresh;
int oldIndex = indexed.getIndex();
int freshIndex;
if (!frameEnv.hasKey(oldIndex)) {
freshIndex = recipient.allocateLocal(2);
frameEnv.put(oldIndex, freshIndex);
} else {
freshIndex = frameEnv.get(oldIndex);
}
indexed.setIndex(freshIndex);
dest = ret.append(fresh);
} else {
dest = ret.append(fresh);
}
srcToDest.put(src, dest);
}
// second pass: retarget branch instructions, copy ranges and tags
Map tagMap = new HashMap();
Map shadowMap = new HashMap();
for (InstructionHandle dest = ret.getStart(), src = sourceList.getStart();
dest != null;
dest = dest.getNext(), src = src.getNext()) {
Instruction inst = dest.getInstruction();
// retarget branches
if (inst instanceof BranchInstruction) {
BranchInstruction branch = (BranchInstruction) inst;
InstructionHandle oldTarget = branch.getTarget();
InstructionHandle newTarget =
(InstructionHandle) srcToDest.get(oldTarget);
if (newTarget == null) {
// assert this is a GOTO
// this was a return instruction we previously replaced
} else {
branch.setTarget(newTarget);
if (branch instanceof Select) {
Select select = (Select) branch;
InstructionHandle[] oldTargets = select.getTargets();
for (int k = oldTargets.length - 1; k >= 0; k--) {
select.setTarget(
k,
(InstructionHandle) srcToDest.get(oldTargets[k]));
}
}
}
}
//copy over tags and range attributes
InstructionTargeter[] srcTargeters = src.getTargeters();
if (srcTargeters != null) {
for (int j = srcTargeters.length - 1; j >= 0; j--) {
InstructionTargeter old = srcTargeters[j];
if (old instanceof Tag) {
Tag oldTag = (Tag) old;
Tag fresh = (Tag) tagMap.get(oldTag);
if (fresh == null) {
fresh = oldTag.copy();
tagMap.put(oldTag, fresh);
}
dest.addTargeter(fresh);
} else if (old instanceof ExceptionRange) {
ExceptionRange er = (ExceptionRange) old;
if (er.getStart() == src) {
ExceptionRange freshEr =
new ExceptionRange(
recipient.getBody(),
er.getCatchType(),
er.getPriority());
freshEr.associateWithTargets(
dest,
(InstructionHandle)srcToDest.get(er.getEnd()),
(InstructionHandle)srcToDest.get(er.getHandler()));
}
} else if (old instanceof ShadowRange) {
ShadowRange oldRange = (ShadowRange) old;
if (oldRange.getStart() == src) {
BcelShadow oldShadow = oldRange.getShadow();
BcelShadow freshEnclosing =
oldShadow.getEnclosingShadow() == null
? null
: (BcelShadow) shadowMap.get(oldShadow.getEnclosingShadow());
BcelShadow freshShadow =
oldShadow.copyInto(recipient, freshEnclosing);
ShadowRange freshRange = new ShadowRange(recipient.getBody());
freshRange.associateWithShadow(freshShadow);
freshRange.associateWithTargets(
dest,
(InstructionHandle) srcToDest.get(oldRange.getEnd()));
shadowMap.put(oldRange, freshRange);
//recipient.matchedShadows.add(freshShadow);
// XXX should go through the NEW copied shadow and update
// the thisVar, targetVar, and argsVar
// ??? Might want to also go through at this time and add
// "extra" vars to the shadow.
}
}
}
}
}
if (!keepReturns) ret.append(footer);
return ret;
}
/** generate the argument stores in preparation for inlining.
*
* @param donor the method we will inline from. Used to get the signature.
* @param recipient the method we will inline into. Used to get the frame size
* so we can allocate fresh locations.
* @param frameEnv an empty environment we populate with a map from donor frame to
* recipient frame.
* @param fact an instruction factory for recipient
*/
private static InstructionList genArgumentStores(
LazyMethodGen donor,
LazyMethodGen recipient,
IntMap frameEnv,
InstructionFactory fact)
{
InstructionList ret = new InstructionList();
int donorFramePos = 0;
// writing ret back to front because we're popping.
if (! donor.isStatic()) {
int targetSlot = recipient.allocateLocal(Type.OBJECT);
ret.insert(InstructionFactory.createStore(Type.OBJECT, targetSlot));
frameEnv.put(donorFramePos, targetSlot);
donorFramePos += 1;
}
Type[] argTypes = donor.getArgumentTypes();
for (int i = 0, len = argTypes.length; i < len; i++) {
Type argType = argTypes[i];
int argSlot = recipient.allocateLocal(argType);
ret.insert(InstructionFactory.createStore(argType, argSlot));
frameEnv.put(donorFramePos, argSlot);
donorFramePos += argType.getSize();
}
return ret;
}
/** get a called method: Assumes the called method is in this class,
* and the reference to it is exact (a la INVOKESPECIAL).
*
* @param ih The InvokeInstruction instructionHandle pointing to the called method.
*/
private LazyMethodGen getCalledMethod(
InstructionHandle ih)
{
InvokeInstruction inst = (InvokeInstruction) ih.getInstruction();
String methodName = inst.getName(cpg);
String signature = inst.getSignature(cpg);
return clazz.getLazyMethodGen(methodName, signature);
}
private void weaveInAddedMethods() {
Collections.sort(addedLazyMethodGens,
new Comparator() {
public int compare(Object a, Object b) {
LazyMethodGen aa = (LazyMethodGen) a;
LazyMethodGen bb = (LazyMethodGen) b;
int i = aa.getName().compareTo(bb.getName());
if (i != 0) return i;
return aa.getSignature().compareTo(bb.getSignature());
}
}
);
for (Iterator i = addedLazyMethodGens.iterator(); i.hasNext(); ) {
clazz.addMethodGen((LazyMethodGen)i.next());
}
}
void addPerSingletonField(Member field) {
ObjectType aspectType = (ObjectType) BcelWorld.makeBcelType(field.getReturnType());
String aspectName = field.getReturnType().getName();
LazyMethodGen clinit = clazz.getStaticInitializer();
InstructionList setup = new InstructionList();
InstructionFactory fact = clazz.getFactory();
setup.append(fact.createNew(aspectType));
setup.append(InstructionFactory.createDup(1));
setup.append(fact.createInvoke(
aspectName,
"<init>",
Type.VOID,
new Type[0],
Constants.INVOKESPECIAL));
setup.append(
fact.createFieldAccess(
aspectName,
field.getName(),
aspectType,
Constants.PUTSTATIC));
clinit.getBody().insert(setup);
}
/**
* Returns null if this is not a Java constructor, and then we won't
* weave into it at all
*/
private InstructionHandle findSuperOrThisCall(LazyMethodGen mg) {
int depth = 1;
InstructionHandle start = mg.getBody().getStart();
while (true) {
if (start == null) return null;
Instruction inst = start.getInstruction();
if (inst instanceof INVOKESPECIAL
&& ((INVOKESPECIAL) inst).getName(cpg).equals("<init>")) {
depth--;
if (depth == 0) return start;
} else if (inst instanceof NEW) {
depth++;
}
start = start.getNext();
}
}
// ----
private boolean match(LazyMethodGen mg) {
BcelShadow enclosingShadow;
List shadowAccumulator = new ArrayList();
// we want to match ajsynthetic constructors...
if (mg.getName().equals("<init>")) {
// XXX the enclosing join point is wrong for things before ignoreMe.
InstructionHandle superOrThisCall = findSuperOrThisCall(mg);
// we don't walk bodies of things where it's a wrong constructor thingie
if (superOrThisCall == null) return false;
enclosingShadow = BcelShadow.makeConstructorExecution(world, mg, superOrThisCall);
// walk the body
boolean beforeSuperOrThisCall = true;
if (shouldWeaveBody(mg)) { //!mg.isAjSynthetic()) {
for (InstructionHandle h = mg.getBody().getStart();
h != null;
h = h.getNext()) {
if (h == superOrThisCall) {
beforeSuperOrThisCall = false;
continue;
}
match(mg, h, beforeSuperOrThisCall ? null : enclosingShadow, shadowAccumulator);
}
match(enclosingShadow, shadowAccumulator);
}
// XXX we don't do pre-inits of interfaces
// now add interface inits and cexecs
if (superOrThisCall != null && ! isThisCall(superOrThisCall)) {
InstructionHandle curr = enclosingShadow.getRange().getStart();
for (Iterator i = addedSuperInitializersAsList.iterator(); i.hasNext(); ) {
IfaceInitList l = (IfaceInitList) i.next();
// generate the cexec jp
Member ifaceInitSig = AjcMemberMaker.interfaceConstructor(l.onType);
BcelShadow cexecShadow =
BcelShadow.makeIfaceConstructorExecution(
world,
mg,
curr,
ifaceInitSig);
if (match(cexecShadow, shadowAccumulator)) {
cexecShadow.getRange().getBody().append(
cexecShadow.getRange().getStart(),
InstructionConstants.NOP);
}
// generate the init jp around it
BcelShadow initShadow =
BcelShadow.makeIfaceInitialization(
world,
mg,
cexecShadow,
ifaceInitSig);
match(initShadow, shadowAccumulator);
// insert code in place
InstructionList inits = genInitInstructions(l.list, false);
initShadow.getRange().insert(inits, Range.InsideAfter);
}
// now we add our initialization code
InstructionList inits = genInitInstructions(addedThisInitializers, false);
enclosingShadow.getRange().insert(inits, Range.OutsideBefore);
}
// actually, you only need to inline the self constructors that are
// in a particular group (partition the constructors into groups where members
// call or are called only by those in the group). Then only inline
// constructors
// in groups where at least one initialization jp matched. Future work.
boolean addedInitialization =
match(
BcelShadow.makeUnfinishedInitialization(world, mg),
initializationShadows);
addedInitialization |=
match(
BcelShadow.makeUnfinishedPreinitialization(world, mg),
initializationShadows);
mg.matchedShadows = shadowAccumulator;
return addedInitialization || !shadowAccumulator.isEmpty();
} else if (!shouldWeaveBody(mg)) { //.isAjSynthetic()) {
return false;
} else {
if (mg.getName().equals("<clinit>")) {
clinitShadow = enclosingShadow = BcelShadow.makeStaticInitialization(world, mg);
//System.err.println(enclosingShadow);
} else if (mg.isAdviceMethod()) {
enclosingShadow = BcelShadow.makeAdviceExecution(world, mg);
} else {
AjAttribute.EffectiveSignatureAttribute effective = mg.getEffectiveSignature();
if (effective == null) {
enclosingShadow = BcelShadow.makeMethodExecution(world, mg);
} else if (effective.isWeaveBody()) {
enclosingShadow =
BcelShadow.makeShadowForMethod(
world,
mg,
effective.getShadowKind(),
effective.getEffectiveSignature());
} else {
return false;
}
}
for (InstructionHandle h = mg.getBody().getStart();
h != null;
h = h.getNext()) {
match(mg, h, enclosingShadow, shadowAccumulator);
}
match(enclosingShadow, shadowAccumulator);
mg.matchedShadows = shadowAccumulator;
return !shadowAccumulator.isEmpty();
}
}
private boolean shouldWeaveBody(LazyMethodGen mg) {
if (mg.isAjSynthetic()) return mg.getName().equals("<clinit>");
AjAttribute.EffectiveSignatureAttribute a = mg.getEffectiveSignature();
if (a != null) return a.isWeaveBody();
return true;
}
/**
* first sorts the mungers, then gens the initializers in the right order
*/
private InstructionList genInitInstructions(List list, boolean isStatic) {
list = PartialOrder.sort(list);
if (list == null) {
throw new BCException("circularity in inter-types");
}
InstructionList ret = new InstructionList();
for (Iterator i = list.iterator(); i.hasNext();) {
ConcreteTypeMunger cmunger = (ConcreteTypeMunger) i.next();
NewFieldTypeMunger munger = (NewFieldTypeMunger) cmunger.getMunger();
ResolvedMember initMethod = munger.getInitMethod(cmunger.getAspectType());
if (!isStatic) ret.append(InstructionConstants.ALOAD_0);
ret.append(Utility.createInvoke(fact, world, initMethod));
}
return ret;
}
private void match(
LazyMethodGen mg,
InstructionHandle ih,
BcelShadow enclosingShadow,
List shadowAccumulator)
{
Instruction i = ih.getInstruction();
if (i instanceof FieldInstruction) {
FieldInstruction fi = (FieldInstruction) i;
if (fi instanceof PUTFIELD || fi instanceof PUTSTATIC) {
// check for sets of constant fields. We first check the previous
// instruction. If the previous instruction is a LD_WHATEVER (push
// constant on the stack) then we must resolve the field to determine
// if it's final. If it is final, then we don't generate a shadow.
InstructionHandle prevHandle = ih.getPrev();
Instruction prevI = prevHandle.getInstruction();
if (Utility.isConstantPushInstruction(prevI)) {
Member field = BcelWorld.makeFieldSignature(clazz, (FieldInstruction) i);
ResolvedMember resolvedField = field.resolve(world);
if (resolvedField == null) {
// we can't find the field, so it's not a join point.
} else if (Modifier.isFinal(resolvedField.getModifiers())) {
// it's final, so it's the set of a final constant, so it's
// not a join point according to 1.0.6 and 1.1.
} else {
matchSetInstruction(mg, ih, enclosingShadow, shadowAccumulator);
}
} else {
matchSetInstruction(mg, ih, enclosingShadow, shadowAccumulator);
}
} else {
matchGetInstruction(mg, ih, enclosingShadow, shadowAccumulator);
}
} else if (i instanceof InvokeInstruction) {
InvokeInstruction ii = (InvokeInstruction) i;
if (ii.getMethodName(clazz.getConstantPoolGen()).equals("<init>")) {
match(
BcelShadow.makeConstructorCall(world, mg, ih, enclosingShadow),
shadowAccumulator);
} else if (ii instanceof INVOKESPECIAL) {
String onTypeName = ii.getClassName(cpg);
if (onTypeName.equals(mg.getEnclosingClass().getName())) {
// we are private
matchInvokeInstruction(mg, ih, ii, enclosingShadow, shadowAccumulator);
} else {
// we are a super call, and this is not a join point in AspectJ-1.{0,1}
}
} else {
matchInvokeInstruction(mg, ih, ii, enclosingShadow, shadowAccumulator);
}
}
// performance optimization... we only actually care about ASTORE instructions,
// since that's what every javac type thing ever uses to start a handler, but for
// now we'll do this for everybody.
if (Range.isRangeHandle(ih)) return;
InstructionTargeter[] targeters = ih.getTargeters();
if (targeters != null) {
for (int j = 0; j < targeters.length; j++) {
InstructionTargeter t = targeters[j];
if (t instanceof ExceptionRange) {
// assert t.getHandler() == ih
ExceptionRange er = (ExceptionRange) t;
if (er.getCatchType() == null) continue;
match(
BcelShadow.makeExceptionHandler(
world,
er,
mg, ih, enclosingShadow),
shadowAccumulator);
}
}
}
}
private void matchSetInstruction(
LazyMethodGen mg,
InstructionHandle ih,
BcelShadow enclosingShadow,
List shadowAccumulator) {
FieldInstruction fi = (FieldInstruction) ih.getInstruction();
Member field = BcelWorld.makeFieldSignature(clazz, fi);
ResolvedMember resolvedField = field.resolve(world);
if (resolvedField == null) {
// we can't find the field, so it's not a join point.
return;
} else if (
Modifier.isFinal(resolvedField.getModifiers())
&& Utility.isConstantPushInstruction(ih.getPrev().getInstruction())) {
// it's the set of a final constant, so it's
// not a join point according to 1.0.6 and 1.1.
return;
} else if (resolvedField.isSynthetic()) {
// sets of synthetics aren't join points in 1.1
return;
} else {
match(
BcelShadow.makeFieldSet(world, mg, ih, enclosingShadow),
shadowAccumulator);
}
}
private void matchGetInstruction(LazyMethodGen mg, InstructionHandle ih, BcelShadow enclosingShadow, List shadowAccumulator) {
FieldInstruction fi = (FieldInstruction) ih.getInstruction();
Member field = BcelWorld.makeFieldSignature(clazz, fi);
ResolvedMember resolvedField = field.resolve(world);
if (resolvedField == null) {
// we can't find the field, so it's not a join point.
return;
} else if (resolvedField.isSynthetic()) {
// sets of synthetics aren't join points in 1.1
return;
} else {
match(BcelShadow.makeFieldGet(world, mg, ih, enclosingShadow), shadowAccumulator);
}
}
private void matchInvokeInstruction(LazyMethodGen mg,
InstructionHandle ih,
InvokeInstruction invoke,
BcelShadow enclosingShadow,
List shadowAccumulator)
{
String methodName = invoke.getName(cpg);
if (methodName.startsWith(NameMangler.PREFIX)) {
Member method =
BcelWorld.makeMethodSignature(clazz, invoke);
ResolvedMember declaredSig = method.resolve(world);
//System.err.println(method + ", declaredSig: " +declaredSig);
if (declaredSig == null) return;
if (declaredSig.getKind() == Member.FIELD) {
Shadow.Kind kind;
if (method.getReturnType().equals(ResolvedTypeX.VOID)) {
kind = Shadow.FieldSet;
} else {
kind = Shadow.FieldGet;
}
match(BcelShadow.makeShadowForMethodCall(world, mg, ih, enclosingShadow,
kind, declaredSig),
shadowAccumulator);
} else {
AjAttribute.EffectiveSignatureAttribute effectiveSig =
declaredSig.getEffectiveSignature();
if (effectiveSig == null) return;
//System.err.println("call to inter-type member: " + effectiveSig);
if (effectiveSig.isWeaveBody()) return;
match(BcelShadow.makeShadowForMethodCall(world, mg, ih, enclosingShadow,
effectiveSig.getShadowKind(), effectiveSig.getEffectiveSignature()),
shadowAccumulator);
}
} else {
match(
BcelShadow.makeMethodCall(world, mg, ih, enclosingShadow),
shadowAccumulator);
}
}
private boolean match(BcelShadow shadow, List shadowAccumulator) {
//System.err.println("match: " + shadow);
boolean isMatched = false;
for (Iterator i = shadowMungers.iterator(); i.hasNext(); ) {
ShadowMunger munger = (ShadowMunger)i.next();
if (munger.match(shadow, world)) {
shadow.addMunger(munger);
isMatched = true;
}
}
if (isMatched) shadowAccumulator.add(shadow);
return isMatched;
}
// ----
private void implement(LazyMethodGen mg) {
List shadows = mg.matchedShadows;
if (shadows == null) return;
// We depend on a partial order such that inner shadows are earlier on the list
// than outer shadows. That's fine. This order is preserved if:
// A preceeds B iff B.getStart() is LATER THAN A.getStart().
for (Iterator i = shadows.iterator(); i.hasNext(); ) {
BcelShadow shadow = (BcelShadow)i.next();
shadow.implement();
}
mg.matchedShadows = null;
}
// ----
public LazyClassGen getLazyClassGen() {
return clazz;
}
public List getShadowMungers() {
return shadowMungers;
}
public BcelWorld getWorld() {
return world;
}
}
|
38,824
|
Bug 38824 Anomalous handling of inter-type declarations to abstract base classes in aspectj 1.1
|
Version 1.1 of aspectj does not handle correctly inter-type declarations to abstract base classes. This appears when the following pattern is present in the code: Suppose there is an interface InterfaceA, another interface InterfaceB and a third interface InterfaceC extending InterfaceA and InterfaceB and containing some method declarations of its own. Suppose also there is an aspect AConcretisingAspect that contains inter-type declarations providing default implementations for all InterfaceC's methods (both own and inherited). Now suppose we have a class hierarchy emanating from an abstract class BaseClass, and an aspect BaseClassAspect declaring that BaseClass implements InterfaceC: aspect BaseClassAspect { declare parents: BaseClass implements InterfaceC; } Unfortunately, during compilation iajc complains for each offspring of BaseClass that it does not implement any of the abstract methods of InterfaceA and InterfaceB (but not of InterfaceC's own!). This does not happen when BaseClass is not abstract; and it does not occur in version 1.0.6 of aspectj.
|
resolved fixed
|
0071cb4
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-14T15:51:53Z
| 2003-06-12T09:26: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.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.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.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.getInterTypeMungers().iterator(); i.hasNext(); ) {
ConcreteTypeMunger m = (ConcreteTypeMunger)i.next();
if (m.matches(onTypeX)) {
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.currentThread().dumpStack();
}
super.handle(
problemId,
problemArguments,
messageArguments,
severity,
problemStartPosition,
problemEndPosition,
referenceContext,
unitResult);
}
}
|
38,824
|
Bug 38824 Anomalous handling of inter-type declarations to abstract base classes in aspectj 1.1
|
Version 1.1 of aspectj does not handle correctly inter-type declarations to abstract base classes. This appears when the following pattern is present in the code: Suppose there is an interface InterfaceA, another interface InterfaceB and a third interface InterfaceC extending InterfaceA and InterfaceB and containing some method declarations of its own. Suppose also there is an aspect AConcretisingAspect that contains inter-type declarations providing default implementations for all InterfaceC's methods (both own and inherited). Now suppose we have a class hierarchy emanating from an abstract class BaseClass, and an aspect BaseClassAspect declaring that BaseClass implements InterfaceC: aspect BaseClassAspect { declare parents: BaseClass implements InterfaceC; } Unfortunately, during compilation iajc complains for each offspring of BaseClass that it does not implement any of the abstract methods of InterfaceA and InterfaceB (but not of InterfaceC's own!). This does not happen when BaseClass is not abstract; and it does not occur in version 1.0.6 of aspectj.
|
resolved fixed
|
0071cb4
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-14T15:51:53Z
| 2003-06-12T09:26:40Z
|
tests/bugs/AbstractBaseAndInterTypeInterface.java
| |
38,824
|
Bug 38824 Anomalous handling of inter-type declarations to abstract base classes in aspectj 1.1
|
Version 1.1 of aspectj does not handle correctly inter-type declarations to abstract base classes. This appears when the following pattern is present in the code: Suppose there is an interface InterfaceA, another interface InterfaceB and a third interface InterfaceC extending InterfaceA and InterfaceB and containing some method declarations of its own. Suppose also there is an aspect AConcretisingAspect that contains inter-type declarations providing default implementations for all InterfaceC's methods (both own and inherited). Now suppose we have a class hierarchy emanating from an abstract class BaseClass, and an aspect BaseClassAspect declaring that BaseClass implements InterfaceC: aspect BaseClassAspect { declare parents: BaseClass implements InterfaceC; } Unfortunately, during compilation iajc complains for each offspring of BaseClass that it does not implement any of the abstract methods of InterfaceA and InterfaceB (but not of InterfaceC's own!). This does not happen when BaseClass is not abstract; and it does not occur in version 1.0.6 of aspectj.
|
resolved fixed
|
0071cb4
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-14T15:51:53Z
| 2003-06-12T09:26:40Z
|
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.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;
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.resolve(CLONEABLE),
world.resolve(SERIALIZABLE)
};
}
public final ResolvedMember[] getDeclaredPointcuts() {
return ResolvedMember.NONE;
}
public final ResolvedTypeX getSuperclass() {
return world.resolve(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;
}
private List getInterTypeMungersIncludingSupers() {
ArrayList ret = new ArrayList();
collectInterTypeMungers(ret);
return ret;
}
/**
* ??? This method is O(N*M) where N = number of methods and M is number of
* inter-type declarations in my super
*/
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 that we don't have any abstract type mungers unless this
* type is abstract.
*/
public void checkInterTypeMungers() {
if (isAbstract()) return;
for (Iterator iter = getInterTypeMungersIncludingSupers().iterator(); iter.hasNext();) {
ConcreteTypeMunger element = (ConcreteTypeMunger) iter.next();
if (element.getSignature() != null && element.getSignature().isAbstract()) {
world.getMessageHandler().handleMessage(
new Message("must implement abstract inter-type declaration: " + element.getSignature(),
"", IMessage.ERROR, getSourceLocation(), null,
new ISourceLocation[] { element.getSourceLocation() }));
}
}
}
/**
* 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.resolve(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();
if (conflictingSignature(existingMember, munger.getSignature())) {
//System.err.println("conflict: " + existingMember + " with " + 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("inter-type declaration from " + munger.getAspectType().getName() +
" conflicts with existing member: " + existingMember,
munger.getSourceLocation())
);
}
} else {
//interTypeMungers.add(munger);
}
//return;
}
}
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,
"can't override " + parent +
" with " + child + " return types don't match",
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,
"can't override " + parent +
" with " + child + " parameter types don't match",
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,
"can't override " + parent +
" with " + child + " visibility is reduced",
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, "overriden method doesn't throw "
+ childExceptions[i].getName(), child.getSourceLocation(), null);
return false;
}
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,
"intertype declaration from "
+ m1.getAspectType().getName()
+ " conflicts with intertype declaration: "
+ m2.getSignature()
+ " from "
+ 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 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,
"inherited abstract " + inherited +
" is not made concrete in " + 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,
"conflicting inherited pointcuts in "
+ 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;
}
}
|
47,952
|
Bug 47952 SoftException.printStackTrace(..) should print wrapped throwable too
|
SoftExceptions should print not only their trace but also that of the wrapped throwable. We should be able to set a flag on class initialization whether we are running under 1.4 and then implement it under 1.4 using initCause() and otherwise by direct delegation. I can do this fix if we're agreed.
|
resolved fixed
|
ad2fb7a
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-15T05:21:33Z
| 2003-12-03T05:40:00Z
|
runtime/src/org/aspectj/lang/SoftException.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.lang;
/**
* Wrapper for checked exceptions matched by a 'declare soft'.
* You can soften checked exceptions at join points by using
* the form <code>declare soft: TypePattern: Pointcut</code>.
* At the join points, any exceptions thrown which match
* TypePattern will be wrapped in <code>SoftException</code>
* and rethrown. You can get the original exception using
* <code>getWrappedThrowable()</code>.
*/
public class SoftException extends RuntimeException {
Throwable inner;
public SoftException(Throwable inner) {
super();
this.inner = inner;
}
public Throwable getWrappedThrowable() { return inner; }
public Throwable getCause() { return inner; }
}
|
47,952
|
Bug 47952 SoftException.printStackTrace(..) should print wrapped throwable too
|
SoftExceptions should print not only their trace but also that of the wrapped throwable. We should be able to set a flag on class initialization whether we are running under 1.4 and then implement it under 1.4 using initCause() and otherwise by direct delegation. I can do this fix if we're agreed.
|
resolved fixed
|
ad2fb7a
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-15T05:21:33Z
| 2003-12-03T05:40:00Z
|
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 org.aspectj.lang.NoAspectBoundException;
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)
return suite;
}
public RuntimeModuleTests(String name) { super(name); }
public void testNothing() {}
public void testNoAspectBoundException() {
RuntimeException fun = new RuntimeException("fun");
NoAspectBoundException nab = new NoAspectBoundException("Foo", fun);
assertEquals(fun,nab.getCause());
}
}
|
36,234
|
Bug 36234 out of memory error when compiling
|
Getting an out of memory error when compiling with Ajc 1.1 RC1. I know this is not very descriptive, but maybe you can point me into a direction of getting more output. here some additional information though: Code base is medium size (about 1500 classfiles) I removed all my aspects and still receive the error. Running it from the command line: ajc -classpath whateveritis -sourceroots whateveritis -d whateveritis
|
resolved fixed
|
b3b1eec
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-15T11:43:14Z
| 2003-04-08T19:26:40Z
|
org.aspectj.ajdt.core/src/org/aspectj/tools/ajc/Main.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.tools.ajc;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.List;
import org.aspectj.ajdt.ajc.BuildArgParser;
import org.aspectj.bridge.AbortException;
import org.aspectj.bridge.ICommand;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.IMessageHandler;
import org.aspectj.bridge.IMessageHolder;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.Message;
import org.aspectj.bridge.MessageHandler;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.bridge.ReflectionFactory;
import org.aspectj.bridge.Version;
import org.aspectj.util.FileUtil;
import org.aspectj.util.LangUtil;
/**
* Programmatic and command-line interface to AspectJ compiler.
* The compiler is an ICommand obtained by reflection.
* Not thread-safe.
* By default, messages are printed as they are emitted;
* info messages go to the output stream, and
* warnings and errors go to the error stream.
* <p>
* Clients can handle all messages by registering a holder:
* <pre>Main main = new Main();
* IMessageHolder holder = new MessageHandler();
* main.setHolder(holder);</pre>
* Clients can get control after each command completes
* by installing a Runnable:
* <pre>main.setCompletionRunner(new Runnable() {..});</pre>
*
*/
public class Main {
/** Header used when rendering exceptions for users */
public static final String THROWN_PREFIX
= "Exception thrown from AspectJ "+ Version.text + LangUtil.EOL
+ ""+ LangUtil.EOL
+ "This might be logged as a bug already -- find current bugs at" + LangUtil.EOL
+ " http://bugs.eclipse.org/bugs/buglist.cgi?product=AspectJ&component=Compiler" + LangUtil.EOL
+ "" + LangUtil.EOL
+ "Bugs for exceptions thrown have titles File:line from the top stack, " + LangUtil.EOL
+ "e.g., \"SomeFile.java:243\"" + LangUtil.EOL
+ "" + LangUtil.EOL
+ "If you don't find the exception below in a bug, please add a new bug" + LangUtil.EOL
+ "at http://bugs.eclipse.org/bugs/enter_bug.cgi?product=AspectJ" + LangUtil.EOL
+ "To make the bug a priority, please include a test program" + LangUtil.EOL
+ "that can reproduce this exception." + LangUtil.EOL;
/** @param args the String[] of command-line arguments */
public static void main(String[] args) throws IOException {
new Main().runMain(args, true);
}
/**
* @return String rendering throwable as compiler error for user/console,
* including information on how to report as a bug.
* @throws NullPointerException if thrown is null
*/
public static String renderExceptionForUser(Throwable thrown) {
String m = thrown.getMessage();
return THROWN_PREFIX
+ (null != m ? m + "\n": "")
+ LangUtil.renderException(thrown, true);
}
/** append nothing if numItems is 0,
* numItems + label + (numItems > 1? "s" : "") otherwise,
* prefixing with " " if sink has content
*/
private static void appendNLabel(StringBuffer sink, String label, int numItems) {
if (0 == numItems) {
return;
}
if (0 < sink.length()) {
sink.append(", ");
}
sink.append(numItems + " ");
if (!LangUtil.isEmpty(label)) {
sink.append(label);
}
if (1 < numItems) {
sink.append("s");
}
}
/** control iteration/continuation for command (compiler) */
protected CommandController controller;
/** ReflectionFactory identifier for command (compiler) */
protected String commandName;
/** client-set message sink */
private IMessageHolder clientHolder;
/** internally-set message sink */
protected final MessageHandler ourHandler;
private int lastFails;
private int lastErrors;
/** if not null, run this synchronously after each compile completes */
private Runnable completionRunner;
public Main() {
controller = new CommandController();
commandName = ReflectionFactory.ECLIPSE;
ourHandler = new MessageHandler(true);
}
/**
* Run without throwing exceptions but optionally using System.exit(..).
* This sets up a message handler which emits messages immediately,
* so report(boolean, IMessageHandler) only reports total number
* of errors or warnings.
* @param args the String[] command line for the compiler
* @param useSystemExit if true, use System.exit(int) to complete
* unless one of the args is -noExit.
* and signal result (0 no exceptions/error, <0 exceptions, >0 compiler errors).
*/
public void runMain(String[] args, boolean useSystemExit) {
boolean verbose = (-1 != ("" + LangUtil.arrayAsList(args)).indexOf("-verbose"));
IMessageHolder holder = clientHolder;
if (null == holder) {
holder = ourHandler;
if (verbose) {
ourHandler.setInterceptor(MessagePrinter.VERBOSE);
} else {
ourHandler.ignore(IMessage.INFO);
ourHandler.setInterceptor(MessagePrinter.TERSE);
}
}
run(args, holder);
boolean skipExit = false;
if (useSystemExit && !LangUtil.isEmpty(args)) { // sigh - pluck -noExit
for (int i = 0; i < args.length; i++) {
if ("-noExit".equals(args[i])) {
skipExit = true;
break;
}
}
}
if (useSystemExit && !skipExit) {
systemExit(holder);
}
}
/**
* Run without using System.exit(..), putting all messages in holder:
* <ul>
* <li>ERROR: compiler error</li>
* <li>WARNING: compiler warning</li>
* <li>FAIL: command error (bad arguments, exception thrown)</li>
* </ul>
* This handles incremental behavior:
* <ul>
* <li>If args include "-incremental", repeat for every input char
* until 'q' is entered.<li>
* <li>If args include "-incrementalTagFile {file}", repeat every time
* we detect that {file} modification time has changed. </li>
* <li>Either way, list files recompiled each time if args includes "-verbose".</li>
* <li>Exit when the commmand/compiler throws any Throwable.</li>
* </ul>
* When complete, this contains all the messages of the final
* run of the command and/or any FAIL messages produced in running
* the command, including any Throwable thrown by the command itself.
*
* @param args the String[] command line for the compiler
* @param holder the MessageHandler sink for messages.
*/
public void run(String[] args, IMessageHolder holder) {
if (LangUtil.isEmpty(args)) {
args = new String[] { "-help" };
} else if (controller.running()) {
fail(holder, "already running with controller: " + controller, null);
return;
}
args = controller.init(args, holder);
if (0 < holder.numMessages(IMessage.ERROR, true)) {
return;
}
ICommand command = ReflectionFactory.makeCommand(commandName, holder);
if (0 < holder.numMessages(IMessage.ERROR, true)) {
return;
}
try {
boolean verbose = (-1 != ("" + Arrays.asList(args)).indexOf("-verbose"));
outer:
while (true) {
boolean passed = command.runCommand(args, holder);
if (report(passed, holder) && controller.incremental()) {
final boolean onCommandLine = controller.commandLineIncremental();
while (controller.doRepeatCommand()) {
holder.clearMessages();
if (controller.buildFresh()) {
continue outer;
} else {
passed = command.repeatCommand(holder);
}
if (!report(passed, holder)) {
break;
}
}
}
break;
}
} catch (AbortException ae) {
if (ae.isSilent()) {
quit();
} else {
IMessage message = ae.getIMessage();
Throwable thrown = ae.getThrown();
if (null == thrown) { // toss AbortException wrapper
if (null != message) {
holder.handleMessage(message);
} else {
fail(holder, "abort without message", ae);
}
} else if (null == message) {
fail(holder, "aborted", thrown);
} else {
String mssg = MessageUtil.MESSAGE_MOST.renderToString(message);
fail(holder, mssg, thrown);
}
}
} catch (Throwable t) {
fail(holder, "unexpected exception", t);
}
}
/** call this to stop after the next iteration of incremental compile */
public void quit() {
controller.quit();
}
/**
* Set holder to be passed all messages.
* When holder is set, messages will not be printed by default.
* @param holder the IMessageHolder sink for all messages
* (use null to restore default behavior)
*/
public void setHolder(IMessageHolder holder) {
clientHolder = holder;
}
/**
* Install a Runnable to be invoked synchronously
* after each compile completes.
* @param runner the Runnable to invoke - null to disable
*/
public void setCompletionRunner(Runnable runner) {
this.completionRunner = runner;
}
/**
* Call System.exit(int) with values derived from the number
* of failures/aborts or errors in messages.
* @param messages the IMessageHolder to interrogate.
* @param messages
*/
protected void systemExit(IMessageHolder messages) {
int num = lastFails; // messages.numMessages(IMessage.FAIL, true);
if (0 < num) {
System.exit(-num);
}
num = lastErrors; // messages.numMessages(IMessage.ERROR, false);
if (0 < num) {
System.exit(num);
}
System.exit(0);
}
/** Messages to the user */
protected void outMessage(String message) { // XXX coordinate with MessagePrinter
System.out.print(message);
System.out.flush();
}
/**
* Report results from a (possibly-incremental) compile run.
* This delegates to any reportHandler or otherwise
* prints summary counts of errors/warnings to System.err (if any errors)
* or System.out (if only warnings).
* WARNING: this silently ignores other messages like FAIL,
* but clears the handler of all messages when returning true. XXX false
*
* This implementation ignores the pass parameter but
* clears the holder after reporting
* on the assumption messages were handled/printed already.
* (ignoring UnsupportedOperationException from holder.clearMessages()).
* @param pass true result of the command
* @param holder IMessageHolder with messages from the command
* @see reportCommandResults(IMessageHolder)
* @return false if the process should abort
*/
protected boolean report(boolean pass, IMessageHolder holder) {
lastFails = holder.numMessages(IMessage.FAIL, true);
boolean result = (0 == lastFails);
final Runnable runner = completionRunner;
if (null != runner) {
runner.run();
}
if (holder == ourHandler) {
lastErrors = holder.numMessages(IMessage.ERROR, false);
int warnings = holder.numMessages(IMessage.WARNING, false);
StringBuffer sb = new StringBuffer();
appendNLabel(sb, "fail|abort", lastFails);
appendNLabel(sb, "error", lastErrors);
appendNLabel(sb, "warning", warnings);
if (0 < sb.length()) {
PrintStream out = (0 < (lastErrors + lastFails)
? System.err
: System.out);
out.println(""); // XXX "wrote class file" messages no eol?
out.println(sb.toString());
}
}
return result;
}
/** convenience API to make fail messages (without MessageUtils's fail prefix) */
protected static void fail(IMessageHandler handler, String message, Throwable thrown) {
handler.handleMessage(new Message(message, IMessage.FAIL, thrown, null));
}
/**
* interceptor IMessageHandler to print as we go.
* This formats all messages to the user.
*/
public static class MessagePrinter implements IMessageHandler {
public static final IMessageHandler VERBOSE
= new MessagePrinter(true);
public static final IMessageHandler TERSE
= new MessagePrinter(false);
final boolean verbose;
protected MessagePrinter(boolean verbose) {
this.verbose = verbose;
}
/**
* Print errors and warnings to System.err,
* and optionally info to System.out,
* rendering message String only.
* @return false always
*/
public boolean handleMessage(IMessage message) {
if (null != message) {
PrintStream out = getStreamFor(message.getKind());
if (null != out) {
out.println(render(message));
}
}
return false;
}
/**
* Render message differently.
* If abort, then prefix stack trace with feedback request.
* If the actual message is empty, then use toString on the whole.
* Prefix message part with file:line;
* If it has context, suffix message with context.
* @param message the IMessage to render
* @return String rendering IMessage (never null)
*/
protected String render(IMessage message) {
IMessage.Kind kind = message.getKind();
StringBuffer sb = new StringBuffer();
String text = message.getMessage();
if (text.equals(AbortException.NO_MESSAGE_TEXT)) {
text = null;
}
boolean toString = (LangUtil.isEmpty(text));
if (toString) {
text = message.toString();
}
ISourceLocation loc = message.getSourceLocation();
String context = null;
if (null != loc) {
File file = loc.getSourceFile();
if (null != file) {
String name = file.getName();
if (!toString || (-1 == text.indexOf(name))) {
sb.append(FileUtil.getBestPath(file));
sb.append(":" + loc.getLine());
int col = loc.getColumn();
if (0 < col) {
sb.append(":" + col);
}
sb.append(" ");
}
}
context = loc.getContext();
}
sb.append(text);
if (null != context) {
sb.append(LangUtil.EOL);
sb.append(context);
}
Throwable thrown = message.getThrown();
if (null != thrown) {
sb.append(LangUtil.EOL);
sb.append(Main.renderExceptionForUser(thrown));
}
if (message.getExtraSourceLocations().isEmpty()) {
return sb.toString();
} else {
return MessageUtil.addExtraSourceLocations(message, sb.toString());
}
}
public boolean isIgnoring(IMessage.Kind kind) {
return (null != getStreamFor(kind));
}
/** @return System.err for FAIL, ABORT, ERROR, and WARNING,
* System.out for INFO if verbose.
*/
protected PrintStream getStreamFor(IMessage.Kind kind) {
if (IMessage.WARNING.isSameOrLessThan(kind)) {
return System.err;
} else if (verbose && IMessage.INFO.equals(kind)) {
return System.out;
} else {
return null;
}
}
}
/** controller for repeatable command delays until input or file changed or removed */
public static class CommandController {
public static String TAG_FILE_OPTION = "-XincrementalFile";
public static String INCREMENTAL_OPTION = "-incremental";
/** maximum 10-minute delay between filesystem checks */
public static long MAX_DELAY = 1000 * 600;
/** default 5-second delay between filesystem checks */
public static long DEFAULT_DELAY = 1000 * 5;
/** @see init(String[]) */
private static String[][] OPTIONS = new String[][]
{ new String[] { INCREMENTAL_OPTION },
new String[] { TAG_FILE_OPTION, null } };
/** true between init(String[]) and doRepeatCommand() that returns false */
private boolean running;
/** true after quit() called */
private boolean quit;
/** true if incremental mode, waiting for input other than 'q' */
private boolean incremental;
/** true if incremental mode, waiting for file to change (repeat) or disappear (quit) */
private File tagFile;
/** last modification time for tagFile as of last command - 0 to start */
private long fileModTime;
/** delay between filesystem checks for tagFile modification time */
private long delay;
/** true just after user types 'r' for rebuild */
private boolean buildFresh;
public CommandController() {
delay = DEFAULT_DELAY;
}
/**
* @param argList read and strip incremental args from this
* @param sink IMessageHandler for error messages
* @return String[] remainder of args
*/
public String[] init(String[] args, IMessageHandler sink) {
running = true;
String[] unused;
if (!LangUtil.isEmpty(args)) {
String[][] options = LangUtil.copyStrings(OPTIONS);
unused = LangUtil.extractOptions(args, options);
incremental = (null != options[0][0]);
if (null != options[1][0]) {
File file = new File(options[1][1]);
if (!file.exists()) {
MessageUtil.abort(sink, "tag file does not exist: " + file);
} else {
tagFile = file;
fileModTime = tagFile.lastModified();
}
}
}
return args;
}
/** @return true if init(String[]) called but doRepeatCommand has not
* returned false */
public boolean running() {
return running;
}
/** @param delay milliseconds between filesystem checks */
public void setDelay(long delay) {
if ((delay > -1) && (delay < MAX_DELAY)) {
this.delay = delay;
}
}
/** @return true if INCREMENTAL_OPTION or TAG_FILE_OPTION was in args */
public boolean incremental() {
return (incremental || (null != tagFile));
}
/** @return true if INCREMENTAL_OPTION was in args */
public boolean commandLineIncremental() {
return incremental;
}
public void quit() {
if (!quit) {
quit = true;
}
}
/** @return true just after user typed 'r' */
boolean buildFresh() {
return buildFresh;
}
/** @return false if we should quit, true to do another command */
boolean doRepeatCommand() {
if (!running) {
return false;
}
boolean result = false;
if (quit) {
result = false;
} else if (incremental) {
try {
if (buildFresh) { // reset before input request
buildFresh = false;
}
System.out.println(" press enter to recompile, r to rebuild, q to quit: ");
System.out.flush();
boolean doMore = false;
// seek for one q or a series of [\n\r]...
do {
int input = System.in.read();
if ('q' == input) {
break; // result = false;
} else if ('r' == input) {
buildFresh = true;
result = true;
} else if (('\n' == input) || ('\r' == input)) {
result = true;
} // else eat anything else
} while (!result);
System.in.skip(Integer.MAX_VALUE);
} catch (IOException e) { // XXX silence for error?
result = false;
}
} else if (null != tagFile) {
long curModTime;
while (true) {
if (!tagFile.exists()) {
result = false;
break;
} else if (fileModTime == (curModTime = tagFile.lastModified())) {
fileCheckDelay();
} else {
fileModTime = curModTime;
result = true;
break;
}
}
} // else, not incremental - false
if (!result && running) {
running = false;
}
return result;
}
/** delay between filesystem checks, returning if quit is set */
protected void fileCheckDelay() {
final Thread thread = Thread.currentThread();
long targetTime = System.currentTimeMillis() + delay;
long curTime;
while (targetTime > (curTime = System.currentTimeMillis())) {
if (quit) {
return;
}
try { Thread.sleep(300); } // 1/3-second delta for quit check
catch (InterruptedException e) {}
}
}
}
}
|
42,515
|
Bug 42515 NPE When compiling intertype declaration
| null |
resolved fixed
|
6d2abc1
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-15T12:50:59Z
| 2003-09-04T10:06:40Z
|
tests/bugs/caseSensitivity/uniqueId/Numbered.java
| |
50,200
|
Bug 50200 aspectjrt.jar manifest file name needs changing to upper case
| null |
resolved fixed
|
6f099df
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-22T10:55:43Z
| 2004-01-19T11:00:00Z
|
build/src/org/aspectj/internal/tools/ant/taskdefs/AntBuilder.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:
* Xerox/PARC initial implementation
* ******************************************************************/
package org.aspectj.internal.tools.ant.taskdefs;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Target;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.taskdefs.Copy;
import org.apache.tools.ant.taskdefs.Javac;
import org.apache.tools.ant.taskdefs.Zip;
import org.apache.tools.ant.types.FileSet;
import org.apache.tools.ant.types.Path;
import org.apache.tools.ant.types.ZipFileSet;
import org.aspectj.internal.tools.build.BuildSpec;
import org.aspectj.internal.tools.build.Builder;
import org.aspectj.internal.tools.build.Messager;
import org.aspectj.internal.tools.build.Module;
import org.aspectj.internal.tools.build.Modules;
import org.aspectj.internal.tools.build.ProductModule;
import org.aspectj.internal.tools.build.Util;
/**
* Implement Builder in Ant.
*/
public class AntBuilder extends Builder {
/*
* XXX This just constructs and uses Ant Task objects,
* which in some cases causes the tasks to fail.
*/
/**
* Factory for a Builder.
* @param config the String configuration, where only substrings
* "verbose" and "useEclipseCompiles" are significant
* @param project the owning Project for all tasks (not null)
* @param tempDir the File path to a temporary dir for side effects (may be null)
* @return a Builder for this project and configuration
*/
public static Builder getBuilder(String config, Project project, File tempDir) {
boolean useEclipseCompiles = false;
boolean verbose = false;
if (null != config) {
if (-1 != config.indexOf("useEclipseCompiles")) {
useEclipseCompiles = true;
}
if (-1 != config.indexOf("verbose")) {
verbose = true;
}
}
Messager handler = new ProjectMessager(project);
Builder result = new ProductBuilder(project, tempDir, useEclipseCompiles, handler);
if (verbose) {
result.setVerbose(true);
}
return result;
}
/**
* Make and register target for this module and antecedants.
* This ensures that the (direct) depends list is generated
* for each target.
* This depends on topoSort to detect cycles. XXX unverified
*/
private static void makeTargetsForModule(
final Module module,
final Hashtable targets,
final boolean rebuild) {
Target target = (Target) targets.get(module.name);
if (null == target) {
// first add the target
target = new Target();
target.setName(module.name);
List req = module.getRequired();
StringBuffer depends = new StringBuffer();
boolean first = true;
for (Iterator iterator = req.iterator(); iterator.hasNext();) {
Module reqModule = (Module) iterator.next();
if (rebuild || reqModule.outOfDate(false)) {
if (!first) {
depends.append(",");
} else {
first = false;
}
depends.append(reqModule.name);
}
}
if (0 < depends.length()) {
target.setDepends(depends.toString());
}
targets.put(module.name, target);
// then recursively add any required modules
for (Iterator iterator = module.getRequired().iterator();
iterator.hasNext();
) {
Module reqModule = (Module) iterator.next();
if (rebuild || reqModule.outOfDate(false)) {
makeTargetsForModule(reqModule, targets, rebuild);
}
}
}
}
private final Project project; // XXX s.b. used only in setupTask
protected AntBuilder(Project project, File tempDir, boolean useEclipseCompiles,
Messager handler) {
super(tempDir, useEclipseCompiles, handler);
this.project = project;
Util.iaxIfNull(project, "project");
}
/**
* Initialize task with project and "ajbuild-" + name as name. (Using bm-
* prefix distinguishes these tasks from tasks found in the build script.)
* @param task the Task to initialize - not null
* @param name the String name suffix for the task
* @return true unless some error
*/
protected boolean setupTask(Task task, String name) {
task.setProject(project);
task.setTaskName("ajbuild-" + name);
return true;
}
/**
* Copy file, optionally filtering.
* (Filters set in project.)
* @param fromFile the readable File source to copy
* @param toFile the writable File destination file
* @param boolean filter if true, enable filtering
* @see org.aspectj.internal.tools.build.Builder#copyFile(File, File, boolean)
*/
protected boolean copyFile(File fromFile, File toFile, boolean filter) {
Copy copy = makeCopyTask(filter);
copy.setFile(fromFile);
copy.setTofile(toFile);
executeTask(copy);
return true;
}
/**
* (Filters set in project.)
* @see org.aspectj.internal.tools.ant.taskdefs.Builder#copyFiles(File, File, String, String, boolean)
*/
protected boolean copyFiles(
File fromDir,
File toDir,
String includes,
String excludes,
boolean filter) {
Copy copy = makeCopyTask(filter);
copy.setTodir(toDir);
FileSet fileset = new FileSet();
fileset.setDir(fromDir);
if (null != includes) {
fileset.setIncludes(includes);
}
if (null != excludes) {
fileset.setExcludes(excludes);
}
copy.addFileset(fileset);
executeTask(copy);
return false;
}
protected void copyFileset(File toDir, FileSet fileSet, boolean filter) {
Copy copy = makeCopyTask(filter);
copy.addFileset(fileSet);
copy.setTodir(toDir);
executeTask(copy);
}
/**
* @param filter if FILTER_ON, use filters
*/
protected Copy makeCopyTask(boolean filter) {
Copy copy = new Copy();
setupTask(copy, "copy");
if (FILTER_ON == filter) {
copy.setFiltering(true);
}
return copy;
}
protected boolean compile(
Module module,
File classesDir,
boolean useExistingClasses,
List errors) {
// -- source paths
Path path = new Path(project);
boolean hasSourceDirectories = false;
for (Iterator iter = module.getSrcDirs().iterator(); iter.hasNext();) {
File file = (File) iter.next();
path.createPathElement().setLocation(file);
if (!hasSourceDirectories) {
hasSourceDirectories = true;
}
}
if (!classesDir.exists() && !classesDir.mkdirs()) {
errors.add("compile - unable to create " + classesDir);
return false;
}
if (!hasSourceDirectories) { // none - dump minimal file and exit
File minFile = new File(classesDir, module.name);
FileWriter fw = null;
try {
fw = new FileWriter(minFile);
fw.write(module.name);
} catch (IOException e) {
errors.add("IOException writing "
+ module.name
+ " to "
+ minFile
+ ": "
+ Util.renderException(e));
} finally {
Util.close(fw);
}
return true; // nothing to compile - ok
}
if (useExistingClasses) {
return true;
}
// XXX test whether build.compiler property takes effect automatically
// I suspect it requires the proper adapter setup.
Javac javac = new Javac();
setupTask(javac, "javac");
javac.setDestdir(classesDir);
javac.setSrcdir(path);
path = null;
// -- classpath
Path classpath = new Path(project);
boolean hasLibraries = setupClasspath(module, classpath);
// need to add system classes??
boolean inEclipse = true; // XXX detect, fork only in eclipse
if (hasLibraries && inEclipse) {
javac.setFork(true); // XXX otherwise never releases library jars
}
// -- set output directory
classpath.createPathElement().setLocation(classesDir);
javac.setClasspath(classpath);
// misc
javac.setDebug(true);
javac.setTarget("1.1"); // 1.1 class files - Javac in 1.4 uses 1.4
// compile
try {
return executeTask(javac);
} catch (BuildException e) {
String args = "" + Arrays.asList(javac.getCurrentCompilerArgs());
errors.add("BuildException compiling " + module.toLongString() + args
+ ": " + Util.renderException(e));
return false;
} finally {
javac.init(); // be nice to let go of classpath libraries...
}
}
public boolean setupClasspath(Module module, Path classpath) { // XXX fix test access
boolean hasLibraries = false;
// required libraries
for (Iterator iter = module.getLibJars().iterator(); iter.hasNext();) {
File file = (File) iter.next();
classpath.createPathElement().setLocation(file);
if (!hasLibraries) {
hasLibraries = true;
}
}
// required modules and their exported libraries
for (Iterator iter = module.getRequired().iterator(); iter.hasNext();) {
Module required = (Module) iter.next();
classpath.createPathElement().setLocation(required.getModuleJar());
if (!hasLibraries) {
hasLibraries = true;
}
// also put on classpath libraries exported from required module
// XXX exported modules not supported
for (Iterator iterator = required.getExportedLibJars().iterator();
iterator.hasNext();
) {
classpath.createPathElement().setLocation((File) iterator.next());
}
}
return hasLibraries;
}
/**
* Merge classes directory and any merge jars into module jar
* with any specified manifest file.
* META-INF directories are excluded.
*/
protected boolean assemble(Module module, File classesDir, List errors) {
if (!buildingEnabled) {
return false;
}
// ---- zip result up
Zip zip = new Zip();
setupTask(zip, "zip");
zip.setDestFile(module.getModuleJar());
ZipFileSet zipfileset = null;
// -- merge any resources in any of the src directories
for (Iterator iter = module.getSrcDirs().iterator(); iter.hasNext();) {
File srcDir = (File) iter.next();
zipfileset = new ZipFileSet();
zipfileset.setProject(project);
zipfileset.setDir(srcDir);
zipfileset.setIncludes(RESOURCE_PATTERN);
zip.addZipfileset(zipfileset);
}
// -- merge any merge jars
List mergeJars = module.getMerges();
final boolean useManifest = false;
if (0 < mergeJars.size()) {
for (Iterator iter = mergeJars.iterator(); iter.hasNext();) {
File mergeJar = (File) iter.next();
zipfileset = new ZipFileSet();
zipfileset.setProject(project);
zipfileset.setSrc(mergeJar);
zipfileset.setIncludes("**/*");
zipfileset.setExcludes("META-INF/manifest.mf"); // XXXFileLiteral
zipfileset.setExcludes("meta-inf/manifest.MF");
zipfileset.setExcludes("META-INF/MANIFEST.mf");
zipfileset.setExcludes("meta-inf/MANIFEST.MF");
zip.addZipfileset(zipfileset);
}
}
// merge classes; put any meta-inf/manifest.mf here
File metaInfDir = new File(classesDir, "META-INF");
Util.deleteContents(metaInfDir);
// -- manifest
File manifest = new File(module.moduleDir, module.name + ".mf.txt"); // XXXFileLiteral
if (Util.canReadFile(manifest)) {
if (Util.canReadDir(metaInfDir) || metaInfDir.mkdirs()) {
copyFile(manifest, new File(metaInfDir, "manifest.mf"), FILTER_ON); // XXXFileLiteral
} else {
errors.add("have manifest, but unable to create " + metaInfDir);
return false;
}
}
zipfileset = new ZipFileSet();
zipfileset.setProject(project);
zipfileset.setDir(classesDir);
zipfileset.setIncludes("**/*");
zip.addZipfileset(zipfileset);
try {
handler.log("assembling " + module + " in " + module.getModuleJar());
return executeTask(zip)
// zip returns true when it doesn't create zipfile
// because there are no entries to add, so verify done
&& Util.canReadFile(module.getModuleJar());
} catch (BuildException e) {
errors.add("BuildException zipping " + module + ": " + e.getMessage());
return false;
} finally {
module.clearOutOfDate();
}
}
/**
* @see org.aspectj.internal.tools.build.Builder#buildAntecedants(Module)
*/
protected String[] getAntecedantModuleNames(Module module, boolean rebuild) {
Hashtable targets = new Hashtable();
makeTargetsForModule(module, targets, rebuild);
// XXX bug: doc says topoSort returns String, but returns Target
Collection result = project.topoSort(module.name, targets);
// XXX is it topoSort that should detect cycles?
int size = result.size();
if (0 == result.size()) {
return new String[0];
}
ArrayList toReturn = new ArrayList();
for (Iterator iter = result.iterator(); iter.hasNext();) {
Target target = (Target) iter.next();
String name = target.getName();
if (null == name) {
throw new Error("null name?");
} else {
toReturn.add(name);
}
}
// topoSort always returns module.name
if ((1 == size)
&& module.name.equals(toReturn.get(0))
&& !module.outOfDate(false)) {
return new String[0];
}
return (String[]) toReturn.toArray(new String[0]);
}
/**
* Generate Module.assembledJar with merge of itself and all antecedants
*/
protected boolean assembleAll(Module module, Messager handler) {
if (!buildingEnabled) {
return false;
}
Util.iaxIfNull(module, "module");
Util.iaxIfNull(handler, "handler");
if (module.outOfDate(false)) {
throw new IllegalStateException("module out of date: " + module);
}
// ---- zip result up
Zip zip = new Zip();
setupTask(zip, "zip");
zip.setDestFile(module.getAssembledJar());
ZipFileSet zipfileset = null;
ArrayList known = module.findKnownJarAntecedants();
// -- merge any antecedents, less any manifest
for (Iterator iter = known.iterator(); iter.hasNext();) {
File jarFile = (File) iter.next();
zipfileset = new ZipFileSet();
zipfileset.setProject(project);
zipfileset.setSrc(jarFile);
zipfileset.setIncludes("**/*");
zipfileset.setExcludes("META-INF/MANIFEST.MF"); // XXXFileLiteral
zipfileset.setExcludes("META-INF/manifest.mf");
zipfileset.setExcludes("meta-inf/manifest.mf");
zipfileset.setExcludes("meta-inf/MANIFEST.MF");
zip.addZipfileset(zipfileset);
}
// merge the module jar itself, including same manifest (?)
zipfileset = new ZipFileSet();
zipfileset.setProject(project);
zipfileset.setSrc(module.getModuleJar());
zip.addZipfileset(zipfileset);
try {
handler.log("assembling all " + module + " in " + module.getAssembledJar());
if (verbose) {
handler.log("knownAntecedants: " + known);
}
return executeTask(zip);
} catch (BuildException e) {
handler.logException("BuildException zipping " + module, e);
return false;
} finally {
module.clearOutOfDate();
}
}
/**
* @see org.aspectj.internal.tools.ant.taskdefs.Builder#buildInstaller(BuildSpec, String)
*/
protected boolean buildInstaller(
BuildSpec buildSpec,
String targDirPath) {
return false;
}
/** task.execute() and any advice */
protected boolean executeTask(Task task) {
if (!buildingEnabled) {
return false;
}
task.execute();
return true;
}
}
// finally caught by failing to comply with proper ant initialization
// /**
// * Build a module that has a build script.
// * @param buildSpec the module to build
// * @param buildScript the script file
// * @throws BuildException if build fails
// */
// private void buildByScript(BuildSpec buildSpec, File buildScript)
// throws BuildException {
// Ant ant = new Ant();
// ant.setProject(getProject());
// ant.setAntfile(buildScript.getAbsolutePath());
// ant.setDescription("building module " + buildSpec.module);
// ant.setDir(buildScript.getParentFile());
// ant.setInheritAll(true);
// ant.setInheritRefs(false);
// ant.setLocation(getLocation());
// ant.setOwningTarget(getOwningTarget());
// // by convention, for build.xml, use module name to publish
// ant.setTarget(buildSpec.module);
// ant.setTaskName("ant");
// loadAntProperties(ant, buildSpec);
// ant.execute();
// }
//
// /** override definitions */
// private void loadAntProperties(Ant ant, BuildSpec buildSpec) {
// Property property = ant.createProperty();
// property.setName(BuildSpec.baseDir_NAME);
// property.setFile(buildSpec.baseDir);
// property = ant.createProperty();
// property.setName(buildSpec.distDir_NAME);
// property.setFile(buildSpec.distDir);
// property = ant.createProperty();
// property.setName(BuildSpec.tempDir_NAME);
// property.setFile(buildSpec.tempDir);
// property = ant.createProperty();
// property.setName(BuildSpec.jarDir_NAME);
// property.setFile(buildSpec.jarDir);
// property = ant.createProperty();
// property.setName(BuildSpec.stagingDir_NAME);
// property.setFile(buildSpec.stagingDir);
// }
/**
* Segregate product-building API's from module-building APIs for clarity.
* These are called by the superclass if the BuildSpec warrants.
* XXX extremely brittle/arbitrary assumptions.
* @see BuildModule for assumptions
*/
class ProductBuilder extends AntBuilder {
private static String getProductInstallResourcesSrc(BuildSpec buildSpec) {
final String resourcesName = "installer-resources"; // XXXFileLiteral
File dir = buildSpec.productDir.getParentFile();
String result = null;
if (null == dir) {
return "../../" + resourcesName;
}
dir = dir.getParentFile();
if (null == dir) {
return "../" + resourcesName;
} else {
dir = new File(dir, resourcesName);
return dir.getPath();
}
}
private static String getProductInstallerFileName(BuildSpec buildSpec) { // XXXFileLiteral
return "aspectj-"
+ buildSpec.productDir.getName()
+ "-"
+ Util.shortVersion(buildSpec.version)
+ ".jar";
}
/**
* Calculate name of main, typically InitialCap, and hence installer class.
* @return $$installer$$.org.aspectj." + ProductName + "Installer"
*/
private static String getProductInstallerMainClass(BuildSpec buildSpec) {
String productName = buildSpec.productDir.getName();
String initial = productName.substring(0, 1).toUpperCase();
productName = initial + productName.substring(1);
return "$installer$.org.aspectj." + productName + "Installer"; // XXXNameLiteral
}
/** @see Builder.getBuilder(String, Project, File) */
ProductBuilder(
Project project,
File tempDir,
boolean useEclipseCompiles,
Messager handler) {
super(project, tempDir, useEclipseCompiles, handler);
}
/**
* Build product by discovering any modules to build,
* building those, assembling the product distribution,
* and optionally creating an installer for it.
* @return true on success
*/
protected boolean buildProduct(BuildSpec buildSpec)
throws BuildException {
Util.iaxIfNull(buildSpec, "buildSpec");
// XXX if installer and not out of date, do not rebuild unless rebuild set
if (!buildSpec.trimTesting) {
buildSpec.trimTesting = true;
handler.log("testing trimmed for " + buildSpec);
}
Util.iaxIfNotCanReadDir(buildSpec.productDir, "productDir");
Util.iaxIfNotCanReadDir(buildSpec.baseDir, "baseDir");
Util.iaxIfNotCanWriteDir(buildSpec.distDir, "distDir");
// ---- discover modules to build, and build them
Modules modules = new Modules(
buildSpec.baseDir,
buildSpec.jarDir,
buildSpec.trimTesting,
handler);
ProductModule[] productModules = discoverModules(buildSpec.productDir, modules);
for (int i = 0; i < productModules.length; i++) {
if (buildSpec.verbose) {
handler.log("building product module " + productModules[i]);
}
if (!buildProductModule(productModules[i])) {
return false;
}
}
if (buildSpec.verbose) {
handler.log("assembling product module for " + buildSpec);
}
// ---- assemble product distribution
final String productName = buildSpec.productDir.getName();
final File targDir = new File(buildSpec.distDir, productName);
final String targDirPath = targDir.getPath();
if (targDir.canWrite()) {
Util.deleteContents(targDir);
}
if (!targDir.canWrite() && !targDir.mkdirs()) {
if (buildSpec.verbose) {
handler.log("buildProduct unable to create " + targDir);
}
return false;
}
// filter-copy everything but the binaries
Copy copy = makeCopyTask(true);
copy.setTodir(targDir);
File distDir = new File(buildSpec.productDir, "dist"); // XXXFileLiteral
Util.iaxIfNotCanReadDir(distDir, "product dist directory");
FileSet fileset = new FileSet();
fileset.setDir(distDir);
fileset.setExcludes(Builder.BINARY_SOURCE_PATTERN);
copy.addFileset(fileset);
if (!executeTask(copy)) {
return false;
}
// copy binaries (but not module flag files)
String excludes = null;
{
StringBuffer buf = new StringBuffer();
for (int i = 0; i < productModules.length; i++) {
if (0 < buf.length()) {
buf.append(",");
}
buf.append(productModules[i].relativePath);
}
if (0 < buf.length()) {
excludes = buf.toString();
}
}
copy = makeCopyTask(false);
copy.setTodir(targDir);
fileset = new FileSet();
fileset.setDir(distDir);
fileset.setIncludes(Builder.BINARY_SOURCE_PATTERN);
if (null != excludes) {
fileset.setExcludes(excludes);
}
copy.addFileset(fileset);
if (!executeTask(copy)) {
return false;
}
// copy binaries associated with module flag files
for (int i = 0; i < productModules.length; i++) {
ProductModule product = productModules[i];
String targPath = targDirPath + "/" + product.relativePath;
File jarFile = (product.assembleAll
? product.module.getAssembledJar()
: product.module.getModuleJar() );
copyFile(jarFile, new File(targPath), FILTER_OFF);
}
handler.log("created product in " + targDir);
// ---- create installer
if (buildSpec.createInstaller) {
return buildInstaller(buildSpec, targDirPath);
} else {
return true;
}
}
protected boolean buildInstaller(BuildSpec buildSpec, String targDirPath) {
if (buildSpec.verbose) {
handler.log("creating installer for " + buildSpec);
}
AJInstaller installer = new AJInstaller();
setupTask(installer, "installer");
installer.setBasedir(targDirPath);
//installer.setCompress();
File installSrcDir = new File(buildSpec.productDir, "install"); // XXXFileLiteral
Util.iaxIfNotCanReadDir(installSrcDir, "installSrcDir");
installer.setHtmlSrc(installSrcDir.getPath());
String resourcePath = getProductInstallResourcesSrc(buildSpec);
File resourceSrcDir = new File(resourcePath);
Util.iaxIfNotCanReadDir(resourceSrcDir, "resourceSrcDir");
installer.setResourcesSrc(resourcePath);
String name = getProductInstallerFileName(buildSpec);
File outFile = new File(buildSpec.jarDir, name);
installer.setZipfile(outFile.getPath());
installer.setMainclass(getProductInstallerMainClass(buildSpec));
installer.setInstallerclassjar(getBuildJar(buildSpec));
return executeTask(installer);
// -- test installer XXX
// create text setup file
// run installer with setup file
// cleanup installed product
}
private String getBuildJar(BuildSpec buildSpec) {
return buildSpec.baseDir.getPath()
+ "/lib/build/build.jar" ; // XXX
}
private Module moduleForReplaceFile(File replaceFile, Modules modules) {
String jarName = moduleAliasFor(replaceFile.getName().toLowerCase());
if (jarName.endsWith(".jar") || jarName.endsWith(".zip")) { // XXXFileLiteral
jarName = jarName.substring(0, jarName.length()-4);
} else {
throw new IllegalArgumentException("can only replace .[jar|zip]");
}
boolean assembleAll = jarName.endsWith("-all");
String name = (!assembleAll ? jarName : jarName.substring(0, jarName.length()-4));
return modules.getModule(name);
}
}
class ProjectMessager extends Messager {
private final Project project;
public ProjectMessager(Project project) {
Util.iaxIfNull(project, "project");
this.project = project;
}
public boolean log(String s) {
project.log(s);
return true;
}
public boolean error(String s) {
project.log(s, Project.MSG_ERR);
return true;
}
public boolean logException(String context, Throwable thrown) {
project.log(context + Util.renderException(thrown), Project.MSG_ERR);
return true;
}
}
|
48,072
|
Bug 48072 Complete relationship information in the structure model
|
Complete the set of relationships surfaced by the structure model (e.g. including support for declare parents etc.) - Mik you had a document listing the things yet to be done here?
|
resolved fixed
|
f24286d
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-23T10:03:14Z
| 2003-12-04T15: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 org.aspectj.ajdt.internal.compiler.AjCompiler;
import org.aspectj.ajdt.internal.compiler.lookup.*;
import org.aspectj.ajdt.internal.compiler.parser.AjParser;
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.weaver.World;
import org.aspectj.weaver.bcel.*;
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.problem.DefaultProblemFactory;
import org.eclipse.jdt.internal.compiler.util.HashtableOfObject;
public class AjBuildManager {
static final boolean FAIL_IF_RUNTIME_NOT_FOUND = false;
private IProgressListener progressListener = null;
private int compiledCount;
private int sourceFileCount;
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 {
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);
//}
setupModel();
if (batch) {
initBcelWorld(handler);
}
if (handler.hasErrors()) {
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?
}
performCompilation(buildConfig.getFiles());
if (handler.hasErrors()) {
return false;
}
} else {
// done already?
// if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) {
// bcelWorld.setModel(StructureModelManager.INSTANCE.getStructureModel());
// }
// System.err.println("XXXX start inc ");
List files = state.getFilesToCompile(true);
for (int i = 0; (i < 5) && !files.isEmpty(); i++) {
// System.err.println("XXXX inc: " + files);
performCompilation(files);
if (handler.hasErrors()) {
return false;
}
files = state.getFilesToCompile(false);
}
if (!files.isEmpty()) {
return batchBuild(buildConfig, baseHandler);
}
}
// 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);
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();
}
return !handler.hasErrors();
} finally {
handler = null;
}
}
private void setupModel() {
String rootLabel = "<root>";
IHierarchy model = AsmManager.getDefault().getHierarchy();
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);
}
/** init only on initial batch compile? no file-specific options */
private void initBcelWorld(IMessageHandler handler) throws IOException {
bcelWorld = new BcelWorld(buildConfig.getClasspath(), handler);
bcelWorld.setXnoInline(buildConfig.isXnoInline());
bcelWeaver = new BcelWeaver(bcelWorld);
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();
bcelWeaver.addJarFile(inJar, buildConfig.getOutputDir(),false);
}
for (Iterator i = buildConfig.getInpath().iterator(); i.hasNext(); ) {
File inPathElement = (File)i.next();
bcelWeaver.addJarFile(inPathElement,buildConfig.getOutputDir(),true);
}
if (buildConfig.getSourcePathResources() != null) {
for (Iterator i = buildConfig.getSourcePathResources().keySet().iterator(); i.hasNext(); ) {
// File resource = (File)i.next();
String resource = (String)i.next();
bcelWeaver.addResource(resource, (File)buildConfig.getSourcePathResources().get(resource), buildConfig.getOutputDir());
// bcelWeaver.addResource(resource, buildConfig.getOutputDir());
}
}
//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 = (String) buildConfig.getJavaOptions().get(CompilerOptions.OPTION_Encoding);
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 = (String) buildConfig.getJavaOptions().get(CompilerOptions.OPTION_Encoding);
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();
String[] classpaths = new String[cps.size()];
for (int i=0; i < cps.size(); i++) {
classpaths[i] = (String)cps.get(i);
}
//System.out.println("compiling");
INameEnvironment environment = getLibraryAccess(classpaths, filenames);
if (!state.classesFromName.isEmpty()) {
environment = new StatefulNameEnvironment(environment, state.classesFromName);
}
AjCompiler compiler = new AjCompiler(
environment,
DefaultErrorHandlingPolicies.proceedWithAllProblems(),
buildConfig.getJavaOptions(),
getBatchRequestor(),
getProblemFactory());
AjProblemReporter pr =
new AjProblemReporter(DefaultErrorHandlingPolicies.proceedWithAllProblems(),
compiler.options, getProblemFactory());
compiler.problemReporter = pr;
AjLookupEnvironment le =
new AjLookupEnvironment(compiler, compiler.options, pr, environment);
EclipseFactory factory = new EclipseFactory(le);
// ew.setLint(bcelWorld.getLint());
// ew.setXnoInline(buildConfig.isXnoInline());
le.factory = factory;
pr.factory = factory;
le.factory.buildManager = this;
compiler.lookupEnvironment = le;
compiler.parser =
new AjParser(
pr,
compiler.options.parseLiteralExpressionsAsConstants);
CompilerOptions options = compiler.options;
options.produceReferenceInfo(true); //TODO turn off when not needed
compiler.compile(getCompilationUnits(filenames, encodings));
// cleanup
environment.cleanup();
}
/*
* Answer the component to which will be handed back compilation results from the compiler
*/
public ICompilerRequestor getBatchRequestor() {
return new ICompilerRequestor() {
int lineDelta = 0;
public void acceptResult(CompilationResult compilationResult) {
if (progressListener != null) {
compiledCount++;
progressListener.setProgress((compiledCount/2.0)/sourceFileCount);
progressListener.setText("compiled: " + new String(compilationResult.getFileName()));
}
if (compilationResult.hasProblems() || compilationResult.hasTasks()) {
IProblem[] problems = compilationResult.getAllProblems();
for (int i=0; i < problems.length; i++) {
IMessage message =
EclipseAdapterUtils.makeMessage(compilationResult.compilationUnit, problems[i]);
handler.handleMessage(message);
}
}
outputClassFiles(compilationResult);
}
};
}
private boolean proceedOnError() {
return true; //???
}
public void outputClassFiles(CompilationResult unitResult) {
if (unitResult == null) return;
String sourceFileName = new String(unitResult.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;
}
} // class AjBuildManager
|
48,072
|
Bug 48072 Complete relationship information in the structure model
|
Complete the set of relationships surfaced by the structure model (e.g. including support for declare parents etc.) - Mik you had a document listing the things yet to be done here?
|
resolved fixed
|
f24286d
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-23T10:03:14Z
| 2003-12-04T15:00:00Z
|
weaver/src/org/aspectj/weaver/Checker.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.util.*;
import org.aspectj.bridge.*;
import org.aspectj.weaver.patterns.*;
public class Checker extends ShadowMunger {
private String msg;
private boolean isError;
public Checker(DeclareErrorOrWarning deow) {
super(deow.getPointcut(), deow.getStart(), deow.getEnd(), deow.getSourceContext());
this.msg = deow.getMessage();
this.isError = deow.isError();
}
public ShadowMunger concretize(ResolvedTypeX fromType, World world, PerClause clause) {
pointcut = pointcut.concretize(fromType, 0, this);
return this;
}
public void specializeOn(Shadow shadow) {
throw new RuntimeException("illegal state");
}
public void implementOn(Shadow shadow) {
throw new RuntimeException("illegal state");
}
public boolean match(Shadow shadow, World world) {
if (super.match(shadow, world)) {
IMessage message = new Message(
msg,
shadow.toString(),
isError ? IMessage.ERROR : IMessage.WARNING,
shadow.getSourceLocation(),
null,
new ISourceLocation[]{this.getSourceLocation()});
world.getMessageHandler().handleMessage(message);
AsmRelationshipProvider.checkerMunger(world.getModel(), shadow, this);
}
return false;
}
public int compareTo(Object other) {
return 0;
}
public Collection getThrownExceptions() { return Collections.EMPTY_LIST; }
public boolean isError() {
return isError;
}
}
|
48,072
|
Bug 48072 Complete relationship information in the structure model
|
Complete the set of relationships surfaced by the structure model (e.g. including support for declare parents etc.) - Mik you had a document listing the things yet to be done here?
|
resolved fixed
|
f24286d
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-23T10:03:14Z
| 2003-12-04T15:00:00Z
|
weaver/src/org/aspectj/weaver/ICrossReferenceHandler.java
| |
48,072
|
Bug 48072 Complete relationship information in the structure model
|
Complete the set of relationships surfaced by the structure model (e.g. including support for declare parents etc.) - Mik you had a document listing the things yet to be done here?
|
resolved fixed
|
f24286d
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-23T10:03:14Z
| 2003-12-04T15:00:00Z
|
weaver/src/org/aspectj/weaver/Shadow.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.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.aspectj.bridge.*;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.util.PartialOrder;
import org.aspectj.util.TypeSafeEnum;
import org.aspectj.weaver.ast.Var;
/*
* The superclass of anything representing a the shadow of a join point. A shadow represents
* some bit of code, and encompasses both entry and exit from that code. All shadows have a kind
* and a signature.
*/
public abstract class Shadow {
private final Kind kind;
private final Member signature;
protected final Shadow enclosingShadow;
protected List mungers = new ArrayList(1);
// ----
protected Shadow(Kind kind, Member signature, Shadow enclosingShadow) {
this.kind = kind;
this.signature = signature;
this.enclosingShadow = enclosingShadow;
}
// ----
public abstract World getIWorld();
/**
* could this(*) pcd ever match
*/
public final boolean hasThis() {
if (getKind().neverHasThis()) {
return false;
} else if (getKind().isEnclosingKind()) {
return !getSignature().isStatic();
} else if (enclosingShadow == null) {
return false;
} else {
return enclosingShadow.hasThis();
}
}
/**
* the type of the this object here
*
* @throws IllegalStateException if there is no this here
*/
public final TypeX getThisType() {
if (!hasThis()) throw new IllegalStateException("no this");
if (getKind().isEnclosingKind()) {
return getSignature().getDeclaringType();
} else {
return enclosingShadow.getThisType();
}
}
/**
* a var referencing this
*
* @throws IllegalStateException if there is no target here
*/
public abstract Var getThisVar();
/**
* could target(*) pcd ever match
*/
public final boolean hasTarget() {
if (getKind().neverHasTarget()) {
return false;
} else if (getKind().isTargetSameAsThis()) {
return hasThis();
} else {
return !getSignature().isStatic();
}
}
/**
* the type of the target object here
*
* @throws IllegalStateException if there is no target here
*/
public final TypeX getTargetType() {
if (!hasTarget()) throw new IllegalStateException("no target");
return getSignature().getDeclaringType();
}
/**
* a var referencing the target
*
* @throws IllegalStateException if there is no target here
*/
public abstract Var getTargetVar();
public TypeX[] getArgTypes() {
if (getKind() == FieldSet) return new TypeX[] { getSignature().getReturnType() };
return getSignature().getParameterTypes();
}
public TypeX getArgType(int arg) {
if (getKind() == FieldSet) return getSignature().getReturnType();
return getSignature().getParameterTypes()[arg];
}
public int getArgCount() {
if (getKind() == FieldSet) return 1;
return getSignature()
.getParameterTypes().length;
}
public abstract TypeX getEnclosingType();
public abstract Var getArgVar(int i);
public abstract Var getThisJoinPointVar();
public abstract Var getThisJoinPointStaticPartVar();
public abstract Var getThisEnclosingJoinPointStaticPartVar();
public abstract Member getEnclosingCodeSignature();
/** returns the kind of shadow this is, representing what happens under this shadow
*/
public Kind getKind() {
return kind;
}
/** returns the signature of the thing under this shadow
*/
public Member getSignature() {
return signature;
}
public TypeX getReturnType() {
if (kind == ConstructorCall) return getSignature().getDeclaringType();
else if (kind == FieldSet) return ResolvedTypeX.VOID;
return getSignature().getReturnType();
}
/**
* These names are the ones that will be returned by thisJoinPoint.getKind()
* Those need to be documented somewhere
*/
public static final Kind MethodCall = new Kind(JoinPoint.METHOD_CALL, 1, true);
public static final Kind ConstructorCall = new Kind(JoinPoint.CONSTRUCTOR_CALL, 2, true);
public static final Kind MethodExecution = new Kind(JoinPoint.METHOD_EXECUTION, 3, false);
public static final Kind ConstructorExecution = new Kind(JoinPoint.CONSTRUCTOR_EXECUTION, 4, false);
public static final Kind FieldGet = new Kind(JoinPoint.FIELD_GET, 5, true);
public static final Kind FieldSet = new Kind(JoinPoint.FIELD_SET, 6, true);
public static final Kind StaticInitialization = new Kind(JoinPoint.STATICINITIALIZATION, 7, false);
public static final Kind PreInitialization = new Kind(JoinPoint.PREINTIALIZATION, 8, false);
public static final Kind AdviceExecution = new Kind(JoinPoint.ADVICE_EXECUTION, 9, false);
public static final Kind Initialization = new Kind(JoinPoint.INITIALIZATION, 10, false);
public static final Kind ExceptionHandler = new Kind(JoinPoint.EXCEPTION_HANDLER, 11, true);
/** A type-safe enum representing the kind of shadows
*/
public static final class Kind extends TypeSafeEnum {
private boolean argsOnStack; //XXX unused
public Kind(String name, int key, boolean argsOnStack) {
super(name, key);
this.argsOnStack = argsOnStack;
}
public String toLegalJavaIdentifier() {
return getName().replace('-', '_');
}
public boolean argsOnStack() {
return !isTargetSameAsThis();
}
// !!! this is false for handlers!
public boolean allowsExtraction() {
return true;
}
// XXX revisit along with removal of priorities
public boolean hasHighPriorityExceptions() {
return !isTargetSameAsThis();
}
/**
* These are all the shadows that contains other shadows within them and
* are often directly associated with methods.
*/
public boolean isEnclosingKind() {
return this == MethodExecution || this == ConstructorExecution ||
this == AdviceExecution || this == StaticInitialization
|| this == Initialization;
}
public boolean isTargetSameAsThis() {
return this == MethodExecution
|| this == ConstructorExecution
|| this == StaticInitialization
|| this == PreInitialization
|| this == AdviceExecution
|| this == Initialization;
}
public boolean neverHasTarget() {
return this == ConstructorCall
|| this == ExceptionHandler
|| this == PreInitialization
|| this == StaticInitialization;
}
public boolean neverHasThis() {
return this == PreInitialization
|| this == StaticInitialization;
}
public String getSimpleName() {
int dash = getName().lastIndexOf('-');
if (dash == -1) return getName();
else return getName().substring(dash+1);
}
public static Kind read(DataInputStream s) throws IOException {
int key = s.readByte();
switch(key) {
case 1: return MethodCall;
case 2: return ConstructorCall;
case 3: return MethodExecution;
case 4: return ConstructorExecution;
case 5: return FieldGet;
case 6: return FieldSet;
case 7: return StaticInitialization;
case 8: return PreInitialization;
case 9: return AdviceExecution;
case 10: return Initialization;
case 11: return ExceptionHandler;
}
throw new BCException("unknown kind: " + key);
}
}
protected boolean checkMunger(ShadowMunger munger) {
for (Iterator i = munger.getThrownExceptions().iterator(); i.hasNext(); ) {
if (!checkCanThrow(munger, (ResolvedTypeX)i.next() )) return false;
}
return true;
}
protected boolean checkCanThrow(ShadowMunger munger, ResolvedTypeX resolvedTypeX) {
if (getKind() == ExceptionHandler) {
//XXX much too lenient rules here, need to walk up exception handlers
return true;
}
if (!isDeclaredException(resolvedTypeX, getSignature())) {
getIWorld().showMessage(IMessage.ERROR, "can't throw checked exception \'" + resolvedTypeX +
"\' at this join point \'" + this +"\'", // from advice in \'" + munger. + "\'",
getSourceLocation(), munger.getSourceLocation());
}
return true;
}
private boolean isDeclaredException(
ResolvedTypeX resolvedTypeX,
Member member)
{
ResolvedTypeX[] excs = getIWorld().resolve(member.getExceptions(getIWorld()));
for (int i=0, len=excs.length; i < len; i++) {
if (excs[i].isAssignableFrom(resolvedTypeX)) return true;
}
return false;
}
public void addMunger(ShadowMunger munger) {
if (checkMunger(munger)) this.mungers.add(munger);
}
public final void implement() {
sortMungers();
if (mungers == null) return;
prepareForMungers();
implementMungers();
}
private void sortMungers() {
List sorted = PartialOrder.sort(mungers);
if (sorted == null) {
// this means that we have circular dependencies
for (Iterator i = mungers.iterator(); i.hasNext(); ) {
ShadowMunger m = (ShadowMunger)i.next();
getIWorld().getMessageHandler().handleMessage(
MessageUtil.error("circular dependency at " + this, m.getSourceLocation()));
}
}
mungers = sorted;
}
/** Prepare the shadow for implementation. After this is done, the shadow
* should be in such a position that each munger simply needs to be implemented.
*/
protected void prepareForMungers() {
throw new RuntimeException("Generic shadows cannot be prepared");
}
/** Actually implement the (non-empty) mungers associated with this shadow */
private void implementMungers() {
World world = getIWorld();
for (Iterator iter = mungers.iterator(); iter.hasNext();) {
ShadowMunger munger = (ShadowMunger) iter.next();
munger.implementOn(this);
if (world.getModel() != null) {
//System.err.println("munger: " + munger + " on " + this);
AsmRelationshipProvider.adviceMunger(world.getModel(), this, munger);
}
}
}
public String makeReflectiveFactoryString() {
return null; //XXX
}
public abstract ISourceLocation getSourceLocation();
// ---- utility
public String toString() {
return getKind() + "(" + getSignature() + ")"; // + getSourceLines();
}
}
|
48,072
|
Bug 48072 Complete relationship information in the structure model
|
Complete the set of relationships surfaced by the structure model (e.g. including support for declare parents etc.) - Mik you had a document listing the things yet to be done here?
|
resolved fixed
|
f24286d
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-23T10:03:14Z
| 2003-12-04T15:00:00Z
|
weaver/src/org/aspectj/weaver/World.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.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.aspectj.asm.IHierarchy;
import org.aspectj.bridge.IMessageHandler;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.Message;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.bridge.IMessage.Kind;
import org.aspectj.weaver.patterns.DeclarePrecedence;
import org.aspectj.weaver.patterns.Pointcut;
public abstract class World {
protected IMessageHandler messageHandler = IMessageHandler.SYSTEM_ERR;
protected Map typeMap = new HashMap(); // Signature to ResolvedType
protected CrosscuttingMembersSet crosscuttingMembersSet = new CrosscuttingMembersSet(this);
protected IHierarchy model = null;
protected Lint lint = new Lint(this);
protected boolean XnoInline;
protected World() {
super();
typeMap.put("B", ResolvedTypeX.BYTE);
typeMap.put("S", ResolvedTypeX.SHORT);
typeMap.put("I", ResolvedTypeX.INT);
typeMap.put("J", ResolvedTypeX.LONG);
typeMap.put("F", ResolvedTypeX.FLOAT);
typeMap.put("D", ResolvedTypeX.DOUBLE);
typeMap.put("C", ResolvedTypeX.CHAR);
typeMap.put("Z", ResolvedTypeX.BOOLEAN);
typeMap.put("V", ResolvedTypeX.VOID);
}
public ResolvedTypeX[] resolve(TypeX[] types) {
int len = types.length;
ResolvedTypeX[] ret = new ResolvedTypeX[len];
for (int i=0; i<len; i++) {
ret[i] = resolve(types[i]);
}
return ret;
}
public ResolvedTypeX resolve(TypeX ty) {
return resolve(ty, false);
}
public ResolvedTypeX resolve(TypeX ty, boolean allowMissing) {
//System.out.println("resolve: " + ty + " world " + typeMap.keySet());
String signature = ty.getSignature();
ResolvedTypeX ret = (ResolvedTypeX)typeMap.get(signature);
if (ret != null) return ret;
if (ty.isArray()) {
ret = new ResolvedTypeX.Array(signature, this, resolve(ty.getComponentType(), allowMissing));
} else {
ret = resolveObjectType(ty);
if (!allowMissing && ret == ResolvedTypeX.MISSING) {
//Thread.currentThread().dumpStack();
MessageUtil.error(messageHandler, "can't find type " + ty.getName());
// + " on classpath " + classPath);
}
}
//System.out.println("ret: " + ret);
typeMap.put(signature, ret);
return ret;
}
//XXX helper method might be bad
public ResolvedTypeX resolve(String name) {
return resolve(TypeX.forName(name));
}
protected final ResolvedTypeX resolveObjectType(TypeX ty) {
ResolvedTypeX.Name name = new ResolvedTypeX.Name(ty.getSignature(), this);
ResolvedTypeX.ConcreteName concreteName = resolveObjectType(name);
if (concreteName == null) return ResolvedTypeX.MISSING;
name.setDelegate(concreteName);
return name;
}
protected abstract ResolvedTypeX.ConcreteName resolveObjectType(ResolvedTypeX.Name ty);
protected final boolean isCoerceableFrom(TypeX type, TypeX other) {
return resolve(type).isCoerceableFrom(other);
}
protected final boolean isAssignableFrom(TypeX type, TypeX other) {
return resolve(type).isAssignableFrom(other);
}
public boolean needsNoConversionFrom(TypeX type, TypeX other) {
return resolve(type).needsNoConversionFrom(other);
}
protected final boolean isInterface(TypeX type) {
return resolve(type).isInterface();
}
protected final ResolvedTypeX getSuperclass(TypeX type) {
return resolve(type).getSuperclass();
}
protected final TypeX[] getDeclaredInterfaces(TypeX type) {
return resolve(type).getDeclaredInterfaces();
}
protected final int getModifiers(TypeX type) {
return resolve(type).getModifiers();
}
protected final ResolvedMember[] getDeclaredFields(TypeX type) {
return resolve(type).getDeclaredFields();
}
protected final ResolvedMember[] getDeclaredMethods(TypeX type) {
return resolve(type).getDeclaredMethods();
}
protected final ResolvedMember[] getDeclaredPointcuts(TypeX type) {
return resolve(type).getDeclaredPointcuts();
}
// ---- members
// XXX should we worry about dealing with context and looking up access?
public ResolvedMember resolve(Member member) {
ResolvedTypeX declaring = member.getDeclaringType().resolve(this);
ResolvedMember ret;
if (member.getKind() == Member.FIELD) {
ret = declaring.lookupField(member);
} else {
ret = declaring.lookupMethod(member);
}
if (ret != null) return ret;
return declaring.lookupSyntheticMember(member);
}
protected int getModifiers(Member member) {
ResolvedMember r = resolve(member);
if (r == null) throw new BCException("bad resolve of " + member);
return r.getModifiers();
}
protected String[] getParameterNames(Member member) {
return resolve(member).getParameterNames();
}
protected TypeX[] getExceptions(Member member) {
return resolve(member).getExceptions();
}
// ---- pointcuts
public ResolvedPointcutDefinition findPointcut(TypeX typeX, String name) {
throw new RuntimeException("not implemented yet");
}
/**
* Get the shadow mungers of this world.
*
* @return a list of {@link IShadowMunger}s appropriate for this world.
*/
//public abstract List getShadowMungers();
// ---- empty world
public static final World EMPTY = new World() {
public List getShadowMungers() { return Collections.EMPTY_LIST; }
public ResolvedTypeX.ConcreteName resolveObjectType(ResolvedTypeX.Name ty) {
return null;
}
public Advice concreteAdvice(AjAttribute.AdviceAttribute attribute, Pointcut p, Member m) {
throw new RuntimeException("unimplemented");
}
public ConcreteTypeMunger concreteTypeMunger(ResolvedTypeMunger munger, ResolvedTypeX aspectType) {
throw new RuntimeException("unimplemented");
}
};
public abstract Advice concreteAdvice(
AjAttribute.AdviceAttribute attribute,
Pointcut pointcut,
Member signature);
public final Advice concreteAdvice(
AdviceKind kind,
Pointcut p,
Member signature,
int extraParameterFlags,
IHasSourceLocation loc)
{
AjAttribute.AdviceAttribute attribute =
new AjAttribute.AdviceAttribute(kind, p, extraParameterFlags, loc.getStart(), loc.getEnd(), loc.getSourceContext());
return concreteAdvice(attribute, p, signature);
}
public ConcreteTypeMunger makeCflowStackFieldAdder(ResolvedMember cflowField) {
throw new RuntimeException("unimplemented");
}
public abstract ConcreteTypeMunger concreteTypeMunger(ResolvedTypeMunger munger, ResolvedTypeX aspectType);
/**
* Nobody should hold onto a copy of this message handler, or setMessageHandler won't
* work right.
*/
public IMessageHandler getMessageHandler() {
return messageHandler;
}
public void setMessageHandler(IMessageHandler messageHandler) {
this.messageHandler = messageHandler;
}
public void showMessage(
Kind kind,
String message,
ISourceLocation loc1,
ISourceLocation loc2)
{
if (loc1 != null) {
messageHandler.handleMessage(new Message(message, kind, null, loc1));
if (loc2 != null) {
messageHandler.handleMessage(new Message(message, kind, null, loc2));
}
} else {
messageHandler.handleMessage(new Message(message, kind, null, loc2));
}
}
// public void addDeclare(ResolvedTypeX onType, Declare declare, boolean forWeaving) {
// // this is not extensible, oh well
// if (declare instanceof DeclareErrorOrWarning) {
// ShadowMunger m = new Checker((DeclareErrorOrWarning)declare);
// onType.addShadowMunger(m);
// } else if (declare instanceof DeclareDominates) {
// declareDominates.add(declare);
// } else if (declare instanceof DeclareParents) {
// declareParents.add(declare);
// } else if (declare instanceof DeclareSoft) {
// DeclareSoft d = (DeclareSoft)declare;
// declareSoft.add(d);
// if (forWeaving) {
// ShadowMunger m = Advice.makeSoftener(this, d.getPointcut().concretize(onType, 0), d.getException());
// onType.addShadowMunger(m);
// }
// } else {
// throw new RuntimeException("unimplemented");
// }
// }
/**
* Same signature as org.aspectj.util.PartialOrder.PartialComparable.compareTo
*/
public int compareByDominates(ResolvedTypeX aspect1, ResolvedTypeX aspect2) {
//System.out.println("dom compare: " + aspect1 + " with " + aspect2);
//System.out.println(crosscuttingMembersSet.getDeclareDominates());
//??? We probably want to cache this result. This is order N where N is the
//??? number of dominates declares in the whole system.
//??? This method can be called a large number of times.
int order = 0;
for (Iterator i = crosscuttingMembersSet.getDeclareDominates().iterator(); i.hasNext(); ) {
DeclarePrecedence d = (DeclarePrecedence)i.next();
int thisOrder = d.compare(aspect1, aspect2);
//System.out.println("comparing: " + thisOrder + ": " + d);
if (thisOrder != 0) {
if (order != 0 && order != thisOrder) {
throw new BCException("conflicting dominates orders");
} else {
order = thisOrder;
}
}
}
return order;
}
public int comparePrecedence(ResolvedTypeX aspect1, ResolvedTypeX aspect2) {
//System.err.println("compare precedence " + aspect1 + ", " + aspect2);
if (aspect1.equals(aspect2)) return 0;
int ret = compareByDominates(aspect1, aspect2);
if (ret != 0) return ret;
if (aspect1.isAssignableFrom(aspect2)) return -1;
else if (aspect2.isAssignableFrom(aspect1)) return +1;
return 0;
}
public List getDeclareParents() {
return crosscuttingMembersSet.getDeclareParents();
}
public List getDeclareSoft() {
return crosscuttingMembersSet.getDeclareSofts();
}
public CrosscuttingMembersSet getCrosscuttingMembersSet() {
return crosscuttingMembersSet;
}
public IHierarchy getModel() {
return model;
}
public void setModel(IHierarchy model) {
this.model = model;
}
public Lint getLint() {
return lint;
}
public void setLint(Lint lint) {
this.lint = lint;
}
public boolean isXnoInline() {
return XnoInline;
}
public void setXnoInline(boolean xnoInline) {
XnoInline = xnoInline;
}
public ResolvedTypeX.Name lookupOrCreateName(TypeX ty) {
String signature = ty.getSignature();
ResolvedTypeX.Name ret = (ResolvedTypeX.Name)typeMap.get(signature);
if (ret == null) {
ret = new ResolvedTypeX.Name(signature, this);
typeMap.put(signature, ret);
}
return ret;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.