From 0a395eb90a627aa707ea289ec42a5dc242d9716d Mon Sep 17 00:00:00 2001 From: aclement Date: Wed, 9 Sep 2009 19:56:20 +0000 Subject: [PATCH] Java5 upgrades --- .../.settings/org.eclipse.jdt.core.prefs | 14 +- .../apache/bcel/ExceptionConstants.java | 40 +- .../apache/bcel/classfile/ConstantPool.java | 12 +- .../apache/bcel/classfile/FieldOrMethod.java | 6 +- .../apache/bcel/classfile/JavaClass.java | 11 +- .../aspectj/apache/bcel/classfile/Method.java | 6 +- .../apache/bcel/classfile/Utility.java | 18 +- .../classfile/annotation/AnnotationGen.java | 24 +- .../annotation/RuntimeAnnotations.java | 12 +- .../RuntimeParameterAnnotations.java | 12 +- .../aspectj/apache/bcel/generic/ClassGen.java | 61 +- .../aspectj/apache/bcel/generic/FieldGen.java | 8 +- .../bcel/generic/FieldGenOrMethodGen.java | 8 +- .../bcel/generic/InstructionHandle.java | 8 +- .../apache/bcel/generic/InstructionList.java | 18 +- .../apache/bcel/generic/MethodGen.java | 50 +- .../org/aspectj/apache/bcel/generic/Type.java | 851 +++++++++--------- .../bcel/util/ClassLoaderRepository.java | 589 ++++++------ .../aspectj/apache/bcel/util/ClassPath.java | 18 +- .../aspectj/apache/bcel/util/ClassQueue.java | 6 +- .../aspectj/apache/bcel/util/ClassVector.java | 6 +- .../util/NonCachingClassLoaderRepository.java | 24 +- .../aspectj/apache/bcel/util/Repository.java | 63 +- .../apache/bcel/util/SyntheticRepository.java | 258 +++--- .../classfile/tests/AnnotationGenTest.java | 16 +- .../bcel/classfile/tests/BcelTestCase.java | 10 +- .../classfile/tests/FieldAnnotationsTest.java | 6 +- .../tests/GeneratingAnnotatedClassesTest.java | 20 +- .../tests/GenericSignatureParsingTest.java | 2 +- .../tests/MethodAnnotationsTest.java | 6 +- .../NonCachingClassLoaderRepositoryTest.java | 4 +- .../tests/ParameterAnnotationsTest.java | 9 +- ...RuntimeVisibleAnnotationAttributeTest.java | 46 +- ...sibleParameterAnnotationAttributeTest.java | 6 +- .../bcel/classfile/tests/VarargsTest.java | 4 +- .../bcel/verifier/DescendingVisitor.java | 4 +- .../apache/bcel/verifier/PassVerifier.java | 6 +- .../apache/bcel/verifier/Verifier.java | 18 +- .../apache/bcel/verifier/VerifierFactory.java | 14 +- .../verifier/VerifierFactoryListModel.java | 9 +- .../apache/bcel/verifier/statics/IntList.java | 6 +- .../verifier/statics/LocalVariableInfo.java | 10 +- .../bcel/verifier/statics/Pass2Verifier.java | 22 +- .../structurals/ControlFlowGraph.java | 30 +- .../structurals/ExceptionHandlers.java | 15 +- .../structurals/InstructionContext.java | 6 +- .../verifier/structurals/OperandStack.java | 12 +- .../verifier/structurals/Pass3bVerifier.java | 40 +- .../verifier/structurals/Subroutines.java | 65 +- .../bcel/verifier/util/BCELFactory.java | 10 +- .../bcel/verifier/util/InstructionFinder.java | 22 +- 51 files changed, 1304 insertions(+), 1237 deletions(-) diff --git a/bcel-builder/.settings/org.eclipse.jdt.core.prefs b/bcel-builder/.settings/org.eclipse.jdt.core.prefs index fd14c0abb..52e4117af 100644 --- a/bcel-builder/.settings/org.eclipse.jdt.core.prefs +++ b/bcel-builder/.settings/org.eclipse.jdt.core.prefs @@ -1,21 +1,21 @@ -#Fri Nov 25 19:12:57 GMT 2005 +#Tue Sep 08 17:08:00 PDT 2009 eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=disabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve -org.eclipse.jdt.core.compiler.compliance=1.3 +org.eclipse.jdt.core.compiler.compliance=1.5 org.eclipse.jdt.core.compiler.debug.lineNumber=generate org.eclipse.jdt.core.compiler.debug.localVariable=generate org.eclipse.jdt.core.compiler.debug.sourceFile=generate org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning -org.eclipse.jdt.core.compiler.problem.assertIdentifier=ignore +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error org.eclipse.jdt.core.compiler.problem.autoboxing=ignore org.eclipse.jdt.core.compiler.problem.deprecation=warning org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled org.eclipse.jdt.core.compiler.problem.discouragedReference=warning org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore -org.eclipse.jdt.core.compiler.problem.enumIdentifier=ignore +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error org.eclipse.jdt.core.compiler.problem.fieldHiding=ignore org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning @@ -54,4 +54,4 @@ org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=di org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=ignore org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning -org.eclipse.jdt.core.compiler.source=1.3 +org.eclipse.jdt.core.compiler.source=1.5 diff --git a/bcel-builder/src/org/aspectj/apache/bcel/ExceptionConstants.java b/bcel-builder/src/org/aspectj/apache/bcel/ExceptionConstants.java index bbe3b4c26..6b41f4d4a 100644 --- a/bcel-builder/src/org/aspectj/apache/bcel/ExceptionConstants.java +++ b/bcel-builder/src/org/aspectj/apache/bcel/ExceptionConstants.java @@ -57,48 +57,48 @@ package org.aspectj.apache.bcel; /** * Exception constants. * - * @version $Id: ExceptionConstants.java,v 1.3 2008/05/28 23:53:04 aclement Exp $ + * @version $Id: ExceptionConstants.java,v 1.4 2009/09/09 19:56:20 aclement Exp $ * @author E. Haase */ public interface ExceptionConstants { /** The mother of all exceptions */ - public static final Class THROWABLE = Throwable.class; + public static final Class THROWABLE = Throwable.class; /** Super class of any run-time exception */ - public static final Class RUNTIME_EXCEPTION = RuntimeException.class; + public static final Class RUNTIME_EXCEPTION = RuntimeException.class; /** Super class of any linking exception (aka Linkage Error) */ - public static final Class LINKING_EXCEPTION = LinkageError.class; + public static final Class LINKING_EXCEPTION = LinkageError.class; /** Linking Exceptions */ - public static final Class CLASS_CIRCULARITY_ERROR = ClassCircularityError.class; - public static final Class CLASS_FORMAT_ERROR = ClassFormatError.class; - public static final Class EXCEPTION_IN_INITIALIZER_ERROR = ExceptionInInitializerError.class; - public static final Class INCOMPATIBLE_CLASS_CHANGE_ERROR = IncompatibleClassChangeError.class; - public static final Class ABSTRACT_METHOD_ERROR = AbstractMethodError.class; + public static final Class CLASS_CIRCULARITY_ERROR = ClassCircularityError.class; + public static final Class CLASS_FORMAT_ERROR = ClassFormatError.class; + public static final Class EXCEPTION_IN_INITIALIZER_ERROR = ExceptionInInitializerError.class; + public static final Class INCOMPATIBLE_CLASS_CHANGE_ERROR = IncompatibleClassChangeError.class; + public static final Class ABSTRACT_METHOD_ERROR = AbstractMethodError.class; public static final Class ILLEGAL_ACCESS_ERROR = IllegalAccessError.class; - public static final Class INSTANTIATION_ERROR = InstantiationError.class; - public static final Class NO_SUCH_FIELD_ERROR = NoSuchFieldError.class; - public static final Class NO_SUCH_METHOD_ERROR = NoSuchMethodError.class; - public static final Class NO_CLASS_DEF_FOUND_ERROR = NoClassDefFoundError.class; - public static final Class UNSATISFIED_LINK_ERROR = UnsatisfiedLinkError.class; - public static final Class VERIFY_ERROR = VerifyError.class; + public static final Class INSTANTIATION_ERROR = InstantiationError.class; + public static final Class NO_SUCH_FIELD_ERROR = NoSuchFieldError.class; + public static final Class NO_SUCH_METHOD_ERROR = NoSuchMethodError.class; + public static final Class NO_CLASS_DEF_FOUND_ERROR = NoClassDefFoundError.class; + public static final Class UNSATISFIED_LINK_ERROR = UnsatisfiedLinkError.class; + public static final Class VERIFY_ERROR = VerifyError.class; /* UnsupportedClassVersionError is new in JDK 1.2 */ //public static final Class UnsupportedClassVersionError = UnsupportedClassVersionError.class; /** Run-Time Exceptions */ - public static final Class NULL_POINTER_EXCEPTION = NullPointerException.class; - public static final Class ARRAY_INDEX_OUT_OF_BOUNDS_EXCEPTION = ArrayIndexOutOfBoundsException.class; - public static final Class ARITHMETIC_EXCEPTION = ArithmeticException.class; + public static final Class NULL_POINTER_EXCEPTION = NullPointerException.class; + public static final Class ARRAY_INDEX_OUT_OF_BOUNDS_EXCEPTION = ArrayIndexOutOfBoundsException.class; + public static final Class ARITHMETIC_EXCEPTION = ArithmeticException.class; public static final Class NEGATIVE_ARRAY_SIZE_EXCEPTION = NegativeArraySizeException.class; - public static final Class CLASS_CAST_EXCEPTION = ClassCastException.class; - public static final Class ILLEGAL_MONITOR_STATE = IllegalMonitorStateException.class; + public static final Class CLASS_CAST_EXCEPTION = ClassCastException.class; + public static final Class ILLEGAL_MONITOR_STATE = IllegalMonitorStateException.class; /** Pre-defined exception arrays according to chapters 5.1-5.4 of the Java Virtual * Machine Specification diff --git a/bcel-builder/src/org/aspectj/apache/bcel/classfile/ConstantPool.java b/bcel-builder/src/org/aspectj/apache/bcel/classfile/ConstantPool.java index a2e35d279..9dd4264f7 100644 --- a/bcel-builder/src/org/aspectj/apache/bcel/classfile/ConstantPool.java +++ b/bcel-builder/src/org/aspectj/apache/bcel/classfile/ConstantPool.java @@ -20,9 +20,9 @@ public class ConstantPool implements Node { private Constant[] pool; private int poolSize; // number of entries in the pool (could be < pool.length as the array is resized in 'chunks') - private Map utf8Cache = new HashMap(); - private Map methodCache = new HashMap(); - private Map fieldCache = new HashMap(); + private Map utf8Cache = new HashMap(); + private Map methodCache = new HashMap(); + private Map fieldCache = new HashMap(); public int getSize() { return poolSize; } @@ -236,7 +236,7 @@ public class ConstantPool implements Node { public int lookupUtf8(String string) { - Integer pos = (Integer) utf8Cache.get(string); + Integer pos = utf8Cache.get(string); if (pos!=null) return pos.intValue(); for (int i=1;iM. Dahm */ public abstract class FieldOrMethod extends Modifiers implements Cloneable, Node { @@ -173,7 +173,7 @@ public abstract class FieldOrMethod extends Modifiers implements Cloneable, Node // remain there. if (annotations==null) { // Find attributes that contain annotation data - List accumulatedAnnotations = new ArrayList(); + List accumulatedAnnotations = new ArrayList(); for (int i = 0; i < attributes.length; i++) { Attribute attribute = attributes[i]; if (attribute instanceof RuntimeAnnotations) { @@ -184,7 +184,7 @@ public abstract class FieldOrMethod extends Modifiers implements Cloneable, Node if (accumulatedAnnotations.size()==0) { annotations = AnnotationGen.NO_ANNOTATIONS; } else { - annotations = (AnnotationGen[])accumulatedAnnotations.toArray(new AnnotationGen[]{}); + annotations = accumulatedAnnotations.toArray(new AnnotationGen[]{}); } } return annotations; diff --git a/bcel-builder/src/org/aspectj/apache/bcel/classfile/JavaClass.java b/bcel-builder/src/org/aspectj/apache/bcel/classfile/JavaClass.java index 230aabe49..d0b94928b 100644 --- a/bcel-builder/src/org/aspectj/apache/bcel/classfile/JavaClass.java +++ b/bcel-builder/src/org/aspectj/apache/bcel/classfile/JavaClass.java @@ -79,7 +79,7 @@ import org.aspectj.apache.bcel.util.SyntheticRepository; * The intent of this class is to represent a parsed or otherwise existing class file. Those interested in programatically * generating classes should see the ClassGen class. * - * @version $Id: JavaClass.java,v 1.14 2008/10/20 18:31:01 aclement Exp $ + * @version $Id: JavaClass.java,v 1.15 2009/09/09 19:56:20 aclement Exp $ * @see org.aspectj.apache.bcel.generic.ClassGen * @author M. Dahm */ @@ -329,7 +329,7 @@ public class JavaClass extends Modifiers implements Cloneable, Node { public AnnotationGen[] getAnnotations() { if (annotationsOutOfDate) { // Find attributes that contain annotation data - List accumulatedAnnotations = new ArrayList(); + List accumulatedAnnotations = new ArrayList(); for (int i = 0; i < attributes.length; i++) { Attribute attribute = attributes[i]; if (attribute instanceof RuntimeAnnotations) { @@ -337,7 +337,7 @@ public class JavaClass extends Modifiers implements Cloneable, Node { accumulatedAnnotations.addAll(runtimeAnnotations.getAnnotations()); } } - annotations = (AnnotationGen[]) accumulatedAnnotations.toArray(new AnnotationGen[] {}); + annotations = accumulatedAnnotations.toArray(new AnnotationGen[] {}); annotationsOutOfDate = false; } return annotations; @@ -601,6 +601,7 @@ public class JavaClass extends Modifiers implements Cloneable, Node { /** * @return String representing class contents. */ + @Override public String toString() { String access = Utility.accessToString(modifiers, true); access = access.equals("") ? "" : access + " "; @@ -683,8 +684,8 @@ public class JavaClass extends Modifiers implements Cloneable, Node { } c.constant_pool = constant_pool.copy(); - c.interfaces = (int[]) interfaces.clone(); - c.interface_names = (String[]) interface_names.clone(); + c.interfaces = interfaces.clone(); + c.interface_names = interface_names.clone(); c.fields = new Field[fields.length]; for (int i = 0; i < fields.length; i++) { diff --git a/bcel-builder/src/org/aspectj/apache/bcel/classfile/Method.java b/bcel-builder/src/org/aspectj/apache/bcel/classfile/Method.java index 25e8847a0..59fe05a85 100644 --- a/bcel-builder/src/org/aspectj/apache/bcel/classfile/Method.java +++ b/bcel-builder/src/org/aspectj/apache/bcel/classfile/Method.java @@ -69,7 +69,7 @@ import org.aspectj.apache.bcel.generic.Type; * for a method in the class. See JVM specification for details. * A method has access flags, a name, a signature and a number of attributes. * - * @version $Id: Method.java,v 1.7 2008/08/26 15:01:15 aclement Exp $ + * @version $Id: Method.java,v 1.8 2009/09/09 19:56:20 aclement Exp $ * @author M. Dahm */ public final class Method extends FieldOrMethod { @@ -232,7 +232,7 @@ public final class Method extends FieldOrMethod { boolean foundSome = false; // Build a list of annotation arrays, one per argument if (parameterAnnotationsInvis!=null || parameterAnnotationsVis!=null) { - List annotationsForEachParameter = new ArrayList(); + List annotationsForEachParameter = new ArrayList(); AnnotationGen[] visibleOnes = null; AnnotationGen[] invisibleOnes = null; for (int i=0; iM. Dahm * * modified: Andy Clement 2-mar-05 Removed unnecessary static and optimized @@ -593,7 +595,7 @@ public abstract class Utility { * @param cp The constant pool gen where we can create the necessary name refs * @param vec A list of AnnotationGen objects */ - public static Attribute[] getAnnotationAttributes(ConstantPool cp,List vec) { + public static Attribute[] getAnnotationAttributes(ConstantPool cp,List vec) { if (vec.size()==0) return null; @@ -603,7 +605,7 @@ public abstract class Utility { // put the annotations in the right output stream for (int i=0; i2) rvaIndex = cp.addUtf8("RuntimeVisibleAnnotations"); if (riaData.length>2) riaIndex = cp.addUtf8("RuntimeInvisibleAnnotations"); - List newAttributes = new ArrayList(); + List newAttributes = new ArrayList(); if (rvaData.length>2) { newAttributes.add( new RuntimeVisibleAnnotations(rvaIndex,rvaData.length,rvaData,cp)); @@ -645,7 +647,7 @@ public abstract class Utility { new RuntimeInvisibleAnnotations(riaIndex,riaData.length,riaData,cp)); } - return (Attribute[])newAttributes.toArray(new Attribute[]{}); + return newAttributes.toArray(new Attribute[]{}); } catch (IOException e) { System.err.println("IOException whilst processing annotations"); e.printStackTrace(); @@ -721,7 +723,7 @@ public abstract class Utility { if (totalVisCount>0) rvaIndex = cp.addUtf8("RuntimeVisibleParameterAnnotations"); if (totalInvisCount>0) riaIndex = cp.addUtf8("RuntimeInvisibleParameterAnnotations"); - List newAttributes = new ArrayList(); + List newAttributes = new ArrayList(); if (totalVisCount>0) { newAttributes.add( @@ -734,7 +736,7 @@ public abstract class Utility { new RuntimeInvisibleParameterAnnotations(riaIndex,riaData.length,riaData,cp)); } - return (Attribute[])newAttributes.toArray(new Attribute[]{}); + return newAttributes.toArray(new Attribute[]{}); } catch (IOException e) { System.err.println("IOException whilst processing parameter annotations"); e.printStackTrace(); diff --git a/bcel-builder/src/org/aspectj/apache/bcel/classfile/annotation/AnnotationGen.java b/bcel-builder/src/org/aspectj/apache/bcel/classfile/annotation/AnnotationGen.java index e845c8597..da9fb7f08 100644 --- a/bcel-builder/src/org/aspectj/apache/bcel/classfile/annotation/AnnotationGen.java +++ b/bcel-builder/src/org/aspectj/apache/bcel/classfile/annotation/AnnotationGen.java @@ -28,7 +28,7 @@ public class AnnotationGen { public static final AnnotationGen[] NO_ANNOTATIONS = new AnnotationGen[0]; private int typeIndex; - private List /* ElementNameValuePairGen */ evs; + private List /* ElementNameValuePairGen */ evs; private ConstantPool cpool; private boolean isRuntimeVisible = false; @@ -54,10 +54,10 @@ public class AnnotationGen { evs = copyValues(a.getValues(),cpool,copyPoolEntries); } - private List copyValues(List in,ConstantPool cpool,boolean copyPoolEntries) { - List out = new ArrayList(); - for (Iterator iter = in.iterator(); iter.hasNext();) { - ElementNameValuePairGen nvp = (ElementNameValuePairGen) iter.next(); + private List copyValues(List in,ConstantPool cpool,boolean copyPoolEntries) { + List out = new ArrayList(); + for (Iterator iter = in.iterator(); iter.hasNext();) { + ElementNameValuePairGen nvp = iter.next(); out.add(new ElementNameValuePairGen(nvp,cpool,copyPoolEntries)); } return out; @@ -65,7 +65,7 @@ public class AnnotationGen { private AnnotationGen(ConstantPool cpool) { this.cpool = cpool; - this.evs=new ArrayList(); + this.evs=new ArrayList(); } /** @@ -81,7 +81,7 @@ public class AnnotationGen { //// return a; // } - public AnnotationGen(ObjectType type,List /*ElementNameValuePairGen*/ elements,boolean vis,ConstantPool cpool) { + public AnnotationGen(ObjectType type,List /*ElementNameValuePairGen*/ elements,boolean vis,ConstantPool cpool) { this.cpool = cpool; if (type!=null) this.typeIndex = cpool.addUtf8(type.getSignature()); // Only null for funky *temporary* FakeAnnotation objects evs = elements; @@ -105,13 +105,13 @@ public class AnnotationGen { dos.writeShort(typeIndex); // u2 index of type name in cpool dos.writeShort(evs.size()); // u2 element_value pair count for (int i = 0 ; i(); evs.add(evp); } @@ -133,7 +133,7 @@ public class AnnotationGen { /** * Returns list of ElementNameValuePair objects */ - public List getValues() { + public List getValues() { return evs; } @@ -172,7 +172,7 @@ public class AnnotationGen { */ public boolean hasNameValuePair(String n, String v) { for (int i=0;i annotations; private boolean visible; // Keep just a byte stream of the data until someone actually asks for it @@ -26,17 +26,17 @@ public abstract class RuntimeAnnotations extends Attribute { ConstantPool cpool) { super(attrid,nameIdx,len,cpool); this.visible = visible; - annotations = new ArrayList(); + annotations = new ArrayList(); } public RuntimeAnnotations(byte attrid,boolean visible,int nameIdx,int len,byte[] data,ConstantPool cpool) { super(attrid,nameIdx,len,cpool); this.visible = visible; - annotations = new ArrayList(); + annotations = new ArrayList(); annotation_data = data; } - public List getAnnotations() { + public List getAnnotations() { if (!inflated) inflate(); return annotations; } @@ -55,8 +55,8 @@ public abstract class RuntimeAnnotations extends Attribute { dos.write(annotation_data,0,length); } else { dos.writeShort(annotations.size()); - for (Iterator i = annotations.iterator(); i.hasNext();) { - AnnotationGen ann = (AnnotationGen) i.next(); + for (Iterator i = annotations.iterator(); i.hasNext();) { + AnnotationGen ann = i.next(); ann.dump(dos); } } diff --git a/bcel-builder/src/org/aspectj/apache/bcel/classfile/annotation/RuntimeParameterAnnotations.java b/bcel-builder/src/org/aspectj/apache/bcel/classfile/annotation/RuntimeParameterAnnotations.java index 6f378351c..7d57cb915 100644 --- a/bcel-builder/src/org/aspectj/apache/bcel/classfile/annotation/RuntimeParameterAnnotations.java +++ b/bcel-builder/src/org/aspectj/apache/bcel/classfile/annotation/RuntimeParameterAnnotations.java @@ -12,7 +12,7 @@ import org.aspectj.apache.bcel.classfile.ConstantPool; public abstract class RuntimeParameterAnnotations extends Attribute { - private List /*Annotation[]*/ parameterAnnotations; + private List /*Annotation[]*/ parameterAnnotations; private boolean visible; @@ -25,13 +25,13 @@ public abstract class RuntimeParameterAnnotations extends Attribute { int nameIdx, int len, ConstantPool cpool) { super(attrid,nameIdx,len,cpool); this.visible = visible; - parameterAnnotations = new ArrayList(); + parameterAnnotations = new ArrayList(); } public RuntimeParameterAnnotations(byte attrid,boolean visible,int nameIdx,int len,byte[] data,ConstantPool cpool) { super(attrid,nameIdx,len,cpool); this.visible = visible; - parameterAnnotations = new ArrayList(); + parameterAnnotations = new ArrayList(); annotation_data = data; } @@ -45,7 +45,7 @@ public abstract class RuntimeParameterAnnotations extends Attribute { } /** Return a list of Annotation[] - each list entry contains the annotations for one parameter */ - public List /*Annotation[]*/ getParameterAnnotations() { + public List /*Annotation[]*/ getParameterAnnotations() { if (!inflated) inflate(); return parameterAnnotations; } @@ -60,7 +60,7 @@ public abstract class RuntimeParameterAnnotations extends Attribute { if (parameterIndex>=parameterAnnotations.size()) { return AnnotationGen.NO_ANNOTATIONS; } - return (AnnotationGen[])parameterAnnotations.get(parameterIndex); + return parameterAnnotations.get(parameterIndex); } public boolean areVisible() { @@ -97,7 +97,7 @@ public abstract class RuntimeParameterAnnotations extends Attribute { } else { dos.writeByte(parameterAnnotations.size()); for (int i=0; iM. Dahm * * Upgraded, Andy Clement 9th Mar 06 - calculates SUID @@ -96,11 +97,11 @@ public class ClassGen extends Modifiers implements Cloneable { private ConstantPool cp; - private ArrayList field_vec = new ArrayList(); - private ArrayList method_vec = new ArrayList(); - private ArrayList attributesList = new ArrayList(); - private ArrayList interface_vec = new ArrayList(); - private ArrayList annotation_vec= new ArrayList(); + private ArrayList field_vec = new ArrayList(); + private ArrayList method_vec = new ArrayList(); + private ArrayList attributesList = new ArrayList(); + private ArrayList interface_vec = new ArrayList(); + private ArrayList annotation_vec= new ArrayList(); /** Convenience constructor to set up some important values initially. * @@ -198,26 +199,26 @@ public class ClassGen extends Modifiers implements Cloneable { * Look for attributes representing annotations and unpack them. */ private AnnotationGen[] unpackAnnotations(Attribute[] attrs) { - List /*AnnotationGen*/ annotationGenObjs = new ArrayList(); + List /*AnnotationGen*/ annotationGenObjs = new ArrayList(); for (int i = 0; i < attrs.length; i++) { Attribute attr = attrs[i]; if (attr instanceof RuntimeVisibleAnnotations) { RuntimeVisibleAnnotations rva = (RuntimeVisibleAnnotations)attr; - List annos = rva.getAnnotations(); - for (Iterator iter = annos.iterator(); iter.hasNext();) { - AnnotationGen a = (AnnotationGen) iter.next(); + List annos = rva.getAnnotations(); + for (Iterator iter = annos.iterator(); iter.hasNext();) { + AnnotationGen a = iter.next(); annotationGenObjs.add(new AnnotationGen(a,getConstantPool(),false)); } } else if (attr instanceof RuntimeInvisibleAnnotations) { RuntimeInvisibleAnnotations ria = (RuntimeInvisibleAnnotations)attr; - List annos = ria.getAnnotations(); - for (Iterator iter = annos.iterator(); iter.hasNext();) { - AnnotationGen a = (AnnotationGen) iter.next(); + List annos = ria.getAnnotations(); + for (Iterator iter = annos.iterator(); iter.hasNext();) { + AnnotationGen a = iter.next(); annotationGenObjs.add(new AnnotationGen(a,getConstantPool(),false)); } } } - return (AnnotationGen[])annotationGenObjs.toArray(new AnnotationGen[]{}); + return annotationGenObjs.toArray(new AnnotationGen[]{}); } /** @@ -331,8 +332,8 @@ public class ClassGen extends Modifiers implements Cloneable { /** @return field object with given name, or null */ public Field containsField(String name) { - for(Iterator e=field_vec.iterator(); e.hasNext(); ) { - Field f = (Field)e.next(); + for(Iterator e=field_vec.iterator(); e.hasNext(); ) { + Field f = e.next(); if(f.getName().equals(name)) return f; } @@ -343,8 +344,8 @@ public class ClassGen extends Modifiers implements Cloneable { /** @return method object with given name and signature, or null */ public Method containsMethod(String name, String signature) { - for(Iterator e=method_vec.iterator(); e.hasNext();) { - Method m = (Method)e.next(); + for(Iterator e=method_vec.iterator(); e.hasNext();) { + Method m = e.next(); if(m.getName().equals(name) && m.getSignature().equals(signature)) return m; } @@ -438,7 +439,7 @@ public class ClassGen extends Modifiers implements Cloneable { } public Method getMethodAt(int pos) { - return (Method)method_vec.get(pos); + return method_vec.get(pos); } public String[] getInterfaceNames() { @@ -454,7 +455,7 @@ public class ClassGen extends Modifiers implements Cloneable { int[] interfaces = new int[size]; for(int i=0; i < size; i++) - interfaces[i] = cp.addClass((String)interface_vec.get(i)); + interfaces[i] = cp.addClass(interface_vec.get(i)); return interfaces; } @@ -556,7 +557,7 @@ public class ClassGen extends Modifiers implements Cloneable { dos.writeInt(classmods); // 3. ordered list of interfaces - List list = new ArrayList(); + List list = new ArrayList(); String[] names = getInterfaceNames(); if (names!=null) { Arrays.sort(names); @@ -576,7 +577,7 @@ public class ClassGen extends Modifiers implements Cloneable { Collections.sort(list,new FieldComparator()); int relevantFlags = Constants.ACC_PUBLIC | Constants.ACC_PRIVATE | Constants.ACC_PROTECTED | Constants.ACC_STATIC | Constants.ACC_FINAL | Constants.ACC_VOLATILE | Constants.ACC_TRANSIENT; - for (Iterator iter = list.iterator(); iter.hasNext();) { + for (Iterator iter = list.iterator(); iter.hasNext();) { Field f = (Field) iter.next(); dos.writeUTF(f.getName()); dos.writeInt(relevantFlags&f.getModifiers()); @@ -585,7 +586,7 @@ public class ClassGen extends Modifiers implements Cloneable { // some up front method processing: discover clinit, init and ordinary methods of interest: list.clear(); // now used for methods - List ctors = new ArrayList(); + List ctors = new ArrayList(); boolean hasClinit = false; for (int i = 0; i < methods.length; i++) { Method m = methods[i]; @@ -621,15 +622,15 @@ public class ClassGen extends Modifiers implements Cloneable { Constants.ACC_NATIVE | Constants.ACC_ABSTRACT | Constants.ACC_STRICT; // 6. sorted non-private constructors - for (Iterator iter = ctors.iterator(); iter.hasNext();) { - Method m = (Method) iter.next(); + for (Iterator iter = ctors.iterator(); iter.hasNext();) { + Method m = iter.next(); dos.writeUTF(m.getName()); // dos.writeInt(relevantFlags & m.getModifiers()); dos.writeUTF(m.getSignature().replace('/','.')); } // 7. sorted non-private methods - for (Iterator iter = list.iterator(); iter.hasNext();) { + for (Iterator iter = list.iterator(); iter.hasNext();) { Method m = (Method) iter.next(); dos.writeUTF(m.getName()); dos.writeInt(relevantFlags & m.getModifiers()); @@ -682,16 +683,16 @@ public class ClassGen extends Modifiers implements Cloneable { } public boolean hasAttribute(String attributeName) { - for (Iterator iter = attributesList.iterator(); iter.hasNext();) { - Attribute attr = (Attribute) iter.next(); + for (Iterator iter = attributesList.iterator(); iter.hasNext();) { + Attribute attr = iter.next(); if (attr.getName().equals(attributeName)) return true; } return false; } public Attribute getAttribute(String attributeName) { - for (Iterator iter = attributesList.iterator(); iter.hasNext();) { - Attribute attr = (Attribute) iter.next(); + for (Iterator iter = attributesList.iterator(); iter.hasNext();) { + Attribute attr = iter.next(); if (attr.getName().equals(attributeName)) return attr; } return null; diff --git a/bcel-builder/src/org/aspectj/apache/bcel/generic/FieldGen.java b/bcel-builder/src/org/aspectj/apache/bcel/generic/FieldGen.java index e4d2d0917..20c5af83f 100644 --- a/bcel-builder/src/org/aspectj/apache/bcel/generic/FieldGen.java +++ b/bcel-builder/src/org/aspectj/apache/bcel/generic/FieldGen.java @@ -73,7 +73,7 @@ import org.aspectj.apache.bcel.classfile.annotation.RuntimeAnnotations; * one can do is to add a constant value attribute to a field (which must of * course be compatible with the declared type). * - * @version $Id: FieldGen.java,v 1.5 2008/05/28 23:52:59 aclement Exp $ + * @version $Id: FieldGen.java,v 1.6 2009/09/09 19:56:20 aclement Exp $ * @author M. Dahm * @see Field */ @@ -113,9 +113,9 @@ public class FieldGen extends FieldGenOrMethodGen { setValue(((ConstantValue)attrs[i]).getConstantValueIndex()); } else if (attrs[i] instanceof RuntimeAnnotations) { RuntimeAnnotations runtimeAnnotations = (RuntimeAnnotations)attrs[i]; - List l = runtimeAnnotations.getAnnotations(); - for (Iterator it = l.iterator(); it.hasNext();) { - AnnotationGen element = (AnnotationGen) it.next(); + List l = runtimeAnnotations.getAnnotations(); + for (Iterator it = l.iterator(); it.hasNext();) { + AnnotationGen element = it.next(); addAnnotation(new AnnotationGen(element,cp,false)); } } else { diff --git a/bcel-builder/src/org/aspectj/apache/bcel/generic/FieldGenOrMethodGen.java b/bcel-builder/src/org/aspectj/apache/bcel/generic/FieldGenOrMethodGen.java index 724c37ad8..94437abd5 100644 --- a/bcel-builder/src/org/aspectj/apache/bcel/generic/FieldGenOrMethodGen.java +++ b/bcel-builder/src/org/aspectj/apache/bcel/generic/FieldGenOrMethodGen.java @@ -67,7 +67,7 @@ import org.aspectj.apache.bcel.classfile.annotation.AnnotationGen; * Super class for FieldGen and MethodGen objects, since they have some methods * in common! * - * @version $Id: FieldGenOrMethodGen.java,v 1.4 2008/05/28 23:52:59 aclement Exp $ + * @version $Id: FieldGenOrMethodGen.java,v 1.5 2009/09/09 19:56:20 aclement Exp $ * @author M. Dahm */ public abstract class FieldGenOrMethodGen extends Modifiers implements Cloneable { @@ -75,8 +75,8 @@ public abstract class FieldGenOrMethodGen extends Modifiers implements Cloneable protected String name; protected Type type; protected ConstantPool cp; - private ArrayList/**/ attributeList = new ArrayList(); - private ArrayList annotationList = new ArrayList(); + private ArrayList/**/ attributeList = new ArrayList(); + private ArrayList annotationList = new ArrayList(); protected FieldGenOrMethodGen() { } @@ -129,7 +129,7 @@ public abstract class FieldGenOrMethodGen extends Modifiers implements Cloneable annotationList.clear(); } - public List/**/ getAttributes() { + public List/**/ getAttributes() { return attributeList; } diff --git a/bcel-builder/src/org/aspectj/apache/bcel/generic/InstructionHandle.java b/bcel-builder/src/org/aspectj/apache/bcel/generic/InstructionHandle.java index 90c10409a..72acb031d 100644 --- a/bcel-builder/src/org/aspectj/apache/bcel/generic/InstructionHandle.java +++ b/bcel-builder/src/org/aspectj/apache/bcel/generic/InstructionHandle.java @@ -68,7 +68,7 @@ import org.aspectj.apache.bcel.classfile.Utility; * doubly-linked list. From the outside only the next and the previous instruction (handle) are accessible. One can traverse the * list via an Enumeration returned by InstructionList.elements(). * - * @version $Id: InstructionHandle.java,v 1.6 2008/08/28 00:03:46 aclement Exp $ + * @version $Id: InstructionHandle.java,v 1.7 2009/09/09 19:56:20 aclement Exp $ * @author M. Dahm * @see Instruction * @see BranchHandle @@ -78,7 +78,7 @@ public class InstructionHandle implements java.io.Serializable { InstructionHandle next, prev; // Will be set from the outside Instruction instruction; protected int i_position = -1; // byte code offset of instruction - private HashSet targeters; + private HashSet targeters; public final InstructionHandle getNext() { return next; @@ -172,7 +172,7 @@ public class InstructionHandle implements java.io.Serializable { */ public void addTargeter(InstructionTargeter t) { if (targeters == null) { - targeters = new HashSet(); + targeters = new HashSet(); } // if(!targeters.contains(t)) @@ -193,7 +193,7 @@ public class InstructionHandle implements java.io.Serializable { return t; } - public Set getTargeters() { + public Set getTargeters() { if (targeters == null || targeters.size() == 0) { return Collections.EMPTY_SET; } diff --git a/bcel-builder/src/org/aspectj/apache/bcel/generic/InstructionList.java b/bcel-builder/src/org/aspectj/apache/bcel/generic/InstructionList.java index 1d10fd695..3475c35f5 100644 --- a/bcel-builder/src/org/aspectj/apache/bcel/generic/InstructionList.java +++ b/bcel-builder/src/org/aspectj/apache/bcel/generic/InstructionList.java @@ -76,7 +76,7 @@ import org.aspectj.apache.bcel.util.ByteSequence; * * A list is finally dumped to a byte code array with getByteCode. * - * @version $Id: InstructionList.java,v 1.7 2008/08/28 00:04:04 aclement Exp $ + * @version $Id: InstructionList.java,v 1.8 2009/09/09 19:56:20 aclement Exp $ * @author M. Dahm * @see Instruction * @see InstructionHandle @@ -685,7 +685,7 @@ public class InstructionList implements Serializable { return; } - ArrayList target_vec = new ArrayList(); + ArrayList target_vec = new ArrayList(); for (InstructionHandle ih = first; ih != null; ih = ih.next) { ih.getInstruction().dispose(); // e.g. BranchInstructions release their targets @@ -696,11 +696,11 @@ public class InstructionList implements Serializable { next = ih.next; length--; - Set targeters = ih.getTargeters(); + Set targeters = ih.getTargeters(); boolean isOK = false; - Iterator tIter = targeters.iterator(); + Iterator tIter = targeters.iterator(); while (tIter.hasNext()) { - InstructionTargeter instructionTargeter = (InstructionTargeter) tIter.next(); + InstructionTargeter instructionTargeter = tIter.next(); if (instructionTargeter.getClass().getName().endsWith("ShadowRange") || instructionTargeter.getClass().getName().endsWith("ExceptionRange") || instructionTargeter.getClass().getName().endsWith("LineNumberTag")) { @@ -983,7 +983,7 @@ public class InstructionList implements Serializable { */ public Instruction[] getInstructions() { ByteSequence bytes = new ByteSequence(getByteCode()); - ArrayList instructions = new ArrayList(); + ArrayList instructions = new ArrayList(); try { while (bytes.available() > 0) { @@ -1068,7 +1068,7 @@ public class InstructionList implements Serializable { * @return complete, i.e., deep copy of this list */ public InstructionList copy() { - HashMap map = new HashMap(); + HashMap map = new HashMap(); InstructionList il = new InstructionList(); /* @@ -1102,14 +1102,14 @@ public class InstructionList implements Serializable { InstructionHandle itarget = bi.getTarget(); // old target // New target is in hash map - bc.setTarget((InstructionHandle) map.get(itarget)); + bc.setTarget(map.get(itarget)); if (bi instanceof InstructionSelect) { // Either LOOKUPSWITCH or TABLESWITCH InstructionHandle[] itargets = ((InstructionSelect) bi).getTargets(); InstructionHandle[] ctargets = ((InstructionSelect) bc).getTargets(); for (int j = 0; j < itargets.length; j++) { // Update all targets - ctargets[j] = (InstructionHandle) map.get(itargets[j]); + ctargets[j] = map.get(itargets[j]); } } } diff --git a/bcel-builder/src/org/aspectj/apache/bcel/generic/MethodGen.java b/bcel-builder/src/org/aspectj/apache/bcel/generic/MethodGen.java index 7943178f5..0f723cf8d 100644 --- a/bcel-builder/src/org/aspectj/apache/bcel/generic/MethodGen.java +++ b/bcel-builder/src/org/aspectj/apache/bcel/generic/MethodGen.java @@ -84,7 +84,7 @@ import org.aspectj.apache.bcel.classfile.annotation.RuntimeParameterAnnotations; * While generating code it may be necessary to insert NOP operations. You can use the `removeNOPs' method to get rid off them. The * resulting method object can be obtained via the `getMethod()' method. * - * @version $Id: MethodGen.java,v 1.11 2009/05/28 00:12:52 aclement Exp $ + * @version $Id: MethodGen.java,v 1.12 2009/09/09 19:56:20 aclement Exp $ * @author M. Dahm * @author Patrick C. Beard [setMaxStack()] * @see InstructionList @@ -103,11 +103,11 @@ public class MethodGen extends FieldGenOrMethodGen { private int highestLineNumber = 0; - private ArrayList localVariablesList = new ArrayList(); - private ArrayList lineNumbersList = new ArrayList(); - private ArrayList exceptionsList = new ArrayList(); - private ArrayList throws_vec = new ArrayList(); - private ArrayList codeAttributesList = new ArrayList(); + private ArrayList localVariablesList = new ArrayList(); + private ArrayList lineNumbersList = new ArrayList(); + private ArrayList exceptionsList = new ArrayList(); + private ArrayList throws_vec = new ArrayList(); + private ArrayList codeAttributesList = new ArrayList(); private List[] param_annotations; // Array of lists containing AnnotationGen objects private boolean hasParameterAnnotations = false; private boolean haveUnpackedParameterAnnotations = false; @@ -332,9 +332,9 @@ public class MethodGen extends FieldGenOrMethodGen { addException(names[j]); } else if (a instanceof RuntimeAnnotations) { RuntimeAnnotations runtimeAnnotations = (RuntimeAnnotations) a; - List l = runtimeAnnotations.getAnnotations(); - for (Iterator it = l.iterator(); it.hasNext();) { - AnnotationGen element = (AnnotationGen) it.next(); + List l = runtimeAnnotations.getAnnotations(); + for (Iterator it = l.iterator(); it.hasNext();) { + AnnotationGen element = it.next(); addAnnotation(new AnnotationGen(element, cp, false)); } } else { @@ -514,7 +514,7 @@ public class MethodGen extends FieldGenOrMethodGen { LineNumber[] ln = new LineNumber[size]; for (int i = 0; i < size; i++) { - ln[i] = ((LineNumberGen) lineNumbersList.get(i)).getLineNumber(); + ln[i] = lineNumbersList.get(i).getLineNumber(); } return new LineNumberTable(cp.addUtf8("LineNumberTable"), 2 + ln.length * 4, ln, cp); @@ -572,7 +572,7 @@ public class MethodGen extends FieldGenOrMethodGen { try { for (int i = 0; i < size; i++) { - CodeExceptionGen c = (CodeExceptionGen) exceptionsList.get(i); + CodeExceptionGen c = exceptionsList.get(i); c_exc[i] = c.getCodeException(cp); } } catch (ArrayIndexOutOfBoundsException e) { @@ -622,7 +622,7 @@ public class MethodGen extends FieldGenOrMethodGen { try { for (int i = 0; i < size; i++) - ex[i] = cp.addClass((String) throws_vec.get(i)); + ex[i] = cp.addClass(throws_vec.get(i)); } catch (ArrayIndexOutOfBoundsException e) { } @@ -722,9 +722,9 @@ public class MethodGen extends FieldGenOrMethodGen { if ((il != null) && !isAbstract()) { // Remove any stale code attribute - List attributes = getAttributes(); + List attributes = getAttributes(); for (int i = 0; i < attributes.size(); i++) { - Attribute a = (Attribute) attributes.get(i); + Attribute a = attributes.get(i); if (a instanceof Code) removeAttribute(a); } @@ -901,8 +901,8 @@ public class MethodGen extends FieldGenOrMethodGen { } static final class BranchStack { - Stack branchTargets = new Stack(); - Hashtable visitedTargets = new Hashtable(); + Stack branchTargets = new Stack(); + Hashtable visitedTargets = new Hashtable(); public void push(InstructionHandle target, int stackDepth) { if (visited(target)) @@ -913,7 +913,7 @@ public class MethodGen extends FieldGenOrMethodGen { public BranchTarget pop() { if (!branchTargets.empty()) { - BranchTarget bt = (BranchTarget) branchTargets.pop(); + BranchTarget bt = branchTargets.pop(); return bt; } @@ -1023,7 +1023,7 @@ public class MethodGen extends FieldGenOrMethodGen { StringBuffer buf = new StringBuffer(signature); if (throws_vec.size() > 0) { - for (Iterator e = throws_vec.iterator(); e.hasNext();) + for (Iterator e = throws_vec.iterator(); e.hasNext();) buf.append("\n\t\tthrows " + e.next()); } @@ -1067,12 +1067,12 @@ public class MethodGen extends FieldGenOrMethodGen { if (haveUnpackedParameterAnnotations) return; // Find attributes that contain parameter annotation data - List attrs = getAttributes(); + List attrs = getAttributes(); RuntimeParameterAnnotations paramAnnVisAttr = null; RuntimeParameterAnnotations paramAnnInvisAttr = null; List accumulatedAnnotations = new ArrayList(); for (int i = 0; i < attrs.size(); i++) { - Attribute attribute = (Attribute) attrs.get(i); + Attribute attribute = attrs.get(i); if (attribute instanceof RuntimeParameterAnnotations) { // Initialize param_annotations @@ -1092,7 +1092,7 @@ public class MethodGen extends FieldGenOrMethodGen { // This returns Annotation[] ... AnnotationGen[] immutableArray = rpa.getAnnotationsOnParameter(j); // ... which needs transforming into an AnnotationGen[] ... - List mutable = makeMutableVersion(immutableArray); + List mutable = makeMutableVersion(immutableArray); // ... then add these to any we already know about param_annotations[j].addAll(mutable); } @@ -1105,8 +1105,8 @@ public class MethodGen extends FieldGenOrMethodGen { haveUnpackedParameterAnnotations = true; } - private List /* AnnotationGen */makeMutableVersion(AnnotationGen[] mutableArray) { - List result = new ArrayList(); + private List /* AnnotationGen */makeMutableVersion(AnnotationGen[] mutableArray) { + List result = new ArrayList(); for (int i = 0; i < mutableArray.length; i++) { result.add(new AnnotationGen(mutableArray[i], getConstantPool(), false)); } @@ -1119,11 +1119,11 @@ public class MethodGen extends FieldGenOrMethodGen { param_annotations = new List[parameterTypes.length]; hasParameterAnnotations = true; } - List existingAnnotations = param_annotations[parameterIndex]; + List existingAnnotations = param_annotations[parameterIndex]; if (existingAnnotations != null) { existingAnnotations.add(annotation); } else { - List l = new ArrayList(); + List l = new ArrayList(); l.add(annotation); param_annotations[parameterIndex] = l; } diff --git a/bcel-builder/src/org/aspectj/apache/bcel/generic/Type.java b/bcel-builder/src/org/aspectj/apache/bcel/generic/Type.java index 58de53fd1..66c11f1e8 100644 --- a/bcel-builder/src/org/aspectj/apache/bcel/generic/Type.java +++ b/bcel-builder/src/org/aspectj/apache/bcel/generic/Type.java @@ -62,415 +62,460 @@ import org.aspectj.apache.bcel.Constants; import org.aspectj.apache.bcel.classfile.ClassFormatException; import org.aspectj.apache.bcel.classfile.Utility; - -/** - * Abstract super class for all possible java types, namely basic types - * such as int, object types like String and array types, e.g. int[] - * - * @version $Id: Type.java,v 1.10 2008/06/23 04:01:47 aclement Exp $ - * @author M. Dahm +/** + * Abstract super class for all possible java types, namely basic types such as int, object types like String and array types, e.g. + * int[] * - * modified: - * AndyClement 2-mar-05: Removed unnecessary static and optimized + * @version $Id: Type.java,v 1.11 2009/09/09 19:56:20 aclement Exp $ + * @author M. Dahm + * + * modified: AndyClement 2-mar-05: Removed unnecessary static and optimized */ public abstract class Type implements java.io.Serializable { - protected byte type; - protected String signature; // signature for the type - - /* Predefined constants */ - public static final BasicType VOID = new BasicType(Constants.T_VOID); - public static final BasicType BOOLEAN = new BasicType(Constants.T_BOOLEAN); - public static final BasicType INT = new BasicType(Constants.T_INT); - public static final BasicType SHORT = new BasicType(Constants.T_SHORT); - public static final BasicType BYTE = new BasicType(Constants.T_BYTE); - public static final BasicType LONG = new BasicType(Constants.T_LONG); - public static final BasicType DOUBLE = new BasicType(Constants.T_DOUBLE); - public static final BasicType FLOAT = new BasicType(Constants.T_FLOAT); - public static final BasicType CHAR = new BasicType(Constants.T_CHAR); - public static final ObjectType OBJECT = new ObjectType("java.lang.Object"); - public static final ObjectType STRING = new ObjectType("java.lang.String"); - public static final ObjectType OBJECT_ARRAY = new ObjectType("java.lang.Object[]"); - public static final ObjectType STRING_ARRAY = new ObjectType("java.lang.String[]"); - public static final ObjectType STRINGBUFFER = new ObjectType("java.lang.StringBuffer"); - public static final ObjectType STRINGBUILDER= new ObjectType("java.lang.StringBuilder"); - public static final ObjectType THROWABLE = new ObjectType("java.lang.Throwable"); - public static final ObjectType CLASS = new ObjectType("java.lang.Class"); - public static final ObjectType INTEGER = new ObjectType("java.lang.Integer"); - public static final ObjectType EXCEPTION = new ObjectType("java.lang.Exception"); - public static final ObjectType LIST = new ObjectType("java.util.List"); - public static final ObjectType ITERATOR = new ObjectType("java.util.Iterator"); - public static final Type[] NO_ARGS = new Type[0]; - public static final ReferenceType NULL = new ReferenceType(){}; - public static final Type UNKNOWN = new Type(Constants.T_UNKNOWN,""){}; - public static final Type[] STRINGARRAY1 = new Type[]{STRING}; - public static final Type[] STRINGARRAY2 = new Type[]{STRING,STRING}; - public static final Type[] STRINGARRAY3 = new Type[]{STRING,STRING,STRING}; - public static final Type[] STRINGARRAY4 = new Type[]{STRING,STRING,STRING,STRING}; - public static final Type[] STRINGARRAY5 = new Type[]{STRING,STRING,STRING,STRING,STRING}; - public static final Type[] STRINGARRAY6 = new Type[]{STRING,STRING,STRING,STRING,STRING,STRING}; - public static final Type[] STRINGARRAY7 = new Type[]{STRING,STRING,STRING,STRING,STRING,STRING,STRING}; - - private static Map commonTypes = new HashMap(); - - static { - commonTypes.put(STRING.getSignature(), STRING); - commonTypes.put(THROWABLE.getSignature(), THROWABLE); - commonTypes.put(VOID.getSignature(), VOID); - commonTypes.put(BOOLEAN.getSignature(), BOOLEAN); - commonTypes.put(BYTE.getSignature(), BYTE); - commonTypes.put(SHORT.getSignature(), SHORT); - commonTypes.put(CHAR.getSignature(), CHAR); - commonTypes.put(INT.getSignature(), INT); - commonTypes.put(LONG.getSignature(), LONG); - commonTypes.put(DOUBLE.getSignature(), DOUBLE); - commonTypes.put(FLOAT.getSignature(), FLOAT); - commonTypes.put(CLASS.getSignature(), CLASS); - commonTypes.put(OBJECT.getSignature(), OBJECT); - commonTypes.put(STRING_ARRAY.getSignature(), STRING_ARRAY); - commonTypes.put(OBJECT_ARRAY.getSignature(), OBJECT_ARRAY); - commonTypes.put(INTEGER.getSignature(), INTEGER); - commonTypes.put(EXCEPTION.getSignature(), EXCEPTION); - commonTypes.put(STRINGBUFFER.getSignature(), STRINGBUFFER); - commonTypes.put(STRINGBUILDER.getSignature(), STRINGBUILDER); - commonTypes.put(LIST.getSignature(), LIST); - commonTypes.put(ITERATOR.getSignature(), ITERATOR); - - } - - protected Type(byte t, String s) { - type = t; - signature = s; - } - - /** - * @return signature for given type. - */ - public String getSignature() { return signature; } - - /** - * @return type as defined in Constants - */ - public byte getType() { return type; } - - /** - * @return stack size of this type (2 for long and double, 0 for void, 1 otherwise) - */ - public int getSize() { - switch(type) { - case Constants.T_DOUBLE: case Constants.T_LONG: - return 2; - case Constants.T_VOID: - return 0; - default: - return 1; - } - } - - /** - * @return Type string, e.g. 'int[]' - */ - public String toString() { - return ((this.equals(Type.NULL) || (type >= Constants.T_UNKNOWN)))? signature : - Utility.signatureToString(signature, false); - } - - /** - * Convert type to Java method signature, e.g. int[] f(java.lang.String x) - * becomes (Ljava/lang/String;)[I - * - * @param return_type what the method returns - * @param arg_types what are the argument types - * @return method signature for given type(s). - */ - public static String getMethodSignature(Type return_type, Type[] arg_types) { - StringBuffer buf = new StringBuffer("("); - int length = (arg_types == null)? 0 : arg_types.length; - for(int i=0; i < length; i++) { - buf.append(arg_types[i].getSignature()); - } - buf.append(')'); - buf.append(return_type.getSignature()); - return buf.toString(); - } - - public static final Type getType(String signature) { - Type t = (Type)commonTypes.get(signature); - if (t!=null) return t; - byte type = Utility.typeOfSignature(signature); - if (type <= Constants.T_VOID) { - return BasicType.getType(type); - } else if (type == Constants.T_ARRAY) { - int dim=0; - do { dim++; } while(signature.charAt(dim) == '['); - // Recurse, but just once, if the signature is ok - Type componentType = getType(signature.substring(dim)); - return new ArrayType(componentType, dim); - } else { // type == T_REFERENCE - // generics awareness - int nextAngly = signature.indexOf('<'); - // Format is 'Lblahblah;' - int index = signature.indexOf(';'); // Look for closing ';' - - String typeString = null; - if (nextAngly==-1 || nextAngly>index) { - typeString = signature.substring(1,index).replace('/','.'); - } else { - boolean endOfSigReached = false; - int posn = nextAngly; - int genericDepth=0; - while (!endOfSigReached) { - switch (signature.charAt(posn++)) { - case '<': genericDepth++;break; - case '>': genericDepth--;break; - case ';': if (genericDepth==0) endOfSigReached=true;break; - default: + protected byte type; + protected String signature; // signature for the type + + /* Predefined constants */ + public static final BasicType VOID = new BasicType(Constants.T_VOID); + public static final BasicType BOOLEAN = new BasicType(Constants.T_BOOLEAN); + public static final BasicType INT = new BasicType(Constants.T_INT); + public static final BasicType SHORT = new BasicType(Constants.T_SHORT); + public static final BasicType BYTE = new BasicType(Constants.T_BYTE); + public static final BasicType LONG = new BasicType(Constants.T_LONG); + public static final BasicType DOUBLE = new BasicType(Constants.T_DOUBLE); + public static final BasicType FLOAT = new BasicType(Constants.T_FLOAT); + public static final BasicType CHAR = new BasicType(Constants.T_CHAR); + public static final ObjectType OBJECT = new ObjectType("java.lang.Object"); + public static final ObjectType STRING = new ObjectType("java.lang.String"); + public static final ObjectType OBJECT_ARRAY = new ObjectType("java.lang.Object[]"); + public static final ObjectType STRING_ARRAY = new ObjectType("java.lang.String[]"); + public static final ObjectType STRINGBUFFER = new ObjectType("java.lang.StringBuffer"); + public static final ObjectType STRINGBUILDER = new ObjectType("java.lang.StringBuilder"); + public static final ObjectType THROWABLE = new ObjectType("java.lang.Throwable"); + public static final ObjectType CLASS = new ObjectType("java.lang.Class"); + public static final ObjectType INTEGER = new ObjectType("java.lang.Integer"); + public static final ObjectType EXCEPTION = new ObjectType("java.lang.Exception"); + public static final ObjectType LIST = new ObjectType("java.util.List"); + public static final ObjectType ITERATOR = new ObjectType("java.util.Iterator"); + public static final Type[] NO_ARGS = new Type[0]; + public static final ReferenceType NULL = new ReferenceType() { + }; + public static final Type UNKNOWN = new Type(Constants.T_UNKNOWN, "") { + }; + public static final Type[] STRINGARRAY1 = new Type[] { STRING }; + public static final Type[] STRINGARRAY2 = new Type[] { STRING, STRING }; + public static final Type[] STRINGARRAY3 = new Type[] { STRING, STRING, STRING }; + public static final Type[] STRINGARRAY4 = new Type[] { STRING, STRING, STRING, STRING }; + public static final Type[] STRINGARRAY5 = new Type[] { STRING, STRING, STRING, STRING, STRING }; + public static final Type[] STRINGARRAY6 = new Type[] { STRING, STRING, STRING, STRING, STRING, STRING }; + public static final Type[] STRINGARRAY7 = new Type[] { STRING, STRING, STRING, STRING, STRING, STRING, STRING }; + + private static Map commonTypes = new HashMap(); + + static { + commonTypes.put(STRING.getSignature(), STRING); + commonTypes.put(THROWABLE.getSignature(), THROWABLE); + commonTypes.put(VOID.getSignature(), VOID); + commonTypes.put(BOOLEAN.getSignature(), BOOLEAN); + commonTypes.put(BYTE.getSignature(), BYTE); + commonTypes.put(SHORT.getSignature(), SHORT); + commonTypes.put(CHAR.getSignature(), CHAR); + commonTypes.put(INT.getSignature(), INT); + commonTypes.put(LONG.getSignature(), LONG); + commonTypes.put(DOUBLE.getSignature(), DOUBLE); + commonTypes.put(FLOAT.getSignature(), FLOAT); + commonTypes.put(CLASS.getSignature(), CLASS); + commonTypes.put(OBJECT.getSignature(), OBJECT); + commonTypes.put(STRING_ARRAY.getSignature(), STRING_ARRAY); + commonTypes.put(OBJECT_ARRAY.getSignature(), OBJECT_ARRAY); + commonTypes.put(INTEGER.getSignature(), INTEGER); + commonTypes.put(EXCEPTION.getSignature(), EXCEPTION); + commonTypes.put(STRINGBUFFER.getSignature(), STRINGBUFFER); + commonTypes.put(STRINGBUILDER.getSignature(), STRINGBUILDER); + commonTypes.put(LIST.getSignature(), LIST); + commonTypes.put(ITERATOR.getSignature(), ITERATOR); + + } + + protected Type(byte t, String s) { + type = t; + signature = s; + } + + /** + * @return signature for given type. + */ + public String getSignature() { + return signature; + } + + /** + * @return type as defined in Constants + */ + public byte getType() { + return type; + } + + /** + * @return stack size of this type (2 for long and double, 0 for void, 1 otherwise) + */ + public int getSize() { + switch (type) { + case Constants.T_DOUBLE: + case Constants.T_LONG: + return 2; + case Constants.T_VOID: + return 0; + default: + return 1; + } + } + + /** + * @return Type string, e.g. 'int[]' + */ + @Override + public String toString() { + return ((this.equals(Type.NULL) || (type >= Constants.T_UNKNOWN))) ? signature : Utility + .signatureToString(signature, false); + } + + /** + * Convert type to Java method signature, e.g. int[] f(java.lang.String x) becomes (Ljava/lang/String;)[I + * + * @param return_type what the method returns + * @param arg_types what are the argument types + * @return method signature for given type(s). + */ + public static String getMethodSignature(Type return_type, Type[] arg_types) { + StringBuffer buf = new StringBuffer("("); + int length = (arg_types == null) ? 0 : arg_types.length; + for (int i = 0; i < length; i++) { + buf.append(arg_types[i].getSignature()); + } + buf.append(')'); + buf.append(return_type.getSignature()); + return buf.toString(); + } + + public static final Type getType(String signature) { + Type t = commonTypes.get(signature); + if (t != null) + return t; + byte type = Utility.typeOfSignature(signature); + if (type <= Constants.T_VOID) { + return BasicType.getType(type); + } else if (type == Constants.T_ARRAY) { + int dim = 0; + do { + dim++; + } while (signature.charAt(dim) == '['); + // Recurse, but just once, if the signature is ok + Type componentType = getType(signature.substring(dim)); + return new ArrayType(componentType, dim); + } else { // type == T_REFERENCE + // generics awareness + int nextAngly = signature.indexOf('<'); + // Format is 'Lblahblah;' + int index = signature.indexOf(';'); // Look for closing ';' + + String typeString = null; + if (nextAngly == -1 || nextAngly > index) { + typeString = signature.substring(1, index).replace('/', '.'); + } else { + boolean endOfSigReached = false; + int posn = nextAngly; + int genericDepth = 0; + while (!endOfSigReached) { + switch (signature.charAt(posn++)) { + case '<': + genericDepth++; + break; + case '>': + genericDepth--; + break; + case ';': + if (genericDepth == 0) + endOfSigReached = true; + break; + default: + } + } + index = posn - 1; + typeString = signature.substring(1, nextAngly).replace('/', '.'); + } + // ObjectType doesn't currently store parameterized info + return new ObjectType(typeString); + } + } + + /** + * Convert signature to a Type object. + * + * @param signature signature string such as Ljava/lang/String; + * @return type object + */ + public static final TypeHolder getTypeInternal(String signature) throws StringIndexOutOfBoundsException { + byte type = Utility.typeOfSignature(signature); + + if (type <= Constants.T_VOID) { + return new TypeHolder(BasicType.getType(type), 1); + } else if (type == Constants.T_ARRAY) { + int dim = 0; + do { + dim++; + } while (signature.charAt(dim) == '['); + // Recurse, but just once, if the signature is ok + TypeHolder th = getTypeInternal(signature.substring(dim)); + return new TypeHolder(new ArrayType(th.getType(), dim), dim + th.getConsumed()); + } else { // type == T_REFERENCE + // Format is 'Lblahblah;' + int index = signature.indexOf(';'); // Look for closing ';' + if (index < 0) + throw new ClassFormatException("Invalid signature: " + signature); + + // generics awareness + int nextAngly = signature.indexOf('<'); + String typeString = null; + if (nextAngly == -1 || nextAngly > index) { + typeString = signature.substring(1, index).replace('/', '.'); + } else { + boolean endOfSigReached = false; + int posn = nextAngly; + int genericDepth = 0; + while (!endOfSigReached) { + switch (signature.charAt(posn++)) { + case '<': + genericDepth++; + break; + case '>': + genericDepth--; + break; + case ';': + if (genericDepth == 0) + endOfSigReached = true; + break; + default: + } } + index = posn - 1; + typeString = signature.substring(1, nextAngly).replace('/', '.'); } - index=posn-1; - typeString = signature.substring(1,nextAngly).replace('/','.'); - } - // ObjectType doesn't currently store parameterized info - return new ObjectType(typeString); - } - } - - /** - * Convert signature to a Type object. - * @param signature signature string such as Ljava/lang/String; - * @return type object - */ - public static final TypeHolder getTypeInternal(String signature) throws StringIndexOutOfBoundsException { - byte type = Utility.typeOfSignature(signature); - - if (type <= Constants.T_VOID) { - return new TypeHolder(BasicType.getType(type),1); - } else if (type == Constants.T_ARRAY) { - int dim=0; - do { dim++; } while(signature.charAt(dim) == '['); - // Recurse, but just once, if the signature is ok - TypeHolder th = getTypeInternal(signature.substring(dim)); - return new TypeHolder(new ArrayType(th.getType(), dim),dim+th.getConsumed()); - } else { // type == T_REFERENCE - // Format is 'Lblahblah;' - int index = signature.indexOf(';'); // Look for closing ';' - if (index < 0) throw new ClassFormatException("Invalid signature: " + signature); - - // generics awareness - int nextAngly = signature.indexOf('<'); - String typeString = null; - if (nextAngly==-1 || nextAngly>index) { - typeString = signature.substring(1,index).replace('/','.'); - } else { - boolean endOfSigReached = false; - int posn = nextAngly; - int genericDepth=0; - while (!endOfSigReached) { - switch (signature.charAt(posn++)) { - case '<': genericDepth++;break; - case '>': genericDepth--;break; - case ';': if (genericDepth==0) endOfSigReached=true;break; - default: + // ObjectType doesn't currently store parameterized info + return new TypeHolder(new ObjectType(typeString), index + 1); + } + } + + /** + * Convert return value of a method (signature) to a Type object. + * + * @param signature signature string such as (Ljava/lang/String;)V + * @return return type + */ + public static Type getReturnType(String signature) { + try { + // Read return type after `)' + int index = signature.lastIndexOf(')') + 1; + return getType(signature.substring(index)); + } catch (StringIndexOutOfBoundsException e) { // Should never occur + throw new ClassFormatException("Invalid method signature: " + signature); + } + } + + /** + * Convert arguments of a method (signature) to an array of Type objects. + * + * @param signature signature string such as (Ljava/lang/String;)V + * @return array of argument types + */ + // OPTIMIZE crap impl + public static Type[] getArgumentTypes(String signature) { + ArrayList vec = new ArrayList(); + int index; + Type[] types; + + try { // Read all declarations between for `(' and `)' + if (signature.charAt(0) != '(') + throw new ClassFormatException("Invalid method signature: " + signature); + + index = 1; // current string position + + while (signature.charAt(index) != ')') { + TypeHolder th = getTypeInternal(signature.substring(index)); + vec.add(th.getType()); + index += th.getConsumed(); // update position } + } catch (StringIndexOutOfBoundsException e) { // Should never occur + throw new ClassFormatException("Invalid method signature: " + signature); + } + + types = new Type[vec.size()]; + vec.toArray(types); + return types; + } + + /** + * Work out the type of each argument in the signature and return the cumulative sizes of all the types (size means number of + * stack slots it consumes, eg double=2, int=1). Unlike the call above, this does minimal unpacking + */ + public static int getArgumentSizes(String signature) { + int size = 0; + if (signature.charAt(0) != '(') + throw new ClassFormatException("Invalid method signature: " + signature); + + int index = 1; // current string position + try { + while (signature.charAt(index) != ')') { + byte type = Utility.typeOfSignature(signature.charAt(index)); + if (type <= Constants.T_VOID) { + size += BasicType.getType(type).getSize(); + index++; + } else if (type == Constants.T_ARRAY) { + int dim = 0; + do { + dim++; + } while (signature.charAt(dim + index) == '['); + TypeHolder th = getTypeInternal(signature.substring(dim + index)); + size += 1; + index += dim + th.getConsumed(); + } else { // type == T_REFERENCE + // Format is 'Lblahblah;' + int index2 = signature.indexOf(';', index); // Look for closing ';' + + // generics awareness + int nextAngly = signature.indexOf('<', index); + if (nextAngly == -1 || nextAngly > index2) { + } else { + boolean endOfSigReached = false; + int posn = nextAngly; + int genericDepth = 0; + while (!endOfSigReached) { + switch (signature.charAt(posn++)) { + case '<': + genericDepth++; + break; + case '>': + genericDepth--; + break; + case ';': + if (genericDepth == 0) + endOfSigReached = true; + break; + default: + } + } + index2 = posn - 1; + } + size++; + index = index2 + 1; + } + } + } catch (StringIndexOutOfBoundsException e) { // Should never occur + throw new ClassFormatException("Invalid method signature: " + signature); + } + return size; + } + + /** + * Return the size of the type expressed in the signature. The signature should contain only one type. + */ + public static int getTypeSize(String signature) { + byte type = Utility.typeOfSignature(signature.charAt(0)); + if (type <= Constants.T_VOID) { + return BasicType.getType(type).getSize(); + } else if (type == Constants.T_ARRAY) { + return 1; + } else { // type == T_REFERENCE + return 1; + } + } + + /** + * Convert runtime java.lang.Class to BCEL Type object. + * + * @param cl Java class + * @return corresponding Type object + */ + public static Type getType(java.lang.Class cl) { + if (cl == null) { + throw new IllegalArgumentException("Class must not be null"); + } + + /* + * That's an amazingly easy case, because getName() returns the signature. That's what we would have liked anyway. + */ + if (cl.isArray()) { + return getType(cl.getName()); + } else if (cl.isPrimitive()) { + if (cl == Integer.TYPE) { + return INT; + } else if (cl == Void.TYPE) { + return VOID; + } else if (cl == Double.TYPE) { + return DOUBLE; + } else if (cl == Float.TYPE) { + return FLOAT; + } else if (cl == Boolean.TYPE) { + return BOOLEAN; + } else if (cl == Byte.TYPE) { + return BYTE; + } else if (cl == Short.TYPE) { + return SHORT; + } else if (cl == Byte.TYPE) { + return BYTE; + } else if (cl == Long.TYPE) { + return LONG; + } else if (cl == Character.TYPE) { + return CHAR; + } else { + throw new IllegalStateException("Ooops, what primitive type is " + cl); + } + } else { // "Real" class + return new ObjectType(cl.getName()); + } + } + + public static String getSignature(java.lang.reflect.Method meth) { + StringBuffer sb = new StringBuffer("("); + Class[] params = meth.getParameterTypes(); // avoid clone + + for (int j = 0; j < params.length; j++) { + sb.append(getType(params[j]).getSignature()); + } + + sb.append(")"); + sb.append(getType(meth.getReturnType()).getSignature()); + return sb.toString(); + } + + public static String getSignature(java.lang.reflect.Constructor cons) { + StringBuffer sb = new StringBuffer("("); + Class[] params = cons.getParameterTypes(); // avoid clone + + for (int j = 0; j < params.length; j++) { + sb.append(getType(params[j]).getSignature()); + } + + sb.append(")V"); + return sb.toString(); + } + + public static class TypeHolder { + private Type t; + private int consumed; + + public Type getType() { + return t; + } + + public int getConsumed() { + return consumed; + } + + public TypeHolder(Type t, int i) { + this.t = t; + this.consumed = i; } - index=posn-1; - typeString = signature.substring(1,nextAngly).replace('/','.'); - } - // ObjectType doesn't currently store parameterized info - return new TypeHolder(new ObjectType(typeString),index+1); - } - } - - /** - * Convert return value of a method (signature) to a Type object. - * - * @param signature signature string such as (Ljava/lang/String;)V - * @return return type - */ - public static Type getReturnType(String signature) { - try { - // Read return type after `)' - int index = signature.lastIndexOf(')') + 1; - return getType(signature.substring(index)); - } catch(StringIndexOutOfBoundsException e) { // Should never occur - throw new ClassFormatException("Invalid method signature: " + signature); - } - } - - /** - * Convert arguments of a method (signature) to an array of Type objects. - * @param signature signature string such as (Ljava/lang/String;)V - * @return array of argument types - */ - // OPTIMIZE crap impl - public static Type[] getArgumentTypes(String signature) { - ArrayList vec = new ArrayList(); - int index; - Type[] types; - - try { // Read all declarations between for `(' and `)' - if (signature.charAt(0) != '(') - throw new ClassFormatException("Invalid method signature: " + signature); - - index = 1; // current string position - - while(signature.charAt(index) != ')') { - TypeHolder th = getTypeInternal(signature.substring(index)); - vec.add(th.getType()); - index += th.getConsumed(); // update position - } - } catch(StringIndexOutOfBoundsException e) { // Should never occur - throw new ClassFormatException("Invalid method signature: " + signature); - } - - types = new Type[vec.size()]; - vec.toArray(types); - return types; - } - - /** - * Work out the type of each argument in the signature and return the cumulative sizes of - * all the types (size means number of stack slots it consumes, eg double=2, int=1). - * Unlike the call above, this does minimal unpacking - */ - public static int getArgumentSizes(String signature) { - int size = 0; - if (signature.charAt(0) != '(') - throw new ClassFormatException("Invalid method signature: " + signature); - - int index = 1; // current string position - try { - while (signature.charAt(index) != ')') { - byte type = Utility.typeOfSignature(signature.charAt(index)); - if (type<=Constants.T_VOID) { - size+=BasicType.getType(type).getSize(); - index++; - } else if (type==Constants.T_ARRAY) { - int dim=0; - do { dim++; } while(signature.charAt(dim+index) == '['); - TypeHolder th = getTypeInternal(signature.substring(dim+index)); - size+=1; - index+=dim+th.getConsumed(); - } else { // type == T_REFERENCE - // Format is 'Lblahblah;' - int index2 = signature.indexOf(';',index); // Look for closing ';' - - // generics awareness - int nextAngly = signature.indexOf('<',index); - if (nextAngly==-1 || nextAngly>index2) { - } else { - boolean endOfSigReached = false; - int posn = nextAngly; - int genericDepth=0; - while (!endOfSigReached) { - switch (signature.charAt(posn++)) { - case '<': genericDepth++;break; - case '>': genericDepth--;break; - case ';': if (genericDepth==0) endOfSigReached=true;break; - default: - } - } - index2=posn-1; - } - size++; - index=index2+1; - } - } - } catch(StringIndexOutOfBoundsException e) { // Should never occur - throw new ClassFormatException("Invalid method signature: " + signature); - } - return size; - } - - /** - * Return the size of the type expressed in the signature. The signature should contain only one type. - */ - public static int getTypeSize(String signature) { - byte type = Utility.typeOfSignature(signature.charAt(0)); - if (type<=Constants.T_VOID) { - return BasicType.getType(type).getSize(); - } else if (type==Constants.T_ARRAY) { - return 1; - } else { // type == T_REFERENCE - return 1; - } - } - - /** Convert runtime java.lang.Class to BCEL Type object. - * @param cl Java class - * @return corresponding Type object - */ - public static Type getType(java.lang.Class cl) { - if(cl == null) { - throw new IllegalArgumentException("Class must not be null"); - } - - /* That's an amazingly easy case, because getName() returns - * the signature. That's what we would have liked anyway. - */ - if(cl.isArray()) { - return getType(cl.getName()); - } else if(cl.isPrimitive()) { - if(cl == Integer.TYPE) { - return INT; - } else if(cl == Void.TYPE) { - return VOID; - } else if(cl == Double.TYPE) { - return DOUBLE; - } else if(cl == Float.TYPE) { - return FLOAT; - } else if(cl == Boolean.TYPE) { - return BOOLEAN; - } else if(cl == Byte.TYPE) { - return BYTE; - } else if(cl == Short.TYPE) { - return SHORT; - } else if(cl == Byte.TYPE) { - return BYTE; - } else if(cl == Long.TYPE) { - return LONG; - } else if(cl == Character.TYPE) { - return CHAR; - } else { - throw new IllegalStateException("Ooops, what primitive type is " + cl); - } - } else { // "Real" class - return new ObjectType(cl.getName()); - } - } - - public static String getSignature(java.lang.reflect.Method meth) { - StringBuffer sb = new StringBuffer("("); - Class[] params = meth.getParameterTypes(); // avoid clone - - for(int j = 0; j < params.length; j++) { - sb.append(getType(params[j]).getSignature()); - } - - sb.append(")"); - sb.append(getType(meth.getReturnType()).getSignature()); - return sb.toString(); - } - - public static String getSignature(java.lang.reflect.Constructor cons) { - StringBuffer sb = new StringBuffer("("); - Class[] params = cons.getParameterTypes(); // avoid clone - - for(int j = 0; j < params.length; j++) { - sb.append(getType(params[j]).getSignature()); - } - - sb.append(")V"); - return sb.toString(); - } - - public static class TypeHolder { - private Type t; - private int consumed; - - public Type getType() {return t;} - public int getConsumed() { return consumed;} - - public TypeHolder(Type t,int i) { this.t=t;this.consumed = i;} - } + } } diff --git a/bcel-builder/src/org/aspectj/apache/bcel/util/ClassLoaderRepository.java b/bcel-builder/src/org/aspectj/apache/bcel/util/ClassLoaderRepository.java index f90f784c9..eb33d8b4e 100644 --- a/bcel-builder/src/org/aspectj/apache/bcel/util/ClassLoaderRepository.java +++ b/bcel-builder/src/org/aspectj/apache/bcel/util/ClassLoaderRepository.java @@ -70,302 +70,327 @@ import java.util.WeakHashMap; import org.aspectj.apache.bcel.classfile.ClassParser; import org.aspectj.apache.bcel.classfile.JavaClass; +import org.aspectj.apache.bcel.util.ClassLoaderRepository.SoftHashMap.SpecialValue; /** - * The repository maintains information about which classes have - * been loaded. - * - * It loads its data from the ClassLoader implementation - * passed into its constructor. - * + * The repository maintains information about which classes have been loaded. + * + * It loads its data from the ClassLoader implementation passed into its constructor. + * * @see org.aspectj.apache.bcel.Repository - * - * @version $Id: ClassLoaderRepository.java,v 1.12 2008/08/26 15:02:41 aclement Exp $ + * + * @version $Id: ClassLoaderRepository.java,v 1.13 2009/09/09 19:56:20 aclement Exp $ * @author M. Dahm * @author David Dixon-Peugh */ public class ClassLoaderRepository implements Repository { - private static java.lang.ClassLoader bootClassLoader = null; - private ClassLoaderReference loaderRef; - - // Choice of cache... - private WeakHashMap /**/localCache = new WeakHashMap(); - private static SoftHashMap /**/sharedCache = new SoftHashMap(Collections.synchronizedMap(new HashMap())); - - // For fast translation of the classname *intentionally not static* - private SoftHashMap /**/ nameMap = new SoftHashMap(new HashMap(), false); - - public static boolean useSharedCache = - System.getProperty("org.aspectj.apache.bcel.useSharedCache","true").equalsIgnoreCase("true"); - - private static int cacheHitsShared = 0; - private static int missSharedEvicted = 0; // Misses in shared cache access due to reference GC - private long timeManipulatingURLs = 0L; - private long timeSpentLoading = 0L; - private int classesLoadedCount = 0; - private int misses = 0; - private int cacheHitsLocal = 0; - private int missLocalEvicted = 0; // Misses in local cache access due to reference GC - - public ClassLoaderRepository(java.lang.ClassLoader loader) { - this.loaderRef = new DefaultClassLoaderReference((loader != null) ? loader : getBootClassLoader()); - } - - public ClassLoaderRepository(ClassLoaderReference loaderRef) { - this.loaderRef = loaderRef; - } - - private static synchronized java.lang.ClassLoader getBootClassLoader() { - if (bootClassLoader == null) { - bootClassLoader = new URLClassLoader(new URL[0]); - } - return bootClassLoader; - } - - // Can track back to its key - public static class SoftHashMap extends AbstractMap { - private Map map; - boolean recordMiss = true; // only interested in recording miss stats sometimes - private ReferenceQueue rq = new ReferenceQueue(); - - public SoftHashMap(Map map) { this.map = map; } - public SoftHashMap() { this(new HashMap()); } - public SoftHashMap(Map map, boolean b) { this(map); this.recordMiss=b;} - - class SpecialValue extends SoftReference { - private final Object key; - SpecialValue(Object k,Object v) { - super(v,rq); - this.key = k; - } - } - - private void processQueue() { - SpecialValue sv = null; - while ((sv = (SpecialValue)rq.poll())!=null) { - map.remove(sv.key); + private static java.lang.ClassLoader bootClassLoader = null; + private ClassLoaderReference loaderRef; + + // Choice of cache... + private WeakHashMap /* */> localCache = new WeakHashMap>(); + private static SoftHashMap /* */sharedCache = new SoftHashMap(Collections + .synchronizedMap(new HashMap())); + + // For fast translation of the classname *intentionally not static* + private SoftHashMap /* */nameMap = new SoftHashMap(new HashMap(), false); + + public static boolean useSharedCache = System.getProperty("org.aspectj.apache.bcel.useSharedCache", "true").equalsIgnoreCase( + "true"); + + private static int cacheHitsShared = 0; + private static int missSharedEvicted = 0; // Misses in shared cache access due to reference GC + private long timeManipulatingURLs = 0L; + private long timeSpentLoading = 0L; + private int classesLoadedCount = 0; + private int misses = 0; + private int cacheHitsLocal = 0; + private int missLocalEvicted = 0; // Misses in local cache access due to reference GC + + public ClassLoaderRepository(java.lang.ClassLoader loader) { + this.loaderRef = new DefaultClassLoaderReference((loader != null) ? loader : getBootClassLoader()); + } + + public ClassLoaderRepository(ClassLoaderReference loaderRef) { + this.loaderRef = loaderRef; + } + + private static synchronized java.lang.ClassLoader getBootClassLoader() { + if (bootClassLoader == null) { + bootClassLoader = new URLClassLoader(new URL[0]); + } + return bootClassLoader; + } + + // Can track back to its key + public static class SoftHashMap extends AbstractMap { + private Map map; + boolean recordMiss = true; // only interested in recording miss stats sometimes + private ReferenceQueue rq = new ReferenceQueue(); + + public SoftHashMap(Map map) { + this.map = map; + } + + public SoftHashMap() { + this(new HashMap()); + } + + public SoftHashMap(Map map, boolean b) { + this(map); + this.recordMiss = b; + } + + class SpecialValue extends SoftReference { + private final Object key; + + SpecialValue(Object k, Object v) { + super(v, rq); + this.key = k; + } + } + + private void processQueue() { + SpecialValue sv = null; + while ((sv = (SpecialValue) rq.poll()) != null) { + map.remove(sv.key); + } + } + + @Override + public Object get(Object key) { + SpecialValue value = map.get(key); + if (value == null) + return null; + if (value.get() == null) { + // it got GC'd + map.remove(value.key); + if (recordMiss) + missSharedEvicted++; + return null; + } else { + return value.get(); + } + } + + @Override + public Object put(Object k, Object v) { + processQueue(); + return map.put(k, new SpecialValue(k, v)); } - } - - public Object get(Object key) { - SpecialValue value = (SpecialValue)map.get(key); - if (value==null) return null; - if (value.get()==null) { - // it got GC'd - map.remove(value.key); - if (recordMiss) missSharedEvicted++; + + @Override + public Set entrySet() { + return map.entrySet(); + } + + @Override + public void clear() { + processQueue(); + map.clear(); + } + + @Override + public int size() { + processQueue(); + return map.size(); + } + + @Override + public Object remove(Object k) { + processQueue(); + SpecialValue value = map.remove(k); + if (value == null) + return null; + if (value.get() != null) { + return value.get(); + } return null; + } + } + + /** + * Store a new JavaClass into this repository as a soft reference and return the reference + */ + private void storeClassAsReference(URL url, JavaClass clazz) { + if (useSharedCache) { + clazz.setRepository(null); // can't risk setting repository, we'll get in a pickle! + sharedCache.put(url, clazz); } else { - return value.get(); + clazz.setRepository(this); + localCache.put(url, new SoftReference(clazz)); } - } - - public Object put(Object k, Object v) { - processQueue(); - return map.put(k, new SpecialValue(k,v)); - } - - public Set entrySet() { - return map.entrySet(); - } - - public void clear() { - processQueue(); - map.clear(); - } - - public int size() { - processQueue(); - return map.size(); - } - - public Object remove(Object k) { - processQueue(); - SpecialValue value = (SpecialValue)map.remove(k); - if (value==null) return null; - if (value.get()!=null) { - return value.get(); + } + + /** + * Store a new JavaClass into this Repository. + */ + public void storeClass(JavaClass clazz) { + storeClassAsReference(toURL(clazz.getClassName()), clazz); + } + + /** + * Remove class from repository + */ + public void removeClass(JavaClass clazz) { + if (useSharedCache) + sharedCache.remove(toURL(clazz.getClassName())); + else + localCache.remove(toURL(clazz.getClassName())); + } + + /** + * Find an already defined JavaClass in the local cache. + */ + public JavaClass findClass(String className) { + if (useSharedCache) + return findClassShared(toURL(className)); + else + return findClassLocal(toURL(className)); + } + + private JavaClass findClassLocal(URL url) { + Object o = localCache.get(url); + if (o != null) { + o = ((Reference) o).get(); + if (o != null) { + return (JavaClass) o; + } else { + missLocalEvicted++; + } } return null; - } - } - - /** - * Store a new JavaClass into this repository as a soft reference and return the reference - */ - private void storeClassAsReference(URL url, JavaClass clazz ) { - if (useSharedCache) { - clazz.setRepository(null); // can't risk setting repository, we'll get in a pickle! - sharedCache.put(url, clazz); - } else { - clazz.setRepository(this); - localCache.put(url, new SoftReference(clazz)); } - } - - /** - * Store a new JavaClass into this Repository. - */ - public void storeClass( JavaClass clazz ) { - storeClassAsReference(toURL(clazz.getClassName()),clazz); - } - - /** - * Remove class from repository - */ - public void removeClass(JavaClass clazz) { - if (useSharedCache) sharedCache.remove(toURL(clazz.getClassName())); - else localCache.remove(toURL(clazz.getClassName())); - } - - /** - * Find an already defined JavaClass in the local cache. - */ - public JavaClass findClass( String className ) { - if (useSharedCache) return findClassShared(toURL(className)); - else return findClassLocal(toURL(className)); - } - - private JavaClass findClassLocal( URL url ) { - Object o = localCache.get(url); - if (o != null) { - o = ((Reference)o).get(); - if (o != null) { - return (JavaClass)o; - } else { - missLocalEvicted++; - } - } - return null; - } - - /** - * Find an already defined JavaClass in the shared cache. - */ - private JavaClass findClassShared(URL url) { - return (JavaClass)sharedCache.get(url); - } - - private URL toURL(String className) { - URL url = (URL)nameMap.get(className); - if (url==null) { - String classFile = className.replace('.', '/'); - url = loaderRef.getClassLoader().getResource(classFile + ".class"); - nameMap.put(className, url); - } - return url; - } - - /** - * Lookup a JavaClass object from the Class Name provided. - */ - public JavaClass loadClass( String className ) throws ClassNotFoundException { - - // translate to a URL - long time = System.currentTimeMillis(); - java.net.URL url = toURL(className); - timeManipulatingURLs += (System.currentTimeMillis() - time); - if (url==null) throw new ClassNotFoundException(className + " not found - unable to determine URL"); - - JavaClass clazz = null; - - // Look in the appropriate cache - if (useSharedCache) { - clazz = findClassShared(url); - if (clazz != null) { cacheHitsShared++; return clazz; } - } else { - clazz = findClassLocal(url); - if (clazz != null) { cacheHitsLocal++; return clazz; } + + /** + * Find an already defined JavaClass in the shared cache. + */ + private JavaClass findClassShared(URL url) { + return (JavaClass) sharedCache.get(url); + } + + private URL toURL(String className) { + URL url = (URL) nameMap.get(className); + if (url == null) { + String classFile = className.replace('.', '/'); + url = loaderRef.getClassLoader().getResource(classFile + ".class"); + nameMap.put(className, url); + } + return url; + } + + /** + * Lookup a JavaClass object from the Class Name provided. + */ + public JavaClass loadClass(String className) throws ClassNotFoundException { + + // translate to a URL + long time = System.currentTimeMillis(); + java.net.URL url = toURL(className); + timeManipulatingURLs += (System.currentTimeMillis() - time); + if (url == null) + throw new ClassNotFoundException(className + " not found - unable to determine URL"); + + JavaClass clazz = null; + + // Look in the appropriate cache + if (useSharedCache) { + clazz = findClassShared(url); + if (clazz != null) { + cacheHitsShared++; + return clazz; + } + } else { + clazz = findClassLocal(url); + if (clazz != null) { + cacheHitsLocal++; + return clazz; + } + } + + // Didn't find it in either cache + misses++; + + try { + // Load it + String classFile = className.replace('.', '/'); + InputStream is = (useSharedCache ? url.openStream() : loaderRef.getClassLoader().getResourceAsStream( + classFile + ".class")); + if (is == null) { + throw new ClassNotFoundException(className + " not found using url " + url); + } + ClassParser parser = new ClassParser(is, className); + clazz = parser.parse(); + + // Cache it + storeClassAsReference(url, clazz); + + timeSpentLoading += (System.currentTimeMillis() - time); + classesLoadedCount++; + return clazz; + } catch (IOException e) { + throw new ClassNotFoundException(e.toString()); + } } - - // Didn't find it in either cache - misses++; - - try { - // Load it - String classFile = className.replace('.', '/'); - InputStream is = (useSharedCache ? url.openStream() : loaderRef.getClassLoader().getResourceAsStream(classFile + ".class")); - if (is == null) { - throw new ClassNotFoundException(className + " not found using url "+url); - } - ClassParser parser = new ClassParser( is, className ); - clazz = parser.parse(); - - // Cache it - storeClassAsReference(url, clazz ); - - timeSpentLoading += (System.currentTimeMillis() - time); - classesLoadedCount++; - return clazz; - } catch (IOException e) { - throw new ClassNotFoundException( e.toString() ); - } - } - - /** - * Produce a report on cache usage. - */ - public String report() { - StringBuffer sb = new StringBuffer(); - sb.append("BCEL repository report."); - if (useSharedCache) sb.append(" (shared cache)"); - else sb.append(" (local cache)"); - sb.append(" Total time spent loading: "+timeSpentLoading+"ms."); - sb.append(" Time spent manipulating URLs: "+timeManipulatingURLs+"ms."); - sb.append(" Classes loaded: "+classesLoadedCount+"."); - if (useSharedCache) { - sb.append(" Shared cache size: "+sharedCache.size()); - sb.append(" Shared cache (hits/missDueToEviction): ("+cacheHitsShared+"/"+missSharedEvicted+")."); - } else { - sb.append(" Local cache size: "+localCache.size()); - sb.append(" Local cache (hits/missDueToEviction): ("+cacheHitsLocal+"/"+missLocalEvicted+")."); - } - return sb.toString(); - } - - /** - * Returns an array of the stats, for testing, the order is fixed: - * 0=time spent loading (static) - * 1=time spent manipulating URLs (static) - * 2=classes loaded (static) - * 3=cache hits shared (static) - * 4=misses in shared due to eviction (static) - * 5=cache hits local - * 6=misses in local due to eviction - * 7=shared cache size - */ - public long[] reportStats() { - return new long[]{timeSpentLoading,timeManipulatingURLs,classesLoadedCount, - cacheHitsShared,missSharedEvicted,cacheHitsLocal,missLocalEvicted, - sharedCache.size()}; - } - - /** - * Reset statistics and clear all caches - */ - public void reset() { - timeManipulatingURLs = 0L; - timeSpentLoading = 0L; - classesLoadedCount = 0; - cacheHitsLocal = 0; - cacheHitsShared = 0; - missSharedEvicted = 0; - missLocalEvicted = 0; - misses = 0; - clear(); - } - - - public JavaClass loadClass(Class clazz) throws ClassNotFoundException { - return loadClass(clazz.getName()); - } - - /** Clear all entries from the local cache */ - public void clear() { - if (useSharedCache) sharedCache.clear(); - else localCache.clear(); - } - -} + /** + * Produce a report on cache usage. + */ + public String report() { + StringBuffer sb = new StringBuffer(); + sb.append("BCEL repository report."); + if (useSharedCache) + sb.append(" (shared cache)"); + else + sb.append(" (local cache)"); + sb.append(" Total time spent loading: " + timeSpentLoading + "ms."); + sb.append(" Time spent manipulating URLs: " + timeManipulatingURLs + "ms."); + sb.append(" Classes loaded: " + classesLoadedCount + "."); + if (useSharedCache) { + sb.append(" Shared cache size: " + sharedCache.size()); + sb.append(" Shared cache (hits/missDueToEviction): (" + cacheHitsShared + "/" + missSharedEvicted + ")."); + } else { + sb.append(" Local cache size: " + localCache.size()); + sb.append(" Local cache (hits/missDueToEviction): (" + cacheHitsLocal + "/" + missLocalEvicted + ")."); + } + return sb.toString(); + } + /** + * Returns an array of the stats, for testing, the order is fixed: 0=time spent loading (static) 1=time spent manipulating URLs + * (static) 2=classes loaded (static) 3=cache hits shared (static) 4=misses in shared due to eviction (static) 5=cache hits + * local 6=misses in local due to eviction 7=shared cache size + */ + public long[] reportStats() { + return new long[] { timeSpentLoading, timeManipulatingURLs, classesLoadedCount, cacheHitsShared, missSharedEvicted, + cacheHitsLocal, missLocalEvicted, sharedCache.size() }; + } + + /** + * Reset statistics and clear all caches + */ + public void reset() { + timeManipulatingURLs = 0L; + timeSpentLoading = 0L; + classesLoadedCount = 0; + cacheHitsLocal = 0; + cacheHitsShared = 0; + missSharedEvicted = 0; + missLocalEvicted = 0; + misses = 0; + clear(); + } + + public JavaClass loadClass(Class clazz) throws ClassNotFoundException { + return loadClass(clazz.getName()); + } + + /** Clear all entries from the local cache */ + public void clear() { + if (useSharedCache) + sharedCache.clear(); + else + localCache.clear(); + } + +} diff --git a/bcel-builder/src/org/aspectj/apache/bcel/util/ClassPath.java b/bcel-builder/src/org/aspectj/apache/bcel/util/ClassPath.java index 447d0c50d..d346256cb 100644 --- a/bcel-builder/src/org/aspectj/apache/bcel/util/ClassPath.java +++ b/bcel-builder/src/org/aspectj/apache/bcel/util/ClassPath.java @@ -62,7 +62,7 @@ import java.io.*; * Responsible for loading (class) files from the CLASSPATH. Inspired by * sun.tools.ClassPath. * - * @version $Id: ClassPath.java,v 1.4 2008/05/28 23:52:53 aclement Exp $ + * @version $Id: ClassPath.java,v 1.5 2009/09/09 19:56:20 aclement Exp $ * @author M. Dahm */ public class ClassPath implements Serializable { @@ -83,7 +83,7 @@ public class ClassPath implements Serializable { public ClassPath(String class_path) { this.class_path = class_path; - ArrayList vec = new ArrayList(); + ArrayList vec = new ArrayList(); for(StringTokenizer tok=new StringTokenizer(class_path, System.getProperty("path.separator")); @@ -137,7 +137,7 @@ public class ClassPath implements Serializable { return false; } - private static final void getPathComponents(String path, ArrayList list) { + private static final void getPathComponents(String path, ArrayList list) { if(path != null) { StringTokenizer tok = new StringTokenizer(path, File.pathSeparator); @@ -161,16 +161,16 @@ public class ClassPath implements Serializable { String boot_path = System.getProperty("sun.boot.class.path"); String ext_path = System.getProperty("java.ext.dirs"); - ArrayList list = new ArrayList(); + ArrayList list = new ArrayList(); getPathComponents(class_path, list); getPathComponents(boot_path, list); - ArrayList dirs = new ArrayList(); + ArrayList dirs = new ArrayList(); getPathComponents(ext_path, dirs); - for(Iterator e = dirs.iterator(); e.hasNext(); ) { - File ext_dir = new File((String)e.next()); + for(Iterator e = dirs.iterator(); e.hasNext(); ) { + File ext_dir = new File(e.next()); String[] extensions = ext_dir.list(new FilenameFilter() { public boolean accept(File dir, String name) { name = name.toLowerCase(); @@ -185,8 +185,8 @@ public class ClassPath implements Serializable { StringBuffer buf = new StringBuffer(); - for(Iterator e = list.iterator(); e.hasNext(); ) { - buf.append((String)e.next()); + for(Iterator e = list.iterator(); e.hasNext(); ) { + buf.append(e.next()); if(e.hasNext()) buf.append(File.pathSeparatorChar); diff --git a/bcel-builder/src/org/aspectj/apache/bcel/util/ClassQueue.java b/bcel-builder/src/org/aspectj/apache/bcel/util/ClassQueue.java index ae91f305d..d424a2625 100644 --- a/bcel-builder/src/org/aspectj/apache/bcel/util/ClassQueue.java +++ b/bcel-builder/src/org/aspectj/apache/bcel/util/ClassQueue.java @@ -60,17 +60,17 @@ import org.aspectj.apache.bcel.classfile.JavaClass; * Utility class implementing a (typesafe) queue of JavaClass * objects. * - * @version $Id: ClassQueue.java,v 1.3 2008/05/28 23:52:53 aclement Exp $ + * @version $Id: ClassQueue.java,v 1.4 2009/09/09 19:56:20 aclement Exp $ * @author M. Dahm * @see ClassVector */ public class ClassQueue implements java.io.Serializable { - protected LinkedList vec = new LinkedList(); + protected LinkedList vec = new LinkedList(); public void enqueue(JavaClass clazz) { vec.addLast(clazz); } public JavaClass dequeue() { - return (JavaClass)vec.removeFirst(); + return vec.removeFirst(); } public boolean empty() { return vec.isEmpty(); } diff --git a/bcel-builder/src/org/aspectj/apache/bcel/util/ClassVector.java b/bcel-builder/src/org/aspectj/apache/bcel/util/ClassVector.java index 7667cd2dc..bb12c40be 100644 --- a/bcel-builder/src/org/aspectj/apache/bcel/util/ClassVector.java +++ b/bcel-builder/src/org/aspectj/apache/bcel/util/ClassVector.java @@ -60,15 +60,15 @@ import org.aspectj.apache.bcel.classfile.JavaClass; * Utility class implementing a (typesafe) collection of JavaClass * objects. Contains the most important methods of a Vector. * - * @version $Id: ClassVector.java,v 1.3 2008/05/28 23:52:53 aclement Exp $ + * @version $Id: ClassVector.java,v 1.4 2009/09/09 19:56:20 aclement Exp $ * @author M. Dahm * @see ClassQueue */ public class ClassVector implements java.io.Serializable { - protected ArrayList vec = new ArrayList(); + protected ArrayList vec = new ArrayList(); public void addElement(JavaClass clazz) { vec.add(clazz); } - public JavaClass elementAt(int index) { return (JavaClass)vec.get(index); } + public JavaClass elementAt(int index) { return vec.get(index); } public void removeElementAt(int index) { vec.remove(index); } public JavaClass[] toArray() { diff --git a/bcel-builder/src/org/aspectj/apache/bcel/util/NonCachingClassLoaderRepository.java b/bcel-builder/src/org/aspectj/apache/bcel/util/NonCachingClassLoaderRepository.java index 489475632..7a8c06224 100644 --- a/bcel-builder/src/org/aspectj/apache/bcel/util/NonCachingClassLoaderRepository.java +++ b/bcel-builder/src/org/aspectj/apache/bcel/util/NonCachingClassLoaderRepository.java @@ -76,7 +76,7 @@ import org.aspectj.apache.bcel.classfile.JavaClass; * * @see org.aspectj.apache.bcel.Repository * - * @version $Id: NonCachingClassLoaderRepository.java,v 1.5 2009/09/04 18:42:08 aclement Exp $ + * @version $Id: NonCachingClassLoaderRepository.java,v 1.6 2009/09/09 19:56:20 aclement Exp $ * @author M. Dahm * @author David Dixon-Peugh * @@ -85,13 +85,13 @@ public class NonCachingClassLoaderRepository implements Repository { private static java.lang.ClassLoader bootClassLoader = null; private final ClassLoaderReference loaderRef; - private final Map loadedClasses = new SoftHashMap(); // CLASSNAME X JAVACLASS + private final Map loadedClasses = new SoftHashMap(); // CLASSNAME X JAVACLASS public static class SoftHashMap extends AbstractMap { - private Map map; + private Map map; private ReferenceQueue rq = new ReferenceQueue(); - public SoftHashMap(Map map) { + public SoftHashMap(Map map) { this.map = map; } @@ -119,8 +119,9 @@ public class NonCachingClassLoaderRepository implements Repository { } } + @Override public Object get(Object key) { - SpecialValue value = (SpecialValue) map.get(key); + SpecialValue value = map.get(key); if (value == null) return null; if (value.get() == null) { @@ -132,32 +133,37 @@ public class NonCachingClassLoaderRepository implements Repository { } } + @Override public Object put(Object k, Object v) { processQueue(); return map.put(k, new SpecialValue(k, v)); } + @Override public Set entrySet() { return map.entrySet(); } + @Override public void clear() { processQueue(); - Set keys = map.keySet(); - for (Iterator iterator = keys.iterator(); iterator.hasNext();) { + Set keys = map.keySet(); + for (Iterator iterator = keys.iterator(); iterator.hasNext();) { Object name = iterator.next(); map.remove(name); } } + @Override public int size() { processQueue(); return map.size(); } + @Override public Object remove(Object k) { processQueue(); - SpecialValue value = (SpecialValue) map.remove(k); + SpecialValue value = map.remove(k); if (value == null) return null; if (value.get() != null) { @@ -207,7 +213,7 @@ public class NonCachingClassLoaderRepository implements Repository { public JavaClass findClass(String className) { synchronized (loadedClasses) { if (loadedClasses.containsKey(className)) { - return (JavaClass) loadedClasses.get(className); + return loadedClasses.get(className); } else { return null; } diff --git a/bcel-builder/src/org/aspectj/apache/bcel/util/Repository.java b/bcel-builder/src/org/aspectj/apache/bcel/util/Repository.java index a4b285534..eea889e61 100644 --- a/bcel-builder/src/org/aspectj/apache/bcel/util/Repository.java +++ b/bcel-builder/src/org/aspectj/apache/bcel/util/Repository.java @@ -57,49 +57,42 @@ package org.aspectj.apache.bcel.util; import org.aspectj.apache.bcel.classfile.JavaClass; /** - * Abstract definition of a class repository. Instances may be used - * to load classes from different sources and may be used in the + * Abstract definition of a class repository. Instances may be used to load classes from different sources and may be used in the * Repository.setRepository method. - * + * * @see org.aspectj.apache.bcel.Repository - * @version $Id: Repository.java,v 1.4 2008/08/28 00:01:38 aclement Exp $ + * @version $Id: Repository.java,v 1.5 2009/09/09 19:56:20 aclement Exp $ * @author M. Dahm * @author David Dixon-Peugh */ public interface Repository { - /** - * Store the provided class under "clazz.getClassName()" - */ - public void storeClass(JavaClass clazz); - - /** - * Remove class from repository - */ - public void removeClass(JavaClass clazz); - - /** - * Find the class with the name provided, if the class - * isn't there, return NULL. - */ - public JavaClass findClass(String className); + /** + * Store the provided class under "clazz.getClassName()" + */ + public void storeClass(JavaClass clazz); - /** - * Find the class with the name provided, if the class - * isn't there, make an attempt to load it. - */ - public JavaClass loadClass(String className) - throws java.lang.ClassNotFoundException; + /** + * Remove class from repository + */ + public void removeClass(JavaClass clazz); - /** - * Find the JavaClass instance for the given run-time class object - */ - public JavaClass loadClass(Class clazz) - throws java.lang.ClassNotFoundException; - - /** Clear all entries from cache. - */ - public void clear(); -} + /** + * Find the class with the name provided, if the class isn't there, return NULL. + */ + public JavaClass findClass(String className); + /** + * Find the class with the name provided, if the class isn't there, make an attempt to load it. + */ + public JavaClass loadClass(String className) throws java.lang.ClassNotFoundException; + /** + * Find the JavaClass instance for the given run-time class object + */ + public JavaClass loadClass(Class clazz) throws java.lang.ClassNotFoundException; + /** + * Clear all entries from cache. + */ + public void clear(); +} diff --git a/bcel-builder/src/org/aspectj/apache/bcel/util/SyntheticRepository.java b/bcel-builder/src/org/aspectj/apache/bcel/util/SyntheticRepository.java index 0f609b2f2..ea0e49216 100644 --- a/bcel-builder/src/org/aspectj/apache/bcel/util/SyntheticRepository.java +++ b/bcel-builder/src/org/aspectj/apache/bcel/util/SyntheticRepository.java @@ -63,143 +63,133 @@ import org.aspectj.apache.bcel.classfile.ClassParser; import org.aspectj.apache.bcel.classfile.JavaClass; /** - * This repository is used in situations where a Class is created - * outside the realm of a ClassLoader. Classes are loaded from - * the file systems using the paths specified in the given - * class path. By default, this is the value returned by - * ClassPath.getClassPath(). - *
- * It is designed to be used as a singleton, however it - * can also be used with custom classpaths. - * -/** - * Abstract definition of a class repository. Instances may be used - * to load classes from different sources and may be used in the - * Repository.setRepository method. - * + * This repository is used in situations where a Class is created outside the realm of a ClassLoader. Classes are loaded from the + * file systems using the paths specified in the given class path. By default, this is the value returned by + * ClassPath.getClassPath().
+ * It is designed to be used as a singleton, however it can also be used with custom classpaths. + * + * /** Abstract definition of a class repository. Instances may be used to load classes from different sources and may be used in + * the Repository.setRepository method. + * * @see org.aspectj.apache.bcel.Repository - * - * @version $Id: SyntheticRepository.java,v 1.7 2008/05/28 23:52:53 aclement Exp $ + * + * @version $Id: SyntheticRepository.java,v 1.8 2009/09/09 19:56:20 aclement Exp $ * @author M. Dahm * @author David Dixon-Peugh */ public class SyntheticRepository implements Repository { - private static final String DEFAULT_PATH = ClassPath.getClassPath(); - - private static HashMap _instances = new HashMap(); // CLASSPATH X REPOSITORY - - private ClassPath _path = null; - private WeakHashMap _loadedClasses = new WeakHashMap(); // CLASSNAME X JAVACLASS - - private SyntheticRepository(ClassPath path) { - _path = path; - } - - public static SyntheticRepository getInstance() { - return getInstance(ClassPath.getSystemClassPath()); - } - - public static SyntheticRepository getInstance(ClassPath classPath) { - SyntheticRepository rep = (SyntheticRepository)_instances.get(classPath); - - if(rep == null) { - rep = new SyntheticRepository(classPath); - _instances.put(classPath, rep); - } - - return rep; - } - - /** - * Store a new JavaClass instance into this Repository. - */ - public void storeClass(JavaClass clazz) { - _loadedClasses.put(clazz.getClassName(), clazz); - clazz.setRepository(this); - } - - /** - * Remove class from repository - */ - public void removeClass(JavaClass clazz) { - _loadedClasses.remove(clazz.getClassName()); - } - - /** - * Find an already defined (cached) JavaClass object by name. - */ - public JavaClass findClass(String className) { - return (JavaClass)_loadedClasses.get(className); - } - - /** - * Load a JavaClass object for the given class name using - * the CLASSPATH environment variable. - */ - public JavaClass loadClass(String className) - throws ClassNotFoundException - { - if(className == null || className.equals("")) { - throw new IllegalArgumentException("Invalid class name " + className); - } - - className = className.replace('/', '.'); // Just in case, canonical form - - try { - return loadClass(_path.getInputStream(className), className); - } catch(IOException e) { - throw new ClassNotFoundException("Exception while looking for class " + - className + ": " + e.toString()); - } - } - - /** - * Try to find class source via getResourceAsStream(). - * @see Class - * @return JavaClass object for given runtime class - */ - public JavaClass loadClass(Class clazz) throws ClassNotFoundException { - String className = clazz.getName(); - String name = className; - int i = name.lastIndexOf('.'); - - if(i > 0) { - name = name.substring(i + 1); - } - - return loadClass(clazz.getResourceAsStream(name + ".class"), className); - } - - private JavaClass loadClass(InputStream is, String className) - throws ClassNotFoundException - { - JavaClass clazz = findClass(className); - - if(clazz != null) { - return clazz; - } - - try { - if(is != null) { - ClassParser parser = new ClassParser(is, className); - clazz = parser.parse(); - - storeClass(clazz); - - return clazz; - } - } catch(IOException e) { - throw new ClassNotFoundException("Exception while looking for class " + - className + ": " + e.toString()); - } - - throw new ClassNotFoundException("SyntheticRepository could not load " + - className); - } - - /** Clear all entries from cache. - */ - public void clear() { - _loadedClasses.clear(); - } + private static final String DEFAULT_PATH = ClassPath.getClassPath(); + + private static HashMap _instances = new HashMap(); // CLASSPATH + // X + // REPOSITORY + + private ClassPath _path = null; + private WeakHashMap _loadedClasses = new WeakHashMap(); // CLASSNAME X JAVACLASS + + private SyntheticRepository(ClassPath path) { + _path = path; + } + + public static SyntheticRepository getInstance() { + return getInstance(ClassPath.getSystemClassPath()); + } + + public static SyntheticRepository getInstance(ClassPath classPath) { + SyntheticRepository rep = _instances.get(classPath); + + if (rep == null) { + rep = new SyntheticRepository(classPath); + _instances.put(classPath, rep); + } + + return rep; + } + + /** + * Store a new JavaClass instance into this Repository. + */ + public void storeClass(JavaClass clazz) { + _loadedClasses.put(clazz.getClassName(), clazz); + clazz.setRepository(this); + } + + /** + * Remove class from repository + */ + public void removeClass(JavaClass clazz) { + _loadedClasses.remove(clazz.getClassName()); + } + + /** + * Find an already defined (cached) JavaClass object by name. + */ + public JavaClass findClass(String className) { + return _loadedClasses.get(className); + } + + /** + * Load a JavaClass object for the given class name using the CLASSPATH environment variable. + */ + public JavaClass loadClass(String className) throws ClassNotFoundException { + if (className == null || className.equals("")) { + throw new IllegalArgumentException("Invalid class name " + className); + } + + className = className.replace('/', '.'); // Just in case, canonical form + + try { + return loadClass(_path.getInputStream(className), className); + } catch (IOException e) { + throw new ClassNotFoundException("Exception while looking for class " + className + ": " + e.toString()); + } + } + + /** + * Try to find class source via getResourceAsStream(). + * + * @see Class + * @return JavaClass object for given runtime class + */ + public JavaClass loadClass(Class clazz) throws ClassNotFoundException { + String className = clazz.getName(); + String name = className; + int i = name.lastIndexOf('.'); + + if (i > 0) { + name = name.substring(i + 1); + } + + return loadClass(clazz.getResourceAsStream(name + ".class"), className); + } + + private JavaClass loadClass(InputStream is, String className) throws ClassNotFoundException { + JavaClass clazz = findClass(className); + + if (clazz != null) { + return clazz; + } + + try { + if (is != null) { + ClassParser parser = new ClassParser(is, className); + clazz = parser.parse(); + + storeClass(clazz); + + return clazz; + } + } catch (IOException e) { + throw new ClassNotFoundException("Exception while looking for class " + className + ": " + e.toString()); + } + + throw new ClassNotFoundException("SyntheticRepository could not load " + className); + } + + /** + * Clear all entries from cache. + */ + public void clear() { + _loadedClasses.clear(); + } } diff --git a/bcel-builder/testsrc/org/aspectj/apache/bcel/classfile/tests/AnnotationGenTest.java b/bcel-builder/testsrc/org/aspectj/apache/bcel/classfile/tests/AnnotationGenTest.java index 306a1a387..377a176a1 100644 --- a/bcel-builder/testsrc/org/aspectj/apache/bcel/classfile/tests/AnnotationGenTest.java +++ b/bcel-builder/testsrc/org/aspectj/apache/bcel/classfile/tests/AnnotationGenTest.java @@ -66,7 +66,7 @@ public class AnnotationGenTest extends BcelTestCase { ObjectType t = new ObjectType("SimpleAnnotation"); - List elements = new ArrayList(); + List elements = new ArrayList(); elements.add(nvGen); // Build an annotation of type 'SimpleAnnotation' with 'id=4' as the only value :) @@ -97,13 +97,13 @@ public class AnnotationGenTest extends BcelTestCase { ObjectType t = new ObjectType("SimpleAnnotation"); - List elements = new ArrayList(); + List elements = new ArrayList(); elements.add(nvGen); // Build a RV annotation of type 'SimpleAnnotation' with 'id=4' as the only value :) AnnotationGen a = new AnnotationGen(t,elements,true,cp); - Vector v = new Vector(); + Vector v = new Vector(); v.add(a); Attribute[] attributes = Utility.getAnnotationAttributes(cp, v); boolean foundRV = false; @@ -121,7 +121,7 @@ public class AnnotationGenTest extends BcelTestCase { // Build a RIV annotation of type 'SimpleAnnotation' with 'id=4' as the only value :) AnnotationGen a2 = new AnnotationGen(t,elements,false,cp); - Vector v2 = new Vector(); + Vector v2 = new Vector(); v2.add(a2); Attribute[] attributes2 = Utility.getAnnotationAttributes(cp, v2); boolean foundRIV = false; @@ -141,7 +141,7 @@ public class AnnotationGenTest extends BcelTestCase { private void checkSerialize(AnnotationGen a,ConstantPool cpg) { try { String beforeName = a.getTypeName(); - List beforeValues = a.getValues(); + List beforeValues = a.getValues(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(baos); a.dump(dos); @@ -157,7 +157,7 @@ public class AnnotationGenTest extends BcelTestCase { dis.close(); String afterName = annAfter.getTypeName(); - List afterValues = annAfter.getValues(); + List afterValues = annAfter.getValues(); if (!beforeName.equals(afterName)) { fail("Deserialization failed: before type='"+beforeName+"' after type='"+afterName+"'"); @@ -166,8 +166,8 @@ public class AnnotationGenTest extends BcelTestCase { fail("Different numbers of element name value pairs?? "+a.getValues().size()+"!="+annAfter.getValues().size()); } for (int i=0;i chosenAttrsList = new ArrayList(); for (int i = 0; i < all.length; i++) { if (verbose) System.err.println("Attribute: "+all[i].getName()); if (all[i].getName().equals(name)) chosenAttrsList.add(all[i]); } assertTrue("Should be one match: "+chosenAttrsList.size(),chosenAttrsList.size()==1); - return (Attribute)chosenAttrsList.get(0); + return chosenAttrsList.get(0); } @@ -128,7 +128,7 @@ public class BcelTestCase extends TestCase { SimpleElementValueGen evg = new SimpleElementValueGen(ElementValueGen.STRING,cp,aFruit); ElementNameValuePairGen nvGen = new ElementNameValuePairGen("fruit",evg,cp); ObjectType t = new ObjectType("SimpleStringAnnotation"); - List elements = new ArrayList(); + List elements = new ArrayList(); elements.add(nvGen); return new AnnotationGen(t,elements,visibility,cp); } diff --git a/bcel-builder/testsrc/org/aspectj/apache/bcel/classfile/tests/FieldAnnotationsTest.java b/bcel-builder/testsrc/org/aspectj/apache/bcel/classfile/tests/FieldAnnotationsTest.java index 0bcf1ac81..f9a179ed8 100644 --- a/bcel-builder/testsrc/org/aspectj/apache/bcel/classfile/tests/FieldAnnotationsTest.java +++ b/bcel-builder/testsrc/org/aspectj/apache/bcel/classfile/tests/FieldAnnotationsTest.java @@ -116,7 +116,7 @@ public class FieldAnnotationsTest extends BcelTestCase { assertTrue("Expected annotation to have name "+name+" but it had name "+a.getTypeName(), a.getTypeName().equals(name)); assertTrue("Expected annotation to have one element but it had "+a.getValues().size(),a.getValues().size()==1); - ElementNameValuePairGen envp = (ElementNameValuePairGen)a.getValues().get(0); + ElementNameValuePairGen envp = a.getValues().get(0); assertTrue("Expected element name "+elementname+" but was "+envp.getNameString(), elementname.equals(envp.getNameString())); assertTrue("Expected element value "+elementvalue+" but was "+envp.getValue().stringifyValue(), @@ -127,8 +127,8 @@ public class FieldAnnotationsTest extends BcelTestCase { // helper methods public void checkValue(AnnotationGen a,String name,String tostring) { - for (Iterator i = a.getValues().iterator(); i.hasNext();) { - ElementNameValuePairGen element = (ElementNameValuePairGen) i.next(); + for (Iterator i = a.getValues().iterator(); i.hasNext();) { + ElementNameValuePairGen element = i.next(); if (element.getNameString().equals(name)) { if (!element.getValue().stringifyValue().equals(tostring)) { fail("Expected element "+name+" to have value "+tostring+" but it had value "+element.getValue().stringifyValue()); diff --git a/bcel-builder/testsrc/org/aspectj/apache/bcel/classfile/tests/GeneratingAnnotatedClassesTest.java b/bcel-builder/testsrc/org/aspectj/apache/bcel/classfile/tests/GeneratingAnnotatedClassesTest.java index 6306c3edc..f0adda504 100644 --- a/bcel-builder/testsrc/org/aspectj/apache/bcel/classfile/tests/GeneratingAnnotatedClassesTest.java +++ b/bcel-builder/testsrc/org/aspectj/apache/bcel/classfile/tests/GeneratingAnnotatedClassesTest.java @@ -90,8 +90,8 @@ public class GeneratingAnnotatedClassesTest extends BcelTestCase { as[0].getTypeName().equals("SimpleAnnotation")); assertTrue("Name of annotation 2 should be SimpleAnnotation but it is "+as[1].getTypeName(), as[1].getTypeName().equals("SimpleAnnotation")); - List vals = as[0].getValues(); - ElementNameValuePairGen nvp = (ElementNameValuePairGen) vals.get(0); + List vals = as[0].getValues(); + ElementNameValuePairGen nvp = vals.get(0); assertTrue("Name of element in SimpleAnnotation should be 'id' but it is "+ nvp.getNameString(),nvp.getNameString().equals("id")); ElementValueGen ev = nvp.getValue(); @@ -237,7 +237,7 @@ public class GeneratingAnnotatedClassesTest extends BcelTestCase { annotations.length==1); AnnotationGen a = annotations[0]; assertTrue("That annotation should only have one value but has "+a.getValues().size(),a.getValues().size()==1); - ElementNameValuePairGen nvp = (ElementNameValuePairGen)a.getValues().get(0); + ElementNameValuePairGen nvp = a.getValues().get(0); ElementValueGen value = (ElementValueGen)nvp.getValue(); assertTrue("Value should be ArrayElementValueGen but is "+value,value instanceof ArrayElementValueGen); ArrayElementValueGen arrayValue = (ArrayElementValueGen)value; @@ -262,10 +262,10 @@ public class GeneratingAnnotatedClassesTest extends BcelTestCase { AnnotationGen[] annotations = cgen.getAnnotations(); assertTrue("Expected one annotation but found "+annotations.length, annotations.length==1); - List l = annotations[0].getValues(); + List l = annotations[0].getValues(); boolean found = false; - for (Iterator iter = l.iterator(); iter.hasNext();) { - ElementNameValuePairGen element = (ElementNameValuePairGen) iter.next(); + for (Iterator iter = l.iterator(); iter.hasNext();) { + ElementNameValuePairGen element = iter.next(); if (element.getNameString().equals("dval")) { if (((SimpleElementValueGen)element.getValue()).stringifyValue().equals("33.4")) found = true; @@ -579,7 +579,7 @@ public class GeneratingAnnotatedClassesTest extends BcelTestCase { ObjectType t = new ObjectType("SimpleAnnotation"); - List elements = new ArrayList(); + List elements = new ArrayList(); elements.add(nvGen); AnnotationGen a = new AnnotationGen(t, elements,true, cp); @@ -590,7 +590,7 @@ public class GeneratingAnnotatedClassesTest extends BcelTestCase { SimpleElementValueGen evg = new SimpleElementValueGen(ElementValueGen.STRING,cp,aFruit); ElementNameValuePairGen nvGen = new ElementNameValuePairGen("fruit",evg,cp); ObjectType t = new ObjectType("SimpleStringAnnotation"); - List elements = new ArrayList(); + List elements = new ArrayList(); elements.add(nvGen); return new AnnotationGen(t,elements,true,cp); } @@ -601,7 +601,7 @@ public class GeneratingAnnotatedClassesTest extends BcelTestCase { ArrayElementValueGen array = new ArrayElementValueGen(cp); array.addElement(new AnnotationElementValueGen(a,cp)); ElementNameValuePairGen nvp = new ElementNameValuePairGen("value",array,cp); - List elements = new ArrayList(); + List elements = new ArrayList(); elements.add(nvp); return new AnnotationGen(new ObjectType("CombinedAnnotation"),elements,true,cp); } @@ -614,7 +614,7 @@ public class GeneratingAnnotatedClassesTest extends BcelTestCase { ObjectType t = new ObjectType("SimpleAnnotation"); - List elements = new ArrayList(); + List elements = new ArrayList(); elements.add(nvGen); AnnotationGen a = new AnnotationGen(t, elements,false, cp); diff --git a/bcel-builder/testsrc/org/aspectj/apache/bcel/classfile/tests/GenericSignatureParsingTest.java b/bcel-builder/testsrc/org/aspectj/apache/bcel/classfile/tests/GenericSignatureParsingTest.java index 257d5f28b..f64e4440f 100644 --- a/bcel-builder/testsrc/org/aspectj/apache/bcel/classfile/tests/GenericSignatureParsingTest.java +++ b/bcel-builder/testsrc/org/aspectj/apache/bcel/classfile/tests/GenericSignatureParsingTest.java @@ -416,7 +416,7 @@ public class GenericSignatureParsingTest extends BcelTestCase { * @return Array of argument types */ public static final String[] methodSignatureArgumentTypes(String signature,boolean chopit) throws ClassFormatException { - ArrayList vec = new ArrayList(); + ArrayList vec = new ArrayList(); int index; String[] types; diff --git a/bcel-builder/testsrc/org/aspectj/apache/bcel/classfile/tests/MethodAnnotationsTest.java b/bcel-builder/testsrc/org/aspectj/apache/bcel/classfile/tests/MethodAnnotationsTest.java index 005eb3f69..2e813e9f2 100644 --- a/bcel-builder/testsrc/org/aspectj/apache/bcel/classfile/tests/MethodAnnotationsTest.java +++ b/bcel-builder/testsrc/org/aspectj/apache/bcel/classfile/tests/MethodAnnotationsTest.java @@ -77,7 +77,7 @@ public class MethodAnnotationsTest extends BcelTestCase { assertTrue("Expected annotation to have name "+name+" but it had name "+a.getTypeName(), a.getTypeName().equals(name)); assertTrue("Expected annotation to have one element but it had "+a.getValues().size(),a.getValues().size()==1); - ElementNameValuePairGen envp = (ElementNameValuePairGen)a.getValues().get(0); + ElementNameValuePairGen envp = a.getValues().get(0); assertTrue("Expected element name "+elementname+" but was "+envp.getNameString(), elementname.equals(envp.getNameString())); assertTrue("Expected element value "+elementvalue+" but was "+envp.getValue().stringifyValue(), @@ -88,8 +88,8 @@ public class MethodAnnotationsTest extends BcelTestCase { // helper methods public void checkValue(AnnotationGen a,String name,String tostring) { - for (Iterator i = a.getValues().iterator(); i.hasNext();) { - ElementNameValuePairGen element = (ElementNameValuePairGen) i.next(); + for (Iterator i = a.getValues().iterator(); i.hasNext();) { + ElementNameValuePairGen element = i.next(); if (element.getNameString().equals(name)) { if (!element.getValue().stringifyValue().equals(tostring)) { fail("Expected element "+name+" to have value "+tostring+" but it had value "+element.getValue().stringifyValue()); diff --git a/bcel-builder/testsrc/org/aspectj/apache/bcel/classfile/tests/NonCachingClassLoaderRepositoryTest.java b/bcel-builder/testsrc/org/aspectj/apache/bcel/classfile/tests/NonCachingClassLoaderRepositoryTest.java index c777f75de..4b7a14715 100644 --- a/bcel-builder/testsrc/org/aspectj/apache/bcel/classfile/tests/NonCachingClassLoaderRepositoryTest.java +++ b/bcel-builder/testsrc/org/aspectj/apache/bcel/classfile/tests/NonCachingClassLoaderRepositoryTest.java @@ -121,7 +121,7 @@ public class NonCachingClassLoaderRepositoryTest extends TestCase { } public void testConcurrency() throws ClassNotFoundException, InterruptedException { - List loaders = new ArrayList(); + List loaders = new ArrayList(); int i1 = 1000; for (int i = 0; i < i1; i++) { DoneChecker loader = new Loader(); @@ -133,7 +133,7 @@ public class NonCachingClassLoaderRepositoryTest extends TestCase { } for (int i = 0; i < i1 * 2; i++) { - DoneChecker loader = (DoneChecker) loaders.get(i); + DoneChecker loader = loaders.get(i); while (!loader.isDone()) { Thread.sleep(10); } diff --git a/bcel-builder/testsrc/org/aspectj/apache/bcel/classfile/tests/ParameterAnnotationsTest.java b/bcel-builder/testsrc/org/aspectj/apache/bcel/classfile/tests/ParameterAnnotationsTest.java index 7733166c7..ea2f96a3e 100644 --- a/bcel-builder/testsrc/org/aspectj/apache/bcel/classfile/tests/ParameterAnnotationsTest.java +++ b/bcel-builder/testsrc/org/aspectj/apache/bcel/classfile/tests/ParameterAnnotationsTest.java @@ -14,6 +14,7 @@ import java.util.ArrayList; import java.util.List; import org.aspectj.apache.bcel.Constants; +import org.aspectj.apache.bcel.classfile.Attribute; import org.aspectj.apache.bcel.classfile.ConstantPool; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.apache.bcel.classfile.Method; @@ -259,7 +260,7 @@ public class ParameterAnnotationsTest extends BcelTestCase { // attributes vanish ! clg = new ClassGen(jc2); mg = new MethodGen(m,clg.getClassName(),clg.getConstantPool()); - List as = mg.getAttributes(); + List as = mg.getAttributes(); assertTrue("Should be 2 (RIPA and RVPA) but there are "+mg.getAttributes().size(),mg.getAttributes().size()==2); List l = mg.getAnnotationsOnParameter(0); assertTrue("Should be 2 annotations on first parameter but there is only "+l.size()+":"+l.toString(), @@ -550,7 +551,7 @@ public class ParameterAnnotationsTest extends BcelTestCase { ObjectType t = new ObjectType("SimpleAnnotation"); - List elements = new ArrayList(); + List elements = new ArrayList(); elements.add(nvGen); AnnotationGen a = new AnnotationGen(t, elements,true, cp); @@ -563,7 +564,7 @@ public class ParameterAnnotationsTest extends BcelTestCase { ArrayElementValueGen array = new ArrayElementValueGen(cp); array.addElement(new AnnotationElementValueGen(a,cp)); ElementNameValuePairGen nvp = new ElementNameValuePairGen("value",array,cp); - List elements = new ArrayList(); + List elements = new ArrayList(); elements.add(nvp); return new AnnotationGen(new ObjectType("CombinedAnnotation"),elements,true,cp); } @@ -576,7 +577,7 @@ public class ParameterAnnotationsTest extends BcelTestCase { ObjectType t = new ObjectType("SimpleAnnotation"); - List elements = new ArrayList(); + List elements = new ArrayList(); elements.add(nvGen); AnnotationGen a = new AnnotationGen(t, elements,false, cp); diff --git a/bcel-builder/testsrc/org/aspectj/apache/bcel/classfile/tests/RuntimeVisibleAnnotationAttributeTest.java b/bcel-builder/testsrc/org/aspectj/apache/bcel/classfile/tests/RuntimeVisibleAnnotationAttributeTest.java index ac9023f22..76ff0d54a 100644 --- a/bcel-builder/testsrc/org/aspectj/apache/bcel/classfile/tests/RuntimeVisibleAnnotationAttributeTest.java +++ b/bcel-builder/testsrc/org/aspectj/apache/bcel/classfile/tests/RuntimeVisibleAnnotationAttributeTest.java @@ -57,16 +57,16 @@ public class RuntimeVisibleAnnotationAttributeTest extends BcelTestCase { ConstantPool pool = clazz.getConstantPool(); Attribute[] rvaAttr = findAttribute("RuntimeVisibleAnnotations",clazz); RuntimeVisibleAnnotations rva = (RuntimeVisibleAnnotations) rvaAttr[0]; - List anns = rva.getAnnotations(); + List anns = rva.getAnnotations(); assertTrue("Should be one annotation but found "+anns.size(), anns.size()==1); - AnnotationGen ann = (AnnotationGen) anns.get(0); + AnnotationGen ann = anns.get(0); assertTrue("Should be called 'SimpleAnnotation' but was called "+ann.getTypeName(), ann.getTypeName().equals("SimpleAnnotation")); - List l = ann.getValues(); + List l = ann.getValues(); assertTrue("Should be one value for annotation 'SimpleAnnotation' but found "+l.size(), l.size()==1); - ElementNameValuePairGen envp = (ElementNameValuePairGen)l.get(0); + ElementNameValuePairGen envp = l.get(0); assertTrue("Name of element in SimpleAnnotation should be 'id' but it is "+envp.getNameString(), envp.getNameString().equals("id")); SimpleElementValueGen evalue = (SimpleElementValueGen)envp.getValue(); @@ -140,9 +140,9 @@ public class RuntimeVisibleAnnotationAttributeTest extends BcelTestCase { AnnotationGen ann = anns[0]; assertTrue("should be called 'AnnotationStringElement' but was called "+ann.getTypeName(), ann.getTypeName().equals("AnnotationStringElement")); - List l = ann.getValues(); + List l = ann.getValues(); assertTrue("Should be one value but there were "+l.size(),l.size()==1); - ElementNameValuePairGen nvp = (ElementNameValuePairGen)l.get(0); + ElementNameValuePairGen nvp = l.get(0); assertTrue("Name of element should be 'stringval' but was "+nvp.getNameString(), nvp.getNameString().equals("stringval")); SimpleElementValueGen ev = (SimpleElementValueGen)nvp.getValue(); @@ -183,10 +183,10 @@ public class RuntimeVisibleAnnotationAttributeTest extends BcelTestCase { AnnotationGen ann = anns[0]; assertTrue("Should be called 'ComplexAnnotation' but was called "+ann.getTypeName(), ann.getTypeName().equals("ComplexAnnotation")); - List l = ann.getValues(); + List l = ann.getValues(); assertTrue("Should be eight values for annotation 'ComplexAnnotation' but found "+l.size(), l.size()==8); - List names = RuntimeVisibleAnnotationAttributeTest.getListOfAnnotationNames(ann); + List names = RuntimeVisibleAnnotationAttributeTest.getListOfAnnotationNames(ann); assertTrue("Cant find expected element ",names.contains("ival")); assertTrue("Cant find expected element ",names.contains("dval")); assertTrue("Cant find expected element ",names.contains("zval")); @@ -208,8 +208,8 @@ public class RuntimeVisibleAnnotationAttributeTest extends BcelTestCase { } private void checkValue(AnnotationGen a,String name,String tostring) { - for (Iterator i = a.getValues().iterator(); i.hasNext();) { - ElementNameValuePairGen element = (ElementNameValuePairGen) i.next(); + for (Iterator i = a.getValues().iterator(); i.hasNext();) { + ElementNameValuePairGen element = i.next(); if (element.getNameString().equals(name)) { if (!element.getValue().stringifyValue().equals(tostring)) { fail("Expected element "+name+" to have value "+tostring+" but it had value "+element.getValue().stringifyValue()); @@ -261,9 +261,9 @@ public class RuntimeVisibleAnnotationAttributeTest extends BcelTestCase { AnnotationGen ann = anns[0]; assertTrue("should be called 'AnnotationClassElement' but was called "+ann.getTypeName(), ann.getTypeName().equals("AnnotationClassElement")); - List l = ann.getValues(); + List l = ann.getValues(); assertTrue("Should be one value but there were "+l.size(),l.size()==1); - ElementNameValuePairGen nvp = (ElementNameValuePairGen)l.get(0); + ElementNameValuePairGen nvp = l.get(0); assertTrue("Name of element should be 'clz' but was "+nvp.getNameString(), nvp.getNameString().equals("clz")); ClassElementValueGen ev = (ClassElementValueGen)nvp.getValue(); @@ -303,9 +303,9 @@ public class RuntimeVisibleAnnotationAttributeTest extends BcelTestCase { AnnotationGen ann = anns[0]; assertTrue("should be called 'AnnotationEnumElement' but was called "+ann.getTypeName(), ann.getTypeName().equals("AnnotationEnumElement")); - List l = ann.getValues(); + List l = ann.getValues(); assertTrue("Should be one value but there were "+l.size(),l.size()==1); - ElementNameValuePairGen nvp = (ElementNameValuePairGen)l.get(0); + ElementNameValuePairGen nvp = l.get(0); assertTrue("Name of element should be 'enumval' but was "+nvp.getNameString(), nvp.getNameString().equals("enumval")); ElementValueGen ev = nvp.getValue(); @@ -352,9 +352,9 @@ public class RuntimeVisibleAnnotationAttributeTest extends BcelTestCase { private void checkCombinedAnnotation(AnnotationGen ann) { assertTrue("should be called 'CombinedAnnotation' but was called "+ann.getTypeName(), ann.getTypeName().equals("CombinedAnnotation")); - List l = ann.getValues(); + List l = ann.getValues(); assertTrue("Should be one value but there were "+l.size(),l.size()==1); - ElementNameValuePairGen nvp = (ElementNameValuePairGen)l.get(0); + ElementNameValuePairGen nvp = l.get(0); assertTrue("Name of element should be 'value' but was "+nvp.getNameString(), nvp.getNameString().equals("value")); ElementValueGen ev = nvp.getValue(); @@ -369,9 +369,9 @@ public class RuntimeVisibleAnnotationAttributeTest extends BcelTestCase { AnnotationElementValueGen inner_ev = (AnnotationElementValueGen)evs[0]; AnnotationGen a = inner_ev.getAnnotation(); assertTrue("Should be SimpleAnnotation but is "+a.getTypeName(),a.getTypeName().equals("SimpleAnnotation")); - List envps = a.getValues(); + List envps = a.getValues(); assertTrue("Should be one name value pair but found "+envps.size(),envps.size()==1); - ElementNameValuePairGen envp = (ElementNameValuePairGen) envps.get(0); + ElementNameValuePairGen envp = envps.get(0); assertTrue("Name should be 'id' but it is "+envp.getNameString(),envp.getNameString().equals("id")); assertTrue("Value of 'id' should be 4 but it is "+envp.getValue().stringifyValue(), envp.getValue().stringifyValue().equals("4")); @@ -382,11 +382,11 @@ public class RuntimeVisibleAnnotationAttributeTest extends BcelTestCase { super.tearDown(); } - public static List getListOfAnnotationNames(AnnotationGen a) { - List l = a.getValues(); - List names = new ArrayList(); - for (Iterator i = l.iterator(); i.hasNext();) { - ElementNameValuePairGen element = (ElementNameValuePairGen) i.next(); + public static List getListOfAnnotationNames(AnnotationGen a) { + List l = a.getValues(); + List names = new ArrayList(); + for (Iterator i = l.iterator(); i.hasNext();) { + ElementNameValuePairGen element = i.next(); names.add(element.getNameString()); } return names; diff --git a/bcel-builder/testsrc/org/aspectj/apache/bcel/classfile/tests/RuntimeVisibleParameterAnnotationAttributeTest.java b/bcel-builder/testsrc/org/aspectj/apache/bcel/classfile/tests/RuntimeVisibleParameterAnnotationAttributeTest.java index 424d5352f..0d269e900 100644 --- a/bcel-builder/testsrc/org/aspectj/apache/bcel/classfile/tests/RuntimeVisibleParameterAnnotationAttributeTest.java +++ b/bcel-builder/testsrc/org/aspectj/apache/bcel/classfile/tests/RuntimeVisibleParameterAnnotationAttributeTest.java @@ -113,7 +113,7 @@ public class RuntimeVisibleParameterAnnotationAttributeTest extends BcelTestCase assertTrue("Expected annotation to have name "+name+" but it had name "+a.getTypeName(), a.getTypeName().equals(name)); assertTrue("Expected annotation to have one element but it had "+a.getValues().size(),a.getValues().size()==1); - ElementNameValuePairGen envp = (ElementNameValuePairGen)a.getValues().get(0); + ElementNameValuePairGen envp = a.getValues().get(0); assertTrue("Expected element name "+elementname+" but was "+envp.getNameString(), elementname.equals(envp.getNameString())); assertTrue("Expected element value "+elementvalue+" but was "+envp.getValue().stringifyValue(), @@ -124,8 +124,8 @@ public class RuntimeVisibleParameterAnnotationAttributeTest extends BcelTestCase // helper methods public void checkValue(AnnotationGen a,String name,String tostring) { - for (Iterator i = a.getValues().iterator(); i.hasNext();) { - ElementNameValuePairGen element = (ElementNameValuePairGen) i.next(); + for (Iterator i = a.getValues().iterator(); i.hasNext();) { + ElementNameValuePairGen element = i.next(); if (element.getNameString().equals(name)) { if (!element.getValue().stringifyValue().equals(tostring)) { fail("Expected element "+name+" to have value "+tostring+" but it had value "+element.getValue().stringifyValue()); diff --git a/bcel-builder/testsrc/org/aspectj/apache/bcel/classfile/tests/VarargsTest.java b/bcel-builder/testsrc/org/aspectj/apache/bcel/classfile/tests/VarargsTest.java index a6f8e8021..770ac426a 100644 --- a/bcel-builder/testsrc/org/aspectj/apache/bcel/classfile/tests/VarargsTest.java +++ b/bcel-builder/testsrc/org/aspectj/apache/bcel/classfile/tests/VarargsTest.java @@ -78,8 +78,8 @@ public class VarargsTest extends BcelTestCase { // helper methods public void checkValue(AnnotationGen a,String name,String tostring) { - for (Iterator i = a.getValues().iterator(); i.hasNext();) { - ElementNameValuePairGen element = (ElementNameValuePairGen) i.next(); + for (Iterator i = a.getValues().iterator(); i.hasNext();) { + ElementNameValuePairGen element = i.next(); if (element.getNameString().equals(name)) { if (!element.getValue().stringifyValue().equals(tostring)) { fail("Expected element "+name+" to have value "+tostring+" but it had value "+element.getValue().stringifyValue()); diff --git a/bcel-builder/verifier-src/org/aspectj/apache/bcel/verifier/DescendingVisitor.java b/bcel-builder/verifier-src/org/aspectj/apache/bcel/verifier/DescendingVisitor.java index 2e77bd2a4..3130e6667 100644 --- a/bcel-builder/verifier-src/org/aspectj/apache/bcel/verifier/DescendingVisitor.java +++ b/bcel-builder/verifier-src/org/aspectj/apache/bcel/verifier/DescendingVisitor.java @@ -105,13 +105,13 @@ import org.aspectj.apache.bcel.classfile.annotation.RuntimeVisibleParameterAnnot * class supplies the traversal strategy, other classes can make use * of it. * - * @version $Id: DescendingVisitor.java,v 1.2 2008/05/28 23:53:00 aclement Exp $ + * @version $Id: DescendingVisitor.java,v 1.3 2009/09/09 19:56:20 aclement Exp $ * @author M. Dahm */ public class DescendingVisitor implements ClassVisitor { private JavaClass clazz; private ClassVisitor visitor; - private Stack stack = new Stack(); + private Stack stack = new Stack(); /** @return container of current entitity, i.e., predecessor during traversal */ diff --git a/bcel-builder/verifier-src/org/aspectj/apache/bcel/verifier/PassVerifier.java b/bcel-builder/verifier-src/org/aspectj/apache/bcel/verifier/PassVerifier.java index 236b618e2..20aa49963 100644 --- a/bcel-builder/verifier-src/org/aspectj/apache/bcel/verifier/PassVerifier.java +++ b/bcel-builder/verifier-src/org/aspectj/apache/bcel/verifier/PassVerifier.java @@ -77,7 +77,7 @@ import java.util.ArrayList; * That means, if you really want a new verification run of a certain * pass you must use a new instance of a given PassVerifier. * - * @version $Id: PassVerifier.java,v 1.2 2008/05/28 23:53:00 aclement Exp $ + * @version $Id: PassVerifier.java,v 1.3 2009/09/09 19:56:20 aclement Exp $ * @author Enver Haase * @see org.aspectj.apache.bcel.verifier.Verifier * @see #verify() @@ -85,7 +85,7 @@ import java.util.ArrayList; public abstract class PassVerifier{ /** The (warning) messages. */ - private ArrayList messages = new ArrayList(); //Type of elements: String + private ArrayList messages = new ArrayList(); //Type of elements: String /** The VerificationResult cache. */ private VerificationResult verificationResult = null; @@ -136,7 +136,7 @@ public abstract class PassVerifier{ verify(); // create messages if not already done (cached!) String[] ret = new String[messages.size()]; for (int i=0; iEnver Haase * @see org.aspectj.apache.bcel.verifier.VerifierFactory * @see org.aspectj.apache.bcel.verifier.PassVerifier @@ -91,9 +91,9 @@ public class Verifier{ /** A Pass2Verifier for this Verifier instance. */ private Pass2Verifier p2v; /** The Pass3aVerifiers for this Verifier instance. Key: Interned string specifying the method number. */ - private HashMap p3avs = new HashMap(); + private HashMap p3avs = new HashMap(); /** The Pass3bVerifiers for this Verifier instance. Key: Interned string specifying the method number. */ - private HashMap p3bvs = new HashMap(); + private HashMap p3bvs = new HashMap(); /** Returns the VerificationResult for the given pass. */ public VerificationResult doPass1(){ @@ -115,7 +115,7 @@ public class Verifier{ public VerificationResult doPass3a(int method_no){ String key = Integer.toString(method_no); Pass3aVerifier p3av; - p3av = (Pass3aVerifier) (p3avs.get(key)); + p3av = (p3avs.get(key)); if (p3avs.get(key) == null){ p3av = new Pass3aVerifier(this, method_no); p3avs.put(key, p3av); @@ -127,7 +127,7 @@ public class Verifier{ public VerificationResult doPass3b(int method_no){ String key = Integer.toString(method_no); Pass3bVerifier p3bv; - p3bv = (Pass3bVerifier) (p3bvs.get(key)); + p3bv = (p3bvs.get(key)); if (p3bvs.get(key) == null){ p3bv = new Pass3bVerifier(this, method_no); p3bvs.put(key, p3bv); @@ -189,9 +189,9 @@ public class Verifier{ messages.add("Pass 2: "+p2m[i]); } } - Iterator p3as = p3avs.values().iterator(); + Iterator p3as = p3avs.values().iterator(); while (p3as.hasNext()){ - Pass3aVerifier pv = (Pass3aVerifier) p3as.next(); + Pass3aVerifier pv = p3as.next(); String[] p3am = pv.getMessages(); int meth = pv.getMethodNo(); for (int i=0; i p3bs = p3bvs.values().iterator(); while (p3bs.hasNext()){ - Pass3bVerifier pv = (Pass3bVerifier) p3bs.next(); + Pass3bVerifier pv = p3bs.next(); String[] p3bm = pv.getMessages(); int meth = pv.getMethodNo(); for (int i=0; iEnver Haase * @see org.aspectj.apache.bcel.verifier.Verifier */ @@ -73,12 +73,12 @@ public class VerifierFactory{ /** * The HashMap that holds the data about the already-constructed Verifier instances. */ - private static HashMap hashMap = new HashMap(); + private static HashMap hashMap = new HashMap(); /** * The VerifierFactoryObserver instances that observe the VerifierFactory. */ - private static Vector observers = new Vector(); + private static Vector observers = new Vector(); /** * The VerifierFactory is not instantiable. @@ -93,7 +93,7 @@ public class VerifierFactory{ public static Verifier getVerifier(String fully_qualified_classname){ // fully_qualified_classname = fully_qualified_classname; - Verifier v = (Verifier) (hashMap.get(fully_qualified_classname)); + Verifier v = (hashMap.get(fully_qualified_classname)); if (v==null){ v = new Verifier(fully_qualified_classname); hashMap.put(fully_qualified_classname, v); @@ -108,9 +108,9 @@ public class VerifierFactory{ */ private static void notify(String fully_qualified_classname){ // notify the observers - Iterator i = observers.iterator(); + Iterator i = observers.iterator(); while (i.hasNext()){ - VerifierFactoryObserver vfo = (VerifierFactoryObserver) i.next(); + VerifierFactoryObserver vfo = i.next(); vfo.update(fully_qualified_classname); } } @@ -124,7 +124,7 @@ public class VerifierFactory{ */ public static Verifier[] getVerifiers(){ Verifier[] vs = new Verifier[hashMap.values().size()]; - return (Verifier[]) (hashMap.values().toArray(vs)); // Because vs is big enough, vs is used to store the values into and returned! + return (hashMap.values().toArray(vs)); // Because vs is big enough, vs is used to store the values into and returned! } /** diff --git a/bcel-builder/verifier-src/org/aspectj/apache/bcel/verifier/VerifierFactoryListModel.java b/bcel-builder/verifier-src/org/aspectj/apache/bcel/verifier/VerifierFactoryListModel.java index 1808a6fca..485223e04 100644 --- a/bcel-builder/verifier-src/org/aspectj/apache/bcel/verifier/VerifierFactoryListModel.java +++ b/bcel-builder/verifier-src/org/aspectj/apache/bcel/verifier/VerifierFactoryListModel.java @@ -54,18 +54,19 @@ package org.aspectj.apache.bcel.verifier; * . */ import javax.swing.event.ListDataEvent; +import javax.swing.event.ListDataListener; /** * This class implements an adapter; it implements both a Swing ListModel and * a VerifierFactoryObserver. * - * @version $Id: VerifierFactoryListModel.java,v 1.2 2008/05/28 23:53:01 aclement Exp $ + * @version $Id: VerifierFactoryListModel.java,v 1.3 2009/09/09 19:56:20 aclement Exp $ * @author Enver Haase */ public class VerifierFactoryListModel implements org.aspectj.apache.bcel.verifier.VerifierFactoryObserver, javax.swing.ListModel{ - private java.util.ArrayList listeners = new java.util.ArrayList(); + private java.util.ArrayList listeners = new java.util.ArrayList(); - private java.util.TreeSet cache = new java.util.TreeSet(); + private java.util.TreeSet cache = new java.util.TreeSet(); public VerifierFactoryListModel() { VerifierFactory.attach(this); @@ -84,7 +85,7 @@ public class VerifierFactoryListModel implements org.aspectj.apache.bcel.verifie for (int i=0; iEnver Haase */ public class IntList{ /** The int are stored as Integer objects here. */ - private ArrayList theList; + private ArrayList theList; /** This constructor creates an empty list. */ IntList(){ - theList = new ArrayList(); + theList = new ArrayList(); } /** Adds an element to the list. */ void add(int i){ diff --git a/bcel-builder/verifier-src/org/aspectj/apache/bcel/verifier/statics/LocalVariableInfo.java b/bcel-builder/verifier-src/org/aspectj/apache/bcel/verifier/statics/LocalVariableInfo.java index 2d4e8ec98..ce92b19c5 100644 --- a/bcel-builder/verifier-src/org/aspectj/apache/bcel/verifier/statics/LocalVariableInfo.java +++ b/bcel-builder/verifier-src/org/aspectj/apache/bcel/verifier/statics/LocalVariableInfo.java @@ -64,15 +64,15 @@ import java.util.Hashtable; * a given slot (== index). This information * often changes in course of byte code offsets. * - * @version $Id: LocalVariableInfo.java,v 1.2 2008/05/28 23:52:54 aclement Exp $ + * @version $Id: LocalVariableInfo.java,v 1.3 2009/09/09 19:56:20 aclement Exp $ * @author Enver Haase */ public class LocalVariableInfo{ /** The types database. KEY: String representing the offset integer. */ - private Hashtable types = new Hashtable(); + private Hashtable types = new Hashtable(); /** The names database. KEY: String representing the offset integer. */ - private Hashtable names = new Hashtable(); + private Hashtable names = new Hashtable(); /** * Adds a name of a local variable and a certain slot to our 'names' @@ -98,7 +98,7 @@ public class LocalVariableInfo{ * variable slot at the given bytecode offset. */ public Type getType(int offset){ - return (Type) types.get(Integer.toString(offset)); + return types.get(Integer.toString(offset)); } /** * Returns the name of the local variable that uses this local @@ -109,7 +109,7 @@ public class LocalVariableInfo{ * variable slot at the given bytecode offset. */ public String getName(int offset){ - return (String) (names.get(Integer.toString(offset))); + return (names.get(Integer.toString(offset))); } /** * Adds some information about this local variable (slot). diff --git a/bcel-builder/verifier-src/org/aspectj/apache/bcel/verifier/statics/Pass2Verifier.java b/bcel-builder/verifier-src/org/aspectj/apache/bcel/verifier/statics/Pass2Verifier.java index a0740d279..f6b15dbb1 100644 --- a/bcel-builder/verifier-src/org/aspectj/apache/bcel/verifier/statics/Pass2Verifier.java +++ b/bcel-builder/verifier-src/org/aspectj/apache/bcel/verifier/statics/Pass2Verifier.java @@ -111,7 +111,7 @@ import org.aspectj.apache.bcel.verifier.exc.LocalVariableInfoInconsistentExcepti * More detailed information is to be found at the do_verify() * method's documentation. * - * @version $Id: Pass2Verifier.java,v 1.3 2008/08/28 00:02:14 aclement Exp $ + * @version $Id: Pass2Verifier.java,v 1.4 2009/09/09 19:56:20 aclement Exp $ * @author Enver Haase * @see #do_verify() */ @@ -214,7 +214,7 @@ public final class Pass2Verifier extends PassVerifier implements Constants{ * @throws ClassConstraintException otherwise. */ private void every_class_has_an_accessible_superclass(){ - HashSet hs = new HashSet(); // save class names to detect circular inheritance + HashSet hs = new HashSet(); // save class names to detect circular inheritance JavaClass jc = Repository.lookupClass(myOwner.getClassName()); int supidx = -1; @@ -258,7 +258,7 @@ public final class Pass2Verifier extends PassVerifier implements Constants{ * @see #every_class_has_an_accessible_superclass() */ private void final_methods_are_not_overridden(){ - HashMap hashmap = new HashMap(); + HashMap hashmap = new HashMap(); JavaClass jc = Repository.lookupClass(myOwner.getClassName()); int supidx = -1; @@ -319,11 +319,11 @@ public final class Pass2Verifier extends PassVerifier implements Constants{ private Class CONST_Methodref; private Class CONST_InterfaceMethodref; */ - private Class CONST_String; - private Class CONST_Integer; - private Class CONST_Float; - private Class CONST_Long; - private Class CONST_Double; + private Class CONST_String; + private Class CONST_Integer; + private Class CONST_Float; + private Class CONST_Long; + private Class CONST_Double; private Class CONST_NameAndType; private Class CONST_Utf8; @@ -332,9 +332,9 @@ public final class Pass2Verifier extends PassVerifier implements Constants{ private final int cplen; // == cp.getLength() -- to save computing power. private DescendingVisitor carrier; - private HashSet field_names = new HashSet(); - private HashSet field_names_and_desc = new HashSet(); - private HashSet method_names_and_desc = new HashSet(); + private HashSet field_names = new HashSet(); + private HashSet field_names_and_desc = new HashSet(); + private HashSet method_names_and_desc = new HashSet(); private CPESSC_Visitor(JavaClass _jc){ jc = _jc; diff --git a/bcel-builder/verifier-src/org/aspectj/apache/bcel/verifier/structurals/ControlFlowGraph.java b/bcel-builder/verifier-src/org/aspectj/apache/bcel/verifier/structurals/ControlFlowGraph.java index 7c2fdcc7b..c5a54fde7 100644 --- a/bcel-builder/verifier-src/org/aspectj/apache/bcel/verifier/structurals/ControlFlowGraph.java +++ b/bcel-builder/verifier-src/org/aspectj/apache/bcel/verifier/structurals/ControlFlowGraph.java @@ -72,7 +72,7 @@ import org.aspectj.apache.bcel.verifier.exc.StructuralCodeConstraintException; /** * This class represents a control flow graph of a method. * - * @version $Id: ControlFlowGraph.java,v 1.3 2008/08/28 00:02:13 aclement Exp $ + * @version $Id: ControlFlowGraph.java,v 1.4 2009/09/09 19:56:20 aclement Exp $ * @author Enver Haase */ public class ControlFlowGraph { @@ -98,18 +98,18 @@ public class ControlFlowGraph { /** * The 'incoming' execution Frames. */ - private final HashMap inFrames; // key: the last-executed JSR + private final HashMap inFrames; // key: the last-executed JSR /** * The 'outgoing' execution Frames. */ - private final HashMap outFrames; // key: the last-executed JSR + private final HashMap outFrames; // key: the last-executed JSR /** * The 'execution predecessors' - a list of type InstructionContext of those instances that have been execute()d before in * that order. */ - private ArrayList executionPredecessors = null; // Type: InstructionContext + private ArrayList executionPredecessors = null; // Type: InstructionContext /** * Creates an InstructionHandleImpl object from an InstructionHandle. Creation of one per InstructionHandle suffices. Don't @@ -121,8 +121,8 @@ public class ControlFlowGraph { } instruction = inst; - inFrames = new java.util.HashMap(); - outFrames = new java.util.HashMap(); + inFrames = new java.util.HashMap(); + outFrames = new java.util.HashMap(); } /* Satisfies InstructionContext.getTag(). */ @@ -145,14 +145,14 @@ public class ControlFlowGraph { /** * Returns a clone of the "outgoing" frame situation with respect to the given ExecutionChain. */ - public Frame getOutFrame(ArrayList execChain) { + public Frame getOutFrame(ArrayList execChain) { executionPredecessors = execChain; Frame org; InstructionContext jsr = lastExecutionJSR(); - org = (Frame) outFrames.get(jsr); + org = outFrames.get(jsr); if (org == null) { throw new AssertionViolatedException("outFrame not set! This:\n" + this + "\nExecutionChain: " @@ -170,9 +170,9 @@ public class ControlFlowGraph { * * @return true - if and only if the "outgoing" frame situation changed from the one before execute()ing. */ - public boolean execute(Frame inFrame, ArrayList execPreds, InstConstraintVisitor icv, ExecutionVisitor ev) { + public boolean execute(Frame inFrame, ArrayList execPreds, InstConstraintVisitor icv, ExecutionVisitor ev) { - executionPredecessors = (ArrayList) execPreds.clone(); + executionPredecessors = (ArrayList) execPreds.clone(); // sanity check if (lastExecutionJSR() == null && subroutines.subroutineOf(getInstruction()) != subroutines.getTopLevel()) { @@ -182,7 +182,7 @@ public class ControlFlowGraph { throw new AssertionViolatedException("Huh?! Am I '" + this + "' part of a subroutine or not?"); } - Frame inF = (Frame) inFrames.get(lastExecutionJSR()); + Frame inF = inFrames.get(lastExecutionJSR()); if (inF == null) {// no incoming frame was set, so set it. inFrames.put(lastExecutionJSR(), inFrame); inF = inFrame; @@ -242,7 +242,7 @@ public class ControlFlowGraph { */ private boolean mergeInFrames(Frame inFrame) { // TODO: Can be performance-improved. - Frame inF = (Frame) inFrames.get(lastExecutionJSR()); + Frame inF = inFrames.get(lastExecutionJSR()); OperandStack oldstack = inF.getStack().getClone(); LocalVariables oldlocals = inF.getLocals().getClone(); try { @@ -399,7 +399,7 @@ public class ControlFlowGraph { private final ExceptionHandlers exceptionhandlers; /** All InstructionContext instances of this ControlFlowGraph. */ - private final Hashtable instructionContexts = new Hashtable(); // keys: InstructionHandle, values: InstructionContextImpl + private final Hashtable instructionContexts = new Hashtable(); // keys: InstructionHandle, values: InstructionContextImpl /** * A Control Flow Graph. @@ -420,7 +420,7 @@ public class ControlFlowGraph { * Returns the InstructionContext of a given instruction. */ public InstructionContext contextOf(InstructionHandle inst) { - InstructionContext ic = (InstructionContext) instructionContexts.get(inst); + InstructionContext ic = instructionContexts.get(inst); if (ic == null) { throw new AssertionViolatedException("InstructionContext requested for an InstructionHandle that's not known!"); } @@ -444,7 +444,7 @@ public class ControlFlowGraph { */ public InstructionContext[] getInstructionContexts() { InstructionContext[] ret = new InstructionContext[instructionContexts.values().size()]; - return (InstructionContext[]) instructionContexts.values().toArray(ret); + return instructionContexts.values().toArray(ret); } /** diff --git a/bcel-builder/verifier-src/org/aspectj/apache/bcel/verifier/structurals/ExceptionHandlers.java b/bcel-builder/verifier-src/org/aspectj/apache/bcel/verifier/structurals/ExceptionHandlers.java index 69e904af0..40abf8f7c 100644 --- a/bcel-builder/verifier-src/org/aspectj/apache/bcel/verifier/structurals/ExceptionHandlers.java +++ b/bcel-builder/verifier-src/org/aspectj/apache/bcel/verifier/structurals/ExceptionHandlers.java @@ -55,13 +55,14 @@ package org.aspectj.apache.bcel.verifier.structurals; */ import org.aspectj.apache.bcel.generic.*; + import java.util.HashSet; import java.util.Hashtable; /** * This class allows easy access to ExceptionHandler objects. * - * @version $Id: ExceptionHandlers.java,v 1.2 2008/05/28 23:53:02 aclement Exp $ + * @version $Id: ExceptionHandlers.java,v 1.3 2009/09/09 19:56:20 aclement Exp $ * @author Enver Haase */ public class ExceptionHandlers{ @@ -69,21 +70,21 @@ public class ExceptionHandlers{ * The ExceptionHandler instances. * Key: InstructionHandle objects, Values: HashSet instances. */ - private Hashtable exceptionhandlers; + private Hashtable> exceptionhandlers; /** * Constructor. Creates a new ExceptionHandlers instance. */ public ExceptionHandlers(MethodGen mg){ - exceptionhandlers = new Hashtable(); + exceptionhandlers = new Hashtable>(); CodeExceptionGen[] cegs = mg.getExceptionHandlers(); for (int i=0; i hs; + hs = exceptionhandlers.get(ih); if (hs == null){ - hs = new HashSet(); + hs = new HashSet(); exceptionhandlers.put(ih, hs); } hs.add(eh); @@ -96,7 +97,7 @@ public class ExceptionHandlers{ * handlers that protect the instruction ih. */ public ExceptionHandler[] getExceptionHandlers(InstructionHandle ih){ - HashSet hs = (HashSet) exceptionhandlers.get(ih); + HashSet hs = exceptionhandlers.get(ih); if (hs == null) return new ExceptionHandler[0]; else{ ExceptionHandler[] ret = new ExceptionHandler[hs.size()]; diff --git a/bcel-builder/verifier-src/org/aspectj/apache/bcel/verifier/structurals/InstructionContext.java b/bcel-builder/verifier-src/org/aspectj/apache/bcel/verifier/structurals/InstructionContext.java index eb366d7ea..2127579f3 100644 --- a/bcel-builder/verifier-src/org/aspectj/apache/bcel/verifier/structurals/InstructionContext.java +++ b/bcel-builder/verifier-src/org/aspectj/apache/bcel/verifier/structurals/InstructionContext.java @@ -63,7 +63,7 @@ import org.aspectj.apache.bcel.generic.InstructionHandle; * to information like control flow successors and * such. * - * @version $Id: InstructionContext.java,v 1.2 2008/05/28 23:53:03 aclement Exp $ + * @version $Id: InstructionContext.java,v 1.3 2009/09/09 19:56:20 aclement Exp $ * @author Enver Haase */ public interface InstructionContext{ @@ -109,7 +109,7 @@ public interface InstructionContext{ * @return true - if and only if the "outgoing" frame situation * changed from the one before execute()ing. */ - boolean execute(Frame inFrame, ArrayList executionPredecessors, InstConstraintVisitor icv, ExecutionVisitor ev); + boolean execute(Frame inFrame, ArrayList executionPredecessors, InstConstraintVisitor icv, ExecutionVisitor ev); /** * This method returns the outgoing execution frame situation; @@ -118,7 +118,7 @@ public interface InstructionContext{ * * @see #execute(Frame, ArrayList, InstConstraintVisitor, ExecutionVisitor) */ - Frame getOutFrame(ArrayList executionPredecessors); + Frame getOutFrame(ArrayList executionPredecessors); /** * Returns the InstructionHandle this InstructionContext is wrapped around. diff --git a/bcel-builder/verifier-src/org/aspectj/apache/bcel/verifier/structurals/OperandStack.java b/bcel-builder/verifier-src/org/aspectj/apache/bcel/verifier/structurals/OperandStack.java index 6b7b7b0df..7559f5c6a 100644 --- a/bcel-builder/verifier-src/org/aspectj/apache/bcel/verifier/structurals/OperandStack.java +++ b/bcel-builder/verifier-src/org/aspectj/apache/bcel/verifier/structurals/OperandStack.java @@ -63,13 +63,13 @@ import java.util.*; * [It's used an an operand stack substitute.] * Elements of this stack are org.aspectj.apache.bcel.generic.Type objects. * - * @version $Id: OperandStack.java,v 1.2 2008/05/28 23:53:02 aclement Exp $ + * @version $Id: OperandStack.java,v 1.3 2009/09/09 19:56:20 aclement Exp $ * @author Enver Haase */ public class OperandStack{ /** We hold the stack information here. */ - private ArrayList stack = new ArrayList(); + private ArrayList stack = new ArrayList(); /** The maximum number of stack slots this OperandStack instance may hold. */ private int maxStack; @@ -96,7 +96,7 @@ public class OperandStack{ */ protected Object clone(){ OperandStack newstack = new OperandStack(this.maxStack); - newstack.stack = (ArrayList) this.stack.clone(); + newstack.stack = (ArrayList) this.stack.clone(); return newstack; } @@ -104,7 +104,7 @@ public class OperandStack{ * Clears the stack. */ public void clear(){ - stack = new ArrayList(); + stack = new ArrayList(); } /** @@ -153,14 +153,14 @@ public class OperandStack{ * iff i==0 the top element is returned. The element is not popped off the stack! */ public Type peek(int i){ - return (Type) stack.get(size()-i-1); + return stack.get(size()-i-1); } /** * Returns the element on top of the stack. The element is popped off the stack. */ public Type pop(){ - Type e = (Type) stack.remove(size()-1); + Type e = stack.remove(size()-1); return e; } diff --git a/bcel-builder/verifier-src/org/aspectj/apache/bcel/verifier/structurals/Pass3bVerifier.java b/bcel-builder/verifier-src/org/aspectj/apache/bcel/verifier/structurals/Pass3bVerifier.java index 224de27c9..efbefb000 100644 --- a/bcel-builder/verifier-src/org/aspectj/apache/bcel/verifier/structurals/Pass3bVerifier.java +++ b/bcel-builder/verifier-src/org/aspectj/apache/bcel/verifier/structurals/Pass3bVerifier.java @@ -85,7 +85,7 @@ import org.aspectj.apache.bcel.verifier.exc.VerifierConstraintViolatedException; * More detailed information is to be found at the do_verify() method's * documentation. * - * @version $Id: Pass3bVerifier.java,v 1.2 2008/05/28 23:53:03 aclement Exp $ + * @version $Id: Pass3bVerifier.java,v 1.3 2009/09/09 19:56:20 aclement Exp $ * @author Enver Haase * @see #do_verify() */ @@ -109,9 +109,9 @@ public final class Pass3bVerifier extends PassVerifier{ * we have about its symbolic execution predecessors. */ private static final class InstructionContextQueue{ - private Vector ics = new Vector(); // Type: InstructionContext - private Vector ecs = new Vector(); // Type: ArrayList (of InstructionContext) - public void add(InstructionContext ic, ArrayList executionChain){ + private Vector ics = new Vector(); // Type: InstructionContext + private Vector> ecs = new Vector>(); // Type: ArrayList (of InstructionContext) + public void add(InstructionContext ic, ArrayList executionChain){ ics.add(ic); ecs.add(executionChain); } @@ -126,10 +126,10 @@ public final class Pass3bVerifier extends PassVerifier{ ecs.remove(i); } public InstructionContext getIC(int i){ - return (InstructionContext) ics.get(i); + return ics.get(i); } - public ArrayList getEC(int i){ - return (ArrayList) ecs.get(i); + public ArrayList getEC(int i){ + return ecs.get(i); } public int size(){ return ics.size(); @@ -166,14 +166,14 @@ public final class Pass3bVerifier extends PassVerifier{ final Random random = new Random(); InstructionContextQueue icq = new InstructionContextQueue(); - start.execute(vanillaFrame, new ArrayList(), icv, ev); // new ArrayList() <=> no Instruction was executed before + start.execute(vanillaFrame, new ArrayList(), icv, ev); // new ArrayList() <=> no Instruction was executed before // => Top-Level routine (no jsr call before) - icq.add(start, new ArrayList()); + icq.add(start, new ArrayList()); // LOOP! while (!icq.isEmpty()){ InstructionContext u; - ArrayList ec; + ArrayList ec; if (!DEBUG){ int r = random.nextInt(icq.size()); u = icq.getIC(r); @@ -186,8 +186,8 @@ public final class Pass3bVerifier extends PassVerifier{ icq.remove(0); } - ArrayList oldchain = (ArrayList) (ec.clone()); - ArrayList newchain = (ArrayList) (ec.clone()); + ArrayList oldchain = (ArrayList) (ec.clone()); + ArrayList newchain = (ArrayList) (ec.clone()); newchain.add(u); if ((u.getInstruction().getInstruction()) instanceof RET){ @@ -206,16 +206,16 @@ public final class Pass3bVerifier extends PassVerifier{ throw new AssertionViolatedException("More RET than JSR in execution chain?!"); } //System.err.println("+"+oldchain.get(ss)); - if (((InstructionContext) oldchain.get(ss)).getInstruction().getInstruction().isJsrInstruction()) { + if (oldchain.get(ss).getInstruction().getInstruction().isJsrInstruction()) { if (skip_jsr == 0){ - lastJSR = (InstructionContext) oldchain.get(ss); + lastJSR = oldchain.get(ss); break; } else{ skip_jsr--; } } - if (((InstructionContext) oldchain.get(ss)).getInstruction().getInstruction() instanceof RET){ + if (oldchain.get(ss).getInstruction().getInstruction() instanceof RET){ skip_jsr++; } } @@ -228,7 +228,7 @@ public final class Pass3bVerifier extends PassVerifier{ } if (theSuccessor.execute(u.getOutFrame(oldchain), newchain, icv, ev)){ - icq.add(theSuccessor, (ArrayList) newchain.clone()); + icq.add(theSuccessor, (ArrayList) newchain.clone()); } } else{// "not a ret" @@ -238,7 +238,7 @@ public final class Pass3bVerifier extends PassVerifier{ for (int s=0; s) newchain.clone()); } } }// end "not a ret" @@ -258,8 +258,8 @@ public final class Pass3bVerifier extends PassVerifier{ // by using an empty chain for the exception handlers. //if (v.execute(new Frame(u.getOutFrame(oldchain).getLocals(), new OperandStack (u.getOutFrame().getStack().maxStack(), (exc_hds[s].getExceptionType()==null? Type.THROWABLE : exc_hds[s].getExceptionType())) ), newchain), icv, ev){ //icq.add(v, (ArrayList) newchain.clone()); - if (v.execute(new Frame(u.getOutFrame(oldchain).getLocals(), new OperandStack (u.getOutFrame(oldchain).getStack().maxStack(), (exc_hds[s].getExceptionType()==null? Type.THROWABLE : exc_hds[s].getExceptionType())) ), new ArrayList(), icv, ev)){ - icq.add(v, new ArrayList()); + if (v.execute(new Frame(u.getOutFrame(oldchain).getLocals(), new OperandStack (u.getOutFrame(oldchain).getStack().maxStack(), (exc_hds[s].getExceptionType()==null? Type.THROWABLE : exc_hds[s].getExceptionType())) ), new ArrayList(), icv, ev)){ + icq.add(v, new ArrayList()); } } @@ -269,7 +269,7 @@ public final class Pass3bVerifier extends PassVerifier{ do{ if ((ih.getInstruction().isReturnInstruction()) && (!(cfg.isDead(ih)))) { InstructionContext ic = cfg.contextOf(ih); - Frame f = ic.getOutFrame(new ArrayList()); // TODO: This is buggy, we check only the top-level return instructions this way. Maybe some maniac returns from a method when in a subroutine? + Frame f = ic.getOutFrame(new ArrayList()); // TODO: This is buggy, we check only the top-level return instructions this way. Maybe some maniac returns from a method when in a subroutine? LocalVariables lvs = f.getLocals(); for (int i=0; iEnver Haase * @see #getTopLevel() */ @@ -109,7 +110,7 @@ public class Subroutines{ private int localVariable = UNSET; /** The instructions that belong to this subroutine. */ - private HashSet instructions = new HashSet(); // Elements: InstructionHandle + private HashSet instructions = new HashSet(); // Elements: InstructionHandle /* * Refer to the Subroutine interface for documentation. @@ -122,7 +123,7 @@ public class Subroutines{ * The JSR or JSR_W instructions that define this * subroutine by targeting it. */ - private HashSet theJSRs = new HashSet(); + private HashSet theJSRs = new HashSet(); /** * The RET instruction that leaves this subroutine. @@ -164,7 +165,7 @@ public class Subroutines{ if (localVariable == UNSET){ throw new AssertionViolatedException("setLeavingRET() called for top-level 'subroutine' or forgot to set local variable first."); } - Iterator iter = instructions.iterator(); + Iterator iter = instructions.iterator(); InstructionHandle ret = null; while(iter.hasNext()){ InstructionHandle actual = (InstructionHandle) iter.next(); @@ -194,7 +195,7 @@ public class Subroutines{ throw new AssertionViolatedException("getLeavingRET() called on top level pseudo-subroutine."); } InstructionHandle[] jsrs = new InstructionHandle[theJSRs.size()]; - return (InstructionHandle[]) (theJSRs.toArray(jsrs)); + return (theJSRs.toArray(jsrs)); } /** @@ -233,7 +234,7 @@ public class Subroutines{ */ public InstructionHandle[] getInstructions(){ InstructionHandle[] ret = new InstructionHandle[instructions.size()]; - return (InstructionHandle[]) instructions.toArray(ret); + return instructions.toArray(ret); } /* @@ -250,18 +251,18 @@ public class Subroutines{ /* Satisfies Subroutine.getRecursivelyAccessedLocalsIndices(). */ public int[] getRecursivelyAccessedLocalsIndices(){ - HashSet s = new HashSet(); + HashSet s = new HashSet(); int[] lvs = getAccessedLocalsIndices(); for (int j=0; j i = s.iterator(); int j=-1; while (i.hasNext()){ j++; - ret[j] = ((Integer) i.next()).intValue(); + ret[j] = i.next().intValue(); } return ret; } @@ -270,7 +271,7 @@ public class Subroutines{ * A recursive helper method for getRecursivelyAccessedLocalsIndices(). * @see #getRecursivelyAccessedLocalsIndices() */ - private void _getRecursivelyAccessedLocalsIndicesHelper(HashSet s, Subroutine[] subs){ + private void _getRecursivelyAccessedLocalsIndicesHelper(HashSet s, Subroutine[] subs){ for (int i=0; i acc = new HashSet(); if (theRET == null && this != TOPLEVEL){ throw new AssertionViolatedException("This subroutine object must be built up completely before calculating accessed locals."); } - Iterator i = instructions.iterator(); + Iterator i = instructions.iterator(); while (i.hasNext()){ InstructionHandle ih = (InstructionHandle) i.next(); // RET is not a LocalVariableInstruction in the current version of BCEL. @@ -327,9 +328,9 @@ public class Subroutines{ * Satisfies Subroutine.subSubs(). */ public Subroutine[] subSubs(){ - HashSet h = new HashSet(); + HashSet h = new HashSet(); - Iterator i = instructions.iterator(); + Iterator i = instructions.iterator(); while (i.hasNext()){ Instruction inst = ((InstructionHandle) i.next()).getInstruction(); if (inst.isJsrInstruction()){ @@ -338,7 +339,7 @@ public class Subroutines{ } } Subroutine[] ret = new Subroutine[h.size()]; - return (Subroutine[]) h.toArray(ret); + return h.toArray(ret); } /* @@ -369,7 +370,7 @@ public class Subroutines{ * Key: InstructionHandle of the leader of the subroutine. * Elements: SubroutineImpl objects. */ - private Hashtable subroutines = new Hashtable(); + private Hashtable subroutines = new Hashtable(); /** * This is referring to a special subroutine, namely the @@ -393,7 +394,7 @@ public class Subroutines{ TOPLEVEL = new SubroutineImpl(); // Calculate "real" subroutines. - HashSet sub_leaders = new HashSet(); // Elements: InstructionHandle + HashSet sub_leaders = new HashSet(); // Elements: InstructionHandle InstructionHandle ih = all[0]; for (int i=0; i iter = sub_leaders.iterator(); while (iter.hasNext()){ SubroutineImpl sr = new SubroutineImpl(); - InstructionHandle astore = (InstructionHandle) (iter.next()); + InstructionHandle astore = (iter.next()); sr.setLocalVariable( ( (astore.getInstruction())).getIndex() ); subroutines.put(astore, sr); } @@ -430,21 +431,21 @@ public class Subroutines{ // Now do a BFS from every subroutine leader to find all the // instructions that belong to a subroutine. - HashSet instructions_assigned = new HashSet(); // we don't want to assign an instruction to two or more Subroutine objects. + HashSet instructions_assigned = new HashSet(); // we don't want to assign an instruction to two or more Subroutine objects. - Hashtable colors = new Hashtable(); //Graph colouring. Key: InstructionHandle, Value: java.awt.Color . + Hashtable colors = new Hashtable(); //Graph colouring. Key: InstructionHandle, Value: java.awt.Color . iter = sub_leaders.iterator(); while (iter.hasNext()){ // Do some BFS with "actual" as the root of the graph. - InstructionHandle actual = (InstructionHandle) (iter.next()); + InstructionHandle actual = (iter.next()); // Init colors for (int i=0; i Q = new ArrayList(); Q.add(actual); // add(Obj) adds to the end, remove(0) removes from the start. /* BFS ALGORITHM MODIFICATION: Start out with multiple "root" nodes, as exception handlers are starting points of top-level code, too. [why top-level? TODO: Refer to the special JustIce notion of subroutines.]*/ @@ -458,10 +459,10 @@ public class Subroutines{ // Loop until Queue is empty while (Q.size() != 0){ - InstructionHandle u = (InstructionHandle) Q.remove(0); + InstructionHandle u = Q.remove(0); InstructionHandle[] successors = getSuccessors(u); for (int i=0; i subs = subroutines.elements(); while (subs.hasMoreElements()){ - Subroutine sub = (Subroutine) subs.nextElement(); + Subroutine sub = subs.nextElement(); if (sub != subroutines.get(all[0])){ // We don't want to forbid top-level exception handlers. if (sub.contains(_protected)){ throw new StructuralCodeConstraintException("Subroutine instruction '"+_protected+"' is protected by an exception handler, '"+handlers[i]+"'. This is forbidden by the JustIce verifier due to its clear definition of subroutines."); @@ -509,7 +510,7 @@ public class Subroutines{ // This includes that subroutines may not call themselves // recursively, even not through intermediate calls to other // subroutines. - noRecursiveCalls(getTopLevel(), new HashSet()); + noRecursiveCalls(getTopLevel(), new HashSet()); } @@ -524,7 +525,7 @@ public class Subroutines{ * * @throws StructuralCodeConstraintException if the above constraint is not satisfied. */ - private void noRecursiveCalls(Subroutine sub, HashSet set){ + private void noRecursiveCalls(Subroutine sub, HashSet set){ Subroutine[] subs = sub.subSubs(); for (int i=0; i i = subroutines.values().iterator(); while (i.hasNext()){ - Subroutine s = (Subroutine) i.next(); + Subroutine s = i.next(); if (s.contains(any)) return s; } System.err.println("DEBUG: Please verify '"+any+"' lies in dead code."); diff --git a/bcel-builder/verifier-src/org/aspectj/apache/bcel/verifier/util/BCELFactory.java b/bcel-builder/verifier-src/org/aspectj/apache/bcel/verifier/util/BCELFactory.java index 4f1ae7e8b..5aa954588 100644 --- a/bcel-builder/verifier-src/org/aspectj/apache/bcel/verifier/util/BCELFactory.java +++ b/bcel-builder/verifier-src/org/aspectj/apache/bcel/verifier/util/BCELFactory.java @@ -85,7 +85,7 @@ import org.aspectj.apache.bcel.verifier.InstructionWalker; * Factory creates il.append() statements, and sets instruction targets. A helper class for BCELifier. * * @see BCELifier - * @version $Id: BCELFactory.java,v 1.4 2008/08/28 00:02:14 aclement Exp $ + * @version $Id: BCELFactory.java,v 1.5 2009/09/09 19:56:20 aclement Exp $ * @author M. Dahm */ class BCELFactory extends org.aspectj.apache.bcel.verifier.EmptyInstVisitor { @@ -99,7 +99,7 @@ class BCELFactory extends org.aspectj.apache.bcel.verifier.EmptyInstVisitor { _out = out; } - private final HashMap branch_map = new HashMap(); // Map + private final HashMap branch_map = new HashMap(); // Map public void start() { if (!_mg.isAbstract() && !_mg.isNative()) { @@ -258,7 +258,7 @@ class BCELFactory extends org.aspectj.apache.bcel.verifier.EmptyInstVisitor { } // Memorize BranchInstructions that need an update - private final ArrayList branches = new ArrayList(); + private final ArrayList branches = new ArrayList(); public void visitBranchInstruction(InstructionBranch bi) { BranchHandle bh = (BranchHandle) branch_map.get(bi); @@ -320,8 +320,8 @@ class BCELFactory extends org.aspectj.apache.bcel.verifier.EmptyInstVisitor { } private void updateBranchTargets() { - for (Iterator i = branches.iterator(); i.hasNext();) { - InstructionBranch bi = (InstructionBranch) i.next(); + for (Iterator i = branches.iterator(); i.hasNext();) { + InstructionBranch bi = i.next(); BranchHandle bh = (BranchHandle) branch_map.get(bi); int pos = bh.getPosition(); String name = bi.getName() + "_" + pos; diff --git a/bcel-builder/verifier-src/org/aspectj/apache/bcel/verifier/util/InstructionFinder.java b/bcel-builder/verifier-src/org/aspectj/apache/bcel/verifier/util/InstructionFinder.java index 58ce3c1ef..ba1f752c1 100644 --- a/bcel-builder/verifier-src/org/aspectj/apache/bcel/verifier/util/InstructionFinder.java +++ b/bcel-builder/verifier-src/org/aspectj/apache/bcel/verifier/util/InstructionFinder.java @@ -81,7 +81,7 @@ import org.apache.regexp.*; ... } - * @version $Id: InstructionFinder.java,v 1.3 2008/08/28 00:02:14 aclement Exp $ + * @version $Id: InstructionFinder.java,v 1.4 2009/09/09 19:56:20 aclement Exp $ * @author M. Dahm * @see Instruction * @see InstructionList @@ -90,7 +90,7 @@ public class InstructionFinder { private static final int OFFSET = 32767; // char + OFFSET is outside of LATIN-1 private static final int NO_OPCODES = 256; // Potential number, some are not used - private static final HashMap map = new HashMap(); // Map + private static final HashMap map = new HashMap(); // Map private InstructionList il; private String il_string; // instruction list as string @@ -126,7 +126,7 @@ public class InstructionFinder { * @return encoded string for a pattern such as "BranchInstruction". */ private static final String mapName(String pattern) { - String result = (String)map.get(pattern); + String result = map.get(pattern); if(result != null) return result; @@ -212,7 +212,7 @@ public class InstructionFinder { * @return iterator of matches where e.nextElement() returns an array of instruction handles * describing the matched area */ - public final Iterator search(String pattern, InstructionHandle from, + public final Iterator search(String pattern, InstructionHandle from, CodeConstraint constraint) { String search = compilePattern(pattern); @@ -230,7 +230,7 @@ public class InstructionFinder { " not found in instruction list."); try { RE regex = new RE(search); - ArrayList matches = new ArrayList(); + ArrayList matches = new ArrayList(); while(start < il_string.length() && regex.match(il_string, start)) { int startExpr = regex.getParenStart(0); @@ -260,7 +260,7 @@ public class InstructionFinder { * returns an array of instruction handles describing the matched * area */ - public final Iterator search(String pattern) { + public final Iterator search(String pattern) { return search(pattern, il.getStart(), null); } @@ -272,7 +272,7 @@ public class InstructionFinder { * @return iterator of matches where e.nextElement() returns an array of instruction handles * describing the matched area */ - public final Iterator search(String pattern, InstructionHandle from) { + public final Iterator search(String pattern, InstructionHandle from) { return search(pattern, from, null); } @@ -284,7 +284,7 @@ public class InstructionFinder { * @param constraint constraints to be checked on matching code * @return instruction handle or `null' if the match failed */ - public final Iterator search(String pattern, CodeConstraint constraint) { + public final Iterator search(String pattern, CodeConstraint constraint) { return search(pattern, il.getStart(), constraint); } @@ -373,9 +373,9 @@ public class InstructionFinder { // Compile strings - for(Iterator i = map.keySet().iterator(); i.hasNext(); ) { - String key = (String)i.next(); - String value = (String)map.get(key); + for(Iterator i = map.keySet().iterator(); i.hasNext(); ) { + String key = i.next(); + String value = map.get(key); char ch = value.charAt(1); // Omit already precompiled patterns if(ch < OFFSET) { -- 2.39.5