issue_id
int64
2.03k
426k
title
stringlengths
9
251
body
stringlengths
1
32.8k
status
stringclasses
6 values
after_fix_sha
stringlengths
7
7
project_name
stringclasses
6 values
repo_url
stringclasses
6 values
repo_name
stringclasses
6 values
language
stringclasses
1 value
issue_url
null
before_fix_sha
null
pull_url
null
commit_datetime
timestamp[us, tz=UTC]
report_datetime
timestamp[us, tz=UTC]
updated_file
stringlengths
2
187
file_content
stringlengths
0
368k
104,720
Bug 104720 VerifyError after weaving around trivial switch statement
After compiling the attached source file and class file with ajc -inpath . -outjar t.jar Tracer.aj (on any of 1.2.1, 1.5.0M2 or the June 2005 snapshot) and then attempting to run it with gij -classpath ./t.jar:$CLASSPATH Test the following error is obtained: Exception in thread "main" java.lang.VerifyError: verification failed at PC 1 in Test:newTest_aroundBody2((I)LTest;): branch out of range at java.lang.VMClassLoader.resolveClass(java.lang.Class) (/usr/lib/libgcj.so.6.0.0) at java.lang.Class.initializeClass() (/usr/lib/libgcj.so.6.0.0) at java.lang.Class.forName(java.lang.String, boolean, java.lang.ClassLoader) (/usr/lib/libgcj.so.6.0.0) at gnu.java.lang.MainThread.run() (/usr/lib/libgcj.so.6.0.0) An excerpt from the output of javap -private -classpath t.jar -c Test shows that the generated switch is indeed bogus: private static final Test newTest_aroundBody2(int); Code: 0: iload_0 1: tableswitch{ //0 to 0 0: -1157627302; default: 16 } 20: invokespecial #3; //Method "<init>":()V 23: areturn
resolved fixed
bf767a9
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-08-25T11:35:49Z
2005-07-21T18:20:00Z
bcel-builder/src/org/aspectj/apache/bcel/generic/SWITCH.java
package org.aspectj.apache.bcel.generic; /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Apache" and "Apache Software Foundation" and * "Apache BCEL" must not be used to endorse or promote products * derived from this software without prior written permission. For * written permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * "Apache BCEL", nor may "Apache" appear in their name, without * prior written permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /** * SWITCH - Branch depending on int value, generates either LOOKUPSWITCH or * TABLESWITCH instruction, depending on whether the match values (int[]) can be * sorted with no gaps between the numbers. * * @version $Id: SWITCH.java,v 1.2 2004/11/19 16:45:19 aclement Exp $ * @author <A HREF="mailto:[email protected]">M. Dahm</A> */ public final class SWITCH implements CompoundInstruction { private int[] match; private InstructionHandle[] targets; private Select instruction; private int match_length; /** * Template for switch() constructs. If the match array can be * sorted in ascending order with gaps no larger than max_gap * between the numbers, a TABLESWITCH instruction is generated, and * a LOOKUPSWITCH otherwise. The former may be more efficient, but * needs more space. * * Note, that the key array always will be sorted, though we leave * the original arrays unaltered. * * @param match array of match values (case 2: ... case 7: ..., etc.) * @param targets the instructions to be branched to for each case * @param target the default target * @param max_gap maximum gap that may between case branches */ public SWITCH(int[] match, InstructionHandle[] targets, InstructionHandle target, int max_gap) { this.match = (int[])match.clone(); this.targets = (InstructionHandle[])targets.clone(); if((match_length = match.length) < 2) // (almost) empty switch, or just default instruction = new TABLESWITCH(match, targets, target); else { sort(0, match_length - 1); if(matchIsOrdered(max_gap)) { fillup(max_gap, target); instruction = new TABLESWITCH(this.match, this.targets, target); } else instruction = new LOOKUPSWITCH(this.match, this.targets, target); } } public SWITCH(int[] match, InstructionHandle[] targets, InstructionHandle target) { this(match, targets, target, 1); } private final void fillup(int max_gap, InstructionHandle target) { int max_size = match_length + match_length * max_gap; int[] m_vec = new int[max_size]; InstructionHandle[] t_vec = new InstructionHandle[max_size]; int count = 1; m_vec[0] = match[0]; t_vec[0] = targets[0]; for(int i=1; i < match_length; i++) { int prev = match[i-1]; int gap = match[i] - prev; for(int j=1; j < gap; j++) { m_vec[count] = prev + j; t_vec[count] = target; count++; } m_vec[count] = match[i]; t_vec[count] = targets[i]; count++; } match = new int[count]; targets = new InstructionHandle[count]; System.arraycopy(m_vec, 0, match, 0, count); System.arraycopy(t_vec, 0, targets, 0, count); } /** * Sort match and targets array with QuickSort. */ private final void sort(int l, int r) { int i = l, j = r; int h, m = match[(l + r) / 2]; InstructionHandle h2; do { while(match[i] < m) i++; while(m < match[j]) j--; if(i <= j) { h=match[i]; match[i]=match[j]; match[j]=h; // Swap elements h2=targets[i]; targets[i]=targets[j]; targets[j]=h2; // Swap instructions, too i++; j--; } } while(i <= j); if(l < j) sort(l, j); if(i < r) sort(i, r); } /** * @return match is sorted in ascending order with no gap bigger than max_gap? */ private final boolean matchIsOrdered(int max_gap) { for(int i=1; i < match_length; i++) if(match[i] - match[i-1] > max_gap) return false; return true; } public final InstructionList getInstructionList() { return new InstructionList(instruction); } public final Instruction getInstruction() { return instruction; } }
104,720
Bug 104720 VerifyError after weaving around trivial switch statement
After compiling the attached source file and class file with ajc -inpath . -outjar t.jar Tracer.aj (on any of 1.2.1, 1.5.0M2 or the June 2005 snapshot) and then attempting to run it with gij -classpath ./t.jar:$CLASSPATH Test the following error is obtained: Exception in thread "main" java.lang.VerifyError: verification failed at PC 1 in Test:newTest_aroundBody2((I)LTest;): branch out of range at java.lang.VMClassLoader.resolveClass(java.lang.Class) (/usr/lib/libgcj.so.6.0.0) at java.lang.Class.initializeClass() (/usr/lib/libgcj.so.6.0.0) at java.lang.Class.forName(java.lang.String, boolean, java.lang.ClassLoader) (/usr/lib/libgcj.so.6.0.0) at gnu.java.lang.MainThread.run() (/usr/lib/libgcj.so.6.0.0) An excerpt from the output of javap -private -classpath t.jar -c Test shows that the generated switch is indeed bogus: private static final Test newTest_aroundBody2(int); Code: 0: iload_0 1: tableswitch{ //0 to 0 0: -1157627302; default: 16 } 20: invokespecial #3; //Method "<init>":()V 23: areturn
resolved fixed
bf767a9
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-08-25T11:35:49Z
2005-07-21T18:20:00Z
bcel-builder/src/org/aspectj/apache/bcel/generic/TABLESWITCH.java
package org.aspectj.apache.bcel.generic; /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Apache" and "Apache Software Foundation" and * "Apache BCEL" must not be used to endorse or promote products * derived from this software without prior written permission. For * written permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * "Apache BCEL", nor may "Apache" appear in their name, without * prior written permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ import java.io.*; import org.aspectj.apache.bcel.util.ByteSequence; /** * TABLESWITCH - Switch within given range of values, i.e., low..high * * @version $Id: TABLESWITCH.java,v 1.2 2004/11/19 16:45:19 aclement Exp $ * @author <A HREF="mailto:[email protected]">M. Dahm</A> * @see SWITCH */ public class TABLESWITCH extends Select { /** * Empty constructor needed for the Class.newInstance() statement in * Instruction.readInstruction(). Not to be used otherwise. */ TABLESWITCH() {} /** * @param match sorted array of match values, match[0] must be low value, * match[match_length - 1] high value * @param targets where to branch for matched values * @param target default branch */ public TABLESWITCH(int[] match, InstructionHandle[] targets, InstructionHandle target) { super(org.aspectj.apache.bcel.Constants.TABLESWITCH, match, targets, target); length = (short)(13 + match_length * 4); /* Alignment remainder assumed * 0 here, until dump time */ fixed_length = length; } /** * Dump instruction as byte code to stream out. * @param out Output stream */ public void dump(DataOutputStream out) throws IOException { super.dump(out); int low = (match_length > 0)? match[0] : 0; out.writeInt(low); int high = (match_length > 0)? match[match_length - 1] : 0; out.writeInt(high); for(int i=0; i < match_length; i++) // jump offsets out.writeInt(indices[i] = getTargetOffset(targets[i])); } /** * Read needed data (e.g. index) from file. */ protected void initFromFile(ByteSequence bytes, boolean wide) throws IOException { super.initFromFile(bytes, wide); int low = bytes.readInt(); int high = bytes.readInt(); match_length = high - low + 1; fixed_length = (short)(13 + match_length * 4); length = (short)(fixed_length + padding); match = new int[match_length]; indices = new int[match_length]; targets = new InstructionHandle[match_length]; for(int i=low; i <= high; i++) match[i - low] = i; for(int i=0; i < match_length; i++) { indices[i] = bytes.readInt(); } } /** * Call corresponding visitor method(s). The order is: * Call visitor methods of implemented interfaces first, then * call methods according to the class hierarchy in descending order, * i.e., the most specific visitXXX() call comes last. * * @param v Visitor object */ public void accept(Visitor v) { v.visitVariableLengthInstruction(this); v.visitStackProducer(this); v.visitBranchInstruction(this); v.visitSelect(this); v.visitTABLESWITCH(this); } }
107,713
Bug 107713 ClassCastException popup
Whenever I change any file and save(auto-compile) I get this in a popup. ClassCastException thrown: org.aspectj.ajdt.internal.compiler.lookup.EclipseSourceType cannot be cast to org.aspectj.weaver.bcel.BcelObjectType This started happening when I wrote these aspects. Before this started happening the IDE showed this line as an error. b.support.firePropertyChange( property, ( oldval == null ) ? oldval : new String(oldval), new String(newval)); ---------------------------------------------------------------- /** * */ package com.blueprint.util.mixin.test; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.lang.reflect.Field; import com.blueprint.util.mixin.test.*; import org.aspectj.lang.Signature; public aspect PropertySupportAspect { PropertyChangeSupport PropertySupport.support = new PropertyChangeSupport(this); public interface PropertySupport{ public void addPropertyChangeListener( PropertyChangeListener listener ); public void addPropertyChangeListener( String propertyName, PropertyChangeListener listener ); public void removePropertyChangeListener( String propertyName, PropertyChangeListener listener ); public void removePropertyChangeListener( PropertyChangeListener listener ); public void hasListeners( String propertyName ); } public void PropertySupport.addPropertyChangeListener (PropertyChangeListener listener){ support.addPropertyChangeListener(listener); } public void PropertySupport.addPropertyChangeListener( String propertyName, PropertyChangeListener listener){ support.addPropertyChangeListener(propertyName, listener); } public void PropertySupport.removePropertyChangeListener( String propertyName, PropertyChangeListener listener) { support.removePropertyChangeListener(propertyName, listener); } public void PropertySupport.removePropertyChangeListener (PropertyChangeListener listener) { support.removePropertyChangeListener(listener); } public void PropertySupport.hasListeners(String propertyName) { support.hasListeners(propertyName); } pointcut callSetter( Bean b ) : call( public void com.blueprint.util.test.Bean.setName( String ) ) && target( b ); void around( Bean b ) : callSetter( b ) { String propertyName = getField( thisJoinPointStaticPart.getSignature() ). getName (); System.out.println( "The property is [" + propertyName + "]" ); String oldValue = b.getName(); proceed( b ); firePropertyChange( b, propertyName, oldValue, b.getName ()); } private Field getField( Signature signature ){ Field field = null; System.out.println( "Getting the field name of [" +signature.getName() + "]" ); try{ String methodName = signature.getName(); field = signature.getDeclaringType(). getDeclaredField( methodName. substring( 3, methodName.length() ). toLowerCase()); field.setAccessible(true); }catch( NoSuchFieldException nsfe ){ nsfe.printStackTrace(); } return field; } void firePropertyChange( Bean b, String property, String oldval, String newval) { System.out.println( "The property is [" + property + "]"); System.out.println( "The old value is [" + oldval + "]"); System.out.println( "The new value is [" + newval + "]"); b.support.firePropertyChange( property, ( oldval == null ) ? oldval : new String(oldval), new String(newval)); } } ---------------------------------------------------------------- import java.io.Serializable; public class Bean implements Serializable{ private String name; public String getName() { return name; } public void setName( String name ) { this.name = name; } } ---------------------------------------------------------------- public aspect BeanSupport { declare parents: Bean implements PropertySupportAspect.PropertySupport; } ----------------------------------------------------------------
resolved fixed
100d9e0
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-08-26T09:09:35Z
2005-08-23T09:40:00Z
weaver/src/org/aspectj/weaver/bcel/BcelWeaver.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * Alexandre Vasseur support for @AJ aspects * ******************************************************************/ package org.aspectj.weaver.bcel; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.jar.Attributes; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.jar.Manifest; import java.util.jar.Attributes.Name; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; import org.aspectj.apache.bcel.classfile.ClassParser; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.IProgressListener; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; import org.aspectj.bridge.SourceLocation; import org.aspectj.bridge.WeaveMessage; import org.aspectj.util.FileUtil; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.Advice; import org.aspectj.weaver.AnnotationOnTypeMunger; import org.aspectj.weaver.AnnotationX; import org.aspectj.weaver.AsmRelationshipProvider; import org.aspectj.weaver.ConcreteTypeMunger; import org.aspectj.weaver.CrosscuttingMembersSet; import org.aspectj.weaver.IClassFileProvider; import org.aspectj.weaver.IWeaveRequestor; import org.aspectj.weaver.IWeaver; import org.aspectj.weaver.NewParentTypeMunger; import org.aspectj.weaver.ResolvedTypeMunger; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.WeaverMetrics; import org.aspectj.weaver.WeaverStateInfo; import org.aspectj.weaver.World; import org.aspectj.weaver.patterns.AndPointcut; import org.aspectj.weaver.patterns.BindingAnnotationTypePattern; import org.aspectj.weaver.patterns.BindingTypePattern; import org.aspectj.weaver.patterns.CflowPointcut; import org.aspectj.weaver.patterns.ConcreteCflowPointcut; import org.aspectj.weaver.patterns.DeclareAnnotation; import org.aspectj.weaver.patterns.DeclareParents; import org.aspectj.weaver.patterns.FastMatchInfo; import org.aspectj.weaver.patterns.IfPointcut; import org.aspectj.weaver.patterns.KindedPointcut; import org.aspectj.weaver.patterns.NameBindingPointcut; import org.aspectj.weaver.patterns.NotPointcut; import org.aspectj.weaver.patterns.OrPointcut; import org.aspectj.weaver.patterns.Pointcut; import org.aspectj.weaver.patterns.PointcutRewriter; import org.aspectj.weaver.patterns.WithinPointcut; public class BcelWeaver implements IWeaver { private BcelWorld world; private CrosscuttingMembersSet xcutSet; private IProgressListener progressListener = null; private double progressMade; private double progressPerClassFile; private boolean inReweavableMode = false; public BcelWeaver(BcelWorld world) { super(); WeaverMetrics.reset(); this.world = world; this.xcutSet = world.getCrosscuttingMembersSet(); } public BcelWeaver() { this(new BcelWorld()); } // ---- fields // private Map sourceJavaClasses = new HashMap(); /* String -> UnwovenClassFile */ private List addedClasses = new ArrayList(); /* List<UnovenClassFile> */ private List deletedTypenames = new ArrayList(); /* List<String> */ // private Map resources = new HashMap(); /* String -> UnwovenClassFile */ private Manifest manifest = null; private boolean needToReweaveWorld = false; private List shadowMungerList = null; // setup by prepareForWeave private List typeMungerList = null; // setup by prepareForWeave private List lateTypeMungerList = null; // setup by prepareForWeave private List declareParentsList = null; // setup by prepareForWeave private ZipOutputStream zipOutputStream; // ---- // only called for testing public void setShadowMungers(List l) { shadowMungerList = l; } /** * Add the given aspect to the weaver. * The type is resolved to support DOT for static inner classes as well as DOLLAR * * @param aspectName */ public void addLibraryAspect(String aspectName) { // 1 - resolve as is ResolvedType type = world.resolve(UnresolvedType.forName(aspectName), true); if (type.equals(ResolvedType.MISSING)) { // fallback on inner class lookup mechanism String fixedName = aspectName; int hasDot = fixedName.lastIndexOf('.'); while (hasDot > 0) { //System.out.println("BcelWeaver.addLibraryAspect " + fixedName); char[] fixedNameChars = fixedName.toCharArray(); fixedNameChars[hasDot] = '$'; fixedName = new String(fixedNameChars); hasDot = fixedName.lastIndexOf('.'); type = world.resolve(UnresolvedType.forName(fixedName), true); if (!type.equals(ResolvedType.MISSING)) { break; } } } //System.out.println("type: " + type + " for " + aspectName); if (type.isAspect()) { //TODO AV - happens to reach that a lot of time: for each type flagged reweavable X for each aspect in the weaverstate //=> mainly for nothing for LTW - pbly for something in incremental build... xcutSet.addOrReplaceAspect(type); } else { // FIXME : Alex: better warning upon no such aspect from aop.xml throw new RuntimeException("Cannot register non aspect: " + type.getName() + " , " + aspectName); } } /** * * @param inFile File path to class directory or zip/jar class archive * @throws IOException */ public void addLibraryJarFile(File inFile) throws IOException { List addedAspects = null; if (inFile.isDirectory()) { addedAspects = addAspectsFromDirectory(inFile); } else { addedAspects = addAspectsFromJarFile(inFile); } for (Iterator i = addedAspects.iterator(); i.hasNext();) { ResolvedType aspectX = (ResolvedType) i.next(); xcutSet.addOrReplaceAspect(aspectX); } } private List addAspectsFromJarFile(File inFile) throws FileNotFoundException, IOException { ZipInputStream inStream = new ZipInputStream(new FileInputStream(inFile)); //??? buffered List addedAspects = new ArrayList(); while (true) { ZipEntry entry = inStream.getNextEntry(); if (entry == null) break; if (entry.isDirectory() || !entry.getName().endsWith(".class")) { continue; } // FIXME ASC performance? of this alternative soln. ClassParser parser = new ClassParser(new ByteArrayInputStream(FileUtil.readAsByteArray(inStream)), entry.getName()); JavaClass jc = parser.parse(); inStream.closeEntry(); ResolvedType type = world.addSourceObjectType(jc).getResolvedTypeX(); if (type.isAspect()) { addedAspects.add(type); } } inStream.close(); return addedAspects; } private List addAspectsFromDirectory(File dir) throws FileNotFoundException, IOException{ List addedAspects = new ArrayList(); File[] classFiles = FileUtil.listFiles(dir,new FileFilter(){ public boolean accept(File pathname) { return pathname.getName().endsWith(".class"); } }); for (int i = 0; i < classFiles.length; i++) { FileInputStream fis = new FileInputStream(classFiles[i]); byte[] bytes = FileUtil.readAsByteArray(fis); addIfAspect(bytes,classFiles[i].getAbsolutePath(),addedAspects); } return addedAspects; } private void addIfAspect(byte[] bytes, String name, List toList) throws IOException { ClassParser parser = new ClassParser(new ByteArrayInputStream(bytes),name); JavaClass jc = parser.parse(); ResolvedType type = world.addSourceObjectType(jc).getResolvedTypeX(); if (type.isAspect()) { toList.add(type); } } // // The ANT copy task should be used to copy resources across. // private final static boolean CopyResourcesFromInpathDirectoriesToOutput=false; /** * Add any .class files in the directory to the outdir. Anything other than .class files in * the directory (or its subdirectories) are considered resources and are also copied. * */ public List addDirectoryContents(File inFile,File outDir) throws IOException { List addedClassFiles = new ArrayList(); // Get a list of all files (i.e. everything that isnt a directory) File[] files = FileUtil.listFiles(inFile,new FileFilter() { public boolean accept(File f) { boolean accept = !f.isDirectory(); return accept; } }); // For each file, add it either as a real .class file or as a resource for (int i = 0; i < files.length; i++) { addedClassFiles.add(addClassFile(files[i],inFile,outDir)); } return addedClassFiles; } /** Adds all class files in the jar */ public List addJarFile(File inFile, File outDir, boolean canBeDirectory){ // System.err.println("? addJarFile(" + inFile + ", " + outDir + ")"); List addedClassFiles = new ArrayList(); needToReweaveWorld = true; JarFile inJar = null; try { // Is this a directory we are looking at? if (inFile.isDirectory() && canBeDirectory) { addedClassFiles.addAll(addDirectoryContents(inFile,outDir)); } else { inJar = new JarFile(inFile); addManifest(inJar.getManifest()); Enumeration entries = inJar.entries(); while (entries.hasMoreElements()) { JarEntry entry = (JarEntry)entries.nextElement(); InputStream inStream = inJar.getInputStream(entry); byte[] bytes = FileUtil.readAsByteArray(inStream); String filename = entry.getName(); // System.out.println("? addJarFile() filename='" + filename + "'"); UnwovenClassFile classFile = new UnwovenClassFile(new File(outDir, filename).getAbsolutePath(), bytes); if (filename.endsWith(".class")) { this.addClassFile(classFile); addedClassFiles.add(classFile); } // else if (!entry.isDirectory()) { // // /* bug-44190 Copy meta-data */ // addResource(filename,classFile); // } inStream.close(); } inJar.close(); } } catch (FileNotFoundException ex) { IMessage message = new Message( "Could not find input jar file " + inFile.getPath() + ", ignoring", new SourceLocation(inFile,0), false); world.getMessageHandler().handleMessage(message); } catch (IOException ex) { IMessage message = new Message( "Could not read input jar file " + inFile.getPath() + "(" + ex.getMessage() + ")", new SourceLocation(inFile,0), true); world.getMessageHandler().handleMessage(message); } finally { if (inJar != null) { try {inJar.close();} catch (IOException ex) { IMessage message = new Message( "Could not close input jar file " + inFile.getPath() + "(" + ex.getMessage() + ")", new SourceLocation(inFile,0), true); world.getMessageHandler().handleMessage(message); } } } return addedClassFiles; } // public void addResource(String name, File inPath, File outDir) throws IOException { // // /* Eliminate CVS files. Relative paths use "/" */ // if (!name.startsWith("CVS/") && (-1 == name.indexOf("/CVS/")) && !name.endsWith("/CVS")) { //// System.err.println("? addResource('" + name + "')"); //// BufferedInputStream inStream = new BufferedInputStream(new FileInputStream(inPath)); //// byte[] bytes = new byte[(int)inPath.length()]; //// inStream.read(bytes); //// inStream.close(); // byte[] bytes = FileUtil.readAsByteArray(inPath); // UnwovenClassFile resourceFile = new UnwovenClassFile(new File(outDir, name).getAbsolutePath(), bytes); // addResource(name,resourceFile); // } // } public boolean needToReweaveWorld() { return needToReweaveWorld; } /** Should be addOrReplace */ public void addClassFile(UnwovenClassFile classFile) { addedClasses.add(classFile); // if (null != sourceJavaClasses.put(classFile.getClassName(), classFile)) { //// throw new RuntimeException(classFile.getClassName()); // } world.addSourceObjectType(classFile.getJavaClass()); } public UnwovenClassFile addClassFile(File classFile, File inPathDir, File outDir) throws IOException { FileInputStream fis = new FileInputStream(classFile); byte[] bytes = FileUtil.readAsByteArray(fis); // String relativePath = files[i].getPath(); // ASSERT: files[i].getAbsolutePath().startsWith(inFile.getAbsolutePath() // or we are in trouble... String filename = classFile.getAbsolutePath().substring( inPathDir.getAbsolutePath().length()+1); UnwovenClassFile ucf = new UnwovenClassFile(new File(outDir,filename).getAbsolutePath(),bytes); if (filename.endsWith(".class")) { // System.err.println("BCELWeaver: processing class from input directory "+classFile); this.addClassFile(ucf); } fis.close(); return ucf; } public void deleteClassFile(String typename) { deletedTypenames.add(typename); // sourceJavaClasses.remove(typename); world.deleteSourceObjectType(UnresolvedType.forName(typename)); } // public void addResource (String name, UnwovenClassFile resourceFile) { // /* bug-44190 Change error to warning and copy first resource */ // if (!resources.containsKey(name)) { // resources.put(name, resourceFile); // } // else { // world.showMessage(IMessage.WARNING, "duplicate resource: '" + name + "'", // null, null); // } // } // ---- weave preparation public void prepareForWeave() { needToReweaveWorld = false; CflowPointcut.clearCaches(); // update mungers for (Iterator i = addedClasses.iterator(); i.hasNext(); ) { UnwovenClassFile jc = (UnwovenClassFile)i.next(); String name = jc.getClassName(); ResolvedType type = world.resolve(name); //System.err.println("added: " + type + " aspect? " + type.isAspect()); if (type.isAspect()) { needToReweaveWorld |= xcutSet.addOrReplaceAspect(type); } } for (Iterator i = deletedTypenames.iterator(); i.hasNext(); ) { String name = (String)i.next(); if (xcutSet.deleteAspect(UnresolvedType.forName(name))) needToReweaveWorld = true; } shadowMungerList = xcutSet.getShadowMungers(); rewritePointcuts(shadowMungerList); typeMungerList = xcutSet.getTypeMungers(); lateTypeMungerList = xcutSet.getLateTypeMungers(); declareParentsList = xcutSet.getDeclareParents(); // The ordering here used to be based on a string compare on toString() for the two mungers - // that breaks for the @AJ style where advice names aren't programmatically generated. So we // have changed the sorting to be based on source location in the file - this is reliable, in // the case of source locations missing, we assume they are 'sorted' - i.e. the order in // which they were added to the collection is correct, this enables the @AJ stuff to work properly. // When @AJ processing starts filling in source locations for mungers, this code may need // a bit of alteration... Collections.sort( shadowMungerList, new Comparator() { public int compare(Object o1, Object o2) { ShadowMunger sm1 = (ShadowMunger)o1; ShadowMunger sm2 = (ShadowMunger)o2; if (sm1.getSourceLocation()==null) return (sm2.getSourceLocation()==null?0:1); if (sm2.getSourceLocation()==null) return -1; return (sm2.getSourceLocation().getOffset()-sm1.getSourceLocation().getOffset()); } }); } /* * Rewrite all of the pointcuts in the world into their most efficient * form for subsequent matching. Also ensure that if pc1.equals(pc2) * then pc1 == pc2 (for non-binding pcds) by making references all * point to the same instance. * Since pointcuts remember their match decision on the last shadow, * this makes matching faster when many pointcuts share common elements, * or even when one single pointcut has one common element (which can * be a side-effect of DNF rewriting). */ private void rewritePointcuts(List/*ShadowMunger*/ shadowMungers) { PointcutRewriter rewriter = new PointcutRewriter(); for (Iterator iter = shadowMungers.iterator(); iter.hasNext();) { ShadowMunger munger = (ShadowMunger) iter.next(); Pointcut p = munger.getPointcut(); Pointcut newP = rewriter.rewrite(p); // validateBindings now whilst we still have around the pointcut // that resembles what the user actually wrote in their program // text. if (munger instanceof Advice) { Advice advice = (Advice) munger; if (advice.getSignature() != null) { final int numFormals; final String names[]; //ATAJ for @AJ aspect, the formal have to be checked according to the argument number // since xxxJoinPoint presence or not have side effects if (advice.getConcreteAspect().isAnnotationStyleAspect()) { numFormals = advice.getBaseParameterCount(); int numArgs = advice.getSignature().getParameterTypes().length; if (numFormals > 0) { names = advice.getSignature().getParameterNames(world); validateBindings(newP,p,numArgs,names); } } else { numFormals = advice.getBaseParameterCount(); if (numFormals > 0) { names = advice.getBaseParameterNames(world); validateBindings(newP,p,numFormals,names); } } } } munger.setPointcut(newP); } // now that we have optimized individual pointcuts, optimize // across the set of pointcuts.... // Use a map from key based on pc equality, to value based on // pc identity. Map/*<Pointcut,Pointcut>*/ pcMap = new HashMap(); for (Iterator iter = shadowMungers.iterator(); iter.hasNext();) { ShadowMunger munger = (ShadowMunger) iter.next(); Pointcut p = munger.getPointcut(); munger.setPointcut(shareEntriesFromMap(p,pcMap)); } } private Pointcut shareEntriesFromMap(Pointcut p,Map pcMap) { // some things cant be shared... if (p instanceof NameBindingPointcut) return p; if (p instanceof IfPointcut) return p; if (p instanceof ConcreteCflowPointcut) return p; if (p instanceof AndPointcut) { AndPointcut apc = (AndPointcut) p; Pointcut left = shareEntriesFromMap(apc.getLeft(),pcMap); Pointcut right = shareEntriesFromMap(apc.getRight(),pcMap); return new AndPointcut(left,right); } else if (p instanceof OrPointcut) { OrPointcut opc = (OrPointcut) p; Pointcut left = shareEntriesFromMap(opc.getLeft(),pcMap); Pointcut right = shareEntriesFromMap(opc.getRight(),pcMap); return new OrPointcut(left,right); } else if (p instanceof NotPointcut) { NotPointcut npc = (NotPointcut) p; Pointcut not = shareEntriesFromMap(npc.getNegatedPointcut(),pcMap); return new NotPointcut(not); } else { // primitive pcd if (pcMap.containsKey(p)) { // based on equality return (Pointcut) pcMap.get(p); // same instance (identity) } else { pcMap.put(p,p); return p; } } } // userPointcut is the pointcut that the user wrote in the program text. // dnfPointcut is the same pointcut rewritten in DNF // numFormals is the number of formal parameters in the pointcut // if numFormals > 0 then every branch of a disjunction must bind each formal once and only once. // in addition, the left and right branches of a disjunction must hold on join point kinds in // common. private void validateBindings(Pointcut dnfPointcut, Pointcut userPointcut, int numFormals, String[] names) { if (numFormals == 0) return; // nothing to check if (dnfPointcut.couldMatchKinds().isEmpty()) return; // cant have problems if you dont match! if (dnfPointcut instanceof OrPointcut) { OrPointcut orBasedDNFPointcut = (OrPointcut) dnfPointcut; Pointcut[] leftBindings = new Pointcut[numFormals]; Pointcut[] rightBindings = new Pointcut[numFormals]; validateOrBranch(orBasedDNFPointcut,userPointcut,numFormals,names,leftBindings,rightBindings); } else { Pointcut[] bindings = new Pointcut[numFormals]; validateSingleBranch(dnfPointcut, userPointcut, numFormals, names,bindings); } } private void validateOrBranch(OrPointcut pc, Pointcut userPointcut, int numFormals, String[] names, Pointcut[] leftBindings, Pointcut[] rightBindings) { Pointcut left = pc.getLeft(); Pointcut right = pc.getRight(); if (left instanceof OrPointcut) { Pointcut[] newRightBindings = new Pointcut[numFormals]; validateOrBranch((OrPointcut)left,userPointcut,numFormals,names,leftBindings,newRightBindings); } else { if (left.couldMatchKinds().size() > 0) validateSingleBranch(left, userPointcut, numFormals, names, leftBindings); } if (right instanceof OrPointcut) { Pointcut[] newLeftBindings = new Pointcut[numFormals]; validateOrBranch((OrPointcut)right,userPointcut,numFormals,names,newLeftBindings,rightBindings); } else { if (right.couldMatchKinds().size() > 0) validateSingleBranch(right, userPointcut, numFormals, names, rightBindings); } Set kindsInCommon = left.couldMatchKinds(); kindsInCommon.retainAll(right.couldMatchKinds()); if (!kindsInCommon.isEmpty() && couldEverMatchSameJoinPoints(left,right)) { // we know that every branch binds every formal, so there is no ambiguity // if each branch binds it in exactly the same way... List ambiguousNames = new ArrayList(); for (int i = 0; i < numFormals; i++) { if (!leftBindings[i].equals(rightBindings[i])) { ambiguousNames.add(names[i]); } } if (!ambiguousNames.isEmpty()) raiseAmbiguityInDisjunctionError(userPointcut,ambiguousNames); } } // pc is a pointcut that does not contain any disjunctions // check that every formal is bound (negation doesn't count). // we know that numFormals > 0 or else we would not be called private void validateSingleBranch(Pointcut pc, Pointcut userPointcut, int numFormals, String[] names, Pointcut[] bindings) { boolean[] foundFormals = new boolean[numFormals]; for (int i = 0; i < foundFormals.length; i++) { foundFormals[i] = false; } validateSingleBranchRecursion(pc, userPointcut, foundFormals, names, bindings); for (int i = 0; i < foundFormals.length; i++) { if (!foundFormals[i]) { boolean ignore = false; // ATAJ soften the unbound error for implicit bindings like JoinPoint in @AJ style for (int j = 0; j < userPointcut.m_ignoreUnboundBindingForNames.length; j++) { if (names[i] != null && names[i].equals(userPointcut.m_ignoreUnboundBindingForNames[j])) { ignore = true; break; } } if (!ignore) { raiseUnboundFormalError(names[i],userPointcut); } } } } // each formal must appear exactly once private void validateSingleBranchRecursion(Pointcut pc, Pointcut userPointcut, boolean[] foundFormals, String[] names, Pointcut[] bindings) { if (pc instanceof NotPointcut) { // nots can only appear at leaves in DNF NotPointcut not = (NotPointcut) pc; if (not.getNegatedPointcut() instanceof NameBindingPointcut) { NameBindingPointcut nnbp = (NameBindingPointcut) not.getNegatedPointcut(); if (!nnbp.getBindingAnnotationTypePatterns().isEmpty() && !nnbp.getBindingTypePatterns().isEmpty()) raiseNegationBindingError(userPointcut); } } else if (pc instanceof AndPointcut) { AndPointcut and = (AndPointcut) pc; validateSingleBranchRecursion(and.getLeft(), userPointcut,foundFormals,names,bindings); validateSingleBranchRecursion(and.getRight(),userPointcut,foundFormals,names,bindings); } else if (pc instanceof NameBindingPointcut) { List/*BindingTypePattern*/ btps = ((NameBindingPointcut)pc).getBindingTypePatterns(); for (Iterator iter = btps.iterator(); iter.hasNext();) { BindingTypePattern btp = (BindingTypePattern) iter.next(); int index = btp.getFormalIndex(); bindings[index] = pc; if (foundFormals[index]) { raiseAmbiguousBindingError(names[index],userPointcut); } else { foundFormals[index] = true; } } List/*BindingAnnotationTypePattern*/ baps = ((NameBindingPointcut)pc).getBindingAnnotationTypePatterns(); for (Iterator iter = baps.iterator(); iter.hasNext();) { BindingAnnotationTypePattern bap = (BindingAnnotationTypePattern) iter.next(); int index = bap.getFormalIndex(); bindings[index] = pc; if (foundFormals[index]) { raiseAmbiguousBindingError(names[index],userPointcut); } else { foundFormals[index] = true; } } } else if (pc instanceof ConcreteCflowPointcut) { ConcreteCflowPointcut cfp = (ConcreteCflowPointcut) pc; int[] slots = cfp.getUsedFormalSlots(); for (int i = 0; i < slots.length; i++) { bindings[slots[i]] = cfp; if (foundFormals[slots[i]]) { raiseAmbiguousBindingError(names[slots[i]],userPointcut); } else { foundFormals[slots[i]] = true; } } } } // By returning false from this method, we are allowing binding of the same // variable on either side of an or. // Be conservative :- have to consider overriding, varargs, autoboxing, // the effects of itds (on within for example), interfaces, the fact that // join points can have multiple signatures and so on. private boolean couldEverMatchSameJoinPoints(Pointcut left, Pointcut right) { if ((left instanceof OrPointcut) || (right instanceof OrPointcut)) return true; // look for withins WithinPointcut leftWithin = (WithinPointcut) findFirstPointcutIn(left,WithinPointcut.class); WithinPointcut rightWithin = (WithinPointcut) findFirstPointcutIn(right,WithinPointcut.class); if ((leftWithin != null) && (rightWithin != null)) { if (!leftWithin.couldEverMatchSameJoinPointsAs(rightWithin)) return false; } // look for kinded KindedPointcut leftKind = (KindedPointcut) findFirstPointcutIn(left,KindedPointcut.class); KindedPointcut rightKind = (KindedPointcut) findFirstPointcutIn(right,KindedPointcut.class); if ((leftKind != null) && (rightKind != null)) { if (!leftKind.couldEverMatchSameJoinPointsAs(rightKind)) return false; } return true; } private Pointcut findFirstPointcutIn(Pointcut toSearch, Class toLookFor) { if (toSearch instanceof NotPointcut) return null; if (toLookFor.isInstance(toSearch)) return toSearch; if (toSearch instanceof AndPointcut) { AndPointcut apc = (AndPointcut) toSearch; Pointcut left = findFirstPointcutIn(apc.getLeft(),toLookFor); if (left != null) return left; return findFirstPointcutIn(apc.getRight(),toLookFor); } return null; } /** * @param userPointcut */ private void raiseNegationBindingError(Pointcut userPointcut) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.NEGATION_DOESNT_ALLOW_BINDING), userPointcut.getSourceContext().makeSourceLocation(userPointcut),null); } /** * @param name * @param userPointcut */ private void raiseAmbiguousBindingError(String name, Pointcut userPointcut) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.AMBIGUOUS_BINDING, name), userPointcut.getSourceContext().makeSourceLocation(userPointcut),null); } /** * @param userPointcut */ private void raiseAmbiguityInDisjunctionError(Pointcut userPointcut, List names) { StringBuffer formalNames = new StringBuffer(names.get(0).toString()); for (int i = 1; i < names.size(); i++) { formalNames.append(", "); formalNames.append(names.get(i)); } world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.AMBIGUOUS_BINDING_IN_OR,formalNames), userPointcut.getSourceContext().makeSourceLocation(userPointcut),null); } /** * @param name * @param userPointcut */ private void raiseUnboundFormalError(String name, Pointcut userPointcut) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.UNBOUND_FORMAL, name), userPointcut.getSourceContext().makeSourceLocation(userPointcut),null); } // public void dumpUnwoven(File file) throws IOException { // BufferedOutputStream os = FileUtil.makeOutputStream(file); // this.zipOutputStream = new ZipOutputStream(os); // dumpUnwoven(); // /* BUG 40943*/ // dumpResourcesToOutJar(); // zipOutputStream.close(); //this flushes and closes the acutal file // } // // // public void dumpUnwoven() throws IOException { // Collection filesToDump = new HashSet(sourceJavaClasses.values()); // for (Iterator i = filesToDump.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // dumpUnchanged(classFile); // } // } // public void dumpResourcesToOutPath() throws IOException { //// System.err.println("? dumpResourcesToOutPath() resources=" + resources.keySet()); // Iterator i = resources.keySet().iterator(); // while (i.hasNext()) { // UnwovenClassFile res = (UnwovenClassFile)resources.get(i.next()); // dumpUnchanged(res); // } // //resources = new HashMap(); // } // /* BUG #40943 */ // public void dumpResourcesToOutJar() throws IOException { //// System.err.println("? dumpResourcesToOutJar() resources=" + resources.keySet()); // Iterator i = resources.keySet().iterator(); // while (i.hasNext()) { // String name = (String)i.next(); // UnwovenClassFile res = (UnwovenClassFile)resources.get(name); // writeZipEntry(name,res.getBytes()); // } // resources = new HashMap(); // } // // // halfway house for when the jar is managed outside of the weaver, but the resources // // to be copied are known in the weaver. // public void dumpResourcesToOutJar(ZipOutputStream zos) throws IOException { // this.zipOutputStream = zos; // dumpResourcesToOutJar(); // } public void addManifest (Manifest newManifest) { // System.out.println("? addManifest() newManifest=" + newManifest); if (manifest == null) { manifest = newManifest; } } public static final String MANIFEST_NAME = "META-INF/MANIFEST.MF"; private static final String WEAVER_MANIFEST_VERSION = "1.0"; private static final Attributes.Name CREATED_BY = new Name("Created-By"); private static final String WEAVER_CREATED_BY = "AspectJ Compiler"; public Manifest getManifest (boolean shouldCreate) { if (manifest == null && shouldCreate) { manifest = new Manifest(); Attributes attributes = manifest.getMainAttributes(); attributes.put(Name.MANIFEST_VERSION,WEAVER_MANIFEST_VERSION); attributes.put(CREATED_BY,WEAVER_CREATED_BY); } return manifest; } // ---- weaving // Used by some test cases only... public Collection weave(File file) throws IOException { OutputStream os = FileUtil.makeOutputStream(file); this.zipOutputStream = new ZipOutputStream(os); prepareForWeave(); Collection c = weave( new IClassFileProvider() { public Iterator getClassFileIterator() { return addedClasses.iterator(); } public IWeaveRequestor getRequestor() { return new IWeaveRequestor() { public void acceptResult(UnwovenClassFile result) { try { writeZipEntry(result.filename, result.bytes); } catch(IOException ex) {} } public void processingReweavableState() {} public void addingTypeMungers() {} public void weavingAspects() {} public void weavingClasses() {} public void weaveCompleted() {} }; } }); // /* BUG 40943*/ // dumpResourcesToOutJar(); zipOutputStream.close(); //this flushes and closes the acutal file return c; } // public Collection weave() throws IOException { // prepareForWeave(); // Collection filesToWeave; // // if (needToReweaveWorld) { // filesToWeave = sourceJavaClasses.values(); // } else { // filesToWeave = addedClasses; // } // // Collection wovenClassNames = new ArrayList(); // world.showMessage(IMessage.INFO, "might need to weave " + filesToWeave + // "(world=" + needToReweaveWorld + ")", null, null); // // // //System.err.println("typeMungers: " + typeMungerList); // // prepareToProcessReweavableState(); // // clear all state from files we'll be reweaving // for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // String className = classFile.getClassName(); // BcelObjectType classType = getClassType(className); // processReweavableStateIfPresent(className, classType); // } // // // // //XXX this isn't quite the right place for this... // for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // String className = classFile.getClassName(); // addTypeMungers(className); // } // // // first weave into aspects // for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // String className = classFile.getClassName(); // BcelObjectType classType = BcelWorld.getBcelObjectType(world.resolve(className)); // if (classType.isAspect()) { // weave(classFile, classType); // wovenClassNames.add(className); // } // } // // // then weave into non-aspects // for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // String className = classFile.getClassName(); // BcelObjectType classType = BcelWorld.getBcelObjectType(world.resolve(className)); // if (! classType.isAspect()) { // weave(classFile, classType); // wovenClassNames.add(className); // } // } // // if (zipOutputStream != null && !needToReweaveWorld) { // Collection filesToDump = new HashSet(sourceJavaClasses.values()); // filesToDump.removeAll(filesToWeave); // for (Iterator i = filesToDump.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // dumpUnchanged(classFile); // } // } // // addedClasses = new ArrayList(); // deletedTypenames = new ArrayList(); // // return wovenClassNames; // } // variation of "weave" that sources class files from an external source. public Collection weave(IClassFileProvider input) throws IOException { Collection wovenClassNames = new ArrayList(); IWeaveRequestor requestor = input.getRequestor(); requestor.processingReweavableState(); prepareToProcessReweavableState(); // clear all state from files we'll be reweaving for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) { UnwovenClassFile classFile = (UnwovenClassFile)i.next(); String className = classFile.getClassName(); BcelObjectType classType = getClassType(className); processReweavableStateIfPresent(className, classType); } requestor.addingTypeMungers(); // We process type mungers in two groups, first mungers that change the type // hierarchy, then 'normal' ITD type mungers. // Process the types in a predictable order (rather than the order encountered). // For class A, the order is superclasses of A then superinterfaces of A // (and this mechanism is applied recursively) List typesToProcess = new ArrayList(); for (Iterator iter = input.getClassFileIterator(); iter.hasNext();) { UnwovenClassFile clf = (UnwovenClassFile) iter.next(); typesToProcess.add(clf.getClassName()); } while (typesToProcess.size()>0) { weaveParentsFor(typesToProcess,(String)typesToProcess.get(0)); } for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) { UnwovenClassFile classFile = (UnwovenClassFile)i.next(); String className = classFile.getClassName(); addNormalTypeMungers(className); } requestor.weavingAspects(); // first weave into aspects for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) { UnwovenClassFile classFile = (UnwovenClassFile)i.next(); String className = classFile.getClassName(); BcelObjectType classType = BcelWorld.getBcelObjectType(world.resolve(className)); if (classType.isAspect()) { weaveAndNotify(classFile, classType,requestor); wovenClassNames.add(className); } } requestor.weavingClasses(); // then weave into non-aspects for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) { UnwovenClassFile classFile = (UnwovenClassFile)i.next(); String className = classFile.getClassName(); BcelObjectType classType = BcelWorld.getBcelObjectType(world.resolve(className)); if (! classType.isAspect()) { weaveAndNotify(classFile, classType, requestor); wovenClassNames.add(className); } } addedClasses = new ArrayList(); deletedTypenames = new ArrayList(); // FIXME asc Should be factored out into Xlint code and done automatically for all xlint messages, ideally. // if a piece of advice hasn't matched anywhere and we are in -1.5 mode, put out a warning if (world.isInJava5Mode() && world.getLint().adviceDidNotMatch.isEnabled()) { List l = world.getCrosscuttingMembersSet().getShadowMungers(); for (Iterator iter = l.iterator(); iter.hasNext();) { ShadowMunger element = (ShadowMunger) iter.next(); if (element instanceof BcelAdvice) { // This will stop us incorrectly reporting deow Checkers BcelAdvice ba = (BcelAdvice)element; if (!ba.hasMatchedSomething()) { // Because we implement some features of AJ itself by creating our own kind of mungers, you sometimes // find that ba.getSignature() is not a BcelMethod - for example it might be a cflow entry munger. if (ba.getSignature()!=null) { if (!(ba.getSignature() instanceof BcelMethod) || !Utility.isSuppressing((AnnotationX[])ba.getSignature().getAnnotations(),"adviceDidNotMatch")) { world.getLint().adviceDidNotMatch.signal(ba.getDeclaringAspect().toString(),element.getSourceLocation()); } } } } } } requestor.weaveCompleted(); return wovenClassNames; } /** * 'typeToWeave' is one from the 'typesForWeaving' list. This routine ensures we process * supertypes (classes/interfaces) of 'typeToWeave' that are in the * 'typesForWeaving' list before 'typeToWeave' itself. 'typesToWeave' is then removed from * the 'typesForWeaving' list. * * Note: Future gotcha in here ... when supplying partial hierarchies, this algorithm may * break down. If you have a hierarchy A>B>C and only give A and C to the weaver, it * may choose to weave them in either order - but you'll probably have other problems if * you are supplying partial hierarchies like that ! */ private void weaveParentsFor(List typesForWeaving,String typeToWeave) { // Look at the supertype first ResolvedType rtx = world.resolve(typeToWeave); ResolvedType superType = rtx.getSuperclass(); if (superType!=null && typesForWeaving.contains(superType.getName())) { weaveParentsFor(typesForWeaving,superType.getName()); } // Then look at the superinterface list ResolvedType[] interfaceTypes = rtx.getDeclaredInterfaces(); for (int i = 0; i < interfaceTypes.length; i++) { ResolvedType rtxI = interfaceTypes[i]; if (typesForWeaving.contains(rtxI.getName())) { weaveParentsFor(typesForWeaving,rtxI.getName()); } } weaveParentTypeMungers(rtx); // Now do this type typesForWeaving.remove(typeToWeave); // and remove it from the list of those to process } public void prepareToProcessReweavableState() { if (inReweavableMode) world.showMessage(IMessage.INFO, WeaverMessages.format(WeaverMessages.REWEAVABLE_MODE), null, null); } public void processReweavableStateIfPresent(String className, BcelObjectType classType) { // If the class is marked reweavable, check any aspects around when it was built are in this world WeaverStateInfo wsi = classType.getWeaverState(); if (wsi!=null && wsi.isReweavable()) { // Check all necessary types are around! world.showMessage(IMessage.INFO, WeaverMessages.format(WeaverMessages.PROCESSING_REWEAVABLE,className,classType.getSourceLocation().getSourceFile()), null,null); Set aspectsPreviouslyInWorld = wsi.getAspectsAffectingType(); if (aspectsPreviouslyInWorld!=null) { // keep track of them just to ensure unique missing aspect error reporting Set alreadyConfirmedReweavableState = new HashSet(); for (Iterator iter = aspectsPreviouslyInWorld.iterator(); iter.hasNext();) { String requiredTypeName = (String) iter.next(); if (!alreadyConfirmedReweavableState.contains(requiredTypeName)) { ResolvedType rtx = world.resolve(UnresolvedType.forName(requiredTypeName),true); boolean exists = rtx!=ResolvedType.MISSING; if (!exists) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.MISSING_REWEAVABLE_TYPE,requiredTypeName,className), classType.getSourceLocation(), null); } else { if (!world.getMessageHandler().isIgnoring(IMessage.INFO)) world.showMessage(IMessage.INFO, WeaverMessages.format(WeaverMessages.VERIFIED_REWEAVABLE_TYPE,requiredTypeName,rtx.getSourceLocation().getSourceFile()), null,null); alreadyConfirmedReweavableState.add(requiredTypeName); } } } } classType.setJavaClass(Utility.makeJavaClass(classType.getJavaClass().getFileName(), wsi.getUnwovenClassFileData())); } else { classType.resetState(); } } private void weaveAndNotify(UnwovenClassFile classFile, BcelObjectType classType, IWeaveRequestor requestor) throws IOException { LazyClassGen clazz = weaveWithoutDump(classFile,classType); classType.finishedWith(); //clazz is null if the classfile was unchanged by weaving... if (clazz != null) { UnwovenClassFile[] newClasses = getClassFilesFor(clazz); for (int i = 0; i < newClasses.length; i++) { requestor.acceptResult(newClasses[i]); } } else { requestor.acceptResult(classFile); } } // helper method public BcelObjectType getClassType(String forClass) { return BcelWorld.getBcelObjectType(world.resolve(forClass)); } public void addParentTypeMungers(String typeName) { weaveParentTypeMungers(world.resolve(typeName)); } public void addNormalTypeMungers(String typeName) { weaveNormalTypeMungers(world.resolve(typeName)); } public UnwovenClassFile[] getClassFilesFor(LazyClassGen clazz) { List childClasses = clazz.getChildClasses(world); UnwovenClassFile[] ret = new UnwovenClassFile[1 + childClasses.size()]; ret[0] = new UnwovenClassFile(clazz.getFileName(),clazz.getJavaClass(world).getBytes()); int index = 1; for (Iterator iter = childClasses.iterator(); iter.hasNext();) { UnwovenClassFile.ChildClass element = (UnwovenClassFile.ChildClass) iter.next(); UnwovenClassFile childClass = new UnwovenClassFile(clazz.getFileName() + "$" + element.name, element.bytes); ret[index++] = childClass; } return ret; } /** * Weaves new parents and annotations onto a type ("declare parents" and "declare @type") * * Algorithm: * 1. First pass, do parents then do annotations. During this pass record: * - any parent mungers that don't match but have a non-wild annotation type pattern * - any annotation mungers that don't match * 2. Multiple subsequent passes which go over the munger lists constructed in the first * pass, repeatedly applying them until nothing changes. * FIXME asc confirm that algorithm is optimal ?? */ public void weaveParentTypeMungers(ResolvedType onType) { if (onType.isRawType()) onType = onType.getGenericType(); onType.clearInterTypeMungers(); List decpToRepeat = new ArrayList(); boolean aParentChangeOccurred = false; boolean anAnnotationChangeOccurred = false; // First pass - apply all decp mungers for (Iterator i = declareParentsList.iterator(); i.hasNext(); ) { DeclareParents decp = (DeclareParents)i.next(); boolean typeChanged = applyDeclareParents(decp,onType); if (typeChanged) { aParentChangeOccurred = true; } else { // Perhaps it would have matched if a 'dec @type' had modified the type if (!decp.getChild().isStarAnnotation()) decpToRepeat.add(decp); } } // Still first pass - apply all dec @type mungers for (Iterator i = xcutSet.getDeclareAnnotationOnTypes().iterator();i.hasNext();) { DeclareAnnotation decA = (DeclareAnnotation)i.next(); boolean typeChanged = applyDeclareAtType(decA,onType,true); if (typeChanged) { anAnnotationChangeOccurred = true; } } while ((aParentChangeOccurred || anAnnotationChangeOccurred) && !decpToRepeat.isEmpty()) { anAnnotationChangeOccurred = aParentChangeOccurred = false; List decpToRepeatNextTime = new ArrayList(); for (Iterator iter = decpToRepeat.iterator(); iter.hasNext();) { DeclareParents decp = (DeclareParents) iter.next(); boolean typeChanged = applyDeclareParents(decp,onType); if (typeChanged) { aParentChangeOccurred = true; } else { decpToRepeatNextTime.add(decp); } } for (Iterator iter = xcutSet.getDeclareAnnotationOnTypes().iterator(); iter.hasNext();) { DeclareAnnotation decA = (DeclareAnnotation) iter.next(); boolean typeChanged = applyDeclareAtType(decA,onType,false); if (typeChanged) { anAnnotationChangeOccurred = true; } } decpToRepeat = decpToRepeatNextTime; } } /** * Apply a declare @type - return true if we change the type */ private boolean applyDeclareAtType(DeclareAnnotation decA, ResolvedType onType,boolean reportProblems) { boolean didSomething = false; if (decA.matches(onType)) { // FIXME asc important this should be guarded by the 'already has annotation' check below but isn't since the compiler is producing classfiles with deca affected things in... AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decA.getSourceLocation(),onType.getSourceLocation()); // FIXME asc same comment above applies here // TAG: WeavingMessage if (!getWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)){ getWorld().getMessageHandler().handleMessage( WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_ANNOTATES, new String[]{ onType.toString(), Utility.beautifyLocation(onType.getSourceLocation()), decA.getAnnotationString(), "type", decA.getAspect().toString(), Utility.beautifyLocation(decA.getSourceLocation()) })); } if (onType.hasAnnotation(decA.getAnnotationX().getSignature())) { // FIXME asc Could put out a lint here for an already annotated type - the problem is that it may have // picked up the annotation during 'source weaving' in which case the message is misleading. Leaving it // off for now... // if (reportProblems) { // world.getLint().elementAlreadyAnnotated.signal( // new String[]{onType.toString(),decA.getAnnotationTypeX().toString()}, // onType.getSourceLocation(),new ISourceLocation[]{decA.getSourceLocation()}); // } return false; } AnnotationX annoX = decA.getAnnotationX(); // check the annotation is suitable for the target boolean problemReported = verifyTargetIsOK(decA, onType, annoX,reportProblems); if (!problemReported) { didSomething = true; ResolvedTypeMunger newAnnotationTM = new AnnotationOnTypeMunger(annoX); newAnnotationTM.setSourceLocation(decA.getSourceLocation()); onType.addInterTypeMunger(new BcelTypeMunger(newAnnotationTM,decA.getAspect().resolve(world))); decA.copyAnnotationTo(onType); } } return didSomething; } /** * Checks for an @target() on the annotation and if found ensures it allows the annotation * to be attached to the target type that matched. */ private boolean verifyTargetIsOK(DeclareAnnotation decA, ResolvedType onType, AnnotationX annoX,boolean outputProblems) { boolean problemReported = false; if (annoX.specifiesTarget()) { if ( (onType.isAnnotation() && !annoX.allowedOnAnnotationType()) || (!annoX.allowedOnRegularType())) { if (outputProblems) { if (decA.isExactPattern()) { world.getMessageHandler().handleMessage(MessageUtil.error( WeaverMessages.format(WeaverMessages.INCORRECT_TARGET_FOR_DECLARE_ANNOTATION, onType.getName(),annoX.stringify(),annoX.getValidTargets()),decA.getSourceLocation())); } else { if (world.getLint().invalidTargetForAnnotation.isEnabled()) { world.getLint().invalidTargetForAnnotation.signal( new String[]{onType.getName(),annoX.stringify(),annoX.getValidTargets()},decA.getSourceLocation(),new ISourceLocation[]{onType.getSourceLocation()}); } } } problemReported = true; } } return problemReported; } /** * Apply a single declare parents - return true if we change the type */ private boolean applyDeclareParents(DeclareParents p, ResolvedType onType) { boolean didSomething = false; List newParents = p.findMatchingNewParents(onType,true); if (!newParents.isEmpty()) { didSomething=true; BcelObjectType classType = BcelWorld.getBcelObjectType(onType); //System.err.println("need to do declare parents for: " + onType); for (Iterator j = newParents.iterator(); j.hasNext(); ) { ResolvedType newParent = (ResolvedType)j.next(); // We set it here so that the imminent matching for ITDs can succeed - we // still haven't done the necessary changes to the class file itself // (like transform super calls) - that is done in BcelTypeMunger.mungeNewParent() classType.addParent(newParent); ResolvedTypeMunger newParentMunger = new NewParentTypeMunger(newParent); newParentMunger.setSourceLocation(p.getSourceLocation()); onType.addInterTypeMunger(new BcelTypeMunger(newParentMunger, xcutSet.findAspectDeclaringParents(p))); } } return didSomething; } public void weaveNormalTypeMungers(ResolvedType onType) { if (onType.isRawType() || onType.isParameterizedType()) onType = onType.getGenericType(); for (Iterator i = typeMungerList.iterator(); i.hasNext(); ) { ConcreteTypeMunger m = (ConcreteTypeMunger)i.next(); if (m.matches(onType)) { onType.addInterTypeMunger(m); } } } // exposed for ClassLoader dynamic weaving public LazyClassGen weaveWithoutDump(UnwovenClassFile classFile, BcelObjectType classType) throws IOException { return weave(classFile, classType, false); } // non-private for testing LazyClassGen weave(UnwovenClassFile classFile, BcelObjectType classType) throws IOException { LazyClassGen ret = weave(classFile, classType, true); if (progressListener != null) { progressMade += progressPerClassFile; progressListener.setProgress(progressMade); progressListener.setText("woven: " + classFile.getFilename()); } return ret; } private LazyClassGen weave(UnwovenClassFile classFile, BcelObjectType classType, boolean dump) throws IOException { if (classType.isSynthetic()) { if (dump) dumpUnchanged(classFile); return null; } // JavaClass javaClass = classType.getJavaClass(); List shadowMungers = fastMatch(shadowMungerList, classType.getResolvedTypeX()); List typeMungers = classType.getResolvedTypeX().getInterTypeMungers(); classType.getResolvedTypeX().checkInterTypeMungers(); LazyClassGen clazz = null; if (shadowMungers.size() > 0 || typeMungers.size() > 0 || classType.isAspect() || world.getDeclareAnnotationOnMethods().size()>0 || world.getDeclareAnnotationOnFields().size()>0 ) { clazz = classType.getLazyClassGen(); //System.err.println("got lazy gen: " + clazz + ", " + clazz.getWeaverState()); try { boolean isChanged = BcelClassWeaver.weave(world, clazz, shadowMungers, typeMungers, lateTypeMungerList); if (isChanged) { if (dump) dump(classFile, clazz); return clazz; } } catch (RuntimeException re) { System.err.println("trouble in: "); clazz.print(System.err); re.printStackTrace(); throw re; } catch (Error re) { System.err.println("trouble in: "); clazz.print(System.err); throw re; } } // this is very odd return behavior trying to keep everyone happy if (dump) { dumpUnchanged(classFile); return clazz; } else { // ATAJ: the class was not weaved, but since it gets there early it may have new generated inner classes // attached to it to support LTW perX aspectOf support (see BcelPerClauseAspectAdder) // that aggressively defines the inner <aspect>$mayHaveAspect interface. if (clazz != null && !clazz.getChildClasses(world).isEmpty()) { return clazz; } return null; } } // ---- writing private void dumpUnchanged(UnwovenClassFile classFile) throws IOException { if (zipOutputStream != null) { writeZipEntry(getEntryName(classFile.getJavaClass().getClassName()), classFile.getBytes()); } else { classFile.writeUnchangedBytes(); } } private String getEntryName(String className) { //XXX what does bcel's getClassName do for inner names return className.replace('.', '/') + ".class"; } private void dump(UnwovenClassFile classFile, LazyClassGen clazz) throws IOException { if (zipOutputStream != null) { String mainClassName = classFile.getJavaClass().getClassName(); writeZipEntry(getEntryName(mainClassName), clazz.getJavaClass(world).getBytes()); if (!clazz.getChildClasses(world).isEmpty()) { for (Iterator i = clazz.getChildClasses(world).iterator(); i.hasNext();) { UnwovenClassFile.ChildClass c = (UnwovenClassFile.ChildClass) i.next(); writeZipEntry(getEntryName(mainClassName + "$" + c.name), c.bytes); } } } else { classFile.writeWovenBytes( clazz.getJavaClass(world).getBytes(), clazz.getChildClasses(world) ); } } private void writeZipEntry(String name, byte[] bytes) throws IOException { ZipEntry newEntry = new ZipEntry(name); //??? get compression scheme right zipOutputStream.putNextEntry(newEntry); zipOutputStream.write(bytes); zipOutputStream.closeEntry(); } private List fastMatch(List list, ResolvedType type) { if (list == null) return Collections.EMPTY_LIST; // here we do the coarsest grained fast match with no kind constraints // this will remove all obvious non-matches and see if we need to do any weaving FastMatchInfo info = new FastMatchInfo(type, null); List result = new ArrayList(); Iterator iter = list.iterator(); while (iter.hasNext()) { ShadowMunger munger = (ShadowMunger)iter.next(); FuzzyBoolean fb = munger.getPointcut().fastMatch(info); WeaverMetrics.recordFastMatchTypeResult(fb); // Could pass: munger.getPointcut().toString(),info if (fb.maybeTrue()) { result.add(munger); } } return result; } public void setProgressListener(IProgressListener listener, double previousProgress, double progressPerClassFile) { progressListener = listener; this.progressMade = previousProgress; this.progressPerClassFile = progressPerClassFile; } public void setReweavableMode(boolean mode,boolean compress) { inReweavableMode = mode; WeaverStateInfo.setReweavableModeDefaults(mode,compress); BcelClassWeaver.setReweavableMode(mode,compress); } public boolean isReweavable() { return inReweavableMode; } public World getWorld() { return world; } }
107,713
Bug 107713 ClassCastException popup
Whenever I change any file and save(auto-compile) I get this in a popup. ClassCastException thrown: org.aspectj.ajdt.internal.compiler.lookup.EclipseSourceType cannot be cast to org.aspectj.weaver.bcel.BcelObjectType This started happening when I wrote these aspects. Before this started happening the IDE showed this line as an error. b.support.firePropertyChange( property, ( oldval == null ) ? oldval : new String(oldval), new String(newval)); ---------------------------------------------------------------- /** * */ package com.blueprint.util.mixin.test; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.lang.reflect.Field; import com.blueprint.util.mixin.test.*; import org.aspectj.lang.Signature; public aspect PropertySupportAspect { PropertyChangeSupport PropertySupport.support = new PropertyChangeSupport(this); public interface PropertySupport{ public void addPropertyChangeListener( PropertyChangeListener listener ); public void addPropertyChangeListener( String propertyName, PropertyChangeListener listener ); public void removePropertyChangeListener( String propertyName, PropertyChangeListener listener ); public void removePropertyChangeListener( PropertyChangeListener listener ); public void hasListeners( String propertyName ); } public void PropertySupport.addPropertyChangeListener (PropertyChangeListener listener){ support.addPropertyChangeListener(listener); } public void PropertySupport.addPropertyChangeListener( String propertyName, PropertyChangeListener listener){ support.addPropertyChangeListener(propertyName, listener); } public void PropertySupport.removePropertyChangeListener( String propertyName, PropertyChangeListener listener) { support.removePropertyChangeListener(propertyName, listener); } public void PropertySupport.removePropertyChangeListener (PropertyChangeListener listener) { support.removePropertyChangeListener(listener); } public void PropertySupport.hasListeners(String propertyName) { support.hasListeners(propertyName); } pointcut callSetter( Bean b ) : call( public void com.blueprint.util.test.Bean.setName( String ) ) && target( b ); void around( Bean b ) : callSetter( b ) { String propertyName = getField( thisJoinPointStaticPart.getSignature() ). getName (); System.out.println( "The property is [" + propertyName + "]" ); String oldValue = b.getName(); proceed( b ); firePropertyChange( b, propertyName, oldValue, b.getName ()); } private Field getField( Signature signature ){ Field field = null; System.out.println( "Getting the field name of [" +signature.getName() + "]" ); try{ String methodName = signature.getName(); field = signature.getDeclaringType(). getDeclaredField( methodName. substring( 3, methodName.length() ). toLowerCase()); field.setAccessible(true); }catch( NoSuchFieldException nsfe ){ nsfe.printStackTrace(); } return field; } void firePropertyChange( Bean b, String property, String oldval, String newval) { System.out.println( "The property is [" + property + "]"); System.out.println( "The old value is [" + oldval + "]"); System.out.println( "The new value is [" + newval + "]"); b.support.firePropertyChange( property, ( oldval == null ) ? oldval : new String(oldval), new String(newval)); } } ---------------------------------------------------------------- import java.io.Serializable; public class Bean implements Serializable{ private String name; public String getName() { return name; } public void setName( String name ) { this.name = name; } } ---------------------------------------------------------------- public aspect BeanSupport { declare parents: Bean implements PropertySupportAspect.PropertySupport; } ----------------------------------------------------------------
resolved fixed
100d9e0
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-08-26T09:09:35Z
2005-08-23T09:40:00Z
weaver/src/org/aspectj/weaver/bcel/BcelWorld.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * Alexandre Vasseur perClause support for @AJ aspects * ******************************************************************/ package org.aspectj.weaver.bcel; import java.io.File; import java.io.IOException; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; import java.util.Iterator; import org.aspectj.apache.bcel.classfile.ClassParser; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.apache.bcel.classfile.Method; import org.aspectj.apache.bcel.generic.ConstantPoolGen; import org.aspectj.apache.bcel.generic.FieldInstruction; import org.aspectj.apache.bcel.generic.GETSTATIC; import org.aspectj.apache.bcel.generic.INVOKEINTERFACE; import org.aspectj.apache.bcel.generic.INVOKESPECIAL; import org.aspectj.apache.bcel.generic.INVOKESTATIC; import org.aspectj.apache.bcel.generic.InvokeInstruction; import org.aspectj.apache.bcel.generic.PUTSTATIC; import org.aspectj.apache.bcel.generic.Type; import org.aspectj.apache.bcel.util.ClassPath; import org.aspectj.apache.bcel.util.Repository; import org.aspectj.apache.bcel.util.ClassLoaderRepository; import org.aspectj.bridge.IMessageHandler; import org.aspectj.weaver.Advice; import org.aspectj.weaver.AdviceKind; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.ConcreteTypeMunger; import org.aspectj.weaver.ICrossReferenceHandler; import org.aspectj.weaver.Member; import org.aspectj.weaver.MemberImpl; import org.aspectj.weaver.ReferenceType; import org.aspectj.weaver.ReferenceTypeDelegate; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedMemberImpl; import org.aspectj.weaver.ResolvedTypeMunger; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.World; import org.aspectj.weaver.patterns.FormalBinding; import org.aspectj.weaver.patterns.Pointcut; import org.aspectj.weaver.patterns.SimpleScope; import org.aspectj.weaver.patterns.PerClause; public class BcelWorld extends World implements Repository { private ClassPathManager classPath; private Repository delegate; //private ClassPathManager aspectPath = null; // private List aspectPathEntries; // ---- constructors public BcelWorld() { this(""); } public BcelWorld(String cp) { this(makeDefaultClasspath(cp), IMessageHandler.THROW, null); } private static List makeDefaultClasspath(String cp) { List classPath = new ArrayList(); classPath.addAll(getPathEntries(cp)); classPath.addAll(getPathEntries(ClassPath.getClassPath())); //System.err.println("classpath: " + classPath); return classPath; } private static List getPathEntries(String s) { List ret = new ArrayList(); StringTokenizer tok = new StringTokenizer(s, File.pathSeparator); while(tok.hasMoreTokens()) ret.add(tok.nextToken()); return ret; } public BcelWorld(List classPath, IMessageHandler handler, ICrossReferenceHandler xrefHandler) { //this.aspectPath = new ClassPathManager(aspectPath, handler); this.classPath = new ClassPathManager(classPath, handler); setMessageHandler(handler); setCrossReferenceHandler(xrefHandler); // Tell BCEL to use us for resolving any classes delegate = this; // TODO Alex do we need to call org.aspectj.apache.bcel.Repository.setRepository(delegate); // if so, how can that be safe in J2EE ?? (static stuff in Bcel) } public BcelWorld(ClassPathManager cpm, IMessageHandler handler, ICrossReferenceHandler xrefHandler) { this.classPath = cpm; setMessageHandler(handler); setCrossReferenceHandler(xrefHandler); // Tell BCEL to use us for resolving any classes delegate = this; // TODO Alex do we need to call org.aspectj.apache.bcel.Repository.setRepository(delegate); // if so, how can that be safe in J2EE ?? (static stuff in Bcel) } /** * Build a World from a ClassLoader, for LTW support * * @param loader * @param handler * @param xrefHandler */ public BcelWorld(ClassLoader loader, IMessageHandler handler, ICrossReferenceHandler xrefHandler) { this.classPath = null; setMessageHandler(handler); setCrossReferenceHandler(xrefHandler); // Tell BCEL to use us for resolving any classes delegate = new ClassLoaderRepository(loader); // TODO Alex do we need to call org.aspectj.apache.bcel.Repository.setRepository(delegate); // if so, how can that be safe in J2EE ?? (static stuff in Bcel) } public void addPath (String name) { classPath.addPath(name, this.getMessageHandler()); } /** * Parse a string into advice. * * <blockquote><pre> * Kind ( Id , ... ) : Pointcut -> MethodSignature * </pre></blockquote> */ public Advice shadowMunger(String str, int extraFlag) { str = str.trim(); int start = 0; int i = str.indexOf('('); AdviceKind kind = AdviceKind.stringToKind(str.substring(start, i)); start = ++i; i = str.indexOf(')', i); String[] ids = parseIds(str.substring(start, i).trim()); //start = ++i; i = str.indexOf(':', i); start = ++i; i = str.indexOf("->", i); Pointcut pointcut = Pointcut.fromString(str.substring(start, i).trim()); Member m = MemberImpl.methodFromString(str.substring(i+2, str.length()).trim()); // now, we resolve UnresolvedType[] types = m.getParameterTypes(); FormalBinding[] bindings = new FormalBinding[ids.length]; for (int j = 0, len = ids.length; j < len; j++) { bindings[j] = new FormalBinding(types[j], ids[j], j, 0, 0, "fromString"); } Pointcut p = pointcut.resolve(new SimpleScope(this, bindings)); return new BcelAdvice(kind, p, m, extraFlag, 0, 0, null, null); } private String[] parseIds(String str) { if (str.length() == 0) return ZERO_STRINGS; List l = new ArrayList(); int start = 0; while (true) { int i = str.indexOf(',', start); if (i == -1) { l.add(str.substring(start).trim()); break; } l.add(str.substring(start, i).trim()); start = i+1; } return (String[]) l.toArray(new String[l.size()]); } // ---- various interactions with bcel public static Type makeBcelType(UnresolvedType type) { return Type.getType(type.getErasureSignature()); } static Type[] makeBcelTypes(UnresolvedType[] types) { Type[] ret = new Type[types.length]; for (int i = 0, len = types.length; i < len; i++) { ret[i] = makeBcelType(types[i]); } return ret; } public static UnresolvedType fromBcel(Type t) { return UnresolvedType.forSignature(t.getSignature()); } static UnresolvedType[] fromBcel(Type[] ts) { UnresolvedType[] ret = new UnresolvedType[ts.length]; for (int i = 0, len = ts.length; i < len; i++) { ret[i] = fromBcel(ts[i]); } return ret; } public ResolvedType resolve(Type t) { return resolve(fromBcel(t)); } protected ReferenceTypeDelegate resolveDelegate(ReferenceType ty) { String name = ty.getName(); JavaClass jc = null; //UnwovenClassFile classFile = (UnwovenClassFile)sourceJavaClasses.get(name); //if (classFile != null) jc = classFile.getJavaClass(); // if (jc == null) { // jc = lookupJavaClass(aspectPath, name); // } if (jc == null) { jc = lookupJavaClass(classPath, name); } if (jc == null) { return null; } else { return makeBcelObjectType(ty, jc, false); } } protected BcelObjectType makeBcelObjectType(ReferenceType resolvedTypeX, JavaClass jc, boolean exposedToWeaver) { BcelObjectType ret = new BcelObjectType(resolvedTypeX, jc, exposedToWeaver); return ret; } private JavaClass lookupJavaClass(ClassPathManager classPath, String name) { if (classPath == null) { try { return delegate.loadClass(name); } catch (ClassNotFoundException e) { return null; } } try { ClassPathManager.ClassFile file = classPath.find(UnresolvedType.forName(name)); if (file == null) return null; ClassParser parser = new ClassParser(file.getInputStream(), file.getPath()); JavaClass jc = parser.parse(); file.close(); return jc; } catch (IOException ioe) { return null; } } public BcelObjectType addSourceObjectType(JavaClass jc) { BcelObjectType ret = null; String signature = UnresolvedType.forName(jc.getClassName()).getSignature(); ReferenceType nameTypeX = (ReferenceType)typeMap.get(signature); if (nameTypeX == null) { if (jc.isGeneric()) { nameTypeX = ReferenceType.fromTypeX(UnresolvedType.forRawTypeName(jc.getClassName()),this); ret = makeBcelObjectType(nameTypeX, jc, true); ReferenceType genericRefType = new ReferenceType( UnresolvedType.forGenericTypeSignature(signature,ret.getDeclaredGenericSignature()),this); nameTypeX.setDelegate(ret); genericRefType.setDelegate(ret); nameTypeX.setGenericType(genericRefType); typeMap.put(signature, nameTypeX); } else { nameTypeX = new ReferenceType(signature, this); ret = makeBcelObjectType(nameTypeX, jc, true); typeMap.put(signature, nameTypeX); } } else { ret = makeBcelObjectType(nameTypeX, jc, true); } return ret; } void deleteSourceObjectType(UnresolvedType ty) { typeMap.remove(ty.getSignature()); } public static Member makeFieldJoinPointSignature(LazyClassGen cg, FieldInstruction fi) { ConstantPoolGen cpg = cg.getConstantPoolGen(); return MemberImpl.field( fi.getClassName(cpg), (fi instanceof GETSTATIC || fi instanceof PUTSTATIC) ? Modifier.STATIC: 0, fi.getName(cpg), fi.getSignature(cpg)); } // public static Member makeFieldSetSignature(LazyClassGen cg, FieldInstruction fi) { // ConstantPoolGen cpg = cg.getConstantPoolGen(); // return // MemberImpl.field( // fi.getClassName(cpg), // (fi instanceof GETSTATIC || fi instanceof PUTSTATIC) // ? Modifier.STATIC // : 0, // fi.getName(cpg), // "(" + fi.getSignature(cpg) + ")" +fi.getSignature(cpg)); // } public Member makeJoinPointSignature(LazyMethodGen mg) { return makeJoinPointSignatureFromMethod(mg, null); } public Member makeJoinPointSignatureFromMethod(LazyMethodGen mg, MemberImpl.Kind kind) { Member ret = mg.getMemberView(); if (ret == null) { int mods = mg.getAccessFlags(); if (mg.getEnclosingClass().isInterface()) { mods |= Modifier.INTERFACE; } if (kind == null) { if (mg.getName().equals("<init>")) { kind = Member.CONSTRUCTOR; } else if (mg.getName().equals("<clinit>")) { kind = Member.STATIC_INITIALIZATION; } else { kind = Member.METHOD; } } return new ResolvedMemberImpl(kind, UnresolvedType.forName(mg.getClassName()), mods, fromBcel(mg.getReturnType()), mg.getName(), fromBcel(mg.getArgumentTypes()) ); } else { return ret; } } public Member makeJoinPointSignatureForMethodInvocation(LazyClassGen cg, InvokeInstruction ii) { ConstantPoolGen cpg = cg.getConstantPoolGen(); String declaring = ii.getClassName(cpg); String name = ii.getName(cpg); String signature = ii.getSignature(cpg); int modifier = (ii instanceof INVOKEINTERFACE) ? Modifier.INTERFACE : (ii instanceof INVOKESTATIC) ? Modifier.STATIC : (ii instanceof INVOKESPECIAL && ! name.equals("<init>")) ? Modifier.PRIVATE : 0; // in Java 1.4 and after, static method call of super class within subclass method appears // as declared by the subclass in the bytecode - but they are not // see #104212 if (ii instanceof INVOKESTATIC) { ResolvedType appearsDeclaredBy = resolve(declaring); // look for the method there for (Iterator iterator = appearsDeclaredBy.getMethods(); iterator.hasNext();) { ResolvedMember method = (ResolvedMember) iterator.next(); if (method.isStatic()) { if (name.equals(method.getName()) && signature.equals(method.getSignature())) { // we found it declaring = method.getDeclaringType().getName(); break; } } } } //FIXME if not found we ll end up again with the bug.. can this happen? return MemberImpl.method(UnresolvedType.forName(declaring), modifier, name, signature); } public static Member makeMungerMethodSignature(JavaClass javaClass, Method method) { int mods = 0; if (method.isStatic()) mods = Modifier.STATIC; else if (javaClass.isInterface()) mods = Modifier.INTERFACE; else if (method.isPrivate()) mods = Modifier.PRIVATE; return MemberImpl.method( UnresolvedType.forName(javaClass.getClassName()), mods, method.getName(), method.getSignature()); } private static final String[] ZERO_STRINGS = new String[0]; public String toString() { StringBuffer buf = new StringBuffer(); buf.append("BcelWorld("); //buf.append(shadowMungerMap); buf.append(")"); return buf.toString(); } public Advice createAdviceMunger( AjAttribute.AdviceAttribute attribute, Pointcut pointcut, Member signature) { //System.err.println("concrete advice: " + signature + " context " + sourceContext); return new BcelAdvice(attribute, pointcut, signature, null); } public ConcreteTypeMunger concreteTypeMunger( ResolvedTypeMunger munger, ResolvedType aspectType) { return new BcelTypeMunger(munger, aspectType); } public ConcreteTypeMunger makeCflowStackFieldAdder(ResolvedMember cflowField) { return new BcelCflowStackFieldAdder(cflowField); } public ConcreteTypeMunger makeCflowCounterFieldAdder(ResolvedMember cflowField) { return new BcelCflowCounterFieldAdder(cflowField); } /** * Register a munger for perclause @AJ aspect so that we add aspectOf(..) to them as needed * * @param aspect * @param kind * @return */ public ConcreteTypeMunger makePerClauseAspect(ResolvedType aspect, PerClause.Kind kind) { return new BcelPerClauseAspectAdder(aspect, kind); } public static BcelObjectType getBcelObjectType(ResolvedType concreteAspect) { //XXX need error checking return (BcelObjectType) ((ReferenceType)concreteAspect).getDelegate(); } public void tidyUp() { // At end of compile, close any open files so deletion of those archives is possible classPath.closeArchives(); } /// The repository interface methods public JavaClass findClass(String className) { return lookupJavaClass(classPath,className); } public JavaClass loadClass(String className) throws ClassNotFoundException { return lookupJavaClass(classPath,className); } public void storeClass(JavaClass clazz) { throw new RuntimeException("Not implemented"); } public void removeClass(JavaClass clazz) { throw new RuntimeException("Not implemented"); } public JavaClass loadClass(Class clazz) throws ClassNotFoundException { throw new RuntimeException("Not implemented"); } public void clear() { throw new RuntimeException("Not implemented"); } }
108,050
Bug 108050 Execution not matching override in doubly derived method
The following sample code fails because the compiler isn't matching the execution of doPost in MockServlet4. The declare warning for "servlet request" doesn't match in that case, nor does advice on the join point actually run at runtime (though this simplified code only shows the problem with declare warning). This was working until fairly recently (certainly in M2, even in AJDT from August 11). public abstract class MockServlet extends HttpServlet { protected void doPost() { } private static aspect FindMatches { declare warning: execution(* HttpServlet.do*(..)): "servlet request"; declare warning: execution(* HttpServlet+.do*(..)): "servlet request2"; } } class HttpServlet { protected void doPost() { } } public class MockDelayingServlet extends MockServlet { private static final long serialVersionUID = 1; } public class MockServlet4 extends MockDelayingServlet { protected void doPost() { } } compiler output (should have 6 warnings, including two for MockServlet4): C:\devel\workspace\test\src\MockServlet.java:16 [warning] servlet request protected void doPost() { ^^^^^^^^^^^^^^^^^^^^^^^^^ method-execution(void MockServlet.doPost()) see also: C:\devel\workspace\test\src\MockServlet.java:20::0 C:\devel\workspace\test\src\MockServlet.java:16 [warning] servlet request2 protected void doPost() { ^^^^^^^^^^^^^^^^^^^^^^^^^ method-execution(void MockServlet.doPost()) see also: C:\devel\workspace\test\src\MockServlet.java:21::0 C:\devel\workspace\test\src\MockServlet.java:26 [warning] servlet request protected void doPost() { ^^^^^^^^^^^^^^^^^^^^^^^^^ method-execution(void HttpServlet.doPost()) see also: C:\devel\workspace\test\src\MockServlet.java:20::0 C:\devel\workspace\test\src\MockServlet.java:26 [warning] servlet request2 protected void doPost() { ^^^^^^^^^^^^^^^^^^^^^^^^^ method-execution(void HttpServlet.doPost()) see also: C:\devel\workspace\test\src\MockServlet.java:21::0 C:\devel\workspace\test\src\MockServlet4.java:9 [warning] servlet request2 protected void doPost() ^^^^^^^^^^^^^^^^^^^^^^^ method-execution(void MockServlet4.doPost()) see also: C:\devel\workspace\test\src\MockServlet.java:21::0 5 warnings
resolved fixed
27e68f3
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-08-26T11:43:32Z
2005-08-25T20:00:00Z
tests/src/org/aspectj/systemtest/ajc150/Ajc150Tests.java
/******************************************************************************* * Copyright (c) 2004 IBM * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Andy Clement - initial API and implementation *******************************************************************************/ package org.aspectj.systemtest.ajc150; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import junit.framework.Test; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.apache.bcel.classfile.Method; import org.aspectj.apache.bcel.util.ClassPath; import org.aspectj.apache.bcel.util.SyntheticRepository; import org.aspectj.asm.AsmManager; import org.aspectj.testing.XMLBasedAjcTestCase; import org.aspectj.util.LangUtil; /** * These are tests that will run on Java 1.4 and use the old harness format for test specification. */ public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase { public static Test suite() { return XMLBasedAjcTestCase.loadSuite(Ajc150Tests.class); } protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml"); } public void test_typeProcessingOrderWhenDeclareParents() { runTest("Order of types passed to compiler determines weaving behavior"); } public void test_aroundMethod() { runTest("method called around in class"); } public void test_aroundMethodAspect() { runTest("method called around in aspect"); } public void test_ambiguousBindingsDetection() { runTest("Various kinds of ambiguous bindings"); } public void test_ambiguousArgsDetection() { runTest("ambiguous args"); } public void testIncorrectExceptionTableWhenBreakInMethod_pr78021() { runTest("Injecting exception into while loop with break statement causes catch block to be ignored"); } public void testIncorrectExceptionTableWhenReturnInMethod_pr79554() { runTest("Return in try-block disables catch-block if final-block is present"); } public void testMissingDebugInfoForGeneratedMethods_pr82570() throws ClassNotFoundException { runTest("Weaved code does not include debug lines"); boolean f = false; JavaClass jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1"); Method[] meths = jc.getMethods(); for (int i = 0; i < meths.length; i++) { Method method = meths[i]; if (f) System.err.println("Line number table for "+method.getName()+method.getSignature()+" = "+method.getLineNumberTable()); assertTrue("Didn't find a line number table for method "+method.getName()+method.getSignature(), method.getLineNumberTable()!=null); } // This test would determine the info isn't there if you pass -g:none ... // cR = ajc(baseDir,new String[]{"PR82570_1.java","-g:none"}); // assertTrue("Expected no compile problem:"+cR,!cR.hasErrorMessages()); // System.err.println(cR.getStandardError()); // jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1"); // meths = jc.getMethods(); // for (int i = 0; i < meths.length; i++) { // Method method = meths[i]; // assertTrue("Found a line number table for method "+method.getName(), // method.getLineNumberTable()==null); // } } public void testCanOverrideProtectedMethodsViaITDandDecp_pr83303() { runTest("compiler error when mixing inheritance, overriding and polymorphism"); } public void testPerTypeWithinMissesNamedInnerTypes() { runTest("pertypewithin() handing of inner classes (1)"); } public void testPerTypeWithinMissesAnonymousInnerTypes() { runTest("pertypewithin() handing of inner classes (2)"); } public void testPerTypeWithinIncorrectlyMatchingInterfaces() { runTest("pertypewithin({interface}) illegal field modifier"); } public void test051_arrayCloningInJava5() { runTest("AJC possible bug with static nested classes"); } public void testBadASMforEnums() throws IOException { runTest("bad asm for enums"); if (LangUtil.is15VMOrGreater()) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintWriter pw = new PrintWriter(baos); AsmManager.dumptree(pw,AsmManager.getDefault().getHierarchy().getRoot(),0); pw.flush(); String tree = baos.toString(); assertTrue("Expected 'Red [enumvalue]' somewhere in here:"+tree,tree.indexOf("Red [enumvalue]")!=-1); } } public void npeOnTypeNotFound() { runTest("structure model npe on type not found"); } public void testNoRuntimeExceptionSoftening() { runTest("declare soft of runtime exception"); } public void testRuntimeNoSoftenWithHandler() { runTest("declare soft w. catch block"); } public void testSyntaxError() { runTest("invalid cons syntax"); } public void testVarargsInConsBug() { runTest("varargs in constructor sig"); } public void testAspectpathdirs() { runTest("dirs on aspectpath"); } public void testIntroSample() { runTest("introduction sample"); } public void testPTWInterface() { runTest("pertypewithin({interface}) illegal field modifier"); } public void testEnumCalledEnumEtc() { runTest("enum called Enum, annotation called Annotation, etc"); } public void testInternalCompilerError_pr86832() { runTest("Internal compiler error"); } public void testCloneMethod_pr83311() { runTest("overriding/polymorphism error on interface method introduction"); } /** * IfPointcut.findResidueInternal() was modified to make this test complete in a short amount * of time - if you see it hanging, someone has messed with the optimization. */ public void testIfEvaluationExplosion_pr94086() { runTest("Exploding compile time with if() statements in pointcut"); } public void testReflectNPE_pr94167() {runTest("NPE in reflect implementation");} public void testStaticImports_pr84260() {runTest("static import failures");} public void testGenerics_pr99089() {runTest("ArrayIndexOutOfBoundsException - Generics in privileged aspects");} public void testGenerics_pr95993() {runTest("NPE at ClassScope.java:660 when compiling generic class");} public void testItdGenerics_pr99228() {runTest("ITD of a field into a generic class");} public void testItdGenerics_pr98320() {runTest("intertype with nested generic type");} public void testItdGenerics_pr100227() {runTest("inner class with generic enclosing class");} public void testItdGenerics_pr100260() {runTest("methods inherited from a generic parent");} public void testSyntaxErrorNPE_pr103266() {runTest("NPE on syntax error");} public void testIllegalStateExceptionOnNestedParameterizedType_pr106634() { runTest("IllegalStateException unpacking signature of nested parameterized type"); } public void testParseErrorOnAnnotationStarPlusPattern() { runTest("(@Foo *)+ type pattern parse error"); } public void test_pr106130_tooManyLocals() { runTest("test weaving with > 256 locals"); } public void testMissingNamePattern_pr106461() { runTest("missing name pattern"); } public void testMissingNamePattern_pr107059() { runTest("parser crashes on call(void (@a *)(..)"); } public void testIntermediateAnnotationMatching() { runTest("intermediate annotation matching"); } public void testBadRuntimeTestGeneration() { runTest("target(@Foo *)"); } public void testErrorMessageOnITDWithTypePatterns() { runTest("clear error message on itd with type pattern"); } public void testAjKeywordsAsIdentifiers() { runTest("before and after are valid identifiers in classes"); } public void testAjKeywordsAsIdentifiers2() { runTest("before and after are valid identifiers in classes, part 2"); } public void testNoBeforeReturningAdvice() { runTest("before returning advice not allowed!"); } public void testDetectVoidFieldType() { runTest("void field type in pointcut expression"); } public void testPointcutOverriding() { runTest("overriding final pointcut from super-aspect"); } public void testAtSuppressWarnings() { runTest("@SuppressWarnings should suppress"); } public void testDEOWWithBindingPointcut() { runTest("declare warning : foo(str) : ...;"); } public void testAroundAdviceAndInterfaceInitializer() { runTest("around advice on interface initializer"); } public void testGoodErrorMessageOnUnmatchedMemberSyntax() { runTest("good error message for unmatched member syntax"); } public void testITDWithNoExceptionAndIntermediary() { runTest("itd override with no exception clause"); } public void testAnonymousInnerClasses() { runTest("anonymous inner classes"); } public void testMultipleAnonymousInnerClasses() { runTest("multiple anonymous inner classes"); } public void testPrivilegedMethodAccessorsGetRightExceptions_pr82989() { runTest("Compiler error due to a wrong exception check in try blocks"); } public void testAnonymousInnerClassWithMethodReturningTypeParameter_pr107898() { runTest("anonymous inner class with method returning type parameter"); } public void testMatchingOfObjectArray() { runTest("matching against Object[]"); } public void testMultipleAnonymousInnerClasses_pr108104() { runTest("multiple anonymous inner classes 2"); } // helper methods..... public SyntheticRepository createRepos(File cpentry) { ClassPath cp = new ClassPath(cpentry+File.pathSeparator+System.getProperty("java.class.path")); return SyntheticRepository.getInstance(cp); } protected JavaClass getClassFrom(File where,String clazzname) throws ClassNotFoundException { SyntheticRepository repos = createRepos(where); return repos.loadClass(clazzname); } }
108,050
Bug 108050 Execution not matching override in doubly derived method
The following sample code fails because the compiler isn't matching the execution of doPost in MockServlet4. The declare warning for "servlet request" doesn't match in that case, nor does advice on the join point actually run at runtime (though this simplified code only shows the problem with declare warning). This was working until fairly recently (certainly in M2, even in AJDT from August 11). public abstract class MockServlet extends HttpServlet { protected void doPost() { } private static aspect FindMatches { declare warning: execution(* HttpServlet.do*(..)): "servlet request"; declare warning: execution(* HttpServlet+.do*(..)): "servlet request2"; } } class HttpServlet { protected void doPost() { } } public class MockDelayingServlet extends MockServlet { private static final long serialVersionUID = 1; } public class MockServlet4 extends MockDelayingServlet { protected void doPost() { } } compiler output (should have 6 warnings, including two for MockServlet4): C:\devel\workspace\test\src\MockServlet.java:16 [warning] servlet request protected void doPost() { ^^^^^^^^^^^^^^^^^^^^^^^^^ method-execution(void MockServlet.doPost()) see also: C:\devel\workspace\test\src\MockServlet.java:20::0 C:\devel\workspace\test\src\MockServlet.java:16 [warning] servlet request2 protected void doPost() { ^^^^^^^^^^^^^^^^^^^^^^^^^ method-execution(void MockServlet.doPost()) see also: C:\devel\workspace\test\src\MockServlet.java:21::0 C:\devel\workspace\test\src\MockServlet.java:26 [warning] servlet request protected void doPost() { ^^^^^^^^^^^^^^^^^^^^^^^^^ method-execution(void HttpServlet.doPost()) see also: C:\devel\workspace\test\src\MockServlet.java:20::0 C:\devel\workspace\test\src\MockServlet.java:26 [warning] servlet request2 protected void doPost() { ^^^^^^^^^^^^^^^^^^^^^^^^^ method-execution(void HttpServlet.doPost()) see also: C:\devel\workspace\test\src\MockServlet.java:21::0 C:\devel\workspace\test\src\MockServlet4.java:9 [warning] servlet request2 protected void doPost() ^^^^^^^^^^^^^^^^^^^^^^^ method-execution(void MockServlet4.doPost()) see also: C:\devel\workspace\test\src\MockServlet.java:21::0 5 warnings
resolved fixed
27e68f3
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-08-26T11:43:32Z
2005-08-25T20:00:00Z
weaver/src/org/aspectj/weaver/JoinPointSignature.java
/* ******************************************************************* * Copyright (c) 2005 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * Adrian Colyer Initial implementation * ******************************************************************/ package org.aspectj.weaver; import java.io.DataOutputStream; import java.io.IOException; import java.util.Collection; import org.aspectj.bridge.ISourceLocation; import org.aspectj.weaver.AjAttribute.EffectiveSignatureAttribute; /** * @author colyer * Instances of this class are created by ResolvedMember.getSignatures() when collating * all of the signatures for a member. We need to create entries in the set for the "gaps" * in the hierarchy. For example: * * class A { * void foo(); * } * * class B extends A {} * * Join Point : call(* B.foo()) * * has signatures: * * B.foo() AND A.foo() * B.foo() will be created as a ResolvedMemberWithSubstituteDeclaringType * * Oh for a JDK 1.4 dynamic proxy.... we have to run on 1.3 :( */ public class JoinPointSignature implements ResolvedMember { private ResolvedMember realMember; private ResolvedType substituteDeclaringType; public JoinPointSignature(ResolvedMember backing, ResolvedType aType) { this.realMember = backing; this.substituteDeclaringType = aType; } public UnresolvedType getDeclaringType() { return substituteDeclaringType; } public int getModifiers(World world) { return realMember.getModifiers(world); } public int getModifiers() { return realMember.getModifiers(); } public UnresolvedType[] getExceptions(World world) { return realMember.getExceptions(world); } public UnresolvedType[] getExceptions() { return realMember.getExceptions(); } public ShadowMunger getAssociatedShadowMunger() { return realMember.getAssociatedShadowMunger(); } public boolean isAjSynthetic() { return realMember.isAjSynthetic(); } public boolean hasAnnotations() { return realMember.hasAnnotations(); } public boolean hasAnnotation(UnresolvedType ofType) { return realMember.hasAnnotation(ofType); } public ResolvedType[] getAnnotationTypes() { return realMember.getAnnotationTypes(); } public void setAnnotationTypes(UnresolvedType[] annotationtypes) { realMember.setAnnotationTypes(annotationtypes); } public void addAnnotation(AnnotationX annotation) { realMember.addAnnotation(annotation); } public boolean isBridgeMethod() { return realMember.isBridgeMethod(); } public boolean isVarargsMethod() { return realMember.isVarargsMethod(); } public boolean isSynthetic() { return realMember.isSynthetic(); } public void write(DataOutputStream s) throws IOException { realMember.write(s); } public ISourceContext getSourceContext(World world) { return realMember.getSourceContext(world); } public String[] getParameterNames() { return realMember.getParameterNames(); } public String[] getParameterNames(World world) { return realMember.getParameterNames(world); } public EffectiveSignatureAttribute getEffectiveSignature() { return realMember.getEffectiveSignature(); } public ISourceLocation getSourceLocation() { return realMember.getSourceLocation(); } public int getEnd() { return realMember.getEnd(); } public ISourceContext getSourceContext() { return realMember.getSourceContext(); } public int getStart() { return realMember.getStart(); } public void setPosition(int sourceStart, int sourceEnd) { realMember.setPosition(sourceStart,sourceEnd); } public void setSourceContext(ISourceContext sourceContext) { realMember.setSourceContext(sourceContext); } public boolean isAbstract() { return realMember.isAbstract(); } public boolean isPublic() { return realMember.isPublic(); } public boolean isProtected() { return realMember.isProtected(); } public boolean isNative() { return realMember.isNative(); } public boolean isDefault() { return realMember.isDefault(); } public boolean isVisible(ResolvedType fromType) { return realMember.isVisible(fromType); } public void setCheckedExceptions(UnresolvedType[] checkedExceptions) { realMember.setCheckedExceptions(checkedExceptions); } public void setAnnotatedElsewhere(boolean b) { realMember.setAnnotatedElsewhere(b); } public boolean isAnnotatedElsewhere() { return realMember.isAnnotatedElsewhere(); } public UnresolvedType getGenericReturnType() { return realMember.getGenericReturnType(); } public UnresolvedType[] getGenericParameterTypes() { return realMember.getGenericParameterTypes(); } public ResolvedMemberImpl parameterizedWith(UnresolvedType[] typeParameters, ResolvedType newDeclaringType, boolean isParameterized) { return realMember.parameterizedWith(typeParameters, newDeclaringType, isParameterized); } public void setTypeVariables(UnresolvedType[] types) { realMember.setTypeVariables(types); } public UnresolvedType[] getTypeVariables() { return realMember.getTypeVariables(); } public ResolvedMember getErasure() { throw new UnsupportedOperationException("Adrian doesn't think you should be asking for the erasure of one of these..."); } public boolean matches(ResolvedMember aCandidateMatch) { return realMember.matches(aCandidateMatch); } public ResolvedMember resolve(World world) { return realMember.resolve(world); } public int compareTo(Object other) { return realMember.compareTo(other); } public String toLongString() { return realMember.toLongString(); } public Kind getKind() { return realMember.getKind(); } public UnresolvedType getReturnType() { return realMember.getReturnType(); } public UnresolvedType getType() { return realMember.getType(); } public String getName() { return realMember.getName(); } public UnresolvedType[] getParameterTypes() { return realMember.getParameterTypes(); } public String getSignature() { return realMember.getSignature(); } public String getDeclaredSignature() { return realMember.getDeclaredSignature(); } public int getArity() { return realMember.getArity(); } public String getParameterSignature() { return realMember.getParameterSignature(); } public boolean isCompatibleWith(Member am) { return realMember.isCompatibleWith(am); } public boolean isProtected(World world) { return realMember.isProtected(world); } public boolean isStatic(World world) { return realMember.isStatic(world); } public boolean isStrict(World world) { return realMember.isStrict(world); } public boolean isStatic() { return realMember.isStatic(); } public boolean isInterface() { return realMember.isInterface(); } public boolean isPrivate() { return realMember.isPrivate(); } public boolean canBeParameterized() { return realMember.canBeParameterized(); } public int getCallsiteModifiers() { return realMember.getCallsiteModifiers(); } public String getExtractableName() { return realMember.getExtractableName(); } public AnnotationX[] getAnnotations() { return realMember.getAnnotations(); } public Collection getDeclaringTypes(World world) { throw new UnsupportedOperationException("Adrian doesn't think you should be calling this..."); } public String getSignatureMakerName() { return realMember.getSignatureMakerName(); } public String getSignatureType() { return realMember.getSignatureType(); } public String getSignatureString(World world) { return realMember.getSignatureString(world); } public JoinPointSignature[] getJoinPointSignatures(World world) { return realMember.getJoinPointSignatures(world); } public String toString() { StringBuffer buf = new StringBuffer(); buf.append(getReturnType().getName()); buf.append(' '); buf.append(getDeclaringType().getName()); buf.append('.'); buf.append(getName()); if (getKind() != FIELD) { buf.append("("); UnresolvedType[] parameterTypes = getParameterTypes(); if (parameterTypes.length != 0) { buf.append(parameterTypes[0]); for (int i=1, len = parameterTypes.length; i < len; i++) { buf.append(", "); buf.append(parameterTypes[i].getName()); } } buf.append(")"); } return buf.toString(); } public String toGenericString() { return realMember.toGenericString(); } public void resetName(String newName) { realMember.resetName(newName); } public void resetKind(Kind newKind) { realMember.resetKind(newKind); } public void resetModifiers(int newModifiers) { realMember.resetModifiers(newModifiers); } public void resetReturnTypeToObjectArray() { realMember.resetReturnTypeToObjectArray(); } }
108,050
Bug 108050 Execution not matching override in doubly derived method
The following sample code fails because the compiler isn't matching the execution of doPost in MockServlet4. The declare warning for "servlet request" doesn't match in that case, nor does advice on the join point actually run at runtime (though this simplified code only shows the problem with declare warning). This was working until fairly recently (certainly in M2, even in AJDT from August 11). public abstract class MockServlet extends HttpServlet { protected void doPost() { } private static aspect FindMatches { declare warning: execution(* HttpServlet.do*(..)): "servlet request"; declare warning: execution(* HttpServlet+.do*(..)): "servlet request2"; } } class HttpServlet { protected void doPost() { } } public class MockDelayingServlet extends MockServlet { private static final long serialVersionUID = 1; } public class MockServlet4 extends MockDelayingServlet { protected void doPost() { } } compiler output (should have 6 warnings, including two for MockServlet4): C:\devel\workspace\test\src\MockServlet.java:16 [warning] servlet request protected void doPost() { ^^^^^^^^^^^^^^^^^^^^^^^^^ method-execution(void MockServlet.doPost()) see also: C:\devel\workspace\test\src\MockServlet.java:20::0 C:\devel\workspace\test\src\MockServlet.java:16 [warning] servlet request2 protected void doPost() { ^^^^^^^^^^^^^^^^^^^^^^^^^ method-execution(void MockServlet.doPost()) see also: C:\devel\workspace\test\src\MockServlet.java:21::0 C:\devel\workspace\test\src\MockServlet.java:26 [warning] servlet request protected void doPost() { ^^^^^^^^^^^^^^^^^^^^^^^^^ method-execution(void HttpServlet.doPost()) see also: C:\devel\workspace\test\src\MockServlet.java:20::0 C:\devel\workspace\test\src\MockServlet.java:26 [warning] servlet request2 protected void doPost() { ^^^^^^^^^^^^^^^^^^^^^^^^^ method-execution(void HttpServlet.doPost()) see also: C:\devel\workspace\test\src\MockServlet.java:21::0 C:\devel\workspace\test\src\MockServlet4.java:9 [warning] servlet request2 protected void doPost() ^^^^^^^^^^^^^^^^^^^^^^^ method-execution(void MockServlet4.doPost()) see also: C:\devel\workspace\test\src\MockServlet.java:21::0 5 warnings
resolved fixed
27e68f3
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-08-26T11:43:32Z
2005-08-25T20:00:00Z
weaver/src/org/aspectj/weaver/ResolvedMemberImpl.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver; import java.io.DataOutputStream; import java.io.IOException; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.aspectj.bridge.ISourceLocation; /** * This is the declared member, i.e. it will always correspond to an * actual method/... declaration */ public class ResolvedMemberImpl extends MemberImpl implements IHasPosition, AnnotatedElement, TypeVariableDeclaringElement, ResolvedMember { public String[] parameterNames = null; protected UnresolvedType[] checkedExceptions = UnresolvedType.NONE; /** * if this member is a parameterized version of a member in a generic type, * then this field holds a reference to the member we parameterize. */ protected ResolvedMember backingGenericMember = null; protected Set annotationTypes = null; // Some members are 'created' to represent other things (for example ITDs). These // members have their annotations stored elsewhere, and this flag indicates that is // the case. It is up to the caller to work out where that is! // Once determined the caller may choose to stash the annotations in this member... private boolean isAnnotatedElsewhere = false; // this field is not serialized. private boolean isAjSynthetic = true; // generic methods have type variables private UnresolvedType[] typeVariables; // these three fields hold the source location of this member protected int start, end; protected ISourceContext sourceContext = null; //XXX deprecate this in favor of the constructor below public ResolvedMemberImpl( Kind kind, UnresolvedType declaringType, int modifiers, UnresolvedType returnType, String name, UnresolvedType[] parameterTypes) { super(kind, declaringType, modifiers, returnType, name, parameterTypes); } public ResolvedMemberImpl( Kind kind, UnresolvedType declaringType, int modifiers, UnresolvedType returnType, String name, UnresolvedType[] parameterTypes, UnresolvedType[] checkedExceptions) { super(kind, declaringType, modifiers, returnType, name, parameterTypes); this.checkedExceptions = checkedExceptions; } public ResolvedMemberImpl( Kind kind, UnresolvedType declaringType, int modifiers, UnresolvedType returnType, String name, UnresolvedType[] parameterTypes, UnresolvedType[] checkedExceptions, ResolvedMember backingGenericMember) { this(kind, declaringType, modifiers, returnType, name, parameterTypes,checkedExceptions); this.backingGenericMember = backingGenericMember; this.isAjSynthetic = backingGenericMember.isAjSynthetic(); } public ResolvedMemberImpl( Kind kind, UnresolvedType declaringType, int modifiers, String name, String signature) { super(kind, declaringType, modifiers, name, signature); } /** * Compute the full set of signatures for a member. This walks up the hierarchy * giving the ResolvedMember in each defining type in the hierarchy. A shadowMember * can be created with a target type (declaring type) that does not actually define * the member. This is ok as long as the member is inherited in the declaring type. * Each declaring type in the line to the actual declaring type is added as an additional * signature. For example: * * class A { void foo(); } * class B extends A {} * * shadowMember : void B.foo() * * gives { void B.foo(), void A.foo() } * @param joinPointSignature * @param inAWorld */ public static JoinPointSignature[] getJoinPointSignatures(Member joinPointSignature, World inAWorld) { // Walk up hierarchy creating one member for each type up to and including the // first defining type ResolvedType originalDeclaringType = joinPointSignature.getDeclaringType().resolve(inAWorld); ResolvedMemberImpl firstDefiningMember = (ResolvedMemberImpl) joinPointSignature.resolve(inAWorld); if (firstDefiningMember == null) { return new JoinPointSignature[0]; } // declaringType can be unresolved if we matched a synthetic member generated by Aj... // should be fixed elsewhere but add this resolve call on the end for now so that we can // focus on one problem at a time... ResolvedType firstDefiningType = firstDefiningMember.getDeclaringType().resolve(inAWorld); if (firstDefiningType != originalDeclaringType) { if (joinPointSignature.getKind() == Member.CONSTRUCTOR) { return new JoinPointSignature[0]; } // else if (shadowMember.isStatic()) { // return new ResolvedMember[] {firstDefiningMember}; // } } List declaringTypes = new ArrayList(); accumulateTypesInBetween(originalDeclaringType, firstDefiningType, declaringTypes); List memberSignatures = new ArrayList(); for (Iterator iter = declaringTypes.iterator(); iter.hasNext();) { ResolvedType declaringType = (ResolvedType) iter.next(); ResolvedMember member = firstDefiningMember.withSubstituteDeclaringType(declaringType); memberSignatures.add(member); } if (shouldWalkUpHierarchyFor(firstDefiningMember)) { // now walk up the hierarchy from the firstDefiningMember and include the signature for // every type between the firstDefiningMember and the root defining member. Iterator superTypeIterator = firstDefiningType.getDirectSupertypes(); List typesAlreadyVisited = new ArrayList(); accumulateMembersMatching(firstDefiningMember,superTypeIterator,typesAlreadyVisited,memberSignatures); } JoinPointSignature[] ret = new JoinPointSignature[memberSignatures.size()]; memberSignatures.toArray(ret); return ret; } private static boolean shouldWalkUpHierarchyFor(Member aMember) { if (aMember.getKind() == Member.CONSTRUCTOR) return false; if (aMember.getKind() == Member.FIELD) return false; if (aMember.isStatic()) return false; return true; } /** * Build a list containing every type between subtype and supertype, inclusively. */ private static void accumulateTypesInBetween(ResolvedType subType, ResolvedType superType, List types) { types.add(subType); if (subType == superType) { return; } else { for (Iterator iter = subType.getDirectSupertypes(); iter.hasNext();) { ResolvedType parent = (ResolvedType) iter.next(); if (superType.isAssignableFrom(parent)) { accumulateTypesInBetween(parent, superType,types); } } } } /** * We have a resolved member, possibly with type parameter references as parameters or return * type. We need to find all its ancestor members. When doing this, a type parameter matches * regardless of bounds (bounds can be narrowed down the hierarchy). */ private static void accumulateMembersMatching( ResolvedMemberImpl memberToMatch, Iterator typesToLookIn, List typesAlreadyVisited, List foundMembers) { while(typesToLookIn.hasNext()) { ResolvedType toLookIn = (ResolvedType) typesToLookIn.next(); if (!typesAlreadyVisited.contains(toLookIn)) { typesAlreadyVisited.add(toLookIn); ResolvedMemberImpl foundMember = (ResolvedMemberImpl) toLookIn.lookupResolvedMember(memberToMatch); if (foundMember != null) { List declaringTypes = new ArrayList(); // declaring type can be unresolved if the member can from an ITD... ResolvedType resolvedDeclaringType = foundMember.getDeclaringType().resolve(toLookIn.getWorld()); accumulateTypesInBetween(toLookIn, resolvedDeclaringType, declaringTypes); for (Iterator iter = declaringTypes.iterator(); iter.hasNext();) { ResolvedType declaringType = (ResolvedType) iter.next(); typesAlreadyVisited.add(declaringType); ResolvedMember member = foundMember.withSubstituteDeclaringType(declaringType); foundMembers.add(member); } if (toLookIn.isParameterizedType() && (foundMember.backingGenericMember != null)) { foundMembers.add(new JoinPointSignature(foundMember.backingGenericMember,foundMember.declaringType.resolve(toLookIn.getWorld()))); } accumulateMembersMatching(foundMember,toLookIn.getDirectSupertypes(),typesAlreadyVisited,foundMembers); // if this was a parameterized type, look in the generic type that backs it too } } } } // ---- public final int getModifiers(World world) { return modifiers; } public final int getModifiers() { return modifiers; } // ---- public final UnresolvedType[] getExceptions(World world) { return getExceptions(); } public UnresolvedType[] getExceptions() { return checkedExceptions; } public ShadowMunger getAssociatedShadowMunger() { return null; } // ??? true or false? public boolean isAjSynthetic() { return isAjSynthetic; } public boolean hasAnnotations() { return (annotationTypes!=null); } public boolean hasAnnotation(UnresolvedType ofType) { // The ctors don't allow annotations to be specified ... yet - but // that doesn't mean it is an error to call this method. // Normally the weaver will be working with subtypes of // this type - BcelField/BcelMethod if (annotationTypes==null) return false; return annotationTypes.contains(ofType); } public ResolvedType[] getAnnotationTypes() { // The ctors don't allow annotations to be specified ... yet - but // that doesn't mean it is an error to call this method. // Normally the weaver will be working with subtypes of // this type - BcelField/BcelMethod if (annotationTypes == null) return null; return (ResolvedType[])annotationTypes.toArray(new ResolvedType[]{}); } public void setAnnotationTypes(UnresolvedType[] annotationtypes) { if (annotationTypes == null) annotationTypes = new HashSet(); for (int i = 0; i < annotationtypes.length; i++) { UnresolvedType typeX = annotationtypes[i]; annotationTypes.add(typeX); } } public void addAnnotation(AnnotationX annotation) { // FIXME asc only allows for annotation types, not instances - should it? if (annotationTypes == null) annotationTypes = new HashSet(); annotationTypes.add(annotation.getSignature()); } public boolean isBridgeMethod() { return (modifiers & Constants.ACC_BRIDGE)!=0; } public boolean isVarargsMethod() { return (modifiers & Constants.ACC_VARARGS)!=0; } public boolean isSynthetic() { return false; } public void write(DataOutputStream s) throws IOException { getKind().write(s); getDeclaringType().write(s); s.writeInt(modifiers); s.writeUTF(getName()); s.writeUTF(getSignature()); UnresolvedType.writeArray(getExceptions(), s); s.writeInt(getStart()); s.writeInt(getEnd()); // Write out any type variables... if (typeVariables==null) { s.writeInt(0); } else { s.writeInt(typeVariables.length); for (int i = 0; i < typeVariables.length; i++) { typeVariables[i].write(s); } } } public static void writeArray(ResolvedMember[] members, DataOutputStream s) throws IOException { s.writeInt(members.length); for (int i = 0, len = members.length; i < len; i++) { members[i].write(s); } } public static ResolvedMemberImpl readResolvedMember(VersionedDataInputStream s, ISourceContext sourceContext) throws IOException { ResolvedMemberImpl m = new ResolvedMemberImpl(Kind.read(s), UnresolvedType.read(s), s.readInt(), s.readUTF(), s.readUTF()); m.checkedExceptions = UnresolvedType.readArray(s); m.start = s.readInt(); m.end = s.readInt(); m.sourceContext = sourceContext; // Read in the type variables... if (s.getMajorVersion()>=AjAttribute.WeaverVersionInfo.WEAVER_VERSION_MAJOR_AJ150) { int tvcount = s.readInt(); if (tvcount!=0) { m.typeVariables = new UnresolvedType[tvcount]; for (int i=0;i<tvcount;i++) { m.typeVariables[i]=UnresolvedType.read(s); } } } return m; } public static ResolvedMember[] readResolvedMemberArray(VersionedDataInputStream s, ISourceContext context) throws IOException { int len = s.readInt(); ResolvedMember[] members = new ResolvedMember[len]; for (int i=0; i < len; i++) { members[i] = ResolvedMemberImpl.readResolvedMember(s, context); } return members; } public ResolvedMember resolve(World world) { // make sure all the pieces of a resolvedmember really are resolved if (annotationTypes!=null) { Set r = new HashSet(); for (Iterator iter = annotationTypes.iterator(); iter.hasNext();) { UnresolvedType element = (UnresolvedType) iter.next(); r.add(world.resolve(element)); } annotationTypes = r; } declaringType = declaringType.resolve(world); if (declaringType.isRawType()) declaringType = ((ReferenceType)declaringType).getGenericType(); if (typeVariables!=null && typeVariables.length>0) { for (int i = 0; i < typeVariables.length; i++) { UnresolvedType array_element = typeVariables[i]; typeVariables[i] = typeVariables[i].resolve(world); } } if (parameterTypes!=null && parameterTypes.length>0) { for (int i = 0; i < parameterTypes.length; i++) { UnresolvedType array_element = parameterTypes[i]; parameterTypes[i] = parameterTypes[i].resolve(world); } } returnType = returnType.resolve(world);return this; } public ISourceContext getSourceContext(World world) { return getDeclaringType().resolve(world).getSourceContext(); } public final String[] getParameterNames() { return parameterNames; } public final String[] getParameterNames(World world) { return getParameterNames(); } public AjAttribute.EffectiveSignatureAttribute getEffectiveSignature() { return null; } public ISourceLocation getSourceLocation() { //System.out.println("get context: " + this + " is " + sourceContext); if (sourceContext == null) { //System.err.println("no context: " + this); return null; } return sourceContext.makeSourceLocation(this); } public int getEnd() { return end; } public ISourceContext getSourceContext() { return sourceContext; } public int getStart() { return start; } public void setPosition(int sourceStart, int sourceEnd) { this.start = sourceStart; this.end = sourceEnd; } public void setSourceContext(ISourceContext sourceContext) { this.sourceContext = sourceContext; } public boolean isAbstract() { return Modifier.isAbstract(modifiers); } public boolean isPublic() { return Modifier.isPublic(modifiers); } public boolean isProtected() { return Modifier.isProtected(modifiers); } public boolean isNative() { return Modifier.isNative(modifiers); } public boolean isDefault() { return !(isPublic() || isProtected() || isPrivate()); } public boolean isVisible(ResolvedType fromType) { World world = fromType.getWorld(); return ResolvedType.isVisible(getModifiers(), getDeclaringType().resolve(world), fromType); } public void setCheckedExceptions(UnresolvedType[] checkedExceptions) { this.checkedExceptions = checkedExceptions; } public void setAnnotatedElsewhere(boolean b) { isAnnotatedElsewhere = b; } public boolean isAnnotatedElsewhere() { return isAnnotatedElsewhere; } /** * Get the UnresolvedType for the return type, taking generic signature into account */ public UnresolvedType getGenericReturnType() { return getReturnType(); } /** * Get the TypeXs of the parameter types, taking generic signature into account */ public UnresolvedType[] getGenericParameterTypes() { return getParameterTypes(); } // return a resolved member in which all type variables in the signature of this // member have been replaced with the given bindings. // the isParameterized flag tells us whether we are creating a raw type version or not // if isParameterized List<T> will turn into List<String> (for example), // but if !isParameterized List<T> will turn into List. public ResolvedMemberImpl parameterizedWith(UnresolvedType[] typeParameters,ResolvedType newDeclaringType, boolean isParameterized) { if (!this.getDeclaringType().isGenericType()) { throw new IllegalStateException("Can't ask to parameterize a member of a non-generic type"); } TypeVariable[] typeVariables = getDeclaringType().getTypeVariables(); if (typeVariables.length != typeParameters.length) { throw new IllegalStateException("Wrong number of type parameters supplied"); } Map typeMap = new HashMap(); for (int i = 0; i < typeVariables.length; i++) { typeMap.put(typeVariables[i].getName(), typeParameters[i]); } UnresolvedType parameterizedReturnType = parameterize(getGenericReturnType(),typeMap,isParameterized); UnresolvedType[] parameterizedParameterTypes = new UnresolvedType[getGenericParameterTypes().length]; for (int i = 0; i < parameterizedParameterTypes.length; i++) { parameterizedParameterTypes[i] = parameterize(getGenericParameterTypes()[i], typeMap,isParameterized); } return new ResolvedMemberImpl( getKind(), newDeclaringType, getModifiers(), parameterizedReturnType, getName(), parameterizedParameterTypes, getExceptions(), this ); } public void setTypeVariables(UnresolvedType[] types) { typeVariables = types; } public UnresolvedType[] getTypeVariables() { return typeVariables; } private UnresolvedType parameterize(UnresolvedType aType, Map typeVariableMap, boolean inParameterizedType) { if (aType instanceof TypeVariableReferenceType) { String variableName = ((TypeVariableReferenceType)aType).getTypeVariable().getName(); if (!typeVariableMap.containsKey(variableName)) { return aType; // if the type variable comes from the method (and not the type) thats OK } return (UnresolvedType) typeVariableMap.get(variableName); } else if (aType.isParameterizedType()) { if (inParameterizedType) { return aType.parameterize(typeVariableMap); } else { return aType.getRawType(); } } return aType; } /** * If this member is defined by a parameterized super-type, return the erasure * of that member. * For example: * interface I<T> { T foo(T aTea); } * class C implements I<String> { * String foo(String aString) { return "something"; } * } * The resolved member for C.foo has signature String foo(String). The * erasure of that member is Object foo(Object) -- use upper bound of type * variable. * A type is a supertype of itself. */ public ResolvedMember getErasure() { if (calculatedMyErasure) return myErasure; calculatedMyErasure = true; ResolvedType resolvedDeclaringType = (ResolvedType) getDeclaringType(); // this next test is fast, and the result is cached. if (!resolvedDeclaringType.hasParameterizedSuperType()) { return null; } else { // we have one or more parameterized super types. // this member may be defined by one of them... we need to find out. Collection declaringTypes = this.getDeclaringTypes(resolvedDeclaringType.getWorld()); for (Iterator iter = declaringTypes.iterator(); iter.hasNext();) { ResolvedType aDeclaringType = (ResolvedType) iter.next(); if (aDeclaringType.isParameterizedType()) { // we've found the (a?) parameterized type that defines this member. // now get the erasure of it ResolvedMemberImpl matchingMember = (ResolvedMemberImpl) aDeclaringType.lookupMemberNoSupers(this); if (matchingMember != null && matchingMember.backingGenericMember != null) { myErasure = matchingMember.backingGenericMember; return myErasure; } } } } return null; } private ResolvedMember myErasure = null; private boolean calculatedMyErasure = false; /** * For ITDs, we use the default factory methods to build a resolved member, then alter a couple of characteristics * using this method - this is safe. */ public void resetName(String newName) {this.name = newName;} public void resetKind(Kind newKind) {this.kind=newKind; } public void resetModifiers(int newModifiers) {this.modifiers=newModifiers;} public void resetReturnTypeToObjectArray() { returnType = UnresolvedType.OBJECTARRAY; } /** * Returns a copy of this member but with the declaring type swapped. * Copy only needs to be shallow. * @param newDeclaringType */ private JoinPointSignature withSubstituteDeclaringType(ResolvedType newDeclaringType) { JoinPointSignature ret = new JoinPointSignature(this,newDeclaringType); return ret; } /** * Returns true if this member matches the other. The matching takes into account * name and parameter types only. When comparing parameter types, we allow any type * variable to match any other type variable regardless of bounds. */ public boolean matches(ResolvedMember aCandidateMatch) { ResolvedMemberImpl candidateMatchImpl = (ResolvedMemberImpl)aCandidateMatch; if (!getName().equals(aCandidateMatch.getName())) return false; UnresolvedType[] myParameterTypes = getGenericParameterTypes(); UnresolvedType[] candidateParameterTypes = aCandidateMatch.getGenericParameterTypes(); if (myParameterTypes.length != candidateParameterTypes.length) return false; String myParameterSignature = getParameterSigWithBoundsRemoved(); String candidateParameterSignature = candidateMatchImpl.getParameterSigWithBoundsRemoved(); if (myParameterSignature.equals(candidateParameterSignature)) { return true; } else { // try erasure myParameterSignature = getParameterSigErasure(); candidateParameterSignature = candidateMatchImpl.getParameterSigErasure(); return myParameterSignature.equals(candidateParameterSignature); } } /** converts e.g. <T extends Number>.... List<T> to just Ljava/util/List<T;>; * whereas the full signature would be Ljava/util/List<T:Ljava/lang/Number;>; */ private String myParameterSignatureWithBoundsRemoved = null; /** * converts e.g. <T extends Number>.... List<T> to just Ljava/util/List; */ private String myParameterSignatureErasure = null; // does NOT produce a meaningful java signature, but does give a unique string suitable for // comparison. private String getParameterSigWithBoundsRemoved() { if (myParameterSignatureWithBoundsRemoved != null) return myParameterSignatureWithBoundsRemoved; StringBuffer sig = new StringBuffer(); UnresolvedType[] myParameterTypes = getGenericParameterTypes(); for (int i = 0; i < myParameterTypes.length; i++) { appendSigWithTypeVarBoundsRemoved(myParameterTypes[i], sig); } myParameterSignatureWithBoundsRemoved = sig.toString(); return myParameterSignatureWithBoundsRemoved; } private String getParameterSigErasure() { if (myParameterSignatureErasure != null) return myParameterSignatureErasure; StringBuffer sig = new StringBuffer(); UnresolvedType[] myParameterTypes = getParameterTypes(); for (int i = 0; i < myParameterTypes.length; i++) { UnresolvedType thisParameter = myParameterTypes[i]; if (thisParameter.isTypeVariableReference()) { sig.append(thisParameter.getUpperBound().getSignature()); } else { sig.append(thisParameter.getSignature()); } } myParameterSignatureErasure = sig.toString(); return myParameterSignatureErasure; } // does NOT produce a meaningful java signature, but does give a unique string suitable for // comparison. private void appendSigWithTypeVarBoundsRemoved(UnresolvedType aType, StringBuffer toBuffer) { if (aType.isTypeVariableReference()) { toBuffer.append("T;"); } else if (aType.isParameterizedType()) { toBuffer.append(aType.getRawType().getSignature()); toBuffer.append("<"); for (int i = 0; i < aType.getTypeParameters().length; i++) { appendSigWithTypeVarBoundsRemoved(aType.getTypeParameters()[i], toBuffer); } toBuffer.append(">;"); } else { toBuffer.append(aType.getSignature()); } } public String toGenericString() { StringBuffer buf = new StringBuffer(); buf.append(getGenericReturnType().getSimpleName()); buf.append(' '); buf.append(declaringType.getName()); buf.append('.'); buf.append(name); if (kind != FIELD) { buf.append("("); UnresolvedType[] params = getGenericParameterTypes(); if (params.length != 0) { buf.append(params[0].getSimpleName()); for (int i=1, len = params.length; i < len; i++) { buf.append(", "); buf.append(params[i].getSimpleName()); } } buf.append(")"); } return buf.toString(); } }
108,377
Bug 108377 Verify Error on intertype field indirection in intertype method
When I run this program: public class A { public static void main(String[] args) { System.out.println(new A().foo()); } } aspect Aspect1 { public A A.a; public String A.value; public String A.foo() { return a.value; } } I get the error: Exception in thread "main" java.lang.VerifyError: (class: Aspect1, method: ajc$interMethod$Aspect1$A$foo signature: (LA;)Ljava/lang/String;) Incompatible type for getting or setting field at A.<init>(A.java:1) at A.main(A.java:3) Javap reveals that the field name is missing the class name part: 1: getfield #50; //Field a:LA; 4: getfield #46; //Field A.value:Ljava/lang/String; If I replace a.value by this.a.value, the correct code is generated: 1: getfield #37; //Field A.a:LA; 4: getfield #46; //Field A.value:Ljava/lang/String;
resolved fixed
be750d5
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-08-31T09:34:59Z
2005-08-30T13:53:20Z
tests/src/org/aspectj/systemtest/ajc150/Ajc150Tests.java
/******************************************************************************* * Copyright (c) 2004 IBM * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Andy Clement - initial API and implementation *******************************************************************************/ package org.aspectj.systemtest.ajc150; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import junit.framework.Test; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.apache.bcel.classfile.Method; import org.aspectj.apache.bcel.util.ClassPath; import org.aspectj.apache.bcel.util.SyntheticRepository; import org.aspectj.asm.AsmManager; import org.aspectj.testing.XMLBasedAjcTestCase; import org.aspectj.util.LangUtil; /** * These are tests that will run on Java 1.4 and use the old harness format for test specification. */ public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase { public static Test suite() { return XMLBasedAjcTestCase.loadSuite(Ajc150Tests.class); } protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml"); } public void test_typeProcessingOrderWhenDeclareParents() { runTest("Order of types passed to compiler determines weaving behavior"); } public void test_aroundMethod() { runTest("method called around in class"); } public void test_aroundMethodAspect() { runTest("method called around in aspect"); } public void test_ambiguousBindingsDetection() { runTest("Various kinds of ambiguous bindings"); } public void test_ambiguousArgsDetection() { runTest("ambiguous args"); } public void testIncorrectExceptionTableWhenBreakInMethod_pr78021() { runTest("Injecting exception into while loop with break statement causes catch block to be ignored"); } public void testIncorrectExceptionTableWhenReturnInMethod_pr79554() { runTest("Return in try-block disables catch-block if final-block is present"); } public void testMissingDebugInfoForGeneratedMethods_pr82570() throws ClassNotFoundException { runTest("Weaved code does not include debug lines"); boolean f = false; JavaClass jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1"); Method[] meths = jc.getMethods(); for (int i = 0; i < meths.length; i++) { Method method = meths[i]; if (f) System.err.println("Line number table for "+method.getName()+method.getSignature()+" = "+method.getLineNumberTable()); assertTrue("Didn't find a line number table for method "+method.getName()+method.getSignature(), method.getLineNumberTable()!=null); } // This test would determine the info isn't there if you pass -g:none ... // cR = ajc(baseDir,new String[]{"PR82570_1.java","-g:none"}); // assertTrue("Expected no compile problem:"+cR,!cR.hasErrorMessages()); // System.err.println(cR.getStandardError()); // jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1"); // meths = jc.getMethods(); // for (int i = 0; i < meths.length; i++) { // Method method = meths[i]; // assertTrue("Found a line number table for method "+method.getName(), // method.getLineNumberTable()==null); // } } public void testCanOverrideProtectedMethodsViaITDandDecp_pr83303() { runTest("compiler error when mixing inheritance, overriding and polymorphism"); } public void testPerTypeWithinMissesNamedInnerTypes() { runTest("pertypewithin() handing of inner classes (1)"); } public void testPerTypeWithinMissesAnonymousInnerTypes() { runTest("pertypewithin() handing of inner classes (2)"); } public void testPerTypeWithinIncorrectlyMatchingInterfaces() { runTest("pertypewithin({interface}) illegal field modifier"); } public void test051_arrayCloningInJava5() { runTest("AJC possible bug with static nested classes"); } public void testBadASMforEnums() throws IOException { runTest("bad asm for enums"); if (LangUtil.is15VMOrGreater()) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintWriter pw = new PrintWriter(baos); AsmManager.dumptree(pw,AsmManager.getDefault().getHierarchy().getRoot(),0); pw.flush(); String tree = baos.toString(); assertTrue("Expected 'Red [enumvalue]' somewhere in here:"+tree,tree.indexOf("Red [enumvalue]")!=-1); } } public void npeOnTypeNotFound() { runTest("structure model npe on type not found"); } public void testNoRuntimeExceptionSoftening() { runTest("declare soft of runtime exception"); } public void testRuntimeNoSoftenWithHandler() { runTest("declare soft w. catch block"); } public void testSyntaxError() { runTest("invalid cons syntax"); } public void testVarargsInConsBug() { runTest("varargs in constructor sig"); } public void testAspectpathdirs() { runTest("dirs on aspectpath"); } public void testIntroSample() { runTest("introduction sample"); } public void testPTWInterface() { runTest("pertypewithin({interface}) illegal field modifier"); } public void testEnumCalledEnumEtc() { runTest("enum called Enum, annotation called Annotation, etc"); } public void testInternalCompilerError_pr86832() { runTest("Internal compiler error"); } public void testCloneMethod_pr83311() { runTest("overriding/polymorphism error on interface method introduction"); } /** * IfPointcut.findResidueInternal() was modified to make this test complete in a short amount * of time - if you see it hanging, someone has messed with the optimization. */ public void testIfEvaluationExplosion_pr94086() { runTest("Exploding compile time with if() statements in pointcut"); } public void testReflectNPE_pr94167() {runTest("NPE in reflect implementation");} public void testStaticImports_pr84260() {runTest("static import failures");} public void testGenerics_pr99089() {runTest("ArrayIndexOutOfBoundsException - Generics in privileged aspects");} public void testGenerics_pr95993() {runTest("NPE at ClassScope.java:660 when compiling generic class");} public void testItdGenerics_pr99228() {runTest("ITD of a field into a generic class");} public void testItdGenerics_pr98320() {runTest("intertype with nested generic type");} public void testItdGenerics_pr100227() {runTest("inner class with generic enclosing class");} public void testItdGenerics_pr100260() {runTest("methods inherited from a generic parent");} public void testSyntaxErrorNPE_pr103266() {runTest("NPE on syntax error");} public void testIllegalStateExceptionOnNestedParameterizedType_pr106634() { runTest("IllegalStateException unpacking signature of nested parameterized type"); } public void testParseErrorOnAnnotationStarPlusPattern() { runTest("(@Foo *)+ type pattern parse error"); } public void test_pr106130_tooManyLocals() { runTest("test weaving with > 256 locals"); } public void testMissingNamePattern_pr106461() { runTest("missing name pattern"); } public void testMissingNamePattern_pr107059() { runTest("parser crashes on call(void (@a *)(..)"); } public void testIntermediateAnnotationMatching() { runTest("intermediate annotation matching"); } public void testBadRuntimeTestGeneration() { runTest("target(@Foo *)"); } public void testErrorMessageOnITDWithTypePatterns() { runTest("clear error message on itd with type pattern"); } public void testAjKeywordsAsIdentifiers() { runTest("before and after are valid identifiers in classes"); } public void testAjKeywordsAsIdentifiers2() { runTest("before and after are valid identifiers in classes, part 2"); } public void testNoBeforeReturningAdvice() { runTest("before returning advice not allowed!"); } public void testDetectVoidFieldType() { runTest("void field type in pointcut expression"); } public void testPointcutOverriding() { runTest("overriding final pointcut from super-aspect"); } public void testAtSuppressWarnings() { runTest("@SuppressWarnings should suppress"); } public void testDEOWWithBindingPointcut() { runTest("declare warning : foo(str) : ...;"); } public void testAroundAdviceAndInterfaceInitializer() { runTest("around advice on interface initializer"); } public void testGoodErrorMessageOnUnmatchedMemberSyntax() { runTest("good error message for unmatched member syntax"); } public void testITDWithNoExceptionAndIntermediary() { runTest("itd override with no exception clause"); } public void testAnonymousInnerClasses() { runTest("anonymous inner classes"); } public void testMultipleAnonymousInnerClasses() { runTest("multiple anonymous inner classes"); } public void testPrivilegedMethodAccessorsGetRightExceptions_pr82989() { runTest("Compiler error due to a wrong exception check in try blocks"); } public void testAnonymousInnerClassWithMethodReturningTypeParameter_pr107898() { runTest("anonymous inner class with method returning type parameter"); } public void testMatchingOfObjectArray() { runTest("matching against Object[]"); } public void testMultipleAnonymousInnerClasses_pr108104() { runTest("multiple anonymous inner classes 2"); } public void testSignatureMatchingInMultipleOverrideScenario() { runTest("signature matching in override scenario"); } public void testWildcardAnnotationMatching_pr108245() { runTest("wildcard annotation matching - pr108245"); } public void testInnerTypesAndTypeVariables() { runTest("inner types and type variables"); } public void testAtAfterThrowingWithNoFormal() { runTest("@AfterThrowing with no formal specified"); } public void testParameterizedVarArgsMatch() { runTest("varargs with type variable"); } // helper methods..... public SyntheticRepository createRepos(File cpentry) { ClassPath cp = new ClassPath(cpentry+File.pathSeparator+System.getProperty("java.class.path")); return SyntheticRepository.getInstance(cp); } protected JavaClass getClassFrom(File where,String clazzname) throws ClassNotFoundException { SyntheticRepository repos = createRepos(where); return repos.loadClass(clazzname); } }
108,448
Bug 108448 IllegalStateException: Undeclared type variable when hiding
null
resolved fixed
2c9ea11
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-08-31T11:42:29Z
2005-08-31T06:33:20Z
weaver/src/org/aspectj/weaver/bcel/BcelField.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.bcel; import java.util.HashSet; import java.util.Iterator; import java.util.List; import org.aspectj.apache.bcel.classfile.Attribute; import org.aspectj.apache.bcel.classfile.Field; import org.aspectj.apache.bcel.classfile.GenericSignatureParser; import org.aspectj.apache.bcel.classfile.Signature; import org.aspectj.apache.bcel.classfile.Synthetic; import org.aspectj.apache.bcel.classfile.annotation.Annotation; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.AnnotationX; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ResolvedMemberImpl; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.World; final class BcelField extends ResolvedMemberImpl { private Field field; private boolean isAjSynthetic; private boolean isSynthetic = false; private AnnotationX[] annotations; private World world; private BcelObjectType bcelObjectType; private UnresolvedType genericFieldType = null; private boolean unpackedGenericSignature = false; BcelField(BcelObjectType declaringType, Field field) { super( FIELD, declaringType.getResolvedTypeX(), field.getAccessFlags(), field.getName(), field.getSignature()); this.field = field; this.world = declaringType.getResolvedTypeX().getWorld(); this.bcelObjectType = declaringType; unpackAttributes(world); checkedExceptions = UnresolvedType.NONE; } // ---- private void unpackAttributes(World world) { Attribute[] attrs = field.getAttributes(); List as = BcelAttributes.readAjAttributes(getDeclaringType().getClassName(),attrs, getSourceContext(world),world.getMessageHandler(),bcelObjectType.getWeaverVersionAttribute()); as.addAll(AtAjAttributes.readAj5FieldAttributes(field, world.resolve(getDeclaringType()), getSourceContext(world), world.getMessageHandler())); for (Iterator iter = as.iterator(); iter.hasNext();) { AjAttribute a = (AjAttribute) iter.next(); if (a instanceof AjAttribute.AjSynthetic) { isAjSynthetic = true; } else { throw new BCException("weird field attribute " + a); } } isAjSynthetic = false; for (int i = attrs.length - 1; i >= 0; i--) { if (attrs[i] instanceof Synthetic) isSynthetic = true; } } public boolean isAjSynthetic() { return isAjSynthetic; // || getName().startsWith(NameMangler.PREFIX); } public boolean isSynthetic() { return isSynthetic; } public boolean hasAnnotation(UnresolvedType ofType) { ensureAnnotationTypesRetrieved(); for (Iterator iter = annotationTypes.iterator(); iter.hasNext();) { ResolvedType aType = (ResolvedType) iter.next(); if (aType.equals(ofType)) return true; } return false; } public ResolvedType[] getAnnotationTypes() { ensureAnnotationTypesRetrieved(); ResolvedType[] ret = new ResolvedType[annotationTypes.size()]; annotationTypes.toArray(ret); return ret; } private void ensureAnnotationTypesRetrieved() { if (annotationTypes == null) { Annotation annos[] = field.getAnnotations(); annotationTypes = new HashSet(); annotations = new AnnotationX[annos.length]; for (int i = 0; i < annos.length; i++) { Annotation annotation = annos[i]; ResolvedType rtx = world.resolve(UnresolvedType.forName(annotation.getTypeName())); annotationTypes.add(rtx); annotations[i] = new AnnotationX(annotation,world); } } } public void addAnnotation(AnnotationX annotation) { ensureAnnotationTypesRetrieved(); // Add it to the set of annotations int len = annotations.length; AnnotationX[] ret = new AnnotationX[len+1]; System.arraycopy(annotations, 0, ret, 0, len); ret[len] = annotation; annotations = ret; // Add it to the set of annotation types annotationTypes.add(UnresolvedType.forName(annotation.getTypeName()).resolve(world)); // FIXME asc this call here suggests we are managing the annotations at // too many levels, here in BcelField we keep a set and in the lower 'field' // object we keep a set - we should think about reducing this to one // level?? field.addAnnotation(annotation.getBcelAnnotation()); } /** * Unpack the generic signature attribute if there is one and we haven't already * done so, then find the true field type of this field (eg. List<String>). */ public UnresolvedType getGenericReturnType() { unpackGenericSignature(); return genericFieldType; } private void unpackGenericSignature() { if (unpackedGenericSignature) return; unpackedGenericSignature = true; String gSig = field.getGenericSignature(); if (gSig != null) { // get from generic Signature.FieldTypeSignature fts = new GenericSignatureParser().parseAsFieldSignature(gSig); Signature.ClassSignature genericTypeSig = bcelObjectType.getGenericClassTypeSignature(); Signature.FormalTypeParameter[] typeVars = ((genericTypeSig == null) ? new Signature.FormalTypeParameter[0] : genericTypeSig.formalTypeParameters); genericFieldType = BcelGenericSignatureToTypeXConverter.fieldTypeSignature2TypeX(fts, typeVars, world); } else { genericFieldType = getReturnType(); } } }
108,448
Bug 108448 IllegalStateException: Undeclared type variable when hiding
null
resolved fixed
2c9ea11
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-08-31T11:42:29Z
2005-08-31T06:33:20Z
weaver/src/org/aspectj/weaver/bcel/BcelGenericSignatureToTypeXConverter.java
/* ******************************************************************* * Copyright (c) 2005 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * Adrian Colyer Initial implementation * ******************************************************************/ package org.aspectj.weaver.bcel; import java.util.HashMap; import java.util.Map; import org.aspectj.apache.bcel.classfile.Signature; import org.aspectj.apache.bcel.classfile.Signature.SimpleClassTypeSignature; import org.aspectj.weaver.BoundedReferenceType; import org.aspectj.weaver.ReferenceType; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.TypeFactory; import org.aspectj.weaver.TypeVariable; import org.aspectj.weaver.TypeVariableReferenceType; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.World; /** * A utility class that assists in unpacking constituent parts of * generic signature attributes and returning their equivalents in * UnresolvedType world. */ public class BcelGenericSignatureToTypeXConverter { public static ResolvedType classTypeSignature2TypeX( Signature.ClassTypeSignature aClassTypeSignature, Signature.FormalTypeParameter[] typeParams, World world) { Map typeMap = new HashMap(); ResolvedType ret = classTypeSignature2TypeX(aClassTypeSignature,typeParams,world,typeMap); fixUpCircularDependencies(ret, typeMap); return ret; } private static ResolvedType classTypeSignature2TypeX( Signature.ClassTypeSignature aClassTypeSignature, Signature.FormalTypeParameter[] typeParams, World world, Map inProgressTypeVariableResolutions) { // class type sig consists of an outer type, and zero or more nested types // the fully qualified name is outer-type.nested-type1.nested-type2.... // each type in the hierarchy may have type arguments // first build the 'raw type' signature StringBuffer sig = new StringBuffer(); sig.append(aClassTypeSignature.outerType.identifier.replace(';',' ').trim()); for (int i = 0; i < aClassTypeSignature.nestedTypes.length; i++) { sig.append("$"); sig.append(aClassTypeSignature.nestedTypes[i].identifier.replace(';',' ').trim()); } sig.append(";"); // now look for any type parameters. // I *think* we only need to worry about the 'right-most' type... SimpleClassTypeSignature innerType = aClassTypeSignature.outerType; if (aClassTypeSignature.nestedTypes.length > 0) { innerType = aClassTypeSignature.nestedTypes[aClassTypeSignature.nestedTypes.length-1]; } if (innerType.typeArguments.length > 0) { // we have to create a parameterized type // type arguments may be array types, class types, or typevariable types ResolvedType theBaseType = UnresolvedType.forSignature(sig.toString()).resolve(world); ResolvedType[] typeArgumentTypes = new ResolvedType[innerType.typeArguments.length]; for (int i = 0; i < typeArgumentTypes.length; i++) { typeArgumentTypes[i] = typeArgument2TypeX(innerType.typeArguments[i],typeParams,world,inProgressTypeVariableResolutions); } return TypeFactory.createParameterizedType( theBaseType, typeArgumentTypes, world); // world.resolve(UnresolvedType.forParameterizedTypes( // UnresolvedType.forSignature(sig.toString()).resolve(world), // typeArgumentTypes)); } else { // we have a non-parameterized type return world.resolve(UnresolvedType.forSignature(sig.toString())); } } public static ResolvedType fieldTypeSignature2TypeX( Signature.FieldTypeSignature aFieldTypeSignature, Signature.FormalTypeParameter[] typeParams, World world) { Map typeMap = new HashMap(); ResolvedType ret = fieldTypeSignature2TypeX(aFieldTypeSignature,typeParams,world,typeMap); fixUpCircularDependencies(ret, typeMap); return ret; } private static ResolvedType fieldTypeSignature2TypeX( Signature.FieldTypeSignature aFieldTypeSignature, Signature.FormalTypeParameter[] typeParams, World world, Map inProgressTypeVariableResolutions) { if (aFieldTypeSignature.isClassTypeSignature()) { return classTypeSignature2TypeX((Signature.ClassTypeSignature)aFieldTypeSignature,typeParams,world,inProgressTypeVariableResolutions); } else if (aFieldTypeSignature.isArrayTypeSignature()) { int dims = 0; Signature.TypeSignature ats = aFieldTypeSignature; while(ats instanceof Signature.ArrayTypeSignature) { dims++; ats = ((Signature.ArrayTypeSignature)ats).typeSig; } return world.resolve(UnresolvedType.makeArray(typeSignature2TypeX(ats,typeParams,world,inProgressTypeVariableResolutions), dims)); } else if (aFieldTypeSignature.isTypeVariableSignature()) { ResolvedType rtx = typeVariableSignature2TypeX((Signature.TypeVariableSignature)aFieldTypeSignature,typeParams,world,inProgressTypeVariableResolutions); return rtx; } else { throw new IllegalStateException("Cant understand field type signature: " + aFieldTypeSignature); } } public static TypeVariable formalTypeParameter2TypeVariable( Signature.FormalTypeParameter aFormalTypeParameter, Signature.FormalTypeParameter[] typeParams, World world) { Map typeMap = new HashMap(); return formalTypeParameter2TypeVariable(aFormalTypeParameter,typeParams,world,typeMap); } private static TypeVariable formalTypeParameter2TypeVariable( Signature.FormalTypeParameter aFormalTypeParameter, Signature.FormalTypeParameter[] typeParams, World world, Map inProgressTypeVariableResolutions) { UnresolvedType upperBound = fieldTypeSignature2TypeX(aFormalTypeParameter.classBound,typeParams,world,inProgressTypeVariableResolutions); UnresolvedType[] ifBounds = new UnresolvedType[aFormalTypeParameter.interfaceBounds.length]; for (int i = 0; i < ifBounds.length; i++) { ifBounds[i] = fieldTypeSignature2TypeX(aFormalTypeParameter.interfaceBounds[i], typeParams,world,inProgressTypeVariableResolutions); } return new TypeVariable(aFormalTypeParameter.identifier,upperBound,ifBounds); } private static ResolvedType typeArgument2TypeX( Signature.TypeArgument aTypeArgument, Signature.FormalTypeParameter[] typeParams, World world, Map inProgressTypeVariableResolutions) { if (aTypeArgument.isWildcard) return UnresolvedType.SOMETHING.resolve(world); if (aTypeArgument.isMinus) { UnresolvedType bound = fieldTypeSignature2TypeX(aTypeArgument.signature, typeParams,world,inProgressTypeVariableResolutions); ReferenceType rBound = (ReferenceType) world.resolve(bound); return new BoundedReferenceType(rBound,false,world); } else if (aTypeArgument.isPlus) { UnresolvedType bound = fieldTypeSignature2TypeX(aTypeArgument.signature, typeParams,world,inProgressTypeVariableResolutions); ReferenceType rBound = (ReferenceType) world.resolve(bound); return new BoundedReferenceType(rBound,true,world); } else { return fieldTypeSignature2TypeX(aTypeArgument.signature,typeParams,world,inProgressTypeVariableResolutions); } } public static ResolvedType typeSignature2TypeX( Signature.TypeSignature aTypeSig, Signature.FormalTypeParameter[] typeParams, World world) { Map typeMap = new HashMap(); ResolvedType ret = typeSignature2TypeX(aTypeSig,typeParams,world,typeMap); fixUpCircularDependencies(ret, typeMap); return ret; } private static ResolvedType typeSignature2TypeX( Signature.TypeSignature aTypeSig, Signature.FormalTypeParameter[] typeParams, World world, Map inProgressTypeVariableResolutions) { if (aTypeSig.isBaseType()) { return world.resolve(UnresolvedType.forSignature(((Signature.BaseTypeSignature)aTypeSig).toString())); } else { return fieldTypeSignature2TypeX((Signature.FieldTypeSignature)aTypeSig,typeParams,world,inProgressTypeVariableResolutions); } } private static ResolvedType typeVariableSignature2TypeX( Signature.TypeVariableSignature aTypeVarSig, Signature.FormalTypeParameter[] typeParams, World world, Map inProgressTypeVariableResolutions) { Signature.FormalTypeParameter typeVarBounds = null; for (int i = 0; i < typeParams.length; i++) { if (typeParams[i].identifier.equals(aTypeVarSig.typeVariableName)) { typeVarBounds = typeParams[i]; break; } } if (typeVarBounds == null) { throw new IllegalStateException("Undeclared type variable in signature: " + aTypeVarSig.typeVariableName); } if (inProgressTypeVariableResolutions.containsKey(typeVarBounds)) { return (ResolvedType) inProgressTypeVariableResolutions.get(typeVarBounds); } inProgressTypeVariableResolutions.put(typeVarBounds,new FTPHolder(typeVarBounds,world)); ResolvedType ret = new TypeVariableReferenceType( formalTypeParameter2TypeVariable(typeVarBounds,typeParams,world,inProgressTypeVariableResolutions), world); inProgressTypeVariableResolutions.put(typeVarBounds,ret); return ret; } private static void fixUpCircularDependencies(ResolvedType aTypeX, Map typeVariableResolutions) { if (! (aTypeX instanceof ReferenceType)) return; ReferenceType rt = (ReferenceType) aTypeX; TypeVariable[] typeVars = rt.getTypeVariables(); for (int i = 0; i < typeVars.length; i++) { if (typeVars[i].getUpperBound() instanceof FTPHolder) { Signature.FormalTypeParameter key = ((FTPHolder) typeVars[i].getUpperBound()).ftpToBeSubstituted; typeVars[i].setUpperBound((UnresolvedType)typeVariableResolutions.get(key)); } } } private static class FTPHolder extends ReferenceType { public Signature.FormalTypeParameter ftpToBeSubstituted; public FTPHolder(Signature.FormalTypeParameter ftp, World world) { super("Ljava/lang/Object;",world); this.ftpToBeSubstituted = ftp; } public String toString() { return "placeholder for TypeVariable of " + ftpToBeSubstituted.toString(); } public ResolvedType resolve(World world) { return this; } } }
108,448
Bug 108448 IllegalStateException: Undeclared type variable when hiding
null
resolved fixed
2c9ea11
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-08-31T11:42:29Z
2005-08-31T06:33:20Z
weaver/src/org/aspectj/weaver/bcel/BcelMethod.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.bcel; import java.lang.reflect.Modifier; import java.util.HashSet; import java.util.Iterator; import java.util.List; import org.aspectj.apache.bcel.classfile.ExceptionTable; import org.aspectj.apache.bcel.classfile.GenericSignatureParser; import org.aspectj.apache.bcel.classfile.LocalVariable; import org.aspectj.apache.bcel.classfile.LocalVariableTable; import org.aspectj.apache.bcel.classfile.Method; import org.aspectj.apache.bcel.classfile.Signature; import org.aspectj.apache.bcel.classfile.Signature.TypeVariableSignature; import org.aspectj.apache.bcel.classfile.annotation.Annotation; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.SourceLocation; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.AnnotationX; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.ResolvedMemberImpl; import org.aspectj.weaver.ResolvedPointcutDefinition; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.World; final class BcelMethod extends ResolvedMemberImpl { private Method method; private boolean isAjSynthetic; private ShadowMunger associatedShadowMunger; private ResolvedPointcutDefinition preResolvedPointcut; // used when ajc has pre-resolved the pointcut of some @Advice // private ResolvedType[] annotationTypes = null; private AnnotationX[] annotations = null; private AjAttribute.EffectiveSignatureAttribute effectiveSignature; private AjAttribute.MethodDeclarationLineNumberAttribute declarationLineNumber; private World world; private BcelObjectType bcelObjectType; BcelMethod(BcelObjectType declaringType, Method method) { super( method.getName().equals("<init>") ? CONSTRUCTOR : (method.getName().equals("<clinit>") ? STATIC_INITIALIZATION : METHOD), declaringType.getResolvedTypeX(), declaringType.isInterface() ? method.getAccessFlags() | Modifier.INTERFACE : method.getAccessFlags(), method.getName(), method.getSignature()); this.method = method; this.sourceContext = declaringType.getResolvedTypeX().getSourceContext(); this.world = declaringType.getResolvedTypeX().getWorld(); this.bcelObjectType = declaringType; unpackJavaAttributes(); unpackAjAttributes(world); } // ---- private void unpackJavaAttributes() { ExceptionTable exnTable = method.getExceptionTable(); checkedExceptions = (exnTable == null) ? UnresolvedType.NONE : UnresolvedType.forNames(exnTable.getExceptionNames()); LocalVariableTable varTable = method.getLocalVariableTable(); int len = getArity(); if (varTable == null) { this.parameterNames = Utility.makeArgNames(len); } else { UnresolvedType[] paramTypes = getParameterTypes(); String[] paramNames = new String[len]; int index = isStatic() ? 0 : 1; for (int i = 0; i < len; i++) { LocalVariable lv = varTable.getLocalVariable(index); if (lv == null) { paramNames[i] = "arg" + i; } else { paramNames[i] = lv.getName(); } index += paramTypes[i].getSize(); } this.parameterNames = paramNames; } } private void unpackAjAttributes(World world) { associatedShadowMunger = null; List as = BcelAttributes.readAjAttributes(getDeclaringType().getClassName(),method.getAttributes(), getSourceContext(world),world.getMessageHandler(),bcelObjectType.getWeaverVersionAttribute()); processAttributes(world, as); as = AtAjAttributes.readAj5MethodAttributes(method, this, world.resolve(getDeclaringType()), preResolvedPointcut,getSourceContext(world), world.getMessageHandler()); processAttributes(world,as); } private void processAttributes(World world, List as) { for (Iterator iter = as.iterator(); iter.hasNext();) { AjAttribute a = (AjAttribute) iter.next(); if (a instanceof AjAttribute.MethodDeclarationLineNumberAttribute) { declarationLineNumber = (AjAttribute.MethodDeclarationLineNumberAttribute)a; } else if (a instanceof AjAttribute.AdviceAttribute) { associatedShadowMunger = ((AjAttribute.AdviceAttribute)a).reify(this, world); // return; } else if (a instanceof AjAttribute.AjSynthetic) { isAjSynthetic = true; } else if (a instanceof AjAttribute.EffectiveSignatureAttribute) { //System.out.println("found effective: " + this); effectiveSignature = (AjAttribute.EffectiveSignatureAttribute)a; } else if (a instanceof AjAttribute.PointcutDeclarationAttribute) { // this is an @AspectJ annotated advice method, with pointcut pre-resolved by ajc preResolvedPointcut = ((AjAttribute.PointcutDeclarationAttribute)a).reify(); } else { throw new BCException("weird method attribute " + a); } } } public boolean isAjSynthetic() { return isAjSynthetic; // || getName().startsWith(NameMangler.PREFIX); } //FIXME ??? needs an isSynthetic method public ShadowMunger getAssociatedShadowMunger() { return associatedShadowMunger; } public AjAttribute.EffectiveSignatureAttribute getEffectiveSignature() { return effectiveSignature; } public boolean hasDeclarationLineNumberInfo() { return declarationLineNumber != null; } public int getDeclarationLineNumber() { if (declarationLineNumber != null) { return declarationLineNumber.getLineNumber(); } else { return -1; } } public int getDeclarationOffset() { if (declarationLineNumber != null) { return declarationLineNumber.getOffset(); } else { return -1; } } public ISourceLocation getSourceLocation() { ISourceLocation ret = super.getSourceLocation(); if ((ret == null || ret.getLine()==0) && hasDeclarationLineNumberInfo()) { // lets see if we can do better ISourceContext isc = getSourceContext(); if (isc !=null) ret = isc.makeSourceLocation(getDeclarationLineNumber(), getDeclarationOffset()); else ret = new SourceLocation(null,getDeclarationLineNumber()); } return ret; } public Kind getKind() { if (associatedShadowMunger != null) { return ADVICE; } else { return super.getKind(); } } public boolean hasAnnotation(UnresolvedType ofType) { ensureAnnotationTypesRetrieved(); for (Iterator iter = annotationTypes.iterator(); iter.hasNext();) { ResolvedType aType = (ResolvedType) iter.next(); if (aType.equals(ofType)) return true; } return false; } public AnnotationX[] getAnnotations() { ensureAnnotationTypesRetrieved(); return annotations; } public ResolvedType[] getAnnotationTypes() { ensureAnnotationTypesRetrieved(); ResolvedType[] ret = new ResolvedType[annotationTypes.size()]; annotationTypes.toArray(ret); return ret; } public void addAnnotation(AnnotationX annotation) { ensureAnnotationTypesRetrieved(); // Add it to the set of annotations int len = annotations.length; AnnotationX[] ret = new AnnotationX[len+1]; System.arraycopy(annotations, 0, ret, 0, len); ret[len] = annotation; annotations = ret; // Add it to the set of annotation types annotationTypes.add(UnresolvedType.forName(annotation.getTypeName()).resolve(world)); // FIXME asc looks like we are managing two 'bunches' of annotations, one // here and one in the real 'method' - should we reduce it to one layer? method.addAnnotation(annotation.getBcelAnnotation()); } private void ensureAnnotationTypesRetrieved() { if (annotationTypes == null || method.getAnnotations().length!=annotations.length) { // sometimes the list changes underneath us! Annotation annos[] = method.getAnnotations(); annotationTypes = new HashSet(); annotations = new AnnotationX[annos.length]; for (int i = 0; i < annos.length; i++) { Annotation annotation = annos[i]; ResolvedType rtx = world.resolve(UnresolvedType.forName(annotation.getTypeName())); annotationTypes.add(rtx); annotations[i] = new AnnotationX(annotation,world); } } } private boolean canBeParameterized = false; /** * A method can be parameterized if it has one or more generic * parameters. A generic parameter (type variable parameter) is * identified by the prefix "T" */ public boolean canBeParameterized() { unpackGenericSignature(); return canBeParameterized; } // genericized version of return and parameter types private boolean unpackedGenericSignature = false; private UnresolvedType genericReturnType = null; private UnresolvedType[] genericParameterTypes = null; public UnresolvedType[] getGenericParameterTypes() { unpackGenericSignature(); return genericParameterTypes; } public UnresolvedType getGenericReturnType() { unpackGenericSignature(); return genericReturnType; } private void unpackGenericSignature() { if (unpackedGenericSignature) return; unpackedGenericSignature = true; String gSig = method.getGenericSignature(); if (gSig != null) { Signature.MethodTypeSignature mSig = new GenericSignatureParser().parseAsMethodSignature(method.getGenericSignature()); if (mSig.formalTypeParameters.length > 0) { // generic method declaration canBeParameterized = true; } Signature.FormalTypeParameter[] parentFormals = bcelObjectType.getAllFormals(); Signature.FormalTypeParameter[] formals = new Signature.FormalTypeParameter[parentFormals.length + mSig.formalTypeParameters.length]; // put method formal in front of type formals for overriding in lookup System.arraycopy(mSig.formalTypeParameters,0,formals,0,mSig.formalTypeParameters.length); System.arraycopy(parentFormals,0,formals,mSig.formalTypeParameters.length,parentFormals.length); Signature.TypeSignature returnTypeSignature = mSig.returnType; genericReturnType = BcelGenericSignatureToTypeXConverter.typeSignature2TypeX( returnTypeSignature, formals, world); Signature.TypeSignature[] paramTypeSigs = mSig.parameters; genericParameterTypes = new UnresolvedType[paramTypeSigs.length]; for (int i = 0; i < paramTypeSigs.length; i++) { genericParameterTypes[i] = BcelGenericSignatureToTypeXConverter.typeSignature2TypeX( paramTypeSigs[i],formals,world); if (paramTypeSigs[i] instanceof TypeVariableSignature) { canBeParameterized = true; } } } else { genericReturnType = getReturnType(); genericParameterTypes = getParameterTypes(); } } }
108,448
Bug 108448 IllegalStateException: Undeclared type variable when hiding
null
resolved fixed
2c9ea11
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-08-31T11:42:29Z
2005-08-31T06:33:20Z
weaver/src/org/aspectj/weaver/bcel/BcelObjectType.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.bcel; import java.io.PrintStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import org.aspectj.apache.bcel.classfile.Attribute; import org.aspectj.apache.bcel.classfile.Field; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.apache.bcel.classfile.Method; import org.aspectj.apache.bcel.classfile.Signature; import org.aspectj.apache.bcel.classfile.annotation.Annotation; import org.aspectj.apache.bcel.classfile.annotation.ElementNameValuePair; import org.aspectj.apache.bcel.classfile.annotation.ElementValue; import org.aspectj.bridge.ISourceLocation; import org.aspectj.weaver.AbstractReferenceTypeDelegate; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.AnnotationX; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ReferenceType; import org.aspectj.weaver.ReferenceTypeDelegate; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedPointcutDefinition; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.TypeVariable; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.WeaverStateInfo; import org.aspectj.weaver.patterns.PerClause; // ??? exposed for testing public class BcelObjectType extends AbstractReferenceTypeDelegate { private JavaClass javaClass; private boolean isObject = false; // set upon construction private LazyClassGen lazyClassGen = null; // set lazily if it's an aspect // lazy, for no particular reason I can discern private ResolvedType[] interfaces = null; private ResolvedType superClass = null; private ResolvedMember[] fields = null; private ResolvedMember[] methods = null; private ResolvedType[] annotationTypes = null; private AnnotationX[] annotations = null; private TypeVariable[] typeVars = null; // track unpackAttribute. In some case (per clause inheritance) we encounter // unpacked state when calling getPerClause // this whole thing would require more clean up (AV) private boolean isUnpacked = false; // strangely non-lazy private ResolvedPointcutDefinition[] pointcuts = null; private PerClause perClause = null; private WeaverStateInfo weaverState = null; private AjAttribute.WeaverVersionInfo wvInfo = AjAttribute.WeaverVersionInfo.UNKNOWN; private List typeMungers = Collections.EMPTY_LIST; private List declares = Collections.EMPTY_LIST; private ResolvedMember[] privilegedAccess = null; private boolean discoveredWhetherAnnotationStyle = false; private boolean isAnnotationStyleAspect = false;// set upon construction private boolean isCodeStyleAspect = false; // not redundant with field above! // TODO asc need soon but not just yet... private boolean haveLookedForDeclaredSignature = false; private String declaredSignature = null; private boolean isGenericType = false; public Collection getTypeMungers() { return typeMungers; } public Collection getDeclares() { return declares; } public Collection getPrivilegedAccesses() { if (privilegedAccess == null) return Collections.EMPTY_LIST; return Arrays.asList(privilegedAccess); } // IMPORTANT! THIS DOESN'T do real work on the java class, just stores it away. BcelObjectType(ReferenceType resolvedTypeX, JavaClass javaClass, boolean exposedToWeaver) { super(resolvedTypeX, exposedToWeaver); this.javaClass = javaClass; //ATAJ: set the delegate right now for @AJ poincut, else it is done too late to lookup // @AJ pc refs annotation in class hierarchy resolvedTypeX.setDelegate(this); if (resolvedTypeX.getSourceContext() == null) { resolvedTypeX.setSourceContext(new BcelSourceContext(this)); } // this should only ever be java.lang.Object which is // the only class in Java-1.4 with no superclasses isObject = (javaClass.getSuperclassNameIndex() == 0); unpackAspectAttributes(); } // repeat initialization public void setJavaClass(JavaClass newclass) { this.javaClass = newclass; resetState(); } public TypeVariable[] getTypeVariables() { if (!isGeneric()) return new TypeVariable[0]; if (typeVars == null) { Signature.ClassSignature classSig = javaClass.getGenericClassTypeSignature(); typeVars = new TypeVariable[classSig.formalTypeParameters.length]; for (int i = 0; i < typeVars.length; i++) { Signature.FormalTypeParameter ftp = classSig.formalTypeParameters[i]; typeVars[i] = BcelGenericSignatureToTypeXConverter.formalTypeParameter2TypeVariable( ftp, classSig.formalTypeParameters, getResolvedTypeX().getWorld()); } } return typeVars; } public int getModifiers() { return javaClass.getAccessFlags(); } /** * Must take into account generic signature */ public ResolvedType getSuperclass() { if (isObject) return null; unpackGenericSignature(); if (superClass == null) { superClass = getResolvedTypeX().getWorld().resolve(UnresolvedType.forName(javaClass.getSuperclassName())); } return superClass; } /** * Retrieves the declared interfaces - this allows for the generic signature on a type. If specified * then the generic signature is used to work out the types - this gets around the results of * erasure when the class was originally compiled. */ public ResolvedType[] getDeclaredInterfaces() { unpackGenericSignature(); if (interfaces == null) { String[] ifaceNames = javaClass.getInterfaceNames(); interfaces = new ResolvedType[ifaceNames.length]; for (int i = 0, len = ifaceNames.length; i < len; i++) { interfaces[i] = getResolvedTypeX().getWorld().resolve(UnresolvedType.forName(ifaceNames[i])); } } return interfaces; } public ResolvedMember[] getDeclaredMethods() { unpackGenericSignature(); if (methods == null) { Method[] ms = javaClass.getMethods(); ResolvedMember[] ret = new ResolvedMember[ms.length]; for (int i = ms.length - 1; i >= 0; i--) { ret[i] = new BcelMethod(this, ms[i]); } methods = ret; } return methods; } public ResolvedMember[] getDeclaredFields() { unpackGenericSignature(); if (fields == null) { Field[] fs = javaClass.getFields(); ResolvedMember[] ret = new ResolvedMember[fs.length]; for (int i = 0, len = fs.length; i < len; i++) { ret[i] = new BcelField(this, fs[i]); } fields = ret; } return fields; } // ---- // fun based on the aj attributes public ResolvedMember[] getDeclaredPointcuts() { return pointcuts; } //??? method only used for testing public void addPointcutDefinition(ResolvedPointcutDefinition d) { int len = pointcuts.length; ResolvedPointcutDefinition[] ret = new ResolvedPointcutDefinition[len+1]; System.arraycopy(pointcuts, 0, ret, 0, len); ret[len] = d; pointcuts = ret; } public boolean isAspect() { return perClause != null; } /** * Check if the type is an @AJ aspect (no matter if used from an LTW point of view). * Such aspects are annotated with @Aspect * * @return true for @AJ aspect */ public boolean isAnnotationStyleAspect() { if (!discoveredWhetherAnnotationStyle) { discoveredWhetherAnnotationStyle = true; isAnnotationStyleAspect = !isCodeStyleAspect && hasAnnotation(AjcMemberMaker.ASPECT_ANNOTATION); } return isAnnotationStyleAspect; } private void unpackAspectAttributes() { isUnpacked = true; List pointcuts = new ArrayList(); typeMungers = new ArrayList(); declares = new ArrayList(); // Pass in empty list that can store things for readAj5 to process List l = BcelAttributes.readAjAttributes(javaClass.getClassName(),javaClass.getAttributes(), getResolvedTypeX().getSourceContext(),getResolvedTypeX().getWorld().getMessageHandler(),AjAttribute.WeaverVersionInfo.UNKNOWN); processAttributes(l,pointcuts,false); l = AtAjAttributes.readAj5ClassAttributes(javaClass, getResolvedTypeX(), getResolvedTypeX().getSourceContext(), getResolvedTypeX().getWorld().getMessageHandler(),isCodeStyleAspect); processAttributes(l,pointcuts,true); this.pointcuts = (ResolvedPointcutDefinition[]) pointcuts.toArray(new ResolvedPointcutDefinition[pointcuts.size()]); } private void processAttributes(List attributeList, List pointcuts, boolean fromAnnotations) { for (Iterator iter = attributeList.iterator(); iter.hasNext();) { AjAttribute a = (AjAttribute) iter.next(); //System.err.println("unpacking: " + this + " and " + a); if (a instanceof AjAttribute.Aspect) { perClause = ((AjAttribute.Aspect)a).reify(this.getResolvedTypeX()); if (!fromAnnotations) isCodeStyleAspect = true; } else if (a instanceof AjAttribute.PointcutDeclarationAttribute) { pointcuts.add(((AjAttribute.PointcutDeclarationAttribute)a).reify()); } else if (a instanceof AjAttribute.WeaverState) { weaverState = ((AjAttribute.WeaverState)a).reify(); } else if (a instanceof AjAttribute.TypeMunger) { typeMungers.add(((AjAttribute.TypeMunger)a).reify(getResolvedTypeX().getWorld(), getResolvedTypeX())); } else if (a instanceof AjAttribute.DeclareAttribute) { declares.add(((AjAttribute.DeclareAttribute)a).getDeclare()); } else if (a instanceof AjAttribute.PrivilegedAttribute) { privilegedAccess = ((AjAttribute.PrivilegedAttribute)a).getAccessedMembers(); } else if (a instanceof AjAttribute.SourceContextAttribute) { if (getResolvedTypeX().getSourceContext() instanceof BcelSourceContext) { ((BcelSourceContext)getResolvedTypeX().getSourceContext()).addAttributeInfo((AjAttribute.SourceContextAttribute)a); } } else if (a instanceof AjAttribute.WeaverVersionInfo) { wvInfo = (AjAttribute.WeaverVersionInfo)a; // Set the weaver version used to build this type } else { throw new BCException("bad attribute " + a); } } } public PerClause getPerClause() { if (!isUnpacked) { unpackAspectAttributes(); } return perClause; } JavaClass getJavaClass() { return javaClass; } public void resetState() { this.interfaces = null; this.superClass = null; this.fields = null; this.methods = null; this.pointcuts = null; this.perClause = null; this.weaverState = null; this.lazyClassGen = null; this.annotations = null; this.annotationTypes = null; isObject = (javaClass.getSuperclassNameIndex() == 0); unpackAspectAttributes(); discoveredWhetherAnnotationStyle = false; isAnnotationStyleAspect=false; } public void finishedWith() { // memory usage experiments.... // this.interfaces = null; // this.superClass = null; // this.fields = null; // this.methods = null; // this.pointcuts = null; // this.perClause = null; // this.weaverState = null; // this.lazyClassGen = null; // this next line frees up memory, but need to understand incremental implications // before leaving it in. // getResolvedTypeX().setSourceContext(null); } public WeaverStateInfo getWeaverState() { return weaverState; } void setWeaverState(WeaverStateInfo weaverState) { this.weaverState = weaverState; } public void printWackyStuff(PrintStream out) { if (typeMungers.size() > 0) { out.println(" TypeMungers: " + typeMungers); } if (declares.size() > 0) { out.println(" declares: " + declares); } } /** * Return the lazyClassGen associated with this type. For aspect types, this * value will be cached, since it is used to inline advice. For non-aspect * types, this lazyClassGen is always newly constructed. */ public LazyClassGen getLazyClassGen() { LazyClassGen ret = lazyClassGen; if (ret == null) { //System.err.println("creating lazy class gen for: " + this); ret = new LazyClassGen(this); //ret.print(System.err); //System.err.println("made LCG from : " + this.getJavaClass().getSuperclassName() ); if (isAspect()) { lazyClassGen = ret; } } return ret; } public boolean isInterface() { return javaClass.isInterface(); } public boolean isEnum() { return javaClass.isEnum(); } public boolean isAnnotation() { return javaClass.isAnnotation(); } public void addAnnotation(AnnotationX annotation) { // Add it to the set of annotations int len = annotations.length; AnnotationX[] ret = new AnnotationX[len+1]; System.arraycopy(annotations, 0, ret, 0, len); ret[len] = annotation; annotations = ret; // Add it to the set of annotation types len = annotationTypes.length; ResolvedType[] ret2 = new ResolvedType[len+1]; System.arraycopy(annotationTypes,0,ret2,0,len); ret2[len] = getResolvedTypeX().getWorld().resolve(UnresolvedType.forName(annotation.getTypeName())); annotationTypes = ret2; } public boolean isAnnotationWithRuntimeRetention() { if (!isAnnotation()) { return false; } else { Annotation[] annotationsOnThisType = javaClass.getAnnotations(); for (int i = 0; i < annotationsOnThisType.length; i++) { Annotation a = annotationsOnThisType[i]; if (a.getTypeName().equals(UnresolvedType.AT_RETENTION.getName())) { List values = a.getValues(); boolean isRuntime = false; for (Iterator it = values.iterator(); it.hasNext();) { ElementNameValuePair element = (ElementNameValuePair) it.next(); ElementValue v = element.getValue(); isRuntime = v.stringifyValue().equals("RUNTIME"); } return isRuntime; } } } return false; } public boolean isSynthetic() { return getResolvedTypeX().isSynthetic(); } public ISourceLocation getSourceLocation() { return getResolvedTypeX().getSourceContext().makeSourceLocation(0, 0); //FIXME ??? we can do better than this } public AjAttribute.WeaverVersionInfo getWeaverVersionAttribute() { return wvInfo; } public void addParent(ResolvedType newParent) { if (newParent.isClass()) { superClass = newParent; } else { ResolvedType[] oldInterfaceNames = getDeclaredInterfaces(); int len = oldInterfaceNames.length; ResolvedType[] newInterfaceNames = new ResolvedType[len+1]; System.arraycopy(oldInterfaceNames, 0, newInterfaceNames, 0, len); newInterfaceNames[len] = newParent; interfaces = newInterfaceNames; } //System.err.println("javaClass: " + Arrays.asList(javaClass.getInterfaceNames()) + " super " + javaClass.getSuperclassName()); //if (lazyClassGen != null) lazyClassGen.print(); } public boolean hasAnnotation(UnresolvedType ofType) { ensureAnnotationTypesRetrieved(); for (int i = 0; i < annotationTypes.length; i++) { ResolvedType annX = annotationTypes[i]; if (annX.equals(ofType)) return true; } return false; } private void ensureAnnotationTypesRetrieved() { if (annotationTypes == null) { Annotation annos[] = javaClass.getAnnotations(); annotationTypes = new ResolvedType[annos.length]; annotations = new AnnotationX[annos.length]; for (int i = 0; i < annos.length; i++) { Annotation annotation = annos[i]; ResolvedType rtx = getResolvedTypeX().getWorld().resolve(UnresolvedType.forName(annotation.getTypeName())); annotationTypes[i] = rtx; annotations[i] = new AnnotationX(annotation,getResolvedTypeX().getWorld()); } } } public ResolvedType[] getAnnotationTypes() { ensureAnnotationTypesRetrieved(); return annotationTypes; } /** * Releases annotations wrapped in an annotationX */ public AnnotationX[] getAnnotations() { ensureAnnotationTypesRetrieved(); return annotations; } public String getDeclaredGenericSignature() { if (!haveLookedForDeclaredSignature) { haveLookedForDeclaredSignature = true; Attribute[] as = javaClass.getAttributes(); for (int i = 0; i < as.length && declaredSignature==null; i++) { Attribute attribute = as[i]; if (attribute instanceof Signature) declaredSignature = ((Signature)attribute).getSignature(); } if (declaredSignature!=null) isGenericType= (declaredSignature.charAt(0)=='<'); } return declaredSignature; } Signature.ClassSignature getGenericClassTypeSignature() { return javaClass.getGenericClassTypeSignature(); } private boolean genericSignatureUnpacked = false; private Signature.FormalTypeParameter[] formalsForResolution = null; private void unpackGenericSignature() { if (genericSignatureUnpacked) return; genericSignatureUnpacked = true; Signature.ClassSignature cSig = getGenericClassTypeSignature(); if (cSig != null) { formalsForResolution = cSig.formalTypeParameters; if (isNestedClass()) { // we have to find any type variables from the outer type before proceeding with resolution. Signature.FormalTypeParameter[] extraFormals = getFormalTypeParametersFromOuterClass(); if (extraFormals.length > 0) { List allFormals = new ArrayList(); for (int i = 0; i < formalsForResolution.length; i++) { allFormals.add(formalsForResolution[i]); } for (int i = 0; i < extraFormals.length; i++) { allFormals.add(extraFormals[i]); } formalsForResolution = new Signature.FormalTypeParameter[allFormals.size()]; allFormals.toArray(formalsForResolution); } } Signature.ClassTypeSignature superSig = cSig.superclassSignature; this.superClass = BcelGenericSignatureToTypeXConverter.classTypeSignature2TypeX( superSig, formalsForResolution, getResolvedTypeX().getWorld()); this.interfaces = new ResolvedType[cSig.superInterfaceSignatures.length]; for (int i = 0; i < cSig.superInterfaceSignatures.length; i++) { this.interfaces[i] = BcelGenericSignatureToTypeXConverter.classTypeSignature2TypeX( cSig.superInterfaceSignatures[i], formalsForResolution, getResolvedTypeX().getWorld()); } } if (isGeneric()) { // update resolved typex to point at generic type not raw type. ReferenceType genericType = (ReferenceType) this.resolvedTypeX.getGenericType(); genericType.setSourceContext(this.resolvedTypeX.getSourceContext()); genericType.setStartPos(this.resolvedTypeX.getStartPos()); this.resolvedTypeX = genericType; } } public Signature.FormalTypeParameter[] getAllFormals() { unpackGenericSignature(); if (formalsForResolution == null) { return new Signature.FormalTypeParameter[0]; } else { return formalsForResolution; } } private boolean isNestedClass() { return javaClass.getClassName().indexOf('$') != -1; } private ReferenceType getOuterClass() { if (!isNestedClass()) throw new IllegalStateException("Can't get the outer class of a non-nested type"); int lastDollar = javaClass.getClassName().lastIndexOf('$'); String superClassName = javaClass.getClassName().substring(0,lastDollar); UnresolvedType outer = UnresolvedType.forName(superClassName); return (ReferenceType) outer.resolve(getResolvedTypeX().getWorld()); } private Signature.FormalTypeParameter[] getFormalTypeParametersFromOuterClass() { ReferenceType outer = getOuterClass(); ReferenceTypeDelegate outerDelegate = outer.getDelegate(); if (!(outerDelegate instanceof BcelObjectType)) { throw new IllegalStateException("How come we're in BcelObjectType resolving an inner type of something that is NOT a BcelObjectType??"); } BcelObjectType outerObjectType = (BcelObjectType) outerDelegate; Signature.ClassSignature outerSig = outerObjectType.getGenericClassTypeSignature(); if (outerSig != null) { return outerSig.formalTypeParameters; } else { return new Signature.FormalTypeParameter[0]; } } private void ensureGenericInfoProcessed() { getDeclaredGenericSignature();} public boolean isGeneric() { ensureGenericInfoProcessed(); return isGenericType; } public String toString() { return (javaClass==null?"BcelObjectType":"BcelObjectTypeFor:"+javaClass.getClassName()); } }
108,448
Bug 108448 IllegalStateException: Undeclared type variable when hiding
null
resolved fixed
2c9ea11
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-08-31T11:42:29Z
2005-08-31T06:33:20Z
weaver/testsrc/org/aspectj/weaver/bcel/BcelGenericSignatureToTypeXTestCase.java
/* ******************************************************************* * Copyright (c) 2005 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * Adrian Colyer Initial implementation * ******************************************************************/ package org.aspectj.weaver.bcel; import junit.framework.TestCase; import org.aspectj.apache.bcel.Repository; import org.aspectj.apache.bcel.classfile.GenericSignatureParser; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.apache.bcel.classfile.Signature; import org.aspectj.weaver.UnresolvedType; /** * @author colyer * */ public class BcelGenericSignatureToTypeXTestCase extends TestCase { public void testEnumFromHell() { BcelWorld world = new BcelWorld(); JavaClass javaLangEnum = Repository.lookupClass("java/lang/Enum"); Signature.ClassSignature cSig = javaLangEnum.getGenericClassTypeSignature(); UnresolvedType superclass = BcelGenericSignatureToTypeXConverter.classTypeSignature2TypeX( cSig.superclassSignature, cSig.formalTypeParameters, world ); assertEquals("Ljava/lang/Object;",superclass.getSignature()); assertEquals("2 superinterfaces",2,cSig.superInterfaceSignatures.length); UnresolvedType comparable = BcelGenericSignatureToTypeXConverter.classTypeSignature2TypeX( cSig.superInterfaceSignatures[0], cSig.formalTypeParameters, world ); assertEquals("Pjava/lang/Comparable<TE;>;",comparable.getSignature()); UnresolvedType serializable = BcelGenericSignatureToTypeXConverter.classTypeSignature2TypeX( cSig.superInterfaceSignatures[1], cSig.formalTypeParameters, world ); assertEquals("Ljava/io/Serializable;",serializable.getSignature()); } public void testColonColon() { BcelWorld world = new BcelWorld(); Signature.ClassSignature cSig = new GenericSignatureParser().parseAsClassSignature("<T::Ljava/io/Serializable;>Ljava/lang/Object;Ljava/lang/Comparable<TT;>;"); UnresolvedType resolved = BcelGenericSignatureToTypeXConverter.classTypeSignature2TypeX( cSig.superclassSignature, cSig.formalTypeParameters, world); assertEquals("Ljava/lang/Object;",resolved.getSignature()); UnresolvedType resolvedInt = BcelGenericSignatureToTypeXConverter.classTypeSignature2TypeX( cSig.superInterfaceSignatures[0], cSig.formalTypeParameters, world); } }
95,992
Bug 95992 Problems resolving type name inside generic class
ajc reports an error when compiling the following code: interface Base<T> { static interface Inner { } } class Test<T extends Test.InnerTest> implements Base<T> { static class InnerTest implements Inner { } } $ ajc -1.5 Test.java Test.java:14 [error] Inner cannot be resolved to a type static class InnerTest implements Inner { Sun's javac compiles it without any error. The error can be avoided by simply writing "Base.Inner" instead of just "Inner". Also, it compiles fine if the constraint "extends Test.InnerTest" is left away.
resolved fixed
b953c03
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-08-31T13:48:16Z
2005-05-19T19:13:20Z
tests/src/org/aspectj/systemtest/ajc150/Ajc150Tests.java
/******************************************************************************* * Copyright (c) 2004 IBM * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Andy Clement - initial API and implementation *******************************************************************************/ package org.aspectj.systemtest.ajc150; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import junit.framework.Test; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.apache.bcel.classfile.Method; import org.aspectj.apache.bcel.util.ClassPath; import org.aspectj.apache.bcel.util.SyntheticRepository; import org.aspectj.asm.AsmManager; import org.aspectj.testing.XMLBasedAjcTestCase; import org.aspectj.util.LangUtil; /** * These are tests that will run on Java 1.4 and use the old harness format for test specification. */ public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase { public static Test suite() { return XMLBasedAjcTestCase.loadSuite(Ajc150Tests.class); } protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml"); } public void test_typeProcessingOrderWhenDeclareParents() { runTest("Order of types passed to compiler determines weaving behavior"); } public void test_aroundMethod() { runTest("method called around in class"); } public void test_aroundMethodAspect() { runTest("method called around in aspect"); } public void test_ambiguousBindingsDetection() { runTest("Various kinds of ambiguous bindings"); } public void test_ambiguousArgsDetection() { runTest("ambiguous args"); } public void testIncorrectExceptionTableWhenBreakInMethod_pr78021() { runTest("Injecting exception into while loop with break statement causes catch block to be ignored"); } public void testIncorrectExceptionTableWhenReturnInMethod_pr79554() { runTest("Return in try-block disables catch-block if final-block is present"); } public void testMissingDebugInfoForGeneratedMethods_pr82570() throws ClassNotFoundException { runTest("Weaved code does not include debug lines"); boolean f = false; JavaClass jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1"); Method[] meths = jc.getMethods(); for (int i = 0; i < meths.length; i++) { Method method = meths[i]; if (f) System.err.println("Line number table for "+method.getName()+method.getSignature()+" = "+method.getLineNumberTable()); assertTrue("Didn't find a line number table for method "+method.getName()+method.getSignature(), method.getLineNumberTable()!=null); } // This test would determine the info isn't there if you pass -g:none ... // cR = ajc(baseDir,new String[]{"PR82570_1.java","-g:none"}); // assertTrue("Expected no compile problem:"+cR,!cR.hasErrorMessages()); // System.err.println(cR.getStandardError()); // jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1"); // meths = jc.getMethods(); // for (int i = 0; i < meths.length; i++) { // Method method = meths[i]; // assertTrue("Found a line number table for method "+method.getName(), // method.getLineNumberTable()==null); // } } public void testCanOverrideProtectedMethodsViaITDandDecp_pr83303() { runTest("compiler error when mixing inheritance, overriding and polymorphism"); } public void testPerTypeWithinMissesNamedInnerTypes() { runTest("pertypewithin() handing of inner classes (1)"); } public void testPerTypeWithinMissesAnonymousInnerTypes() { runTest("pertypewithin() handing of inner classes (2)"); } public void testPerTypeWithinIncorrectlyMatchingInterfaces() { runTest("pertypewithin({interface}) illegal field modifier"); } public void test051_arrayCloningInJava5() { runTest("AJC possible bug with static nested classes"); } public void testBadASMforEnums() throws IOException { runTest("bad asm for enums"); if (LangUtil.is15VMOrGreater()) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintWriter pw = new PrintWriter(baos); AsmManager.dumptree(pw,AsmManager.getDefault().getHierarchy().getRoot(),0); pw.flush(); String tree = baos.toString(); assertTrue("Expected 'Red [enumvalue]' somewhere in here:"+tree,tree.indexOf("Red [enumvalue]")!=-1); } } public void npeOnTypeNotFound() { runTest("structure model npe on type not found"); } public void testNoRuntimeExceptionSoftening() { runTest("declare soft of runtime exception"); } public void testRuntimeNoSoftenWithHandler() { runTest("declare soft w. catch block"); } public void testSyntaxError() { runTest("invalid cons syntax"); } public void testVarargsInConsBug() { runTest("varargs in constructor sig"); } public void testAspectpathdirs() { runTest("dirs on aspectpath"); } public void testIntroSample() { runTest("introduction sample"); } public void testPTWInterface() { runTest("pertypewithin({interface}) illegal field modifier"); } public void testEnumCalledEnumEtc() { runTest("enum called Enum, annotation called Annotation, etc"); } public void testInternalCompilerError_pr86832() { runTest("Internal compiler error"); } public void testCloneMethod_pr83311() { runTest("overriding/polymorphism error on interface method introduction"); } /** * IfPointcut.findResidueInternal() was modified to make this test complete in a short amount * of time - if you see it hanging, someone has messed with the optimization. */ public void testIfEvaluationExplosion_pr94086() { runTest("Exploding compile time with if() statements in pointcut"); } public void testReflectNPE_pr94167() {runTest("NPE in reflect implementation");} public void testStaticImports_pr84260() {runTest("static import failures");} public void testGenerics_pr99089() {runTest("ArrayIndexOutOfBoundsException - Generics in privileged aspects");} public void testGenerics_pr95993() {runTest("NPE at ClassScope.java:660 when compiling generic class");} public void testItdGenerics_pr99228() {runTest("ITD of a field into a generic class");} public void testItdGenerics_pr98320() {runTest("intertype with nested generic type");} public void testItdGenerics_pr100227() {runTest("inner class with generic enclosing class");} public void testItdGenerics_pr100260() {runTest("methods inherited from a generic parent");} public void testSyntaxErrorNPE_pr103266() {runTest("NPE on syntax error");} public void testIllegalStateExceptionOnNestedParameterizedType_pr106634() { runTest("IllegalStateException unpacking signature of nested parameterized type"); } public void testParseErrorOnAnnotationStarPlusPattern() { runTest("(@Foo *)+ type pattern parse error"); } public void test_pr106130_tooManyLocals() { runTest("test weaving with > 256 locals"); } public void testMissingNamePattern_pr106461() { runTest("missing name pattern"); } public void testMissingNamePattern_pr107059() { runTest("parser crashes on call(void (@a *)(..)"); } public void testIntermediateAnnotationMatching() { runTest("intermediate annotation matching"); } public void testBadRuntimeTestGeneration() { runTest("target(@Foo *)"); } public void testErrorMessageOnITDWithTypePatterns() { runTest("clear error message on itd with type pattern"); } public void testAjKeywordsAsIdentifiers() { runTest("before and after are valid identifiers in classes"); } public void testAjKeywordsAsIdentifiers2() { runTest("before and after are valid identifiers in classes, part 2"); } public void testNoBeforeReturningAdvice() { runTest("before returning advice not allowed!"); } public void testDetectVoidFieldType() { runTest("void field type in pointcut expression"); } public void testPointcutOverriding() { runTest("overriding final pointcut from super-aspect"); } public void testAtSuppressWarnings() { runTest("@SuppressWarnings should suppress"); } public void testDEOWWithBindingPointcut() { runTest("declare warning : foo(str) : ...;"); } public void testAroundAdviceAndInterfaceInitializer() { runTest("around advice on interface initializer"); } public void testGoodErrorMessageOnUnmatchedMemberSyntax() { runTest("good error message for unmatched member syntax"); } public void testITDWithNoExceptionAndIntermediary() { runTest("itd override with no exception clause"); } public void testAnonymousInnerClasses() { runTest("anonymous inner classes"); } public void testMultipleAnonymousInnerClasses() { runTest("multiple anonymous inner classes"); } public void testPrivilegedMethodAccessorsGetRightExceptions_pr82989() { runTest("Compiler error due to a wrong exception check in try blocks"); } public void testAnonymousInnerClassWithMethodReturningTypeParameter_pr107898() { runTest("anonymous inner class with method returning type parameter"); } public void testMatchingOfObjectArray() { runTest("matching against Object[]"); } public void testMultipleAnonymousInnerClasses_pr108104() { runTest("multiple anonymous inner classes 2"); } public void testSignatureMatchingInMultipleOverrideScenario() { runTest("signature matching in override scenario"); } public void testWildcardAnnotationMatching_pr108245() { runTest("wildcard annotation matching - pr108245"); } public void testInnerTypesAndTypeVariables() { runTest("inner types and type variables"); } public void testAtAfterThrowingWithNoFormal() { runTest("@AfterThrowing with no formal specified"); } public void testParameterizedVarArgsMatch() { runTest("varargs with type variable"); } public void testFieldAccessInsideITDM() { runTest("itd field access inside itd method"); } public void testTypeVarWithTypeVarBound() { runTest("type variable with type variable bound"); } public void testEnumSwitchInITD() { runTest("switch on enum inside ITD method"); } // helper methods..... public SyntheticRepository createRepos(File cpentry) { ClassPath cp = new ClassPath(cpentry+File.pathSeparator+System.getProperty("java.class.path")); return SyntheticRepository.getInstance(cp); } protected JavaClass getClassFrom(File where,String clazzname) throws ClassNotFoundException { SyntheticRepository repos = createRepos(where); return repos.loadClass(clazzname); } }
104,024
Bug 104024 combining varargs and inner classes crashes the parser
class Outer { public class Inner {} } public class Bug { public void varargs(Object... varargs) {} public void test() { Outer.Inner inner = new Outer().new Inner(); varargs(inner); // works varargs(new Outer().new Inner()); // crashes } }
resolved fixed
f2af562
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-08-31T14:15:45Z
2005-07-15T15:06:40Z
tests/src/org/aspectj/systemtest/ajc150/Ajc150Tests.java
/******************************************************************************* * Copyright (c) 2004 IBM * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Andy Clement - initial API and implementation *******************************************************************************/ package org.aspectj.systemtest.ajc150; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import junit.framework.Test; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.apache.bcel.classfile.Method; import org.aspectj.apache.bcel.util.ClassPath; import org.aspectj.apache.bcel.util.SyntheticRepository; import org.aspectj.asm.AsmManager; import org.aspectj.testing.XMLBasedAjcTestCase; import org.aspectj.util.LangUtil; /** * These are tests that will run on Java 1.4 and use the old harness format for test specification. */ public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase { public static Test suite() { return XMLBasedAjcTestCase.loadSuite(Ajc150Tests.class); } protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml"); } public void test_typeProcessingOrderWhenDeclareParents() { runTest("Order of types passed to compiler determines weaving behavior"); } public void test_aroundMethod() { runTest("method called around in class"); } public void test_aroundMethodAspect() { runTest("method called around in aspect"); } public void test_ambiguousBindingsDetection() { runTest("Various kinds of ambiguous bindings"); } public void test_ambiguousArgsDetection() { runTest("ambiguous args"); } public void testIncorrectExceptionTableWhenBreakInMethod_pr78021() { runTest("Injecting exception into while loop with break statement causes catch block to be ignored"); } public void testIncorrectExceptionTableWhenReturnInMethod_pr79554() { runTest("Return in try-block disables catch-block if final-block is present"); } public void testMissingDebugInfoForGeneratedMethods_pr82570() throws ClassNotFoundException { runTest("Weaved code does not include debug lines"); boolean f = false; JavaClass jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1"); Method[] meths = jc.getMethods(); for (int i = 0; i < meths.length; i++) { Method method = meths[i]; if (f) System.err.println("Line number table for "+method.getName()+method.getSignature()+" = "+method.getLineNumberTable()); assertTrue("Didn't find a line number table for method "+method.getName()+method.getSignature(), method.getLineNumberTable()!=null); } // This test would determine the info isn't there if you pass -g:none ... // cR = ajc(baseDir,new String[]{"PR82570_1.java","-g:none"}); // assertTrue("Expected no compile problem:"+cR,!cR.hasErrorMessages()); // System.err.println(cR.getStandardError()); // jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1"); // meths = jc.getMethods(); // for (int i = 0; i < meths.length; i++) { // Method method = meths[i]; // assertTrue("Found a line number table for method "+method.getName(), // method.getLineNumberTable()==null); // } } public void testCanOverrideProtectedMethodsViaITDandDecp_pr83303() { runTest("compiler error when mixing inheritance, overriding and polymorphism"); } public void testPerTypeWithinMissesNamedInnerTypes() { runTest("pertypewithin() handing of inner classes (1)"); } public void testPerTypeWithinMissesAnonymousInnerTypes() { runTest("pertypewithin() handing of inner classes (2)"); } public void testPerTypeWithinIncorrectlyMatchingInterfaces() { runTest("pertypewithin({interface}) illegal field modifier"); } public void test051_arrayCloningInJava5() { runTest("AJC possible bug with static nested classes"); } public void testBadASMforEnums() throws IOException { runTest("bad asm for enums"); if (LangUtil.is15VMOrGreater()) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintWriter pw = new PrintWriter(baos); AsmManager.dumptree(pw,AsmManager.getDefault().getHierarchy().getRoot(),0); pw.flush(); String tree = baos.toString(); assertTrue("Expected 'Red [enumvalue]' somewhere in here:"+tree,tree.indexOf("Red [enumvalue]")!=-1); } } public void npeOnTypeNotFound() { runTest("structure model npe on type not found"); } public void testNoRuntimeExceptionSoftening() { runTest("declare soft of runtime exception"); } public void testRuntimeNoSoftenWithHandler() { runTest("declare soft w. catch block"); } public void testSyntaxError() { runTest("invalid cons syntax"); } public void testVarargsInConsBug() { runTest("varargs in constructor sig"); } public void testAspectpathdirs() { runTest("dirs on aspectpath"); } public void testIntroSample() { runTest("introduction sample"); } public void testPTWInterface() { runTest("pertypewithin({interface}) illegal field modifier"); } public void testEnumCalledEnumEtc() { runTest("enum called Enum, annotation called Annotation, etc"); } public void testInternalCompilerError_pr86832() { runTest("Internal compiler error"); } public void testCloneMethod_pr83311() { runTest("overriding/polymorphism error on interface method introduction"); } /** * IfPointcut.findResidueInternal() was modified to make this test complete in a short amount * of time - if you see it hanging, someone has messed with the optimization. */ public void testIfEvaluationExplosion_pr94086() { runTest("Exploding compile time with if() statements in pointcut"); } public void testReflectNPE_pr94167() {runTest("NPE in reflect implementation");} public void testStaticImports_pr84260() {runTest("static import failures");} public void testGenerics_pr99089() {runTest("ArrayIndexOutOfBoundsException - Generics in privileged aspects");} public void testGenerics_pr95993() {runTest("NPE at ClassScope.java:660 when compiling generic class");} public void testItdGenerics_pr99228() {runTest("ITD of a field into a generic class");} public void testItdGenerics_pr98320() {runTest("intertype with nested generic type");} public void testItdGenerics_pr100227() {runTest("inner class with generic enclosing class");} public void testItdGenerics_pr100260() {runTest("methods inherited from a generic parent");} public void testSyntaxErrorNPE_pr103266() {runTest("NPE on syntax error");} public void testIllegalStateExceptionOnNestedParameterizedType_pr106634() { runTest("IllegalStateException unpacking signature of nested parameterized type"); } public void testParseErrorOnAnnotationStarPlusPattern() { runTest("(@Foo *)+ type pattern parse error"); } public void test_pr106130_tooManyLocals() { runTest("test weaving with > 256 locals"); } public void testMissingNamePattern_pr106461() { runTest("missing name pattern"); } public void testMissingNamePattern_pr107059() { runTest("parser crashes on call(void (@a *)(..)"); } public void testIntermediateAnnotationMatching() { runTest("intermediate annotation matching"); } public void testBadRuntimeTestGeneration() { runTest("target(@Foo *)"); } public void testErrorMessageOnITDWithTypePatterns() { runTest("clear error message on itd with type pattern"); } public void testAjKeywordsAsIdentifiers() { runTest("before and after are valid identifiers in classes"); } public void testAjKeywordsAsIdentifiers2() { runTest("before and after are valid identifiers in classes, part 2"); } public void testNoBeforeReturningAdvice() { runTest("before returning advice not allowed!"); } public void testDetectVoidFieldType() { runTest("void field type in pointcut expression"); } public void testPointcutOverriding() { runTest("overriding final pointcut from super-aspect"); } public void testAtSuppressWarnings() { runTest("@SuppressWarnings should suppress"); } public void testDEOWWithBindingPointcut() { runTest("declare warning : foo(str) : ...;"); } public void testAroundAdviceAndInterfaceInitializer() { runTest("around advice on interface initializer"); } public void testGoodErrorMessageOnUnmatchedMemberSyntax() { runTest("good error message for unmatched member syntax"); } public void testITDWithNoExceptionAndIntermediary() { runTest("itd override with no exception clause"); } public void testAnonymousInnerClasses() { runTest("anonymous inner classes"); } public void testMultipleAnonymousInnerClasses() { runTest("multiple anonymous inner classes"); } public void testPrivilegedMethodAccessorsGetRightExceptions_pr82989() { runTest("Compiler error due to a wrong exception check in try blocks"); } public void testAnonymousInnerClassWithMethodReturningTypeParameter_pr107898() { runTest("anonymous inner class with method returning type parameter"); } public void testMatchingOfObjectArray() { runTest("matching against Object[]"); } public void testMultipleAnonymousInnerClasses_pr108104() { runTest("multiple anonymous inner classes 2"); } public void testSignatureMatchingInMultipleOverrideScenario() { runTest("signature matching in override scenario"); } public void testWildcardAnnotationMatching_pr108245() { runTest("wildcard annotation matching - pr108245"); } public void testInnerTypesAndTypeVariables() { runTest("inner types and type variables"); } public void testAtAfterThrowingWithNoFormal() { runTest("@AfterThrowing with no formal specified"); } public void testParameterizedVarArgsMatch() { runTest("varargs with type variable"); } public void testFieldAccessInsideITDM() { runTest("itd field access inside itd method"); } public void testTypeVarWithTypeVarBound() { runTest("type variable with type variable bound"); } public void testEnumSwitchInITD() { runTest("switch on enum inside ITD method"); } public void testInnerTypeOfGeneric() { runTest("inner type of generic interface reference from parameterized type"); } public void testDeclareParentsIntroducingCovariantReturnType() { runTest("declare parents introducing override with covariance"); } // helper methods..... public SyntheticRepository createRepos(File cpentry) { ClassPath cp = new ClassPath(cpentry+File.pathSeparator+System.getProperty("java.class.path")); return SyntheticRepository.getInstance(cp); } protected JavaClass getClassFrom(File where,String clazzname) throws ClassNotFoundException { SyntheticRepository repos = createRepos(where); return repos.loadClass(clazzname); } }
107,858
Bug 107858 illegal argument to proceed crashes the parser
in a context where proceed requires zero arguments, calling it with an extra argument crashes the compiler, but only if that argument is a field access: class Foo { Foo field; void test() {} } public aspect Bug { void around() : call(void Foo.test()) { Foo foo = new Foo().field; proceed(foo); // caught at compile time proceed(new Foo().field); // crashes } } /home/user/sgelin3/dev/java/ajc/new_bug/Bug.java [error] Internal compiler error java.lang.NullPointerException at org.aspectj.ajdt.internal.compiler.ast.AccessForInlineVisitor.getAccessibleField(AccessForInlineVisitor.java:145) at org.aspectj.ajdt.internal.compiler.ast.AccessForInlineVisitor.endVisit(AccessForInlineVisitor.java:108) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.FieldReference.traverse(FieldReference.java:609) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.MessageSend.traverse(MessageSend.java:467) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.traverse(MethodDeclaration.java:212)
resolved fixed
6c8747b
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-08-31T14:24:14Z
2005-08-24T16:13:20Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/AccessForInlineVisitor.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.ajdt.internal.compiler.ast; //import java.util.Arrays; import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory; import org.aspectj.ajdt.internal.compiler.lookup.InlineAccessFieldBinding; import org.aspectj.ajdt.internal.compiler.lookup.InterTypeFieldBinding; import org.aspectj.ajdt.internal.compiler.lookup.InterTypeMethodBinding; import org.aspectj.ajdt.internal.compiler.lookup.PrivilegedFieldBinding; import org.aspectj.ajdt.internal.compiler.lookup.PrivilegedHandler; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.ResolvedMember; import org.aspectj.org.eclipse.jdt.internal.compiler.ASTVisitor; //import org.aspectj.org.eclipse.jdt.internal.compiler.AbstractSyntaxTreeVisitorAdapter; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.AllocationExpression; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.AssertStatement; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.ClassLiteralAccess; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.FieldReference; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.MessageSend; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.QualifiedNameReference; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.QualifiedTypeReference; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.SingleNameReference; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.SingleTypeReference; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.ThisReference; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ArrayBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.BlockScope; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.FieldBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.MethodBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.VariableBinding; /** * Walks the body of around advice * * Makes sure that all member accesses are to public members. Will * convert to use access methods when needed to ensure that. This * makes it much simpler (and more modular) to inline the body of * an around. * * ??? constructors are handled different and require access to the * target type. changes to org.eclipse.jdt.internal.compiler.ast.AllocationExpression * would be required to fix this issue. * * @author Jim Hugunin */ public class AccessForInlineVisitor extends ASTVisitor { PrivilegedHandler handler; AspectDeclaration inAspect; EclipseFactory world; // alias for inAspect.world // set to true for ClassLiteralAccess and AssertStatement // ??? A better answer would be to transform these into inlinable forms public boolean isInlinable = true; public AccessForInlineVisitor(AspectDeclaration inAspect, PrivilegedHandler handler) { this.inAspect = inAspect; this.world = inAspect.factory; this.handler = handler; } public void endVisit(SingleNameReference ref, BlockScope scope) { if (ref.binding instanceof FieldBinding) { ref.binding = getAccessibleField((FieldBinding)ref.binding, ref.actualReceiverType); } } public void endVisit(QualifiedNameReference ref, BlockScope scope) { if (ref.binding instanceof FieldBinding) { ref.binding = getAccessibleField((FieldBinding)ref.binding, ref.actualReceiverType); } if (ref.otherBindings != null && ref.otherBindings.length > 0) { TypeBinding receiverType; if (ref.binding instanceof FieldBinding) { receiverType = ((FieldBinding)ref.binding).type; } else if (ref.binding instanceof VariableBinding) { receiverType = ((VariableBinding)ref.binding).type; } else { //!!! understand and fix this case later receiverType = ref.otherBindings[0].declaringClass; } for (int i=0, len=ref.otherBindings.length; i < len; i++) { FieldBinding binding = ref.otherBindings[i]; ref.otherBindings[i] = getAccessibleField(binding, receiverType); receiverType = binding.type; } } } public void endVisit(FieldReference ref, BlockScope scope) { ref.binding = getAccessibleField(ref.binding, ref.receiverType); } public void endVisit(MessageSend send, BlockScope scope) { if (send instanceof Proceed) return; if (send.binding == null || !send.binding.isValidBinding()) return; if (send.isSuperAccess() && !send.binding.isStatic()) { send.receiver = new ThisReference(send.sourceStart, send.sourceEnd); MethodBinding superAccessBinding = getSuperAccessMethod(send.binding); AstUtil.replaceMethodBinding(send, superAccessBinding); } else if (!isPublic(send.binding)) { send.syntheticAccessor = getAccessibleMethod(send.binding, send.actualReceiverType); } } public void endVisit(AllocationExpression send, BlockScope scope) { if (send.binding == null || !send.binding.isValidBinding()) return; //XXX TBD if (isPublic(send.binding)) return; makePublic(send.binding.declaringClass); send.binding = handler.getPrivilegedAccessMethod(send.binding, send); } public void endVisit( QualifiedTypeReference ref, BlockScope scope) { makePublic(ref.resolvedType); //getTypeBinding(scope)); //??? might be trouble } public void endVisit( SingleTypeReference ref, BlockScope scope) { makePublic(ref.resolvedType); //getTypeBinding(scope)); //??? might be trouble } private FieldBinding getAccessibleField(FieldBinding binding, TypeBinding receiverType) { //System.err.println("checking field: " + binding); if (!binding.isValidBinding()) return binding; makePublic(receiverType); if (isPublic(binding)) return binding; if (binding instanceof PrivilegedFieldBinding) return binding; if (binding instanceof InterTypeFieldBinding) return binding; if (binding.isPrivate() && binding.declaringClass != inAspect.binding) { binding.modifiers = AstUtil.makePackageVisible(binding.modifiers); } ResolvedMember m = world.makeResolvedMember(binding, receiverType); if (inAspect.accessForInline.containsKey(m)) return (FieldBinding)inAspect.accessForInline.get(m); FieldBinding ret = new InlineAccessFieldBinding(inAspect, binding, m); //System.err.println(" made accessor: " + ret); inAspect.accessForInline.put(m, ret); return ret; } private MethodBinding getAccessibleMethod(MethodBinding binding, TypeBinding receiverType) { if (!binding.isValidBinding()) return binding; makePublic(receiverType); //??? if (isPublic(binding)) return binding; if (binding instanceof InterTypeMethodBinding) return binding; ResolvedMember m = null; if (binding.isPrivate() && binding.declaringClass != inAspect.binding) { // does this always mean that the aspect is an inner aspect of the bindings // declaring class? After all, the field is private but we can see it from // where we are. binding.modifiers = AstUtil.makePackageVisible(binding.modifiers); m = world.makeResolvedMember(binding); } else { // Sometimes receiverType and binding.declaringClass are *not* the same. // Sometimes receiverType is a subclass of binding.declaringClass. In these situations // we want the generated inline accessor to call the method on the subclass (at // runtime this will be satisfied by the super). m = world.makeResolvedMember(binding, receiverType); } if (inAspect.accessForInline.containsKey(m)) return (MethodBinding)inAspect.accessForInline.get(m); MethodBinding ret = world.makeMethodBinding( AjcMemberMaker.inlineAccessMethodForMethod(inAspect.typeX, m)); inAspect.accessForInline.put(m, ret); return ret; } static class SuperAccessMethodPair { public ResolvedMember originalMethod; public MethodBinding accessMethod; public SuperAccessMethodPair(ResolvedMember originalMethod, MethodBinding accessMethod) { this.originalMethod = originalMethod; this.accessMethod = accessMethod; } } private MethodBinding getSuperAccessMethod(MethodBinding binding) { ResolvedMember m = world.makeResolvedMember(binding); ResolvedMember superAccessMember = AjcMemberMaker.superAccessMethod(inAspect.typeX, m); if (inAspect.superAccessForInline.containsKey(superAccessMember)) { return ((SuperAccessMethodPair)inAspect.superAccessForInline.get(superAccessMember)).accessMethod; } MethodBinding ret = world.makeMethodBinding(superAccessMember); inAspect.superAccessForInline.put(superAccessMember, new SuperAccessMethodPair(m, ret)); return ret; } private boolean isPublic(FieldBinding fieldBinding) { // these are always effectively public to the inliner if (fieldBinding instanceof InterTypeFieldBinding) return true; return fieldBinding.isPublic(); } private boolean isPublic(MethodBinding methodBinding) { // these are always effectively public to the inliner if (methodBinding instanceof InterTypeMethodBinding) return true; return methodBinding.isPublic(); } private void makePublic(TypeBinding binding) { if (binding == null || !binding.isValidBinding()) return; // has already produced an error if (binding instanceof ReferenceBinding) { ReferenceBinding rb = (ReferenceBinding)binding; if (!rb.isPublic()) handler.notePrivilegedTypeAccess(rb, null); //??? } else if (binding instanceof ArrayBinding) { makePublic( ((ArrayBinding)binding).leafComponentType ); } else { return; } } public void endVisit(AssertStatement assertStatement, BlockScope scope) { isInlinable = false; } public void endVisit(ClassLiteralAccess classLiteral, BlockScope scope) { isInlinable = false; } public boolean visit( TypeDeclaration localTypeDeclaration, BlockScope scope) { // we don't want to transform any local anonymous classes as they won't be inlined return false; } }
107,858
Bug 107858 illegal argument to proceed crashes the parser
in a context where proceed requires zero arguments, calling it with an extra argument crashes the compiler, but only if that argument is a field access: class Foo { Foo field; void test() {} } public aspect Bug { void around() : call(void Foo.test()) { Foo foo = new Foo().field; proceed(foo); // caught at compile time proceed(new Foo().field); // crashes } } /home/user/sgelin3/dev/java/ajc/new_bug/Bug.java [error] Internal compiler error java.lang.NullPointerException at org.aspectj.ajdt.internal.compiler.ast.AccessForInlineVisitor.getAccessibleField(AccessForInlineVisitor.java:145) at org.aspectj.ajdt.internal.compiler.ast.AccessForInlineVisitor.endVisit(AccessForInlineVisitor.java:108) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.FieldReference.traverse(FieldReference.java:609) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.MessageSend.traverse(MessageSend.java:467) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.traverse(MethodDeclaration.java:212)
resolved fixed
6c8747b
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-08-31T14:24:14Z
2005-08-24T16:13:20Z
tests/src/org/aspectj/systemtest/ajc150/Ajc150Tests.java
/******************************************************************************* * Copyright (c) 2004 IBM * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Andy Clement - initial API and implementation *******************************************************************************/ package org.aspectj.systemtest.ajc150; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import junit.framework.Test; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.apache.bcel.classfile.Method; import org.aspectj.apache.bcel.util.ClassPath; import org.aspectj.apache.bcel.util.SyntheticRepository; import org.aspectj.asm.AsmManager; import org.aspectj.testing.XMLBasedAjcTestCase; import org.aspectj.util.LangUtil; /** * These are tests that will run on Java 1.4 and use the old harness format for test specification. */ public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase { public static Test suite() { return XMLBasedAjcTestCase.loadSuite(Ajc150Tests.class); } protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml"); } public void test_typeProcessingOrderWhenDeclareParents() { runTest("Order of types passed to compiler determines weaving behavior"); } public void test_aroundMethod() { runTest("method called around in class"); } public void test_aroundMethodAspect() { runTest("method called around in aspect"); } public void test_ambiguousBindingsDetection() { runTest("Various kinds of ambiguous bindings"); } public void test_ambiguousArgsDetection() { runTest("ambiguous args"); } public void testIncorrectExceptionTableWhenBreakInMethod_pr78021() { runTest("Injecting exception into while loop with break statement causes catch block to be ignored"); } public void testIncorrectExceptionTableWhenReturnInMethod_pr79554() { runTest("Return in try-block disables catch-block if final-block is present"); } public void testMissingDebugInfoForGeneratedMethods_pr82570() throws ClassNotFoundException { runTest("Weaved code does not include debug lines"); boolean f = false; JavaClass jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1"); Method[] meths = jc.getMethods(); for (int i = 0; i < meths.length; i++) { Method method = meths[i]; if (f) System.err.println("Line number table for "+method.getName()+method.getSignature()+" = "+method.getLineNumberTable()); assertTrue("Didn't find a line number table for method "+method.getName()+method.getSignature(), method.getLineNumberTable()!=null); } // This test would determine the info isn't there if you pass -g:none ... // cR = ajc(baseDir,new String[]{"PR82570_1.java","-g:none"}); // assertTrue("Expected no compile problem:"+cR,!cR.hasErrorMessages()); // System.err.println(cR.getStandardError()); // jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1"); // meths = jc.getMethods(); // for (int i = 0; i < meths.length; i++) { // Method method = meths[i]; // assertTrue("Found a line number table for method "+method.getName(), // method.getLineNumberTable()==null); // } } public void testCanOverrideProtectedMethodsViaITDandDecp_pr83303() { runTest("compiler error when mixing inheritance, overriding and polymorphism"); } public void testPerTypeWithinMissesNamedInnerTypes() { runTest("pertypewithin() handing of inner classes (1)"); } public void testPerTypeWithinMissesAnonymousInnerTypes() { runTest("pertypewithin() handing of inner classes (2)"); } public void testPerTypeWithinIncorrectlyMatchingInterfaces() { runTest("pertypewithin({interface}) illegal field modifier"); } public void test051_arrayCloningInJava5() { runTest("AJC possible bug with static nested classes"); } public void testBadASMforEnums() throws IOException { runTest("bad asm for enums"); if (LangUtil.is15VMOrGreater()) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintWriter pw = new PrintWriter(baos); AsmManager.dumptree(pw,AsmManager.getDefault().getHierarchy().getRoot(),0); pw.flush(); String tree = baos.toString(); assertTrue("Expected 'Red [enumvalue]' somewhere in here:"+tree,tree.indexOf("Red [enumvalue]")!=-1); } } public void npeOnTypeNotFound() { runTest("structure model npe on type not found"); } public void testNoRuntimeExceptionSoftening() { runTest("declare soft of runtime exception"); } public void testRuntimeNoSoftenWithHandler() { runTest("declare soft w. catch block"); } public void testSyntaxError() { runTest("invalid cons syntax"); } public void testVarargsInConsBug() { runTest("varargs in constructor sig"); } public void testAspectpathdirs() { runTest("dirs on aspectpath"); } public void testIntroSample() { runTest("introduction sample"); } public void testPTWInterface() { runTest("pertypewithin({interface}) illegal field modifier"); } public void testEnumCalledEnumEtc() { runTest("enum called Enum, annotation called Annotation, etc"); } public void testInternalCompilerError_pr86832() { runTest("Internal compiler error"); } public void testCloneMethod_pr83311() { runTest("overriding/polymorphism error on interface method introduction"); } /** * IfPointcut.findResidueInternal() was modified to make this test complete in a short amount * of time - if you see it hanging, someone has messed with the optimization. */ public void testIfEvaluationExplosion_pr94086() { runTest("Exploding compile time with if() statements in pointcut"); } public void testReflectNPE_pr94167() {runTest("NPE in reflect implementation");} public void testStaticImports_pr84260() {runTest("static import failures");} public void testGenerics_pr99089() {runTest("ArrayIndexOutOfBoundsException - Generics in privileged aspects");} public void testGenerics_pr95993() {runTest("NPE at ClassScope.java:660 when compiling generic class");} public void testItdGenerics_pr99228() {runTest("ITD of a field into a generic class");} public void testItdGenerics_pr98320() {runTest("intertype with nested generic type");} public void testItdGenerics_pr100227() {runTest("inner class with generic enclosing class");} public void testItdGenerics_pr100260() {runTest("methods inherited from a generic parent");} public void testSyntaxErrorNPE_pr103266() {runTest("NPE on syntax error");} public void testIllegalStateExceptionOnNestedParameterizedType_pr106634() { runTest("IllegalStateException unpacking signature of nested parameterized type"); } public void testParseErrorOnAnnotationStarPlusPattern() { runTest("(@Foo *)+ type pattern parse error"); } public void test_pr106130_tooManyLocals() { runTest("test weaving with > 256 locals"); } public void testMissingNamePattern_pr106461() { runTest("missing name pattern"); } public void testMissingNamePattern_pr107059() { runTest("parser crashes on call(void (@a *)(..)"); } public void testIntermediateAnnotationMatching() { runTest("intermediate annotation matching"); } public void testBadRuntimeTestGeneration() { runTest("target(@Foo *)"); } public void testErrorMessageOnITDWithTypePatterns() { runTest("clear error message on itd with type pattern"); } public void testAjKeywordsAsIdentifiers() { runTest("before and after are valid identifiers in classes"); } public void testAjKeywordsAsIdentifiers2() { runTest("before and after are valid identifiers in classes, part 2"); } public void testNoBeforeReturningAdvice() { runTest("before returning advice not allowed!"); } public void testDetectVoidFieldType() { runTest("void field type in pointcut expression"); } public void testPointcutOverriding() { runTest("overriding final pointcut from super-aspect"); } public void testAtSuppressWarnings() { runTest("@SuppressWarnings should suppress"); } public void testDEOWWithBindingPointcut() { runTest("declare warning : foo(str) : ...;"); } public void testAroundAdviceAndInterfaceInitializer() { runTest("around advice on interface initializer"); } public void testGoodErrorMessageOnUnmatchedMemberSyntax() { runTest("good error message for unmatched member syntax"); } public void testITDWithNoExceptionAndIntermediary() { runTest("itd override with no exception clause"); } public void testAnonymousInnerClasses() { runTest("anonymous inner classes"); } public void testMultipleAnonymousInnerClasses() { runTest("multiple anonymous inner classes"); } public void testPrivilegedMethodAccessorsGetRightExceptions_pr82989() { runTest("Compiler error due to a wrong exception check in try blocks"); } public void testAnonymousInnerClassWithMethodReturningTypeParameter_pr107898() { runTest("anonymous inner class with method returning type parameter"); } public void testMatchingOfObjectArray() { runTest("matching against Object[]"); } public void testMultipleAnonymousInnerClasses_pr108104() { runTest("multiple anonymous inner classes 2"); } public void testSignatureMatchingInMultipleOverrideScenario() { runTest("signature matching in override scenario"); } public void testWildcardAnnotationMatching_pr108245() { runTest("wildcard annotation matching - pr108245"); } public void testInnerTypesAndTypeVariables() { runTest("inner types and type variables"); } public void testAtAfterThrowingWithNoFormal() { runTest("@AfterThrowing with no formal specified"); } public void testParameterizedVarArgsMatch() { runTest("varargs with type variable"); } public void testFieldAccessInsideITDM() { runTest("itd field access inside itd method"); } public void testTypeVarWithTypeVarBound() { runTest("type variable with type variable bound"); } public void testEnumSwitchInITD() { runTest("switch on enum inside ITD method"); } public void testInnerTypeOfGeneric() { runTest("inner type of generic interface reference from parameterized type"); } public void testDeclareParentsIntroducingCovariantReturnType() { runTest("declare parents introducing override with covariance"); } public void testInnerClassPassedToVarargs() { runTest("inner class passed as argument to varargs method"); } // helper methods..... public SyntheticRepository createRepos(File cpentry) { ClassPath cp = new ClassPath(cpentry+File.pathSeparator+System.getProperty("java.class.path")); return SyntheticRepository.getInstance(cp); } protected JavaClass getClassFrom(File where,String clazzname) throws ClassNotFoundException { SyntheticRepository repos = createRepos(where); return repos.loadClass(clazzname); } }
71,159
Bug 71159 pointcut call(MethodPattern) matches non-visible methods in parent class
aspectjtools.jar / ajc v1.2 We believe that the call(methodpattern) pointcut has matching behaviour that is inconsistent with what we expect from Java in relation to invocations of methods on subclasses and superclasses. Background: Our goal is to use an aspect to declare ajc compiler warnings on any invocation to a target method, where the space of targets is defined as any visible method of any class in a specified package P or its subpackages. As well as straight invocations from types in packages oustide P and its subpackages, we wish to match method invocations on P where the methods invoked are inherited from P -- that is , they are obtained in a type that directly extends a type in P or its subpackages. The fragment of the aspect we are using is: public aspect Aspect1 { pointcut methodCalls() : !within(Aspect1) && call(* P..*.*(..)) ; // 'P' is the target package space declare warning : methodCalls() : "invoking"; //... } Consider these cases: Case 1 method inheritance: Superclass A in package P declares and implements a public method M. A direct subclass B (in a package outside P) directly extends A and inherits this method. Now, any calls inside B to M or this.M() are matched by the call() join point above which seeks to match calls to P..*.*() This is as we would expect since the implementation in package space P is actually being called. Case 2 method overriding: Superclass A in package P declares and implements a public method M. Direct subclass B (in a package outside P) overrides A.M with its own implementation M'. M' does not invoke M. Now, calls inside B to M' or this.M'() are still matched by the call() join point above which seeks to match calls to P..*.*() even though M' does not invoke or depend on M. We do not expect this result since we do not think M is actually called. Case 3 redeclaration of non-visible method with the same name: Superclass A in package P declares and implements a private method M. Direct subclass B (in a package outside P) introduces its own method M having the same signature as A.M. Now, calls in B to M or this.M() are still matched by the call() join point above which seeks to match calls to P..*.*() even though A.M is not visible to B and is never called by it. We do not expect this result since we do not think A.M is ever called. The only way we can explain this apparent behaviour is by reasoning that the compiler is treating the subclass B "as a type of" its parent A and somehow concluding that method calls on B can be equated with calls to methods of identical signature on A. However this seems at odds with the rules for Java visibility and with our expectations for when the call(...) joinpoint should match. We have experimented with execution(...) join points to perform this matching but that has turned up a different set of problems which we are still analyzing. Please can you shed any light on what the call joinpoint is doing here? regards, Dave
resolved fixed
7e0c3cd
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-08-31T15:44:22Z
2004-07-30T15:06:40Z
tests/bugs150/pr71159/pkg1/A.java
71,159
Bug 71159 pointcut call(MethodPattern) matches non-visible methods in parent class
aspectjtools.jar / ajc v1.2 We believe that the call(methodpattern) pointcut has matching behaviour that is inconsistent with what we expect from Java in relation to invocations of methods on subclasses and superclasses. Background: Our goal is to use an aspect to declare ajc compiler warnings on any invocation to a target method, where the space of targets is defined as any visible method of any class in a specified package P or its subpackages. As well as straight invocations from types in packages oustide P and its subpackages, we wish to match method invocations on P where the methods invoked are inherited from P -- that is , they are obtained in a type that directly extends a type in P or its subpackages. The fragment of the aspect we are using is: public aspect Aspect1 { pointcut methodCalls() : !within(Aspect1) && call(* P..*.*(..)) ; // 'P' is the target package space declare warning : methodCalls() : "invoking"; //... } Consider these cases: Case 1 method inheritance: Superclass A in package P declares and implements a public method M. A direct subclass B (in a package outside P) directly extends A and inherits this method. Now, any calls inside B to M or this.M() are matched by the call() join point above which seeks to match calls to P..*.*() This is as we would expect since the implementation in package space P is actually being called. Case 2 method overriding: Superclass A in package P declares and implements a public method M. Direct subclass B (in a package outside P) overrides A.M with its own implementation M'. M' does not invoke M. Now, calls inside B to M' or this.M'() are still matched by the call() join point above which seeks to match calls to P..*.*() even though M' does not invoke or depend on M. We do not expect this result since we do not think M is actually called. Case 3 redeclaration of non-visible method with the same name: Superclass A in package P declares and implements a private method M. Direct subclass B (in a package outside P) introduces its own method M having the same signature as A.M. Now, calls in B to M or this.M() are still matched by the call() join point above which seeks to match calls to P..*.*() even though A.M is not visible to B and is never called by it. We do not expect this result since we do not think A.M is ever called. The only way we can explain this apparent behaviour is by reasoning that the compiler is treating the subclass B "as a type of" its parent A and somehow concluding that method calls on B can be equated with calls to methods of identical signature on A. However this seems at odds with the rules for Java visibility and with our expectations for when the call(...) joinpoint should match. We have experimented with execution(...) join points to perform this matching but that has turned up a different set of problems which we are still analyzing. Please can you shed any light on what the call joinpoint is doing here? regards, Dave
resolved fixed
7e0c3cd
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-08-31T15:44:22Z
2004-07-30T15:06:40Z
tests/bugs150/pr71159/pkg1/B.java
71,159
Bug 71159 pointcut call(MethodPattern) matches non-visible methods in parent class
aspectjtools.jar / ajc v1.2 We believe that the call(methodpattern) pointcut has matching behaviour that is inconsistent with what we expect from Java in relation to invocations of methods on subclasses and superclasses. Background: Our goal is to use an aspect to declare ajc compiler warnings on any invocation to a target method, where the space of targets is defined as any visible method of any class in a specified package P or its subpackages. As well as straight invocations from types in packages oustide P and its subpackages, we wish to match method invocations on P where the methods invoked are inherited from P -- that is , they are obtained in a type that directly extends a type in P or its subpackages. The fragment of the aspect we are using is: public aspect Aspect1 { pointcut methodCalls() : !within(Aspect1) && call(* P..*.*(..)) ; // 'P' is the target package space declare warning : methodCalls() : "invoking"; //... } Consider these cases: Case 1 method inheritance: Superclass A in package P declares and implements a public method M. A direct subclass B (in a package outside P) directly extends A and inherits this method. Now, any calls inside B to M or this.M() are matched by the call() join point above which seeks to match calls to P..*.*() This is as we would expect since the implementation in package space P is actually being called. Case 2 method overriding: Superclass A in package P declares and implements a public method M. Direct subclass B (in a package outside P) overrides A.M with its own implementation M'. M' does not invoke M. Now, calls inside B to M' or this.M'() are still matched by the call() join point above which seeks to match calls to P..*.*() even though M' does not invoke or depend on M. We do not expect this result since we do not think M is actually called. Case 3 redeclaration of non-visible method with the same name: Superclass A in package P declares and implements a private method M. Direct subclass B (in a package outside P) introduces its own method M having the same signature as A.M. Now, calls in B to M or this.M() are still matched by the call() join point above which seeks to match calls to P..*.*() even though A.M is not visible to B and is never called by it. We do not expect this result since we do not think A.M is ever called. The only way we can explain this apparent behaviour is by reasoning that the compiler is treating the subclass B "as a type of" its parent A and somehow concluding that method calls on B can be equated with calls to methods of identical signature on A. However this seems at odds with the rules for Java visibility and with our expectations for when the call(...) joinpoint should match. We have experimented with execution(...) join points to perform this matching but that has turned up a different set of problems which we are still analyzing. Please can you shed any light on what the call joinpoint is doing here? regards, Dave
resolved fixed
7e0c3cd
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-08-31T15:44:22Z
2004-07-30T15:06:40Z
tests/bugs150/pr71159/pkg1/C.java
71,159
Bug 71159 pointcut call(MethodPattern) matches non-visible methods in parent class
aspectjtools.jar / ajc v1.2 We believe that the call(methodpattern) pointcut has matching behaviour that is inconsistent with what we expect from Java in relation to invocations of methods on subclasses and superclasses. Background: Our goal is to use an aspect to declare ajc compiler warnings on any invocation to a target method, where the space of targets is defined as any visible method of any class in a specified package P or its subpackages. As well as straight invocations from types in packages oustide P and its subpackages, we wish to match method invocations on P where the methods invoked are inherited from P -- that is , they are obtained in a type that directly extends a type in P or its subpackages. The fragment of the aspect we are using is: public aspect Aspect1 { pointcut methodCalls() : !within(Aspect1) && call(* P..*.*(..)) ; // 'P' is the target package space declare warning : methodCalls() : "invoking"; //... } Consider these cases: Case 1 method inheritance: Superclass A in package P declares and implements a public method M. A direct subclass B (in a package outside P) directly extends A and inherits this method. Now, any calls inside B to M or this.M() are matched by the call() join point above which seeks to match calls to P..*.*() This is as we would expect since the implementation in package space P is actually being called. Case 2 method overriding: Superclass A in package P declares and implements a public method M. Direct subclass B (in a package outside P) overrides A.M with its own implementation M'. M' does not invoke M. Now, calls inside B to M' or this.M'() are still matched by the call() join point above which seeks to match calls to P..*.*() even though M' does not invoke or depend on M. We do not expect this result since we do not think M is actually called. Case 3 redeclaration of non-visible method with the same name: Superclass A in package P declares and implements a private method M. Direct subclass B (in a package outside P) introduces its own method M having the same signature as A.M. Now, calls in B to M or this.M() are still matched by the call() join point above which seeks to match calls to P..*.*() even though A.M is not visible to B and is never called by it. We do not expect this result since we do not think A.M is ever called. The only way we can explain this apparent behaviour is by reasoning that the compiler is treating the subclass B "as a type of" its parent A and somehow concluding that method calls on B can be equated with calls to methods of identical signature on A. However this seems at odds with the rules for Java visibility and with our expectations for when the call(...) joinpoint should match. We have experimented with execution(...) join points to perform this matching but that has turned up a different set of problems which we are still analyzing. Please can you shed any light on what the call joinpoint is doing here? regards, Dave
resolved fixed
7e0c3cd
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-08-31T15:44:22Z
2004-07-30T15:06:40Z
tests/src/org/aspectj/systemtest/ajc150/Ajc150Tests.java
/******************************************************************************* * Copyright (c) 2004 IBM * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Andy Clement - initial API and implementation *******************************************************************************/ package org.aspectj.systemtest.ajc150; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import junit.framework.Test; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.apache.bcel.classfile.Method; import org.aspectj.apache.bcel.util.ClassPath; import org.aspectj.apache.bcel.util.SyntheticRepository; import org.aspectj.asm.AsmManager; import org.aspectj.testing.XMLBasedAjcTestCase; import org.aspectj.util.LangUtil; /** * These are tests that will run on Java 1.4 and use the old harness format for test specification. */ public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase { public static Test suite() { return XMLBasedAjcTestCase.loadSuite(Ajc150Tests.class); } protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml"); } public void test_typeProcessingOrderWhenDeclareParents() { runTest("Order of types passed to compiler determines weaving behavior"); } public void test_aroundMethod() { runTest("method called around in class"); } public void test_aroundMethodAspect() { runTest("method called around in aspect"); } public void test_ambiguousBindingsDetection() { runTest("Various kinds of ambiguous bindings"); } public void test_ambiguousArgsDetection() { runTest("ambiguous args"); } public void testIncorrectExceptionTableWhenBreakInMethod_pr78021() { runTest("Injecting exception into while loop with break statement causes catch block to be ignored"); } public void testIncorrectExceptionTableWhenReturnInMethod_pr79554() { runTest("Return in try-block disables catch-block if final-block is present"); } public void testMissingDebugInfoForGeneratedMethods_pr82570() throws ClassNotFoundException { runTest("Weaved code does not include debug lines"); boolean f = false; JavaClass jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1"); Method[] meths = jc.getMethods(); for (int i = 0; i < meths.length; i++) { Method method = meths[i]; if (f) System.err.println("Line number table for "+method.getName()+method.getSignature()+" = "+method.getLineNumberTable()); assertTrue("Didn't find a line number table for method "+method.getName()+method.getSignature(), method.getLineNumberTable()!=null); } // This test would determine the info isn't there if you pass -g:none ... // cR = ajc(baseDir,new String[]{"PR82570_1.java","-g:none"}); // assertTrue("Expected no compile problem:"+cR,!cR.hasErrorMessages()); // System.err.println(cR.getStandardError()); // jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1"); // meths = jc.getMethods(); // for (int i = 0; i < meths.length; i++) { // Method method = meths[i]; // assertTrue("Found a line number table for method "+method.getName(), // method.getLineNumberTable()==null); // } } public void testCanOverrideProtectedMethodsViaITDandDecp_pr83303() { runTest("compiler error when mixing inheritance, overriding and polymorphism"); } public void testPerTypeWithinMissesNamedInnerTypes() { runTest("pertypewithin() handing of inner classes (1)"); } public void testPerTypeWithinMissesAnonymousInnerTypes() { runTest("pertypewithin() handing of inner classes (2)"); } public void testPerTypeWithinIncorrectlyMatchingInterfaces() { runTest("pertypewithin({interface}) illegal field modifier"); } public void test051_arrayCloningInJava5() { runTest("AJC possible bug with static nested classes"); } public void testBadASMforEnums() throws IOException { runTest("bad asm for enums"); if (LangUtil.is15VMOrGreater()) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintWriter pw = new PrintWriter(baos); AsmManager.dumptree(pw,AsmManager.getDefault().getHierarchy().getRoot(),0); pw.flush(); String tree = baos.toString(); assertTrue("Expected 'Red [enumvalue]' somewhere in here:"+tree,tree.indexOf("Red [enumvalue]")!=-1); } } public void npeOnTypeNotFound() { runTest("structure model npe on type not found"); } public void testNoRuntimeExceptionSoftening() { runTest("declare soft of runtime exception"); } public void testRuntimeNoSoftenWithHandler() { runTest("declare soft w. catch block"); } public void testSyntaxError() { runTest("invalid cons syntax"); } public void testVarargsInConsBug() { runTest("varargs in constructor sig"); } public void testAspectpathdirs() { runTest("dirs on aspectpath"); } public void testIntroSample() { runTest("introduction sample"); } public void testPTWInterface() { runTest("pertypewithin({interface}) illegal field modifier"); } public void testEnumCalledEnumEtc() { runTest("enum called Enum, annotation called Annotation, etc"); } public void testInternalCompilerError_pr86832() { runTest("Internal compiler error"); } public void testCloneMethod_pr83311() { runTest("overriding/polymorphism error on interface method introduction"); } /** * IfPointcut.findResidueInternal() was modified to make this test complete in a short amount * of time - if you see it hanging, someone has messed with the optimization. */ public void testIfEvaluationExplosion_pr94086() { runTest("Exploding compile time with if() statements in pointcut"); } public void testReflectNPE_pr94167() {runTest("NPE in reflect implementation");} public void testStaticImports_pr84260() {runTest("static import failures");} public void testGenerics_pr99089() {runTest("ArrayIndexOutOfBoundsException - Generics in privileged aspects");} public void testGenerics_pr95993() {runTest("NPE at ClassScope.java:660 when compiling generic class");} public void testItdGenerics_pr99228() {runTest("ITD of a field into a generic class");} public void testItdGenerics_pr98320() {runTest("intertype with nested generic type");} public void testItdGenerics_pr100227() {runTest("inner class with generic enclosing class");} public void testItdGenerics_pr100260() {runTest("methods inherited from a generic parent");} public void testSyntaxErrorNPE_pr103266() {runTest("NPE on syntax error");} public void testIllegalStateExceptionOnNestedParameterizedType_pr106634() { runTest("IllegalStateException unpacking signature of nested parameterized type"); } public void testParseErrorOnAnnotationStarPlusPattern() { runTest("(@Foo *)+ type pattern parse error"); } public void test_pr106130_tooManyLocals() { runTest("test weaving with > 256 locals"); } public void testMissingNamePattern_pr106461() { runTest("missing name pattern"); } public void testMissingNamePattern_pr107059() { runTest("parser crashes on call(void (@a *)(..)"); } public void testIntermediateAnnotationMatching() { runTest("intermediate annotation matching"); } public void testBadRuntimeTestGeneration() { runTest("target(@Foo *)"); } public void testErrorMessageOnITDWithTypePatterns() { runTest("clear error message on itd with type pattern"); } public void testAjKeywordsAsIdentifiers() { runTest("before and after are valid identifiers in classes"); } public void testAjKeywordsAsIdentifiers2() { runTest("before and after are valid identifiers in classes, part 2"); } public void testNoBeforeReturningAdvice() { runTest("before returning advice not allowed!"); } public void testDetectVoidFieldType() { runTest("void field type in pointcut expression"); } public void testPointcutOverriding() { runTest("overriding final pointcut from super-aspect"); } public void testAtSuppressWarnings() { runTest("@SuppressWarnings should suppress"); } public void testDEOWWithBindingPointcut() { runTest("declare warning : foo(str) : ...;"); } public void testAroundAdviceAndInterfaceInitializer() { runTest("around advice on interface initializer"); } public void testGoodErrorMessageOnUnmatchedMemberSyntax() { runTest("good error message for unmatched member syntax"); } public void testITDWithNoExceptionAndIntermediary() { runTest("itd override with no exception clause"); } public void testAnonymousInnerClasses() { runTest("anonymous inner classes"); } public void testMultipleAnonymousInnerClasses() { runTest("multiple anonymous inner classes"); } public void testPrivilegedMethodAccessorsGetRightExceptions_pr82989() { runTest("Compiler error due to a wrong exception check in try blocks"); } public void testAnonymousInnerClassWithMethodReturningTypeParameter_pr107898() { runTest("anonymous inner class with method returning type parameter"); } public void testMatchingOfObjectArray() { runTest("matching against Object[]"); } public void testMultipleAnonymousInnerClasses_pr108104() { runTest("multiple anonymous inner classes 2"); } public void testSignatureMatchingInMultipleOverrideScenario() { runTest("signature matching in override scenario"); } public void testWildcardAnnotationMatching_pr108245() { runTest("wildcard annotation matching - pr108245"); } public void testInnerTypesAndTypeVariables() { runTest("inner types and type variables"); } public void testAtAfterThrowingWithNoFormal() { runTest("@AfterThrowing with no formal specified"); } public void testParameterizedVarArgsMatch() { runTest("varargs with type variable"); } public void testFieldAccessInsideITDM() { runTest("itd field access inside itd method"); } public void testTypeVarWithTypeVarBound() { runTest("type variable with type variable bound"); } public void testEnumSwitchInITD() { runTest("switch on enum inside ITD method"); } public void testInnerTypeOfGeneric() { runTest("inner type of generic interface reference from parameterized type"); } public void testDeclareParentsIntroducingCovariantReturnType() { runTest("declare parents introducing override with covariance"); } public void testInnerClassPassedToVarargs() { runTest("inner class passed as argument to varargs method"); } public void testInlinedFieldAccessInProceedCall() { runTest("inlined field access in proceed call"); } // helper methods..... public SyntheticRepository createRepos(File cpentry) { ClassPath cp = new ClassPath(cpentry+File.pathSeparator+System.getProperty("java.class.path")); return SyntheticRepository.getInstance(cp); } protected JavaClass getClassFrom(File where,String clazzname) throws ClassNotFoundException { SyntheticRepository repos = createRepos(where); return repos.loadClass(clazzname); } }
71,159
Bug 71159 pointcut call(MethodPattern) matches non-visible methods in parent class
aspectjtools.jar / ajc v1.2 We believe that the call(methodpattern) pointcut has matching behaviour that is inconsistent with what we expect from Java in relation to invocations of methods on subclasses and superclasses. Background: Our goal is to use an aspect to declare ajc compiler warnings on any invocation to a target method, where the space of targets is defined as any visible method of any class in a specified package P or its subpackages. As well as straight invocations from types in packages oustide P and its subpackages, we wish to match method invocations on P where the methods invoked are inherited from P -- that is , they are obtained in a type that directly extends a type in P or its subpackages. The fragment of the aspect we are using is: public aspect Aspect1 { pointcut methodCalls() : !within(Aspect1) && call(* P..*.*(..)) ; // 'P' is the target package space declare warning : methodCalls() : "invoking"; //... } Consider these cases: Case 1 method inheritance: Superclass A in package P declares and implements a public method M. A direct subclass B (in a package outside P) directly extends A and inherits this method. Now, any calls inside B to M or this.M() are matched by the call() join point above which seeks to match calls to P..*.*() This is as we would expect since the implementation in package space P is actually being called. Case 2 method overriding: Superclass A in package P declares and implements a public method M. Direct subclass B (in a package outside P) overrides A.M with its own implementation M'. M' does not invoke M. Now, calls inside B to M' or this.M'() are still matched by the call() join point above which seeks to match calls to P..*.*() even though M' does not invoke or depend on M. We do not expect this result since we do not think M is actually called. Case 3 redeclaration of non-visible method with the same name: Superclass A in package P declares and implements a private method M. Direct subclass B (in a package outside P) introduces its own method M having the same signature as A.M. Now, calls in B to M or this.M() are still matched by the call() join point above which seeks to match calls to P..*.*() even though A.M is not visible to B and is never called by it. We do not expect this result since we do not think A.M is ever called. The only way we can explain this apparent behaviour is by reasoning that the compiler is treating the subclass B "as a type of" its parent A and somehow concluding that method calls on B can be equated with calls to methods of identical signature on A. However this seems at odds with the rules for Java visibility and with our expectations for when the call(...) joinpoint should match. We have experimented with execution(...) join points to perform this matching but that has turned up a different set of problems which we are still analyzing. Please can you shed any light on what the call joinpoint is doing here? regards, Dave
resolved fixed
7e0c3cd
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-08-31T15:44:22Z
2004-07-30T15:06:40Z
weaver/src/org/aspectj/weaver/ResolvedMemberImpl.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver; import java.io.DataOutputStream; import java.io.IOException; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.aspectj.bridge.ISourceLocation; /** * This is the declared member, i.e. it will always correspond to an * actual method/... declaration */ public class ResolvedMemberImpl extends MemberImpl implements IHasPosition, AnnotatedElement, TypeVariableDeclaringElement, ResolvedMember { public String[] parameterNames = null; protected UnresolvedType[] checkedExceptions = UnresolvedType.NONE; /** * if this member is a parameterized version of a member in a generic type, * then this field holds a reference to the member we parameterize. */ protected ResolvedMember backingGenericMember = null; protected Set annotationTypes = null; // Some members are 'created' to represent other things (for example ITDs). These // members have their annotations stored elsewhere, and this flag indicates that is // the case. It is up to the caller to work out where that is! // Once determined the caller may choose to stash the annotations in this member... private boolean isAnnotatedElsewhere = false; // this field is not serialized. private boolean isAjSynthetic = true; // generic methods have type variables private UnresolvedType[] typeVariables; // these three fields hold the source location of this member protected int start, end; protected ISourceContext sourceContext = null; //XXX deprecate this in favor of the constructor below public ResolvedMemberImpl( Kind kind, UnresolvedType declaringType, int modifiers, UnresolvedType returnType, String name, UnresolvedType[] parameterTypes) { super(kind, declaringType, modifiers, returnType, name, parameterTypes); } public ResolvedMemberImpl( Kind kind, UnresolvedType declaringType, int modifiers, UnresolvedType returnType, String name, UnresolvedType[] parameterTypes, UnresolvedType[] checkedExceptions) { super(kind, declaringType, modifiers, returnType, name, parameterTypes); this.checkedExceptions = checkedExceptions; } public ResolvedMemberImpl( Kind kind, UnresolvedType declaringType, int modifiers, UnresolvedType returnType, String name, UnresolvedType[] parameterTypes, UnresolvedType[] checkedExceptions, ResolvedMember backingGenericMember) { this(kind, declaringType, modifiers, returnType, name, parameterTypes,checkedExceptions); this.backingGenericMember = backingGenericMember; this.isAjSynthetic = backingGenericMember.isAjSynthetic(); } public ResolvedMemberImpl( Kind kind, UnresolvedType declaringType, int modifiers, String name, String signature) { super(kind, declaringType, modifiers, name, signature); } /** * Compute the full set of signatures for a member. This walks up the hierarchy * giving the ResolvedMember in each defining type in the hierarchy. A shadowMember * can be created with a target type (declaring type) that does not actually define * the member. This is ok as long as the member is inherited in the declaring type. * Each declaring type in the line to the actual declaring type is added as an additional * signature. For example: * * class A { void foo(); } * class B extends A {} * * shadowMember : void B.foo() * * gives { void B.foo(), void A.foo() } * @param joinPointSignature * @param inAWorld */ public static JoinPointSignature[] getJoinPointSignatures(Member joinPointSignature, World inAWorld) { // Walk up hierarchy creating one member for each type up to and including the // first defining type ResolvedType originalDeclaringType = joinPointSignature.getDeclaringType().resolve(inAWorld); ResolvedMemberImpl firstDefiningMember = (ResolvedMemberImpl) joinPointSignature.resolve(inAWorld); if (firstDefiningMember == null) { return new JoinPointSignature[0]; } // declaringType can be unresolved if we matched a synthetic member generated by Aj... // should be fixed elsewhere but add this resolve call on the end for now so that we can // focus on one problem at a time... ResolvedType firstDefiningType = firstDefiningMember.getDeclaringType().resolve(inAWorld); if (firstDefiningType != originalDeclaringType) { if (joinPointSignature.getKind() == Member.CONSTRUCTOR) { return new JoinPointSignature[0]; } // else if (shadowMember.isStatic()) { // return new ResolvedMember[] {firstDefiningMember}; // } } List declaringTypes = new ArrayList(); accumulateTypesInBetween(originalDeclaringType, firstDefiningType, declaringTypes); Set memberSignatures = new HashSet(); for (Iterator iter = declaringTypes.iterator(); iter.hasNext();) { ResolvedType declaringType = (ResolvedType) iter.next(); ResolvedMember member = firstDefiningMember.withSubstituteDeclaringType(declaringType); memberSignatures.add(member); } if (shouldWalkUpHierarchyFor(firstDefiningMember)) { // now walk up the hierarchy from the firstDefiningMember and include the signature for // every type between the firstDefiningMember and the root defining member. Iterator superTypeIterator = firstDefiningType.getDirectSupertypes(); List typesAlreadyVisited = new ArrayList(); accumulateMembersMatching(firstDefiningMember,superTypeIterator,typesAlreadyVisited,memberSignatures); } JoinPointSignature[] ret = new JoinPointSignature[memberSignatures.size()]; memberSignatures.toArray(ret); return ret; } private static boolean shouldWalkUpHierarchyFor(Member aMember) { if (aMember.getKind() == Member.CONSTRUCTOR) return false; if (aMember.getKind() == Member.FIELD) return false; if (aMember.isStatic()) return false; return true; } /** * Build a list containing every type between subtype and supertype, inclusively. */ private static void accumulateTypesInBetween(ResolvedType subType, ResolvedType superType, List types) { types.add(subType); if (subType == superType) { return; } else { for (Iterator iter = subType.getDirectSupertypes(); iter.hasNext();) { ResolvedType parent = (ResolvedType) iter.next(); if (superType.isAssignableFrom(parent)) { accumulateTypesInBetween(parent, superType,types); } } } } /** * We have a resolved member, possibly with type parameter references as parameters or return * type. We need to find all its ancestor members. When doing this, a type parameter matches * regardless of bounds (bounds can be narrowed down the hierarchy). */ private static void accumulateMembersMatching( ResolvedMemberImpl memberToMatch, Iterator typesToLookIn, List typesAlreadyVisited, Set foundMembers) { while(typesToLookIn.hasNext()) { ResolvedType toLookIn = (ResolvedType) typesToLookIn.next(); if (!typesAlreadyVisited.contains(toLookIn)) { typesAlreadyVisited.add(toLookIn); ResolvedMemberImpl foundMember = (ResolvedMemberImpl) toLookIn.lookupResolvedMember(memberToMatch); if (foundMember != null) { List declaringTypes = new ArrayList(); // declaring type can be unresolved if the member can from an ITD... ResolvedType resolvedDeclaringType = foundMember.getDeclaringType().resolve(toLookIn.getWorld()); accumulateTypesInBetween(toLookIn, resolvedDeclaringType, declaringTypes); for (Iterator iter = declaringTypes.iterator(); iter.hasNext();) { ResolvedType declaringType = (ResolvedType) iter.next(); // typesAlreadyVisited.add(declaringType); ResolvedMember member = foundMember.withSubstituteDeclaringType(declaringType); foundMembers.add(member); } if (toLookIn.isParameterizedType() && (foundMember.backingGenericMember != null)) { foundMembers.add(new JoinPointSignature(foundMember.backingGenericMember,foundMember.declaringType.resolve(toLookIn.getWorld()))); } accumulateMembersMatching(foundMember,toLookIn.getDirectSupertypes(),typesAlreadyVisited,foundMembers); // if this was a parameterized type, look in the generic type that backs it too } } } } // ---- public final int getModifiers(World world) { return modifiers; } public final int getModifiers() { return modifiers; } // ---- public final UnresolvedType[] getExceptions(World world) { return getExceptions(); } public UnresolvedType[] getExceptions() { return checkedExceptions; } public ShadowMunger getAssociatedShadowMunger() { return null; } // ??? true or false? public boolean isAjSynthetic() { return isAjSynthetic; } public boolean hasAnnotations() { return (annotationTypes!=null); } public boolean hasAnnotation(UnresolvedType ofType) { // The ctors don't allow annotations to be specified ... yet - but // that doesn't mean it is an error to call this method. // Normally the weaver will be working with subtypes of // this type - BcelField/BcelMethod if (annotationTypes==null) return false; return annotationTypes.contains(ofType); } public ResolvedType[] getAnnotationTypes() { // The ctors don't allow annotations to be specified ... yet - but // that doesn't mean it is an error to call this method. // Normally the weaver will be working with subtypes of // this type - BcelField/BcelMethod if (annotationTypes == null) return null; return (ResolvedType[])annotationTypes.toArray(new ResolvedType[]{}); } public void setAnnotationTypes(UnresolvedType[] annotationtypes) { if (annotationTypes == null) annotationTypes = new HashSet(); for (int i = 0; i < annotationtypes.length; i++) { UnresolvedType typeX = annotationtypes[i]; annotationTypes.add(typeX); } } public void addAnnotation(AnnotationX annotation) { // FIXME asc only allows for annotation types, not instances - should it? if (annotationTypes == null) annotationTypes = new HashSet(); annotationTypes.add(annotation.getSignature()); } public boolean isBridgeMethod() { return (modifiers & Constants.ACC_BRIDGE)!=0; } public boolean isVarargsMethod() { return (modifiers & Constants.ACC_VARARGS)!=0; } public boolean isSynthetic() { return false; } public void write(DataOutputStream s) throws IOException { getKind().write(s); getDeclaringType().write(s); s.writeInt(modifiers); s.writeUTF(getName()); s.writeUTF(getSignature()); UnresolvedType.writeArray(getExceptions(), s); s.writeInt(getStart()); s.writeInt(getEnd()); // Write out any type variables... if (typeVariables==null) { s.writeInt(0); } else { s.writeInt(typeVariables.length); for (int i = 0; i < typeVariables.length; i++) { typeVariables[i].write(s); } } } public static void writeArray(ResolvedMember[] members, DataOutputStream s) throws IOException { s.writeInt(members.length); for (int i = 0, len = members.length; i < len; i++) { members[i].write(s); } } public static ResolvedMemberImpl readResolvedMember(VersionedDataInputStream s, ISourceContext sourceContext) throws IOException { ResolvedMemberImpl m = new ResolvedMemberImpl(Kind.read(s), UnresolvedType.read(s), s.readInt(), s.readUTF(), s.readUTF()); m.checkedExceptions = UnresolvedType.readArray(s); m.start = s.readInt(); m.end = s.readInt(); m.sourceContext = sourceContext; // Read in the type variables... if (s.getMajorVersion()>=AjAttribute.WeaverVersionInfo.WEAVER_VERSION_MAJOR_AJ150) { int tvcount = s.readInt(); if (tvcount!=0) { m.typeVariables = new UnresolvedType[tvcount]; for (int i=0;i<tvcount;i++) { m.typeVariables[i]=UnresolvedType.read(s); } } } return m; } public static ResolvedMember[] readResolvedMemberArray(VersionedDataInputStream s, ISourceContext context) throws IOException { int len = s.readInt(); ResolvedMember[] members = new ResolvedMember[len]; for (int i=0; i < len; i++) { members[i] = ResolvedMemberImpl.readResolvedMember(s, context); } return members; } public ResolvedMember resolve(World world) { // make sure all the pieces of a resolvedmember really are resolved if (annotationTypes!=null) { Set r = new HashSet(); for (Iterator iter = annotationTypes.iterator(); iter.hasNext();) { UnresolvedType element = (UnresolvedType) iter.next(); r.add(world.resolve(element)); } annotationTypes = r; } declaringType = declaringType.resolve(world); if (declaringType.isRawType()) declaringType = ((ReferenceType)declaringType).getGenericType(); if (typeVariables!=null && typeVariables.length>0) { for (int i = 0; i < typeVariables.length; i++) { UnresolvedType array_element = typeVariables[i]; typeVariables[i] = typeVariables[i].resolve(world); } } if (parameterTypes!=null && parameterTypes.length>0) { for (int i = 0; i < parameterTypes.length; i++) { UnresolvedType array_element = parameterTypes[i]; parameterTypes[i] = parameterTypes[i].resolve(world); } } returnType = returnType.resolve(world);return this; } public ISourceContext getSourceContext(World world) { return getDeclaringType().resolve(world).getSourceContext(); } public final String[] getParameterNames() { return parameterNames; } public final String[] getParameterNames(World world) { return getParameterNames(); } public AjAttribute.EffectiveSignatureAttribute getEffectiveSignature() { return null; } public ISourceLocation getSourceLocation() { //System.out.println("get context: " + this + " is " + sourceContext); if (sourceContext == null) { //System.err.println("no context: " + this); return null; } return sourceContext.makeSourceLocation(this); } public int getEnd() { return end; } public ISourceContext getSourceContext() { return sourceContext; } public int getStart() { return start; } public void setPosition(int sourceStart, int sourceEnd) { this.start = sourceStart; this.end = sourceEnd; } public void setSourceContext(ISourceContext sourceContext) { this.sourceContext = sourceContext; } public boolean isAbstract() { return Modifier.isAbstract(modifiers); } public boolean isPublic() { return Modifier.isPublic(modifiers); } public boolean isProtected() { return Modifier.isProtected(modifiers); } public boolean isNative() { return Modifier.isNative(modifiers); } public boolean isDefault() { return !(isPublic() || isProtected() || isPrivate()); } public boolean isVisible(ResolvedType fromType) { World world = fromType.getWorld(); return ResolvedType.isVisible(getModifiers(), getDeclaringType().resolve(world), fromType); } public void setCheckedExceptions(UnresolvedType[] checkedExceptions) { this.checkedExceptions = checkedExceptions; } public void setAnnotatedElsewhere(boolean b) { isAnnotatedElsewhere = b; } public boolean isAnnotatedElsewhere() { return isAnnotatedElsewhere; } /** * Get the UnresolvedType for the return type, taking generic signature into account */ public UnresolvedType getGenericReturnType() { return getReturnType(); } /** * Get the TypeXs of the parameter types, taking generic signature into account */ public UnresolvedType[] getGenericParameterTypes() { return getParameterTypes(); } // return a resolved member in which all type variables in the signature of this // member have been replaced with the given bindings. // the isParameterized flag tells us whether we are creating a raw type version or not // if isParameterized List<T> will turn into List<String> (for example), // but if !isParameterized List<T> will turn into List. public ResolvedMemberImpl parameterizedWith(UnresolvedType[] typeParameters,ResolvedType newDeclaringType, boolean isParameterized) { if (!this.getDeclaringType().isGenericType()) { throw new IllegalStateException("Can't ask to parameterize a member of a non-generic type"); } TypeVariable[] typeVariables = getDeclaringType().getTypeVariables(); if (typeVariables.length != typeParameters.length) { throw new IllegalStateException("Wrong number of type parameters supplied"); } Map typeMap = new HashMap(); for (int i = 0; i < typeVariables.length; i++) { typeMap.put(typeVariables[i].getName(), typeParameters[i]); } UnresolvedType parameterizedReturnType = parameterize(getGenericReturnType(),typeMap,isParameterized); UnresolvedType[] parameterizedParameterTypes = new UnresolvedType[getGenericParameterTypes().length]; for (int i = 0; i < parameterizedParameterTypes.length; i++) { parameterizedParameterTypes[i] = parameterize(getGenericParameterTypes()[i], typeMap,isParameterized); } return new ResolvedMemberImpl( getKind(), newDeclaringType, getModifiers(), parameterizedReturnType, getName(), parameterizedParameterTypes, getExceptions(), this ); } public void setTypeVariables(UnresolvedType[] types) { typeVariables = types; } public UnresolvedType[] getTypeVariables() { return typeVariables; } private UnresolvedType parameterize(UnresolvedType aType, Map typeVariableMap, boolean inParameterizedType) { if (aType instanceof TypeVariableReferenceType) { String variableName = ((TypeVariableReferenceType)aType).getTypeVariable().getName(); if (!typeVariableMap.containsKey(variableName)) { return aType; // if the type variable comes from the method (and not the type) thats OK } return (UnresolvedType) typeVariableMap.get(variableName); } else if (aType.isParameterizedType()) { if (inParameterizedType) { return aType.parameterize(typeVariableMap); } else { return aType.getRawType(); } } return aType; } /** * If this member is defined by a parameterized super-type, return the erasure * of that member. * For example: * interface I<T> { T foo(T aTea); } * class C implements I<String> { * String foo(String aString) { return "something"; } * } * The resolved member for C.foo has signature String foo(String). The * erasure of that member is Object foo(Object) -- use upper bound of type * variable. * A type is a supertype of itself. */ public ResolvedMember getErasure() { if (calculatedMyErasure) return myErasure; calculatedMyErasure = true; ResolvedType resolvedDeclaringType = (ResolvedType) getDeclaringType(); // this next test is fast, and the result is cached. if (!resolvedDeclaringType.hasParameterizedSuperType()) { return null; } else { // we have one or more parameterized super types. // this member may be defined by one of them... we need to find out. Collection declaringTypes = this.getDeclaringTypes(resolvedDeclaringType.getWorld()); for (Iterator iter = declaringTypes.iterator(); iter.hasNext();) { ResolvedType aDeclaringType = (ResolvedType) iter.next(); if (aDeclaringType.isParameterizedType()) { // we've found the (a?) parameterized type that defines this member. // now get the erasure of it ResolvedMemberImpl matchingMember = (ResolvedMemberImpl) aDeclaringType.lookupMemberNoSupers(this); if (matchingMember != null && matchingMember.backingGenericMember != null) { myErasure = matchingMember.backingGenericMember; return myErasure; } } } } return null; } private ResolvedMember myErasure = null; private boolean calculatedMyErasure = false; /** * For ITDs, we use the default factory methods to build a resolved member, then alter a couple of characteristics * using this method - this is safe. */ public void resetName(String newName) {this.name = newName;} public void resetKind(Kind newKind) {this.kind=newKind; } public void resetModifiers(int newModifiers) {this.modifiers=newModifiers;} public void resetReturnTypeToObjectArray() { returnType = UnresolvedType.OBJECTARRAY; } /** * Returns a copy of this member but with the declaring type swapped. * Copy only needs to be shallow. * @param newDeclaringType */ private JoinPointSignature withSubstituteDeclaringType(ResolvedType newDeclaringType) { JoinPointSignature ret = new JoinPointSignature(this,newDeclaringType); return ret; } /** * Returns true if this member matches the other. The matching takes into account * name and parameter types only. When comparing parameter types, we allow any type * variable to match any other type variable regardless of bounds. */ public boolean matches(ResolvedMember aCandidateMatch) { ResolvedMemberImpl candidateMatchImpl = (ResolvedMemberImpl)aCandidateMatch; if (!getName().equals(aCandidateMatch.getName())) return false; UnresolvedType[] myParameterTypes = getGenericParameterTypes(); UnresolvedType[] candidateParameterTypes = aCandidateMatch.getGenericParameterTypes(); if (myParameterTypes.length != candidateParameterTypes.length) return false; String myParameterSignature = getParameterSigWithBoundsRemoved(); String candidateParameterSignature = candidateMatchImpl.getParameterSigWithBoundsRemoved(); if (myParameterSignature.equals(candidateParameterSignature)) { return true; } else { // try erasure myParameterSignature = getParameterSigErasure(); candidateParameterSignature = candidateMatchImpl.getParameterSigErasure(); return myParameterSignature.equals(candidateParameterSignature); } } /** converts e.g. <T extends Number>.... List<T> to just Ljava/util/List<T;>; * whereas the full signature would be Ljava/util/List<T:Ljava/lang/Number;>; */ private String myParameterSignatureWithBoundsRemoved = null; /** * converts e.g. <T extends Number>.... List<T> to just Ljava/util/List; */ private String myParameterSignatureErasure = null; // does NOT produce a meaningful java signature, but does give a unique string suitable for // comparison. private String getParameterSigWithBoundsRemoved() { if (myParameterSignatureWithBoundsRemoved != null) return myParameterSignatureWithBoundsRemoved; StringBuffer sig = new StringBuffer(); UnresolvedType[] myParameterTypes = getGenericParameterTypes(); for (int i = 0; i < myParameterTypes.length; i++) { appendSigWithTypeVarBoundsRemoved(myParameterTypes[i], sig); } myParameterSignatureWithBoundsRemoved = sig.toString(); return myParameterSignatureWithBoundsRemoved; } private String getParameterSigErasure() { if (myParameterSignatureErasure != null) return myParameterSignatureErasure; StringBuffer sig = new StringBuffer(); UnresolvedType[] myParameterTypes = getParameterTypes(); for (int i = 0; i < myParameterTypes.length; i++) { UnresolvedType thisParameter = myParameterTypes[i]; if (thisParameter.isTypeVariableReference()) { sig.append(thisParameter.getUpperBound().getSignature()); } else { sig.append(thisParameter.getSignature()); } } myParameterSignatureErasure = sig.toString(); return myParameterSignatureErasure; } // does NOT produce a meaningful java signature, but does give a unique string suitable for // comparison. private void appendSigWithTypeVarBoundsRemoved(UnresolvedType aType, StringBuffer toBuffer) { if (aType.isTypeVariableReference()) { toBuffer.append("T;"); } else if (aType.isParameterizedType()) { toBuffer.append(aType.getRawType().getSignature()); toBuffer.append("<"); for (int i = 0; i < aType.getTypeParameters().length; i++) { appendSigWithTypeVarBoundsRemoved(aType.getTypeParameters()[i], toBuffer); } toBuffer.append(">;"); } else { toBuffer.append(aType.getSignature()); } } public String toGenericString() { StringBuffer buf = new StringBuffer(); buf.append(getGenericReturnType().getSimpleName()); buf.append(' '); buf.append(declaringType.getName()); buf.append('.'); buf.append(name); if (kind != FIELD) { buf.append("("); UnresolvedType[] params = getGenericParameterTypes(); if (params.length != 0) { buf.append(params[0].getSimpleName()); for (int i=1, len = params.length; i < len; i++) { buf.append(", "); buf.append(params[i].getSimpleName()); } } buf.append(")"); } return buf.toString(); } }
59,196
Bug 59196 "adviceexecution() && args()" pcd does not pick up around advice execution because args() does not match the AroundClosure parameter.
In the following sample, the advice defined in "other_aspect" does not pick up the execution of around advice defined in "some_aspect". It matches only against the before advice defined in "some_aspect". The implicit AroundClosure parameter of an around advice seems to come in the way of args() matching. ------------------------------------------------------ aspect some_aspect { pointcut call_m(int a, int b) : call(int test.m(..)) && args(a, b); before(int x, int y) : call_m(x, y) { ... } int around(int x, int y) : call_m(x, y) { ... } } aspect other_aspect { before(int x, int y) : adviceexecution() && within(some_aspect) && args(x, y){ ... } } -------------------------------------------------------- AspectJ doc has to state this explicitly.
resolved fixed
a66e0a2
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-01T08:30:41Z
2004-04-20T08:33:20Z
tests/src/org/aspectj/systemtest/ajc150/Ajc150Tests.java
/******************************************************************************* * Copyright (c) 2004 IBM * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Andy Clement - initial API and implementation *******************************************************************************/ package org.aspectj.systemtest.ajc150; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import junit.framework.Test; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.apache.bcel.classfile.Method; import org.aspectj.apache.bcel.util.ClassPath; import org.aspectj.apache.bcel.util.SyntheticRepository; import org.aspectj.asm.AsmManager; import org.aspectj.testing.XMLBasedAjcTestCase; import org.aspectj.util.LangUtil; /** * These are tests that will run on Java 1.4 and use the old harness format for test specification. */ public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase { public static Test suite() { return XMLBasedAjcTestCase.loadSuite(Ajc150Tests.class); } protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml"); } public void test_typeProcessingOrderWhenDeclareParents() { runTest("Order of types passed to compiler determines weaving behavior"); } public void test_aroundMethod() { runTest("method called around in class"); } public void test_aroundMethodAspect() { runTest("method called around in aspect"); } public void test_ambiguousBindingsDetection() { runTest("Various kinds of ambiguous bindings"); } public void test_ambiguousArgsDetection() { runTest("ambiguous args"); } public void testIncorrectExceptionTableWhenBreakInMethod_pr78021() { runTest("Injecting exception into while loop with break statement causes catch block to be ignored"); } public void testIncorrectExceptionTableWhenReturnInMethod_pr79554() { runTest("Return in try-block disables catch-block if final-block is present"); } public void testMissingDebugInfoForGeneratedMethods_pr82570() throws ClassNotFoundException { runTest("Weaved code does not include debug lines"); boolean f = false; JavaClass jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1"); Method[] meths = jc.getMethods(); for (int i = 0; i < meths.length; i++) { Method method = meths[i]; if (f) System.err.println("Line number table for "+method.getName()+method.getSignature()+" = "+method.getLineNumberTable()); assertTrue("Didn't find a line number table for method "+method.getName()+method.getSignature(), method.getLineNumberTable()!=null); } // This test would determine the info isn't there if you pass -g:none ... // cR = ajc(baseDir,new String[]{"PR82570_1.java","-g:none"}); // assertTrue("Expected no compile problem:"+cR,!cR.hasErrorMessages()); // System.err.println(cR.getStandardError()); // jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1"); // meths = jc.getMethods(); // for (int i = 0; i < meths.length; i++) { // Method method = meths[i]; // assertTrue("Found a line number table for method "+method.getName(), // method.getLineNumberTable()==null); // } } public void testCanOverrideProtectedMethodsViaITDandDecp_pr83303() { runTest("compiler error when mixing inheritance, overriding and polymorphism"); } public void testPerTypeWithinMissesNamedInnerTypes() { runTest("pertypewithin() handing of inner classes (1)"); } public void testPerTypeWithinMissesAnonymousInnerTypes() { runTest("pertypewithin() handing of inner classes (2)"); } public void testPerTypeWithinIncorrectlyMatchingInterfaces() { runTest("pertypewithin({interface}) illegal field modifier"); } public void test051_arrayCloningInJava5() { runTest("AJC possible bug with static nested classes"); } public void testBadASMforEnums() throws IOException { runTest("bad asm for enums"); if (LangUtil.is15VMOrGreater()) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintWriter pw = new PrintWriter(baos); AsmManager.dumptree(pw,AsmManager.getDefault().getHierarchy().getRoot(),0); pw.flush(); String tree = baos.toString(); assertTrue("Expected 'Red [enumvalue]' somewhere in here:"+tree,tree.indexOf("Red [enumvalue]")!=-1); } } public void npeOnTypeNotFound() { runTest("structure model npe on type not found"); } public void testNoRuntimeExceptionSoftening() { runTest("declare soft of runtime exception"); } public void testRuntimeNoSoftenWithHandler() { runTest("declare soft w. catch block"); } public void testSyntaxError() { runTest("invalid cons syntax"); } public void testVarargsInConsBug() { runTest("varargs in constructor sig"); } public void testAspectpathdirs() { runTest("dirs on aspectpath"); } public void testIntroSample() { runTest("introduction sample"); } public void testPTWInterface() { runTest("pertypewithin({interface}) illegal field modifier"); } public void testEnumCalledEnumEtc() { runTest("enum called Enum, annotation called Annotation, etc"); } public void testInternalCompilerError_pr86832() { runTest("Internal compiler error"); } public void testCloneMethod_pr83311() { runTest("overriding/polymorphism error on interface method introduction"); } /** * IfPointcut.findResidueInternal() was modified to make this test complete in a short amount * of time - if you see it hanging, someone has messed with the optimization. */ public void testIfEvaluationExplosion_pr94086() { runTest("Exploding compile time with if() statements in pointcut"); } public void testReflectNPE_pr94167() {runTest("NPE in reflect implementation");} public void testStaticImports_pr84260() {runTest("static import failures");} public void testGenerics_pr99089() {runTest("ArrayIndexOutOfBoundsException - Generics in privileged aspects");} public void testGenerics_pr95993() {runTest("NPE at ClassScope.java:660 when compiling generic class");} public void testItdGenerics_pr99228() {runTest("ITD of a field into a generic class");} public void testItdGenerics_pr98320() {runTest("intertype with nested generic type");} public void testItdGenerics_pr100227() {runTest("inner class with generic enclosing class");} public void testItdGenerics_pr100260() {runTest("methods inherited from a generic parent");} public void testSyntaxErrorNPE_pr103266() {runTest("NPE on syntax error");} public void testIllegalStateExceptionOnNestedParameterizedType_pr106634() { runTest("IllegalStateException unpacking signature of nested parameterized type"); } public void testParseErrorOnAnnotationStarPlusPattern() { runTest("(@Foo *)+ type pattern parse error"); } public void test_pr106130_tooManyLocals() { runTest("test weaving with > 256 locals"); } public void testMissingNamePattern_pr106461() { runTest("missing name pattern"); } public void testMissingNamePattern_pr107059() { runTest("parser crashes on call(void (@a *)(..)"); } public void testIntermediateAnnotationMatching() { runTest("intermediate annotation matching"); } public void testBadRuntimeTestGeneration() { runTest("target(@Foo *)"); } public void testErrorMessageOnITDWithTypePatterns() { runTest("clear error message on itd with type pattern"); } public void testAjKeywordsAsIdentifiers() { runTest("before and after are valid identifiers in classes"); } public void testAjKeywordsAsIdentifiers2() { runTest("before and after are valid identifiers in classes, part 2"); } public void testNoBeforeReturningAdvice() { runTest("before returning advice not allowed!"); } public void testDetectVoidFieldType() { runTest("void field type in pointcut expression"); } public void testPointcutOverriding() { runTest("overriding final pointcut from super-aspect"); } public void testAtSuppressWarnings() { runTest("@SuppressWarnings should suppress"); } public void testDEOWWithBindingPointcut() { runTest("declare warning : foo(str) : ...;"); } public void testAroundAdviceAndInterfaceInitializer() { runTest("around advice on interface initializer"); } public void testGoodErrorMessageOnUnmatchedMemberSyntax() { runTest("good error message for unmatched member syntax"); } public void testITDWithNoExceptionAndIntermediary() { runTest("itd override with no exception clause"); } public void testAnonymousInnerClasses() { runTest("anonymous inner classes"); } public void testMultipleAnonymousInnerClasses() { runTest("multiple anonymous inner classes"); } public void testPrivilegedMethodAccessorsGetRightExceptions_pr82989() { runTest("Compiler error due to a wrong exception check in try blocks"); } public void testAnonymousInnerClassWithMethodReturningTypeParameter_pr107898() { runTest("anonymous inner class with method returning type parameter"); } public void testMatchingOfObjectArray() { runTest("matching against Object[]"); } public void testMultipleAnonymousInnerClasses_pr108104() { runTest("multiple anonymous inner classes 2"); } public void testSignatureMatchingInMultipleOverrideScenario() { runTest("signature matching in override scenario"); } public void testWildcardAnnotationMatching_pr108245() { runTest("wildcard annotation matching - pr108245"); } public void testInnerTypesAndTypeVariables() { runTest("inner types and type variables"); } public void testAtAfterThrowingWithNoFormal() { runTest("@AfterThrowing with no formal specified"); } public void testParameterizedVarArgsMatch() { runTest("varargs with type variable"); } public void testFieldAccessInsideITDM() { runTest("itd field access inside itd method"); } public void testTypeVarWithTypeVarBound() { runTest("type variable with type variable bound"); } public void testEnumSwitchInITD() { runTest("switch on enum inside ITD method"); } public void testInnerTypeOfGeneric() { runTest("inner type of generic interface reference from parameterized type"); } public void testDeclareParentsIntroducingCovariantReturnType() { runTest("declare parents introducing override with covariance"); } public void testInnerClassPassedToVarargs() { runTest("inner class passed as argument to varargs method"); } public void testInlinedFieldAccessInProceedCall() { runTest("inlined field access in proceed call"); } public void testVisibiltyInSignatureMatchingWithOverridesPart1() { runTest("visibility in signature matching with overrides - 1"); } public void testVisibiltyInSignatureMatchingWithOverridesPart2() { runTest("visibility in signature matching with overrides - 2"); } public void testVisibiltyInSignatureMatchingWithOverridesPart3() { runTest("visibility in signature matching with overrides - 3"); } // helper methods..... public SyntheticRepository createRepos(File cpentry) { ClassPath cp = new ClassPath(cpentry+File.pathSeparator+System.getProperty("java.class.path")); return SyntheticRepository.getInstance(cp); } protected JavaClass getClassFrom(File where,String clazzname) throws ClassNotFoundException { SyntheticRepository repos = createRepos(where); return repos.loadClass(clazzname); } }
59,196
Bug 59196 "adviceexecution() && args()" pcd does not pick up around advice execution because args() does not match the AroundClosure parameter.
In the following sample, the advice defined in "other_aspect" does not pick up the execution of around advice defined in "some_aspect". It matches only against the before advice defined in "some_aspect". The implicit AroundClosure parameter of an around advice seems to come in the way of args() matching. ------------------------------------------------------ aspect some_aspect { pointcut call_m(int a, int b) : call(int test.m(..)) && args(a, b); before(int x, int y) : call_m(x, y) { ... } int around(int x, int y) : call_m(x, y) { ... } } aspect other_aspect { before(int x, int y) : adviceexecution() && within(some_aspect) && args(x, y){ ... } } -------------------------------------------------------- AspectJ doc has to state this explicitly.
resolved fixed
a66e0a2
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-01T08:30:41Z
2004-04-20T08:33:20Z
weaver/src/org/aspectj/weaver/patterns/ArgsPointcut.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataOutputStream; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Set; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.reflect.CodeSignature; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.BetaException; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.World; import org.aspectj.weaver.ast.Literal; import org.aspectj.weaver.ast.Test; import org.aspectj.weaver.internal.tools.PointcutExpressionImpl; /** * args(arguments) * * @author Erik Hilsdale * @author Jim Hugunin */ public class ArgsPointcut extends NameBindingPointcut { private TypePatternList arguments; public ArgsPointcut(TypePatternList arguments) { this.arguments = arguments; this.pointcutKind = ARGS; } public TypePatternList getArguments() { return arguments; } public Set couldMatchKinds() { return Shadow.ALL_SHADOW_KINDS; // empty args() matches jps with no args } public FuzzyBoolean fastMatch(FastMatchInfo type) { return FuzzyBoolean.MAYBE; } public FuzzyBoolean fastMatch(Class targetType) { return FuzzyBoolean.MAYBE; } protected FuzzyBoolean matchInternal(Shadow shadow) { FuzzyBoolean ret = arguments.matches(shadow.getIWorld().resolve(shadow.getGenericArgTypes()), TypePattern.DYNAMIC); return ret; } public FuzzyBoolean match(JoinPoint jp, JoinPoint.StaticPart jpsp) { FuzzyBoolean ret = arguments.matches(jp.getArgs(),TypePattern.DYNAMIC); // this may have given a false match (e.g. args(int) may have matched a call to doIt(Integer x)) due to boxing // check for this... if (ret == FuzzyBoolean.YES) { // are the sigs compatible too... CodeSignature sig = (CodeSignature)jp.getSignature(); Class[] pTypes = sig.getParameterTypes(); ret = checkSignatureMatch(pTypes); } return ret; } /** * @param ret * @param pTypes * @return */ private FuzzyBoolean checkSignatureMatch(Class[] pTypes) { Collection tps = arguments.getExactTypes(); int sigIndex = 0; for (Iterator iter = tps.iterator(); iter.hasNext();) { UnresolvedType tp = (UnresolvedType) iter.next(); Class lookForClass = getPossiblyBoxed(tp); if (lookForClass != null) { boolean foundMatchInSig = false; while (sigIndex < pTypes.length && !foundMatchInSig) { if (pTypes[sigIndex++] == lookForClass) foundMatchInSig = true; } if (!foundMatchInSig) { return FuzzyBoolean.NO; } } } return FuzzyBoolean.YES; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#matchesDynamically(java.lang.Object, java.lang.Object, java.lang.Object[]) */ public boolean matchesDynamically(Object thisObject, Object targetObject, Object[] args) { return (arguments.matches(args,TypePattern.DYNAMIC) == FuzzyBoolean.YES); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#matchesStatically(java.lang.String, java.lang.reflect.Member, java.lang.Class, java.lang.Class, java.lang.reflect.Member) */ public FuzzyBoolean matchesStatically(String joinpointKind, Member member, Class thisClass, Class targetClass, Member withinCode) { Class[] paramTypes = new Class[0]; if (member instanceof Method) { paramTypes = ((Method)member).getParameterTypes(); } else if (member instanceof Constructor) { paramTypes = ((Constructor)member).getParameterTypes(); } else if (member instanceof PointcutExpressionImpl.Handler){ paramTypes = new Class[] {((PointcutExpressionImpl.Handler)member).getHandledExceptionType()}; } else if (member instanceof Field) { if (joinpointKind.equals(Shadow.FieldGet.getName())) return FuzzyBoolean.NO; // no args here paramTypes = new Class[] {((Field)member).getType()}; } else { return FuzzyBoolean.NO; } return arguments.matchesArgsPatternSubset(paramTypes); } private Class getPossiblyBoxed(UnresolvedType tp) { Class ret = (Class) ExactTypePattern.primitiveTypesMap.get(tp.getName()); if (ret == null) ret = (Class) ExactTypePattern.boxedPrimitivesMap.get(tp.getName()); return ret; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.NameBindingPointcut#getBindingAnnotationTypePatterns() */ public List getBindingAnnotationTypePatterns() { return Collections.EMPTY_LIST; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.NameBindingPointcut#getBindingTypePatterns() */ public List getBindingTypePatterns() { List l = new ArrayList(); TypePattern[] pats = arguments.getTypePatterns(); for (int i = 0; i < pats.length; i++) { if (pats[i] instanceof BindingTypePattern) { l.add(pats[i]); } } return l; } public void write(DataOutputStream s) throws IOException { s.writeByte(Pointcut.ARGS); arguments.write(s); writeLocation(s); } public static Pointcut read(VersionedDataInputStream s, ISourceContext context) throws IOException { ArgsPointcut ret = new ArgsPointcut(TypePatternList.read(s, context)); ret.readLocation(context, s); return ret; } public boolean equals(Object other) { if (!(other instanceof ArgsPointcut)) return false; ArgsPointcut o = (ArgsPointcut)other; return o.arguments.equals(this.arguments); } public int hashCode() { return arguments.hashCode(); } public void resolveBindings(IScope scope, Bindings bindings) { arguments.resolveBindings(scope, bindings, true, true); if (arguments.ellipsisCount > 1) { scope.message(IMessage.ERROR, this, "uses more than one .. in args (compiler limitation)"); } } public void resolveBindingsFromRTTI() { arguments.resolveBindingsFromRTTI(true, true); if (arguments.ellipsisCount > 1) { throw new UnsupportedOperationException("uses more than one .. in args (compiler limitation)"); } } public void postRead(ResolvedType enclosingType) { arguments.postRead(enclosingType); } public Pointcut concretize1(ResolvedType inAspect, IntMap bindings) { if (isDeclare(bindings.getEnclosingAdvice())) { // Enforce rule about which designators are supported in declare inAspect.getWorld().showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ARGS_IN_DECLARE), bindings.getEnclosingAdvice().getSourceLocation(), null); return Pointcut.makeMatchesNothing(Pointcut.CONCRETE); } TypePatternList args = arguments.resolveReferences(bindings); if (inAspect.crosscuttingMembers != null) { inAspect.crosscuttingMembers.exposeTypes(args.getExactTypes()); } Pointcut ret = new ArgsPointcut(args); ret.copyLocationFrom(this); return ret; } private Test findResidueNoEllipsis(Shadow shadow, ExposedState state, TypePattern[] patterns) { int len = shadow.getArgCount(); //System.err.println("boudn to : " + len + ", " + patterns.length); if (patterns.length != len) { return Literal.FALSE; } Test ret = Literal.TRUE; for (int i=0; i < len; i++) { UnresolvedType argType = shadow.getGenericArgTypes()[i]; TypePattern type = patterns[i]; ResolvedType argRTX = shadow.getIWorld().resolve(argType,true); if (!(type instanceof BindingTypePattern)) { if (argRTX == ResolvedType.MISSING) { IMessage msg = new Message( WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_ARG_TYPE,argType.getName()), "",IMessage.ERROR,shadow.getSourceLocation(),null,new ISourceLocation[]{getSourceLocation()}); } if (type.matchesInstanceof(argRTX).alwaysTrue()) { continue; } } else { BindingTypePattern btp = (BindingTypePattern)type; // Check if we have already bound something to this formal if ((state.get(btp.getFormalIndex())!=null) &&(lastMatchedShadowId != shadow.shadowId)) { // ISourceLocation isl = getSourceLocation(); // Message errorMessage = new Message( // "Ambiguous binding of type "+type.getExactType().toString()+ // " using args(..) at this line - formal is already bound"+ // ". See secondary source location for location of args(..)", // shadow.getSourceLocation(),true,new ISourceLocation[]{getSourceLocation()}); // shadow.getIWorld().getMessageHandler().handleMessage(errorMessage); state.setErroneousVar(btp.getFormalIndex()); } } World world = shadow.getIWorld(); ResolvedType typeToExpose = type.getExactType().resolve(world); if (typeToExpose.isParameterizedType()) { boolean inDoubt = (type.matchesInstanceof(argRTX) == FuzzyBoolean.MAYBE); if (inDoubt && world.getLint().uncheckedArgument.isEnabled()) { String uncheckedMatchWith = typeToExpose.getSimpleBaseName(); if (argRTX.isParameterizedType() && (argRTX.getRawType() == typeToExpose.getRawType())) { uncheckedMatchWith = argRTX.getSimpleName(); } if (!isUncheckedArgumentWarningSuppressed()) { world.getLint().uncheckedArgument.signal( new String[] { typeToExpose.getSimpleName(), uncheckedMatchWith, typeToExpose.getSimpleBaseName(), shadow.toResolvedString(world)}, getSourceLocation(), new ISourceLocation[] {shadow.getSourceLocation()}); } } } ret = Test.makeAnd(ret, exposeStateForVar(shadow.getArgVar(i), type, state,shadow.getIWorld())); } return ret; } /** * We need to find out if someone has put the @SuppressAjWarnings{"uncheckedArgument"} * annotation somewhere. That somewhere is going to be an a piece of advice that uses this * pointcut. But how do we find it??? * @return */ private boolean isUncheckedArgumentWarningSuppressed() { return false; } protected Test findResidueInternal(Shadow shadow, ExposedState state) { if (arguments.matches(shadow.getIWorld().resolve(shadow.getGenericArgTypes()), TypePattern.DYNAMIC).alwaysFalse()) { return Literal.FALSE; } int ellipsisCount = arguments.ellipsisCount; if (ellipsisCount == 0) { return findResidueNoEllipsis(shadow, state, arguments.getTypePatterns()); } else if (ellipsisCount == 1) { TypePattern[] patternsWithEllipsis = arguments.getTypePatterns(); TypePattern[] patternsWithoutEllipsis = new TypePattern[shadow.getArgCount()]; int lenWithEllipsis = patternsWithEllipsis.length; int lenWithoutEllipsis = patternsWithoutEllipsis.length; // l1+1 >= l0 int indexWithEllipsis = 0; int indexWithoutEllipsis = 0; while (indexWithoutEllipsis < lenWithoutEllipsis) { TypePattern p = patternsWithEllipsis[indexWithEllipsis++]; if (p == TypePattern.ELLIPSIS) { int newLenWithoutEllipsis = lenWithoutEllipsis - (lenWithEllipsis-indexWithEllipsis); while (indexWithoutEllipsis < newLenWithoutEllipsis) { patternsWithoutEllipsis[indexWithoutEllipsis++] = TypePattern.ANY; } } else { patternsWithoutEllipsis[indexWithoutEllipsis++] = p; } } return findResidueNoEllipsis(shadow, state, patternsWithoutEllipsis); } else { throw new BetaException("unimplemented"); } } public String toString() { return "args" + arguments.toString() + ""; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } }
74,048
Bug 74048 AJDT reports unnecessary compile time warnings for private static aspects
null
resolved fixed
16512b2
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-01T09:38:36Z
2004-09-16T10:20:00Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/problem/AjProblemReporter.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.ajdt.internal.compiler.problem; import java.lang.reflect.Modifier; import java.util.Iterator; import java.util.List; import org.aspectj.ajdt.internal.compiler.ast.PointcutDeclaration; import org.aspectj.ajdt.internal.compiler.ast.Proceed; import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory; import org.aspectj.ajdt.internal.compiler.lookup.InterTypeMethodBinding; import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation; import org.aspectj.org.eclipse.jdt.core.compiler.IProblem; import org.aspectj.org.eclipse.jdt.internal.compiler.CompilationResult; import org.aspectj.org.eclipse.jdt.internal.compiler.IErrorHandlingPolicy; import org.aspectj.org.eclipse.jdt.internal.compiler.IProblemFactory; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.ASTNode; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Annotation; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.ExplicitConstructorCall; import org.aspectj.org.eclipse.jdt.internal.compiler.impl.CompilerOptions; import org.aspectj.org.eclipse.jdt.internal.compiler.impl.ReferenceContext; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ArrayBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.MethodBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TagBits; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.problem.ProblemReporter; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.ConcreteTypeMunger; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.patterns.DeclareAnnotation; import org.aspectj.weaver.patterns.DeclareSoft; /** * Extends problem reporter to support compiler-side implementation of declare soft. * Also overrides error reporting for the need to implement abstract methods to * account for inter-type declarations and pointcut declarations. This second * job might be better done directly in the SourceTypeBinding/ClassScope classes. * * @author Jim Hugunin */ public class AjProblemReporter extends ProblemReporter { private static final boolean DUMP_STACK = false; public EclipseFactory factory; public AjProblemReporter( IErrorHandlingPolicy policy, CompilerOptions options, IProblemFactory problemFactory) { super(policy, options, problemFactory); } public void unhandledException( TypeBinding exceptionType, ASTNode location) { if (!factory.getWorld().getDeclareSoft().isEmpty()) { Shadow callSite = factory.makeShadow(location, referenceContext); Shadow enclosingExec = factory.makeShadow(referenceContext); // PR 72157 - calls to super / this within a constructor are not part of the cons join point. if ((callSite == null) && (enclosingExec.getKind() == Shadow.ConstructorExecution) && (location instanceof ExplicitConstructorCall)) { super.unhandledException(exceptionType, location); return; } // System.err.println("about to show error for unhandled exception: " + new String(exceptionType.sourceName()) + // " at " + location + " in " + referenceContext); for (Iterator i = factory.getWorld().getDeclareSoft().iterator(); i.hasNext(); ) { DeclareSoft d = (DeclareSoft)i.next(); // We need the exceptionType to match the type in the declare soft statement // This means it must either be the same type or a subtype ResolvedType throwException = factory.fromEclipse((ReferenceBinding)exceptionType); FuzzyBoolean isExceptionTypeOrSubtype = d.getException().matchesInstanceof(throwException); if (!isExceptionTypeOrSubtype.alwaysTrue() ) continue; if (callSite != null) { FuzzyBoolean match = d.getPointcut().match(callSite); if (match.alwaysTrue()) { //System.err.println("matched callSite: " + callSite + " with " + d); return; } else if (!match.alwaysFalse()) { //!!! need this check to happen much sooner //throw new RuntimeException("unimplemented, shouldn't have fuzzy match here"); } } if (enclosingExec != null) { FuzzyBoolean match = d.getPointcut().match(enclosingExec); if (match.alwaysTrue()) { //System.err.println("matched enclosingExec: " + enclosingExec + " with " + d); return; } else if (!match.alwaysFalse()) { //!!! need this check to happen much sooner //throw new RuntimeException("unimplemented, shouldn't have fuzzy match here"); } } } } //??? is this always correct if (location instanceof Proceed) { return; } super.unhandledException(exceptionType, location); } private boolean isPointcutDeclaration(MethodBinding binding) { return CharOperation.prefixEquals(PointcutDeclaration.mangledPrefix, binding.selector); } private boolean isIntertypeDeclaration(MethodBinding binding) { return (binding instanceof InterTypeMethodBinding); } public void abstractMethodCannotBeOverridden( SourceTypeBinding type, MethodBinding concreteMethod) { if (isPointcutDeclaration(concreteMethod)) { return; } super.abstractMethodCannotBeOverridden(type, concreteMethod); } public void inheritedMethodReducesVisibility(SourceTypeBinding type, MethodBinding concreteMethod, MethodBinding[] abstractMethods) { // if we implemented this method by a public inter-type declaration, then there is no error ResolvedType onTypeX = null; // If the type is anonymous, look at its supertype if (!type.isAnonymousType()) { onTypeX = factory.fromEclipse(type); } else { // Hmmm. If the ITD is on an interface that is being 'instantiated' using an anonymous type, // we sort it out elsewhere and don't come into this method - // so we don't have to worry about interfaces, just the superclass. onTypeX = factory.fromEclipse(type.superclass()); //abstractMethod.declaringClass); } for (Iterator i = onTypeX.getInterTypeMungersIncludingSupers().iterator(); i.hasNext(); ) { ConcreteTypeMunger m = (ConcreteTypeMunger)i.next(); ResolvedMember sig = m.getSignature(); if (!Modifier.isAbstract(sig.getModifiers())) { if (ResolvedType .matches( AjcMemberMaker.interMethod( sig, m.getAspectType(), sig.getDeclaringType().resolve(factory.getWorld()).isInterface()), factory.makeResolvedMember(concreteMethod))) { return; } } } super.inheritedMethodReducesVisibility(type,concreteMethod,abstractMethods); } // if either of the MethodBinding is an ITD, we have already reported it. public void staticAndInstanceConflict(MethodBinding currentMethod, MethodBinding inheritedMethod) { if (currentMethod instanceof InterTypeMethodBinding) return; if (inheritedMethod instanceof InterTypeMethodBinding) return; super.staticAndInstanceConflict(currentMethod, inheritedMethod); } public void abstractMethodMustBeImplemented( SourceTypeBinding type, MethodBinding abstractMethod) { // if this is a PointcutDeclaration then there is no error if (isPointcutDeclaration(abstractMethod)) return; if (isIntertypeDeclaration(abstractMethod)) return; // when there is a problem with an ITD not being implemented, it will be reported elsewhere if (CharOperation.prefixEquals("ajc$interField".toCharArray(), abstractMethod.selector)) { //??? think through how this could go wrong return; } // if we implemented this method by an inter-type declaration, then there is no error //??? be sure this is always right ResolvedType onTypeX = null; // If the type is anonymous, look at its supertype if (!type.isAnonymousType()) { onTypeX = factory.fromEclipse(type); } else { // Hmmm. If the ITD is on an interface that is being 'instantiated' using an anonymous type, // we sort it out elsewhere and don't come into this method - // so we don't have to worry about interfaces, just the superclass. onTypeX = factory.fromEclipse(type.superclass()); //abstractMethod.declaringClass); } for (Iterator i = onTypeX.getInterTypeMungersIncludingSupers().iterator(); i.hasNext(); ) { ConcreteTypeMunger m = (ConcreteTypeMunger)i.next(); ResolvedMember sig = m.getSignature(); if (!Modifier.isAbstract(sig.getModifiers())) { if (ResolvedType .matches( AjcMemberMaker.interMethod( sig, m.getAspectType(), sig.getDeclaringType().resolve(factory.getWorld()).isInterface()), factory.makeResolvedMember(abstractMethod))) { return; } } } super.abstractMethodMustBeImplemented(type, abstractMethod); } /* (non-Javadoc) * @see org.aspectj.org.eclipse.jdt.internal.compiler.problem.ProblemReporter#disallowedTargetForAnnotation(org.aspectj.org.eclipse.jdt.internal.compiler.ast.Annotation) */ public void disallowedTargetForAnnotation(Annotation annotation) { // if the annotation's recipient is an ITD, it might be allowed after all... if (annotation.recipient instanceof MethodBinding) { MethodBinding binding = (MethodBinding) annotation.recipient; String name = new String(binding.selector); if (name.startsWith("ajc$")) { long metaTagBits = annotation.resolvedType.getAnnotationTagBits(); // could be forward reference if (name.indexOf("interField") != -1) { if ((metaTagBits & TagBits.AnnotationForField) != 0) return; } else if (name.indexOf("interConstructor") != -1) { if ((metaTagBits & TagBits.AnnotationForConstructor) != 0) return; } else if (name.indexOf("interMethod") != -1) { if ((metaTagBits & TagBits.AnnotationForMethod) != 0) return; } else if (name.indexOf("declare_"+DeclareAnnotation.AT_TYPE+"_")!=-1) { if ((metaTagBits & TagBits.AnnotationForAnnotationType)!=0 || (metaTagBits & TagBits.AnnotationForType)!=0) return; } else if (name.indexOf("declare_"+DeclareAnnotation.AT_FIELD+"_")!=-1) { if ((metaTagBits & TagBits.AnnotationForField)!=0) return; } else if (name.indexOf("declare_"+DeclareAnnotation.AT_CONSTRUCTOR+"_")!=-1) { if ((metaTagBits & TagBits.AnnotationForConstructor)!=0) return; } else if (name.indexOf("declare_eow") != -1) { if ((metaTagBits & TagBits.AnnotationForField) != 0) return; } } } // not our special case, report the problem... super.disallowedTargetForAnnotation(annotation); } public void handle( int problemId, String[] problemArguments, String[] messageArguments, int severity, int problemStartPosition, int problemEndPosition, ReferenceContext referenceContext, CompilationResult unitResult) { if (severity != Ignore && DUMP_STACK) { Thread.dumpStack(); } super.handle( problemId, problemArguments, messageArguments, severity, problemStartPosition, problemEndPosition, referenceContext, unitResult); } // PR71076 public void javadocMissingParamTag(char[] name, int sourceStart, int sourceEnd, int modifiers) { boolean reportIt = true; String sName = new String(name); if (sName.startsWith("ajc$")) reportIt = false; if (sName.equals("thisJoinPoint")) reportIt = false; if (sName.equals("thisJoinPointStaticPart")) reportIt = false; if (sName.equals("thisEnclosingJoinPointStaticPart")) reportIt = false; if (sName.equals("ajc_aroundClosure")) reportIt = false; if (reportIt) super.javadocMissingParamTag(name,sourceStart,sourceEnd,modifiers); } public void abstractMethodInAbstractClass(SourceTypeBinding type, AbstractMethodDeclaration methodDecl) { String abstractMethodName = new String(methodDecl.selector); if (abstractMethodName.startsWith("ajc$pointcut")) { // This will already have been reported, see: PointcutDeclaration.postParse() return; } String[] arguments = new String[] {new String(type.sourceName()), abstractMethodName}; super.handle( IProblem.AbstractMethodInAbstractClass, arguments, arguments, methodDecl.sourceStart, methodDecl.sourceEnd,this.referenceContext, this.referenceContext == null ? null : this.referenceContext.compilationResult()); } /** * Called when there is an ITD marked @override that doesn't override a supertypes method. * The method and the binding are passed - some information is useful from each. The 'method' * knows about source offsets for the message, the 'binding' has the signature of what the * ITD is trying to be in the target class. */ public void itdMethodMustOverride(AbstractMethodDeclaration method,MethodBinding binding) { this.handle( IProblem.MethodMustOverride, new String[] {new String(binding.selector), typesAsString(binding.isVarargs(), binding.parameters, false), new String(binding.declaringClass.readableName()), }, new String[] {new String(binding.selector), typesAsString(binding.isVarargs(), binding.parameters, true), new String(binding.declaringClass.shortReadableName()),}, method.sourceStart, method.sourceEnd, this.referenceContext, this.referenceContext == null ? null : this.referenceContext.compilationResult()); } /** * Overrides the implementation in ProblemReporter and is ITD aware. * To report a *real* problem with an ITD marked @override, the other methodMustOverride() method is used. */ public void methodMustOverride(AbstractMethodDeclaration method) { MethodBinding binding = method.binding; // ignore ajc$ methods if (new String(method.selector).startsWith("ajc$")) return; ResolvedMember possiblyErroneousRm = factory.makeResolvedMember(method.binding); ResolvedType onTypeX = factory.fromEclipse(method.binding.declaringClass); // Can't use 'getInterTypeMungersIncludingSupers()' since that will exclude abstract ITDs // on any super classes - so we have to trawl up ourselves.. I wonder if this problem // affects other code in the problem reporter that looks through ITDs... ResolvedType supertypeToLookAt = onTypeX.getSuperclass(); while (supertypeToLookAt!=null) { List itMungers = supertypeToLookAt.getInterTypeMungers(); for (Iterator i = itMungers.iterator(); i.hasNext(); ) { ConcreteTypeMunger m = (ConcreteTypeMunger)i.next(); ResolvedMember sig = m.getSignature(); ResolvedMember rm = AjcMemberMaker.interMethod(sig,m.getAspectType(), sig.getDeclaringType().resolve(factory.getWorld()).isInterface()); if (ResolvedType.matches(rm,possiblyErroneousRm)) { // match, so dont need to report a problem! return; } } supertypeToLookAt = supertypeToLookAt.getSuperclass(); } // report the error... super.methodMustOverride(method); } private String typesAsString(boolean isVarargs, TypeBinding[] types, boolean makeShort) { StringBuffer buffer = new StringBuffer(10); for (int i = 0, length = types.length; i < length; i++) { if (i != 0) buffer.append(", "); //$NON-NLS-1$ TypeBinding type = types[i]; boolean isVarargType = isVarargs && i == length-1; if (isVarargType) type = ((ArrayBinding)type).elementsType(); buffer.append(new String(makeShort ? type.shortReadableName() : type.readableName())); if (isVarargType) buffer.append("..."); //$NON-NLS-1$ } return buffer.toString(); } public void visibilityConflict(MethodBinding currentMethod, MethodBinding inheritedMethod) { // Not quite sure if the conditions on this test are right - basically I'm saying // DONT WORRY if its ITDs since the error will be reported another way... if (isIntertypeDeclaration(currentMethod) && isIntertypeDeclaration(inheritedMethod) && Modifier.isPrivate(currentMethod.modifiers) && Modifier.isPrivate(inheritedMethod.modifiers)) { return; } super.visibilityConflict(currentMethod,inheritedMethod); } }
74,048
Bug 74048 AJDT reports unnecessary compile time warnings for private static aspects
null
resolved fixed
16512b2
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-01T09:38:36Z
2004-09-16T10:20:00Z
tests/src/org/aspectj/systemtest/ajc150/Ajc150Tests.java
/******************************************************************************* * Copyright (c) 2004 IBM * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Andy Clement - initial API and implementation *******************************************************************************/ package org.aspectj.systemtest.ajc150; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import junit.framework.Test; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.apache.bcel.classfile.Method; import org.aspectj.apache.bcel.util.ClassPath; import org.aspectj.apache.bcel.util.SyntheticRepository; import org.aspectj.asm.AsmManager; import org.aspectj.testing.XMLBasedAjcTestCase; import org.aspectj.util.LangUtil; /** * These are tests that will run on Java 1.4 and use the old harness format for test specification. */ public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase { public static Test suite() { return XMLBasedAjcTestCase.loadSuite(Ajc150Tests.class); } protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml"); } public void test_typeProcessingOrderWhenDeclareParents() { runTest("Order of types passed to compiler determines weaving behavior"); } public void test_aroundMethod() { runTest("method called around in class"); } public void test_aroundMethodAspect() { runTest("method called around in aspect"); } public void test_ambiguousBindingsDetection() { runTest("Various kinds of ambiguous bindings"); } public void test_ambiguousArgsDetection() { runTest("ambiguous args"); } public void testIncorrectExceptionTableWhenBreakInMethod_pr78021() { runTest("Injecting exception into while loop with break statement causes catch block to be ignored"); } public void testIncorrectExceptionTableWhenReturnInMethod_pr79554() { runTest("Return in try-block disables catch-block if final-block is present"); } public void testMissingDebugInfoForGeneratedMethods_pr82570() throws ClassNotFoundException { runTest("Weaved code does not include debug lines"); boolean f = false; JavaClass jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1"); Method[] meths = jc.getMethods(); for (int i = 0; i < meths.length; i++) { Method method = meths[i]; if (f) System.err.println("Line number table for "+method.getName()+method.getSignature()+" = "+method.getLineNumberTable()); assertTrue("Didn't find a line number table for method "+method.getName()+method.getSignature(), method.getLineNumberTable()!=null); } // This test would determine the info isn't there if you pass -g:none ... // cR = ajc(baseDir,new String[]{"PR82570_1.java","-g:none"}); // assertTrue("Expected no compile problem:"+cR,!cR.hasErrorMessages()); // System.err.println(cR.getStandardError()); // jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1"); // meths = jc.getMethods(); // for (int i = 0; i < meths.length; i++) { // Method method = meths[i]; // assertTrue("Found a line number table for method "+method.getName(), // method.getLineNumberTable()==null); // } } public void testCanOverrideProtectedMethodsViaITDandDecp_pr83303() { runTest("compiler error when mixing inheritance, overriding and polymorphism"); } public void testPerTypeWithinMissesNamedInnerTypes() { runTest("pertypewithin() handing of inner classes (1)"); } public void testPerTypeWithinMissesAnonymousInnerTypes() { runTest("pertypewithin() handing of inner classes (2)"); } public void testPerTypeWithinIncorrectlyMatchingInterfaces() { runTest("pertypewithin({interface}) illegal field modifier"); } public void test051_arrayCloningInJava5() { runTest("AJC possible bug with static nested classes"); } public void testBadASMforEnums() throws IOException { runTest("bad asm for enums"); if (LangUtil.is15VMOrGreater()) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintWriter pw = new PrintWriter(baos); AsmManager.dumptree(pw,AsmManager.getDefault().getHierarchy().getRoot(),0); pw.flush(); String tree = baos.toString(); assertTrue("Expected 'Red [enumvalue]' somewhere in here:"+tree,tree.indexOf("Red [enumvalue]")!=-1); } } public void npeOnTypeNotFound() { runTest("structure model npe on type not found"); } public void testNoRuntimeExceptionSoftening() { runTest("declare soft of runtime exception"); } public void testRuntimeNoSoftenWithHandler() { runTest("declare soft w. catch block"); } public void testSyntaxError() { runTest("invalid cons syntax"); } public void testVarargsInConsBug() { runTest("varargs in constructor sig"); } public void testAspectpathdirs() { runTest("dirs on aspectpath"); } public void testIntroSample() { runTest("introduction sample"); } public void testPTWInterface() { runTest("pertypewithin({interface}) illegal field modifier"); } public void testEnumCalledEnumEtc() { runTest("enum called Enum, annotation called Annotation, etc"); } public void testInternalCompilerError_pr86832() { runTest("Internal compiler error"); } public void testCloneMethod_pr83311() { runTest("overriding/polymorphism error on interface method introduction"); } /** * IfPointcut.findResidueInternal() was modified to make this test complete in a short amount * of time - if you see it hanging, someone has messed with the optimization. */ public void testIfEvaluationExplosion_pr94086() { runTest("Exploding compile time with if() statements in pointcut"); } public void testReflectNPE_pr94167() {runTest("NPE in reflect implementation");} public void testStaticImports_pr84260() {runTest("static import failures");} public void testGenerics_pr99089() {runTest("ArrayIndexOutOfBoundsException - Generics in privileged aspects");} public void testGenerics_pr95993() {runTest("NPE at ClassScope.java:660 when compiling generic class");} public void testItdGenerics_pr99228() {runTest("ITD of a field into a generic class");} public void testItdGenerics_pr98320() {runTest("intertype with nested generic type");} public void testItdGenerics_pr100227() {runTest("inner class with generic enclosing class");} public void testItdGenerics_pr100260() {runTest("methods inherited from a generic parent");} public void testSyntaxErrorNPE_pr103266() {runTest("NPE on syntax error");} public void testIllegalStateExceptionOnNestedParameterizedType_pr106634() { runTest("IllegalStateException unpacking signature of nested parameterized type"); } public void testParseErrorOnAnnotationStarPlusPattern() { runTest("(@Foo *)+ type pattern parse error"); } public void test_pr106130_tooManyLocals() { runTest("test weaving with > 256 locals"); } public void testMissingNamePattern_pr106461() { runTest("missing name pattern"); } public void testMissingNamePattern_pr107059() { runTest("parser crashes on call(void (@a *)(..)"); } public void testIntermediateAnnotationMatching() { runTest("intermediate annotation matching"); } public void testBadRuntimeTestGeneration() { runTest("target(@Foo *)"); } public void testErrorMessageOnITDWithTypePatterns() { runTest("clear error message on itd with type pattern"); } public void testAjKeywordsAsIdentifiers() { runTest("before and after are valid identifiers in classes"); } public void testAjKeywordsAsIdentifiers2() { runTest("before and after are valid identifiers in classes, part 2"); } public void testNoBeforeReturningAdvice() { runTest("before returning advice not allowed!"); } public void testDetectVoidFieldType() { runTest("void field type in pointcut expression"); } public void testPointcutOverriding() { runTest("overriding final pointcut from super-aspect"); } public void testAtSuppressWarnings() { runTest("@SuppressWarnings should suppress"); } public void testDEOWWithBindingPointcut() { runTest("declare warning : foo(str) : ...;"); } public void testAroundAdviceAndInterfaceInitializer() { runTest("around advice on interface initializer"); } public void testGoodErrorMessageOnUnmatchedMemberSyntax() { runTest("good error message for unmatched member syntax"); } public void testITDWithNoExceptionAndIntermediary() { runTest("itd override with no exception clause"); } public void testAnonymousInnerClasses() { runTest("anonymous inner classes"); } public void testMultipleAnonymousInnerClasses() { runTest("multiple anonymous inner classes"); } public void testPrivilegedMethodAccessorsGetRightExceptions_pr82989() { runTest("Compiler error due to a wrong exception check in try blocks"); } public void testAnonymousInnerClassWithMethodReturningTypeParameter_pr107898() { runTest("anonymous inner class with method returning type parameter"); } public void testMatchingOfObjectArray() { runTest("matching against Object[]"); } public void testMultipleAnonymousInnerClasses_pr108104() { runTest("multiple anonymous inner classes 2"); } public void testSignatureMatchingInMultipleOverrideScenario() { runTest("signature matching in override scenario"); } public void testWildcardAnnotationMatching_pr108245() { runTest("wildcard annotation matching - pr108245"); } public void testInnerTypesAndTypeVariables() { runTest("inner types and type variables"); } public void testAtAfterThrowingWithNoFormal() { runTest("@AfterThrowing with no formal specified"); } public void testParameterizedVarArgsMatch() { runTest("varargs with type variable"); } public void testFieldAccessInsideITDM() { runTest("itd field access inside itd method"); } public void testTypeVarWithTypeVarBound() { runTest("type variable with type variable bound"); } public void testEnumSwitchInITD() { runTest("switch on enum inside ITD method"); } public void testInnerTypeOfGeneric() { runTest("inner type of generic interface reference from parameterized type"); } public void testDeclareParentsIntroducingCovariantReturnType() { runTest("declare parents introducing override with covariance"); } public void testInnerClassPassedToVarargs() { runTest("inner class passed as argument to varargs method"); } public void testInlinedFieldAccessInProceedCall() { runTest("inlined field access in proceed call"); } public void testVisibiltyInSignatureMatchingWithOverridesPart1() { runTest("visibility in signature matching with overrides - 1"); } public void testVisibiltyInSignatureMatchingWithOverridesPart2() { runTest("visibility in signature matching with overrides - 2"); } public void testVisibiltyInSignatureMatchingWithOverridesPart3() { runTest("visibility in signature matching with overrides - 3"); } public void testArgsGeneratedCorrectlyForAdviceExecution() { runTest("args generated correctly for advice execution join point"); } // helper methods..... public SyntheticRepository createRepos(File cpentry) { ClassPath cp = new ClassPath(cpentry+File.pathSeparator+System.getProperty("java.class.path")); return SyntheticRepository.getInstance(cp); } protected JavaClass getClassFrom(File where,String clazzname) throws ClassNotFoundException { SyntheticRepository repos = createRepos(where); return repos.loadClass(clazzname); } }
59,076
Bug 59076 Reduce footprint of JoinPoint.StaticPart objects
Tests show that each object consumes 180+ bytes. For a large project (1000+ classes) where an aspect is used to implement a pervasive cross-cutting concern e.g. exception logging this can lead to >1MB of additional heap space. Two possible approaches could be: 1. Break literal String used by Factory.makeXXXSig() methods into component parts e.g. package, class, method. ... names. These could then be shared automatically by the JVM as interned Strings. 2. Lazy instantiation of handler static JPs in the catch block. Any enhancements could be enabled by a compiler option similar to -XlazyTjp.
resolved fixed
a5e645f
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-01T14:17:29Z
2004-04-19T15:53:20Z
runtime/src/org/aspectj/runtime/reflect/Factory.java
/* ******************************************************************* * Copyright (c) 1999-2001 Xerox Corporation, * 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Xerox/PARC initial implementation * Alex Vasseur new factory methods for variants of JP * ******************************************************************/ package org.aspectj.runtime.reflect; import java.lang.reflect.Constructor; import java.lang.reflect.Member; import java.lang.reflect.Method; import org.aspectj.lang.*; import org.aspectj.lang.reflect.*; public final class Factory { Class lexicalClass; ClassLoader lookupClassLoader; String filename; public Factory(String filename, Class lexicalClass) { //System.out.println("making this.filename = filename; this.lexicalClass = lexicalClass; lookupClassLoader = lexicalClass.getClassLoader(); } public JoinPoint.StaticPart makeSJP(String kind, Signature sig, SourceLocation loc) { return new JoinPointImpl.StaticPartImpl(kind, sig, loc); } public JoinPoint.StaticPart makeSJP(String kind, Signature sig, int l, int c) { return new JoinPointImpl.StaticPartImpl(kind, sig, makeSourceLoc(l, c)); } public JoinPoint.StaticPart makeSJP(String kind, Signature sig, int l) { return new JoinPointImpl.StaticPartImpl(kind, sig, makeSourceLoc(l, -1)); } public JoinPoint.EnclosingStaticPart makeESJP(String kind, Signature sig, SourceLocation loc) { return new JoinPointImpl.EnclosingStaticPartImpl(kind, sig, loc); } public JoinPoint.EnclosingStaticPart makeESJP(String kind, Signature sig, int l, int c) { return new JoinPointImpl.EnclosingStaticPartImpl(kind, sig, makeSourceLoc(l, c)); } public JoinPoint.EnclosingStaticPart makeESJP(String kind, Signature sig, int l) { return new JoinPointImpl.EnclosingStaticPartImpl(kind, sig, makeSourceLoc(l, -1)); } public static JoinPoint.StaticPart makeEncSJP(Member member) { Signature sig = null; String kind = null; if (member instanceof Method) { Method method = (Method) member; sig = new MethodSignatureImpl(method.getModifiers(),method.getName(), method.getDeclaringClass(),method.getParameterTypes(), new String[method.getParameterTypes().length], method.getExceptionTypes(),method.getReturnType()); kind = JoinPoint.METHOD_EXECUTION; } else if (member instanceof Constructor) { Constructor cons = (Constructor) member; sig = new ConstructorSignatureImpl(cons.getModifiers(),cons.getDeclaringClass(), cons.getParameterTypes(), new String[cons.getParameterTypes().length], cons.getExceptionTypes()); kind = JoinPoint.CONSTRUCTOR_EXECUTION; } else { throw new IllegalArgumentException("member must be either a method or constructor"); } return new JoinPointImpl.EnclosingStaticPartImpl(kind,sig,null); } private static Object[] NO_ARGS = new Object[0]; public static JoinPoint makeJP(JoinPoint.StaticPart staticPart, Object _this, Object target) { return new JoinPointImpl(staticPart, _this, target, NO_ARGS); } public static JoinPoint makeJP(JoinPoint.StaticPart staticPart, Object _this, Object target, Object arg0) { return new JoinPointImpl(staticPart, _this, target, new Object[] {arg0}); } public static JoinPoint makeJP(JoinPoint.StaticPart staticPart, Object _this, Object target, Object arg0, Object arg1) { return new JoinPointImpl(staticPart, _this, target, new Object[] {arg0, arg1}); } public static JoinPoint makeJP(JoinPoint.StaticPart staticPart, Object _this, Object target, Object[] args) { return new JoinPointImpl(staticPart, _this, target, args); } public MethodSignature makeMethodSig(String stringRep) { MethodSignatureImpl ret = new MethodSignatureImpl(stringRep); ret.setLookupClassLoader(lookupClassLoader); return ret; } public MethodSignature makeMethodSig(int modifiers, String name, Class declaringType, Class[] parameterTypes, String[] parameterNames, Class[] exceptionTypes, Class returnType) { MethodSignatureImpl ret = new MethodSignatureImpl(modifiers,name,declaringType,parameterTypes,parameterNames,exceptionTypes,returnType); ret.setLookupClassLoader(lookupClassLoader); return ret; } public ConstructorSignature makeConstructorSig(String stringRep) { ConstructorSignatureImpl ret = new ConstructorSignatureImpl(stringRep); ret.setLookupClassLoader(lookupClassLoader); return ret; } public ConstructorSignature makeConstructorSig(int modifiers, Class declaringType, Class[] parameterTypes, String[] parameterNames, Class[] exceptionTypes) { ConstructorSignatureImpl ret = new ConstructorSignatureImpl(modifiers,declaringType,parameterTypes,parameterNames,exceptionTypes); ret.setLookupClassLoader(lookupClassLoader); return ret; } public FieldSignature makeFieldSig(String stringRep) { FieldSignatureImpl ret = new FieldSignatureImpl(stringRep); ret.setLookupClassLoader(lookupClassLoader); return ret; } public FieldSignature makeFieldSig(int modifiers, String name, Class declaringType, Class fieldType) { FieldSignatureImpl ret = new FieldSignatureImpl(modifiers,name,declaringType,fieldType); ret.setLookupClassLoader(lookupClassLoader); return ret; } public AdviceSignature makeAdviceSig(String stringRep) { AdviceSignatureImpl ret = new AdviceSignatureImpl(stringRep); ret.setLookupClassLoader(lookupClassLoader); return ret; } public AdviceSignature makeAdviceSig(int modifiers, String name, Class declaringType, Class[] parameterTypes, String[] parameterNames, Class[] exceptionTypes, Class returnType) { AdviceSignatureImpl ret = new AdviceSignatureImpl(modifiers,name,declaringType,parameterTypes,parameterNames,exceptionTypes,returnType); ret.setLookupClassLoader(lookupClassLoader); return ret; } public InitializerSignature makeInitializerSig(String stringRep) { InitializerSignatureImpl ret = new InitializerSignatureImpl(stringRep); ret.setLookupClassLoader(lookupClassLoader); return ret; } public InitializerSignature makeInitializerSig(int modifiers, Class declaringType) { InitializerSignatureImpl ret = new InitializerSignatureImpl(modifiers,declaringType); ret.setLookupClassLoader(lookupClassLoader); return ret; } public CatchClauseSignature makeCatchClauseSig(String stringRep) { CatchClauseSignatureImpl ret = new CatchClauseSignatureImpl(stringRep); ret.setLookupClassLoader(lookupClassLoader); return ret; } public CatchClauseSignature makeCatchClauseSig(Class declaringType, Class parameterType, String parameterName) { CatchClauseSignatureImpl ret = new CatchClauseSignatureImpl(declaringType,parameterType,parameterName); ret.setLookupClassLoader(lookupClassLoader); return ret; } public SourceLocation makeSourceLoc(int line, int col) { return new SourceLocationImpl(lexicalClass, this.filename, line); } }
59,076
Bug 59076 Reduce footprint of JoinPoint.StaticPart objects
Tests show that each object consumes 180+ bytes. For a large project (1000+ classes) where an aspect is used to implement a pervasive cross-cutting concern e.g. exception logging this can lead to >1MB of additional heap space. Two possible approaches could be: 1. Break literal String used by Factory.makeXXXSig() methods into component parts e.g. package, class, method. ... names. These could then be shared automatically by the JVM as interned Strings. 2. Lazy instantiation of handler static JPs in the catch block. Any enhancements could be enabled by a compiler option similar to -XlazyTjp.
resolved fixed
a5e645f
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-01T14:17:29Z
2004-04-19T15:53:20Z
runtime/src/org/aspectj/runtime/reflect/SignatureImpl.java
/* ******************************************************************* * Copyright (c) 1999-2001 Xerox Corporation, * 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Xerox/PARC initial implementation * ******************************************************************/ package org.aspectj.runtime.reflect; import org.aspectj.lang.Signature; import java.lang.ref.SoftReference; import java.util.Hashtable; import java.util.StringTokenizer; abstract class SignatureImpl implements Signature { private static boolean useCache = true; int modifiers = -1; String name; String declaringTypeName; Class declaringType; SoftReference toStringCacheRef; SignatureImpl(int modifiers, String name, Class declaringType) { this.modifiers = modifiers; this.name = name; this.declaringType = declaringType; } protected abstract String createToString (StringMaker sm); /* Use a soft cache for the short, middle and long String representations */ String toString (StringMaker sm) { String[] toStringCache = null; if (toStringCacheRef == null || toStringCacheRef.get() == null) { toStringCache = new String[3]; if (useCache) toStringCacheRef = new SoftReference(toStringCache); } else { toStringCache = (String[])toStringCacheRef.get(); } if (toStringCache[sm.cacheOffset] == null) { toStringCache[sm.cacheOffset] = createToString(sm); } return toStringCache[sm.cacheOffset]; } public final String toString() { return toString(StringMaker.middleStringMaker); } public final String toShortString() { return toString(StringMaker.shortStringMaker); } public final String toLongString() { return toString(StringMaker.longStringMaker); } public int getModifiers() { if (modifiers == -1) modifiers = extractInt(0); return modifiers; } public String getName() { if (name == null) name = extractString(1); return name; } public Class getDeclaringType() { if (declaringType == null) declaringType = extractType(2); return declaringType; } public String getDeclaringTypeName() { if (declaringTypeName == null) { declaringTypeName = getDeclaringType().getName(); } return declaringTypeName; } String fullTypeName(Class type) { if (type == null) return "ANONYMOUS"; if (type.isArray()) return fullTypeName(type.getComponentType()) + "[]"; return type.getName().replace('$', '.'); } String stripPackageName(String name) { int dot = name.lastIndexOf('.'); if (dot == -1) return name; return name.substring(dot+1); } String shortTypeName(Class type) { if (type == null) return "ANONYMOUS"; if (type.isArray()) return shortTypeName(type.getComponentType()) + "[]"; return stripPackageName(type.getName()).replace('$', '.'); } void addFullTypeNames(StringBuffer buf, Class[] types) { for (int i = 0; i < types.length; i++) { if (i > 0) buf.append(", "); buf.append(fullTypeName(types[i])); } } void addShortTypeNames(StringBuffer buf, Class[] types) { for (int i = 0; i < types.length; i++) { if (i > 0) buf.append(", "); buf.append(shortTypeName(types[i])); } } void addTypeArray(StringBuffer buf, Class[] types) { addFullTypeNames(buf, types); } // lazy version private String stringRep; ClassLoader lookupClassLoader = null; public void setLookupClassLoader(ClassLoader loader) { this.lookupClassLoader = loader; } private ClassLoader getLookupClassLoader() { if (lookupClassLoader == null) lookupClassLoader = this.getClass().getClassLoader(); return lookupClassLoader; } public SignatureImpl(String stringRep) { this.stringRep = stringRep; } static final char SEP = '-'; String extractString(int n) { //System.out.println(n + ": from " + stringRep); int startIndex = 0; int endIndex = stringRep.indexOf(SEP); while (n-- > 0) { startIndex = endIndex+1; endIndex = stringRep.indexOf(SEP, startIndex); } if (endIndex == -1) endIndex = stringRep.length(); //System.out.println(" " + stringRep.substring(startIndex, endIndex)); return stringRep.substring(startIndex, endIndex); } int extractInt(int n) { String s = extractString(n); return Integer.parseInt(s, 16); } Class extractType(int n) { String s = extractString(n); return makeClass(s); } static Hashtable prims = new Hashtable(); static { prims.put("void", Void.TYPE); prims.put("boolean", Boolean.TYPE); prims.put("byte", Byte.TYPE); prims.put("char", Character.TYPE); prims.put("short", Short.TYPE); prims.put("int", Integer.TYPE); prims.put("long", Long.TYPE); prims.put("float", Float.TYPE); prims.put("double", Double.TYPE); } Class makeClass(String s) { if (s.equals("*")) return null; Class ret = (Class)prims.get(s); if (ret != null) return ret; try { /* The documentation of Class.forName explains why this is the right thing * better than I could here. */ ClassLoader loader = getLookupClassLoader(); if (loader == null) { return Class.forName(s); } else { // used to be 'return loader.loadClass(s)' but that didn't cause // array types to be created and loaded correctly. (pr70404) return Class.forName(s,false,loader); } } catch (ClassNotFoundException e) { //System.out.println("null for: " + s); //XXX there should be a better return value for this return ClassNotFoundException.class; } } static String[] EMPTY_STRING_ARRAY = new String[0]; static Class[] EMPTY_CLASS_ARRAY = new Class[0]; static final String INNER_SEP = ":"; String[] extractStrings(int n) { String s = extractString(n); StringTokenizer st = new StringTokenizer(s, INNER_SEP); final int N = st.countTokens(); String[] ret = new String[N]; for (int i = 0; i < N; i++) ret[i]= st.nextToken(); return ret; } Class[] extractTypes(int n) { String s = extractString(n); StringTokenizer st = new StringTokenizer(s, INNER_SEP); final int N = st.countTokens(); Class[] ret = new Class[N]; for (int i = 0; i < N; i++) ret[i]= makeClass(st.nextToken()); return ret; } /* * Used for testing */ static void setUseCache (boolean b) { useCache = b; } static boolean getUseCache () { return useCache; } }
59,076
Bug 59076 Reduce footprint of JoinPoint.StaticPart objects
Tests show that each object consumes 180+ bytes. For a large project (1000+ classes) where an aspect is used to implement a pervasive cross-cutting concern e.g. exception logging this can lead to >1MB of additional heap space. Two possible approaches could be: 1. Break literal String used by Factory.makeXXXSig() methods into component parts e.g. package, class, method. ... names. These could then be shared automatically by the JVM as interned Strings. 2. Lazy instantiation of handler static JPs in the catch block. Any enhancements could be enabled by a compiler option similar to -XlazyTjp.
resolved fixed
a5e645f
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-01T14:17:29Z
2004-04-19T15:53:20Z
weaver/src/org/aspectj/weaver/bcel/LazyClassGen.java
/* ******************************************************************* * Copyright (c) 2002 Contributors * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * Andy Clement 6Jul05 generics - signature attribute * ******************************************************************/ package org.aspectj.weaver.bcel; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import org.aspectj.apache.bcel.Constants; import org.aspectj.apache.bcel.classfile.Attribute; import org.aspectj.apache.bcel.classfile.ConstantUtf8; import org.aspectj.apache.bcel.classfile.Field; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.apache.bcel.classfile.Method; import org.aspectj.apache.bcel.classfile.Signature; import org.aspectj.apache.bcel.classfile.Unknown; import org.aspectj.apache.bcel.classfile.annotation.Annotation; import org.aspectj.apache.bcel.generic.ClassGen; import org.aspectj.apache.bcel.generic.ConstantPoolGen; import org.aspectj.apache.bcel.generic.FieldGen; import org.aspectj.apache.bcel.generic.InstructionConstants; import org.aspectj.apache.bcel.generic.InstructionFactory; import org.aspectj.apache.bcel.generic.InstructionHandle; import org.aspectj.apache.bcel.generic.InstructionList; import org.aspectj.apache.bcel.generic.ObjectType; import org.aspectj.apache.bcel.generic.PUSH; import org.aspectj.apache.bcel.generic.RETURN; import org.aspectj.apache.bcel.generic.Type; import org.aspectj.apache.bcel.generic.annotation.AnnotationGen; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.SourceLocation; import org.aspectj.util.CollectionUtil; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.BCException; import org.aspectj.weaver.Member; import org.aspectj.weaver.NameMangler; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.TypeVariable; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.WeaverStateInfo; import org.aspectj.weaver.World; import org.aspectj.weaver.AjAttribute.WeaverVersionInfo; /** * Lazy lazy lazy. * We don't unpack the underlying class unless necessary. Things * like new methods and annotations accumulate in here until they * must be written out, don't add them to the underlying MethodGen! * Things are slightly different if this represents an Aspect. */ public final class LazyClassGen { int highestLineNumber = 0; // ---- JSR 45 info private SortedMap /* <String, InlinedSourceFileInfo> */ inlinedFiles = new TreeMap(); private boolean regenerateGenericSignatureAttribute = false; private BcelObjectType myType; // XXX is not set for types we create private ClassGen myGen; private ConstantPoolGen constantPoolGen; private List /*LazyMethodGen*/ methodGens = new ArrayList(); private List /*LazyClassGen*/ classGens = new ArrayList(); private List /*AnnotationGen*/ annotations = new ArrayList(); private int childCounter = 0; private InstructionFactory fact; private boolean isSerializable = false; private boolean hasSerialVersionUIDField = false; private boolean hasClinit = false; // --- static class InlinedSourceFileInfo { int highestLineNumber; int offset; // calculated InlinedSourceFileInfo(int highestLineNumber) { this.highestLineNumber = highestLineNumber; } } void addInlinedSourceFileInfo(String fullpath, int highestLineNumber) { Object o = inlinedFiles.get(fullpath); if (o != null) { InlinedSourceFileInfo info = (InlinedSourceFileInfo) o; if (info.highestLineNumber < highestLineNumber) { info.highestLineNumber = highestLineNumber; } } else { inlinedFiles.put(fullpath, new InlinedSourceFileInfo(highestLineNumber)); } } void calculateSourceDebugExtensionOffsets() { int i = roundUpToHundreds(highestLineNumber); for (Iterator iter = inlinedFiles.values().iterator(); iter.hasNext();) { InlinedSourceFileInfo element = (InlinedSourceFileInfo) iter.next(); element.offset = i; i = roundUpToHundreds(i + element.highestLineNumber); } } private static int roundUpToHundreds(int i) { return ((i / 100) + 1) * 100; } int getSourceDebugExtensionOffset(String fullpath) { return ((InlinedSourceFileInfo) inlinedFiles.get(fullpath)).offset; } private Unknown getSourceDebugExtensionAttribute() { int nameIndex = constantPoolGen.addUtf8("SourceDebugExtension"); String data = getSourceDebugExtensionString(); //System.err.println(data); byte[] bytes = Utility.stringToUTF(data); int length = bytes.length; return new Unknown(nameIndex, length, bytes, constantPoolGen.getConstantPool()); } // private LazyClassGen() {} // public static void main(String[] args) { // LazyClassGen m = new LazyClassGen(); // m.highestLineNumber = 37; // m.inlinedFiles.put("boo/baz/foo.java", new InlinedSourceFileInfo( 83)); // m.inlinedFiles.put("boo/barz/foo.java", new InlinedSourceFileInfo(292)); // m.inlinedFiles.put("boo/baz/moo.java", new InlinedSourceFileInfo(128)); // m.calculateSourceDebugExtensionOffsets(); // System.err.println(m.getSourceDebugExtensionString()); // } // For the entire pathname, we're using package names. This is probably wrong. private String getSourceDebugExtensionString() { StringBuffer out = new StringBuffer(); String myFileName = getFileName(); // header section out.append("SMAP\n"); out.append(myFileName); out.append("\nAspectJ\n"); // stratum section out.append("*S AspectJ\n"); // file section out.append("*F\n"); out.append("1 "); out.append(myFileName); out.append("\n"); int i = 2; for (Iterator iter = inlinedFiles.keySet().iterator(); iter.hasNext();) { String element = (String) iter.next(); int ii = element.lastIndexOf('/'); if (ii == -1) { out.append(i++); out.append(' '); out.append(element); out.append('\n'); } else { out.append("+ "); out.append(i++); out.append(' '); out.append(element.substring(ii+1)); out.append('\n'); out.append(element); out.append('\n'); } } // emit line section out.append("*L\n"); out.append("1#1,"); out.append(highestLineNumber); out.append(":1,1\n"); i = 2; for (Iterator iter = inlinedFiles.values().iterator(); iter.hasNext();) { InlinedSourceFileInfo element = (InlinedSourceFileInfo) iter.next(); out.append("1#"); out.append(i++); out.append(','); out.append(element.highestLineNumber); out.append(":"); out.append(element.offset + 1); out.append(",1\n"); } // end section out.append("*E\n"); // and finish up... return out.toString(); } // ---- end JSR45-related stuff /** Emit disassembled class and newline to out */ public static void disassemble(String path, String name, PrintStream out) throws IOException { if (null == out) { return; } //out.println("classPath: " + classPath); BcelWorld world = new BcelWorld(path); LazyClassGen clazz = new LazyClassGen(BcelWorld.getBcelObjectType(world.resolve(name))); clazz.print(out); out.println(); } public int getNewGeneratedNameTag() { return childCounter++; } // ---- public LazyClassGen( String class_name, String super_class_name, String file_name, int access_flags, String[] interfaces) { myGen = new ClassGen(class_name, super_class_name, file_name, access_flags, interfaces); constantPoolGen = myGen.getConstantPool(); fact = new InstructionFactory(myGen, constantPoolGen); regenerateGenericSignatureAttribute = true; } //Non child type, so it comes from a real type in the world. public LazyClassGen(BcelObjectType myType) { myGen = new ClassGen(myType.getJavaClass()); constantPoolGen = myGen.getConstantPool(); fact = new InstructionFactory(myGen, constantPoolGen); this.myType = myType; /* Does this class support serialization */ if (UnresolvedType.SERIALIZABLE.resolve(getType().getWorld()).isAssignableFrom(getType())) { isSerializable = true; // ResolvedMember[] fields = getType().getDeclaredFields(); // for (int i = 0; i < fields.length; i++) { // ResolvedMember field = fields[i]; // if (field.getName().equals("serialVersionUID") // && field.isStatic() && field.getType().equals(ResolvedType.LONG)) { // hasSerialVersionUIDField = true; // } // } hasSerialVersionUIDField = hasSerialVersionUIDField(getType()); ResolvedMember[] methods = getType().getDeclaredMethods(); for (int i = 0; i < methods.length; i++) { ResolvedMember method = methods[i]; if (method.getName().equals("<clinit>")) { hasClinit = true; } } } Method[] methods = myGen.getMethods(); for (int i = 0; i < methods.length; i++) { addMethodGen(new LazyMethodGen(methods[i], this)); } } public static boolean hasSerialVersionUIDField (ResolvedType type) { ResolvedMember[] fields = type.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { ResolvedMember field = fields[i]; if (field.getName().equals("serialVersionUID") && field.isStatic() && field.getType().equals(ResolvedType.LONG)) { return true; } } return false; } // public void addAttribute(Attribute i) { // myGen.addAttribute(i); // } // ---- public String getInternalClassName() { return getConstantPoolGen().getConstantPool().getConstantString( myGen.getClassNameIndex(), Constants.CONSTANT_Class); } public String getInternalFileName() { String str = getInternalClassName(); int index = str.lastIndexOf('/'); if (index == -1) { return getFileName(); } else { return str.substring(0, index + 1) + getFileName(); } } public File getPackagePath(File root) { String str = getInternalClassName(); int index = str.lastIndexOf('/'); if (index == -1) return root; return new File(root, str.substring(0, index)); } public String getClassId() { String str = getInternalClassName(); int index = str.lastIndexOf('/'); if (index == -1) return str; return str.substring(index + 1); } public void addMethodGen(LazyMethodGen gen) { //assert gen.getClassName() == super.getClassName(); methodGens.add(gen); if (highestLineNumber < gen.highestLineNumber) highestLineNumber = gen.highestLineNumber; } public void addMethodGen(LazyMethodGen gen, ISourceLocation sourceLocation) { addMethodGen(gen); if (!gen.getMethod().isPrivate()) { warnOnAddedMethod(gen.getMethod(),sourceLocation); } } public void errorOnAddedField (Field field, ISourceLocation sourceLocation) { if (isSerializable && !hasSerialVersionUIDField) { getWorld().getLint().serialVersionUIDBroken.signal( new String[] { myType.getResolvedTypeX().getName().toString(), field.getName() }, sourceLocation, null); } } public void warnOnAddedInterface (String name, ISourceLocation sourceLocation) { warnOnModifiedSerialVersionUID(sourceLocation,"added interface " + name); } public void warnOnAddedMethod (Method method, ISourceLocation sourceLocation) { warnOnModifiedSerialVersionUID(sourceLocation,"added non-private method " + method.getName()); } public void warnOnAddedStaticInitializer (Shadow shadow, ISourceLocation sourceLocation) { if (!hasClinit) { warnOnModifiedSerialVersionUID(sourceLocation,"added static initializer"); } } public void warnOnModifiedSerialVersionUID (ISourceLocation sourceLocation, String reason) { if (isSerializable && !hasSerialVersionUIDField) getWorld().getLint().needsSerialVersionUIDField.signal( new String[] { myType.getResolvedTypeX().getName().toString(), reason }, sourceLocation, null); } public World getWorld () { return myType.getResolvedTypeX().getWorld(); } public List getMethodGens() { return methodGens; //???Collections.unmodifiableList(methodGens); } // FIXME asc Should be collection returned here public Field[] getFieldGens() { return myGen.getFields(); } // FIXME asc How do the ones on the underlying class surface if this just returns new ones added? // FIXME asc ...although no one calls this right now ! public List getAnnotations() { return annotations; } private void writeBack(BcelWorld world) { if (getConstantPoolGen().getSize() > Short.MAX_VALUE) { reportClassTooBigProblem(); return; } if (annotations.size()>0) { for (Iterator iter = annotations.iterator(); iter.hasNext();) { AnnotationGen element = (AnnotationGen) iter.next(); myGen.addAnnotation(element); } // Attribute[] annAttributes = org.aspectj.apache.bcel.classfile.Utility.getAnnotationAttributes(getConstantPoolGen(),annotations); // for (int i = 0; i < annAttributes.length; i++) { // Attribute attribute = annAttributes[i]; // System.err.println("Adding attribute for "+attribute); // myGen.addAttribute(attribute); // } } // Add a weaver version attribute to the file being produced (if necessary...) boolean hasVersionAttribute = false; Attribute[] attrs = myGen.getAttributes(); for (int i = 0; i < attrs.length && !hasVersionAttribute; i++) { Attribute attribute = attrs[i]; if (attribute.getName().equals("org.aspectj.weaver.WeaverVersion")) hasVersionAttribute=true; } if (!hasVersionAttribute) myGen.addAttribute(BcelAttributes.bcelAttribute(new AjAttribute.WeaverVersionInfo(),getConstantPoolGen())); if (myType != null && myType.getWeaverState() != null) { myGen.addAttribute(BcelAttributes.bcelAttribute( new AjAttribute.WeaverState(myType.getWeaverState()), getConstantPoolGen())); } //FIXME ATAJ needed only for slow Aspects.aspectOf() - keep or remove //make a lot of test fail since the test compare weaved class file // based on some test data as text files... // if (!myGen.isInterface()) { // addAjClassField(); // } addAjcInitializers(); int len = methodGens.size(); myGen.setMethods(new Method[0]); calculateSourceDebugExtensionOffsets(); for (int i = 0; i < len; i++) { LazyMethodGen gen = (LazyMethodGen) methodGens.get(i); // we skip empty clinits if (isEmptyClinit(gen)) continue; myGen.addMethod(gen.getMethod()); } if (inlinedFiles.size() != 0) { if (hasSourceDebugExtensionAttribute(myGen)) { world.showMessage( IMessage.WARNING, WeaverMessages.format(WeaverMessages.OVERWRITE_JSR45,getFileName()), null, null); } // 17Feb05 - ASC - Skip this for now - it crashes IBM 1.4.2 jvms (pr80430). Will be revisited when contents // of attribute are confirmed to be correct. // myGen.addAttribute(getSourceDebugExtensionAttribute()); } fixupGenericSignatureAttribute(); } /** * When working with 1.5 generics, a signature attribute is attached to the type which indicates * how it was declared. This routine ensures the signature attribute for what we are about * to write out is correct. Basically its responsibilities are: * 1. Checking whether the attribute needs changing (i.e. did weaving change the type hierarchy) * 2. If it did, removing the old attribute * 3. Check if we need an attribute at all, are we generic? are our supertypes parameterized/generic? * 4. Build the new attribute which includes all typevariable, supertype and superinterface information */ private void fixupGenericSignatureAttribute () { // TODO asc generics Temporarily assume that types we generate dont need a signature attribute (closure/etc).. will need revisiting no doubt... if (myType==null) return; // 1. Has anything changed that would require us to modify this attribute? if (!regenerateGenericSignatureAttribute) return; // 2. Find the old attribute Signature sigAttr = null; if (myType!=null) { // if null, this is a type built from scratch, it won't already have a sig attribute Attribute[] as = myGen.getAttributes(); for (int i = 0; i < as.length; i++) { Attribute attribute = as[i]; if (attribute.getName().equals("Signature")) sigAttr = (Signature)attribute; } } // 3. Do we need an attribute? boolean needAttribute = false; if (sigAttr!=null) needAttribute = true; // If we had one before, we definetly still need one as types can't be 'removed' from the hierarchy // check the interfaces if (!needAttribute) { if (myType==null) { boolean stop = true; } ResolvedType[] interfaceRTXs = myType.getDeclaredInterfaces(); for (int i = 0; i < interfaceRTXs.length; i++) { ResolvedType typeX = interfaceRTXs[i]; if (typeX.isGenericType() || typeX.isParameterizedType()) needAttribute = true; } // check the supertype ResolvedType superclassRTX = myType.getSuperclass(); if (superclassRTX.isGenericType() || superclassRTX.isParameterizedType()) needAttribute = true; } if (needAttribute) { StringBuffer signature = new StringBuffer(); // first, the type variables... TypeVariable[] tVars = myType.getTypeVariables(); if (tVars.length>0) { signature.append("<"); for (int i = 0; i < tVars.length; i++) { TypeVariable variable = tVars[i]; if (i!=0) signature.append(","); signature.append(variable.getSignature()); } signature.append(">"); } // now the supertype signature.append(myType.getSuperclass().getSignature()); ResolvedType[] interfaceRTXs = myType.getDeclaredInterfaces(); for (int i = 0; i < interfaceRTXs.length; i++) { String s = interfaceRTXs[i].getSignatureForAttribute(); signature.append(s); } myGen.addAttribute(createSignatureAttribute(signature.toString())); } // TODO asc generics The 'old' signature is left in the constant pool - I wonder how safe it would be to // remove it since we don't know what else (if anything) is referring to it } /** * Helper method to create a signature attribute based on a string signature: * e.g. "Ljava/lang/Object;LI<Ljava/lang/Double;>;" */ private Signature createSignatureAttribute(String signature) { int nameIndex = constantPoolGen.addUtf8("Signature"); int sigIndex = constantPoolGen.addUtf8(signature); return new Signature(nameIndex,2,sigIndex,constantPoolGen.getConstantPool()); } /** * */ private void reportClassTooBigProblem() { // PR 59208 // we've generated a class that is just toooooooooo big (you've been generating programs // again haven't you? come on, admit it, no-one writes classes this big by hand). // create an empty myGen so that we can give back a return value that doesn't upset the // rest of the process. myGen = new ClassGen(myGen.getClassName(), myGen.getSuperclassName(), myGen.getFileName(), myGen.getAccessFlags(), myGen.getInterfaceNames()); // raise an error against this compilation unit. getWorld().showMessage( IMessage.ERROR, WeaverMessages.format(WeaverMessages.CLASS_TOO_BIG, this.getClassName()), new SourceLocation(new File(myGen.getFileName()),0), null ); } private static boolean hasSourceDebugExtensionAttribute(ClassGen gen) { ConstantPoolGen pool = gen.getConstantPool(); Attribute[] attrs = gen.getAttributes(); for (int i = 0; i < attrs.length; i++) { if ("SourceDebugExtension" .equals(((ConstantUtf8) pool.getConstant(attrs[i].getNameIndex())).getBytes())) { return true; } } return false; } public JavaClass getJavaClass(BcelWorld world) { writeBack(world); return myGen.getJavaClass(); } public void addGeneratedInner(LazyClassGen newClass) { classGens.add(newClass); } public void addInterface(UnresolvedType typeX, ISourceLocation sourceLocation) { regenerateGenericSignatureAttribute = true; myGen.addInterface(typeX.getRawName()); if (!typeX.equals(UnresolvedType.SERIALIZABLE)) warnOnAddedInterface(typeX.getName(),sourceLocation); } public void setSuperClass(UnresolvedType typeX) { regenerateGenericSignatureAttribute = true; myGen.setSuperclassName(typeX.getName()); } public String getSuperClassname() { return myGen.getSuperclassName(); } // non-recursive, may be a bug, ha ha. private List getClassGens() { List ret = new ArrayList(); ret.add(this); ret.addAll(classGens); return ret; } public List getChildClasses(BcelWorld world) { if (classGens.isEmpty()) return Collections.EMPTY_LIST; List ret = new ArrayList(); for (Iterator i = classGens.iterator(); i.hasNext();) { LazyClassGen clazz = (LazyClassGen) i.next(); byte[] bytes = clazz.getJavaClass(world).getBytes(); String name = clazz.getName(); int index = name.lastIndexOf('$'); // XXX this could be bad, check use of dollar signs. name = name.substring(index+1); ret.add(new UnwovenClassFile.ChildClass(name, bytes)); } return ret; } public String toString() { return toShortString(); } public String toShortString() { String s = org.aspectj.apache.bcel.classfile.Utility.accessToString(myGen.getAccessFlags(), true); if (s != "") s += " "; s += org.aspectj.apache.bcel.classfile.Utility.classOrInterface(myGen.getAccessFlags()); s += " "; s += myGen.getClassName(); return s; } public String toLongString() { ByteArrayOutputStream s = new ByteArrayOutputStream(); print(new PrintStream(s)); return new String(s.toByteArray()); } public void print() { print(System.out); } public void print(PrintStream out) { List classGens = getClassGens(); for (Iterator iter = classGens.iterator(); iter.hasNext();) { LazyClassGen element = (LazyClassGen) iter.next(); element.printOne(out); if (iter.hasNext()) out.println(); } } private void printOne(PrintStream out) { out.print(toShortString()); out.print(" extends "); out.print( org.aspectj.apache.bcel.classfile.Utility.compactClassName( myGen.getSuperclassName(), false)); int size = myGen.getInterfaces().length; if (size > 0) { out.print(" implements "); for (int i = 0; i < size; i++) { out.print(myGen.getInterfaceNames()[i]); if (i < size - 1) out.print(", "); } } out.print(":"); out.println(); // XXX make sure to pass types correctly around, so this doesn't happen. if (myType != null) { myType.printWackyStuff(out); } Field[] fields = myGen.getFields(); for (int i = 0, len = fields.length; i < len; i++) { out.print(" "); out.println(fields[i]); } List methodGens = getMethodGens(); for (Iterator iter = methodGens.iterator(); iter.hasNext();) { LazyMethodGen gen = (LazyMethodGen) iter.next(); // we skip empty clinits if (isEmptyClinit(gen)) continue; gen.print(out, (myType != null ? myType.getWeaverVersionAttribute() : WeaverVersionInfo.UNKNOWN)); if (iter.hasNext()) out.println(); } // out.println(" ATTRIBS: " + Arrays.asList(myGen.getAttributes())); out.println("end " + toShortString()); } private boolean isEmptyClinit(LazyMethodGen gen) { if (!gen.getName().equals("<clinit>")) return false; //System.err.println("checking clinig: " + gen); InstructionHandle start = gen.getBody().getStart(); while (start != null) { if (Range.isRangeHandle(start) || (start.getInstruction() instanceof RETURN)) { start = start.getNext(); } else { return false; } } return true; } public ConstantPoolGen getConstantPoolGen() { return constantPoolGen; } public String getName() { return myGen.getClassName(); } public boolean isWoven() { return myType.getWeaverState() != null; } public boolean isReweavable() { if (myType.getWeaverState()==null) return false; return myType.getWeaverState().isReweavable(); } public Set getAspectsAffectingType() { if (myType.getWeaverState()==null) return null; return myType.getWeaverState().getAspectsAffectingType(); } public WeaverStateInfo getOrCreateWeaverStateInfo() { WeaverStateInfo ret = myType.getWeaverState(); if (ret != null) return ret; ret = new WeaverStateInfo(); myType.setWeaverState(ret); return ret; } public InstructionFactory getFactory() { return fact; } public LazyMethodGen getStaticInitializer() { for (Iterator i = methodGens.iterator(); i.hasNext();) { LazyMethodGen gen = (LazyMethodGen) i.next(); if (gen.getName().equals("<clinit>")) return gen; } LazyMethodGen clinit = new LazyMethodGen( Modifier.STATIC, Type.VOID, "<clinit>", new Type[0], CollectionUtil.NO_STRINGS, this); clinit.getBody().insert(InstructionConstants.RETURN); methodGens.add(clinit); return clinit; } public LazyMethodGen getAjcPreClinit() { for (Iterator i = methodGens.iterator(); i.hasNext();) { LazyMethodGen gen = (LazyMethodGen) i.next(); if (gen.getName().equals(NameMangler.AJC_PRE_CLINIT_NAME)) return gen; } LazyMethodGen ajcClinit = new LazyMethodGen( Modifier.STATIC, Type.VOID, NameMangler.AJC_PRE_CLINIT_NAME, new Type[0], CollectionUtil.NO_STRINGS, this); ajcClinit.getBody().insert(InstructionConstants.RETURN); methodGens.add(ajcClinit); getStaticInitializer().getBody().insert(Utility.createInvoke(getFactory(), ajcClinit)); return ajcClinit; } // reflective thisJoinPoint support Map/*BcelShadow, Field*/ tjpFields = new HashMap(); public static final ObjectType proceedingTjpType = new ObjectType("org.aspectj.lang.ProceedingJoinPoint"); public static final ObjectType tjpType = new ObjectType("org.aspectj.lang.JoinPoint"); public static final ObjectType staticTjpType = new ObjectType("org.aspectj.lang.JoinPoint$StaticPart"); public static final ObjectType enclosingStaticTjpType = new ObjectType("org.aspectj.lang.JoinPoint$EnclosingStaticPart"); private static final ObjectType sigType = new ObjectType("org.aspectj.lang.Signature"); // private static final ObjectType slType = // new ObjectType("org.aspectj.lang.reflect.SourceLocation"); private static final ObjectType factoryType = new ObjectType("org.aspectj.runtime.reflect.Factory"); private static final ObjectType classType = new ObjectType("java.lang.Class"); public Field getTjpField(BcelShadow shadow, final boolean isEnclosingJp) { Field ret = (Field)tjpFields.get(shadow); if (ret != null) return ret; int modifiers = Modifier.STATIC | Modifier.FINAL; // XXX - Do we ever inline before or after advice? If we do, then we // better include them in the check below. (or just change it to // shadow.getEnclosingMethod().getCanInline()) // If the enclosing method is around advice, we could inline the join point // that has led to this shadow. If we do that then the TJP we are creating // here must be PUBLIC so it is visible to the type in which the // advice is inlined. (PR71377) LazyMethodGen encMethod = shadow.getEnclosingMethod(); boolean shadowIsInAroundAdvice = false; if (encMethod!=null && encMethod.getName().startsWith(NameMangler.PREFIX+"around")) { shadowIsInAroundAdvice = true; } if (getType().isInterface() || shadowIsInAroundAdvice) { modifiers |= Modifier.PUBLIC; } else { modifiers |= Modifier.PRIVATE; } ret = new FieldGen(modifiers, isEnclosingJp?enclosingStaticTjpType:staticTjpType, "ajc$tjp_" + tjpFields.size(), getConstantPoolGen()).getField(); addField(ret); tjpFields.put(shadow, ret); return ret; } //FIXME ATAJ needed only for slow Aspects.aspectOf - keep or remove // private void addAjClassField() { // // Andy: Why build it again?? // Field ajClassField = new FieldGen( // Modifier.PRIVATE | Modifier.FINAL | Modifier.STATIC, // classType, // "aj$class", // getConstantPoolGen()).getField(); // addField(ajClassField); // // InstructionList il = new InstructionList(); // il.append(new PUSH(getConstantPoolGen(), getClassName())); // il.append(fact.createInvoke("java.lang.Class", "forName", classType, // new Type[] {Type.STRING}, Constants.INVOKESTATIC)); // il.append(fact.createFieldAccess(getClassName(), ajClassField.getName(), // classType, Constants.PUTSTATIC)); // // getStaticInitializer().getBody().insert(il); // } private void addAjcInitializers() { if (tjpFields.size() == 0) return; InstructionList il = initializeAllTjps(); getStaticInitializer().getBody().insert(il); } private InstructionList initializeAllTjps() { InstructionList list = new InstructionList(); InstructionFactory fact = getFactory(); // make a new factory list.append(fact.createNew(factoryType)); list.append(InstructionFactory.createDup(1)); list.append(new PUSH(getConstantPoolGen(), getFileName())); // load the current Class object //XXX check that this works correctly for inners/anonymous list.append(new PUSH(getConstantPoolGen(), getClassName())); //XXX do we need to worry about the fact the theorectically this could throw //a ClassNotFoundException list.append(fact.createInvoke("java.lang.Class", "forName", classType, new Type[] {Type.STRING}, Constants.INVOKESTATIC)); list.append(fact.createInvoke(factoryType.getClassName(), "<init>", Type.VOID, new Type[] {Type.STRING, classType}, Constants.INVOKESPECIAL)); list.append(InstructionFactory.createStore(factoryType, 0)); List entries = new ArrayList(tjpFields.entrySet()); Collections.sort(entries, new Comparator() { public int compare(Object a, Object b) { Map.Entry ae = (Map.Entry) a; Map.Entry be = (Map.Entry) b; return ((Field) ae.getValue()) .getName() .compareTo(((Field)be.getValue()).getName()); } }); for (Iterator i = entries.iterator(); i.hasNext(); ) { Map.Entry entry = (Map.Entry)i.next(); initializeTjp(fact, list, (Field)entry.getValue(), (BcelShadow)entry.getKey()); } return list; } private void initializeTjp(InstructionFactory fact, InstructionList list, Field field, BcelShadow shadow) { Member sig = shadow.getSignature(); //ResolvedMember mem = shadow.getSignature().resolve(shadow.getWorld()); // load the factory list.append(InstructionFactory.createLoad(factoryType, 0)); // load the kind list.append(new PUSH(getConstantPoolGen(), shadow.getKind().getName())); // create the signature list.append(InstructionFactory.createLoad(factoryType, 0)); list.append(new PUSH(getConstantPoolGen(), sig.getSignatureString(shadow.getWorld()))); list.append(fact.createInvoke(factoryType.getClassName(), sig.getSignatureMakerName(), new ObjectType(sig.getSignatureType()), new Type[] { Type.STRING }, Constants.INVOKEVIRTUAL)); //XXX should load source location from shadow list.append(Utility.createConstant(fact, shadow.getSourceLine())); final String factoryMethod; if (staticTjpType.equals(field.getType())) { factoryMethod = "makeSJP"; } else if (enclosingStaticTjpType.equals(field.getType())) { factoryMethod = "makeESJP"; } else { throw new Error("should not happen"); } list.append(fact.createInvoke(factoryType.getClassName(), factoryMethod, field.getType(), new Type[] { Type.STRING, sigType, Type.INT}, Constants.INVOKEVIRTUAL)); // put it in the field list.append(fact.createFieldAccess(getClassName(), field.getName(), field.getType(), Constants.PUTSTATIC)); } public ResolvedType getType() { if (myType == null) return null; return myType.getResolvedTypeX(); } public BcelObjectType getBcelObjectType() { return myType; } public String getFileName() { return myGen.getFileName(); } private void addField(Field field) { myGen.addField(field); } public void replaceField(Field oldF, Field newF){ myGen.removeField(oldF); myGen.addField(newF); } public void addField(Field field, ISourceLocation sourceLocation) { addField(field); if (!(field.isPrivate() && (field.isStatic() || field.isTransient()))) { errorOnAddedField(field,sourceLocation); } } public String getClassName() { return myGen.getClassName(); } public boolean isInterface() { return myGen.isInterface(); } public boolean isAbstract() { return myGen.isAbstract(); } public LazyMethodGen getLazyMethodGen(Member m) { return getLazyMethodGen(m.getName(), m.getSignature()); } public LazyMethodGen getLazyMethodGen(String name, String signature) { for (Iterator i = methodGens.iterator(); i.hasNext();) { LazyMethodGen gen = (LazyMethodGen) i.next(); if (gen.getName().equals(name) && gen.getSignature().equals(signature)) return gen; } throw new BCException("Class " + this.getName() + " does not have a method " + name + " with signature " + signature); } public void forcePublic() { myGen.setAccessFlags(Utility.makePublic(myGen.getAccessFlags())); } public boolean hasAnnotation(UnresolvedType t) { // annotations on the real thing AnnotationGen agens[] = myGen.getAnnotations(); if (agens==null) return false; for (int i = 0; i < agens.length; i++) { AnnotationGen gen = agens[i]; if (t.equals(UnresolvedType.forSignature(gen.getTypeSignature()))) return true; } // annotations added during this weave return false; } public void addAnnotation(Annotation a) { if (!hasAnnotation(UnresolvedType.forSignature(a.getTypeSignature()))) { annotations.add(new AnnotationGen(a,getConstantPoolGen(),true)); } } }
102,459
Bug 102459 provide more detail in -showWeaveInfo messages
When advice is executed, the object you have to work with is the joinpoint. This can then be queried to get various information out of it. It would be nice, if as part of the weaving you could get hold of the same information. This is particularly useful in the case of writing a coverage tool. In order to measure where you've been, you have to know all the places you could possibly go. The introduction of the -showWeaveInfo option means that we can record these places, however, this would be greatly enhanced by providing similar information as to that which is collected as the program is running. The information which would be good is the same as that obtained from JoinPoint.StaticPart.getSignature().toLongString().
resolved fixed
c6bc7a2
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-01T18:40:31Z
2005-07-01T09:26:40Z
bridge/src/org/aspectj/bridge/WeaveMessage.java
/* ******************************************************************* * Copyright (c) 2004 IBM Corporation * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Andy Clement IBM initial implementation 30-May-2004 * ******************************************************************/ package org.aspectj.bridge; public class WeaveMessage extends Message { // Kinds of weaving message we can produce public static WeaveMessageKind WEAVEMESSAGE_DECLAREPARENTSIMPLEMENTS = new WeaveMessageKind(1,"Extending interface set for type '%1' (%2) to include '%3' (%4)"); public static WeaveMessageKind WEAVEMESSAGE_ITD = new WeaveMessageKind(2,"Type '%1' (%2) has intertyped %3 from '%4' (%5)"); // %6 is information like "[with runtime test]" public static WeaveMessageKind WEAVEMESSAGE_ADVISES = new WeaveMessageKind(3,"Type '%1' (%2) advised by %3 advice from '%4' (%5)%6"); public static WeaveMessageKind WEAVEMESSAGE_DECLAREPARENTSEXTENDS = new WeaveMessageKind(4,"Setting superclass of type '%1' (%2) to '%3' (%4)"); public static WeaveMessageKind WEAVEMESSAGE_SOFTENS = new WeaveMessageKind(5,"Softening exceptions in type '%1' (%2) as defined by aspect '%3' (%4)"); public static WeaveMessageKind WEAVEMESSAGE_ANNOTATES = new WeaveMessageKind(6,"'%1' (%2) is annotated with %3 %4 annotation from '%5' (%6)"); private String affectedtypename; private String aspectname; // private ctor - use the static factory method private WeaveMessage(String message, String affectedtypename, String aspectname) { super(message, IMessage.WEAVEINFO, null, null); this.affectedtypename = affectedtypename; this.aspectname = aspectname; } /** * Static helper method for constructing weaving messages. * @param kind what kind of message (e.g. declare parents) * @param inserts inserts for the message (inserts are marked %n in the message) * @return new weaving message */ public static WeaveMessage constructWeavingMessage( WeaveMessageKind kind, String[] inserts) { StringBuffer str = new StringBuffer(kind.getMessage()); int pos = -1; while ((pos=new String(str).indexOf("%"))!=-1) { int n = Character.getNumericValue(str.charAt(pos+1)); str.replace(pos,pos+2,inserts[n-1]); } return new WeaveMessage(str.toString(), null, null); } /** * Static helper method for constructing weaving messages. * @param kind what kind of message (e.g. declare parents) * @param inserts inserts for the message (inserts are marked %n in the message) * @param affectedtypename the type which is being advised/declaredUpon * @param aspectname the aspect that defined the advice or declares * @return new weaving message */ public static WeaveMessage constructWeavingMessage( WeaveMessageKind kind, String[] inserts, String affectedtypename, String aspectname) { StringBuffer str = new StringBuffer(kind.getMessage()); int pos = -1; while ((pos=new String(str).indexOf("%"))!=-1) { int n = Character.getNumericValue(str.charAt(pos+1)); str.replace(pos,pos+2,inserts[n-1]); } return new WeaveMessage(str.toString(), affectedtypename, aspectname); } /** * @return Returns the aspectname. */ public String getAspectname() { return aspectname; } /** * @return Returns the affectedtypename. */ public String getAffectedtypename() { return affectedtypename; } public static class WeaveMessageKind { private int id; private String message; public WeaveMessageKind(int id,String message) { this.id = id; this.message = message; } public String getMessage() { return message; } } }
102,459
Bug 102459 provide more detail in -showWeaveInfo messages
When advice is executed, the object you have to work with is the joinpoint. This can then be queried to get various information out of it. It would be nice, if as part of the weaving you could get hold of the same information. This is particularly useful in the case of writing a coverage tool. In order to measure where you've been, you have to know all the places you could possibly go. The introduction of the -showWeaveInfo option means that we can record these places, however, this would be greatly enhanced by providing similar information as to that which is collected as the program is running. The information which would be good is the same as that obtained from JoinPoint.StaticPart.getSignature().toLongString().
resolved fixed
c6bc7a2
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-01T18:40:31Z
2005-07-01T09:26:40Z
tests/java5/ataspectj/ataspectj/ltwlog/MainVerboseAndShow.java
/******************************************************************************* * Copyright (c) 2005 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * Alexandre Vasseur initial implementation *******************************************************************************/ package ataspectj.ltwlog; import java.util.ArrayList; import java.util.Arrays; /** * @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a> */ public class MainVerboseAndShow { void target() {}; public static void main(String args[]) throws Throwable { new MainVerboseAndShow().target(); if (!MessageHolder.startsAs(Arrays.asList(new String[]{ "info weaving 'ataspectj/ltwlog/MainVerboseAndShow'", "weaveinfo Type 'ataspectj.ltwlog.MainVerboseAndShow' (MainVerboseAndShow.java:22) advised by before advice from 'ataspectj.ltwlog.Aspect1' (Aspect1.java)", "info weaving 'ataspectj/ltwlog/Aspect1'"}))) { MessageHolder.dump(); throw new RuntimeException("failed"); } } }
102,459
Bug 102459 provide more detail in -showWeaveInfo messages
When advice is executed, the object you have to work with is the joinpoint. This can then be queried to get various information out of it. It would be nice, if as part of the weaving you could get hold of the same information. This is particularly useful in the case of writing a coverage tool. In order to measure where you've been, you have to know all the places you could possibly go. The introduction of the -showWeaveInfo option means that we can record these places, however, this would be greatly enhanced by providing similar information as to that which is collected as the program is running. The information which would be good is the same as that obtained from JoinPoint.StaticPart.getSignature().toLongString().
resolved fixed
c6bc7a2
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-01T18:40:31Z
2005-07-01T09:26:40Z
weaver/src/org/aspectj/weaver/Shadow.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver; import java.io.DataInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import org.aspectj.asm.IRelationship; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; import org.aspectj.bridge.WeaveMessage; import org.aspectj.lang.JoinPoint; import org.aspectj.util.PartialOrder; import org.aspectj.util.TypeSafeEnum; import org.aspectj.weaver.ast.Var; import org.aspectj.weaver.bcel.BcelAdvice; /* * The superclass of anything representing a the shadow of a join point. A shadow represents * some bit of code, and encompasses both entry and exit from that code. All shadows have a kind * and a signature. */ public abstract class Shadow { // every Shadow has a unique id, doesn't matter if it wraps... private static int nextShadowID = 100; // easier to spot than zero. private final Kind kind; private final Member signature; private Member matchingSignature; private ResolvedMember resolvedSignature; protected final Shadow enclosingShadow; protected List mungers = new ArrayList(1); public int shadowId = nextShadowID++; // every time we build a shadow, it gets a new id // ---- protected Shadow(Kind kind, Member signature, Shadow enclosingShadow) { this.kind = kind; this.signature = signature; this.enclosingShadow = enclosingShadow; } // ---- public abstract World getIWorld(); public List /*ShadowMunger*/ getMungers() { return mungers; } /** * could this(*) pcd ever match */ public final boolean hasThis() { if (getKind().neverHasThis()) { return false; } else if (getKind().isEnclosingKind()) { return !getSignature().isStatic(); } else if (enclosingShadow == null) { return false; } else { return enclosingShadow.hasThis(); } } /** * the type of the this object here * * @throws IllegalStateException if there is no this here */ public final UnresolvedType getThisType() { if (!hasThis()) throw new IllegalStateException("no this"); if (getKind().isEnclosingKind()) { return getSignature().getDeclaringType(); } else { return enclosingShadow.getThisType(); } } /** * a var referencing this * * @throws IllegalStateException if there is no target here */ public abstract Var getThisVar(); /** * could target(*) pcd ever match */ public final boolean hasTarget() { if (getKind().neverHasTarget()) { return false; } else if (getKind().isTargetSameAsThis()) { return hasThis(); } else { return !getSignature().isStatic(); } } /** * the type of the target object here * * @throws IllegalStateException if there is no target here */ public final UnresolvedType getTargetType() { if (!hasTarget()) throw new IllegalStateException("no target"); return getSignature().getDeclaringType(); } /** * a var referencing the target * * @throws IllegalStateException if there is no target here */ public abstract Var getTargetVar(); public UnresolvedType[] getArgTypes() { if (getKind() == FieldSet) return new UnresolvedType[] { getSignature().getReturnType() }; return getSignature().getParameterTypes(); } public UnresolvedType[] getGenericArgTypes() { if (getKind() == FieldSet) return new UnresolvedType[] { getResolvedSignature().getGenericReturnType() }; return getResolvedSignature().getGenericParameterTypes(); } public UnresolvedType getArgType(int arg) { if (getKind() == FieldSet) return getSignature().getReturnType(); return getSignature().getParameterTypes()[arg]; } public int getArgCount() { if (getKind() == FieldSet) return 1; return getSignature() .getParameterTypes().length; } public abstract UnresolvedType getEnclosingType(); public abstract Var getArgVar(int i); public abstract Var getThisJoinPointVar(); public abstract Var getThisJoinPointStaticPartVar(); public abstract Var getThisEnclosingJoinPointStaticPartVar(); // annotation variables public abstract Var getKindedAnnotationVar(UnresolvedType forAnnotationType); public abstract Var getWithinAnnotationVar(UnresolvedType forAnnotationType); public abstract Var getWithinCodeAnnotationVar(UnresolvedType forAnnotationType); public abstract Var getThisAnnotationVar(UnresolvedType forAnnotationType); public abstract Var getTargetAnnotationVar(UnresolvedType forAnnotationType); public abstract Var getArgAnnotationVar(int i, UnresolvedType forAnnotationType); public abstract Member getEnclosingCodeSignature(); /** returns the kind of shadow this is, representing what happens under this shadow */ public Kind getKind() { return kind; } /** returns the signature of the thing under this shadow */ public Member getSignature() { return signature; } /** * returns the signature of the thing under this shadow, with * any synthetic arguments removed */ public Member getMatchingSignature() { return matchingSignature != null ? matchingSignature : signature; } public void setMatchingSignature(Member member) { this.matchingSignature = member; } /** * returns the resolved signature of the thing under this shadow * */ public ResolvedMember getResolvedSignature() { if (resolvedSignature == null) { resolvedSignature = signature.resolve(getIWorld()); } return resolvedSignature; } public UnresolvedType getReturnType() { if (kind == ConstructorCall) return getSignature().getDeclaringType(); else if (kind == FieldSet) return ResolvedType.VOID; return getResolvedSignature().getGenericReturnType(); } /** * These names are the ones that will be returned by thisJoinPoint.getKind() * Those need to be documented somewhere */ public static final Kind MethodCall = new Kind(JoinPoint.METHOD_CALL, 1, true); public static final Kind ConstructorCall = new Kind(JoinPoint.CONSTRUCTOR_CALL, 2, true); public static final Kind MethodExecution = new Kind(JoinPoint.METHOD_EXECUTION, 3, false); public static final Kind ConstructorExecution = new Kind(JoinPoint.CONSTRUCTOR_EXECUTION, 4, false); public static final Kind FieldGet = new Kind(JoinPoint.FIELD_GET, 5, true); public static final Kind FieldSet = new Kind(JoinPoint.FIELD_SET, 6, true); public static final Kind StaticInitialization = new Kind(JoinPoint.STATICINITIALIZATION, 7, false); public static final Kind PreInitialization = new Kind(JoinPoint.PREINTIALIZATION, 8, false); public static final Kind AdviceExecution = new Kind(JoinPoint.ADVICE_EXECUTION, 9, false); public static final Kind Initialization = new Kind(JoinPoint.INITIALIZATION, 10, false); public static final Kind ExceptionHandler = new Kind(JoinPoint.EXCEPTION_HANDLER, 11, true); public static final int MAX_SHADOW_KIND = 11; public static final Kind[] SHADOW_KINDS = new Kind[] { MethodCall, ConstructorCall, MethodExecution, ConstructorExecution, FieldGet, FieldSet, StaticInitialization, PreInitialization, AdviceExecution, Initialization, ExceptionHandler, }; public static final Set ALL_SHADOW_KINDS = new HashSet(); static { for (int i = 0; i < SHADOW_KINDS.length; i++) { ALL_SHADOW_KINDS.add(SHADOW_KINDS[i]); } } /** A type-safe enum representing the kind of shadows */ public static final class Kind extends TypeSafeEnum { private boolean argsOnStack; //XXX unused public Kind(String name, int key, boolean argsOnStack) { super(name, key); this.argsOnStack = argsOnStack; } public String toLegalJavaIdentifier() { return getName().replace('-', '_'); } public boolean argsOnStack() { return !isTargetSameAsThis(); } // !!! this is false for handlers! public boolean allowsExtraction() { return true; } // XXX revisit along with removal of priorities public boolean hasHighPriorityExceptions() { return !isTargetSameAsThis(); } /** * These are all the shadows that contains other shadows within them and * are often directly associated with methods. */ public boolean isEnclosingKind() { return this == MethodExecution || this == ConstructorExecution || this == AdviceExecution || this == StaticInitialization || this == Initialization; } public boolean isTargetSameAsThis() { return this == MethodExecution || this == ConstructorExecution || this == StaticInitialization || this == PreInitialization || this == AdviceExecution || this == Initialization; } public boolean neverHasTarget() { return this == ConstructorCall || this == ExceptionHandler || this == PreInitialization || this == StaticInitialization; } public boolean neverHasThis() { return this == PreInitialization || this == StaticInitialization; } public String getSimpleName() { int dash = getName().lastIndexOf('-'); if (dash == -1) return getName(); else return getName().substring(dash+1); } public static Kind read(DataInputStream s) throws IOException { int key = s.readByte(); switch(key) { case 1: return MethodCall; case 2: return ConstructorCall; case 3: return MethodExecution; case 4: return ConstructorExecution; case 5: return FieldGet; case 6: return FieldSet; case 7: return StaticInitialization; case 8: return PreInitialization; case 9: return AdviceExecution; case 10: return Initialization; case 11: return ExceptionHandler; } throw new BCException("unknown kind: " + key); } } /** * Only does the check if the munger requires it (@AJ aspects don't) * * @param munger * @return */ protected boolean checkMunger(ShadowMunger munger) { if (munger.mustCheckExceptions()) { for (Iterator i = munger.getThrownExceptions().iterator(); i.hasNext(); ) { if (!checkCanThrow(munger, (ResolvedType)i.next() )) return false; } } return true; } protected boolean checkCanThrow(ShadowMunger munger, ResolvedType resolvedTypeX) { if (getKind() == ExceptionHandler) { //XXX much too lenient rules here, need to walk up exception handlers return true; } if (!isDeclaredException(resolvedTypeX, getSignature())) { getIWorld().showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.CANT_THROW_CHECKED,resolvedTypeX,this), // from advice in \'" + munger. + "\'", getSourceLocation(), munger.getSourceLocation()); } return true; } private boolean isDeclaredException( ResolvedType resolvedTypeX, Member member) { ResolvedType[] excs = getIWorld().resolve(member.getExceptions(getIWorld())); for (int i=0, len=excs.length; i < len; i++) { if (excs[i].isAssignableFrom(resolvedTypeX)) return true; } return false; } public void addMunger(ShadowMunger munger) { if (checkMunger(munger)) this.mungers.add(munger); } public final void implement() { sortMungers(); if (mungers == null) return; prepareForMungers(); implementMungers(); } private void sortMungers() { List sorted = PartialOrder.sort(mungers); if (sorted == null) { // this means that we have circular dependencies for (Iterator i = mungers.iterator(); i.hasNext(); ) { ShadowMunger m = (ShadowMunger)i.next(); getIWorld().getMessageHandler().handleMessage( MessageUtil.error( WeaverMessages.format(WeaverMessages.CIRCULAR_DEPENDENCY,this), m.getSourceLocation())); } } mungers = sorted; } /** Prepare the shadow for implementation. After this is done, the shadow * should be in such a position that each munger simply needs to be implemented. */ protected void prepareForMungers() { throw new RuntimeException("Generic shadows cannot be prepared"); } /* * Ensure we report a nice source location - particular in the case * where the source info is missing (binary weave). */ private String beautifyLocation(ISourceLocation isl) { StringBuffer nice = new StringBuffer(); if (isl==null || isl.getSourceFile()==null || isl.getSourceFile().getName().indexOf("no debug info available")!=-1) { nice.append("no debug info available"); } else { // can't use File.getName() as this fails when a Linux box encounters a path created on Windows and vice-versa int takeFrom = isl.getSourceFile().getPath().lastIndexOf('/'); if (takeFrom == -1) { takeFrom = isl.getSourceFile().getPath().lastIndexOf('\\'); } nice.append(isl.getSourceFile().getPath().substring(takeFrom +1)); if (isl.getLine()!=0) nice.append(":").append(isl.getLine()); } return nice.toString(); } /* * Report a message about the advice weave that has occurred. Some messing about * to make it pretty ! This code is just asking for an NPE to occur ... */ private void reportWeavingMessage(ShadowMunger munger) { Advice advice = (Advice)munger; AdviceKind aKind = advice.getKind(); // Only report on interesting advice kinds ... if (aKind == null || advice.getConcreteAspect()==null) { // We suspect someone is programmatically driving the weaver // (e.g. IdWeaveTestCase in the weaver testcases) return; } if (!( aKind.equals(AdviceKind.Before) || aKind.equals(AdviceKind.After) || aKind.equals(AdviceKind.AfterReturning) || aKind.equals(AdviceKind.AfterThrowing) || aKind.equals(AdviceKind.Around) || aKind.equals(AdviceKind.Softener))) return; String description = advice.getKind().toString(); String advisedType = this.getEnclosingType().getName(); String advisingType= advice.getConcreteAspect().getName(); Message msg = null; if (advice.getKind().equals(AdviceKind.Softener)) { msg = WeaveMessage.constructWeavingMessage( WeaveMessage.WEAVEMESSAGE_SOFTENS, new String[]{advisedType,beautifyLocation(getSourceLocation()), advisingType,beautifyLocation(munger.getSourceLocation())}, advisedType, advisingType); } else { boolean runtimeTest = ((BcelAdvice)advice).hasDynamicTests(); msg = WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_ADVISES, new String[]{ advisedType, beautifyLocation(getSourceLocation()), description, advisingType,beautifyLocation(munger.getSourceLocation()), (runtimeTest?" [with runtime test]":"")}, advisedType, advisingType); // Boolean.toString(runtimeTest)}); } getIWorld().getMessageHandler().handleMessage(msg); } public IRelationship.Kind determineRelKind(ShadowMunger munger) { AdviceKind ak = ((Advice)munger).getKind(); if (ak.getKey()==AdviceKind.Before.getKey()) return IRelationship.Kind.ADVICE_BEFORE; else if (ak.getKey()==AdviceKind.After.getKey()) return IRelationship.Kind.ADVICE_AFTER; else if (ak.getKey()==AdviceKind.AfterThrowing.getKey()) return IRelationship.Kind.ADVICE_AFTERTHROWING; else if (ak.getKey()==AdviceKind.AfterReturning.getKey()) return IRelationship.Kind.ADVICE_AFTERRETURNING; else if (ak.getKey()==AdviceKind.Around.getKey()) return IRelationship.Kind.ADVICE_AROUND; else if (ak.getKey()==AdviceKind.CflowEntry.getKey() || ak.getKey()==AdviceKind.CflowBelowEntry.getKey() || ak.getKey()==AdviceKind.InterInitializer.getKey() || ak.getKey()==AdviceKind.PerCflowEntry.getKey() || ak.getKey()==AdviceKind.PerCflowBelowEntry.getKey() || ak.getKey()==AdviceKind.PerThisEntry.getKey() || ak.getKey()==AdviceKind.PerTargetEntry.getKey() || ak.getKey()==AdviceKind.Softener.getKey() || ak.getKey()==AdviceKind.PerTypeWithinEntry.getKey()) { //System.err.println("Dont want a message about this: "+ak); return null; } throw new RuntimeException("Shadow.determineRelKind: What the hell is it? "+ak); } /** Actually implement the (non-empty) mungers associated with this shadow */ private void implementMungers() { World world = getIWorld(); for (Iterator iter = mungers.iterator(); iter.hasNext();) { ShadowMunger munger = (ShadowMunger) iter.next(); munger.implementOn(this); if (world.getCrossReferenceHandler() != null) { world.getCrossReferenceHandler().addCrossReference( munger.getSourceLocation(), // What is being applied this.getSourceLocation(), // Where is it being applied determineRelKind(munger), // What kind of advice? ((BcelAdvice)munger).hasDynamicTests() // Is a runtime test being stuffed in the code? ); } // TAG: WeavingMessage if (!getIWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)) { reportWeavingMessage(munger); } if (world.getModel() != null) { //System.err.println("munger: " + munger + " on " + this); AsmRelationshipProvider.getDefault().adviceMunger(world.getModel(), this, munger); } } } public String makeReflectiveFactoryString() { return null; //XXX } public abstract ISourceLocation getSourceLocation(); // ---- utility public String toString() { return getKind() + "(" + getSignature() + ")"; // + getSourceLines(); } public String toResolvedString(World world) { return getKind() + "(" + world.resolve(getSignature()).toGenericString() + ")"; } }
98,290
Bug 98290 no "matches declare" entry in structure model for single declare warning statement
A project containing one class and one aspect: ----------------------------------------------------- package pack; public class C { public static void main(String[] args) { new C().sayHello(); } public void sayHello() { System.out.println("HELLO"); } } ---------------------------------------------------- package pack; public aspect A { declare warning : execution(* C.sayHello(..)) : "blah blah"; } ----------------------------------------------------- has the "matched by" entry for A.aj, but doesn't have the "matches declare" entry for C.java. This means that in AJDT, C.sayHello isn't added to our map and consequently we don't get any relationships showing in the Cross Reference view for A.aj.
resolved fixed
619f8bc
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-01T19:47:37Z
2005-06-03T14:46:40Z
weaver/src/org/aspectj/weaver/bcel/BcelShadow.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * Alexandre Vasseur support for @AJ aspects * ******************************************************************/ package org.aspectj.weaver.bcel; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.aspectj.apache.bcel.Constants; import org.aspectj.apache.bcel.classfile.Field; import org.aspectj.apache.bcel.generic.ACONST_NULL; import org.aspectj.apache.bcel.generic.ALOAD; import org.aspectj.apache.bcel.generic.ANEWARRAY; import org.aspectj.apache.bcel.generic.ArrayType; import org.aspectj.apache.bcel.generic.BranchInstruction; import org.aspectj.apache.bcel.generic.ConstantPoolGen; import org.aspectj.apache.bcel.generic.DUP; import org.aspectj.apache.bcel.generic.DUP_X1; import org.aspectj.apache.bcel.generic.FieldInstruction; import org.aspectj.apache.bcel.generic.INVOKEINTERFACE; import org.aspectj.apache.bcel.generic.INVOKESPECIAL; import org.aspectj.apache.bcel.generic.INVOKESTATIC; import org.aspectj.apache.bcel.generic.Instruction; import org.aspectj.apache.bcel.generic.InstructionConstants; import org.aspectj.apache.bcel.generic.InstructionFactory; import org.aspectj.apache.bcel.generic.InstructionHandle; import org.aspectj.apache.bcel.generic.InstructionList; import org.aspectj.apache.bcel.generic.InstructionTargeter; import org.aspectj.apache.bcel.generic.InvokeInstruction; import org.aspectj.apache.bcel.generic.LoadInstruction; import org.aspectj.apache.bcel.generic.MULTIANEWARRAY; import org.aspectj.apache.bcel.generic.NEW; import org.aspectj.apache.bcel.generic.ObjectType; import org.aspectj.apache.bcel.generic.PUSH; import org.aspectj.apache.bcel.generic.ReturnInstruction; import org.aspectj.apache.bcel.generic.SWAP; import org.aspectj.apache.bcel.generic.StoreInstruction; import org.aspectj.apache.bcel.generic.TargetLostException; import org.aspectj.apache.bcel.generic.Type; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.weaver.Advice; import org.aspectj.weaver.AdviceKind; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.BCException; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.Member; import org.aspectj.weaver.MemberImpl; import org.aspectj.weaver.NameMangler; import org.aspectj.weaver.NewConstructorTypeMunger; import org.aspectj.weaver.NewFieldTypeMunger; import org.aspectj.weaver.NewMethodTypeMunger; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedMemberImpl; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.World; import org.aspectj.weaver.ast.Var; /* * Some fun implementation stuff: * * * expressionKind advice is non-execution advice * * may have a target. * * if the body is extracted, it will be extracted into * a static method. The first argument to the static * method is the target * * advice may expose a this object, but that's the advice's * consideration, not ours. This object will NOT be cached in another * local, but will always come from frame zero. * * * non-expressionKind advice is execution advice * * may have a this. * * target is same as this, and is exposed that way to advice * (i.e., target will not be cached, will always come from frame zero) * * if the body is extracted, it will be extracted into a method * with same static/dynamic modifier as enclosing method. If non-static, * target of callback call will be this. * * * because of these two facts, the setup of the actual arguments (including * possible target) callback method is the same for both kinds of advice: * push the targetVar, if it exists (it will not exist for advice on static * things), then push all the argVars. * * Protected things: * * * the above is sufficient for non-expressionKind advice for protected things, * since the target will always be this. * * * For expressionKind things, we have to modify the signature of the callback * method slightly. For non-static expressionKind things, we modify * the first argument of the callback method NOT to be the type specified * by the method/field signature (the owner), but rather we type it to * the currentlyEnclosing type. We are guaranteed this will be fine, * since the verifier verifies that the target is a subtype of the currently * enclosingType. * * Worries: * * * ConstructorCalls will be weirder than all of these, since they * supposedly don't have a target (according to AspectJ), but they clearly * do have a target of sorts, just one that needs to be pushed on the stack, * dupped, and not touched otherwise until the constructor runs. * * @author Jim Hugunin * @author Erik Hilsdale * */ public class BcelShadow extends Shadow { private ShadowRange range; private final BcelWorld world; private final LazyMethodGen enclosingMethod; private boolean fallsThrough; //XXX not used anymore // ---- initialization /** * This generates an unassociated shadow, rooted in a particular method but not rooted * to any particular point in the code. It should be given to a rooted ShadowRange * in the {@link ShadowRange#associateWithShadow(BcelShadow)} method. */ public BcelShadow( BcelWorld world, Kind kind, Member signature, LazyMethodGen enclosingMethod, BcelShadow enclosingShadow) { super(kind, signature, enclosingShadow); this.world = world; this.enclosingMethod = enclosingMethod; fallsThrough = kind.argsOnStack(); } // ---- copies all state, including Shadow's mungers... public BcelShadow copyInto(LazyMethodGen recipient, BcelShadow enclosing) { BcelShadow s = new BcelShadow(world, getKind(), getSignature(), recipient, enclosing); List src = mungers; List dest = s.mungers; for (Iterator i = src.iterator(); i.hasNext(); ) { dest.add(i.next()); } return s; } // ---- overridden behaviour public World getIWorld() { return world; } private void deleteNewAndDup() { final ConstantPoolGen cpg = getEnclosingClass().getConstantPoolGen(); int depth = 1; InstructionHandle ih = range.getStart(); while (true) { Instruction inst = ih.getInstruction(); if (inst instanceof INVOKESPECIAL && ((INVOKESPECIAL) inst).getName(cpg).equals("<init>")) { depth++; } else if (inst instanceof NEW) { depth--; if (depth == 0) break; } ih = ih.getPrev(); } // now IH points to the NEW. We're followed by the DUP, and that is followed // by the actual instruciton we care about. InstructionHandle newHandle = ih; InstructionHandle endHandle = newHandle.getNext(); InstructionHandle nextHandle; if (endHandle.getInstruction() instanceof DUP) { nextHandle = endHandle.getNext(); retargetFrom(newHandle, nextHandle); retargetFrom(endHandle, nextHandle); } else if (endHandle.getInstruction() instanceof DUP_X1) { InstructionHandle dupHandle = endHandle; endHandle = endHandle.getNext(); nextHandle = endHandle.getNext(); if (endHandle.getInstruction() instanceof SWAP) {} else { // XXX see next XXX comment throw new RuntimeException("Unhandled kind of new " + endHandle); } retargetFrom(newHandle, nextHandle); retargetFrom(dupHandle, nextHandle); retargetFrom(endHandle, nextHandle); } else { endHandle = newHandle; nextHandle = endHandle.getNext(); retargetFrom(newHandle, nextHandle); // add a POP here... we found a NEW w/o a dup or anything else, so // we must be in statement context. getRange().insert(InstructionConstants.POP, Range.OutsideAfter); } // assert (dupHandle.getInstruction() instanceof DUP); try { range.getBody().delete(newHandle, endHandle); } catch (TargetLostException e) { throw new BCException("shouldn't happen"); } } private void retargetFrom(InstructionHandle old, InstructionHandle fresh) { InstructionTargeter[] sources = old.getTargeters(); if (sources != null) { for (int i = sources.length - 1; i >= 0; i--) { sources[i].updateTarget(old, fresh); } } } protected void prepareForMungers() { // if we're a constructor call, we need to remove the new:dup or the new:dup_x1:swap, // and store all our // arguments on the frame. // ??? This is a bit of a hack (for the Java langauge). We do this because // we sometime add code "outsideBefore" when dealing with weaving join points. We only // do this for exposing state that is on the stack. It turns out to just work for // everything except for constructor calls and exception handlers. If we were to clean // this up, every ShadowRange would have three instructionHandle points, the start of // the arg-setup code, the start of the running code, and the end of the running code. if (getKind() == ConstructorCall) { deleteNewAndDup(); initializeArgVars(); } else if (getKind() == PreInitialization) { // pr74952 ShadowRange range = getRange(); range.insert(InstructionConstants.NOP,Range.InsideAfter); } else if (getKind() == ExceptionHandler) { ShadowRange range = getRange(); InstructionList body = range.getBody(); InstructionHandle start = range.getStart(); // Create a store instruction to put the value from the top of the // stack into a local variable slot. This is a trimmed version of // what is in initializeArgVars() (since there is only one argument // at a handler jp and only before advice is supported) (pr46298) argVars = new BcelVar[1]; int positionOffset = (hasTarget() ? 1 : 0) + ((hasThis() && !getKind().isTargetSameAsThis()) ? 1 : 0); UnresolvedType tx = getArgType(0); argVars[0] = genTempVar(tx, "ajc$arg0"); InstructionHandle insertedInstruction = range.insert(argVars[0].createStore(getFactory()), Range.OutsideBefore); // Now the exception range starts just after our new instruction. // The next bit of code changes the exception range to point at // the store instruction InstructionTargeter[] targeters = start.getTargeters(); for (int i = 0; i < targeters.length; i++) { InstructionTargeter t = targeters[i]; if (t instanceof ExceptionRange) { ExceptionRange er = (ExceptionRange) t; er.updateTarget(start, insertedInstruction, body); } } } // now we ask each munger to request our state isThisJoinPointLazy = world.isXlazyTjp(); for (Iterator iter = mungers.iterator(); iter.hasNext();) { ShadowMunger munger = (ShadowMunger) iter.next(); munger.specializeOn(this); } initializeThisJoinPoint(); // If we are an expression kind, we require our target/arguments on the stack // before we do our actual thing. However, they may have been removed // from the stack as the shadowMungers have requested state. // if any of our shadowMungers requested either the arguments or target, // the munger will have added code // to pop the target/arguments into temporary variables, represented by // targetVar and argVars. In such a case, we must make sure to re-push the // values. // If we are nonExpressionKind, we don't expect arguments on the stack // so this is moot. If our argVars happen to be null, then we know that // no ShadowMunger has squirrelled away our arguments, so they're still // on the stack. InstructionFactory fact = getFactory(); if (getKind().argsOnStack() && argVars != null) { // Special case first (pr46298). If we are an exception handler and the instruction // just after the shadow is a POP then we should remove the pop. The code // above which generated the store instruction has already cleared the stack. // We also don't generate any code for the arguments in this case as it would be // an incorrect aload. if (getKind() == ExceptionHandler && range.getEnd().getNext().getInstruction().equals(InstructionConstants.POP)) { // easier than deleting it ... range.getEnd().getNext().setInstruction(InstructionConstants.NOP); } else { range.insert( BcelRenderer.renderExprs(fact, world, argVars), Range.InsideBefore); if (targetVar != null) { range.insert( BcelRenderer.renderExpr(fact, world, targetVar), Range.InsideBefore); } if (getKind() == ConstructorCall) { range.insert((Instruction) InstructionFactory.createDup(1), Range.InsideBefore); range.insert( fact.createNew( (ObjectType) BcelWorld.makeBcelType( getSignature().getDeclaringType())), Range.InsideBefore); } } } } // ---- getters public ShadowRange getRange() { return range; } public void setRange(ShadowRange range) { this.range = range; } public int getSourceLine() { // if the kind of join point for which we are a shadow represents // a method or constructor execution, then the best source line is // the one from the enclosingMethod declarationLineNumber if available. Kind kind = getKind(); if ( (kind == MethodExecution) || (kind == ConstructorExecution) || (kind == AdviceExecution) || (kind == StaticInitialization) || (kind == PreInitialization) || (kind == Initialization)) { if (getEnclosingMethod().hasDeclaredLineNumberInfo()) { return getEnclosingMethod().getDeclarationLineNumber(); } } if (range == null) { if (getEnclosingMethod().hasBody()) { return Utility.getSourceLine(getEnclosingMethod().getBody().getStart()); } else { return 0; } } int ret = Utility.getSourceLine(range.getStart()); if (ret < 0) return 0; return ret; } // overrides public UnresolvedType getEnclosingType() { return getEnclosingClass().getType(); } public LazyClassGen getEnclosingClass() { return enclosingMethod.getEnclosingClass(); } public BcelWorld getWorld() { return world; } // ---- factory methods public static BcelShadow makeConstructorExecution( BcelWorld world, LazyMethodGen enclosingMethod, InstructionHandle justBeforeStart) { final InstructionList body = enclosingMethod.getBody(); BcelShadow s = new BcelShadow( world, ConstructorExecution, world.makeJoinPointSignature(enclosingMethod), enclosingMethod, null); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets( Range.genStart(body, justBeforeStart.getNext()), Range.genEnd(body)); return s; } public static BcelShadow makeStaticInitialization( BcelWorld world, LazyMethodGen enclosingMethod) { InstructionList body = enclosingMethod.getBody(); // move the start past ajc$preClinit InstructionHandle clinitStart = body.getStart(); if (clinitStart.getInstruction() instanceof InvokeInstruction) { InvokeInstruction ii = (InvokeInstruction)clinitStart.getInstruction(); if (ii .getName(enclosingMethod.getEnclosingClass().getConstantPoolGen()) .equals(NameMangler.AJC_PRE_CLINIT_NAME)) { clinitStart = clinitStart.getNext(); } } InstructionHandle clinitEnd = body.getEnd(); //XXX should move the end before the postClinit, but the return is then tricky... // if (clinitEnd.getInstruction() instanceof InvokeInstruction) { // InvokeInstruction ii = (InvokeInstruction)clinitEnd.getInstruction(); // if (ii.getName(enclosingMethod.getEnclosingClass().getConstantPoolGen()).equals(NameMangler.AJC_POST_CLINIT_NAME)) { // clinitEnd = clinitEnd.getPrev(); // } // } BcelShadow s = new BcelShadow( world, StaticInitialization, world.makeJoinPointSignature(enclosingMethod), enclosingMethod, null); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets( Range.genStart(body, clinitStart), Range.genEnd(body, clinitEnd)); return s; } /** Make the shadow for an exception handler. Currently makes an empty shadow that * only allows before advice to be woven into it. */ public static BcelShadow makeExceptionHandler( BcelWorld world, ExceptionRange exceptionRange, LazyMethodGen enclosingMethod, InstructionHandle startOfHandler, BcelShadow enclosingShadow) { InstructionList body = enclosingMethod.getBody(); UnresolvedType catchType = exceptionRange.getCatchType(); UnresolvedType inType = enclosingMethod.getEnclosingClass().getType(); ResolvedMemberImpl sig = MemberImpl.makeExceptionHandlerSignature(inType, catchType); sig.parameterNames = new String[] {findHandlerParamName(startOfHandler)}; BcelShadow s = new BcelShadow( world, ExceptionHandler, sig, enclosingMethod, enclosingShadow); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); InstructionHandle start = Range.genStart(body, startOfHandler); InstructionHandle end = Range.genEnd(body, start); r.associateWithTargets(start, end); exceptionRange.updateTarget(startOfHandler, start, body); return s; } private static String findHandlerParamName(InstructionHandle startOfHandler) { if (startOfHandler.getInstruction() instanceof StoreInstruction && startOfHandler.getNext() != null) { int slot = ((StoreInstruction)startOfHandler.getInstruction()).getIndex(); //System.out.println("got store: " + startOfHandler.getInstruction() + ", " + index); InstructionTargeter[] targeters = startOfHandler.getNext().getTargeters(); if (targeters!=null) { for (int i=targeters.length-1; i >= 0; i--) { if (targeters[i] instanceof LocalVariableTag) { LocalVariableTag t = (LocalVariableTag)targeters[i]; if (t.getSlot() == slot) { return t.getName(); } //System.out.println("tag: " + targeters[i]); } } } } return "<missing>"; } /** create an init join point associated w/ an interface in the body of a constructor */ public static BcelShadow makeIfaceInitialization( BcelWorld world, LazyMethodGen constructor, Member interfaceConstructorSignature) { InstructionList body = constructor.getBody(); // UnresolvedType inType = constructor.getEnclosingClass().getType(); BcelShadow s = new BcelShadow( world, Initialization, interfaceConstructorSignature, constructor, null); s.fallsThrough = true; // ShadowRange r = new ShadowRange(body); // r.associateWithShadow(s); // InstructionHandle start = Range.genStart(body, handle); // InstructionHandle end = Range.genEnd(body, handle); // // r.associateWithTargets(start, end); return s; } public void initIfaceInitializer(InstructionHandle end) { final InstructionList body = enclosingMethod.getBody(); ShadowRange r = new ShadowRange(body); r.associateWithShadow(this); InstructionHandle nop = body.insert(end, InstructionConstants.NOP); r.associateWithTargets( Range.genStart(body, nop), Range.genEnd(body, nop)); } // public static BcelShadow makeIfaceConstructorExecution( // BcelWorld world, // LazyMethodGen constructor, // InstructionHandle next, // Member interfaceConstructorSignature) // { // // final InstructionFactory fact = constructor.getEnclosingClass().getFactory(); // InstructionList body = constructor.getBody(); // // UnresolvedType inType = constructor.getEnclosingClass().getType(); // BcelShadow s = // new BcelShadow( // world, // ConstructorExecution, // interfaceConstructorSignature, // constructor, // null); // s.fallsThrough = true; // ShadowRange r = new ShadowRange(body); // r.associateWithShadow(s); // // ??? this may or may not work // InstructionHandle start = Range.genStart(body, next); // //InstructionHandle end = Range.genEnd(body, body.append(start, fact.NOP)); // InstructionHandle end = Range.genStart(body, next); // //body.append(start, fact.NOP); // // r.associateWithTargets(start, end); // return s; // } /** Create an initialization join point associated with a constructor, but not * with any body of code yet. If this is actually matched, it's range will be set * when we inline self constructors. * * @param constructor The constructor starting this initialization. */ public static BcelShadow makeUnfinishedInitialization( BcelWorld world, LazyMethodGen constructor) { BcelShadow ret = new BcelShadow( world, Initialization, world.makeJoinPointSignature(constructor), constructor, null); if (constructor.getEffectiveSignature() != null) { ret.setMatchingSignature(constructor.getEffectiveSignature().getEffectiveSignature()); } return ret; } public static BcelShadow makeUnfinishedPreinitialization( BcelWorld world, LazyMethodGen constructor) { BcelShadow ret = new BcelShadow( world, PreInitialization, world.makeJoinPointSignature(constructor), constructor, null); ret.fallsThrough = true; if (constructor.getEffectiveSignature() != null) { ret.setMatchingSignature(constructor.getEffectiveSignature().getEffectiveSignature()); } return ret; } public static BcelShadow makeMethodExecution( BcelWorld world, LazyMethodGen enclosingMethod, boolean lazyInit) { if (!lazyInit) return makeMethodExecution(world, enclosingMethod); BcelShadow s = new BcelShadow( world, MethodExecution, enclosingMethod.getMemberView(), enclosingMethod, null); return s; } public void init() { if (range != null) return; final InstructionList body = enclosingMethod.getBody(); ShadowRange r = new ShadowRange(body); r.associateWithShadow(this); r.associateWithTargets( Range.genStart(body), Range.genEnd(body)); } public static BcelShadow makeMethodExecution( BcelWorld world, LazyMethodGen enclosingMethod) { return makeShadowForMethod(world, enclosingMethod, MethodExecution, enclosingMethod.getMemberView()); //world.makeMethodSignature(enclosingMethod)); } public static BcelShadow makeShadowForMethod(BcelWorld world, LazyMethodGen enclosingMethod, Shadow.Kind kind, Member sig) { final InstructionList body = enclosingMethod.getBody(); BcelShadow s = new BcelShadow( world, kind, sig, enclosingMethod, null); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets( Range.genStart(body), Range.genEnd(body)); return s; } public static BcelShadow makeAdviceExecution( BcelWorld world, LazyMethodGen enclosingMethod) { final InstructionList body = enclosingMethod.getBody(); BcelShadow s = new BcelShadow( world, AdviceExecution, world.makeJoinPointSignatureFromMethod(enclosingMethod, Member.ADVICE), enclosingMethod, null); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets(Range.genStart(body), Range.genEnd(body)); return s; } // constructor call shadows are <em>initially</em> just around the // call to the constructor. If ANY advice gets put on it, we move // the NEW instruction inside the join point, which involves putting // all the arguments in temps. public static BcelShadow makeConstructorCall( BcelWorld world, LazyMethodGen enclosingMethod, InstructionHandle callHandle, BcelShadow enclosingShadow) { final InstructionList body = enclosingMethod.getBody(); Member sig = world.makeJoinPointSignatureForMethodInvocation( enclosingMethod.getEnclosingClass(), (InvokeInstruction) callHandle.getInstruction()); BcelShadow s = new BcelShadow( world, ConstructorCall, sig, enclosingMethod, enclosingShadow); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets( Range.genStart(body, callHandle), Range.genEnd(body, callHandle)); retargetAllBranches(callHandle, r.getStart()); return s; } public static BcelShadow makeMethodCall( BcelWorld world, LazyMethodGen enclosingMethod, InstructionHandle callHandle, BcelShadow enclosingShadow) { final InstructionList body = enclosingMethod.getBody(); BcelShadow s = new BcelShadow( world, MethodCall, world.makeJoinPointSignatureForMethodInvocation( enclosingMethod.getEnclosingClass(), (InvokeInstruction) callHandle.getInstruction()), enclosingMethod, enclosingShadow); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets( Range.genStart(body, callHandle), Range.genEnd(body, callHandle)); retargetAllBranches(callHandle, r.getStart()); return s; } public static BcelShadow makeShadowForMethodCall( BcelWorld world, LazyMethodGen enclosingMethod, InstructionHandle callHandle, BcelShadow enclosingShadow, Kind kind, ResolvedMember sig) { final InstructionList body = enclosingMethod.getBody(); BcelShadow s = new BcelShadow( world, kind, sig, enclosingMethod, enclosingShadow); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets( Range.genStart(body, callHandle), Range.genEnd(body, callHandle)); retargetAllBranches(callHandle, r.getStart()); return s; } public static BcelShadow makeFieldGet( BcelWorld world, ResolvedMember field, LazyMethodGen enclosingMethod, InstructionHandle getHandle, BcelShadow enclosingShadow) { final InstructionList body = enclosingMethod.getBody(); BcelShadow s = new BcelShadow( world, FieldGet, field, // BcelWorld.makeFieldSignature( // enclosingMethod.getEnclosingClass(), // (FieldInstruction) getHandle.getInstruction()), enclosingMethod, enclosingShadow); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets( Range.genStart(body, getHandle), Range.genEnd(body, getHandle)); retargetAllBranches(getHandle, r.getStart()); return s; } public static BcelShadow makeFieldSet( BcelWorld world, LazyMethodGen enclosingMethod, InstructionHandle setHandle, BcelShadow enclosingShadow) { final InstructionList body = enclosingMethod.getBody(); BcelShadow s = new BcelShadow( world, FieldSet, BcelWorld.makeFieldJoinPointSignature( enclosingMethod.getEnclosingClass(), (FieldInstruction) setHandle.getInstruction()), enclosingMethod, enclosingShadow); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets( Range.genStart(body, setHandle), Range.genEnd(body, setHandle)); retargetAllBranches(setHandle, r.getStart()); return s; } public static void retargetAllBranches(InstructionHandle from, InstructionHandle to) { InstructionTargeter[] sources = from.getTargeters(); if (sources != null) { for (int i = sources.length - 1; i >= 0; i--) { InstructionTargeter source = sources[i]; if (source instanceof BranchInstruction) { source.updateTarget(from, to); } } } } // // ---- type access methods // private ObjectType getTargetBcelType() { // return (ObjectType) BcelWorld.makeBcelType(getTargetType()); // } // private Type getArgBcelType(int arg) { // return BcelWorld.makeBcelType(getArgType(arg)); // } // ---- kinding /** * If the end of my range has no real instructions following then * my context needs a return at the end. */ public boolean terminatesWithReturn() { return getRange().getRealNext() == null; } /** * Is arg0 occupied with the value of this */ public boolean arg0HoldsThis() { if (getKind().isEnclosingKind()) { return !getSignature().isStatic(); } else if (enclosingShadow == null) { //XXX this is mostly right // this doesn't do the right thing for calls in the pre part of introduced constructors. return !enclosingMethod.isStatic(); } else { return ((BcelShadow)enclosingShadow).arg0HoldsThis(); } } // ---- argument getting methods private BcelVar thisVar = null; private BcelVar targetVar = null; private BcelVar[] argVars = null; private Map/*<UnresolvedType,BcelVar>*/ kindedAnnotationVars = null; private Map/*<UnresolvedType,BcelVar>*/ thisAnnotationVars = null; private Map/*<UnresolvedType,BcelVar>*/ targetAnnotationVars = null; private Map/*<UnresolvedType,BcelVar>*/[] argAnnotationVars = null; private Map/*<UnresolvedType,BcelVar>*/ withinAnnotationVars = null; private Map/*<UnresolvedType,BcelVar>*/ withincodeAnnotationVars = null; public Var getThisVar() { if (!hasThis()) { throw new IllegalStateException("no this"); } initializeThisVar(); return thisVar; } public Var getThisAnnotationVar(UnresolvedType forAnnotationType) { if (!hasThis()) { throw new IllegalStateException("no this"); } initializeThisAnnotationVars(); // FIXME asc Why bother with this if we always return one? // Even if we can't find one, we have to return one as we might have this annotation at runtime Var v = (Var) thisAnnotationVars.get(forAnnotationType); if (v==null) v = new TypeAnnotationAccessVar(forAnnotationType.resolve(world),(BcelVar)getThisVar()); return v; } public Var getTargetVar() { if (!hasTarget()) { throw new IllegalStateException("no target"); } initializeTargetVar(); return targetVar; } public Var getTargetAnnotationVar(UnresolvedType forAnnotationType) { if (!hasTarget()) { throw new IllegalStateException("no target"); } initializeTargetAnnotationVars(); // FIXME asc why bother with this if we always return one? Var v =(Var) targetAnnotationVars.get(forAnnotationType); // Even if we can't find one, we have to return one as we might have this annotation at runtime if (v==null) v = new TypeAnnotationAccessVar(forAnnotationType.resolve(world),(BcelVar)getTargetVar()); return v; } public Var getArgVar(int i) { initializeArgVars(); return argVars[i]; } public Var getArgAnnotationVar(int i,UnresolvedType forAnnotationType) { initializeArgAnnotationVars(); Var v= (Var) argAnnotationVars[i].get(forAnnotationType); if (v==null) v = new TypeAnnotationAccessVar(forAnnotationType.resolve(world),(BcelVar)getArgVar(i)); return v; } public Var getKindedAnnotationVar(UnresolvedType forAnnotationType) { initializeKindedAnnotationVars(); return (Var) kindedAnnotationVars.get(forAnnotationType); } public Var getWithinAnnotationVar(UnresolvedType forAnnotationType) { initializeWithinAnnotationVars(); return (Var) withinAnnotationVars.get(forAnnotationType); } public Var getWithinCodeAnnotationVar(UnresolvedType forAnnotationType) { initializeWithinCodeAnnotationVars(); return (Var) withincodeAnnotationVars.get(forAnnotationType); } // reflective thisJoinPoint support private BcelVar thisJoinPointVar = null; private boolean isThisJoinPointLazy; private int lazyTjpConsumers = 0; private BcelVar thisJoinPointStaticPartVar = null; // private BcelVar thisEnclosingJoinPointStaticPartVar = null; public final Var getThisJoinPointStaticPartVar() { return getThisJoinPointStaticPartBcelVar(); } public final Var getThisEnclosingJoinPointStaticPartVar() { return getThisEnclosingJoinPointStaticPartBcelVar(); } public void requireThisJoinPoint(boolean hasGuardTest) { if (!hasGuardTest) { isThisJoinPointLazy = false; } else { lazyTjpConsumers++; } if (thisJoinPointVar == null) { thisJoinPointVar = genTempVar(UnresolvedType.forName("org.aspectj.lang.JoinPoint")); } } public Var getThisJoinPointVar() { requireThisJoinPoint(false); return thisJoinPointVar; } void initializeThisJoinPoint() { if (thisJoinPointVar == null) return; if (isThisJoinPointLazy) { isThisJoinPointLazy = checkLazyTjp(); } if (isThisJoinPointLazy) { createThisJoinPoint(); // make sure any state needed is initialized, but throw the instructions out if (lazyTjpConsumers == 1) return; // special case only one lazyTjpUser InstructionFactory fact = getFactory(); InstructionList il = new InstructionList(); il.append(InstructionConstants.ACONST_NULL); il.append(thisJoinPointVar.createStore(fact)); range.insert(il, Range.OutsideBefore); } else { InstructionFactory fact = getFactory(); InstructionList il = createThisJoinPoint(); il.append(thisJoinPointVar.createStore(fact)); range.insert(il, Range.OutsideBefore); } } private boolean checkLazyTjp() { // check for around advice for (Iterator i = mungers.iterator(); i.hasNext();) { ShadowMunger munger = (ShadowMunger) i.next(); if (munger instanceof Advice) { if ( ((Advice)munger).getKind() == AdviceKind.Around) { world.getLint().canNotImplementLazyTjp.signal( new String[] {toString()}, getSourceLocation(), new ISourceLocation[] { munger.getSourceLocation() } ); return false; } } } return true; } InstructionList loadThisJoinPoint() { InstructionFactory fact = getFactory(); InstructionList il = new InstructionList(); if (isThisJoinPointLazy) { il.append(createThisJoinPoint()); if (lazyTjpConsumers > 1) { il.append(thisJoinPointVar.createStore(fact)); InstructionHandle end = il.append(thisJoinPointVar.createLoad(fact)); il.insert(InstructionFactory.createBranchInstruction(Constants.IFNONNULL, end)); il.insert(thisJoinPointVar.createLoad(fact)); } } else { thisJoinPointVar.appendLoad(il, fact); } return il; } InstructionList createThisJoinPoint() { InstructionFactory fact = getFactory(); InstructionList il = new InstructionList(); BcelVar staticPart = getThisJoinPointStaticPartBcelVar(); staticPart.appendLoad(il, fact); if (hasThis()) { ((BcelVar)getThisVar()).appendLoad(il, fact); } else { il.append(new ACONST_NULL()); } if (hasTarget()) { ((BcelVar)getTargetVar()).appendLoad(il, fact); } else { il.append(new ACONST_NULL()); } switch(getArgCount()) { case 0: il.append(fact.createInvoke("org.aspectj.runtime.reflect.Factory", "makeJP", LazyClassGen.tjpType, new Type[] { LazyClassGen.staticTjpType, Type.OBJECT, Type.OBJECT}, Constants.INVOKESTATIC)); break; case 1: ((BcelVar)getArgVar(0)).appendLoadAndConvert(il, fact, world.getCoreType(ResolvedType.OBJECT)); il.append(fact.createInvoke("org.aspectj.runtime.reflect.Factory", "makeJP", LazyClassGen.tjpType, new Type[] { LazyClassGen.staticTjpType, Type.OBJECT, Type.OBJECT, Type.OBJECT}, Constants.INVOKESTATIC)); break; case 2: ((BcelVar)getArgVar(0)).appendLoadAndConvert(il, fact, world.getCoreType(ResolvedType.OBJECT)); ((BcelVar)getArgVar(1)).appendLoadAndConvert(il, fact, world.getCoreType(ResolvedType.OBJECT)); il.append(fact.createInvoke("org.aspectj.runtime.reflect.Factory", "makeJP", LazyClassGen.tjpType, new Type[] { LazyClassGen.staticTjpType, Type.OBJECT, Type.OBJECT, Type.OBJECT, Type.OBJECT}, Constants.INVOKESTATIC)); break; default: il.append(makeArgsObjectArray()); il.append(fact.createInvoke("org.aspectj.runtime.reflect.Factory", "makeJP", LazyClassGen.tjpType, new Type[] { LazyClassGen.staticTjpType, Type.OBJECT, Type.OBJECT, new ArrayType(Type.OBJECT, 1)}, Constants.INVOKESTATIC)); break; } return il; } /** * Get the Var for the jpStaticPart * @return */ public BcelVar getThisJoinPointStaticPartBcelVar() { return getThisJoinPointStaticPartBcelVar(false); } /** * Get the Var for the xxxxJpStaticPart, xxx = this or enclosing * @param isEnclosingJp true to have the enclosingJpStaticPart * @return */ public BcelVar getThisJoinPointStaticPartBcelVar(final boolean isEnclosingJp) { if (thisJoinPointStaticPartVar == null) { Field field = getEnclosingClass().getTjpField(this, isEnclosingJp); thisJoinPointStaticPartVar = new BcelFieldRef( isEnclosingJp? world.getCoreType(UnresolvedType.forName("org.aspectj.lang.JoinPoint$EnclosingStaticPart")): world.getCoreType(UnresolvedType.forName("org.aspectj.lang.JoinPoint$StaticPart")), getEnclosingClass().getClassName(), field.getName()); // getEnclosingClass().warnOnAddedStaticInitializer(this,munger.getSourceLocation()); } return thisJoinPointStaticPartVar; } /** * Get the Var for the enclosingJpStaticPart * @return */ public BcelVar getThisEnclosingJoinPointStaticPartBcelVar() { if (enclosingShadow == null) { // the enclosing of an execution is itself return getThisJoinPointStaticPartBcelVar(true); } else { return ((BcelShadow)enclosingShadow).getThisJoinPointStaticPartBcelVar(true); } } //??? need to better understand all the enclosing variants public Member getEnclosingCodeSignature() { if (getKind().isEnclosingKind()) { return getSignature(); } else if (getKind() == Shadow.PreInitialization) { // PreInit doesn't enclose code but its signature // is correctly the signature of the ctor. return getSignature(); } else if (enclosingShadow == null) { return getEnclosingMethod().getMemberView(); } else { return enclosingShadow.getSignature(); } } private InstructionList makeArgsObjectArray() { InstructionFactory fact = getFactory(); BcelVar arrayVar = genTempVar(UnresolvedType.OBJECTARRAY); final InstructionList il = new InstructionList(); int alen = getArgCount() ; il.append(Utility.createConstant(fact, alen)); il.append((Instruction)fact.createNewArray(Type.OBJECT, (short)1)); arrayVar.appendStore(il, fact); int stateIndex = 0; for (int i = 0, len = getArgCount(); i<len; i++) { arrayVar.appendConvertableArrayStore(il, fact, stateIndex, (BcelVar)getArgVar(i)); stateIndex++; } arrayVar.appendLoad(il, fact); return il; } // ---- initializing var tables /* initializing this is doesn't do anything, because this * is protected from side-effects, so we don't need to copy its location */ private void initializeThisVar() { if (thisVar != null) return; thisVar = new BcelVar(getThisType().resolve(world), 0); thisVar.setPositionInAroundState(0); } public void initializeTargetVar() { InstructionFactory fact = getFactory(); if (targetVar != null) return; if (getKind().isTargetSameAsThis()) { if (hasThis()) initializeThisVar(); targetVar = thisVar; } else { initializeArgVars(); // gotta pop off the args before we find the target UnresolvedType type = getTargetType(); type = ensureTargetTypeIsCorrect(type); targetVar = genTempVar(type, "ajc$target"); range.insert(targetVar.createStore(fact), Range.OutsideBefore); targetVar.setPositionInAroundState(hasThis() ? 1 : 0); } } /* PR 72528 * This method double checks the target type under certain conditions. The Java 1.4 * compilers seem to take calls to clone methods on array types and create bytecode that * looks like clone is being called on Object. If we advise a clone call with around * advice we extract the call into a helper method which we can then refer to. Because the * type in the bytecode for the call to clone is Object we create a helper method with * an Object parameter - this is not correct as we have lost the fact that the actual * type is an array type. If we don't do the check below we will create code that fails * java verification. This method checks for the peculiar set of conditions and if they * are true, it has a sneak peek at the code before the call to see what is on the stack. */ public UnresolvedType ensureTargetTypeIsCorrect(UnresolvedType tx) { if (tx.equals(ResolvedType.OBJECT) && getKind() == MethodCall && getSignature().getReturnType().equals(ResolvedType.OBJECT) && getSignature().getArity()==0 && getSignature().getName().charAt(0) == 'c' && getSignature().getName().equals("clone")) { // Lets go back through the code from the start of the shadow InstructionHandle searchPtr = range.getStart().getPrev(); while (Range.isRangeHandle(searchPtr) || searchPtr.getInstruction() instanceof StoreInstruction) { // ignore this instruction - it doesnt give us the info we want searchPtr = searchPtr.getPrev(); } // A load instruction may tell us the real type of what the clone() call is on if (searchPtr.getInstruction() instanceof LoadInstruction) { LoadInstruction li = (LoadInstruction)searchPtr.getInstruction(); li.getIndex(); LocalVariableTag lvt = LazyMethodGen.getLocalVariableTag(searchPtr,li.getIndex()); return lvt.getType(); } // A field access instruction may tell us the real type of what the clone() call is on if (searchPtr.getInstruction() instanceof FieldInstruction) { FieldInstruction si = (FieldInstruction)searchPtr.getInstruction(); Type t = si.getFieldType(getEnclosingClass().getConstantPoolGen()); return BcelWorld.fromBcel(t); } // A new array instruction obviously tells us it is an array type ! if (searchPtr.getInstruction() instanceof ANEWARRAY) { //ANEWARRAY ana = (ANEWARRAY)searchPoint.getInstruction(); //Type t = ana.getType(getEnclosingClass().getConstantPoolGen()); // Just use a standard java.lang.object array - that will work fine return BcelWorld.fromBcel(new ArrayType(Type.OBJECT,1)); } // A multi new array instruction obviously tells us it is an array type ! if (searchPtr.getInstruction() instanceof MULTIANEWARRAY) { MULTIANEWARRAY ana = (MULTIANEWARRAY)searchPtr.getInstruction(); // Type t = ana.getType(getEnclosingClass().getConstantPoolGen()); // t = new ArrayType(t,ana.getDimensions()); // Just use a standard java.lang.object array - that will work fine return BcelWorld.fromBcel(new ArrayType(Type.OBJECT,ana.getDimensions())); } throw new BCException("Can't determine real target of clone() when processing instruction "+ searchPtr.getInstruction()); } return tx; } public void initializeArgVars() { if (argVars != null) return; InstructionFactory fact = getFactory(); int len = getArgCount(); argVars = new BcelVar[len]; int positionOffset = (hasTarget() ? 1 : 0) + ((hasThis() && !getKind().isTargetSameAsThis()) ? 1 : 0); if (getKind().argsOnStack()) { // we move backwards because we're popping off the stack for (int i = len - 1; i >= 0; i--) { UnresolvedType type = getArgType(i); BcelVar tmp = genTempVar(type, "ajc$arg" + i); range.insert(tmp.createStore(getFactory()), Range.OutsideBefore); int position = i; position += positionOffset; tmp.setPositionInAroundState(position); argVars[i] = tmp; } } else { int index = 0; if (arg0HoldsThis()) index++; for (int i = 0; i < len; i++) { UnresolvedType type = getArgType(i); BcelVar tmp = genTempVar(type, "ajc$arg" + i); range.insert(tmp.createCopyFrom(fact, index), Range.OutsideBefore); argVars[i] = tmp; int position = i; position += positionOffset; // System.out.println("set position: " + tmp + ", " + position + " in " + this); // System.out.println(" hasThis: " + hasThis() + ", hasTarget: " + hasTarget()); tmp.setPositionInAroundState(position); index += type.getSize(); } } } public void initializeForAroundClosure() { initializeArgVars(); if (hasTarget()) initializeTargetVar(); if (hasThis()) initializeThisVar(); // System.out.println("initialized: " + this + " thisVar = " + thisVar); } public void initializeThisAnnotationVars() { if (thisAnnotationVars != null) return; thisAnnotationVars = new HashMap(); // populate.. } public void initializeTargetAnnotationVars() { if (targetAnnotationVars != null) return; if (getKind().isTargetSameAsThis()) { if (hasThis()) initializeThisAnnotationVars(); targetAnnotationVars = thisAnnotationVars; } else { targetAnnotationVars = new HashMap(); ResolvedType[] rtx = this.getTargetType().resolve(world).getAnnotationTypes(); // what about annotations we havent gotten yet but we will get in subclasses? for (int i = 0; i < rtx.length; i++) { ResolvedType typeX = rtx[i]; targetAnnotationVars.put(typeX,new TypeAnnotationAccessVar(typeX,(BcelVar)getTargetVar())); } // populate. } } public void initializeArgAnnotationVars() { if (argAnnotationVars != null) return; int numArgs = getArgCount(); argAnnotationVars = new Map[numArgs]; for (int i = 0; i < argAnnotationVars.length; i++) { argAnnotationVars[i] = new HashMap(); //FIXME asc just delete this logic - we always build the Var on demand, as we don't know at weave time // what the full set of annotations could be (due to static/dynamic type differences...) } } protected Member getRelevantMember(Member relevantMember, ResolvedType relevantType){ if (relevantMember != null){ return relevantMember; } relevantMember = getSignature().resolve(world); // check the ITD'd dooberries List mungers = relevantType.resolve(world).getInterTypeMungers(); for (Iterator iter = mungers.iterator(); iter.hasNext();) { BcelTypeMunger typeMunger = (BcelTypeMunger) iter.next(); if (typeMunger.getMunger() instanceof NewMethodTypeMunger || typeMunger.getMunger() instanceof NewConstructorTypeMunger) { ResolvedMember fakerm = typeMunger.getSignature(); if (fakerm.getName().equals(getSignature().getName()) && fakerm.getParameterSignature().equals(getSignature().getParameterSignature())){ if (relevantMember.getKind()==ResolvedMember.CONSTRUCTOR){ relevantMember = AjcMemberMaker.interConstructor( relevantType, (ResolvedMember)relevantMember, typeMunger.getAspectType()); } else { relevantMember = AjcMemberMaker.interMethod((ResolvedMember)relevantMember, typeMunger.getAspectType(), false); } // in the above.. what about if it's on an Interface? Can that happen? // then the last arg of the above should be true return relevantMember; } } } return null; } protected ResolvedType [] getAnnotations(Member relevantMember, ResolvedType relevantType){ if (relevantMember == null){ // check the ITD'd dooberries List mungers = relevantType.resolve(world).getInterTypeMungers(); for (Iterator iter = mungers.iterator(); iter.hasNext();) { BcelTypeMunger typeMunger = (BcelTypeMunger) iter.next(); if (typeMunger.getMunger() instanceof NewMethodTypeMunger || typeMunger.getMunger() instanceof NewConstructorTypeMunger) { ResolvedMember fakerm = typeMunger.getSignature(); //if (fakerm.hasAnnotations()) ResolvedMember ajcMethod = (getSignature().getKind()==ResolvedMember.CONSTRUCTOR? AjcMemberMaker.postIntroducedConstructor(typeMunger.getAspectType(),fakerm.getDeclaringType(),fakerm.getParameterTypes()): AjcMemberMaker.interMethodDispatcher(fakerm,typeMunger.getAspectType())); //AjcMemberMaker.interMethodBody(fakerm,typeMunger.getAspectType())); ResolvedMember rmm = findMethod(typeMunger.getAspectType(),ajcMethod); if (fakerm.getName().equals(getSignature().getName()) && fakerm.getParameterSignature().equals(getSignature().getParameterSignature())) { relevantType = typeMunger.getAspectType(); relevantMember = rmm; return relevantMember.getAnnotationTypes(); } } } } return relevantMember.getAnnotationTypes(); } public void initializeKindedAnnotationVars() { if (kindedAnnotationVars != null) return; kindedAnnotationVars = new HashMap(); // by determining what "kind" of shadow we are, we can find out the // annotations on the appropriate element (method, field, constructor, type). // Then create one BcelVar entry in the map for each annotation, keyed by // annotation type (UnresolvedType). // FIXME asc Refactor this code, there is duplication ResolvedType[] annotations = null; Member relevantMember = getSignature(); ResolvedType relevantType = relevantMember.getDeclaringType().resolve(world); if (getKind() == Shadow.StaticInitialization) { annotations = relevantType.resolve(world).getAnnotationTypes(); } else if (getKind() == Shadow.MethodCall || getKind() == Shadow.ConstructorCall) { relevantMember = findMethod2(relevantType.resolve(world).getDeclaredMethods(),getSignature()); annotations = getAnnotations(relevantMember,relevantType); relevantMember = getRelevantMember(relevantMember,relevantType); } else if (getKind() == Shadow.FieldSet || getKind() == Shadow.FieldGet) { relevantMember = findField(relevantType.getDeclaredFields(),getSignature()); if (relevantMember==null) { // check the ITD'd dooberries List mungers = relevantType.resolve(world).getInterTypeMungers(); for (Iterator iter = mungers.iterator(); iter.hasNext();) { BcelTypeMunger typeMunger = (BcelTypeMunger) iter.next(); if (typeMunger.getMunger() instanceof NewFieldTypeMunger) { ResolvedMember fakerm = typeMunger.getSignature(); //if (fakerm.hasAnnotations()) ResolvedMember ajcMethod = AjcMemberMaker.interFieldInitializer(fakerm,typeMunger.getAspectType()); ResolvedMember rmm = findMethod(typeMunger.getAspectType(),ajcMethod); if (fakerm.equals(getSignature())) { relevantType = typeMunger.getAspectType(); relevantMember = rmm; } } } } annotations = relevantMember.getAnnotationTypes(); } else if (getKind() == Shadow.MethodExecution || getKind() == Shadow.ConstructorExecution || getKind() == Shadow.AdviceExecution) { ResolvedMember rm[] = relevantType.getDeclaredMethods(); relevantMember = findMethod2(relevantType.getDeclaredMethods(),getSignature()); annotations = getAnnotations(relevantMember,relevantType); relevantMember = getRelevantMember(relevantMember,relevantType); } else if (getKind() == Shadow.ExceptionHandler) { relevantType = getSignature().getParameterTypes()[0].resolve(world); annotations = relevantType.getAnnotationTypes(); } else if (getKind() == Shadow.PreInitialization || getKind() == Shadow.Initialization) { ResolvedMember found = findMethod2(relevantType.getDeclaredMethods(),getSignature()); annotations = found.getAnnotationTypes(); } if (annotations == null) { // We can't have recognized the shadow - should blow up now to be on the safe side throw new BCException("Couldn't discover annotations for shadow: "+getKind()); } for (int i = 0; i < annotations.length; i++) { ResolvedType aTX = annotations[i]; KindedAnnotationAccessVar kaav = new KindedAnnotationAccessVar(getKind(),aTX.resolve(world),relevantType,relevantMember); kindedAnnotationVars.put(aTX,kaav); } } //FIXME asc whats the real diff between this one and the version in findMethod()? ResolvedMember findMethod2(ResolvedMember rm[], Member sig) { ResolvedMember found = null; // String searchString = getSignature().getName()+getSignature().getParameterSignature(); for (int i = 0; i < rm.length && found==null; i++) { ResolvedMember member = rm[i]; if (member.getName().equals(sig.getName()) && member.getParameterSignature().equals(sig.getParameterSignature())) found = member; } return found; } private ResolvedMember findMethod(ResolvedType aspectType, ResolvedMember ajcMethod) { ResolvedMember decMethods[] = aspectType.getDeclaredMethods(); for (int i = 0; i < decMethods.length; i++) { ResolvedMember member = decMethods[i]; if (member.equals(ajcMethod)) return member; } return null; } private ResolvedMember findField(ResolvedMember[] members,Member lookingFor) { for (int i = 0; i < members.length; i++) { ResolvedMember member = members[i]; if ( member.getName().equals(getSignature().getName()) && member.getType().equals(getSignature().getType())) { return member; } } return null; } public void initializeWithinAnnotationVars() { if (withinAnnotationVars != null) return; withinAnnotationVars = new HashMap(); ResolvedType[] annotations = getEnclosingType().resolve(world).getAnnotationTypes(); for (int i = 0; i < annotations.length; i++) { ResolvedType ann = annotations[i]; Kind k = Shadow.StaticInitialization; withinAnnotationVars.put(ann,new KindedAnnotationAccessVar(k,ann,getEnclosingType(),null)); } } public void initializeWithinCodeAnnotationVars() { if (withincodeAnnotationVars != null) return; withincodeAnnotationVars = new HashMap(); // For some shadow we are interested in annotations on the method containing that shadow. ResolvedType[] annotations = getEnclosingMethod().getMemberView().getAnnotationTypes(); for (int i = 0; i < annotations.length; i++) { ResolvedType ann = annotations[i]; Kind k = (getEnclosingMethod().getMemberView().getKind()==Member.CONSTRUCTOR? Shadow.ConstructorExecution:Shadow.MethodExecution); withincodeAnnotationVars.put(ann, new KindedAnnotationAccessVar(k,ann,getEnclosingType(),getEnclosingCodeSignature())); } } // ---- weave methods void weaveBefore(BcelAdvice munger) { range.insert( munger.getAdviceInstructions(this, null, range.getRealStart()), Range.InsideBefore); } public void weaveAfter(BcelAdvice munger) { weaveAfterThrowing(munger, UnresolvedType.THROWABLE); weaveAfterReturning(munger); } /** * We guarantee that the return value is on the top of the stack when * munger.getAdviceInstructions() will be run * (Unless we have a void return type in which case there's nothing) */ public void weaveAfterReturning(BcelAdvice munger) { // InstructionFactory fact = getFactory(); List returns = new ArrayList(); Instruction ret = null; for (InstructionHandle ih = range.getStart(); ih != range.getEnd(); ih = ih.getNext()) { if (ih.getInstruction() instanceof ReturnInstruction) { returns.add(ih); ret = Utility.copyInstruction(ih.getInstruction()); } } InstructionList retList; InstructionHandle afterAdvice; if (ret != null) { retList = new InstructionList(ret); afterAdvice = retList.getStart(); } else /* if (munger.hasDynamicTests()) */ { /* * 27: getstatic #72; //Field ajc$cflowCounter$0:Lorg/aspectj/runtime/internal/CFlowCounter; 30: invokevirtual #87; //Method org/aspectj/runtime/internal/CFlowCounter.dec:()V 33: aload 6 35: athrow 36: nop 37: getstatic #72; //Field ajc$cflowCounter$0:Lorg/aspectj/runtime/internal/CFlowCounter; 40: invokevirtual #87; //Method org/aspectj/runtime/internal/CFlowCounter.dec:()V 43: d2i 44: invokespecial #23; //Method java/lang/Object."<init>":()V */ retList = new InstructionList(InstructionConstants.NOP); afterAdvice = retList.getStart(); // } else { // retList = new InstructionList(); // afterAdvice = null; } InstructionList advice = new InstructionList(); BcelVar tempVar = null; if (munger.hasExtraParameter()) { UnresolvedType tempVarType = getReturnType(); if (tempVarType.equals(ResolvedType.VOID)) { tempVar = genTempVar(UnresolvedType.OBJECT); advice.append(InstructionConstants.ACONST_NULL); tempVar.appendStore(advice, getFactory()); } else { tempVar = genTempVar(tempVarType); advice.append(InstructionFactory.createDup(tempVarType.getSize())); tempVar.appendStore(advice, getFactory()); } } advice.append(munger.getAdviceInstructions(this, tempVar, afterAdvice)); if (ret != null) { InstructionHandle gotoTarget = advice.getStart(); for (Iterator i = returns.iterator(); i.hasNext();) { InstructionHandle ih = (InstructionHandle) i.next(); Utility.replaceInstruction( ih, InstructionFactory.createBranchInstruction( Constants.GOTO, gotoTarget), enclosingMethod); } range.append(advice); range.append(retList); } else { range.append(advice); range.append(retList); } } public void weaveAfterThrowing(BcelAdvice munger, UnresolvedType catchType) { // a good optimization would be not to generate anything here // if the shadow is GUARANTEED empty (i.e., there's NOTHING, not even // a shadow, inside me). if (getRange().getStart().getNext() == getRange().getEnd()) return; InstructionFactory fact = getFactory(); InstructionList handler = new InstructionList(); BcelVar exceptionVar = genTempVar(catchType); exceptionVar.appendStore(handler, fact); // pr62642 // I will now jump through some firey BCEL hoops to generate a trivial bit of code: // if (exc instanceof ExceptionInInitializerError) // throw (ExceptionInInitializerError)exc; if (this.getEnclosingMethod().getName().equals("<clinit>")) { ResolvedType eiieType = world.resolve("java.lang.ExceptionInInitializerError"); ObjectType eiieBcelType = (ObjectType)BcelWorld.makeBcelType(eiieType); InstructionList ih = new InstructionList(InstructionConstants.NOP); handler.append(exceptionVar.createLoad(fact)); handler.append(fact.createInstanceOf(eiieBcelType)); BranchInstruction bi = InstructionFactory.createBranchInstruction(Constants.IFEQ,ih.getStart()); handler.append(bi); handler.append(exceptionVar.createLoad(fact)); handler.append(fact.createCheckCast(eiieBcelType)); handler.append(InstructionConstants.ATHROW); handler.append(ih); } InstructionList endHandler = new InstructionList( exceptionVar.createLoad(fact)); handler.append(munger.getAdviceInstructions(this, exceptionVar, endHandler.getStart())); handler.append(endHandler); handler.append(InstructionConstants.ATHROW); InstructionHandle handlerStart = handler.getStart(); if (isFallsThrough()) { InstructionHandle jumpTarget = handler.append(InstructionConstants.NOP); handler.insert(InstructionFactory.createBranchInstruction(Constants.GOTO, jumpTarget)); } InstructionHandle protectedEnd = handler.getStart(); range.insert(handler, Range.InsideAfter); enclosingMethod.addExceptionHandler(range.getStart().getNext(), protectedEnd.getPrev(), handlerStart, (ObjectType)BcelWorld.makeBcelType(catchType), //???Type.THROWABLE, // high priority if our args are on the stack getKind().hasHighPriorityExceptions()); } //??? this shares a lot of code with the above weaveAfterThrowing //??? would be nice to abstract that to say things only once public void weaveSoftener(BcelAdvice munger, UnresolvedType catchType) { // a good optimization would be not to generate anything here // if the shadow is GUARANTEED empty (i.e., there's NOTHING, not even // a shadow, inside me). if (getRange().getStart().getNext() == getRange().getEnd()) return; InstructionFactory fact = getFactory(); InstructionList handler = new InstructionList(); InstructionList rtExHandler = new InstructionList(); BcelVar exceptionVar = genTempVar(catchType); handler.append(fact.createNew(NameMangler.SOFT_EXCEPTION_TYPE)); handler.append(InstructionFactory.createDup(1)); handler.append(exceptionVar.createLoad(fact)); handler.append(fact.createInvoke(NameMangler.SOFT_EXCEPTION_TYPE, "<init>", Type.VOID, new Type[] { Type.THROWABLE }, Constants.INVOKESPECIAL)); //??? special handler.append(InstructionConstants.ATHROW); // ENH 42737 exceptionVar.appendStore(rtExHandler, fact); // aload_1 rtExHandler.append(exceptionVar.createLoad(fact)); // instanceof class java/lang/RuntimeException rtExHandler.append(fact.createInstanceOf(new ObjectType("java.lang.RuntimeException"))); // ifeq go to new SOFT_EXCEPTION_TYPE instruction rtExHandler.append(InstructionFactory.createBranchInstruction(Constants.IFEQ,handler.getStart())); // aload_1 rtExHandler.append(exceptionVar.createLoad(fact)); // athrow rtExHandler.append(InstructionFactory.ATHROW); InstructionHandle handlerStart = rtExHandler.getStart(); if (isFallsThrough()) { InstructionHandle jumpTarget = range.getEnd();//handler.append(fact.NOP); rtExHandler.insert(InstructionFactory.createBranchInstruction(Constants.GOTO, jumpTarget)); } rtExHandler.append(handler); InstructionHandle protectedEnd = rtExHandler.getStart(); range.insert(rtExHandler, Range.InsideAfter); enclosingMethod.addExceptionHandler(range.getStart().getNext(), protectedEnd.getPrev(), handlerStart, (ObjectType)BcelWorld.makeBcelType(catchType), // high priority if our args are on the stack getKind().hasHighPriorityExceptions()); } public void weavePerObjectEntry(final BcelAdvice munger, final BcelVar onVar) { final InstructionFactory fact = getFactory(); InstructionList entryInstructions = new InstructionList(); InstructionList entrySuccessInstructions = new InstructionList(); onVar.appendLoad(entrySuccessInstructions, fact); entrySuccessInstructions.append( Utility.createInvoke(fact, world, AjcMemberMaker.perObjectBind(munger.getConcreteAspect()))); InstructionList testInstructions = munger.getTestInstructions(this, entrySuccessInstructions.getStart(), range.getRealStart(), entrySuccessInstructions.getStart()); entryInstructions.append(testInstructions); entryInstructions.append(entrySuccessInstructions); range.insert(entryInstructions, Range.InsideBefore); } // PTWIMPL Create static initializer to call the aspect factory /** * Causes the aspect instance to be *set* for later retrievable through localAspectof()/aspectOf() */ public void weavePerTypeWithinAspectInitialization(final BcelAdvice munger,UnresolvedType t) { if (t.resolve(world).isInterface()) return; // Don't initialize statics in final InstructionFactory fact = getFactory(); InstructionList entryInstructions = new InstructionList(); InstructionList entrySuccessInstructions = new InstructionList(); BcelObjectType aspectType = BcelWorld.getBcelObjectType(munger.getConcreteAspect()); String aspectname = munger.getConcreteAspect().getName(); String ptwField = NameMangler.perTypeWithinFieldForTarget(munger.getConcreteAspect()); entrySuccessInstructions.append(new PUSH(fact.getConstantPool(),t.getName())); entrySuccessInstructions.append(fact.createInvoke(aspectname,"ajc$createAspectInstance",new ObjectType(aspectname), new Type[]{new ObjectType("java.lang.String")},Constants.INVOKESTATIC)); entrySuccessInstructions.append(fact.createPutStatic(t.getName(),ptwField, new ObjectType(aspectname))); entryInstructions.append(entrySuccessInstructions); range.insert(entryInstructions, Range.InsideBefore); } public void weaveCflowEntry(final BcelAdvice munger, final Member cflowField) { final boolean isPer = munger.getKind() == AdviceKind.PerCflowBelowEntry || munger.getKind() == AdviceKind.PerCflowEntry; final Type objectArrayType = new ArrayType(Type.OBJECT, 1); final InstructionFactory fact = getFactory(); final BcelVar testResult = genTempVar(ResolvedType.BOOLEAN); InstructionList entryInstructions = new InstructionList(); { InstructionList entrySuccessInstructions = new InstructionList(); if (munger.hasDynamicTests()) { entryInstructions.append(Utility.createConstant(fact, 0)); testResult.appendStore(entryInstructions, fact); entrySuccessInstructions.append(Utility.createConstant(fact, 1)); testResult.appendStore(entrySuccessInstructions, fact); } if (isPer) { entrySuccessInstructions.append( fact.createInvoke(munger.getConcreteAspect().getName(), NameMangler.PERCFLOW_PUSH_METHOD, Type.VOID, new Type[] { }, Constants.INVOKESTATIC)); } else { BcelVar[] cflowStateVars = munger.getExposedStateAsBcelVars(); if (cflowStateVars.length == 0) { // This should be getting managed by a counter - lets make sure. if (!cflowField.getType().getName().endsWith("CFlowCounter")) throw new RuntimeException("Incorrectly attempting counter operation on stacked cflow"); entrySuccessInstructions.append( Utility.createGet(fact, cflowField)); //arrayVar.appendLoad(entrySuccessInstructions, fact); entrySuccessInstructions.append(fact.createInvoke(NameMangler.CFLOW_COUNTER_TYPE,"inc",Type.VOID,new Type[] { },Constants.INVOKEVIRTUAL)); } else { BcelVar arrayVar = genTempVar(UnresolvedType.OBJECTARRAY); int alen = cflowStateVars.length; entrySuccessInstructions.append(Utility.createConstant(fact, alen)); entrySuccessInstructions.append( (Instruction) fact.createNewArray(Type.OBJECT, (short) 1)); arrayVar.appendStore(entrySuccessInstructions, fact); for (int i = 0; i < alen; i++) { arrayVar.appendConvertableArrayStore( entrySuccessInstructions, fact, i, cflowStateVars[i]); } entrySuccessInstructions.append( Utility.createGet(fact, cflowField)); arrayVar.appendLoad(entrySuccessInstructions, fact); entrySuccessInstructions.append( fact.createInvoke(NameMangler.CFLOW_STACK_TYPE, "push", Type.VOID, new Type[] { objectArrayType }, Constants.INVOKEVIRTUAL)); } } InstructionList testInstructions = munger.getTestInstructions(this, entrySuccessInstructions.getStart(), range.getRealStart(), entrySuccessInstructions.getStart()); entryInstructions.append(testInstructions); entryInstructions.append(entrySuccessInstructions); } // this is the same for both per and non-per weaveAfter(new BcelAdvice(null, null, null, 0, 0, 0, null, null) { public InstructionList getAdviceInstructions( BcelShadow s, BcelVar extraArgVar, InstructionHandle ifNoAdvice) { InstructionList exitInstructions = new InstructionList(); if (munger.hasDynamicTests()) { testResult.appendLoad(exitInstructions, fact); exitInstructions.append( InstructionFactory.createBranchInstruction( Constants.IFEQ, ifNoAdvice)); } exitInstructions.append(Utility.createGet(fact, cflowField)); if (munger.getKind() != AdviceKind.PerCflowEntry && munger.getKind() != AdviceKind.PerCflowBelowEntry && munger.getExposedStateAsBcelVars().length==0) { exitInstructions .append( fact .createInvoke( NameMangler.CFLOW_COUNTER_TYPE, "dec", Type.VOID, new Type[] { }, Constants.INVOKEVIRTUAL)); } else { exitInstructions .append( fact .createInvoke( NameMangler.CFLOW_STACK_TYPE, "pop", Type.VOID, new Type[] { }, Constants.INVOKEVIRTUAL)); } return exitInstructions; } }); range.insert(entryInstructions, Range.InsideBefore); } public void weaveAroundInline( BcelAdvice munger, boolean hasDynamicTest) { /* Implementation notes: * * AroundInline still extracts the instructions of the original shadow into * an extracted method. This allows inlining of even that advice that doesn't * call proceed or calls proceed more than once. * * It extracts the instructions of the original shadow into a method. * * Then it extracts the instructions of the advice into a new method defined on * this enclosing class. This new method can then be specialized as below. * * Then it searches in the instructions of the advice for any call to the * proceed method. * * At such a call, there is stuff on the stack representing the arguments to * proceed. Pop these into the frame. * * Now build the stack for the call to the extracted method, taking values * either from the join point state or from the new frame locs from proceed. * Now call the extracted method. The right return value should be on the * stack, so no cast is necessary. * * If only one call to proceed is made, we can re-inline the original shadow. * We are not doing that presently. * * If the body of the advice can be determined to not alter the stack, or if * this shadow doesn't care about the stack, i.e. method-execution, then the * new method for the advice can also be re-lined. We are not doing that * presently. */ // !!! THIS BLOCK OF CODE SHOULD BE IN A METHOD CALLED weaveAround(...); Member mungerSig = munger.getSignature(); ResolvedType declaringType = world.resolve(mungerSig.getDeclaringType(),true); if (declaringType == ResolvedType.MISSING) { IMessage msg = new Message( WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_DURING_AROUND_WEAVE,declaringType.getClassName()), "",IMessage.ERROR,getSourceLocation(),null, new ISourceLocation[]{ munger.getSourceLocation()}); world.getMessageHandler().handleMessage(msg); } //??? might want some checks here to give better errors BcelObjectType ot = BcelWorld.getBcelObjectType(declaringType); LazyMethodGen adviceMethod = ot.getLazyClassGen().getLazyMethodGen(mungerSig); if (!adviceMethod.getCanInline()) { weaveAroundClosure(munger, hasDynamicTest); return; } // specific test for @AJ proceedInInners if (munger.getConcreteAspect().isAnnotationStyleAspect()) { // if we can't find one proceed() // we suspect that the call is happening in an inner class // so we don't inline it. // Note: for code style, this is done at Aspect compilation time. boolean canSeeProceedPassedToOther = false; InstructionHandle curr = adviceMethod.getBody().getStart(); InstructionHandle end = adviceMethod.getBody().getEnd(); ConstantPoolGen cpg = adviceMethod.getEnclosingClass().getConstantPoolGen(); while (curr != end) { InstructionHandle next = curr.getNext(); Instruction inst = curr.getInstruction(); if ((inst instanceof InvokeInstruction) && ((InvokeInstruction)inst).getSignature(cpg).indexOf("Lorg/aspectj/lang/ProceedingJoinPoint;") > 0) { // we may want to refine to exclude stuff returning jp ? // does code style skip inline if i write dump(thisJoinPoint) ? canSeeProceedPassedToOther = true;// we see one pjp passed around - dangerous break; } curr = next; } if (canSeeProceedPassedToOther) { // remember this decision to avoid re-analysis adviceMethod.setCanInline(false); weaveAroundClosure(munger, hasDynamicTest); return; } } // We can't inline around methods if they have around advice on them, this // is because the weaving will extract the body and hence the proceed call. //??? should consider optimizations to recognize simple cases that don't require body extraction enclosingMethod.setCanInline(false); // start by exposing various useful things into the frame final InstructionFactory fact = getFactory(); // now generate the aroundBody method LazyMethodGen extractedMethod = extractMethod( NameMangler.aroundCallbackMethodName( getSignature(), getEnclosingClass()), Modifier.PRIVATE, munger ); // now extract the advice into its own method String adviceMethodName = NameMangler.aroundCallbackMethodName( getSignature(), getEnclosingClass()) + "$advice"; List argVarList = new ArrayList(); List proceedVarList = new ArrayList(); int extraParamOffset = 0; // Create the extra parameters that are needed for passing to proceed // This code is very similar to that found in makeCallToCallback and should // be rationalized in the future if (thisVar != null) { argVarList.add(thisVar); proceedVarList.add(new BcelVar(thisVar.getType(), extraParamOffset)); extraParamOffset += thisVar.getType().getSize(); } if (targetVar != null && targetVar != thisVar) { argVarList.add(targetVar); proceedVarList.add(new BcelVar(targetVar.getType(), extraParamOffset)); extraParamOffset += targetVar.getType().getSize(); } for (int i = 0, len = getArgCount(); i < len; i++) { argVarList.add(argVars[i]); proceedVarList.add(new BcelVar(argVars[i].getType(), extraParamOffset)); extraParamOffset += argVars[i].getType().getSize(); } if (thisJoinPointVar != null) { argVarList.add(thisJoinPointVar); proceedVarList.add(new BcelVar(thisJoinPointVar.getType(), extraParamOffset)); extraParamOffset += thisJoinPointVar.getType().getSize(); } Type[] adviceParameterTypes = adviceMethod.getArgumentTypes(); Type[] extractedMethodParameterTypes = extractedMethod.getArgumentTypes(); Type[] parameterTypes = new Type[extractedMethodParameterTypes.length + adviceParameterTypes.length + 1]; int parameterIndex = 0; System.arraycopy( extractedMethodParameterTypes, 0, parameterTypes, parameterIndex, extractedMethodParameterTypes.length); parameterIndex += extractedMethodParameterTypes.length; parameterTypes[parameterIndex++] = BcelWorld.makeBcelType(adviceMethod.getEnclosingClass().getType()); System.arraycopy( adviceParameterTypes, 0, parameterTypes, parameterIndex, adviceParameterTypes.length); LazyMethodGen localAdviceMethod = new LazyMethodGen( Modifier.PRIVATE | Modifier.FINAL | Modifier.STATIC, adviceMethod.getReturnType(), adviceMethodName, parameterTypes, new String[0], getEnclosingClass()); String donorFileName = adviceMethod.getEnclosingClass().getInternalFileName(); String recipientFileName = getEnclosingClass().getInternalFileName(); // System.err.println("donor " + donorFileName); // System.err.println("recip " + recipientFileName); if (! donorFileName.equals(recipientFileName)) { localAdviceMethod.fromFilename = donorFileName; getEnclosingClass().addInlinedSourceFileInfo( donorFileName, adviceMethod.highestLineNumber); } getEnclosingClass().addMethodGen(localAdviceMethod); // create a map that will move all slots in advice method forward by extraParamOffset // in order to make room for the new proceed-required arguments that are added at // the beginning of the parameter list int nVars = adviceMethod.getMaxLocals() + extraParamOffset; IntMap varMap = IntMap.idMap(nVars); for (int i=extraParamOffset; i < nVars; i++) { varMap.put(i-extraParamOffset, i); } localAdviceMethod.getBody().insert( BcelClassWeaver.genInlineInstructions(adviceMethod, localAdviceMethod, varMap, fact, true)); localAdviceMethod.setMaxLocals(nVars); //System.err.println(localAdviceMethod); // the shadow is now empty. First, create a correct call // to the around advice. This includes both the call (which may involve // value conversion of the advice arguments) and the return // (which may involve value conversion of the return value). Right now // we push a null for the unused closure. It's sad, but there it is. InstructionList advice = new InstructionList(); // InstructionHandle adviceMethodInvocation; { for (Iterator i = argVarList.iterator(); i.hasNext(); ) { BcelVar var = (BcelVar)i.next(); var.appendLoad(advice, fact); } // ??? we don't actually need to push NULL for the closure if we take care advice.append( munger.getAdviceArgSetup( this, null, (munger.getConcreteAspect().isAnnotationStyleAspect())? this.loadThisJoinPoint(): new InstructionList(InstructionConstants.ACONST_NULL))); // adviceMethodInvocation = advice.append( Utility.createInvoke(fact, localAdviceMethod)); //(fact, getWorld(), munger.getSignature())); advice.append( Utility.createConversion( getFactory(), BcelWorld.makeBcelType(munger.getSignature().getReturnType()), extractedMethod.getReturnType())); if (! isFallsThrough()) { advice.append(InstructionFactory.createReturn(extractedMethod.getReturnType())); } } // now, situate the call inside the possible dynamic tests, // and actually add the whole mess to the shadow if (! hasDynamicTest) { range.append(advice); } else { InstructionList afterThingie = new InstructionList(InstructionConstants.NOP); InstructionList callback = makeCallToCallback(extractedMethod); if (terminatesWithReturn()) { callback.append( InstructionFactory.createReturn(extractedMethod.getReturnType())); } else { //InstructionHandle endNop = range.insert(fact.NOP, Range.InsideAfter); advice.append( InstructionFactory.createBranchInstruction( Constants.GOTO, afterThingie.getStart())); } range.append( munger.getTestInstructions( this, advice.getStart(), callback.getStart(), advice.getStart())); range.append(advice); range.append(callback); range.append(afterThingie); } // now search through the advice, looking for a call to PROCEED. // Then we replace the call to proceed with some argument setup, and a // call to the extracted method. // inlining support for code style aspects if (!munger.getConcreteAspect().isAnnotationStyleAspect()) { String proceedName = NameMangler.proceedMethodName(munger.getSignature().getName()); InstructionHandle curr = localAdviceMethod.getBody().getStart(); InstructionHandle end = localAdviceMethod.getBody().getEnd(); ConstantPoolGen cpg = localAdviceMethod.getEnclosingClass().getConstantPoolGen(); while (curr != end) { InstructionHandle next = curr.getNext(); Instruction inst = curr.getInstruction(); if ((inst instanceof INVOKESTATIC) && proceedName.equals(((INVOKESTATIC) inst).getMethodName(cpg))) { localAdviceMethod.getBody().append( curr, getRedoneProceedCall( fact, extractedMethod, munger, localAdviceMethod, proceedVarList)); Utility.deleteInstruction(curr, localAdviceMethod); } curr = next; } // and that's it. } else { //ATAJ inlining support for @AJ aspects // [TODO document @AJ code rule: don't manipulate 2 jps proceed at the same time.. in an advice body] InstructionHandle curr = localAdviceMethod.getBody().getStart(); InstructionHandle end = localAdviceMethod.getBody().getEnd(); ConstantPoolGen cpg = localAdviceMethod.getEnclosingClass().getConstantPoolGen(); while (curr != end) { InstructionHandle next = curr.getNext(); Instruction inst = curr.getInstruction(); if ((inst instanceof INVOKEINTERFACE) && "proceed".equals(((INVOKEINTERFACE) inst).getMethodName(cpg))) { final boolean isProceedWithArgs; if (((INVOKEINTERFACE) inst).getArgumentTypes(cpg).length == 1) { // proceed with args as a boxed Object[] isProceedWithArgs = true; } else { isProceedWithArgs = false; } InstructionList insteadProceedIl = getRedoneProceedCallForAnnotationStyle( fact, extractedMethod, munger, localAdviceMethod, proceedVarList, isProceedWithArgs ); localAdviceMethod.getBody().append(curr, insteadProceedIl); Utility.deleteInstruction(curr, localAdviceMethod); } curr = next; } } } private InstructionList getRedoneProceedCall( InstructionFactory fact, LazyMethodGen callbackMethod, BcelAdvice munger, LazyMethodGen localAdviceMethod, List argVarList) { InstructionList ret = new InstructionList(); // we have on stack all the arguments for the ADVICE call. // we have in frame somewhere all the arguments for the non-advice call. BcelVar[] adviceVars = munger.getExposedStateAsBcelVars(); IntMap proceedMap = makeProceedArgumentMap(adviceVars); // System.out.println(proceedMap + " for " + this); // System.out.println(argVarList); ResolvedType[] proceedParamTypes = world.resolve(munger.getSignature().getParameterTypes()); // remove this*JoinPoint* as arguments to proceed if (munger.getBaseParameterCount()+1 < proceedParamTypes.length) { int len = munger.getBaseParameterCount()+1; ResolvedType[] newTypes = new ResolvedType[len]; System.arraycopy(proceedParamTypes, 0, newTypes, 0, len); proceedParamTypes = newTypes; } //System.out.println("stateTypes: " + Arrays.asList(stateTypes)); BcelVar[] proceedVars = Utility.pushAndReturnArrayOfVars(proceedParamTypes, ret, fact, localAdviceMethod); Type[] stateTypes = callbackMethod.getArgumentTypes(); // System.out.println("stateTypes: " + Arrays.asList(stateTypes)); for (int i=0, len=stateTypes.length; i < len; i++) { Type stateType = stateTypes[i]; ResolvedType stateTypeX = BcelWorld.fromBcel(stateType).resolve(world); if (proceedMap.hasKey(i)) { //throw new RuntimeException("unimplemented"); proceedVars[proceedMap.get(i)].appendLoadAndConvert(ret, fact, stateTypeX); } else { ((BcelVar) argVarList.get(i)).appendLoad(ret, fact); } } ret.append(Utility.createInvoke(fact, callbackMethod)); ret.append(Utility.createConversion(fact, callbackMethod.getReturnType(), BcelWorld.makeBcelType(munger.getSignature().getReturnType()))); return ret; } /** * ATAJ Handle the inlining for @AJ aspects * * @param fact * @param callbackMethod * @param munger * @param localAdviceMethod * @param argVarList * @param isProceedWithArgs * @return */ private InstructionList getRedoneProceedCallForAnnotationStyle( InstructionFactory fact, LazyMethodGen callbackMethod, BcelAdvice munger, LazyMethodGen localAdviceMethod, List argVarList, boolean isProceedWithArgs) { // Notes: // proceedingjp is on stack (since user was calling pjp.proceed(...) // the boxed args to proceed() are on stack as well (Object[]) unless // the call is to pjp.proceed(<noarg>) // new Object[]{new Integer(argAdvice1-1)};// arg of proceed // call to proceed(..) is NOT made // instead we do // itar callback args i // get from array i, convert it to the callback arg i // if ask for JP, push the one we got on the stack // invoke callback, create conversion back to Object/Integer // rest of method -- (hence all those conversions) // intValue() from original code // int res = .. from original code //Note: we just don't care about the proceed map etc InstructionList ret = new InstructionList(); // store the Object[] array on stack if proceed with args if (isProceedWithArgs) { Type objectArrayType = Type.getType("[Ljava/lang/Object;"); int localProceedArgArray = localAdviceMethod.allocateLocal(objectArrayType); ret.append(InstructionFactory.createStore(objectArrayType, localProceedArgArray)); Type proceedingJpType = Type.getType("Lorg/aspectj/lang/ProceedingJoinPoint;"); int localJp = localAdviceMethod.allocateLocal(proceedingJpType); ret.append(InstructionFactory.createStore(proceedingJpType, localJp)); // push on stack each element of the object array // that is assumed to be consistent with the callback argument (ie munger args) // TODO do we want to try catch ClassCast and AOOBE exception ? // special logic when withincode is static or not int startIndex = 0; if (thisVar != null) { startIndex = 1; //TODO this logic is actually depending on target as well - test me ret.append(new ALOAD(0));//thisVar } for (int i = startIndex, len=callbackMethod.getArgumentTypes().length; i < len; i++) { Type stateType = callbackMethod.getArgumentTypes()[i]; ResolvedType stateTypeX = BcelWorld.fromBcel(stateType).resolve(world); if ("Lorg/aspectj/lang/JoinPoint;".equals(stateType.getSignature())) { ret.append(new ALOAD(localJp));// from localAdvice signature } else { ret.append(InstructionFactory.createLoad(objectArrayType, localProceedArgArray)); ret.append(Utility.createConstant(fact, i-startIndex)); ret.append(InstructionFactory.createArrayLoad(Type.OBJECT)); ret.append(Utility.createConversion( fact, Type.OBJECT, stateType )); } } } else { Type proceedingJpType = Type.getType("Lorg/aspectj/lang/ProceedingJoinPoint;"); int localJp = localAdviceMethod.allocateLocal(proceedingJpType); ret.append(InstructionFactory.createStore(proceedingJpType, localJp)); for (int i = 0, len=callbackMethod.getArgumentTypes().length; i < len; i++) { Type stateType = callbackMethod.getArgumentTypes()[i]; ResolvedType stateTypeX = BcelWorld.fromBcel(stateType).resolve(world); if ("Lorg/aspectj/lang/JoinPoint;".equals(stateType.getSignature())) { ret.append(new ALOAD(localJp));// from localAdvice signature // } else if ("Lorg/aspectj/lang/ProceedingJoinPoint;".equals(stateType.getSignature())) { // //FIXME ALEX? // ret.append(new ALOAD(localJp));// from localAdvice signature //// ret.append(fact.createCheckCast( //// (ReferenceType) BcelWorld.makeBcelType(stateTypeX) //// )); // // cast ? // } else { ret.append(InstructionFactory.createLoad(stateType, i)); } } } // do the callback invoke ret.append(Utility.createInvoke(fact, callbackMethod)); // box it again. Handles cases where around advice does return something else than Object if (!UnresolvedType.OBJECT.equals(munger.getSignature().getReturnType())) { ret.append(Utility.createConversion( fact, callbackMethod.getReturnType(), Type.OBJECT )); } ret.append(Utility.createConversion( fact, callbackMethod.getReturnType(), BcelWorld.makeBcelType(munger.getSignature().getReturnType()) )); return ret; // // // // if (proceedMap.hasKey(i)) { // ret.append(new ALOAD(i)); // //throw new RuntimeException("unimplemented"); // //proceedVars[proceedMap.get(i)].appendLoadAndConvert(ret, fact, stateTypeX); // } else { // //((BcelVar) argVarList.get(i)).appendLoad(ret, fact); // //ret.append(new ALOAD(i)); // if ("Lorg/aspectj/lang/JoinPoint;".equals(stateType.getSignature())) { // ret.append(new ALOAD(i)); // } else { // ret.append(new ALOAD(i)); // } // } // } // // ret.append(Utility.createInvoke(fact, callbackMethod)); // ret.append(Utility.createConversion(fact, callbackMethod.getReturnType(), // BcelWorld.makeBcelType(munger.getSignature().getReturnType()))); // // //ret.append(new ACONST_NULL());//will be POPed // if (true) return ret; // // // // // we have on stack all the arguments for the ADVICE call. // // we have in frame somewhere all the arguments for the non-advice call. // // BcelVar[] adviceVars = munger.getExposedStateAsBcelVars(); // IntMap proceedMap = makeProceedArgumentMap(adviceVars); // // System.out.println(proceedMap + " for " + this); // System.out.println(argVarList); // // ResolvedType[] proceedParamTypes = // world.resolve(munger.getSignature().getParameterTypes()); // // remove this*JoinPoint* as arguments to proceed // if (munger.getBaseParameterCount()+1 < proceedParamTypes.length) { // int len = munger.getBaseParameterCount()+1; // ResolvedType[] newTypes = new ResolvedType[len]; // System.arraycopy(proceedParamTypes, 0, newTypes, 0, len); // proceedParamTypes = newTypes; // } // // //System.out.println("stateTypes: " + Arrays.asList(stateTypes)); // BcelVar[] proceedVars = // Utility.pushAndReturnArrayOfVars(proceedParamTypes, ret, fact, localAdviceMethod); // // Type[] stateTypes = callbackMethod.getArgumentTypes(); //// System.out.println("stateTypes: " + Arrays.asList(stateTypes)); // // for (int i=0, len=stateTypes.length; i < len; i++) { // Type stateType = stateTypes[i]; // ResolvedType stateTypeX = BcelWorld.fromBcel(stateType).resolve(world); // if (proceedMap.hasKey(i)) { // //throw new RuntimeException("unimplemented"); // proceedVars[proceedMap.get(i)].appendLoadAndConvert(ret, fact, stateTypeX); // } else { // ((BcelVar) argVarList.get(i)).appendLoad(ret, fact); // } // } // // ret.append(Utility.createInvoke(fact, callbackMethod)); // ret.append(Utility.createConversion(fact, callbackMethod.getReturnType(), // BcelWorld.makeBcelType(munger.getSignature().getReturnType()))); // return ret; } public void weaveAroundClosure(BcelAdvice munger, boolean hasDynamicTest) { InstructionFactory fact = getFactory(); enclosingMethod.setCanInline(false); // MOVE OUT ALL THE INSTRUCTIONS IN MY SHADOW INTO ANOTHER METHOD! LazyMethodGen callbackMethod = extractMethod( NameMangler.aroundCallbackMethodName( getSignature(), getEnclosingClass()), 0, munger); BcelVar[] adviceVars = munger.getExposedStateAsBcelVars(); String closureClassName = NameMangler.makeClosureClassName( getEnclosingClass().getType(), getEnclosingClass().getNewGeneratedNameTag()); Member constructorSig = new MemberImpl(Member.CONSTRUCTOR, UnresolvedType.forName(closureClassName), 0, "<init>", "([Ljava/lang/Object;)V"); BcelVar closureHolder = null; // This is not being used currently since getKind() == preinitializaiton // cannot happen in around advice if (getKind() == PreInitialization) { closureHolder = genTempVar(AjcMemberMaker.AROUND_CLOSURE_TYPE); } InstructionList closureInstantiation = makeClosureInstantiation(constructorSig, closureHolder); /*LazyMethodGen constructor = */ makeClosureClassAndReturnConstructor( closureClassName, callbackMethod, makeProceedArgumentMap(adviceVars) ); InstructionList returnConversionCode; if (getKind() == PreInitialization) { returnConversionCode = new InstructionList(); BcelVar stateTempVar = genTempVar(UnresolvedType.OBJECTARRAY); closureHolder.appendLoad(returnConversionCode, fact); returnConversionCode.append( Utility.createInvoke( fact, world, AjcMemberMaker.aroundClosurePreInitializationGetter())); stateTempVar.appendStore(returnConversionCode, fact); Type[] stateTypes = getSuperConstructorParameterTypes(); returnConversionCode.append(InstructionConstants.ALOAD_0); // put "this" back on the stack for (int i = 0, len = stateTypes.length; i < len; i++) { UnresolvedType bcelTX = BcelWorld.fromBcel(stateTypes[i]); ResolvedType stateRTX = world.resolve(bcelTX,true); if (stateRTX == ResolvedType.MISSING) { IMessage msg = new Message( WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_DURING_AROUND_WEAVE_PREINIT,bcelTX.getClassName()), "",IMessage.ERROR,getSourceLocation(),null, new ISourceLocation[]{ munger.getSourceLocation()}); world.getMessageHandler().handleMessage(msg); } stateTempVar.appendConvertableArrayLoad( returnConversionCode, fact, i, stateRTX); } } else { returnConversionCode = Utility.createConversion( getFactory(), BcelWorld.makeBcelType(munger.getSignature().getReturnType()), callbackMethod.getReturnType()); if (!isFallsThrough()) { returnConversionCode.append( InstructionFactory.createReturn(callbackMethod.getReturnType())); } } // ATAJ for @AJ aspect we need to link the closure with the joinpoint instance if (munger.getConcreteAspect()!=null && munger.getConcreteAspect().isAnnotationStyleAspect()) { closureInstantiation.append(Utility.createInvoke( getFactory(), getWorld(), new MemberImpl( Member.METHOD, UnresolvedType.forName("org.aspectj.runtime.internal.AroundClosure"), Modifier.PUBLIC, "linkClosureAndJoinPoint", "()Lorg/aspectj/lang/ProceedingJoinPoint;" ) )); } InstructionList advice = new InstructionList(); advice.append(munger.getAdviceArgSetup(this, null, closureInstantiation)); // invoke the advice advice.append(munger.getNonTestAdviceInstructions(this)); advice.append(returnConversionCode); if (!hasDynamicTest) { range.append(advice); } else { InstructionList callback = makeCallToCallback(callbackMethod); InstructionList postCallback = new InstructionList(); if (terminatesWithReturn()) { callback.append( InstructionFactory.createReturn(callbackMethod.getReturnType())); } else { advice.append( InstructionFactory.createBranchInstruction( Constants.GOTO, postCallback.append(InstructionConstants.NOP))); } range.append( munger.getTestInstructions( this, advice.getStart(), callback.getStart(), advice.getStart())); range.append(advice); range.append(callback); range.append(postCallback); } } // exposed for testing InstructionList makeCallToCallback(LazyMethodGen callbackMethod) { InstructionFactory fact = getFactory(); InstructionList callback = new InstructionList(); if (thisVar != null) { callback.append(InstructionConstants.ALOAD_0); } if (targetVar != null && targetVar != thisVar) { callback.append(BcelRenderer.renderExpr(fact, world, targetVar)); } callback.append(BcelRenderer.renderExprs(fact, world, argVars)); // remember to render tjps if (thisJoinPointVar != null) { callback.append(BcelRenderer.renderExpr(fact, world, thisJoinPointVar)); } callback.append(Utility.createInvoke(fact, callbackMethod)); return callback; } /** side-effect-free */ private InstructionList makeClosureInstantiation(Member constructor, BcelVar holder) { // LazyMethodGen constructor) { InstructionFactory fact = getFactory(); BcelVar arrayVar = genTempVar(UnresolvedType.OBJECTARRAY); //final Type objectArrayType = new ArrayType(Type.OBJECT, 1); final InstructionList il = new InstructionList(); int alen = getArgCount() + (thisVar == null ? 0 : 1) + ((targetVar != null && targetVar != thisVar) ? 1 : 0) + (thisJoinPointVar == null ? 0 : 1); il.append(Utility.createConstant(fact, alen)); il.append((Instruction)fact.createNewArray(Type.OBJECT, (short)1)); arrayVar.appendStore(il, fact); int stateIndex = 0; if (thisVar != null) { arrayVar.appendConvertableArrayStore(il, fact, stateIndex, thisVar); thisVar.setPositionInAroundState(stateIndex); stateIndex++; } if (targetVar != null && targetVar != thisVar) { arrayVar.appendConvertableArrayStore(il, fact, stateIndex, targetVar); targetVar.setPositionInAroundState(stateIndex); stateIndex++; } for (int i = 0, len = getArgCount(); i<len; i++) { arrayVar.appendConvertableArrayStore(il, fact, stateIndex, argVars[i]); argVars[i].setPositionInAroundState(stateIndex); stateIndex++; } if (thisJoinPointVar != null) { arrayVar.appendConvertableArrayStore(il, fact, stateIndex, thisJoinPointVar); thisJoinPointVar.setPositionInAroundState(stateIndex); stateIndex++; } il.append(fact.createNew(new ObjectType(constructor.getDeclaringType().getName()))); il.append(new DUP()); arrayVar.appendLoad(il, fact); il.append(Utility.createInvoke(fact, world, constructor)); if (getKind() == PreInitialization) { il.append(InstructionConstants.DUP); holder.appendStore(il, fact); } return il; } private IntMap makeProceedArgumentMap(BcelVar[] adviceArgs) { //System.err.println("coming in with " + Arrays.asList(adviceArgs)); IntMap ret = new IntMap(); for(int i = 0, len = adviceArgs.length; i < len; i++) { BcelVar v = (BcelVar) adviceArgs[i]; if (v == null) continue; // XXX we don't know why this is required int pos = v.getPositionInAroundState(); if (pos >= 0) { // need this test to avoid args bound via cflow ret.put(pos, i); } } //System.err.println("returning " + ret); return ret; } /** * * * @param callbackMethod the method we will call back to when our run method gets called. * * @param proceedMap A map from state position to proceed argument position. May be * non covering on state position. */ private LazyMethodGen makeClosureClassAndReturnConstructor( String closureClassName, LazyMethodGen callbackMethod, IntMap proceedMap) { String superClassName = "org.aspectj.runtime.internal.AroundClosure"; Type objectArrayType = new ArrayType(Type.OBJECT, 1); LazyClassGen closureClass = new LazyClassGen(closureClassName, superClassName, getEnclosingClass().getFileName(), Modifier.PUBLIC, new String[] {}); InstructionFactory fact = new InstructionFactory(closureClass.getConstantPoolGen()); // constructor LazyMethodGen constructor = new LazyMethodGen(Modifier.PUBLIC, Type.VOID, "<init>", new Type[] {objectArrayType}, new String[] {}, closureClass); InstructionList cbody = constructor.getBody(); cbody.append(InstructionFactory.createLoad(Type.OBJECT, 0)); cbody.append(InstructionFactory.createLoad(objectArrayType, 1)); cbody.append(fact.createInvoke(superClassName, "<init>", Type.VOID, new Type[] {objectArrayType}, Constants.INVOKESPECIAL)); cbody.append(InstructionFactory.createReturn(Type.VOID)); closureClass.addMethodGen(constructor); // method LazyMethodGen runMethod = new LazyMethodGen(Modifier.PUBLIC, Type.OBJECT, "run", new Type[] {objectArrayType}, new String[] {}, closureClass); InstructionList mbody = runMethod.getBody(); BcelVar proceedVar = new BcelVar(UnresolvedType.OBJECTARRAY.resolve(world), 1); // int proceedVarIndex = 1; BcelVar stateVar = new BcelVar(UnresolvedType.OBJECTARRAY.resolve(world), runMethod.allocateLocal(1)); // int stateVarIndex = runMethod.allocateLocal(1); mbody.append(InstructionFactory.createThis()); mbody.append(fact.createGetField(superClassName, "state", objectArrayType)); mbody.append(stateVar.createStore(fact)); // mbody.append(fact.createStore(objectArrayType, stateVarIndex)); Type[] stateTypes = callbackMethod.getArgumentTypes(); for (int i=0, len=stateTypes.length; i < len; i++) { Type stateType = stateTypes[i]; ResolvedType stateTypeX = BcelWorld.fromBcel(stateType).resolve(world); if (proceedMap.hasKey(i)) { mbody.append( proceedVar.createConvertableArrayLoad(fact, proceedMap.get(i), stateTypeX)); } else { mbody.append( stateVar.createConvertableArrayLoad(fact, i, stateTypeX)); } } mbody.append(Utility.createInvoke(fact, callbackMethod)); if (getKind() == PreInitialization) { mbody.append(Utility.createSet( fact, AjcMemberMaker.aroundClosurePreInitializationField())); mbody.append(InstructionConstants.ACONST_NULL); } else { mbody.append( Utility.createConversion( fact, callbackMethod.getReturnType(), Type.OBJECT)); } mbody.append(InstructionFactory.createReturn(Type.OBJECT)); closureClass.addMethodGen(runMethod); // class getEnclosingClass().addGeneratedInner(closureClass); return constructor; } // ---- extraction methods public LazyMethodGen extractMethod(String newMethodName, int visibilityModifier, ShadowMunger munger) { LazyMethodGen.assertGoodBody(range.getBody(), newMethodName); if (!getKind().allowsExtraction()) throw new BCException(); LazyMethodGen freshMethod = createMethodGen(newMethodName,visibilityModifier); // System.err.println("******"); // System.err.println("ABOUT TO EXTRACT METHOD for" + this); // enclosingMethod.print(System.err); // System.err.println("INTO"); // freshMethod.print(System.err); // System.err.println("WITH REMAP"); // System.err.println(makeRemap()); range.extractInstructionsInto(freshMethod, makeRemap(), (getKind() != PreInitialization) && isFallsThrough()); if (getKind() == PreInitialization) { addPreInitializationReturnCode( freshMethod, getSuperConstructorParameterTypes()); } getEnclosingClass().addMethodGen(freshMethod,munger.getSourceLocation()); return freshMethod; } private void addPreInitializationReturnCode( LazyMethodGen extractedMethod, Type[] superConstructorTypes) { InstructionList body = extractedMethod.getBody(); final InstructionFactory fact = getFactory(); BcelVar arrayVar = new BcelVar( world.getCoreType(UnresolvedType.OBJECTARRAY), extractedMethod.allocateLocal(1)); int len = superConstructorTypes.length; body.append(Utility.createConstant(fact, len)); body.append((Instruction)fact.createNewArray(Type.OBJECT, (short)1)); arrayVar.appendStore(body, fact); for (int i = len - 1; i >= 0; i++) { // convert thing on top of stack to object body.append( Utility.createConversion(fact, superConstructorTypes[i], Type.OBJECT)); // push object array arrayVar.appendLoad(body, fact); // swap body.append(InstructionConstants.SWAP); // do object array store. body.append(Utility.createConstant(fact, i)); body.append(InstructionConstants.SWAP); body.append(InstructionFactory.createArrayStore(Type.OBJECT)); } arrayVar.appendLoad(body, fact); body.append(InstructionConstants.ARETURN); } private Type[] getSuperConstructorParameterTypes() { // assert getKind() == PreInitialization InstructionHandle superCallHandle = getRange().getEnd().getNext(); InvokeInstruction superCallInstruction = (InvokeInstruction) superCallHandle.getInstruction(); return superCallInstruction.getArgumentTypes( getEnclosingClass().getConstantPoolGen()); } /** make a map from old frame location to new frame location. Any unkeyed frame * location picks out a copied local */ private IntMap makeRemap() { IntMap ret = new IntMap(5); int reti = 0; if (thisVar != null) { ret.put(0, reti++); // thisVar guaranteed to be 0 } if (targetVar != null && targetVar != thisVar) { ret.put(targetVar.getSlot(), reti++); } for (int i = 0, len = argVars.length; i < len; i++) { ret.put(argVars[i].getSlot(), reti); reti += argVars[i].getType().getSize(); } if (thisJoinPointVar != null) { ret.put(thisJoinPointVar.getSlot(), reti++); } // we not only need to put the arguments, we also need to remap their // aliases, which we so helpfully put into temps at the beginning of this join // point. if (! getKind().argsOnStack()) { int oldi = 0; int newi = 0; // if we're passing in a this and we're not argsOnStack we're always // passing in a target too if (arg0HoldsThis()) { ret.put(0, 0); oldi++; newi+=1; } //assert targetVar == thisVar for (int i = 0; i < getArgCount(); i++) { UnresolvedType type = getArgType(i); ret.put(oldi, newi); oldi += type.getSize(); newi += type.getSize(); } } // System.err.println("making remap for : " + this); // if (targetVar != null) System.err.println("target slot : " + targetVar.getSlot()); // if (thisVar != null) System.err.println(" this slot : " + thisVar.getSlot()); // System.err.println(ret); return ret; } /** * The new method always static. * It may take some extra arguments: this, target. * If it's argsOnStack, then it must take both this/target * If it's argsOnFrame, it shares this and target. * ??? rewrite this to do less array munging, please */ private LazyMethodGen createMethodGen(String newMethodName, int visibilityModifier) { Type[] parameterTypes = BcelWorld.makeBcelTypes(getArgTypes()); int modifiers = Modifier.FINAL | visibilityModifier; // XXX some bug // if (! isExpressionKind() && getSignature().isStrict(world)) { // modifiers |= Modifier.STRICT; // } modifiers |= Modifier.STATIC; if (targetVar != null && targetVar != thisVar) { UnresolvedType targetType = getTargetType(); targetType = ensureTargetTypeIsCorrect(targetType); ResolvedMember resolvedMember = getSignature().resolve(world); if (resolvedMember != null && Modifier.isProtected(resolvedMember.getModifiers()) && !samePackage(targetType.getPackageName(), getEnclosingType().getPackageName()) && !resolvedMember.getName().equals("clone")) { if (!targetType.resolve(world).isAssignableFrom(getThisType().resolve(world))) { throw new BCException("bad bytecode"); } targetType = getThisType(); } parameterTypes = addType(BcelWorld.makeBcelType(targetType), parameterTypes); } if (thisVar != null) { UnresolvedType thisType = getThisType(); parameterTypes = addType(BcelWorld.makeBcelType(thisType), parameterTypes); } // We always want to pass down thisJoinPoint in case we have already woven // some advice in here. If we only have a single piece of around advice on a // join point, it is unnecessary to accept (and pass) tjp. if (thisJoinPointVar != null) { parameterTypes = addTypeToEnd(LazyClassGen.tjpType, parameterTypes); //FIXME ALEX? which one //parameterTypes = addTypeToEnd(LazyClassGen.proceedingTjpType, parameterTypes); } UnresolvedType returnType; if (getKind() == PreInitialization) { returnType = UnresolvedType.OBJECTARRAY; } else { returnType = getReturnType(); } return new LazyMethodGen( modifiers, BcelWorld.makeBcelType(returnType), newMethodName, parameterTypes, new String[0], // XXX again, we need to look up methods! // UnresolvedType.getNames(getSignature().getExceptions(world)), getEnclosingClass()); } private boolean samePackage(String p1, String p2) { if (p1 == null) return p2 == null; if (p2 == null) return false; return p1.equals(p2); } private Type[] addType(Type type, Type[] types) { int len = types.length; Type[] ret = new Type[len+1]; ret[0] = type; System.arraycopy(types, 0, ret, 1, len); return ret; } private Type[] addTypeToEnd(Type type, Type[] types) { int len = types.length; Type[] ret = new Type[len+1]; ret[len] = type; System.arraycopy(types, 0, ret, 0, len); return ret; } public BcelVar genTempVar(UnresolvedType typeX) { return new BcelVar(typeX.resolve(world), genTempVarIndex(typeX.getSize())); } // public static final boolean CREATE_TEMP_NAMES = true; public BcelVar genTempVar(UnresolvedType typeX, String localName) { BcelVar tv = genTempVar(typeX); // if (CREATE_TEMP_NAMES) { // for (InstructionHandle ih = range.getStart(); ih != range.getEnd(); ih = ih.getNext()) { // if (Range.isRangeHandle(ih)) continue; // ih.addTargeter(new LocalVariableTag(typeX, localName, tv.getSlot())); // } // } return tv; } // eh doesn't think we need to garbage collect these (64K is a big number...) private int genTempVarIndex(int size) { return enclosingMethod.allocateLocal(size); } public InstructionFactory getFactory() { return getEnclosingClass().getFactory(); } public ISourceLocation getSourceLocation() { int sourceLine = getSourceLine(); if (sourceLine == 0 || sourceLine == -1) { // Thread.currentThread().dumpStack(); // System.err.println(this + ": " + range); return getEnclosingClass().getType().getSourceLocation(); } else { // For staticinitialization, if we have a nice offset, don't build a new source loc if (getKind()==Shadow.StaticInitialization && getEnclosingClass().getType().getSourceLocation().getOffset()!=0) return getEnclosingClass().getType().getSourceLocation(); else return getEnclosingClass().getType().getSourceContext().makeSourceLocation(sourceLine, 0); } } public Shadow getEnclosingShadow() { return enclosingShadow; } public LazyMethodGen getEnclosingMethod() { return enclosingMethod; } public boolean isFallsThrough() { return !terminatesWithReturn(); //fallsThrough; } }
98,290
Bug 98290 no "matches declare" entry in structure model for single declare warning statement
A project containing one class and one aspect: ----------------------------------------------------- package pack; public class C { public static void main(String[] args) { new C().sayHello(); } public void sayHello() { System.out.println("HELLO"); } } ---------------------------------------------------- package pack; public aspect A { declare warning : execution(* C.sayHello(..)) : "blah blah"; } ----------------------------------------------------- has the "matched by" entry for A.aj, but doesn't have the "matches declare" entry for C.java. This means that in AJDT, C.sayHello isn't added to our map and consequently we don't get any relationships showing in the Cross Reference view for A.aj.
resolved fixed
619f8bc
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-01T19:47:37Z
2005-06-03T14:46:40Z
weaver/src/org/aspectj/weaver/bcel/LazyMethodGen.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.bcel; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Set; import java.util.Stack; 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.Method; import org.aspectj.apache.bcel.classfile.Synthetic; import org.aspectj.apache.bcel.classfile.annotation.Annotation; import org.aspectj.apache.bcel.generic.BranchHandle; import org.aspectj.apache.bcel.generic.BranchInstruction; import org.aspectj.apache.bcel.generic.CPInstruction; import org.aspectj.apache.bcel.generic.ClassGenException; import org.aspectj.apache.bcel.generic.CodeExceptionGen; import org.aspectj.apache.bcel.generic.ConstantPoolGen; import org.aspectj.apache.bcel.generic.Instruction; import org.aspectj.apache.bcel.generic.InstructionHandle; import org.aspectj.apache.bcel.generic.InstructionList; import org.aspectj.apache.bcel.generic.InstructionTargeter; import org.aspectj.apache.bcel.generic.LineNumberGen; import org.aspectj.apache.bcel.generic.LocalVariableGen; import org.aspectj.apache.bcel.generic.LocalVariableInstruction; import org.aspectj.apache.bcel.generic.MethodGen; import org.aspectj.apache.bcel.generic.ObjectType; import org.aspectj.apache.bcel.generic.Select; import org.aspectj.apache.bcel.generic.Type; import org.aspectj.apache.bcel.generic.annotation.AnnotationGen; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.AnnotationX; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.MemberImpl; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.AjAttribute.EffectiveSignatureAttribute; import org.aspectj.weaver.AjAttribute.WeaverVersionInfo; /** * A LazyMethodGen should be treated as a MethodGen. It's our way of abstracting over the * low-level Method objects. It converts through {@link MethodGen} to create * and to serialize, but that's it. * * <p> At any rate, there are two ways to create LazyMethodGens. * One is from a method, which * does work through MethodGen to do the correct thing. * The other is the creation of a completely empty * LazyMethodGen, and it is used when we're constructing code from scratch. * * <p> We stay away from targeters for rangey things like Shadows and Exceptions. */ public final class LazyMethodGen { private int accessFlags; private Type returnType; private final String name; private Type[] argumentTypes; //private final String[] argumentNames; private String[] declaredExceptions; private InstructionList body; // leaving null for abstracts private Attribute[] attributes; private List newAnnotations; private final LazyClassGen enclosingClass; private BcelMethod memberView; private AjAttribute.EffectiveSignatureAttribute effectiveSignature; int highestLineNumber = 0; /** This is nonnull if this method is the result of an "inlining". We currently * copy methods into other classes for around advice. We add this field so * we can get JSR45 information correct. If/when we do _actual_ inlining, * we'll need to subtype LineNumberTag to have external line numbers. */ String fromFilename = null; private int maxLocals; private boolean canInline = true; private boolean hasExceptionHandlers; private boolean isSynthetic = false; /** * only used by {@link BcelClassWeaver} */ List /*ShadowMungers*/ matchedShadows; List /*Test*/ matchedShadowTests; // Used for interface introduction // this is the type of the interface the method is technically on public ResolvedType definingType = null; public LazyMethodGen( int accessFlags, Type returnType, String name, Type[] paramTypes, String[] declaredExceptions, LazyClassGen enclosingClass) { //System.err.println("raw create of: " + name + ", " + enclosingClass.getName() + ", " + returnType); this.memberView = null; // ??? should be okay, since constructed ones aren't woven into this.accessFlags = accessFlags; this.returnType = returnType; this.name = name; this.argumentTypes = paramTypes; //this.argumentNames = Utility.makeArgNames(paramTypes.length); this.declaredExceptions = declaredExceptions; if (!Modifier.isAbstract(accessFlags)) { body = new InstructionList(); setMaxLocals(calculateMaxLocals()); } else { body = null; } this.attributes = new Attribute[0]; this.enclosingClass = enclosingClass; assertGoodBody(); // @AJ advice are not inlined by default since requires further analysis // and weaving ordering control // TODO AV - improve - note: no room for improvement as long as aspects are reweavable // since the inlined version with wrappers and an to be done annotation to keep // inline state will be garbaged due to reweavable impl if (memberView != null && isAdviceMethod()) { if (enclosingClass.getType().isAnnotationStyleAspect()) { //TODO we could check for @Around advice as well this.canInline = false; } } } private int calculateMaxLocals() { int ret = 0; if (!Modifier.isStatic(accessFlags)) ret++; for (int i = 0, len = argumentTypes.length; i < len; i++) { ret += argumentTypes[i].getSize(); } return ret; } private Method savedMethod = null; // build from an existing method, lazy build saves most work for initialization public LazyMethodGen(Method m, LazyClassGen enclosingClass) { savedMethod = m; this.enclosingClass = enclosingClass; if (!(m.isAbstract() || m.isNative()) && m.getCode() == null) { throw new RuntimeException("bad non-abstract method with no code: " + m + " on " + enclosingClass); } if ((m.isAbstract() || m.isNative()) && m.getCode() != null) { throw new RuntimeException("bad abstract method with code: " + m + " on " + enclosingClass); } this.memberView = new BcelMethod(enclosingClass.getBcelObjectType(), m); this.accessFlags = m.getAccessFlags(); this.name = m.getName(); // @AJ advice are not inlined by default since requires further analysis // and weaving ordering control // TODO AV - improve - note: no room for improvement as long as aspects are reweavable // since the inlined version with wrappers and an to be done annotation to keep // inline state will be garbaged due to reweavable impl if (memberView != null && isAdviceMethod()) { if (enclosingClass.getType().isAnnotationStyleAspect()) { //TODO we could check for @Around advice as well this.canInline = false; } } } public boolean hasDeclaredLineNumberInfo() { return (memberView != null && memberView.hasDeclarationLineNumberInfo()); } public int getDeclarationLineNumber() { if (hasDeclaredLineNumberInfo()) { return memberView.getDeclarationLineNumber(); } else { return -1; } } public void addAnnotation(AnnotationX ax) { initialize(); if (memberView==null) { // If member view is null, we manage them in newAnnotations if (newAnnotations==null) newAnnotations = new ArrayList(); newAnnotations.add(ax); } else { memberView.addAnnotation(ax); } } public boolean hasAnnotation(UnresolvedType annotationTypeX) { initialize(); if (memberView==null) { // Check local annotations first if (newAnnotations!=null) { for (Iterator iter = newAnnotations.iterator(); iter.hasNext();) { AnnotationX element = (AnnotationX) iter.next(); if (element.getBcelAnnotation().getTypeName().equals(annotationTypeX.getName())) return true; } } memberView = new BcelMethod(getEnclosingClass().getBcelObjectType(), getMethod()); return memberView.hasAnnotation(annotationTypeX); } return memberView.hasAnnotation(annotationTypeX); } private void initialize() { if (returnType != null) return; //System.err.println("initializing: " + getName() + ", " + enclosingClass.getName() + ", " + returnType + ", " + savedMethod); MethodGen gen = new MethodGen(savedMethod, enclosingClass.getName(), enclosingClass.getConstantPoolGen()); this.returnType = gen.getReturnType(); this.argumentTypes = gen.getArgumentTypes(); this.declaredExceptions = gen.getExceptions(); this.attributes = gen.getAttributes(); //this.annotations = gen.getAnnotations(); this.maxLocals = gen.getMaxLocals(); // this.returnType = BcelWorld.makeBcelType(memberView.getReturnType()); // this.argumentTypes = BcelWorld.makeBcelTypes(memberView.getParameterTypes()); // // this.declaredExceptions = UnresolvedType.getNames(memberView.getExceptions()); //gen.getExceptions(); // this.attributes = new Attribute[0]; //gen.getAttributes(); // this.maxLocals = savedMethod.getCode().getMaxLocals(); if (gen.isAbstract() || gen.isNative()) { body = null; } else { //body = new InstructionList(savedMethod.getCode().getCode()); body = gen.getInstructionList(); unpackHandlers(gen); unpackLineNumbers(gen); unpackLocals(gen); } assertGoodBody(); //System.err.println("initialized: " + this.getClassName() + "." + this.getName()); } // XXX we're relying on the javac promise I've just made up that we won't have an early exception // in the list mask a later exception: That is, for two exceptions E and F, // if E preceeds F, then either E \cup F = {}, or E \nonstrictsubset F. So when we add F, // we add it on the _OUTSIDE_ of any handlers that share starts or ends with it. // with that in mind, we merrily go adding ranges for exceptions. private void unpackHandlers(MethodGen gen) { CodeExceptionGen[] exns = gen.getExceptionHandlers(); if (exns != null) { int len = exns.length; if (len > 0) hasExceptionHandlers = true; int priority = len - 1; for (int i = 0; i < len; i++, priority--) { CodeExceptionGen exn = exns[i]; InstructionHandle start = Range.genStart( body, getOutermostExceptionStart(exn.getStartPC())); InstructionHandle end = Range.genEnd(body, getOutermostExceptionEnd(exn.getEndPC())); // this doesn't necessarily handle overlapping correctly!!! ExceptionRange er = new ExceptionRange( body, exn.getCatchType() == null ? null : BcelWorld.fromBcel(exn.getCatchType()), priority); er.associateWithTargets(start, end, exn.getHandlerPC()); exn.setStartPC(null); // also removes from target exn.setEndPC(null); // also removes from target exn.setHandlerPC(null); // also removes from target } gen.removeExceptionHandlers(); } } private InstructionHandle getOutermostExceptionStart(InstructionHandle ih) { while (true) { if (ExceptionRange.isExceptionStart(ih.getPrev())) { ih = ih.getPrev(); } else { return ih; } } } private InstructionHandle getOutermostExceptionEnd(InstructionHandle ih) { while (true) { if (ExceptionRange.isExceptionEnd(ih.getNext())) { ih = ih.getNext(); } else { return ih; } } } private void unpackLineNumbers(MethodGen gen) { LineNumberTag lr = null; for (InstructionHandle ih = body.getStart(); ih != null; ih = ih.getNext()) { InstructionTargeter[] targeters = ih.getTargeters(); if (targeters != null) { for (int i = targeters.length - 1; i >= 0; i--) { InstructionTargeter targeter = targeters[i]; if (targeter instanceof LineNumberGen) { LineNumberGen lng = (LineNumberGen) targeter; lng.updateTarget(ih, null); int lineNumber = lng.getSourceLine(); if (highestLineNumber < lineNumber) highestLineNumber = lineNumber; lr = new LineNumberTag(lineNumber); } } } if (lr != null) { ih.addTargeter(lr); } } gen.removeLineNumbers(); } private void unpackLocals(MethodGen gen) { Set locals = new HashSet(); for (InstructionHandle ih = body.getStart(); ih != null; ih = ih.getNext()) { InstructionTargeter[] targeters = ih.getTargeters(); List ends = new ArrayList(0); if (targeters != null) { for (int i = targeters.length - 1; i >= 0; i--) { InstructionTargeter targeter = targeters[i]; if (targeter instanceof LocalVariableGen) { LocalVariableGen lng = (LocalVariableGen) targeter; LocalVariableTag lr = new LocalVariableTag(BcelWorld.fromBcel(lng.getType()), lng.getName(), lng.getIndex()); if (lng.getStart() == ih) { locals.add(lr); } else { ends.add(lr); } } } } for (Iterator i = locals.iterator(); i.hasNext(); ) { ih.addTargeter((LocalVariableTag) i.next()); } locals.removeAll(ends); } gen.removeLocalVariables(); } // =============== public int allocateLocal(Type type) { return allocateLocal(type.getSize()); } public int allocateLocal(int slots) { int max = getMaxLocals(); setMaxLocals(max + slots); return max; } public Method getMethod() { if (savedMethod != null) return savedMethod; //??? this relies on gentle treatment of constant pool try { MethodGen gen = pack(); return gen.getMethod(); } catch (ClassGenException e) { enclosingClass.getBcelObjectType().getResolvedTypeX().getWorld().showMessage( IMessage.ERROR, WeaverMessages.format(WeaverMessages.PROBLEM_GENERATING_METHOD, this.getClassName(), this.getName(), e.getMessage()), this.getMemberView() == null ? null : this.getMemberView().getSourceLocation(), null); // throw e; PR 70201.... let the normal problem reporting infrastructure deal with this rather than crashing. body = null; MethodGen gen = pack(); return gen.getMethod(); } } public void markAsChanged() { initialize(); savedMethod = null; } // ============================= public String toString() { WeaverVersionInfo weaverVersion = enclosingClass.getBcelObjectType().getWeaverVersionAttribute(); return toLongString(weaverVersion); } public String toShortString() { String access = org.aspectj.apache.bcel.classfile.Utility.accessToString(getAccessFlags()); StringBuffer buf = new StringBuffer(); if (!access.equals("")) { buf.append(access); buf.append(" "); } buf.append( org.aspectj.apache.bcel.classfile.Utility.signatureToString( getReturnType().getSignature(), true)); buf.append(" "); buf.append(getName()); buf.append("("); { int len = argumentTypes.length; if (len > 0) { buf.append( org.aspectj.apache.bcel.classfile.Utility.signatureToString( argumentTypes[0].getSignature(), true)); for (int i = 1; i < argumentTypes.length; i++) { buf.append(", "); buf.append( org.aspectj.apache.bcel.classfile.Utility.signatureToString( argumentTypes[i].getSignature(), true)); } } } buf.append(")"); { int len = declaredExceptions != null ? declaredExceptions.length : 0; if (len > 0) { buf.append(" throws "); buf.append(declaredExceptions[0]); for (int i = 1; i < declaredExceptions.length; i++) { buf.append(", "); buf.append(declaredExceptions[i]); } } } return buf.toString(); } public String toLongString(WeaverVersionInfo weaverVersion) { ByteArrayOutputStream s = new ByteArrayOutputStream(); print(new PrintStream(s),weaverVersion); return new String(s.toByteArray()); } public void print(WeaverVersionInfo weaverVersion) { print(System.out,weaverVersion); } public void print(PrintStream out, WeaverVersionInfo weaverVersion) { out.print(" " + toShortString()); printAspectAttributes(out,weaverVersion); InstructionList body = getBody(); if (body == null) { out.println(";"); return; } out.println(":"); new BodyPrinter(out).run(); out.println(" end " + toShortString()); } private void printAspectAttributes(PrintStream out, WeaverVersionInfo weaverVersion) { ISourceContext context = null; if (enclosingClass != null && enclosingClass.getType() != null) { context = enclosingClass.getType().getSourceContext(); } List as = BcelAttributes.readAjAttributes(getClassName(),attributes, context,null,weaverVersion); if (! as.isEmpty()) { out.println(" " + as.get(0)); // XXX assuming exactly one attribute, munger... } } private class BodyPrinter { Map prefixMap = new HashMap(); Map suffixMap = new HashMap(); Map labelMap = new HashMap(); InstructionList body; PrintStream out; ConstantPool pool; List ranges; BodyPrinter(PrintStream out) { this.pool = enclosingClass.getConstantPoolGen().getConstantPool(); this.body = getBody(); this.out = out; } void run() { //killNops(); assignLabels(); print(); } // label assignment void assignLabels() { LinkedList exnTable = new LinkedList(); String pendingLabel = null; // boolean hasPendingTargeters = false; int lcounter = 0; for (InstructionHandle ih = body.getStart(); ih != null; ih = ih.getNext()) { InstructionTargeter[] targeters = ih.getTargeters(); if (targeters != null) { for (int i = targeters.length - 1; i >= 0; i--) { InstructionTargeter t = targeters[i]; if (t instanceof ExceptionRange) { // assert isRangeHandle(h); ExceptionRange r = (ExceptionRange) t; if (r.getStart() == ih) { insertHandler(r, exnTable); } } else if (t instanceof BranchInstruction) { if (pendingLabel == null) { pendingLabel = "L" + lcounter++; } } else { // assert isRangeHandle(h) } } } if (pendingLabel != null) { labelMap.put(ih, pendingLabel); if (! Range.isRangeHandle(ih)) { pendingLabel = null; } } } int ecounter = 0; for (Iterator i = exnTable.iterator(); i.hasNext();) { ExceptionRange er = (ExceptionRange) i.next(); String exceptionLabel = "E" + ecounter++; labelMap.put(Range.getRealStart(er.getHandler()), exceptionLabel); labelMap.put(er.getHandler(), exceptionLabel); } } // printing void print() { int depth = 0; int currLine = -1; bodyPrint: for (InstructionHandle ih = body.getStart(); ih != null; ih = ih.getNext()) { if (Range.isRangeHandle(ih)) { Range r = Range.getRange(ih); // don't print empty ranges, that is, ranges who contain no actual instructions for (InstructionHandle xx = r.getStart(); Range.isRangeHandle(xx); xx = xx.getNext()) { if (xx == r.getEnd()) continue bodyPrint; } // doesn't handle nested: if (r.getStart().getNext() == r.getEnd()) continue; if (r.getStart() == ih) { printRangeString(r, depth++); } else { if (r.getEnd() != ih) throw new RuntimeException("bad"); printRangeString(r, --depth); } } else { printInstruction(ih, depth); int line = getLineNumber(ih, currLine); if (line != currLine) { currLine = line; out.println(" (line " + line + ")"); } else { out.println(); } } } } void printRangeString(Range r, int depth) { printDepth(depth); out.println(getRangeString(r, labelMap)); } String getRangeString(Range r, Map labelMap) { if (r instanceof ExceptionRange) { ExceptionRange er = (ExceptionRange) r; return er.toString() + " -> " + labelMap.get(er.getHandler()); // // + " PRI " + er.getPriority(); } else { return r.toString(); } } void printDepth(int depth) { pad(BODY_INDENT); while (depth > 0) { out.print("| "); depth--; } } void printLabel(String s, int depth) { int space = Math.max(CODE_INDENT - depth * 2, 0); if (s == null) { pad(space); } else { space = Math.max(space - (s.length() + 2), 0); pad(space); out.print(s); out.print(": "); } } void printInstruction(InstructionHandle h, int depth) { printDepth(depth); printLabel((String) labelMap.get(h), depth); Instruction inst = h.getInstruction(); if (inst instanceof CPInstruction) { CPInstruction cpinst = (CPInstruction) inst; out.print(Constants.OPCODE_NAMES[cpinst.getOpcode()].toUpperCase()); out.print(" "); out.print(pool.constantToString(pool.getConstant(cpinst.getIndex()))); } else if (inst instanceof Select) { Select sinst = (Select) inst; out.println(Constants.OPCODE_NAMES[sinst.getOpcode()].toUpperCase()); int[] matches = sinst.getMatchs(); InstructionHandle[] targets = sinst.getTargets(); InstructionHandle defaultTarget = sinst.getTarget(); for (int i = 0, len = matches.length; i < len; i++) { printDepth(depth); printLabel(null, depth); out.print(" "); out.print(matches[i]); out.print(": \t"); out.println(labelMap.get(targets[i])); } printDepth(depth); printLabel(null, depth); out.print(" "); out.print("default: \t"); out.print(labelMap.get(defaultTarget)); } else if (inst instanceof BranchInstruction) { BranchInstruction brinst = (BranchInstruction) inst; out.print(Constants.OPCODE_NAMES[brinst.getOpcode()].toUpperCase()); out.print(" "); out.print(labelMap.get(brinst.getTarget())); } else if (inst instanceof LocalVariableInstruction) { LocalVariableInstruction lvinst = (LocalVariableInstruction) inst; out.print(inst.toString(false).toUpperCase()); int index = lvinst.getIndex(); LocalVariableTag tag = getLocalVariableTag(h, index); if (tag != null) { out.print(" // "); out.print(tag.getType()); out.print(" "); out.print(tag.getName()); } } else { out.print(inst.toString(false).toUpperCase()); } } static final int BODY_INDENT = 4; static final int CODE_INDENT = 16; void pad(int size) { for (int i = 0; i < size; i++) { out.print(" "); } } } static LocalVariableTag getLocalVariableTag( InstructionHandle ih, int index) { InstructionTargeter[] targeters = ih.getTargeters(); if (targeters == null) return null; for (int i = targeters.length - 1; i >= 0; i--) { InstructionTargeter t = targeters[i]; if (t instanceof LocalVariableTag) { LocalVariableTag lvt = (LocalVariableTag) t; if (lvt.getSlot() == index) return lvt; } } return null; } static int getLineNumber( InstructionHandle ih, int prevLine) { InstructionTargeter[] targeters = ih.getTargeters(); if (targeters == null) return prevLine; for (int i = targeters.length - 1; i >= 0; i--) { InstructionTargeter t = targeters[i]; if (t instanceof LineNumberTag) { return ((LineNumberTag)t).getLineNumber(); } } return prevLine; } public boolean isStatic() { return Modifier.isStatic(getAccessFlags()); } public boolean isAbstract() { return Modifier.isAbstract(getAccessFlags()); } public boolean isBridgeMethod() { return (getAccessFlags() & Constants.ACC_BRIDGE) != 0; } public void addExceptionHandler( InstructionHandle start, InstructionHandle end, InstructionHandle handlerStart, ObjectType catchType, boolean highPriority) { InstructionHandle start1 = Range.genStart(body, start); InstructionHandle end1 = Range.genEnd(body, end); ExceptionRange er = new ExceptionRange(body, BcelWorld.fromBcel(catchType), highPriority); er.associateWithTargets(start1, end1, handlerStart); } public int getAccessFlags() { return accessFlags; } public Type[] getArgumentTypes() { initialize(); return argumentTypes; } public LazyClassGen getEnclosingClass() { return enclosingClass; } public int getMaxLocals() { return maxLocals; } public String getName() { return name; } public Type getReturnType() { initialize(); return returnType; } public void setMaxLocals(int maxLocals) { this.maxLocals = maxLocals; } public InstructionList getBody() { markAsChanged(); return body; } public boolean hasBody() { if (savedMethod != null) return savedMethod.getCode() != null; return body != null; } public Attribute[] getAttributes() { return attributes; } public String[] getDeclaredExceptions() { return declaredExceptions; } public String getClassName() { return enclosingClass.getName(); } // ---- packing! public MethodGen pack() { //killNops(); MethodGen gen = new MethodGen( getAccessFlags(), getReturnType(), getArgumentTypes(), null, //getArgumentNames(), getName(), getEnclosingClass().getName(), new InstructionList(), getEnclosingClass().getConstantPoolGen()); for (int i = 0, len = declaredExceptions.length; i < len; i++) { gen.addException(declaredExceptions[i]); } for (int i = 0, len = attributes.length; i < len; i++) { gen.addAttribute(attributes[i]); } if (newAnnotations!=null) { for (Iterator iter = newAnnotations.iterator(); iter.hasNext();) { AnnotationX element = (AnnotationX) iter.next(); gen.addAnnotation(new AnnotationGen(element.getBcelAnnotation(),gen.getConstantPool(),true)); } } if (memberView!=null && memberView.getAnnotations()!=null && memberView.getAnnotations().length!=0) { AnnotationX[] ans = memberView.getAnnotations(); for (int i = 0, len = ans.length; i < len; i++) { Annotation a= ans[i].getBcelAnnotation(); gen.addAnnotation(new AnnotationGen(a,gen.getConstantPool(),true)); } } if (isSynthetic) { ConstantPoolGen cpg = gen.getConstantPool(); int index = cpg.addUtf8("Synthetic"); gen.addAttribute(new Synthetic(index, 0, new byte[0], cpg.getConstantPool())); } if (hasBody()) { packBody(gen); gen.setMaxLocals(); gen.setMaxStack(); } else { gen.setInstructionList(null); } return gen; } public void makeSynthetic() { isSynthetic = true; } /** fill the newly created method gen with our body, * inspired by InstructionList.copy() */ public void packBody(MethodGen gen) { HashMap map = new HashMap(); InstructionList fresh = gen.getInstructionList(); /* Make copies of all instructions, append them to the new list * and associate old instruction references with the new ones, i.e., * a 1:1 mapping. */ for (InstructionHandle ih = getBody().getStart(); ih != null; ih = ih.getNext()) { if (Range.isRangeHandle(ih)) { continue; } Instruction i = ih.getInstruction(); Instruction c = Utility.copyInstruction(i); if (c instanceof BranchInstruction) map.put(ih, fresh.append((BranchInstruction) c)); else map.put(ih, fresh.append(c)); } // at this point, no rangeHandles are in fresh. Let's use that... /* Update branch targets and insert various attributes. * Insert our exceptionHandlers * into a sorted list, so they can be added in order later. */ InstructionHandle ih = getBody().getStart(); InstructionHandle jh = fresh.getStart(); LinkedList exnList = new LinkedList(); // map from localvariabletag to instruction handle Map localVariableStarts = new HashMap(); Map localVariableEnds = new HashMap(); int currLine = -1; while (ih != null) { if (map.get(ih) == null) { // we're a range instruction Range r = Range.getRange(ih); if (r instanceof ExceptionRange) { ExceptionRange er = (ExceptionRange) r; if (er.getStart() == ih) { //System.err.println("er " + er); if (!er.isEmpty()){ // order is important, insert handlers in order of start insertHandler(er, exnList); } } } else { // we must be a shadow range or something equally useless, // so forget about doing anything } // just increment ih. ih = ih.getNext(); } else { // assert map.get(ih) == jh Instruction i = ih.getInstruction(); Instruction j = jh.getInstruction(); if (i instanceof BranchInstruction) { BranchInstruction bi = (BranchInstruction) i; BranchInstruction bj = (BranchInstruction) j; InstructionHandle itarget = bi.getTarget(); // old target // try { // New target is in hash map bj.setTarget(remap(itarget, map)); // } catch (NullPointerException e) { // print(); // System.out.println("Was trying to remap " + bi); // System.out.println("who's target was supposedly " + itarget); // throw e; // } if (bi instanceof Select) { // Either LOOKUPSWITCH or TABLESWITCH InstructionHandle[] itargets = ((Select) bi).getTargets(); InstructionHandle[] jtargets = ((Select) bj).getTargets(); for (int k = itargets.length - 1; k >= 0; k--) { // Update all targets jtargets[k] = remap(itargets[k], map); jtargets[k].addTargeter(bj); } } } // now deal with line numbers // and store up info for local variables InstructionTargeter[] targeters = ih.getTargeters(); int lineNumberOffset = (fromFilename == null) ? 0 : getEnclosingClass().getSourceDebugExtensionOffset(fromFilename); if (targeters != null) { for (int k = targeters.length - 1; k >= 0; k--) { InstructionTargeter targeter = targeters[k]; if (targeter instanceof LineNumberTag) { int line = ((LineNumberTag)targeter).getLineNumber(); if (line != currLine) { gen.addLineNumber(jh, line + lineNumberOffset); currLine = line; } } else if (targeter instanceof LocalVariableTag) { LocalVariableTag lvt = (LocalVariableTag) targeter; if (localVariableStarts.get(lvt) == null) { localVariableStarts.put(lvt, jh); } localVariableEnds.put(lvt, jh); } } } // now continue ih = ih.getNext(); jh = jh.getNext(); } } // now add exception handlers for (Iterator iter = exnList.iterator(); iter.hasNext();) { ExceptionRange r = (ExceptionRange) iter.next(); if (r.isEmpty()) continue; gen.addExceptionHandler( remap(r.getRealStart(), map), remap(r.getRealEnd(), map), remap(r.getHandler(), map), (r.getCatchType() == null) ? null : (ObjectType) BcelWorld.makeBcelType(r.getCatchType())); } // now add local variables gen.removeLocalVariables(); // this next iteration _might_ be overkill, but we had problems with // bcel before with duplicate local variables. Now that we're patching // bcel we should be able to do without it if we're paranoid enough // through the rest of the compiler. Map duplicatedLocalMap = new HashMap(); List keys = new ArrayList(); keys.addAll(localVariableStarts.keySet()); for (Iterator iter = keys.iterator(); iter.hasNext(); ) { LocalVariableTag tag = (LocalVariableTag) iter.next(); // have we already added one with the same slot number and start location? // if so, just continue. InstructionHandle start = (InstructionHandle) localVariableStarts.get(tag); Set slots = (Set) duplicatedLocalMap.get(start); if (slots == null) { slots = new HashSet(); duplicatedLocalMap.put(start, slots); } if (slots.contains(new Integer(tag.getSlot()))) { // we already have a var starting at this tag with this slot continue; } slots.add(new Integer(tag.getSlot())); gen.addLocalVariable( tag.getName(), BcelWorld.makeBcelType(tag.getType()), tag.getSlot(), (InstructionHandle) localVariableStarts.get(tag), (InstructionHandle) localVariableEnds.get(tag)); } // JAVAC adds line number tables (with just one entry) to generated accessor methods - this // keeps some tools that rely on finding at least some form of linenumbertable happy. // Let's check if we have one - if we don't then let's add one. // TODO Could be made conditional on whether line debug info is being produced if (gen.getLineNumbers().length==0) { gen.addLineNumber(gen.getInstructionList().getStart(),1); } } /** This procedure should not currently be used. */ // public void killNops() { // InstructionHandle curr = body.getStart(); // while (true) { // if (curr == null) break; // InstructionHandle next = curr.getNext(); // if (curr.getInstruction() instanceof NOP) { // InstructionTargeter[] targeters = curr.getTargeters(); // if (targeters != null) { // for (int i = 0, len = targeters.length; i < len; i++) { // InstructionTargeter targeter = targeters[i]; // targeter.updateTarget(curr, next); // } // } // try { // body.delete(curr); // } catch (TargetLostException e) { // } // } // curr = next; // } // } private static InstructionHandle remap(InstructionHandle ih, Map map) { while (true) { Object ret = map.get(ih); if (ret == null) { ih = ih.getNext(); } else { return (InstructionHandle) ret; } } } // Update to all these comments, ASC 11-01-2005 // The right thing to do may be to do more with priorities as // we create new exception handlers, but that is a relatively // complex task. In the meantime, just taking account of the // priority here enables a couple of bugs to be fixed to do // with using return or break in code that contains a finally // block (pr78021,pr79554). // exception ordering. // What we should be doing is dealing with priority inversions way earlier than we are // and counting on the tree structure. In which case, the below code is in fact right. // XXX THIS COMMENT BELOW IS CURRENTLY WRONG. // An exception A preceeds an exception B in the exception table iff: // * A and B were in the original method, and A preceeded B in the original exception table // * If A has a higher priority than B, than it preceeds B. // * If A and B have the same priority, then the one whose START happens EARLIEST has LEAST priority. // in short, the outermost exception has least priority. // we implement this with a LinkedList. We could possibly implement this with a java.util.SortedSet, // but I don't trust the only implementation, TreeSet, to do the right thing. /* private */ static void insertHandler(ExceptionRange fresh, LinkedList l) { // Old implementation, simply: l.add(0,fresh); for (ListIterator iter = l.listIterator(); iter.hasNext();) { ExceptionRange r = (ExceptionRange) iter.next(); int freal = fresh.getRealStart().getPosition(); int rreal = r.getRealStart().getPosition(); if (fresh.getPriority() >= r.getPriority()) { iter.previous(); iter.add(fresh); return; } } // we have reached the end l.add(fresh); } public boolean isPrivate() { return Modifier.isPrivate(getAccessFlags()); } public boolean isProtected() { return Modifier.isProtected(getAccessFlags()); } public boolean isDefault() { return !(isProtected() || isPrivate() || isPublic()); } public boolean isPublic() { return Modifier.isPublic(getAccessFlags()); } // ---- /** A good body is a body with the following properties: * * <ul> * <li> For each branch instruction S in body, target T of S is in body. * <li> For each branch instruction S in body, target T of S has S as a targeter. * <li> For each instruction T in body, for each branch instruction S that is a * targeter of T, S is in body. * <li> For each non-range-handle instruction T in body, for each instruction S * that is a targeter of T, S is * either a branch instruction, an exception range or a tag * <li> For each range-handle instruction T in body, there is exactly one targeter S * that is a range. * <li> For each range-handle instruction T in body, the range R targeting T is in body. * <li> For each instruction T in body, for each exception range R targeting T, R is * in body. * <li> For each exception range R in body, let T := R.handler. T is in body, and R is one * of T's targeters * <li> All ranges are properly nested: For all ranges Q and R, if Q.start preceeds * R.start, then R.end preceeds Q.end. * </ul> * * Where the shorthand "R is in body" means "R.start is in body, R.end is in body, and * any InstructionHandle stored in a field of R (such as an exception handle) is in body". */ public void assertGoodBody() { if (true) return; // only enable for debugging, consider using cheaper toString() assertGoodBody(getBody(), toString()); //definingType.getNameAsIdentifier() + "." + getName()); //toString()); } public static void assertGoodBody(InstructionList il, String from) { if (true) return; // only to be enabled for debugging if (il == null) return; Set body = new HashSet(); Stack ranges = new Stack(); for (InstructionHandle ih = il.getStart(); ih != null; ih = ih.getNext()) { body.add(ih); if (ih.getInstruction() instanceof BranchInstruction) { body.add(ih.getInstruction()); } } for (InstructionHandle ih = il.getStart(); ih != null; ih = ih.getNext()) { assertGoodHandle(ih, body, ranges, from); InstructionTargeter[] ts = ih.getTargeters(); if (ts != null) { for (int i = ts.length - 1; i >= 0; i--) { assertGoodTargeter(ts[i], ih, body, from); } } } } private static void assertGoodHandle(InstructionHandle ih, Set body, Stack ranges, String from) { Instruction inst = ih.getInstruction(); if ((inst instanceof BranchInstruction) ^ (ih instanceof BranchHandle)) { throw new BCException("bad instruction/handle pair in " + from); } if (Range.isRangeHandle(ih)) { assertGoodRangeHandle(ih, body, ranges, from); } else if (inst instanceof BranchInstruction) { assertGoodBranchInstruction((BranchHandle) ih, (BranchInstruction) inst, body, ranges, from); } } private static void assertGoodBranchInstruction( BranchHandle ih, BranchInstruction inst, Set body, Stack ranges, String from) { if (ih.getTarget() != inst.getTarget()) { throw new BCException("bad branch instruction/handle pair in " + from); } InstructionHandle target = ih.getTarget(); assertInBody(target, body, from); assertTargetedBy(target, inst, from); if (inst instanceof Select) { Select sel = (Select) inst; InstructionHandle[] itargets = sel.getTargets(); for (int k = itargets.length - 1; k >= 0; k--) { assertInBody(itargets[k], body, from); assertTargetedBy(itargets[k], inst, from); } } } /** ih is an InstructionHandle or a BranchInstruction */ private static void assertInBody(Object ih, Set body, String from) { if (! body.contains(ih)) throw new BCException("thing not in body in " + from); } private static void assertGoodRangeHandle(InstructionHandle ih, Set body, Stack ranges, String from) { Range r = getRangeAndAssertExactlyOne(ih, from); assertGoodRange(r, body, from); if (r.getStart() == ih) { ranges.push(r); } else if (r.getEnd() == ih) { if (ranges.peek() != r) throw new BCException("bad range inclusion in " + from); ranges.pop(); } } private static void assertGoodRange(Range r, Set body, String from) { assertInBody(r.getStart(), body, from); assertRangeHandle(r.getStart(), from); assertTargetedBy(r.getStart(), r, from); assertInBody(r.getEnd(), body, from); assertRangeHandle(r.getEnd(), from); assertTargetedBy(r.getEnd(), r, from); if (r instanceof ExceptionRange) { ExceptionRange er = (ExceptionRange) r; assertInBody(er.getHandler(), body, from); assertTargetedBy(er.getHandler(), r, from); } } private static void assertRangeHandle(InstructionHandle ih, String from) { if (! Range.isRangeHandle(ih)) throw new BCException("bad range handle " + ih + " in " + from); } private static void assertTargetedBy( InstructionHandle target, InstructionTargeter targeter, String from) { InstructionTargeter[] ts = target.getTargeters(); if (ts == null) throw new BCException("bad targeting relationship in " + from); for (int i = ts.length - 1; i >= 0; i--) { if (ts[i] == targeter) return; } throw new RuntimeException("bad targeting relationship in " + from); } private static void assertTargets(InstructionTargeter targeter, InstructionHandle target, String from) { if (targeter instanceof Range) { Range r = (Range) targeter; if (r.getStart() == target || r.getEnd() == target) return; if (r instanceof ExceptionRange) { if (((ExceptionRange)r).getHandler() == target) return; } } else if (targeter instanceof BranchInstruction) { BranchInstruction bi = (BranchInstruction) targeter; if (bi.getTarget() == target) return; if (targeter instanceof Select) { Select sel = (Select) targeter; InstructionHandle[] itargets = sel.getTargets(); for (int k = itargets.length - 1; k >= 0; k--) { if (itargets[k] == target) return; } } } else if (targeter instanceof Tag) { return; } throw new BCException(targeter + " doesn't target " + target + " in " + from ); } private static Range getRangeAndAssertExactlyOne(InstructionHandle ih, String from) { Range ret = null; InstructionTargeter[] ts = ih.getTargeters(); if (ts == null) throw new BCException("range handle with no range in " + from); for (int i = ts.length - 1; i >= 0; i--) { if (ts[i] instanceof Range) { if (ret != null) throw new BCException("range handle with multiple ranges in " + from); ret = (Range) ts[i]; } } if (ret == null) throw new BCException("range handle with no range in " + from); return ret; } private static void assertGoodTargeter( InstructionTargeter t, InstructionHandle ih, Set body, String from) { assertTargets(t, ih, from); if (t instanceof Range) { assertGoodRange((Range) t, body, from); } else if (t instanceof BranchInstruction) { assertInBody(t, body, from); } } // ---- boolean isAdviceMethod() { return memberView.getAssociatedShadowMunger() != null; } boolean isAjSynthetic() { if (memberView == null) return true; return memberView.isAjSynthetic(); } public ISourceLocation getSourceLocation() { if (memberView!=null) return memberView.getSourceLocation(); return null; } public AjAttribute.EffectiveSignatureAttribute getEffectiveSignature() { //if (memberView == null) return null; if (effectiveSignature != null) return effectiveSignature; return memberView.getEffectiveSignature(); } public void setEffectiveSignature(ResolvedMember member, Shadow.Kind kind, boolean shouldWeave) { this.effectiveSignature = new AjAttribute.EffectiveSignatureAttribute(member,kind,shouldWeave); } public String getSignature() { if (memberView!=null) return memberView.getSignature(); return MemberImpl.typesToSignature(BcelWorld.fromBcel(getReturnType()), BcelWorld.fromBcel(getArgumentTypes()),false); } public String getParameterSignature() { if (memberView!=null) return memberView.getParameterSignature(); return MemberImpl.typesToSignature(BcelWorld.fromBcel(getArgumentTypes())); } public BcelMethod getMemberView() { return memberView; } public void forcePublic() { markAsChanged(); accessFlags = Utility.makePublic(accessFlags); } public boolean getCanInline() { return canInline; } public void setCanInline(boolean canInline) { this.canInline = canInline; } /** * Adds an attribute to the method * @param attr */ public void addAttribute(Attribute attr) { Attribute[] newAttributes = new Attribute[attributes.length + 1]; System.arraycopy(attributes, 0, newAttributes, 0, attributes.length); newAttributes[attributes.length] = attr; attributes = newAttributes; } }
108,062
Bug 108062 NPE when opening resources from CVS resources history
NPE when opening resources (double-click) from CVS resources history view. java.lang.NullPointerException at org.eclipse.mylar.java.ui.editor.MylarJavaElementDescriptor.drawCompositeImage(MylarJavaElementDescriptor.java:40) at org.eclipse.jface.resource.CompositeImageDescriptor.getImageData(CompositeImageDescriptor.java:205) at org.eclipse.jface.resource.ImageDescriptor.createImage(ImageDescriptor.java:279) at org.eclipse.jface.resource.ImageDescriptor.createImage(ImageDescriptor.java:233) at org.eclipse.jface.resource.ImageDescriptor.createImage(ImageDescriptor.java:211) at org.eclipse.mylar.ui.MylarImages.getImage(MylarImages.java:108) at org.eclipse.mylar.java.ui.editor.MylarCompilationUnitEditor.updatedTitleImage(MylarCompilationUnitEditor.java:55) at org.eclipse.jdt.internal.ui.javaeditor.JavaEditorErrorTickUpdater$1.run(JavaEditorErrorTickUpdater.java:86) at org.eclipse.swt.widgets.Synchronizer.syncExec(Synchronizer.java:152) at org.eclipse.ui.internal.UISynchronizer.syncExec(UISynchronizer.java:28) at org.eclipse.swt.widgets.Display.syncExec(Display.java:3413) at org.eclipse.jdt.internal.ui.javaeditor.JavaEditorErrorTickUpdater.postImageChange(JavaEditorErrorTickUpdater.java:84) at org.eclipse.jdt.internal.ui.javaeditor.JavaEditorErrorTickUpdater.updateEditorImage(JavaEditorErrorTickUpdater.java:77) at org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor.doSetInput(CompilationUnitEditor.java:1548) at org.eclipse.ui.texteditor.AbstractTextEditor$16.run(AbstractTextEditor.java:2360) at org.eclipse.jface.operation.ModalContext.runInCurrentThread(ModalContext.java:346) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:291) at org.eclipse.jface.window.ApplicationWindow$1.run(ApplicationWindow.java:624) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:69) at org.eclipse.jface.window.ApplicationWindow.run(ApplicationWindow.java:621) at org.eclipse.ui.internal.WorkbenchWindow.run(WorkbenchWindow.java:2135) at org.eclipse.ui.texteditor.AbstractTextEditor.internalInit(AbstractTextEditor.java:2378) at org.eclipse.ui.texteditor.AbstractTextEditor.init(AbstractTextEditor.java:2405) at org.eclipse.ui.internal.EditorManager.createSite(EditorManager.java:773) at org.eclipse.ui.internal.EditorReference.createPartHelper(EditorReference.java:572) at org.eclipse.ui.internal.EditorReference.createPart(EditorReference.java:365) at org.eclipse.ui.internal.WorkbenchPartReference.getPart(WorkbenchPartReference.java:552) at org.eclipse.ui.internal.EditorReference.getEditor(EditorReference.java:214) at org.eclipse.ui.internal.WorkbenchPage.busyOpenEditorBatched(WorkbenchPage.java:2325) at org.eclipse.ui.internal.WorkbenchPage.busyOpenEditor(WorkbenchPage.java:2258) at org.eclipse.ui.internal.WorkbenchPage.access$9(WorkbenchPage.java:2250) at org.eclipse.ui.internal.WorkbenchPage$9.run(WorkbenchPage.java:2236) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:69) at org.eclipse.ui.internal.WorkbenchPage.openEditor(WorkbenchPage.java:2231) at org.eclipse.ui.internal.WorkbenchPage.openEditor(WorkbenchPage.java:2204) at org.eclipse.team.internal.ccvs.ui.actions.OpenLogEntryAction$1.run(OpenLogEntryAction.java:85) at org.eclipse.team.internal.ccvs.ui.repo.RepositoryManager.run(RepositoryManager.java:651) at org.eclipse.team.internal.ccvs.ui.actions.CVSAction$2.run(CVSAction.java:347) at org.eclipse.team.internal.ccvs.ui.actions.CVSAction$3.run(CVSAction.java:356) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:69) at org.eclipse.team.internal.ccvs.ui.actions.CVSAction.run(CVSAction.java:353) at org.eclipse.team.internal.ccvs.ui.actions.OpenLogEntryAction.execute(OpenLogEntryAction.java:64) at org.eclipse.team.internal.ccvs.ui.actions.CVSAction.run(CVSAction.java:117) at org.eclipse.team.internal.ccvs.ui.HistoryView$6.handleEvent(HistoryView.java:199) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:66) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:843) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:3080) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:2713) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1699) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1663) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:367) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:143) at org.eclipse.ui.internal.ide.IDEApplication.run(IDEApplication.java:103) at org.eclipse.core.internal.runtime.PlatformActivator$1.run(PlatformActivator.java:226) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:376) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:163) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:585) at org.eclipse.core.launcher.Main.invokeFramework(Main.java:334) at org.eclipse.core.launcher.Main.basicRun(Main.java:278) at org.eclipse.core.launcher.Main.run(Main.java:973) at org.eclipse.core.launcher.Main.main(Main.java:948)
resolved fixed
ad753aa
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-02T09:35:02Z
2005-08-25T22:46:40Z
bcel-builder/src/org/aspectj/apache/bcel/classfile/GenericSignatureParser.java
/* ******************************************************************* * Copyright (c) 2005 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * Adrian Colyer Initial implementation * ******************************************************************/ package org.aspectj.apache.bcel.classfile; import java.util.ArrayList; import java.util.List; import org.aspectj.apache.bcel.classfile.Signature.ArrayTypeSignature; import org.aspectj.apache.bcel.classfile.Signature.ClassTypeSignature; import org.aspectj.apache.bcel.classfile.Signature.FieldTypeSignature; import org.aspectj.apache.bcel.classfile.Signature.FormalTypeParameter; import org.aspectj.apache.bcel.classfile.Signature.MethodTypeSignature; import org.aspectj.apache.bcel.classfile.Signature.SimpleClassTypeSignature; import org.aspectj.apache.bcel.classfile.Signature.TypeArgument; import org.aspectj.apache.bcel.classfile.Signature.TypeSignature; import org.aspectj.apache.bcel.classfile.Signature.TypeVariableSignature; import org.aspectj.apache.bcel.classfile.Signature.BaseTypeSignature; /** * Parses the generic signature attribute as defined in the JVM spec. */ public class GenericSignatureParser { private String inputString; private String[] tokenStream; // for parse in flight private int tokenIndex = 0; /** * AMC. * Parse the signature string interpreting it as a ClassSignature according to * the grammar defined in Section 4.4.4 of the JVM specification. */ public Signature.ClassSignature parseAsClassSignature(String sig) { this.inputString = sig; tokenStream = tokenize(sig); tokenIndex = 0; Signature.ClassSignature classSig = new Signature.ClassSignature(); // FormalTypeParameters-opt if (maybeEat("<")) { List formalTypeParametersList = new ArrayList(); do { formalTypeParametersList.add(parseFormalTypeParameter()); } while (!maybeEat(">")); classSig.formalTypeParameters = new FormalTypeParameter[formalTypeParametersList.size()]; formalTypeParametersList.toArray(classSig.formalTypeParameters); } classSig.superclassSignature = parseClassTypeSignature(); List superIntSigs = new ArrayList(); while (tokenIndex < tokenStream.length) { superIntSigs.add(parseClassTypeSignature()); } classSig.superInterfaceSignatures = new ClassTypeSignature[superIntSigs.size()]; superIntSigs.toArray(classSig.superInterfaceSignatures); return classSig; } /** * AMC. * Parse the signature string interpreting it as a MethodTypeSignature according to * the grammar defined in Section 4.4.4 of the JVM specification. */ public MethodTypeSignature parseAsMethodSignature(String sig) { this.inputString = sig; tokenStream = tokenize(sig); tokenIndex = 0; FormalTypeParameter[] formals = new FormalTypeParameter[0]; TypeSignature[] params = new TypeSignature[0]; TypeSignature returnType = null; FieldTypeSignature[] throwsSigs = new FieldTypeSignature[0]; // FormalTypeParameters-opt if (maybeEat("<")) { List formalTypeParametersList = new ArrayList(); do { formalTypeParametersList.add(parseFormalTypeParameter()); } while (!maybeEat(">")); formals = new FormalTypeParameter[formalTypeParametersList.size()]; formalTypeParametersList.toArray(formals); } // Parameters eat("("); List paramList = new ArrayList(); while(!maybeEat(")")) { FieldTypeSignature fsig = parseFieldTypeSignature(true); if (fsig != null) { paramList.add(fsig); } else { paramList.add(new Signature.BaseTypeSignature(eatIdentifier())); } } params = new TypeSignature[paramList.size()]; paramList.toArray(params); // return type returnType = parseFieldTypeSignature(true); if (returnType == null) returnType = new Signature.BaseTypeSignature(eatIdentifier()); // throws List throwsList = new ArrayList(); while (maybeEat("^")) { FieldTypeSignature fsig = parseFieldTypeSignature(false); throwsList.add(fsig); } throwsSigs = new FieldTypeSignature[throwsList.size()]; throwsList.toArray(throwsSigs); return new Signature.MethodTypeSignature(formals,params,returnType,throwsSigs); } /** * AMC. * Parse the signature string interpreting it as a FieldTypeSignature according to * the grammar defined in Section 4.4.4 of the JVM specification. */ public FieldTypeSignature parseAsFieldSignature(String sig) { this.inputString = sig; tokenStream = tokenize(sig); tokenIndex = 0; return parseFieldTypeSignature(false); } private FormalTypeParameter parseFormalTypeParameter() { FormalTypeParameter ftp = new FormalTypeParameter(); // Identifier ftp.identifier = eatIdentifier(); // ClassBound eat(":"); ftp.classBound = parseFieldTypeSignature(true); if (ftp.classBound == null) { ftp.classBound = new ClassTypeSignature("Ljava/lang/Object;","Ljava/lang/Object"); } // Optional InterfaceBounds List optionalBounds = new ArrayList(); while (maybeEat(":")) { optionalBounds.add(parseFieldTypeSignature(false)); } ftp.interfaceBounds = new FieldTypeSignature[optionalBounds.size()]; optionalBounds.toArray(ftp.interfaceBounds); return ftp; } private FieldTypeSignature parseFieldTypeSignature(boolean isOptional) { if (isOptional) { // anything other than 'L', 'T' or '[' and we're out of here if (!tokenStream[tokenIndex].startsWith("L") && !tokenStream[tokenIndex].startsWith("T") && !tokenStream[tokenIndex].startsWith("[")) { return null; } } if (maybeEat("[")) { return parseArrayTypeSignature(); } else if (tokenStream[tokenIndex].startsWith("L")) { return parseClassTypeSignature(); } else if (tokenStream[tokenIndex].startsWith("T")) { return parseTypeVariableSignature(); } else { throw new IllegalStateException("Expecting [,L, or T, but found " + tokenStream[tokenIndex] + " while unpacking " + inputString); } } private ArrayTypeSignature parseArrayTypeSignature() { // opening [ already eaten FieldTypeSignature fieldType = parseFieldTypeSignature(true); if (fieldType != null) { return new ArrayTypeSignature(fieldType); } else { // must be BaseType array return new ArrayTypeSignature(new BaseTypeSignature(eatIdentifier())); } } // L PackageSpecifier* SimpleClassTypeSignature ClassTypeSignature* ; private ClassTypeSignature parseClassTypeSignature() { SimpleClassTypeSignature outerType = null; SimpleClassTypeSignature[] nestedTypes = new SimpleClassTypeSignature[0]; StringBuffer ret = new StringBuffer(); String identifier = eatIdentifier(); ret.append(identifier); while (maybeEat("/")) { ret.append("/"); // dont forget this... ret.append(eatIdentifier()); } identifier = ret.toString(); // now we have either a "." indicating the start of a nested type, // or a "<" indication type arguments, or ";" and we are done. while (!maybeEat(";")) { if (maybeEat(".")) { // outer type completed outerType = new SimpleClassTypeSignature(identifier); List nestedTypeList = new ArrayList(); do { ret.append("."); SimpleClassTypeSignature sig = parseSimpleClassTypeSignature(); ret.append(sig.toString()); nestedTypeList.add(sig); } while(maybeEat(".")); nestedTypes = new SimpleClassTypeSignature[nestedTypeList.size()]; nestedTypeList.toArray(nestedTypes); } else if (tokenStream[tokenIndex].equals("<")) { ret.append("<"); TypeArgument[] tArgs = maybeParseTypeArguments(); for (int i=0; i < tArgs.length; i++) { ret.append(tArgs[i].toString()); } ret.append(">"); outerType = new SimpleClassTypeSignature(identifier,tArgs); // now parse possible nesteds... List nestedTypeList = new ArrayList(); while (maybeEat(".")) { ret.append("."); SimpleClassTypeSignature sig = parseSimpleClassTypeSignature(); ret.append(sig.toString()); nestedTypeList.add(sig); } nestedTypes = new SimpleClassTypeSignature[nestedTypeList.size()]; nestedTypeList.toArray(nestedTypes); } else { throw new IllegalStateException("Expecting .,<, or ;, but found " + tokenStream[tokenIndex] + " while unpacking " + inputString); } } ret.append(";"); if (outerType == null) outerType = new SimpleClassTypeSignature(ret.toString()); return new ClassTypeSignature(ret.toString(),outerType,nestedTypes); } private SimpleClassTypeSignature parseSimpleClassTypeSignature() { String identifier = eatIdentifier(); TypeArgument[] tArgs = maybeParseTypeArguments(); if (tArgs != null) { return new SimpleClassTypeSignature(identifier,tArgs); } else { return new SimpleClassTypeSignature(identifier); } } private TypeArgument parseTypeArgument() { boolean isPlus = false; boolean isMinus = false; if (maybeEat("*")) { return new TypeArgument(); } else if (maybeEat("+")) { isPlus = true; } else if (maybeEat("-")) { isMinus = true; } FieldTypeSignature sig = parseFieldTypeSignature(false); return new TypeArgument(isPlus,isMinus,sig); } private TypeArgument[] maybeParseTypeArguments() { if (maybeEat("<")) { List typeArgs = new ArrayList(); do { TypeArgument arg = parseTypeArgument(); typeArgs.add(arg); } while(!maybeEat(">")); TypeArgument[] tArgs = new TypeArgument[typeArgs.size()]; typeArgs.toArray(tArgs); return tArgs; } else { return null; } } private TypeVariableSignature parseTypeVariableSignature() { TypeVariableSignature tv = new TypeVariableSignature(eatIdentifier()); eat(";"); return tv; } private boolean maybeEat(String token) { if (tokenStream.length <= tokenIndex) return false; if (tokenStream[tokenIndex].equals(token)) { tokenIndex++; return true; } return false; } private void eat(String token) { if (!tokenStream[tokenIndex].equals(token)) { throw new IllegalStateException("Expecting " + token + " but found " + tokenStream[tokenIndex] + " while unpacking " + inputString); } tokenIndex++; } private String eatIdentifier() { return tokenStream[tokenIndex++]; } /** * non-private for test visibility * Splits a string containing a generic signature into tokens for consumption * by the parser. */ public String[] tokenize(String signatureString) { char[] chars = signatureString.toCharArray(); int index = 0; List tokens = new ArrayList(); StringBuffer identifier = new StringBuffer(); boolean inParens = false; boolean inArray = false; boolean couldSeePrimitive = false; do { switch (chars[index]) { case '<' : if (identifier.length() > 0) tokens.add(identifier.toString()); identifier = new StringBuffer(); tokens.add("<"); break; case '>' : if (identifier.length() > 0) tokens.add(identifier.toString()); identifier = new StringBuffer(); tokens.add(">"); break; case ':' : if (identifier.length() > 0) tokens.add(identifier.toString()); identifier = new StringBuffer(); tokens.add(":"); break; case '/' : if (identifier.length() > 0) tokens.add(identifier.toString()); identifier = new StringBuffer(); tokens.add("/"); couldSeePrimitive = false; break; case ';' : if (identifier.length() > 0) tokens.add(identifier.toString()); identifier = new StringBuffer(); tokens.add(";"); couldSeePrimitive = true; inArray = false; break; case '^': if (identifier.length() > 0) tokens.add(identifier.toString()); identifier = new StringBuffer(); tokens.add("^"); break; case '+': tokens.add("+"); break; case '-': tokens.add("-"); break; case '*': tokens.add("*"); break; case '.' : if (identifier.length() > 0) tokens.add(identifier.toString()); identifier = new StringBuffer(); tokens.add("."); break; case '(' : tokens.add("("); inParens = true; couldSeePrimitive = true; break; case ')' : tokens.add(")"); inParens = false; break; case '[' : tokens.add("["); couldSeePrimitive = true; inArray = true; break; case 'B' : case 'C' : case 'D' : case 'F' : case 'I' : case 'J' : case 'S' : case 'V' : case 'Z' : if ((inParens || inArray) && couldSeePrimitive && identifier.length() == 0) { tokens.add(new String("" + chars[index])); } else { identifier.append(chars[index]); } couldSeePrimitive = false; inArray = false; break; default : identifier.append(chars[index]); } } while((++index) < chars.length); if (identifier.length() > 0) tokens.add(identifier.toString()); String [] tokenArray = new String[tokens.size()]; tokens.toArray(tokenArray); return tokenArray; } }
108,062
Bug 108062 NPE when opening resources from CVS resources history
NPE when opening resources (double-click) from CVS resources history view. java.lang.NullPointerException at org.eclipse.mylar.java.ui.editor.MylarJavaElementDescriptor.drawCompositeImage(MylarJavaElementDescriptor.java:40) at org.eclipse.jface.resource.CompositeImageDescriptor.getImageData(CompositeImageDescriptor.java:205) at org.eclipse.jface.resource.ImageDescriptor.createImage(ImageDescriptor.java:279) at org.eclipse.jface.resource.ImageDescriptor.createImage(ImageDescriptor.java:233) at org.eclipse.jface.resource.ImageDescriptor.createImage(ImageDescriptor.java:211) at org.eclipse.mylar.ui.MylarImages.getImage(MylarImages.java:108) at org.eclipse.mylar.java.ui.editor.MylarCompilationUnitEditor.updatedTitleImage(MylarCompilationUnitEditor.java:55) at org.eclipse.jdt.internal.ui.javaeditor.JavaEditorErrorTickUpdater$1.run(JavaEditorErrorTickUpdater.java:86) at org.eclipse.swt.widgets.Synchronizer.syncExec(Synchronizer.java:152) at org.eclipse.ui.internal.UISynchronizer.syncExec(UISynchronizer.java:28) at org.eclipse.swt.widgets.Display.syncExec(Display.java:3413) at org.eclipse.jdt.internal.ui.javaeditor.JavaEditorErrorTickUpdater.postImageChange(JavaEditorErrorTickUpdater.java:84) at org.eclipse.jdt.internal.ui.javaeditor.JavaEditorErrorTickUpdater.updateEditorImage(JavaEditorErrorTickUpdater.java:77) at org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor.doSetInput(CompilationUnitEditor.java:1548) at org.eclipse.ui.texteditor.AbstractTextEditor$16.run(AbstractTextEditor.java:2360) at org.eclipse.jface.operation.ModalContext.runInCurrentThread(ModalContext.java:346) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:291) at org.eclipse.jface.window.ApplicationWindow$1.run(ApplicationWindow.java:624) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:69) at org.eclipse.jface.window.ApplicationWindow.run(ApplicationWindow.java:621) at org.eclipse.ui.internal.WorkbenchWindow.run(WorkbenchWindow.java:2135) at org.eclipse.ui.texteditor.AbstractTextEditor.internalInit(AbstractTextEditor.java:2378) at org.eclipse.ui.texteditor.AbstractTextEditor.init(AbstractTextEditor.java:2405) at org.eclipse.ui.internal.EditorManager.createSite(EditorManager.java:773) at org.eclipse.ui.internal.EditorReference.createPartHelper(EditorReference.java:572) at org.eclipse.ui.internal.EditorReference.createPart(EditorReference.java:365) at org.eclipse.ui.internal.WorkbenchPartReference.getPart(WorkbenchPartReference.java:552) at org.eclipse.ui.internal.EditorReference.getEditor(EditorReference.java:214) at org.eclipse.ui.internal.WorkbenchPage.busyOpenEditorBatched(WorkbenchPage.java:2325) at org.eclipse.ui.internal.WorkbenchPage.busyOpenEditor(WorkbenchPage.java:2258) at org.eclipse.ui.internal.WorkbenchPage.access$9(WorkbenchPage.java:2250) at org.eclipse.ui.internal.WorkbenchPage$9.run(WorkbenchPage.java:2236) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:69) at org.eclipse.ui.internal.WorkbenchPage.openEditor(WorkbenchPage.java:2231) at org.eclipse.ui.internal.WorkbenchPage.openEditor(WorkbenchPage.java:2204) at org.eclipse.team.internal.ccvs.ui.actions.OpenLogEntryAction$1.run(OpenLogEntryAction.java:85) at org.eclipse.team.internal.ccvs.ui.repo.RepositoryManager.run(RepositoryManager.java:651) at org.eclipse.team.internal.ccvs.ui.actions.CVSAction$2.run(CVSAction.java:347) at org.eclipse.team.internal.ccvs.ui.actions.CVSAction$3.run(CVSAction.java:356) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:69) at org.eclipse.team.internal.ccvs.ui.actions.CVSAction.run(CVSAction.java:353) at org.eclipse.team.internal.ccvs.ui.actions.OpenLogEntryAction.execute(OpenLogEntryAction.java:64) at org.eclipse.team.internal.ccvs.ui.actions.CVSAction.run(CVSAction.java:117) at org.eclipse.team.internal.ccvs.ui.HistoryView$6.handleEvent(HistoryView.java:199) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:66) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:843) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:3080) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:2713) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1699) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1663) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:367) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:143) at org.eclipse.ui.internal.ide.IDEApplication.run(IDEApplication.java:103) at org.eclipse.core.internal.runtime.PlatformActivator$1.run(PlatformActivator.java:226) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:376) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:163) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:585) at org.eclipse.core.launcher.Main.invokeFramework(Main.java:334) at org.eclipse.core.launcher.Main.basicRun(Main.java:278) at org.eclipse.core.launcher.Main.run(Main.java:973) at org.eclipse.core.launcher.Main.main(Main.java:948)
resolved fixed
ad753aa
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-02T09:35:02Z
2005-08-25T22:46:40Z
tests/bugs150/pr108602.java
108,062
Bug 108062 NPE when opening resources from CVS resources history
NPE when opening resources (double-click) from CVS resources history view. java.lang.NullPointerException at org.eclipse.mylar.java.ui.editor.MylarJavaElementDescriptor.drawCompositeImage(MylarJavaElementDescriptor.java:40) at org.eclipse.jface.resource.CompositeImageDescriptor.getImageData(CompositeImageDescriptor.java:205) at org.eclipse.jface.resource.ImageDescriptor.createImage(ImageDescriptor.java:279) at org.eclipse.jface.resource.ImageDescriptor.createImage(ImageDescriptor.java:233) at org.eclipse.jface.resource.ImageDescriptor.createImage(ImageDescriptor.java:211) at org.eclipse.mylar.ui.MylarImages.getImage(MylarImages.java:108) at org.eclipse.mylar.java.ui.editor.MylarCompilationUnitEditor.updatedTitleImage(MylarCompilationUnitEditor.java:55) at org.eclipse.jdt.internal.ui.javaeditor.JavaEditorErrorTickUpdater$1.run(JavaEditorErrorTickUpdater.java:86) at org.eclipse.swt.widgets.Synchronizer.syncExec(Synchronizer.java:152) at org.eclipse.ui.internal.UISynchronizer.syncExec(UISynchronizer.java:28) at org.eclipse.swt.widgets.Display.syncExec(Display.java:3413) at org.eclipse.jdt.internal.ui.javaeditor.JavaEditorErrorTickUpdater.postImageChange(JavaEditorErrorTickUpdater.java:84) at org.eclipse.jdt.internal.ui.javaeditor.JavaEditorErrorTickUpdater.updateEditorImage(JavaEditorErrorTickUpdater.java:77) at org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor.doSetInput(CompilationUnitEditor.java:1548) at org.eclipse.ui.texteditor.AbstractTextEditor$16.run(AbstractTextEditor.java:2360) at org.eclipse.jface.operation.ModalContext.runInCurrentThread(ModalContext.java:346) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:291) at org.eclipse.jface.window.ApplicationWindow$1.run(ApplicationWindow.java:624) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:69) at org.eclipse.jface.window.ApplicationWindow.run(ApplicationWindow.java:621) at org.eclipse.ui.internal.WorkbenchWindow.run(WorkbenchWindow.java:2135) at org.eclipse.ui.texteditor.AbstractTextEditor.internalInit(AbstractTextEditor.java:2378) at org.eclipse.ui.texteditor.AbstractTextEditor.init(AbstractTextEditor.java:2405) at org.eclipse.ui.internal.EditorManager.createSite(EditorManager.java:773) at org.eclipse.ui.internal.EditorReference.createPartHelper(EditorReference.java:572) at org.eclipse.ui.internal.EditorReference.createPart(EditorReference.java:365) at org.eclipse.ui.internal.WorkbenchPartReference.getPart(WorkbenchPartReference.java:552) at org.eclipse.ui.internal.EditorReference.getEditor(EditorReference.java:214) at org.eclipse.ui.internal.WorkbenchPage.busyOpenEditorBatched(WorkbenchPage.java:2325) at org.eclipse.ui.internal.WorkbenchPage.busyOpenEditor(WorkbenchPage.java:2258) at org.eclipse.ui.internal.WorkbenchPage.access$9(WorkbenchPage.java:2250) at org.eclipse.ui.internal.WorkbenchPage$9.run(WorkbenchPage.java:2236) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:69) at org.eclipse.ui.internal.WorkbenchPage.openEditor(WorkbenchPage.java:2231) at org.eclipse.ui.internal.WorkbenchPage.openEditor(WorkbenchPage.java:2204) at org.eclipse.team.internal.ccvs.ui.actions.OpenLogEntryAction$1.run(OpenLogEntryAction.java:85) at org.eclipse.team.internal.ccvs.ui.repo.RepositoryManager.run(RepositoryManager.java:651) at org.eclipse.team.internal.ccvs.ui.actions.CVSAction$2.run(CVSAction.java:347) at org.eclipse.team.internal.ccvs.ui.actions.CVSAction$3.run(CVSAction.java:356) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:69) at org.eclipse.team.internal.ccvs.ui.actions.CVSAction.run(CVSAction.java:353) at org.eclipse.team.internal.ccvs.ui.actions.OpenLogEntryAction.execute(OpenLogEntryAction.java:64) at org.eclipse.team.internal.ccvs.ui.actions.CVSAction.run(CVSAction.java:117) at org.eclipse.team.internal.ccvs.ui.HistoryView$6.handleEvent(HistoryView.java:199) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:66) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:843) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:3080) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:2713) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1699) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1663) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:367) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:143) at org.eclipse.ui.internal.ide.IDEApplication.run(IDEApplication.java:103) at org.eclipse.core.internal.runtime.PlatformActivator$1.run(PlatformActivator.java:226) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:376) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:163) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:585) at org.eclipse.core.launcher.Main.invokeFramework(Main.java:334) at org.eclipse.core.launcher.Main.basicRun(Main.java:278) at org.eclipse.core.launcher.Main.run(Main.java:973) at org.eclipse.core.launcher.Main.main(Main.java:948)
resolved fixed
ad753aa
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-02T09:35:02Z
2005-08-25T22:46:40Z
tests/src/org/aspectj/systemtest/ajc150/Ajc150Tests.java
/******************************************************************************* * Copyright (c) 2004 IBM * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Andy Clement - initial API and implementation *******************************************************************************/ package org.aspectj.systemtest.ajc150; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import junit.framework.Test; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.apache.bcel.classfile.Method; import org.aspectj.apache.bcel.util.ClassPath; import org.aspectj.apache.bcel.util.SyntheticRepository; import org.aspectj.asm.AsmManager; import org.aspectj.testing.XMLBasedAjcTestCase; import org.aspectj.util.LangUtil; /** * These are tests that will run on Java 1.4 and use the old harness format for test specification. */ public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase { public static Test suite() { return XMLBasedAjcTestCase.loadSuite(Ajc150Tests.class); } protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml"); } public void test_typeProcessingOrderWhenDeclareParents() { runTest("Order of types passed to compiler determines weaving behavior"); } public void test_aroundMethod() { runTest("method called around in class"); } public void test_aroundMethodAspect() { runTest("method called around in aspect"); } public void test_ambiguousBindingsDetection() { runTest("Various kinds of ambiguous bindings"); } public void test_ambiguousArgsDetection() { runTest("ambiguous args"); } public void testIncorrectExceptionTableWhenBreakInMethod_pr78021() { runTest("Injecting exception into while loop with break statement causes catch block to be ignored"); } public void testIncorrectExceptionTableWhenReturnInMethod_pr79554() { runTest("Return in try-block disables catch-block if final-block is present"); } public void testMissingDebugInfoForGeneratedMethods_pr82570() throws ClassNotFoundException { runTest("Weaved code does not include debug lines"); boolean f = false; JavaClass jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1"); Method[] meths = jc.getMethods(); for (int i = 0; i < meths.length; i++) { Method method = meths[i]; if (f) System.err.println("Line number table for "+method.getName()+method.getSignature()+" = "+method.getLineNumberTable()); assertTrue("Didn't find a line number table for method "+method.getName()+method.getSignature(), method.getLineNumberTable()!=null); } // This test would determine the info isn't there if you pass -g:none ... // cR = ajc(baseDir,new String[]{"PR82570_1.java","-g:none"}); // assertTrue("Expected no compile problem:"+cR,!cR.hasErrorMessages()); // System.err.println(cR.getStandardError()); // jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1"); // meths = jc.getMethods(); // for (int i = 0; i < meths.length; i++) { // Method method = meths[i]; // assertTrue("Found a line number table for method "+method.getName(), // method.getLineNumberTable()==null); // } } public void testCanOverrideProtectedMethodsViaITDandDecp_pr83303() { runTest("compiler error when mixing inheritance, overriding and polymorphism"); } public void testPerTypeWithinMissesNamedInnerTypes() { runTest("pertypewithin() handing of inner classes (1)"); } public void testPerTypeWithinMissesAnonymousInnerTypes() { runTest("pertypewithin() handing of inner classes (2)"); } public void testPerTypeWithinIncorrectlyMatchingInterfaces() { runTest("pertypewithin({interface}) illegal field modifier"); } public void test051_arrayCloningInJava5() { runTest("AJC possible bug with static nested classes"); } public void testBadASMforEnums() throws IOException { runTest("bad asm for enums"); if (LangUtil.is15VMOrGreater()) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintWriter pw = new PrintWriter(baos); AsmManager.dumptree(pw,AsmManager.getDefault().getHierarchy().getRoot(),0); pw.flush(); String tree = baos.toString(); assertTrue("Expected 'Red [enumvalue]' somewhere in here:"+tree,tree.indexOf("Red [enumvalue]")!=-1); } } public void npeOnTypeNotFound() { runTest("structure model npe on type not found"); } public void testNoRuntimeExceptionSoftening() { runTest("declare soft of runtime exception"); } public void testRuntimeNoSoftenWithHandler() { runTest("declare soft w. catch block"); } public void testSyntaxError() { runTest("invalid cons syntax"); } public void testVarargsInConsBug() { runTest("varargs in constructor sig"); } public void testAspectpathdirs() { runTest("dirs on aspectpath"); } public void testIntroSample() { runTest("introduction sample"); } public void testPTWInterface() { runTest("pertypewithin({interface}) illegal field modifier"); } public void testEnumCalledEnumEtc() { runTest("enum called Enum, annotation called Annotation, etc"); } public void testInternalCompilerError_pr86832() { runTest("Internal compiler error"); } public void testCloneMethod_pr83311() { runTest("overriding/polymorphism error on interface method introduction"); } /** * IfPointcut.findResidueInternal() was modified to make this test complete in a short amount * of time - if you see it hanging, someone has messed with the optimization. */ public void testIfEvaluationExplosion_pr94086() { runTest("Exploding compile time with if() statements in pointcut"); } public void testReflectNPE_pr94167() {runTest("NPE in reflect implementation");} public void testStaticImports_pr84260() {runTest("static import failures");} public void testGenerics_pr99089() {runTest("ArrayIndexOutOfBoundsException - Generics in privileged aspects");} public void testGenerics_pr95993() {runTest("NPE at ClassScope.java:660 when compiling generic class");} public void testItdGenerics_pr99228() {runTest("ITD of a field into a generic class");} public void testItdGenerics_pr98320() {runTest("intertype with nested generic type");} public void testItdGenerics_pr100227() {runTest("inner class with generic enclosing class");} public void testItdGenerics_pr100260() {runTest("methods inherited from a generic parent");} public void testSyntaxErrorNPE_pr103266() {runTest("NPE on syntax error");} public void testIllegalStateExceptionOnNestedParameterizedType_pr106634() { runTest("IllegalStateException unpacking signature of nested parameterized type"); } public void testParseErrorOnAnnotationStarPlusPattern() { runTest("(@Foo *)+ type pattern parse error"); } public void test_pr106130_tooManyLocals() { runTest("test weaving with > 256 locals"); } public void testMissingNamePattern_pr106461() { runTest("missing name pattern"); } public void testMissingNamePattern_pr107059() { runTest("parser crashes on call(void (@a *)(..)"); } public void testIntermediateAnnotationMatching() { runTest("intermediate annotation matching"); } public void testBadRuntimeTestGeneration() { runTest("target(@Foo *)"); } public void testErrorMessageOnITDWithTypePatterns() { runTest("clear error message on itd with type pattern"); } public void testAjKeywordsAsIdentifiers() { runTest("before and after are valid identifiers in classes"); } public void testAjKeywordsAsIdentifiers2() { runTest("before and after are valid identifiers in classes, part 2"); } public void testNoBeforeReturningAdvice() { runTest("before returning advice not allowed!"); } public void testDetectVoidFieldType() { runTest("void field type in pointcut expression"); } public void testPointcutOverriding() { runTest("overriding final pointcut from super-aspect"); } public void testAtSuppressWarnings() { runTest("@SuppressWarnings should suppress"); } public void testDEOWWithBindingPointcut() { runTest("declare warning : foo(str) : ...;"); } public void testAroundAdviceAndInterfaceInitializer() { runTest("around advice on interface initializer"); } public void testGoodErrorMessageOnUnmatchedMemberSyntax() { runTest("good error message for unmatched member syntax"); } public void testITDWithNoExceptionAndIntermediary() { runTest("itd override with no exception clause"); } public void testAnonymousInnerClasses() { runTest("anonymous inner classes"); } public void testMultipleAnonymousInnerClasses() { runTest("multiple anonymous inner classes"); } public void testPrivilegedMethodAccessorsGetRightExceptions_pr82989() { runTest("Compiler error due to a wrong exception check in try blocks"); } public void testAnonymousInnerClassWithMethodReturningTypeParameter_pr107898() { runTest("anonymous inner class with method returning type parameter"); } public void testMatchingOfObjectArray() { runTest("matching against Object[]"); } public void testMultipleAnonymousInnerClasses_pr108104() { runTest("multiple anonymous inner classes 2"); } public void testSignatureMatchingInMultipleOverrideScenario() { runTest("signature matching in override scenario"); } public void testWildcardAnnotationMatching_pr108245() { runTest("wildcard annotation matching - pr108245"); } public void testInnerTypesAndTypeVariables() { runTest("inner types and type variables"); } public void testAtAfterThrowingWithNoFormal() { runTest("@AfterThrowing with no formal specified"); } public void testParameterizedVarArgsMatch() { runTest("varargs with type variable"); } public void testFieldAccessInsideITDM() { runTest("itd field access inside itd method"); } public void testTypeVarWithTypeVarBound() { runTest("type variable with type variable bound"); } public void testEnumSwitchInITD() { runTest("switch on enum inside ITD method"); } public void testInnerTypeOfGeneric() { runTest("inner type of generic interface reference from parameterized type"); } public void testDeclareParentsIntroducingCovariantReturnType() { runTest("declare parents introducing override with covariance"); } public void testInnerClassPassedToVarargs() { runTest("inner class passed as argument to varargs method"); } public void testInlinedFieldAccessInProceedCall() { runTest("inlined field access in proceed call"); } public void testVisibiltyInSignatureMatchingWithOverridesPart1() { runTest("visibility in signature matching with overrides - 1"); } public void testVisibiltyInSignatureMatchingWithOverridesPart2() { runTest("visibility in signature matching with overrides - 2"); } public void testVisibiltyInSignatureMatchingWithOverridesPart3() { runTest("visibility in signature matching with overrides - 3"); } public void testArgsGeneratedCorrectlyForAdviceExecution() { runTest("args generated correctly for advice execution join point"); } public void testNoUnusedWarningsOnAspectTypes() { runTest("no unused warnings on aspect types"); } public void testSyntheticArgumentsOnITDConstructorsNotUsedInMatching() { runTest("synthetic arguments on itd cons are not used in matching"); } // helper methods..... public SyntheticRepository createRepos(File cpentry) { ClassPath cp = new ClassPath(cpentry+File.pathSeparator+System.getProperty("java.class.path")); return SyntheticRepository.getInstance(cp); } protected JavaClass getClassFrom(File where,String clazzname) throws ClassNotFoundException { SyntheticRepository repos = createRepos(where); return repos.loadClass(clazzname); } }
99,136
Bug 99136 xlint advice not applied appears twice with cflows
////////////// in the following code aspect A{ before(): call(* *(..)) && cflow(execution(* *(..))) {} } //////////////////////////////////// two "advice not appied" xlint messages are produced, one for the before advice and one for the cflow within the before advice.
resolved fixed
047173e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-02T10:40:19Z
2005-06-09T12:26:40Z
tests/bugs150/pr105479/Driver.java
99,136
Bug 99136 xlint advice not applied appears twice with cflows
////////////// in the following code aspect A{ before(): call(* *(..)) && cflow(execution(* *(..))) {} } //////////////////////////////////// two "advice not appied" xlint messages are produced, one for the before advice and one for the cflow within the before advice.
resolved fixed
047173e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-02T10:40:19Z
2005-06-09T12:26:40Z
tests/bugs150/pr105479/ReturnTypeTester.java
99,136
Bug 99136 xlint advice not applied appears twice with cflows
////////////// in the following code aspect A{ before(): call(* *(..)) && cflow(execution(* *(..))) {} } //////////////////////////////////// two "advice not appied" xlint messages are produced, one for the before advice and one for the cflow within the before advice.
resolved fixed
047173e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-02T10:40:19Z
2005-06-09T12:26:40Z
tests/harness/XLintcflow.java
99,136
Bug 99136 xlint advice not applied appears twice with cflows
////////////// in the following code aspect A{ before(): call(* *(..)) && cflow(execution(* *(..))) {} } //////////////////////////////////// two "advice not appied" xlint messages are produced, one for the before advice and one for the cflow within the before advice.
resolved fixed
047173e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-02T10:40:19Z
2005-06-09T12:26:40Z
tests/src/org/aspectj/systemtest/ajc150/Ajc150Tests.java
/******************************************************************************* * Copyright (c) 2004 IBM * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Andy Clement - initial API and implementation *******************************************************************************/ package org.aspectj.systemtest.ajc150; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import junit.framework.Test; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.apache.bcel.classfile.Method; import org.aspectj.apache.bcel.util.ClassPath; import org.aspectj.apache.bcel.util.SyntheticRepository; import org.aspectj.asm.AsmManager; import org.aspectj.testing.XMLBasedAjcTestCase; import org.aspectj.util.LangUtil; /** * These are tests that will run on Java 1.4 and use the old harness format for test specification. */ public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase { public static Test suite() { return XMLBasedAjcTestCase.loadSuite(Ajc150Tests.class); } protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml"); } public void test_typeProcessingOrderWhenDeclareParents() { runTest("Order of types passed to compiler determines weaving behavior"); } public void test_aroundMethod() { runTest("method called around in class"); } public void test_aroundMethodAspect() { runTest("method called around in aspect"); } public void test_ambiguousBindingsDetection() { runTest("Various kinds of ambiguous bindings"); } public void test_ambiguousArgsDetection() { runTest("ambiguous args"); } public void testIncorrectExceptionTableWhenBreakInMethod_pr78021() { runTest("Injecting exception into while loop with break statement causes catch block to be ignored"); } public void testIncorrectExceptionTableWhenReturnInMethod_pr79554() { runTest("Return in try-block disables catch-block if final-block is present"); } public void testMissingDebugInfoForGeneratedMethods_pr82570() throws ClassNotFoundException { runTest("Weaved code does not include debug lines"); boolean f = false; JavaClass jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1"); Method[] meths = jc.getMethods(); for (int i = 0; i < meths.length; i++) { Method method = meths[i]; if (f) System.err.println("Line number table for "+method.getName()+method.getSignature()+" = "+method.getLineNumberTable()); assertTrue("Didn't find a line number table for method "+method.getName()+method.getSignature(), method.getLineNumberTable()!=null); } // This test would determine the info isn't there if you pass -g:none ... // cR = ajc(baseDir,new String[]{"PR82570_1.java","-g:none"}); // assertTrue("Expected no compile problem:"+cR,!cR.hasErrorMessages()); // System.err.println(cR.getStandardError()); // jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1"); // meths = jc.getMethods(); // for (int i = 0; i < meths.length; i++) { // Method method = meths[i]; // assertTrue("Found a line number table for method "+method.getName(), // method.getLineNumberTable()==null); // } } public void testCanOverrideProtectedMethodsViaITDandDecp_pr83303() { runTest("compiler error when mixing inheritance, overriding and polymorphism"); } public void testPerTypeWithinMissesNamedInnerTypes() { runTest("pertypewithin() handing of inner classes (1)"); } public void testPerTypeWithinMissesAnonymousInnerTypes() { runTest("pertypewithin() handing of inner classes (2)"); } public void testPerTypeWithinIncorrectlyMatchingInterfaces() { runTest("pertypewithin({interface}) illegal field modifier"); } public void test051_arrayCloningInJava5() { runTest("AJC possible bug with static nested classes"); } public void testBadASMforEnums() throws IOException { runTest("bad asm for enums"); if (LangUtil.is15VMOrGreater()) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintWriter pw = new PrintWriter(baos); AsmManager.dumptree(pw,AsmManager.getDefault().getHierarchy().getRoot(),0); pw.flush(); String tree = baos.toString(); assertTrue("Expected 'Red [enumvalue]' somewhere in here:"+tree,tree.indexOf("Red [enumvalue]")!=-1); } } public void npeOnTypeNotFound() { runTest("structure model npe on type not found"); } public void testNoRuntimeExceptionSoftening() { runTest("declare soft of runtime exception"); } public void testRuntimeNoSoftenWithHandler() { runTest("declare soft w. catch block"); } public void testSyntaxError() { runTest("invalid cons syntax"); } public void testVarargsInConsBug() { runTest("varargs in constructor sig"); } public void testAspectpathdirs() { runTest("dirs on aspectpath"); } public void testIntroSample() { runTest("introduction sample"); } public void testPTWInterface() { runTest("pertypewithin({interface}) illegal field modifier"); } public void testEnumCalledEnumEtc() { runTest("enum called Enum, annotation called Annotation, etc"); } public void testInternalCompilerError_pr86832() { runTest("Internal compiler error"); } public void testCloneMethod_pr83311() { runTest("overriding/polymorphism error on interface method introduction"); } /** * IfPointcut.findResidueInternal() was modified to make this test complete in a short amount * of time - if you see it hanging, someone has messed with the optimization. */ public void testIfEvaluationExplosion_pr94086() { runTest("Exploding compile time with if() statements in pointcut"); } public void testReflectNPE_pr94167() {runTest("NPE in reflect implementation");} public void testStaticImports_pr84260() {runTest("static import failures");} public void testGenerics_pr99089() {runTest("ArrayIndexOutOfBoundsException - Generics in privileged aspects");} public void testGenerics_pr95993() {runTest("NPE at ClassScope.java:660 when compiling generic class");} public void testItdGenerics_pr99228() {runTest("ITD of a field into a generic class");} public void testItdGenerics_pr98320() {runTest("intertype with nested generic type");} public void testItdGenerics_pr100227() {runTest("inner class with generic enclosing class");} public void testItdGenerics_pr100260() {runTest("methods inherited from a generic parent");} public void testSyntaxErrorNPE_pr103266() {runTest("NPE on syntax error");} public void testIllegalStateExceptionOnNestedParameterizedType_pr106634() { runTest("IllegalStateException unpacking signature of nested parameterized type"); } public void testParseErrorOnAnnotationStarPlusPattern() { runTest("(@Foo *)+ type pattern parse error"); } public void test_pr106130_tooManyLocals() { runTest("test weaving with > 256 locals"); } public void testMissingNamePattern_pr106461() { runTest("missing name pattern"); } public void testMissingNamePattern_pr107059() { runTest("parser crashes on call(void (@a *)(..)"); } public void testIntermediateAnnotationMatching() { runTest("intermediate annotation matching"); } public void testBadRuntimeTestGeneration() { runTest("target(@Foo *)"); } public void testErrorMessageOnITDWithTypePatterns() { runTest("clear error message on itd with type pattern"); } public void testAjKeywordsAsIdentifiers() { runTest("before and after are valid identifiers in classes"); } public void testAjKeywordsAsIdentifiers2() { runTest("before and after are valid identifiers in classes, part 2"); } public void testNoBeforeReturningAdvice() { runTest("before returning advice not allowed!"); } public void testDetectVoidFieldType() { runTest("void field type in pointcut expression"); } public void testPointcutOverriding() { runTest("overriding final pointcut from super-aspect"); } public void testAtSuppressWarnings() { runTest("@SuppressWarnings should suppress"); } public void testDEOWWithBindingPointcut() { runTest("declare warning : foo(str) : ...;"); } public void testAroundAdviceAndInterfaceInitializer() { runTest("around advice on interface initializer"); } public void testGoodErrorMessageOnUnmatchedMemberSyntax() { runTest("good error message for unmatched member syntax"); } public void testITDWithNoExceptionAndIntermediary() { runTest("itd override with no exception clause"); } public void testAnonymousInnerClasses() { runTest("anonymous inner classes"); } public void testMultipleAnonymousInnerClasses() { runTest("multiple anonymous inner classes"); } public void testPrivilegedMethodAccessorsGetRightExceptions_pr82989() { runTest("Compiler error due to a wrong exception check in try blocks"); } public void testAnonymousInnerClassWithMethodReturningTypeParameter_pr107898() { runTest("anonymous inner class with method returning type parameter"); } public void testMatchingOfObjectArray() { runTest("matching against Object[]"); } public void testMultipleAnonymousInnerClasses_pr108104() { runTest("multiple anonymous inner classes 2"); } public void testSignatureMatchingInMultipleOverrideScenario() { runTest("signature matching in override scenario"); } public void testWildcardAnnotationMatching_pr108245() { runTest("wildcard annotation matching - pr108245"); } public void testInnerTypesAndTypeVariables() { runTest("inner types and type variables"); } public void testAtAfterThrowingWithNoFormal() { runTest("@AfterThrowing with no formal specified"); } public void testParameterizedVarArgsMatch() { runTest("varargs with type variable"); } public void testFieldAccessInsideITDM() { runTest("itd field access inside itd method"); } public void testTypeVarWithTypeVarBound() { runTest("type variable with type variable bound"); } public void testEnumSwitchInITD() { runTest("switch on enum inside ITD method"); } public void testInnerTypeOfGeneric() { runTest("inner type of generic interface reference from parameterized type"); } public void testDeclareParentsIntroducingCovariantReturnType() { runTest("declare parents introducing override with covariance"); } public void testInnerClassPassedToVarargs() { runTest("inner class passed as argument to varargs method"); } public void testInlinedFieldAccessInProceedCall() { runTest("inlined field access in proceed call"); } public void testVisibiltyInSignatureMatchingWithOverridesPart1() { runTest("visibility in signature matching with overrides - 1"); } public void testVisibiltyInSignatureMatchingWithOverridesPart2() { runTest("visibility in signature matching with overrides - 2"); } public void testVisibiltyInSignatureMatchingWithOverridesPart3() { runTest("visibility in signature matching with overrides - 3"); } public void testArgsGeneratedCorrectlyForAdviceExecution() { runTest("args generated correctly for advice execution join point"); } public void testNoUnusedWarningsOnAspectTypes() { runTest("no unused warnings on aspect types"); } public void testSyntheticArgumentsOnITDConstructorsNotUsedInMatching() { runTest("synthetic arguments on itd cons are not used in matching"); } public void testParsingOfGenericTypeSignature() { runTest("parse generic type signature with parameterized type in interface"); } // helper methods..... public SyntheticRepository createRepos(File cpentry) { ClassPath cp = new ClassPath(cpentry+File.pathSeparator+System.getProperty("java.class.path")); return SyntheticRepository.getInstance(cp); } protected JavaClass getClassFrom(File where,String clazzname) throws ClassNotFoundException { SyntheticRepository repos = createRepos(where); return repos.loadClass(clazzname); } }
99,136
Bug 99136 xlint advice not applied appears twice with cflows
////////////// in the following code aspect A{ before(): call(* *(..)) && cflow(execution(* *(..))) {} } //////////////////////////////////// two "advice not appied" xlint messages are produced, one for the before advice and one for the cflow within the before advice.
resolved fixed
047173e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-02T10:40:19Z
2005-06-09T12:26:40Z
tests/src/org/aspectj/systemtest/xlint/XLintTests.java
/* ******************************************************************* * Copyright (c) 2004 IBM Corporation * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * ******************************************************************/ package org.aspectj.systemtest.xlint; import java.io.File; import junit.framework.Test; import org.aspectj.testing.XMLBasedAjcTestCase; public class XLintTests extends org.aspectj.testing.XMLBasedAjcTestCase { public static Test suite() { return XMLBasedAjcTestCase.loadSuite(XLintTests.class); } protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/xlint/xlint.xml"); } public void test001(){ runTest("options -Xlint args()"); } public void test002(){ runTest("options declare field on bad type"); } public void test003(){ runTest("options declare method on bad type"); } public void test004(){ runTest("options -Xlint declare parent"); } public void test005(){ runTest("options -Xlint target()"); } public void test006(){ runTest("options -Xlint this()"); } public void test007(){ runTest("options negative -Xlint args()"); } public void test008(){ runTest("options negative -Xlint declare parent"); } public void test009(){ runTest("options negative -Xlint target()"); } public void test010(){ runTest("options negative -Xlint this()"); } public void test011(){ runTest("unmatched type name in a declare parents should result in a warning in -Xlint mode"); } public void test012(){ runTest("privileged access to code outside the control of the compiler"); } public void test013(){ runTest("Unexpected Xlint:unresolvableMember warning with withincode"); } public void test014(){ runTest("valid XLintWarningTest file, default level of warning"); } public void test015(){ runTest("XLint:ignore suppresses XLint warnings"); } public void test016(){ runTest("XLint:error promotes XLint warnings to error"); } public void test017(){ runTest("alias getCause for getWrappedThrowable in SoftException"); } public void test018(){ runTest("XLint warning for call PCD's using subtype of defining type"); } public void test019(){ runTest("XLint warning for call PCD's using subtype of defining type (-1.3 -Xlint:ignore)"); } // FIXME asc put this back in ! // public void test020() { // if (is15VMOrGreater) // runTest("7 lint warnings"); // } }
99,136
Bug 99136 xlint advice not applied appears twice with cflows
////////////// in the following code aspect A{ before(): call(* *(..)) && cflow(execution(* *(..))) {} } //////////////////////////////////// two "advice not appied" xlint messages are produced, one for the before advice and one for the cflow within the before advice.
resolved fixed
047173e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-02T10:40:19Z
2005-06-09T12:26:40Z
weaver/src/org/aspectj/weaver/bcel/BcelWeaver.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * Alexandre Vasseur support for @AJ aspects * ******************************************************************/ package org.aspectj.weaver.bcel; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.jar.Attributes; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.jar.Manifest; import java.util.jar.Attributes.Name; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; import org.aspectj.apache.bcel.classfile.ClassParser; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.IProgressListener; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; import org.aspectj.bridge.SourceLocation; import org.aspectj.bridge.WeaveMessage; import org.aspectj.util.FileUtil; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.Advice; import org.aspectj.weaver.AnnotationOnTypeMunger; import org.aspectj.weaver.AnnotationX; import org.aspectj.weaver.AsmRelationshipProvider; import org.aspectj.weaver.ConcreteTypeMunger; import org.aspectj.weaver.CrosscuttingMembersSet; import org.aspectj.weaver.IClassFileProvider; import org.aspectj.weaver.IWeaveRequestor; import org.aspectj.weaver.IWeaver; import org.aspectj.weaver.NewParentTypeMunger; import org.aspectj.weaver.ResolvedTypeMunger; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.WeaverMetrics; import org.aspectj.weaver.WeaverStateInfo; import org.aspectj.weaver.World; import org.aspectj.weaver.patterns.AndPointcut; import org.aspectj.weaver.patterns.BindingAnnotationTypePattern; import org.aspectj.weaver.patterns.BindingTypePattern; import org.aspectj.weaver.patterns.CflowPointcut; import org.aspectj.weaver.patterns.ConcreteCflowPointcut; import org.aspectj.weaver.patterns.DeclareAnnotation; import org.aspectj.weaver.patterns.DeclareParents; import org.aspectj.weaver.patterns.FastMatchInfo; import org.aspectj.weaver.patterns.IfPointcut; import org.aspectj.weaver.patterns.KindedPointcut; import org.aspectj.weaver.patterns.NameBindingPointcut; import org.aspectj.weaver.patterns.NotPointcut; import org.aspectj.weaver.patterns.OrPointcut; import org.aspectj.weaver.patterns.Pointcut; import org.aspectj.weaver.patterns.PointcutRewriter; import org.aspectj.weaver.patterns.WithinPointcut; public class BcelWeaver implements IWeaver { private BcelWorld world; private CrosscuttingMembersSet xcutSet; private IProgressListener progressListener = null; private double progressMade; private double progressPerClassFile; private boolean inReweavableMode = false; public BcelWeaver(BcelWorld world) { super(); WeaverMetrics.reset(); this.world = world; this.xcutSet = world.getCrosscuttingMembersSet(); } public BcelWeaver() { this(new BcelWorld()); } // ---- fields // private Map sourceJavaClasses = new HashMap(); /* String -> UnwovenClassFile */ private List addedClasses = new ArrayList(); /* List<UnovenClassFile> */ private List deletedTypenames = new ArrayList(); /* List<String> */ // private Map resources = new HashMap(); /* String -> UnwovenClassFile */ private Manifest manifest = null; private boolean needToReweaveWorld = false; private List shadowMungerList = null; // setup by prepareForWeave private List typeMungerList = null; // setup by prepareForWeave private List lateTypeMungerList = null; // setup by prepareForWeave private List declareParentsList = null; // setup by prepareForWeave private ZipOutputStream zipOutputStream; // ---- // only called for testing public void setShadowMungers(List l) { shadowMungerList = l; } /** * Add the given aspect to the weaver. * The type is resolved to support DOT for static inner classes as well as DOLLAR * * @param aspectName */ public void addLibraryAspect(String aspectName) { // 1 - resolve as is ResolvedType type = world.resolve(UnresolvedType.forName(aspectName), true); if (type.equals(ResolvedType.MISSING)) { // fallback on inner class lookup mechanism String fixedName = aspectName; int hasDot = fixedName.lastIndexOf('.'); while (hasDot > 0) { //System.out.println("BcelWeaver.addLibraryAspect " + fixedName); char[] fixedNameChars = fixedName.toCharArray(); fixedNameChars[hasDot] = '$'; fixedName = new String(fixedNameChars); hasDot = fixedName.lastIndexOf('.'); type = world.resolve(UnresolvedType.forName(fixedName), true); if (!type.equals(ResolvedType.MISSING)) { break; } } } //System.out.println("type: " + type + " for " + aspectName); if (type.isAspect()) { //TODO AV - happens to reach that a lot of time: for each type flagged reweavable X for each aspect in the weaverstate //=> mainly for nothing for LTW - pbly for something in incremental build... xcutSet.addOrReplaceAspect(type); } else { // FIXME : Alex: better warning upon no such aspect from aop.xml throw new RuntimeException("Cannot register non aspect: " + type.getName() + " , " + aspectName); } } /** * * @param inFile File path to class directory or zip/jar class archive * @throws IOException */ public void addLibraryJarFile(File inFile) throws IOException { List addedAspects = null; if (inFile.isDirectory()) { addedAspects = addAspectsFromDirectory(inFile); } else { addedAspects = addAspectsFromJarFile(inFile); } for (Iterator i = addedAspects.iterator(); i.hasNext();) { ResolvedType aspectX = (ResolvedType) i.next(); xcutSet.addOrReplaceAspect(aspectX); } } private List addAspectsFromJarFile(File inFile) throws FileNotFoundException, IOException { ZipInputStream inStream = new ZipInputStream(new FileInputStream(inFile)); //??? buffered List addedAspects = new ArrayList(); while (true) { ZipEntry entry = inStream.getNextEntry(); if (entry == null) break; if (entry.isDirectory() || !entry.getName().endsWith(".class")) { continue; } // FIXME ASC performance? of this alternative soln. ClassParser parser = new ClassParser(new ByteArrayInputStream(FileUtil.readAsByteArray(inStream)), entry.getName()); JavaClass jc = parser.parse(); inStream.closeEntry(); ResolvedType type = world.addSourceObjectType(jc).getResolvedTypeX(); if (type.isAspect()) { addedAspects.add(type); } } inStream.close(); return addedAspects; } private List addAspectsFromDirectory(File dir) throws FileNotFoundException, IOException{ List addedAspects = new ArrayList(); File[] classFiles = FileUtil.listFiles(dir,new FileFilter(){ public boolean accept(File pathname) { return pathname.getName().endsWith(".class"); } }); for (int i = 0; i < classFiles.length; i++) { FileInputStream fis = new FileInputStream(classFiles[i]); byte[] bytes = FileUtil.readAsByteArray(fis); addIfAspect(bytes,classFiles[i].getAbsolutePath(),addedAspects); } return addedAspects; } private void addIfAspect(byte[] bytes, String name, List toList) throws IOException { ClassParser parser = new ClassParser(new ByteArrayInputStream(bytes),name); JavaClass jc = parser.parse(); ResolvedType type = world.addSourceObjectType(jc).getResolvedTypeX(); if (type.isAspect()) { toList.add(type); } } // // The ANT copy task should be used to copy resources across. // private final static boolean CopyResourcesFromInpathDirectoriesToOutput=false; /** * Add any .class files in the directory to the outdir. Anything other than .class files in * the directory (or its subdirectories) are considered resources and are also copied. * */ public List addDirectoryContents(File inFile,File outDir) throws IOException { List addedClassFiles = new ArrayList(); // Get a list of all files (i.e. everything that isnt a directory) File[] files = FileUtil.listFiles(inFile,new FileFilter() { public boolean accept(File f) { boolean accept = !f.isDirectory(); return accept; } }); // For each file, add it either as a real .class file or as a resource for (int i = 0; i < files.length; i++) { addedClassFiles.add(addClassFile(files[i],inFile,outDir)); } return addedClassFiles; } /** Adds all class files in the jar */ public List addJarFile(File inFile, File outDir, boolean canBeDirectory){ // System.err.println("? addJarFile(" + inFile + ", " + outDir + ")"); List addedClassFiles = new ArrayList(); needToReweaveWorld = true; JarFile inJar = null; try { // Is this a directory we are looking at? if (inFile.isDirectory() && canBeDirectory) { addedClassFiles.addAll(addDirectoryContents(inFile,outDir)); } else { inJar = new JarFile(inFile); addManifest(inJar.getManifest()); Enumeration entries = inJar.entries(); while (entries.hasMoreElements()) { JarEntry entry = (JarEntry)entries.nextElement(); InputStream inStream = inJar.getInputStream(entry); byte[] bytes = FileUtil.readAsByteArray(inStream); String filename = entry.getName(); // System.out.println("? addJarFile() filename='" + filename + "'"); UnwovenClassFile classFile = new UnwovenClassFile(new File(outDir, filename).getAbsolutePath(), bytes); if (filename.endsWith(".class")) { this.addClassFile(classFile); addedClassFiles.add(classFile); } // else if (!entry.isDirectory()) { // // /* bug-44190 Copy meta-data */ // addResource(filename,classFile); // } inStream.close(); } inJar.close(); } } catch (FileNotFoundException ex) { IMessage message = new Message( "Could not find input jar file " + inFile.getPath() + ", ignoring", new SourceLocation(inFile,0), false); world.getMessageHandler().handleMessage(message); } catch (IOException ex) { IMessage message = new Message( "Could not read input jar file " + inFile.getPath() + "(" + ex.getMessage() + ")", new SourceLocation(inFile,0), true); world.getMessageHandler().handleMessage(message); } finally { if (inJar != null) { try {inJar.close();} catch (IOException ex) { IMessage message = new Message( "Could not close input jar file " + inFile.getPath() + "(" + ex.getMessage() + ")", new SourceLocation(inFile,0), true); world.getMessageHandler().handleMessage(message); } } } return addedClassFiles; } // public void addResource(String name, File inPath, File outDir) throws IOException { // // /* Eliminate CVS files. Relative paths use "/" */ // if (!name.startsWith("CVS/") && (-1 == name.indexOf("/CVS/")) && !name.endsWith("/CVS")) { //// System.err.println("? addResource('" + name + "')"); //// BufferedInputStream inStream = new BufferedInputStream(new FileInputStream(inPath)); //// byte[] bytes = new byte[(int)inPath.length()]; //// inStream.read(bytes); //// inStream.close(); // byte[] bytes = FileUtil.readAsByteArray(inPath); // UnwovenClassFile resourceFile = new UnwovenClassFile(new File(outDir, name).getAbsolutePath(), bytes); // addResource(name,resourceFile); // } // } public boolean needToReweaveWorld() { return needToReweaveWorld; } /** Should be addOrReplace */ public void addClassFile(UnwovenClassFile classFile) { addedClasses.add(classFile); // if (null != sourceJavaClasses.put(classFile.getClassName(), classFile)) { //// throw new RuntimeException(classFile.getClassName()); // } world.addSourceObjectType(classFile.getJavaClass()); } public UnwovenClassFile addClassFile(File classFile, File inPathDir, File outDir) throws IOException { FileInputStream fis = new FileInputStream(classFile); byte[] bytes = FileUtil.readAsByteArray(fis); // String relativePath = files[i].getPath(); // ASSERT: files[i].getAbsolutePath().startsWith(inFile.getAbsolutePath() // or we are in trouble... String filename = classFile.getAbsolutePath().substring( inPathDir.getAbsolutePath().length()+1); UnwovenClassFile ucf = new UnwovenClassFile(new File(outDir,filename).getAbsolutePath(),bytes); if (filename.endsWith(".class")) { // System.err.println("BCELWeaver: processing class from input directory "+classFile); this.addClassFile(ucf); } fis.close(); return ucf; } public void deleteClassFile(String typename) { deletedTypenames.add(typename); // sourceJavaClasses.remove(typename); world.deleteSourceObjectType(UnresolvedType.forName(typename)); } // public void addResource (String name, UnwovenClassFile resourceFile) { // /* bug-44190 Change error to warning and copy first resource */ // if (!resources.containsKey(name)) { // resources.put(name, resourceFile); // } // else { // world.showMessage(IMessage.WARNING, "duplicate resource: '" + name + "'", // null, null); // } // } // ---- weave preparation public void prepareForWeave() { needToReweaveWorld = false; CflowPointcut.clearCaches(); // update mungers for (Iterator i = addedClasses.iterator(); i.hasNext(); ) { UnwovenClassFile jc = (UnwovenClassFile)i.next(); String name = jc.getClassName(); ResolvedType type = world.resolve(name); //System.err.println("added: " + type + " aspect? " + type.isAspect()); if (type.isAspect()) { needToReweaveWorld |= xcutSet.addOrReplaceAspect(type); } } for (Iterator i = deletedTypenames.iterator(); i.hasNext(); ) { String name = (String)i.next(); if (xcutSet.deleteAspect(UnresolvedType.forName(name))) needToReweaveWorld = true; } shadowMungerList = xcutSet.getShadowMungers(); rewritePointcuts(shadowMungerList); typeMungerList = xcutSet.getTypeMungers(); lateTypeMungerList = xcutSet.getLateTypeMungers(); declareParentsList = xcutSet.getDeclareParents(); // The ordering here used to be based on a string compare on toString() for the two mungers - // that breaks for the @AJ style where advice names aren't programmatically generated. So we // have changed the sorting to be based on source location in the file - this is reliable, in // the case of source locations missing, we assume they are 'sorted' - i.e. the order in // which they were added to the collection is correct, this enables the @AJ stuff to work properly. // When @AJ processing starts filling in source locations for mungers, this code may need // a bit of alteration... Collections.sort( shadowMungerList, new Comparator() { public int compare(Object o1, Object o2) { ShadowMunger sm1 = (ShadowMunger)o1; ShadowMunger sm2 = (ShadowMunger)o2; if (sm1.getSourceLocation()==null) return (sm2.getSourceLocation()==null?0:1); if (sm2.getSourceLocation()==null) return -1; return (sm2.getSourceLocation().getOffset()-sm1.getSourceLocation().getOffset()); } }); } /* * Rewrite all of the pointcuts in the world into their most efficient * form for subsequent matching. Also ensure that if pc1.equals(pc2) * then pc1 == pc2 (for non-binding pcds) by making references all * point to the same instance. * Since pointcuts remember their match decision on the last shadow, * this makes matching faster when many pointcuts share common elements, * or even when one single pointcut has one common element (which can * be a side-effect of DNF rewriting). */ private void rewritePointcuts(List/*ShadowMunger*/ shadowMungers) { PointcutRewriter rewriter = new PointcutRewriter(); for (Iterator iter = shadowMungers.iterator(); iter.hasNext();) { ShadowMunger munger = (ShadowMunger) iter.next(); Pointcut p = munger.getPointcut(); Pointcut newP = rewriter.rewrite(p); // validateBindings now whilst we still have around the pointcut // that resembles what the user actually wrote in their program // text. if (munger instanceof Advice) { Advice advice = (Advice) munger; if (advice.getSignature() != null) { final int numFormals; final String names[]; //ATAJ for @AJ aspect, the formal have to be checked according to the argument number // since xxxJoinPoint presence or not have side effects if (advice.getConcreteAspect().isAnnotationStyleAspect()) { numFormals = advice.getBaseParameterCount(); int numArgs = advice.getSignature().getParameterTypes().length; if (numFormals > 0) { names = advice.getSignature().getParameterNames(world); validateBindings(newP,p,numArgs,names); } } else { numFormals = advice.getBaseParameterCount(); if (numFormals > 0) { names = advice.getBaseParameterNames(world); validateBindings(newP,p,numFormals,names); } } } } munger.setPointcut(newP); } // now that we have optimized individual pointcuts, optimize // across the set of pointcuts.... // Use a map from key based on pc equality, to value based on // pc identity. Map/*<Pointcut,Pointcut>*/ pcMap = new HashMap(); for (Iterator iter = shadowMungers.iterator(); iter.hasNext();) { ShadowMunger munger = (ShadowMunger) iter.next(); Pointcut p = munger.getPointcut(); munger.setPointcut(shareEntriesFromMap(p,pcMap)); } } private Pointcut shareEntriesFromMap(Pointcut p,Map pcMap) { // some things cant be shared... if (p instanceof NameBindingPointcut) return p; if (p instanceof IfPointcut) return p; if (p instanceof ConcreteCflowPointcut) return p; if (p instanceof AndPointcut) { AndPointcut apc = (AndPointcut) p; Pointcut left = shareEntriesFromMap(apc.getLeft(),pcMap); Pointcut right = shareEntriesFromMap(apc.getRight(),pcMap); return new AndPointcut(left,right); } else if (p instanceof OrPointcut) { OrPointcut opc = (OrPointcut) p; Pointcut left = shareEntriesFromMap(opc.getLeft(),pcMap); Pointcut right = shareEntriesFromMap(opc.getRight(),pcMap); return new OrPointcut(left,right); } else if (p instanceof NotPointcut) { NotPointcut npc = (NotPointcut) p; Pointcut not = shareEntriesFromMap(npc.getNegatedPointcut(),pcMap); return new NotPointcut(not); } else { // primitive pcd if (pcMap.containsKey(p)) { // based on equality return (Pointcut) pcMap.get(p); // same instance (identity) } else { pcMap.put(p,p); return p; } } } // userPointcut is the pointcut that the user wrote in the program text. // dnfPointcut is the same pointcut rewritten in DNF // numFormals is the number of formal parameters in the pointcut // if numFormals > 0 then every branch of a disjunction must bind each formal once and only once. // in addition, the left and right branches of a disjunction must hold on join point kinds in // common. private void validateBindings(Pointcut dnfPointcut, Pointcut userPointcut, int numFormals, String[] names) { if (numFormals == 0) return; // nothing to check if (dnfPointcut.couldMatchKinds().isEmpty()) return; // cant have problems if you dont match! if (dnfPointcut instanceof OrPointcut) { OrPointcut orBasedDNFPointcut = (OrPointcut) dnfPointcut; Pointcut[] leftBindings = new Pointcut[numFormals]; Pointcut[] rightBindings = new Pointcut[numFormals]; validateOrBranch(orBasedDNFPointcut,userPointcut,numFormals,names,leftBindings,rightBindings); } else { Pointcut[] bindings = new Pointcut[numFormals]; validateSingleBranch(dnfPointcut, userPointcut, numFormals, names,bindings); } } private void validateOrBranch(OrPointcut pc, Pointcut userPointcut, int numFormals, String[] names, Pointcut[] leftBindings, Pointcut[] rightBindings) { Pointcut left = pc.getLeft(); Pointcut right = pc.getRight(); if (left instanceof OrPointcut) { Pointcut[] newRightBindings = new Pointcut[numFormals]; validateOrBranch((OrPointcut)left,userPointcut,numFormals,names,leftBindings,newRightBindings); } else { if (left.couldMatchKinds().size() > 0) validateSingleBranch(left, userPointcut, numFormals, names, leftBindings); } if (right instanceof OrPointcut) { Pointcut[] newLeftBindings = new Pointcut[numFormals]; validateOrBranch((OrPointcut)right,userPointcut,numFormals,names,newLeftBindings,rightBindings); } else { if (right.couldMatchKinds().size() > 0) validateSingleBranch(right, userPointcut, numFormals, names, rightBindings); } Set kindsInCommon = left.couldMatchKinds(); kindsInCommon.retainAll(right.couldMatchKinds()); if (!kindsInCommon.isEmpty() && couldEverMatchSameJoinPoints(left,right)) { // we know that every branch binds every formal, so there is no ambiguity // if each branch binds it in exactly the same way... List ambiguousNames = new ArrayList(); for (int i = 0; i < numFormals; i++) { if (!leftBindings[i].equals(rightBindings[i])) { ambiguousNames.add(names[i]); } } if (!ambiguousNames.isEmpty()) raiseAmbiguityInDisjunctionError(userPointcut,ambiguousNames); } } // pc is a pointcut that does not contain any disjunctions // check that every formal is bound (negation doesn't count). // we know that numFormals > 0 or else we would not be called private void validateSingleBranch(Pointcut pc, Pointcut userPointcut, int numFormals, String[] names, Pointcut[] bindings) { boolean[] foundFormals = new boolean[numFormals]; for (int i = 0; i < foundFormals.length; i++) { foundFormals[i] = false; } validateSingleBranchRecursion(pc, userPointcut, foundFormals, names, bindings); for (int i = 0; i < foundFormals.length; i++) { if (!foundFormals[i]) { boolean ignore = false; // ATAJ soften the unbound error for implicit bindings like JoinPoint in @AJ style for (int j = 0; j < userPointcut.m_ignoreUnboundBindingForNames.length; j++) { if (names[i] != null && names[i].equals(userPointcut.m_ignoreUnboundBindingForNames[j])) { ignore = true; break; } } if (!ignore) { raiseUnboundFormalError(names[i],userPointcut); } } } } // each formal must appear exactly once private void validateSingleBranchRecursion(Pointcut pc, Pointcut userPointcut, boolean[] foundFormals, String[] names, Pointcut[] bindings) { if (pc instanceof NotPointcut) { // nots can only appear at leaves in DNF NotPointcut not = (NotPointcut) pc; if (not.getNegatedPointcut() instanceof NameBindingPointcut) { NameBindingPointcut nnbp = (NameBindingPointcut) not.getNegatedPointcut(); if (!nnbp.getBindingAnnotationTypePatterns().isEmpty() && !nnbp.getBindingTypePatterns().isEmpty()) raiseNegationBindingError(userPointcut); } } else if (pc instanceof AndPointcut) { AndPointcut and = (AndPointcut) pc; validateSingleBranchRecursion(and.getLeft(), userPointcut,foundFormals,names,bindings); validateSingleBranchRecursion(and.getRight(),userPointcut,foundFormals,names,bindings); } else if (pc instanceof NameBindingPointcut) { List/*BindingTypePattern*/ btps = ((NameBindingPointcut)pc).getBindingTypePatterns(); for (Iterator iter = btps.iterator(); iter.hasNext();) { BindingTypePattern btp = (BindingTypePattern) iter.next(); int index = btp.getFormalIndex(); bindings[index] = pc; if (foundFormals[index]) { raiseAmbiguousBindingError(names[index],userPointcut); } else { foundFormals[index] = true; } } List/*BindingAnnotationTypePattern*/ baps = ((NameBindingPointcut)pc).getBindingAnnotationTypePatterns(); for (Iterator iter = baps.iterator(); iter.hasNext();) { BindingAnnotationTypePattern bap = (BindingAnnotationTypePattern) iter.next(); int index = bap.getFormalIndex(); bindings[index] = pc; if (foundFormals[index]) { raiseAmbiguousBindingError(names[index],userPointcut); } else { foundFormals[index] = true; } } } else if (pc instanceof ConcreteCflowPointcut) { ConcreteCflowPointcut cfp = (ConcreteCflowPointcut) pc; int[] slots = cfp.getUsedFormalSlots(); for (int i = 0; i < slots.length; i++) { bindings[slots[i]] = cfp; if (foundFormals[slots[i]]) { raiseAmbiguousBindingError(names[slots[i]],userPointcut); } else { foundFormals[slots[i]] = true; } } } } // By returning false from this method, we are allowing binding of the same // variable on either side of an or. // Be conservative :- have to consider overriding, varargs, autoboxing, // the effects of itds (on within for example), interfaces, the fact that // join points can have multiple signatures and so on. private boolean couldEverMatchSameJoinPoints(Pointcut left, Pointcut right) { if ((left instanceof OrPointcut) || (right instanceof OrPointcut)) return true; // look for withins WithinPointcut leftWithin = (WithinPointcut) findFirstPointcutIn(left,WithinPointcut.class); WithinPointcut rightWithin = (WithinPointcut) findFirstPointcutIn(right,WithinPointcut.class); if ((leftWithin != null) && (rightWithin != null)) { if (!leftWithin.couldEverMatchSameJoinPointsAs(rightWithin)) return false; } // look for kinded KindedPointcut leftKind = (KindedPointcut) findFirstPointcutIn(left,KindedPointcut.class); KindedPointcut rightKind = (KindedPointcut) findFirstPointcutIn(right,KindedPointcut.class); if ((leftKind != null) && (rightKind != null)) { if (!leftKind.couldEverMatchSameJoinPointsAs(rightKind)) return false; } return true; } private Pointcut findFirstPointcutIn(Pointcut toSearch, Class toLookFor) { if (toSearch instanceof NotPointcut) return null; if (toLookFor.isInstance(toSearch)) return toSearch; if (toSearch instanceof AndPointcut) { AndPointcut apc = (AndPointcut) toSearch; Pointcut left = findFirstPointcutIn(apc.getLeft(),toLookFor); if (left != null) return left; return findFirstPointcutIn(apc.getRight(),toLookFor); } return null; } /** * @param userPointcut */ private void raiseNegationBindingError(Pointcut userPointcut) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.NEGATION_DOESNT_ALLOW_BINDING), userPointcut.getSourceContext().makeSourceLocation(userPointcut),null); } /** * @param name * @param userPointcut */ private void raiseAmbiguousBindingError(String name, Pointcut userPointcut) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.AMBIGUOUS_BINDING, name), userPointcut.getSourceContext().makeSourceLocation(userPointcut),null); } /** * @param userPointcut */ private void raiseAmbiguityInDisjunctionError(Pointcut userPointcut, List names) { StringBuffer formalNames = new StringBuffer(names.get(0).toString()); for (int i = 1; i < names.size(); i++) { formalNames.append(", "); formalNames.append(names.get(i)); } world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.AMBIGUOUS_BINDING_IN_OR,formalNames), userPointcut.getSourceContext().makeSourceLocation(userPointcut),null); } /** * @param name * @param userPointcut */ private void raiseUnboundFormalError(String name, Pointcut userPointcut) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.UNBOUND_FORMAL, name), userPointcut.getSourceContext().makeSourceLocation(userPointcut),null); } // public void dumpUnwoven(File file) throws IOException { // BufferedOutputStream os = FileUtil.makeOutputStream(file); // this.zipOutputStream = new ZipOutputStream(os); // dumpUnwoven(); // /* BUG 40943*/ // dumpResourcesToOutJar(); // zipOutputStream.close(); //this flushes and closes the acutal file // } // // // public void dumpUnwoven() throws IOException { // Collection filesToDump = new HashSet(sourceJavaClasses.values()); // for (Iterator i = filesToDump.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // dumpUnchanged(classFile); // } // } // public void dumpResourcesToOutPath() throws IOException { //// System.err.println("? dumpResourcesToOutPath() resources=" + resources.keySet()); // Iterator i = resources.keySet().iterator(); // while (i.hasNext()) { // UnwovenClassFile res = (UnwovenClassFile)resources.get(i.next()); // dumpUnchanged(res); // } // //resources = new HashMap(); // } // /* BUG #40943 */ // public void dumpResourcesToOutJar() throws IOException { //// System.err.println("? dumpResourcesToOutJar() resources=" + resources.keySet()); // Iterator i = resources.keySet().iterator(); // while (i.hasNext()) { // String name = (String)i.next(); // UnwovenClassFile res = (UnwovenClassFile)resources.get(name); // writeZipEntry(name,res.getBytes()); // } // resources = new HashMap(); // } // // // halfway house for when the jar is managed outside of the weaver, but the resources // // to be copied are known in the weaver. // public void dumpResourcesToOutJar(ZipOutputStream zos) throws IOException { // this.zipOutputStream = zos; // dumpResourcesToOutJar(); // } public void addManifest (Manifest newManifest) { // System.out.println("? addManifest() newManifest=" + newManifest); if (manifest == null) { manifest = newManifest; } } public static final String MANIFEST_NAME = "META-INF/MANIFEST.MF"; private static final String WEAVER_MANIFEST_VERSION = "1.0"; private static final Attributes.Name CREATED_BY = new Name("Created-By"); private static final String WEAVER_CREATED_BY = "AspectJ Compiler"; public Manifest getManifest (boolean shouldCreate) { if (manifest == null && shouldCreate) { manifest = new Manifest(); Attributes attributes = manifest.getMainAttributes(); attributes.put(Name.MANIFEST_VERSION,WEAVER_MANIFEST_VERSION); attributes.put(CREATED_BY,WEAVER_CREATED_BY); } return manifest; } // ---- weaving // Used by some test cases only... public Collection weave(File file) throws IOException { OutputStream os = FileUtil.makeOutputStream(file); this.zipOutputStream = new ZipOutputStream(os); prepareForWeave(); Collection c = weave( new IClassFileProvider() { public Iterator getClassFileIterator() { return addedClasses.iterator(); } public IWeaveRequestor getRequestor() { return new IWeaveRequestor() { public void acceptResult(UnwovenClassFile result) { try { writeZipEntry(result.filename, result.bytes); } catch(IOException ex) {} } public void processingReweavableState() {} public void addingTypeMungers() {} public void weavingAspects() {} public void weavingClasses() {} public void weaveCompleted() {} }; } }); // /* BUG 40943*/ // dumpResourcesToOutJar(); zipOutputStream.close(); //this flushes and closes the acutal file return c; } // public Collection weave() throws IOException { // prepareForWeave(); // Collection filesToWeave; // // if (needToReweaveWorld) { // filesToWeave = sourceJavaClasses.values(); // } else { // filesToWeave = addedClasses; // } // // Collection wovenClassNames = new ArrayList(); // world.showMessage(IMessage.INFO, "might need to weave " + filesToWeave + // "(world=" + needToReweaveWorld + ")", null, null); // // // //System.err.println("typeMungers: " + typeMungerList); // // prepareToProcessReweavableState(); // // clear all state from files we'll be reweaving // for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // String className = classFile.getClassName(); // BcelObjectType classType = getClassType(className); // processReweavableStateIfPresent(className, classType); // } // // // // //XXX this isn't quite the right place for this... // for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // String className = classFile.getClassName(); // addTypeMungers(className); // } // // // first weave into aspects // for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // String className = classFile.getClassName(); // BcelObjectType classType = BcelWorld.getBcelObjectType(world.resolve(className)); // if (classType.isAspect()) { // weave(classFile, classType); // wovenClassNames.add(className); // } // } // // // then weave into non-aspects // for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // String className = classFile.getClassName(); // BcelObjectType classType = BcelWorld.getBcelObjectType(world.resolve(className)); // if (! classType.isAspect()) { // weave(classFile, classType); // wovenClassNames.add(className); // } // } // // if (zipOutputStream != null && !needToReweaveWorld) { // Collection filesToDump = new HashSet(sourceJavaClasses.values()); // filesToDump.removeAll(filesToWeave); // for (Iterator i = filesToDump.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // dumpUnchanged(classFile); // } // } // // addedClasses = new ArrayList(); // deletedTypenames = new ArrayList(); // // return wovenClassNames; // } // variation of "weave" that sources class files from an external source. public Collection weave(IClassFileProvider input) throws IOException { Collection wovenClassNames = new ArrayList(); IWeaveRequestor requestor = input.getRequestor(); requestor.processingReweavableState(); prepareToProcessReweavableState(); // clear all state from files we'll be reweaving for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) { UnwovenClassFile classFile = (UnwovenClassFile)i.next(); String className = classFile.getClassName(); BcelObjectType classType = getClassType(className); // null return from getClassType() means the delegate is an eclipse source type - so // there *cant* be any reweavable state... (he bravely claimed...) if (classType !=null) processReweavableStateIfPresent(className, classType); } requestor.addingTypeMungers(); // We process type mungers in two groups, first mungers that change the type // hierarchy, then 'normal' ITD type mungers. // Process the types in a predictable order (rather than the order encountered). // For class A, the order is superclasses of A then superinterfaces of A // (and this mechanism is applied recursively) List typesToProcess = new ArrayList(); for (Iterator iter = input.getClassFileIterator(); iter.hasNext();) { UnwovenClassFile clf = (UnwovenClassFile) iter.next(); typesToProcess.add(clf.getClassName()); } while (typesToProcess.size()>0) { weaveParentsFor(typesToProcess,(String)typesToProcess.get(0)); } for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) { UnwovenClassFile classFile = (UnwovenClassFile)i.next(); String className = classFile.getClassName(); addNormalTypeMungers(className); } requestor.weavingAspects(); // first weave into aspects for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) { UnwovenClassFile classFile = (UnwovenClassFile)i.next(); String className = classFile.getClassName(); BcelObjectType classType = BcelWorld.getBcelObjectType(world.resolve(className)); if (classType.isAspect()) { weaveAndNotify(classFile, classType,requestor); wovenClassNames.add(className); } } requestor.weavingClasses(); // then weave into non-aspects for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) { UnwovenClassFile classFile = (UnwovenClassFile)i.next(); String className = classFile.getClassName(); BcelObjectType classType = BcelWorld.getBcelObjectType(world.resolve(className)); if (! classType.isAspect()) { weaveAndNotify(classFile, classType, requestor); wovenClassNames.add(className); } } addedClasses = new ArrayList(); deletedTypenames = new ArrayList(); // FIXME asc Should be factored out into Xlint code and done automatically for all xlint messages, ideally. // if a piece of advice hasn't matched anywhere and we are in -1.5 mode, put out a warning if (world.isInJava5Mode() && world.getLint().adviceDidNotMatch.isEnabled()) { List l = world.getCrosscuttingMembersSet().getShadowMungers(); for (Iterator iter = l.iterator(); iter.hasNext();) { ShadowMunger element = (ShadowMunger) iter.next(); if (element instanceof BcelAdvice) { // This will stop us incorrectly reporting deow Checkers BcelAdvice ba = (BcelAdvice)element; if (!ba.hasMatchedSomething()) { // Because we implement some features of AJ itself by creating our own kind of mungers, you sometimes // find that ba.getSignature() is not a BcelMethod - for example it might be a cflow entry munger. if (ba.getSignature()!=null) { if (!(ba.getSignature() instanceof BcelMethod) || !Utility.isSuppressing((AnnotationX[])ba.getSignature().getAnnotations(),"adviceDidNotMatch")) { world.getLint().adviceDidNotMatch.signal(ba.getDeclaringAspect().toString(),element.getSourceLocation()); } } } } } } requestor.weaveCompleted(); return wovenClassNames; } /** * 'typeToWeave' is one from the 'typesForWeaving' list. This routine ensures we process * supertypes (classes/interfaces) of 'typeToWeave' that are in the * 'typesForWeaving' list before 'typeToWeave' itself. 'typesToWeave' is then removed from * the 'typesForWeaving' list. * * Note: Future gotcha in here ... when supplying partial hierarchies, this algorithm may * break down. If you have a hierarchy A>B>C and only give A and C to the weaver, it * may choose to weave them in either order - but you'll probably have other problems if * you are supplying partial hierarchies like that ! */ private void weaveParentsFor(List typesForWeaving,String typeToWeave) { // Look at the supertype first ResolvedType rtx = world.resolve(typeToWeave); ResolvedType superType = rtx.getSuperclass(); if (superType!=null && typesForWeaving.contains(superType.getName())) { weaveParentsFor(typesForWeaving,superType.getName()); } // Then look at the superinterface list ResolvedType[] interfaceTypes = rtx.getDeclaredInterfaces(); for (int i = 0; i < interfaceTypes.length; i++) { ResolvedType rtxI = interfaceTypes[i]; if (typesForWeaving.contains(rtxI.getName())) { weaveParentsFor(typesForWeaving,rtxI.getName()); } } weaveParentTypeMungers(rtx); // Now do this type typesForWeaving.remove(typeToWeave); // and remove it from the list of those to process } public void prepareToProcessReweavableState() { if (inReweavableMode) world.showMessage(IMessage.INFO, WeaverMessages.format(WeaverMessages.REWEAVABLE_MODE), null, null); } public void processReweavableStateIfPresent(String className, BcelObjectType classType) { // If the class is marked reweavable, check any aspects around when it was built are in this world WeaverStateInfo wsi = classType.getWeaverState(); if (wsi!=null && wsi.isReweavable()) { // Check all necessary types are around! world.showMessage(IMessage.INFO, WeaverMessages.format(WeaverMessages.PROCESSING_REWEAVABLE,className,classType.getSourceLocation().getSourceFile()), null,null); Set aspectsPreviouslyInWorld = wsi.getAspectsAffectingType(); if (aspectsPreviouslyInWorld!=null) { // keep track of them just to ensure unique missing aspect error reporting Set alreadyConfirmedReweavableState = new HashSet(); for (Iterator iter = aspectsPreviouslyInWorld.iterator(); iter.hasNext();) { String requiredTypeName = (String) iter.next(); if (!alreadyConfirmedReweavableState.contains(requiredTypeName)) { ResolvedType rtx = world.resolve(UnresolvedType.forName(requiredTypeName),true); boolean exists = rtx!=ResolvedType.MISSING; if (!exists) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.MISSING_REWEAVABLE_TYPE,requiredTypeName,className), classType.getSourceLocation(), null); } else { if (!world.getMessageHandler().isIgnoring(IMessage.INFO)) world.showMessage(IMessage.INFO, WeaverMessages.format(WeaverMessages.VERIFIED_REWEAVABLE_TYPE,requiredTypeName,rtx.getSourceLocation().getSourceFile()), null,null); alreadyConfirmedReweavableState.add(requiredTypeName); } } } } classType.setJavaClass(Utility.makeJavaClass(classType.getJavaClass().getFileName(), wsi.getUnwovenClassFileData())); } else { classType.resetState(); } } private void weaveAndNotify(UnwovenClassFile classFile, BcelObjectType classType, IWeaveRequestor requestor) throws IOException { LazyClassGen clazz = weaveWithoutDump(classFile,classType); classType.finishedWith(); //clazz is null if the classfile was unchanged by weaving... if (clazz != null) { UnwovenClassFile[] newClasses = getClassFilesFor(clazz); for (int i = 0; i < newClasses.length; i++) { requestor.acceptResult(newClasses[i]); } } else { requestor.acceptResult(classFile); } } /** helper method - will return NULL if the underlying delegate is an EclipseSourceType and not a BcelObjectType */ public BcelObjectType getClassType(String forClass) { return BcelWorld.getBcelObjectType(world.resolve(forClass)); } public void addParentTypeMungers(String typeName) { weaveParentTypeMungers(world.resolve(typeName)); } public void addNormalTypeMungers(String typeName) { weaveNormalTypeMungers(world.resolve(typeName)); } public UnwovenClassFile[] getClassFilesFor(LazyClassGen clazz) { List childClasses = clazz.getChildClasses(world); UnwovenClassFile[] ret = new UnwovenClassFile[1 + childClasses.size()]; ret[0] = new UnwovenClassFile(clazz.getFileName(),clazz.getJavaClass(world).getBytes()); int index = 1; for (Iterator iter = childClasses.iterator(); iter.hasNext();) { UnwovenClassFile.ChildClass element = (UnwovenClassFile.ChildClass) iter.next(); UnwovenClassFile childClass = new UnwovenClassFile(clazz.getFileName() + "$" + element.name, element.bytes); ret[index++] = childClass; } return ret; } /** * Weaves new parents and annotations onto a type ("declare parents" and "declare @type") * * Algorithm: * 1. First pass, do parents then do annotations. During this pass record: * - any parent mungers that don't match but have a non-wild annotation type pattern * - any annotation mungers that don't match * 2. Multiple subsequent passes which go over the munger lists constructed in the first * pass, repeatedly applying them until nothing changes. * FIXME asc confirm that algorithm is optimal ?? */ public void weaveParentTypeMungers(ResolvedType onType) { if (onType.isRawType()) onType = onType.getGenericType(); onType.clearInterTypeMungers(); List decpToRepeat = new ArrayList(); boolean aParentChangeOccurred = false; boolean anAnnotationChangeOccurred = false; // First pass - apply all decp mungers for (Iterator i = declareParentsList.iterator(); i.hasNext(); ) { DeclareParents decp = (DeclareParents)i.next(); boolean typeChanged = applyDeclareParents(decp,onType); if (typeChanged) { aParentChangeOccurred = true; } else { // Perhaps it would have matched if a 'dec @type' had modified the type if (!decp.getChild().isStarAnnotation()) decpToRepeat.add(decp); } } // Still first pass - apply all dec @type mungers for (Iterator i = xcutSet.getDeclareAnnotationOnTypes().iterator();i.hasNext();) { DeclareAnnotation decA = (DeclareAnnotation)i.next(); boolean typeChanged = applyDeclareAtType(decA,onType,true); if (typeChanged) { anAnnotationChangeOccurred = true; } } while ((aParentChangeOccurred || anAnnotationChangeOccurred) && !decpToRepeat.isEmpty()) { anAnnotationChangeOccurred = aParentChangeOccurred = false; List decpToRepeatNextTime = new ArrayList(); for (Iterator iter = decpToRepeat.iterator(); iter.hasNext();) { DeclareParents decp = (DeclareParents) iter.next(); boolean typeChanged = applyDeclareParents(decp,onType); if (typeChanged) { aParentChangeOccurred = true; } else { decpToRepeatNextTime.add(decp); } } for (Iterator iter = xcutSet.getDeclareAnnotationOnTypes().iterator(); iter.hasNext();) { DeclareAnnotation decA = (DeclareAnnotation) iter.next(); boolean typeChanged = applyDeclareAtType(decA,onType,false); if (typeChanged) { anAnnotationChangeOccurred = true; } } decpToRepeat = decpToRepeatNextTime; } } /** * Apply a declare @type - return true if we change the type */ private boolean applyDeclareAtType(DeclareAnnotation decA, ResolvedType onType,boolean reportProblems) { boolean didSomething = false; if (decA.matches(onType)) { // FIXME asc important this should be guarded by the 'already has annotation' check below but isn't since the compiler is producing classfiles with deca affected things in... AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decA.getSourceLocation(),onType.getSourceLocation()); // FIXME asc same comment above applies here // TAG: WeavingMessage if (!getWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)){ getWorld().getMessageHandler().handleMessage( WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_ANNOTATES, new String[]{ onType.toString(), Utility.beautifyLocation(onType.getSourceLocation()), decA.getAnnotationString(), "type", decA.getAspect().toString(), Utility.beautifyLocation(decA.getSourceLocation()) })); } if (onType.hasAnnotation(decA.getAnnotationX().getSignature())) { // FIXME asc Could put out a lint here for an already annotated type - the problem is that it may have // picked up the annotation during 'source weaving' in which case the message is misleading. Leaving it // off for now... // if (reportProblems) { // world.getLint().elementAlreadyAnnotated.signal( // new String[]{onType.toString(),decA.getAnnotationTypeX().toString()}, // onType.getSourceLocation(),new ISourceLocation[]{decA.getSourceLocation()}); // } return false; } AnnotationX annoX = decA.getAnnotationX(); // check the annotation is suitable for the target boolean problemReported = verifyTargetIsOK(decA, onType, annoX,reportProblems); if (!problemReported) { didSomething = true; ResolvedTypeMunger newAnnotationTM = new AnnotationOnTypeMunger(annoX); newAnnotationTM.setSourceLocation(decA.getSourceLocation()); onType.addInterTypeMunger(new BcelTypeMunger(newAnnotationTM,decA.getAspect().resolve(world))); decA.copyAnnotationTo(onType); } } return didSomething; } /** * Checks for an @target() on the annotation and if found ensures it allows the annotation * to be attached to the target type that matched. */ private boolean verifyTargetIsOK(DeclareAnnotation decA, ResolvedType onType, AnnotationX annoX,boolean outputProblems) { boolean problemReported = false; if (annoX.specifiesTarget()) { if ( (onType.isAnnotation() && !annoX.allowedOnAnnotationType()) || (!annoX.allowedOnRegularType())) { if (outputProblems) { if (decA.isExactPattern()) { world.getMessageHandler().handleMessage(MessageUtil.error( WeaverMessages.format(WeaverMessages.INCORRECT_TARGET_FOR_DECLARE_ANNOTATION, onType.getName(),annoX.stringify(),annoX.getValidTargets()),decA.getSourceLocation())); } else { if (world.getLint().invalidTargetForAnnotation.isEnabled()) { world.getLint().invalidTargetForAnnotation.signal( new String[]{onType.getName(),annoX.stringify(),annoX.getValidTargets()},decA.getSourceLocation(),new ISourceLocation[]{onType.getSourceLocation()}); } } } problemReported = true; } } return problemReported; } /** * Apply a single declare parents - return true if we change the type */ private boolean applyDeclareParents(DeclareParents p, ResolvedType onType) { boolean didSomething = false; List newParents = p.findMatchingNewParents(onType,true); if (!newParents.isEmpty()) { didSomething=true; BcelObjectType classType = BcelWorld.getBcelObjectType(onType); //System.err.println("need to do declare parents for: " + onType); for (Iterator j = newParents.iterator(); j.hasNext(); ) { ResolvedType newParent = (ResolvedType)j.next(); // We set it here so that the imminent matching for ITDs can succeed - we // still haven't done the necessary changes to the class file itself // (like transform super calls) - that is done in BcelTypeMunger.mungeNewParent() classType.addParent(newParent); ResolvedTypeMunger newParentMunger = new NewParentTypeMunger(newParent); newParentMunger.setSourceLocation(p.getSourceLocation()); onType.addInterTypeMunger(new BcelTypeMunger(newParentMunger, xcutSet.findAspectDeclaringParents(p))); } } return didSomething; } public void weaveNormalTypeMungers(ResolvedType onType) { if (onType.isRawType() || onType.isParameterizedType()) onType = onType.getGenericType(); for (Iterator i = typeMungerList.iterator(); i.hasNext(); ) { ConcreteTypeMunger m = (ConcreteTypeMunger)i.next(); if (m.matches(onType)) { onType.addInterTypeMunger(m); } } } // exposed for ClassLoader dynamic weaving public LazyClassGen weaveWithoutDump(UnwovenClassFile classFile, BcelObjectType classType) throws IOException { return weave(classFile, classType, false); } // non-private for testing LazyClassGen weave(UnwovenClassFile classFile, BcelObjectType classType) throws IOException { LazyClassGen ret = weave(classFile, classType, true); if (progressListener != null) { progressMade += progressPerClassFile; progressListener.setProgress(progressMade); progressListener.setText("woven: " + classFile.getFilename()); } return ret; } private LazyClassGen weave(UnwovenClassFile classFile, BcelObjectType classType, boolean dump) throws IOException { if (classType.isSynthetic()) { if (dump) dumpUnchanged(classFile); return null; } // JavaClass javaClass = classType.getJavaClass(); List shadowMungers = fastMatch(shadowMungerList, classType.getResolvedTypeX()); List typeMungers = classType.getResolvedTypeX().getInterTypeMungers(); classType.getResolvedTypeX().checkInterTypeMungers(); LazyClassGen clazz = null; if (shadowMungers.size() > 0 || typeMungers.size() > 0 || classType.isAspect() || world.getDeclareAnnotationOnMethods().size()>0 || world.getDeclareAnnotationOnFields().size()>0 ) { clazz = classType.getLazyClassGen(); //System.err.println("got lazy gen: " + clazz + ", " + clazz.getWeaverState()); try { boolean isChanged = BcelClassWeaver.weave(world, clazz, shadowMungers, typeMungers, lateTypeMungerList); if (isChanged) { if (dump) dump(classFile, clazz); return clazz; } } catch (RuntimeException re) { System.err.println("trouble in: "); clazz.print(System.err); re.printStackTrace(); throw re; } catch (Error re) { System.err.println("trouble in: "); clazz.print(System.err); throw re; } } // this is very odd return behavior trying to keep everyone happy if (dump) { dumpUnchanged(classFile); return clazz; } else { // ATAJ: the class was not weaved, but since it gets there early it may have new generated inner classes // attached to it to support LTW perX aspectOf support (see BcelPerClauseAspectAdder) // that aggressively defines the inner <aspect>$mayHaveAspect interface. if (clazz != null && !clazz.getChildClasses(world).isEmpty()) { return clazz; } return null; } } // ---- writing private void dumpUnchanged(UnwovenClassFile classFile) throws IOException { if (zipOutputStream != null) { writeZipEntry(getEntryName(classFile.getJavaClass().getClassName()), classFile.getBytes()); } else { classFile.writeUnchangedBytes(); } } private String getEntryName(String className) { //XXX what does bcel's getClassName do for inner names return className.replace('.', '/') + ".class"; } private void dump(UnwovenClassFile classFile, LazyClassGen clazz) throws IOException { if (zipOutputStream != null) { String mainClassName = classFile.getJavaClass().getClassName(); writeZipEntry(getEntryName(mainClassName), clazz.getJavaClass(world).getBytes()); if (!clazz.getChildClasses(world).isEmpty()) { for (Iterator i = clazz.getChildClasses(world).iterator(); i.hasNext();) { UnwovenClassFile.ChildClass c = (UnwovenClassFile.ChildClass) i.next(); writeZipEntry(getEntryName(mainClassName + "$" + c.name), c.bytes); } } } else { classFile.writeWovenBytes( clazz.getJavaClass(world).getBytes(), clazz.getChildClasses(world) ); } } private void writeZipEntry(String name, byte[] bytes) throws IOException { ZipEntry newEntry = new ZipEntry(name); //??? get compression scheme right zipOutputStream.putNextEntry(newEntry); zipOutputStream.write(bytes); zipOutputStream.closeEntry(); } private List fastMatch(List list, ResolvedType type) { if (list == null) return Collections.EMPTY_LIST; // here we do the coarsest grained fast match with no kind constraints // this will remove all obvious non-matches and see if we need to do any weaving FastMatchInfo info = new FastMatchInfo(type, null); List result = new ArrayList(); Iterator iter = list.iterator(); while (iter.hasNext()) { ShadowMunger munger = (ShadowMunger)iter.next(); FuzzyBoolean fb = munger.getPointcut().fastMatch(info); WeaverMetrics.recordFastMatchTypeResult(fb); // Could pass: munger.getPointcut().toString(),info if (fb.maybeTrue()) { result.add(munger); } } return result; } public void setProgressListener(IProgressListener listener, double previousProgress, double progressPerClassFile) { progressListener = listener; this.progressMade = previousProgress; this.progressPerClassFile = progressPerClassFile; } public void setReweavableMode(boolean mode,boolean compress) { inReweavableMode = mode; WeaverStateInfo.setReweavableModeDefaults(mode,compress); BcelClassWeaver.setReweavableMode(mode,compress); } public boolean isReweavable() { return inReweavableMode; } public World getWorld() { return world; } }
102,212
Bug 102212 [itds] abstract synchronized: compile error expected
when using intertype declaration, the compiler doesn't check for illegal modifier combinations such as "abstract synchronized". another manifestation of this problem is when using intertype declaration to add a synchronized method to an interface. the problem is more severe in this case because conceptually, this method is not abstract at all. interface Interface {} abstract class Parent {} class Child extends Parent implements Interface {} aspect Bug { // illegal modifier combination not caught by ajc public abstract synchronized void Parent._abstract(); public synchronized void Child._abstract() {} // the following has the same effect, but is easier to miss public /* implicit abstract */ synchronized void Interface._interface() {} // use Child to make java complain: "illegal modifiers: 0x421" // (this corresponds to "public abstract synchronized") public static void main(String[] args) { new Child(); } }
resolved fixed
b17ff4e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-02T14:38:11Z
2005-06-29T21:20:00Z
tests/src/org/aspectj/systemtest/ajc150/Ajc150Tests.java
/******************************************************************************* * Copyright (c) 2004 IBM * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Andy Clement - initial API and implementation *******************************************************************************/ package org.aspectj.systemtest.ajc150; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import junit.framework.Test; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.apache.bcel.classfile.Method; import org.aspectj.apache.bcel.util.ClassPath; import org.aspectj.apache.bcel.util.SyntheticRepository; import org.aspectj.asm.AsmManager; import org.aspectj.testing.XMLBasedAjcTestCase; import org.aspectj.util.LangUtil; /** * These are tests that will run on Java 1.4 and use the old harness format for test specification. */ public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase { public static Test suite() { return XMLBasedAjcTestCase.loadSuite(Ajc150Tests.class); } protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml"); } public void test_typeProcessingOrderWhenDeclareParents() { runTest("Order of types passed to compiler determines weaving behavior"); } public void test_aroundMethod() { runTest("method called around in class"); } public void test_aroundMethodAspect() { runTest("method called around in aspect"); } public void test_ambiguousBindingsDetection() { runTest("Various kinds of ambiguous bindings"); } public void test_ambiguousArgsDetection() { runTest("ambiguous args"); } public void testIncorrectExceptionTableWhenBreakInMethod_pr78021() { runTest("Injecting exception into while loop with break statement causes catch block to be ignored"); } public void testIncorrectExceptionTableWhenReturnInMethod_pr79554() { runTest("Return in try-block disables catch-block if final-block is present"); } public void testMissingDebugInfoForGeneratedMethods_pr82570() throws ClassNotFoundException { runTest("Weaved code does not include debug lines"); boolean f = false; JavaClass jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1"); Method[] meths = jc.getMethods(); for (int i = 0; i < meths.length; i++) { Method method = meths[i]; if (f) System.err.println("Line number table for "+method.getName()+method.getSignature()+" = "+method.getLineNumberTable()); assertTrue("Didn't find a line number table for method "+method.getName()+method.getSignature(), method.getLineNumberTable()!=null); } // This test would determine the info isn't there if you pass -g:none ... // cR = ajc(baseDir,new String[]{"PR82570_1.java","-g:none"}); // assertTrue("Expected no compile problem:"+cR,!cR.hasErrorMessages()); // System.err.println(cR.getStandardError()); // jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1"); // meths = jc.getMethods(); // for (int i = 0; i < meths.length; i++) { // Method method = meths[i]; // assertTrue("Found a line number table for method "+method.getName(), // method.getLineNumberTable()==null); // } } public void testCanOverrideProtectedMethodsViaITDandDecp_pr83303() { runTest("compiler error when mixing inheritance, overriding and polymorphism"); } public void testPerTypeWithinMissesNamedInnerTypes() { runTest("pertypewithin() handing of inner classes (1)"); } public void testPerTypeWithinMissesAnonymousInnerTypes() { runTest("pertypewithin() handing of inner classes (2)"); } public void testPerTypeWithinIncorrectlyMatchingInterfaces() { runTest("pertypewithin({interface}) illegal field modifier"); } public void test051_arrayCloningInJava5() { runTest("AJC possible bug with static nested classes"); } public void testBadASMforEnums() throws IOException { runTest("bad asm for enums"); if (LangUtil.is15VMOrGreater()) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintWriter pw = new PrintWriter(baos); AsmManager.dumptree(pw,AsmManager.getDefault().getHierarchy().getRoot(),0); pw.flush(); String tree = baos.toString(); assertTrue("Expected 'Red [enumvalue]' somewhere in here:"+tree,tree.indexOf("Red [enumvalue]")!=-1); } } public void npeOnTypeNotFound() { runTest("structure model npe on type not found"); } public void testNoRuntimeExceptionSoftening() { runTest("declare soft of runtime exception"); } public void testRuntimeNoSoftenWithHandler() { runTest("declare soft w. catch block"); } public void testSyntaxError() { runTest("invalid cons syntax"); } public void testVarargsInConsBug() { runTest("varargs in constructor sig"); } public void testAspectpathdirs() { runTest("dirs on aspectpath"); } public void testIntroSample() { runTest("introduction sample"); } public void testPTWInterface() { runTest("pertypewithin({interface}) illegal field modifier"); } public void testEnumCalledEnumEtc() { runTest("enum called Enum, annotation called Annotation, etc"); } public void testInternalCompilerError_pr86832() { runTest("Internal compiler error"); } public void testCloneMethod_pr83311() { runTest("overriding/polymorphism error on interface method introduction"); } /** * IfPointcut.findResidueInternal() was modified to make this test complete in a short amount * of time - if you see it hanging, someone has messed with the optimization. */ public void testIfEvaluationExplosion_pr94086() { runTest("Exploding compile time with if() statements in pointcut"); } public void testReflectNPE_pr94167() {runTest("NPE in reflect implementation");} public void testStaticImports_pr84260() {runTest("static import failures");} public void testGenerics_pr99089() {runTest("ArrayIndexOutOfBoundsException - Generics in privileged aspects");} public void testGenerics_pr95993() {runTest("NPE at ClassScope.java:660 when compiling generic class");} public void testItdGenerics_pr99228() {runTest("ITD of a field into a generic class");} public void testItdGenerics_pr98320() {runTest("intertype with nested generic type");} public void testItdGenerics_pr100227() {runTest("inner class with generic enclosing class");} public void testItdGenerics_pr100260() {runTest("methods inherited from a generic parent");} public void testSyntaxErrorNPE_pr103266() {runTest("NPE on syntax error");} public void testIllegalStateExceptionOnNestedParameterizedType_pr106634() { runTest("IllegalStateException unpacking signature of nested parameterized type"); } public void testParseErrorOnAnnotationStarPlusPattern() { runTest("(@Foo *)+ type pattern parse error"); } public void test_pr106130_tooManyLocals() { runTest("test weaving with > 256 locals"); } public void testMissingNamePattern_pr106461() { runTest("missing name pattern"); } public void testMissingNamePattern_pr107059() { runTest("parser crashes on call(void (@a *)(..)"); } public void testIntermediateAnnotationMatching() { runTest("intermediate annotation matching"); } public void testBadRuntimeTestGeneration() { runTest("target(@Foo *)"); } public void testErrorMessageOnITDWithTypePatterns() { runTest("clear error message on itd with type pattern"); } public void testAjKeywordsAsIdentifiers() { runTest("before and after are valid identifiers in classes"); } public void testAjKeywordsAsIdentifiers2() { runTest("before and after are valid identifiers in classes, part 2"); } public void testNoBeforeReturningAdvice() { runTest("before returning advice not allowed!"); } public void testDetectVoidFieldType() { runTest("void field type in pointcut expression"); } public void testPointcutOverriding() { runTest("overriding final pointcut from super-aspect"); } public void testAtSuppressWarnings() { runTest("@SuppressWarnings should suppress"); } public void testDEOWWithBindingPointcut() { runTest("declare warning : foo(str) : ...;"); } public void testAroundAdviceAndInterfaceInitializer() { runTest("around advice on interface initializer"); } public void testGoodErrorMessageOnUnmatchedMemberSyntax() { runTest("good error message for unmatched member syntax"); } public void testITDWithNoExceptionAndIntermediary() { runTest("itd override with no exception clause"); } public void testAnonymousInnerClasses() { runTest("anonymous inner classes"); } public void testMultipleAnonymousInnerClasses() { runTest("multiple anonymous inner classes"); } public void testPrivilegedMethodAccessorsGetRightExceptions_pr82989() { runTest("Compiler error due to a wrong exception check in try blocks"); } public void testAnonymousInnerClassWithMethodReturningTypeParameter_pr107898() { runTest("anonymous inner class with method returning type parameter"); } public void testMatchingOfObjectArray() { runTest("matching against Object[]"); } public void testMultipleAnonymousInnerClasses_pr108104() { runTest("multiple anonymous inner classes 2"); } public void testSignatureMatchingInMultipleOverrideScenario() { runTest("signature matching in override scenario"); } public void testWildcardAnnotationMatching_pr108245() { runTest("wildcard annotation matching - pr108245"); } public void testInnerTypesAndTypeVariables() { runTest("inner types and type variables"); } public void testAtAfterThrowingWithNoFormal() { runTest("@AfterThrowing with no formal specified"); } public void testParameterizedVarArgsMatch() { runTest("varargs with type variable"); } public void testFieldAccessInsideITDM() { runTest("itd field access inside itd method"); } public void testTypeVarWithTypeVarBound() { runTest("type variable with type variable bound"); } public void testEnumSwitchInITD() { runTest("switch on enum inside ITD method"); } public void testInnerTypeOfGeneric() { runTest("inner type of generic interface reference from parameterized type"); } public void testDeclareParentsIntroducingCovariantReturnType() { runTest("declare parents introducing override with covariance"); } public void testInnerClassPassedToVarargs() { runTest("inner class passed as argument to varargs method"); } public void testInlinedFieldAccessInProceedCall() { runTest("inlined field access in proceed call"); } public void testVisibiltyInSignatureMatchingWithOverridesPart1() { runTest("visibility in signature matching with overrides - 1"); } public void testVisibiltyInSignatureMatchingWithOverridesPart2() { runTest("visibility in signature matching with overrides - 2"); } public void testVisibiltyInSignatureMatchingWithOverridesPart3() { runTest("visibility in signature matching with overrides - 3"); } public void testArgsGeneratedCorrectlyForAdviceExecution() { runTest("args generated correctly for advice execution join point"); } public void testNoUnusedWarningsOnAspectTypes() { runTest("no unused warnings on aspect types"); } public void testSyntheticArgumentsOnITDConstructorsNotUsedInMatching() { runTest("synthetic arguments on itd cons are not used in matching"); } public void testParsingOfGenericTypeSignature() { runTest("parse generic type signature with parameterized type in interface"); } public void testOverrideAndCovarianceWithDecPRuntime() { runTest("override and covariance with decp - runtime"); } public void testOverrideAndCovarianceWithDecPRuntimeMultiFiles() { runTest("override and covariance with decp - runtime separate files"); } public void testAbstractSynchronizedITDMethods() { runTest("abstract synchronized itdms not detected"); } // helper methods..... public SyntheticRepository createRepos(File cpentry) { ClassPath cp = new ClassPath(cpentry+File.pathSeparator+System.getProperty("java.class.path")); return SyntheticRepository.getInstance(cp); } protected JavaClass getClassFrom(File where,String clazzname) throws ClassNotFoundException { SyntheticRepository repos = createRepos(where); return repos.loadClass(clazzname); } }
102,212
Bug 102212 [itds] abstract synchronized: compile error expected
when using intertype declaration, the compiler doesn't check for illegal modifier combinations such as "abstract synchronized". another manifestation of this problem is when using intertype declaration to add a synchronized method to an interface. the problem is more severe in this case because conceptually, this method is not abstract at all. interface Interface {} abstract class Parent {} class Child extends Parent implements Interface {} aspect Bug { // illegal modifier combination not caught by ajc public abstract synchronized void Parent._abstract(); public synchronized void Child._abstract() {} // the following has the same effect, but is easier to miss public /* implicit abstract */ synchronized void Interface._interface() {} // use Child to make java complain: "illegal modifiers: 0x421" // (this corresponds to "public abstract synchronized") public static void main(String[] args) { new Child(); } }
resolved fixed
b17ff4e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-02T14:38:11Z
2005-06-29T21:20:00Z
weaver/src/org/aspectj/weaver/bcel/BcelTypeMunger.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.bcel; import java.lang.reflect.Modifier; import java.util.Iterator; import java.util.List; import java.util.Set; import org.aspectj.apache.bcel.Constants; import org.aspectj.apache.bcel.classfile.annotation.Annotation; import org.aspectj.apache.bcel.generic.ConstantPoolGen; import org.aspectj.apache.bcel.generic.FieldGen; import org.aspectj.apache.bcel.generic.INVOKESPECIAL; import org.aspectj.apache.bcel.generic.InstructionConstants; import org.aspectj.apache.bcel.generic.InstructionFactory; import org.aspectj.apache.bcel.generic.InstructionHandle; import org.aspectj.apache.bcel.generic.InstructionList; import org.aspectj.apache.bcel.generic.Type; import org.aspectj.apache.bcel.generic.annotation.AnnotationGen; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; import org.aspectj.bridge.WeaveMessage; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.AnnotationOnTypeMunger; import org.aspectj.weaver.AnnotationX; import org.aspectj.weaver.AsmRelationshipProvider; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ConcreteTypeMunger; import org.aspectj.weaver.Member; import org.aspectj.weaver.NameMangler; import org.aspectj.weaver.NewConstructorTypeMunger; import org.aspectj.weaver.NewFieldTypeMunger; import org.aspectj.weaver.NewMethodTypeMunger; import org.aspectj.weaver.NewParentTypeMunger; import org.aspectj.weaver.PerObjectInterfaceTypeMunger; import org.aspectj.weaver.PrivilegedAccessMunger; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.ResolvedTypeMunger; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.WeaverStateInfo; import org.aspectj.weaver.AjAttribute.EffectiveSignatureAttribute; import org.aspectj.weaver.patterns.DeclareAnnotation; import org.aspectj.weaver.patterns.Pointcut; //XXX addLazyMethodGen is probably bad everywhere public class BcelTypeMunger extends ConcreteTypeMunger { public BcelTypeMunger(ResolvedTypeMunger munger, ResolvedType aspectType) { super(munger, aspectType); } public String toString() { return "(BcelTypeMunger " + getMunger() + ")"; } public boolean munge(BcelClassWeaver weaver) { boolean changed = false; boolean worthReporting = true; if (munger.getKind() == ResolvedTypeMunger.Field) { changed = mungeNewField(weaver, (NewFieldTypeMunger)munger); } else if (munger.getKind() == ResolvedTypeMunger.Method) { changed = mungeNewMethod(weaver, (NewMethodTypeMunger)munger); } else if (munger.getKind() == ResolvedTypeMunger.PerObjectInterface) { changed = mungePerObjectInterface(weaver, (PerObjectInterfaceTypeMunger)munger); worthReporting = false; } else if (munger.getKind() == ResolvedTypeMunger.PerTypeWithinInterface) { // PTWIMPL Transform the target type (add the aspect instance field) changed = mungePerTypeWithinTransformer(weaver); worthReporting = false; } else if (munger.getKind() == ResolvedTypeMunger.PrivilegedAccess) { changed = mungePrivilegedAccess(weaver, (PrivilegedAccessMunger)munger); worthReporting = false; } else if (munger.getKind() == ResolvedTypeMunger.Constructor) { changed = mungeNewConstructor(weaver, (NewConstructorTypeMunger)munger); } else if (munger.getKind() == ResolvedTypeMunger.Parent) { changed = mungeNewParent(weaver, (NewParentTypeMunger)munger); } else if (munger.getKind() == ResolvedTypeMunger.AnnotationOnType) { changed = mungeNewAnnotationOnType(weaver,(AnnotationOnTypeMunger)munger); } else { throw new RuntimeException("unimplemented"); } if (changed && munger.changesPublicSignature()) { WeaverStateInfo info = weaver.getLazyClassGen().getOrCreateWeaverStateInfo(); info.addConcreteMunger(this); } // Whilst type mungers aren't persisting their source locations, we add this relationship during // compilation time (see other reference to ResolvedTypeMunger.persist) if (ResolvedTypeMunger.persistSourceLocation) { if (changed && worthReporting) { if (munger.getKind().equals(ResolvedTypeMunger.Parent)) { AsmRelationshipProvider.getDefault().addRelationship(weaver.getLazyClassGen().getType(), munger,getAspectType()); } else { AsmRelationshipProvider.getDefault().addRelationship(weaver.getLazyClassGen().getType(), munger,getAspectType()); } } } // TAG: WeavingMessage if (changed && worthReporting && munger!=null && !weaver.getWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)) { String tName = weaver.getLazyClassGen().getType().getSourceLocation().getSourceFile().getName(); if (tName.indexOf("no debug info available")!=-1) tName = "no debug info available"; else tName = getShortname(weaver.getLazyClassGen().getType().getSourceLocation().getSourceFile().getPath()); String fName = getShortname(getAspectType().getSourceLocation().getSourceFile().getPath()); if (munger.getKind().equals(ResolvedTypeMunger.Parent)) { // This message could come out of AjLookupEnvironment.addParent if doing parents // munging at compile time only... NewParentTypeMunger parentTM = (NewParentTypeMunger)munger; if (parentTM.getNewParent().isInterface()) { weaver.getWorld().getMessageHandler().handleMessage(WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_DECLAREPARENTSIMPLEMENTS, new String[]{weaver.getLazyClassGen().getType().getName(), tName,parentTM.getNewParent().getName(),fName}, weaver.getLazyClassGen().getClassName(), getAspectType().getName())); } else { weaver.getWorld().getMessageHandler().handleMessage( WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_DECLAREPARENTSEXTENDS, new String[]{weaver.getLazyClassGen().getType().getName(), tName,parentTM.getNewParent().getName(),fName })); // TAG: WeavingMessage DECLARE PARENTS: EXTENDS // reportDeclareParentsMessage(WeaveMessage.WEAVEMESSAGE_DECLAREPARENTSEXTENDS,sourceType,parent); } } else { weaver.getWorld().getMessageHandler().handleMessage(WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_ITD, new String[]{weaver.getLazyClassGen().getType().getName(), tName,munger.getKind().toString().toLowerCase(), getAspectType().getName(), fName+":'"+munger.getSignature()+"'"}, weaver.getLazyClassGen().getClassName(), getAspectType().getName())); } } return changed; } private String getShortname(String path) { int takefrom = path.lastIndexOf('/'); if (takefrom == -1) { takefrom = path.lastIndexOf('\\'); } return path.substring(takefrom+1); } private boolean mungeNewAnnotationOnType(BcelClassWeaver weaver,AnnotationOnTypeMunger munger) { // FIXME asc this has already been done up front, need to do it here too? weaver.getLazyClassGen().addAnnotation(munger.getNewAnnotation().getBcelAnnotation()); return true; } /** * For a long time, AspectJ did not allow binary weaving of declare parents. This restriction is now lifted * but could do with more testing! */ private boolean mungeNewParent(BcelClassWeaver weaver, NewParentTypeMunger munger) { LazyClassGen newParentTarget = weaver.getLazyClassGen(); ResolvedType newParent = munger.getNewParent(); boolean cont = true; // Set to false when we error, so we don't actually *do* the munge cont = enforceDecpRule1_abstractMethodsImplemented(weaver, munger.getSourceLocation(),newParentTarget, newParent); cont = enforceDecpRule2_cantExtendFinalClass(weaver,munger.getSourceLocation(),newParentTarget,newParent) && cont; List methods = newParent.getMethodsWithoutIterator(false); for (Iterator iter = methods.iterator(); iter.hasNext();) { ResolvedMember superMethod = (ResolvedMember) iter.next(); if (!superMethod.getName().equals("<init>")) { LazyMethodGen subMethod = findMatchingMethod(newParentTarget, superMethod); if (subMethod!=null) { cont = enforceDecpRule3_visibilityChanges(weaver, newParent, superMethod, subMethod) && cont; cont = enforceDecpRule4_compatibleReturnTypes(weaver, superMethod, subMethod) && cont; cont = enforceDecpRule5_cantChangeFromStaticToNonstatic(weaver,munger.getSourceLocation(),superMethod,subMethod) && cont; } } } if (!cont) return false; // A rule was violated and an error message already reported if (newParent.isClass()) { // Changing the supertype if (!attemptToModifySuperCalls(weaver,newParentTarget,newParent)) return false; newParentTarget.setSuperClass(newParent); } else { // Adding a new interface newParentTarget.addInterface(newParent,getSourceLocation()); } return true; } /** * Rule 1: For the declare parents to be allowed, the target type must override and implement * inherited abstract methods (if the type is not declared abstract) */ private boolean enforceDecpRule1_abstractMethodsImplemented(BcelClassWeaver weaver, ISourceLocation mungerLoc,LazyClassGen newParentTarget, ResolvedType newParent) { boolean ruleCheckingSucceeded = true; if (!(newParentTarget.isAbstract() || newParentTarget.isInterface())) { // Ignore abstract classes or interfaces List methods = newParent.getMethodsWithoutIterator(false); for (Iterator i = methods.iterator(); i.hasNext();) { ResolvedMember o = (ResolvedMember)i.next(); if (o.isAbstract() && !o.getName().startsWith("ajc$interField")) { // Ignore abstract methods of ajc$interField prefixed methods ResolvedMember discoveredImpl = null; List newParentTargetMethods = newParentTarget.getType().getMethodsWithoutIterator(false); for (Iterator ii = newParentTargetMethods.iterator(); ii.hasNext() && discoveredImpl==null;) { ResolvedMember gen2 = (ResolvedMember) ii.next(); if (gen2.getName().equals(o.getName()) && gen2.getParameterSignature().equals(o.getParameterSignature()) && !gen2.isAbstract()) { discoveredImpl = gen2; // Found a valid implementation ! } } if (discoveredImpl == null) { // didnt find a valid implementation, lets check the ITDs on this type to see if they satisfy it boolean satisfiedByITD = false; for (Iterator ii = newParentTarget.getType().getInterTypeMungersIncludingSupers().iterator(); ii.hasNext(); ) { ConcreteTypeMunger m = (ConcreteTypeMunger)ii.next(); if (m.getMunger() instanceof NewMethodTypeMunger) { ResolvedMember sig = m.getSignature(); if (!Modifier.isAbstract(sig.getModifiers())) { if (ResolvedType .matches( AjcMemberMaker.interMethod( sig,m.getAspectType(),sig.getDeclaringType().resolve(weaver.getWorld()).isInterface()),o)) { satisfiedByITD = true; } } } } if (!satisfiedByITD) { error(weaver, "The type " + newParentTarget.getName() + " must implement the inherited abstract method "+o.getDeclaringType()+"."+o.getName()+o.getParameterSignature(), newParentTarget.getType().getSourceLocation(),new ISourceLocation[]{o.getSourceLocation(),mungerLoc}); ruleCheckingSucceeded=false; } } } } } return ruleCheckingSucceeded; } /** * Rule 2. Can't extend final types */ private boolean enforceDecpRule2_cantExtendFinalClass(BcelClassWeaver weaver, ISourceLocation mungerLoc, LazyClassGen newParentTarget, ResolvedType newParent) { if (newParent.isFinal()) { error(weaver,"Cannot make type "+newParentTarget.getName()+" extend final class "+newParent.getName(), newParentTarget.getType().getSourceLocation(), new ISourceLocation[]{mungerLoc}); return false; } return true; } /** * Rule 3. Can't narrow visibility of methods when overriding */ private boolean enforceDecpRule3_visibilityChanges(BcelClassWeaver weaver, ResolvedType newParent, ResolvedMember superMethod, LazyMethodGen subMethod) { boolean cont = true; if (superMethod.isPublic()) { if (subMethod.isProtected() || subMethod.isDefault() || subMethod.isPrivate()) { weaver.getWorld().getMessageHandler().handleMessage(MessageUtil.error( "Cannot reduce the visibility of the inherited method '"+superMethod+"' from "+newParent.getName(), superMethod.getSourceLocation())); cont=false; } } else if (superMethod.isProtected()) { if (subMethod.isDefault() || subMethod.isPrivate()) { weaver.getWorld().getMessageHandler().handleMessage(MessageUtil.error( "Cannot reduce the visibility of the inherited method '"+superMethod+"' from "+newParent.getName(), superMethod.getSourceLocation())); cont=false; } } else if (superMethod.isDefault()) { if (subMethod.isPrivate()) { weaver.getWorld().getMessageHandler().handleMessage(MessageUtil.error( "Cannot reduce the visibility of the inherited method '"+superMethod+"' from "+newParent.getName(), superMethod.getSourceLocation())); cont=false; } } return cont; } /** * Rule 4. Can't have incompatible return types */ private boolean enforceDecpRule4_compatibleReturnTypes(BcelClassWeaver weaver, ResolvedMember superMethod, LazyMethodGen subMethod) { boolean cont = true; String superReturnTypeSig = superMethod.getReturnType().getSignature(); String subReturnTypeSig = subMethod.getReturnType().getSignature(); if (!superReturnTypeSig.equals(subReturnTypeSig)) { // Allow for covariance - wish I could test this (need Java5...) ResolvedType subType = weaver.getWorld().resolve(subMethod.getReturnType()); ResolvedType superType = weaver.getWorld().resolve(superMethod.getReturnType()); if (!superType.isAssignableFrom(subType)) { ISourceLocation sloc = subMethod.getSourceLocation(); weaver.getWorld().getMessageHandler().handleMessage(MessageUtil.error( "The return type is incompatible with "+superMethod.getDeclaringType()+"."+superMethod.getName()+superMethod.getParameterSignature(), subMethod.getSourceLocation())); cont=false; } } return cont; } /** * Rule5. Method overrides can't change the staticality (word?) - you can't override and make an instance * method static or override and make a static method an instance method. */ private boolean enforceDecpRule5_cantChangeFromStaticToNonstatic(BcelClassWeaver weaver,ISourceLocation mungerLoc,ResolvedMember superMethod, LazyMethodGen subMethod ) { if (superMethod.isStatic() && !subMethod.isStatic()) { error(weaver,"This instance method "+subMethod.getName()+subMethod.getParameterSignature()+ " cannot override the static method from "+superMethod.getDeclaringType().getName(), subMethod.getSourceLocation(),new ISourceLocation[]{mungerLoc}); return false; } else if (!superMethod.isStatic() && subMethod.isStatic()) { error(weaver,"The static method "+subMethod.getName()+subMethod.getParameterSignature()+ " cannot hide the instance method from "+superMethod.getDeclaringType().getName(), subMethod.getSourceLocation(),new ISourceLocation[]{mungerLoc}); return false; } return true; } public void error(BcelClassWeaver weaver,String text,ISourceLocation primaryLoc,ISourceLocation[] extraLocs) { IMessage msg = new Message(text, primaryLoc, true, extraLocs); weaver.getWorld().getMessageHandler().handleMessage(msg); } private LazyMethodGen findMatchingMethod(LazyClassGen newParentTarget, ResolvedMember m) { LazyMethodGen found = null; // Search the type for methods overriding super methods (methods that come from the new parent) // Don't use the return value in the comparison as overriding doesnt for (Iterator i = newParentTarget.getMethodGens().iterator(); i.hasNext() && found==null;) { LazyMethodGen gen = (LazyMethodGen) i.next(); if (gen.getName().equals(m.getName()) && gen.getParameterSignature().equals(m.getParameterSignature())) { found = gen; } } return found; } /** * The main part of implementing declare parents extends. Modify super ctor calls to target the new type. */ public boolean attemptToModifySuperCalls(BcelClassWeaver weaver,LazyClassGen newParentTarget, ResolvedType newParent) { String currentParent = newParentTarget.getSuperClassname(); List mgs = newParentTarget.getMethodGens(); // Look for ctors to modify for (Iterator iter = mgs.iterator(); iter.hasNext();) { LazyMethodGen aMethod = (LazyMethodGen) iter.next(); if (aMethod.getName().equals("<init>")) { InstructionList insList = aMethod.getBody(); InstructionHandle handle = insList.getStart(); while (handle!= null) { if (handle.getInstruction() instanceof INVOKESPECIAL) { ConstantPoolGen cpg = newParentTarget.getConstantPoolGen(); INVOKESPECIAL invokeSpecial = (INVOKESPECIAL)handle.getInstruction(); if (invokeSpecial.getClassName(cpg).equals(currentParent) && invokeSpecial.getMethodName(cpg).equals("<init>")) { // System.err.println("Transforming super call '<init>"+sp.getSignature(cpg)+"'"); // 1. Check there is a ctor in the new parent with the same signature ResolvedMember newCtor = getConstructorWithSignature(newParent,invokeSpecial.getSignature(cpg)); if (newCtor == null) { // 2. Check ITDCs to see if the necessary ctor is provided that way boolean satisfiedByITDC = false; for (Iterator ii = newParentTarget.getType().getInterTypeMungersIncludingSupers().iterator(); ii.hasNext() && !satisfiedByITDC; ) { ConcreteTypeMunger m = (ConcreteTypeMunger)ii.next(); if (m.getMunger() instanceof NewConstructorTypeMunger) { if (m.getSignature().getSignature().equals(invokeSpecial.getSignature(cpg))) { satisfiedByITDC = true; } } } if (!satisfiedByITDC) { String csig = createReadableCtorSig(newParent, cpg, invokeSpecial); weaver.getWorld().getMessageHandler().handleMessage(MessageUtil.error( "Unable to modify hierarchy for "+newParentTarget.getClassName()+" - the constructor "+ csig+" is missing",this.getSourceLocation())); return false; } } int idx = cpg.addMethodref(newParent.getClassName(), invokeSpecial.getMethodName(cpg), invokeSpecial.getSignature(cpg)); invokeSpecial.setIndex(idx); } } handle = handle.getNext(); } } } return true; } /** * Creates a nice signature for the ctor, something like "(int,Integer,String)" */ private String createReadableCtorSig(ResolvedType newParent, ConstantPoolGen cpg, INVOKESPECIAL invokeSpecial) { StringBuffer sb = new StringBuffer(); Type[] ctorArgs = invokeSpecial.getArgumentTypes(cpg); sb.append(newParent.getClassName()); sb.append("("); for (int i = 0; i < ctorArgs.length; i++) { String argtype = ctorArgs[i].toString(); if (argtype.lastIndexOf(".")!=-1) sb.append(argtype.substring(argtype.lastIndexOf(".")+1)); else sb.append(argtype); if (i+1<ctorArgs.length) sb.append(","); } sb.append(")"); return sb.toString(); } private ResolvedMember getConstructorWithSignature(ResolvedType tx,String signature) { ResolvedMember[] mems = tx.getDeclaredJavaMethods(); for (int i = 0; i < mems.length; i++) { ResolvedMember rm = mems[i]; if (rm.getName().equals("<init>")) { if (rm.getSignature().equals(signature)) return rm; } } return null; } private boolean mungePrivilegedAccess( BcelClassWeaver weaver, PrivilegedAccessMunger munger) { LazyClassGen gen = weaver.getLazyClassGen(); ResolvedMember member = munger.getMember(); ResolvedType onType = weaver.getWorld().resolve(member.getDeclaringType(),munger.getSourceLocation()); if (onType.isRawType()) onType = onType.getGenericType(); //System.out.println("munging: " + gen + " with " + member); if (onType.equals(gen.getType())) { if (member.getKind() == Member.FIELD) { //System.out.println("matched: " + gen); addFieldGetter(gen, member, AjcMemberMaker.privilegedAccessMethodForFieldGet(aspectType, member)); addFieldSetter(gen, member, AjcMemberMaker.privilegedAccessMethodForFieldSet(aspectType, member)); return true; } else if (member.getKind() == Member.METHOD) { addMethodDispatch(gen, member, AjcMemberMaker.privilegedAccessMethodForMethod(aspectType, member)); return true; } else if (member.getKind() == Member.CONSTRUCTOR) { for (Iterator i = gen.getMethodGens().iterator(); i.hasNext(); ) { LazyMethodGen m = (LazyMethodGen)i.next(); if (m.getMemberView() != null && m.getMemberView().getKind() == Member.CONSTRUCTOR) { // m.getMemberView().equals(member)) { m.forcePublic(); //return true; } } return true; //throw new BCException("no match for " + member + " in " + gen); } else if (member.getKind() == Member.STATIC_INITIALIZATION) { gen.forcePublic(); return true; } else { throw new RuntimeException("unimplemented"); } } return false; } private void addFieldGetter( LazyClassGen gen, ResolvedMember field, ResolvedMember accessMethod) { LazyMethodGen mg = makeMethodGen(gen, accessMethod); InstructionList il = new InstructionList(); InstructionFactory fact = gen.getFactory(); if (field.isStatic()) { il.append(fact.createFieldAccess( gen.getClassName(), field.getName(), BcelWorld.makeBcelType(field.getType()), Constants.GETSTATIC)); } else { il.append(InstructionConstants.ALOAD_0); il.append(fact.createFieldAccess( gen.getClassName(), field.getName(), BcelWorld.makeBcelType(field.getType()), Constants.GETFIELD)); } il.append(InstructionFactory.createReturn(BcelWorld.makeBcelType(field.getType()))); mg.getBody().insert(il); gen.addMethodGen(mg,getSignature().getSourceLocation()); } private void addFieldSetter( LazyClassGen gen, ResolvedMember field, ResolvedMember accessMethod) { LazyMethodGen mg = makeMethodGen(gen, accessMethod); InstructionList il = new InstructionList(); InstructionFactory fact = gen.getFactory(); Type fieldType = BcelWorld.makeBcelType(field.getType()); if (field.isStatic()) { il.append(InstructionFactory.createLoad(fieldType, 0)); il.append(fact.createFieldAccess( gen.getClassName(), field.getName(), fieldType, Constants.PUTSTATIC)); } else { il.append(InstructionConstants.ALOAD_0); il.append(InstructionFactory.createLoad(fieldType, 1)); il.append(fact.createFieldAccess( gen.getClassName(), field.getName(), fieldType, Constants.PUTFIELD)); } il.append(InstructionFactory.createReturn(Type.VOID)); mg.getBody().insert(il); gen.addMethodGen(mg,getSignature().getSourceLocation()); } private void addMethodDispatch( LazyClassGen gen, ResolvedMember method, ResolvedMember accessMethod) { LazyMethodGen mg = makeMethodGen(gen, accessMethod); InstructionList il = new InstructionList(); InstructionFactory fact = gen.getFactory(); //Type fieldType = BcelWorld.makeBcelType(field.getType()); Type[] paramTypes = BcelWorld.makeBcelTypes(method.getParameterTypes()); int pos = 0; if (!method.isStatic()) { il.append(InstructionConstants.ALOAD_0); pos++; } for (int i = 0, len = paramTypes.length; i < len; i++) { Type paramType = paramTypes[i]; il.append(InstructionFactory.createLoad(paramType, pos)); pos+=paramType.getSize(); } il.append(Utility.createInvoke(fact, (BcelWorld)aspectType.getWorld(), method)); il.append(InstructionFactory.createReturn(BcelWorld.makeBcelType(method.getReturnType()))); mg.getBody().insert(il); gen.addMethodGen(mg); } protected LazyMethodGen makeMethodGen(LazyClassGen gen, ResolvedMember member) { LazyMethodGen ret = new LazyMethodGen( member.getModifiers(), BcelWorld.makeBcelType(member.getReturnType()), member.getName(), BcelWorld.makeBcelTypes(member.getParameterTypes()), UnresolvedType.getNames(member.getExceptions()), gen); // 43972 : Static crosscutting makes interfaces unusable for javac // ret.makeSynthetic(); return ret; } protected FieldGen makeFieldGen(LazyClassGen gen, ResolvedMember member) { return new FieldGen( member.getModifiers(), BcelWorld.makeBcelType(member.getReturnType()), member.getName(), gen.getConstantPoolGen()); } private boolean mungePerObjectInterface( BcelClassWeaver weaver, PerObjectInterfaceTypeMunger munger) { LazyClassGen gen = weaver.getLazyClassGen(); if (couldMatch(gen.getBcelObjectType(), munger.getTestPointcut())) { FieldGen fg = makeFieldGen(gen, AjcMemberMaker.perObjectField(gen.getType(), aspectType)); gen.addField(fg.getField(),getSourceLocation()); Type fieldType = BcelWorld.makeBcelType(aspectType); LazyMethodGen mg = new LazyMethodGen( Modifier.PUBLIC, fieldType, NameMangler.perObjectInterfaceGet(aspectType), new Type[0], new String[0], gen); InstructionList il = new InstructionList(); InstructionFactory fact = gen.getFactory(); il.append(InstructionConstants.ALOAD_0); il.append(fact.createFieldAccess( gen.getClassName(), fg.getName(), fieldType, Constants.GETFIELD)); il.append(InstructionFactory.createReturn(fieldType)); mg.getBody().insert(il); gen.addMethodGen(mg); LazyMethodGen mg1 = new LazyMethodGen( Modifier.PUBLIC, Type.VOID, NameMangler.perObjectInterfaceSet(aspectType), new Type[]{fieldType,}, new String[0], gen); InstructionList il1 = new InstructionList(); il1.append(InstructionConstants.ALOAD_0); il1.append(InstructionFactory.createLoad(fieldType, 1)); il1.append(fact.createFieldAccess( gen.getClassName(), fg.getName(), fieldType, Constants.PUTFIELD)); il1.append(InstructionFactory.createReturn(Type.VOID)); mg1.getBody().insert(il1); gen.addMethodGen(mg1); gen.addInterface(munger.getInterfaceType(),getSourceLocation()); return true; } else { return false; } } // PTWIMPL Add field to hold aspect instance and an accessor private boolean mungePerTypeWithinTransformer(BcelClassWeaver weaver) { LazyClassGen gen = weaver.getLazyClassGen(); // if (couldMatch(gen.getBcelObjectType(), munger.getTestPointcut())) { // Add (to the target type) the field that will hold the aspect instance // e.g ajc$com_blah_SecurityAspect$ptwAspectInstance FieldGen fg = makeFieldGen(gen, AjcMemberMaker.perTypeWithinField(gen.getType(), aspectType)); gen.addField(fg.getField(),getSourceLocation()); // Add an accessor for this new field, the ajc$<aspectname>$localAspectOf() method // e.g. "public com_blah_SecurityAspect ajc$com_blah_SecurityAspect$localAspectOf()" Type fieldType = BcelWorld.makeBcelType(aspectType); LazyMethodGen mg = new LazyMethodGen( Modifier.PUBLIC | Modifier.STATIC,fieldType, NameMangler.perTypeWithinLocalAspectOf(aspectType), new Type[0], new String[0],gen); InstructionList il = new InstructionList(); //PTWIMPL ?? Should check if it is null and throw NoAspectBoundException InstructionFactory fact = gen.getFactory(); il.append(fact.createFieldAccess( gen.getClassName(), fg.getName(), fieldType, Constants.GETSTATIC)); il.append(InstructionFactory.createReturn(fieldType)); mg.getBody().insert(il); gen.addMethodGen(mg); return true; // } else { // return false; // } } // ??? Why do we have this method? I thought by now we would know if it matched or not private boolean couldMatch( BcelObjectType bcelObjectType, Pointcut pointcut) { return !bcelObjectType.isInterface(); } private boolean mungeNewMethod(BcelClassWeaver weaver, NewMethodTypeMunger munger) { ResolvedMember unMangledInterMethod = munger.getSignature(); // do matching on the unMangled one, but actually add them to the mangled method ResolvedMember interMethodBody = munger.getInterMethodBody(aspectType); ResolvedMember interMethodDispatcher = munger.getInterMethodDispatcher(aspectType); LazyClassGen gen = weaver.getLazyClassGen(); ResolvedType onType = weaver.getWorld().resolve(unMangledInterMethod.getDeclaringType(),munger.getSourceLocation()); if (onType.isRawType()) onType = onType.getGenericType(); boolean onInterface = onType.isInterface(); if (onType.isAnnotation()) { signalError(WeaverMessages.ITDM_ON_ANNOTATION_NOT_ALLOWED,weaver,onType); return false; } if (onType.isEnum()) { signalError(WeaverMessages.ITDM_ON_ENUM_NOT_ALLOWED,weaver,onType); return false; } if (onType.equals(gen.getType())) { ResolvedMember mangledInterMethod = AjcMemberMaker.interMethod(unMangledInterMethod, aspectType, onInterface); LazyMethodGen mg = makeMethodGen(gen, mangledInterMethod); // pr98901 // For copying the annotations across, we have to discover the real member in the aspect // which is holding them. if (weaver.getWorld().isInJava5Mode()){ AnnotationX annotationsOnRealMember[] = null; ResolvedType toLookOn = aspectType; if (aspectType.isRawType()) toLookOn = aspectType.getGenericType(); ResolvedMember realMember = getRealMemberForITDFromAspect(toLookOn,interMethodDispatcher); if (realMember==null) throw new BCException("Couldn't find ITD holder member '"+ interMethodDispatcher+"' on aspect "+aspectType); annotationsOnRealMember = realMember.getAnnotations(); if (annotationsOnRealMember!=null) { for (int i = 0; i < annotationsOnRealMember.length; i++) { AnnotationX annotationX = annotationsOnRealMember[i]; Annotation a = annotationX.getBcelAnnotation(); AnnotationGen ag = new AnnotationGen(a,weaver.getLazyClassGen().getConstantPoolGen(),true); mg.addAnnotation(new AnnotationX(ag.getAnnotation(),weaver.getWorld())); } } // the below loop fixes the very special (and very stupid) // case where an aspect declares an annotation // on an ITD it declared on itself. List allDecams = weaver.getWorld().getDeclareAnnotationOnMethods(); for (Iterator i = allDecams.iterator(); i.hasNext();){ DeclareAnnotation decaMC = (DeclareAnnotation) i.next(); if (decaMC.matches(unMangledInterMethod,weaver.getWorld()) && mg.getEnclosingClass().getType() == aspectType) { mg.addAnnotation(decaMC.getAnnotationX()); } } } if (!onInterface && !Modifier.isAbstract(mangledInterMethod.getModifiers())) { InstructionList body = mg.getBody(); InstructionFactory fact = gen.getFactory(); int pos = 0; if (!unMangledInterMethod.isStatic()) { body.append(InstructionFactory.createThis()); pos++; } Type[] paramTypes = BcelWorld.makeBcelTypes(mangledInterMethod.getParameterTypes()); for (int i = 0, len = paramTypes.length; i < len; i++) { Type paramType = paramTypes[i]; body.append(InstructionFactory.createLoad(paramType, pos)); pos+=paramType.getSize(); } body.append(Utility.createInvoke(fact, weaver.getWorld(), interMethodBody)); body.append( InstructionFactory.createReturn( BcelWorld.makeBcelType(mangledInterMethod.getReturnType()))); } else { //??? this is okay //if (!(mg.getBody() == null)) throw new RuntimeException("bas"); } // XXX make sure to check that we set exceptions properly on this guy. weaver.addLazyMethodGen(mg); weaver.getLazyClassGen().warnOnAddedMethod(mg.getMethod(),getSignature().getSourceLocation()); addNeededSuperCallMethods(weaver, onType, munger.getSuperMethodsCalled()); return true; } else if (onInterface && !Modifier.isAbstract(unMangledInterMethod.getModifiers())) { // This means the 'gen' should be the top most implementor // - if it is *not* then something went wrong after we worked // out that it was the top most implementor (see pr49657) if (!gen.getType().isTopmostImplementor(onType)) { ResolvedType rtx = gen.getType().getTopmostImplementor(onType); if (!rtx.isExposedToWeaver()) { ISourceLocation sLoc = munger.getSourceLocation(); weaver.getWorld().getMessageHandler().handleMessage(MessageUtil.error( WeaverMessages.format(WeaverMessages.ITD_NON_EXPOSED_IMPLEMENTOR,rtx,getAspectType().getName()), (sLoc==null?getAspectType().getSourceLocation():sLoc))); } else { // XXX what does this state mean? // We have incorrectly identified what is the top most implementor and its not because // a type wasn't exposed to the weaver } return false; } else { ResolvedMember mangledInterMethod = AjcMemberMaker.interMethod(unMangledInterMethod, aspectType, false); LazyMethodGen mg = makeMethodGen(gen, mangledInterMethod); Type[] paramTypes = BcelWorld.makeBcelTypes(mangledInterMethod.getParameterTypes()); Type returnType = BcelWorld.makeBcelType(mangledInterMethod.getReturnType()); InstructionList body = mg.getBody(); InstructionFactory fact = gen.getFactory(); int pos = 0; if (!mangledInterMethod.isStatic()) { body.append(InstructionFactory.createThis()); pos++; } for (int i = 0, len = paramTypes.length; i < len; i++) { Type paramType = paramTypes[i]; body.append(InstructionFactory.createLoad(paramType, pos)); pos+=paramType.getSize(); } body.append(Utility.createInvoke(fact, weaver.getWorld(), interMethodBody)); body.append(InstructionFactory.createReturn(returnType)); mg.definingType = onType; weaver.addOrReplaceLazyMethodGen(mg); addNeededSuperCallMethods(weaver, onType, munger.getSuperMethodsCalled()); return true; } } else { return false; } } private ResolvedMember getRealMemberForITDFromAspect(ResolvedType aspectType,ResolvedMember lookingFor) { ResolvedMember aspectMethods[] = aspectType.getDeclaredMethods(); UnresolvedType [] lookingForParams = lookingFor.getParameterTypes(); ResolvedMember realMember = null; for (int i = 0; realMember==null && i < aspectMethods.length; i++) { ResolvedMember member = aspectMethods[i]; if (member.getName().equals(lookingFor.getName())){ UnresolvedType [] memberParams = member.getParameterTypes(); if (memberParams.length == lookingForParams.length){ boolean matchOK = true; for (int j = 0; j < memberParams.length && matchOK; j++){ UnresolvedType memberParam = memberParams[j]; UnresolvedType lookingForParam = lookingForParams[j].resolve(aspectType.getWorld()); if (lookingForParam.isTypeVariableReference()) lookingForParam = lookingForParam.getUpperBound(); if (!memberParam.equals(lookingForParam)){ matchOK=false; } } if (matchOK) realMember = member; } } } return realMember; } private void addNeededSuperCallMethods( BcelClassWeaver weaver, ResolvedType onType, Set neededSuperCalls) { LazyClassGen gen = weaver.getLazyClassGen(); for (Iterator iter = neededSuperCalls.iterator(); iter.hasNext();) { ResolvedMember superMethod = (ResolvedMember) iter.next(); if (weaver.addDispatchTarget(superMethod)) { //System.err.println("super type: " + superMethod.getDeclaringType() + ", " + gen.getType()); boolean isSuper = !superMethod.getDeclaringType().equals(gen.getType()); String dispatchName; if (isSuper) dispatchName = NameMangler.superDispatchMethod(onType, superMethod.getName()); else dispatchName = NameMangler.protectedDispatchMethod( onType, superMethod.getName()); LazyMethodGen dispatcher = makeDispatcher( gen, dispatchName, superMethod, weaver.getWorld(), isSuper); weaver.addLazyMethodGen(dispatcher); } } } private void signalError(String msgid,BcelClassWeaver weaver,UnresolvedType onType) { IMessage msg = MessageUtil.error( WeaverMessages.format(msgid,onType.getName()),getSourceLocation()); weaver.getWorld().getMessageHandler().handleMessage(msg); } private boolean mungeNewConstructor( BcelClassWeaver weaver, NewConstructorTypeMunger newConstructorTypeMunger) { final LazyClassGen currentClass = weaver.getLazyClassGen(); final InstructionFactory fact = currentClass.getFactory(); ResolvedMember newConstructorMember = newConstructorTypeMunger.getSyntheticConstructor(); ResolvedType onType = newConstructorMember.getDeclaringType().resolve(weaver.getWorld()); if (onType.isRawType()) onType = onType.getGenericType(); if (onType.isAnnotation()) { signalError(WeaverMessages.ITDC_ON_ANNOTATION_NOT_ALLOWED,weaver,onType); return false; } if (onType.isEnum()) { signalError(WeaverMessages.ITDC_ON_ENUM_NOT_ALLOWED,weaver,onType); return false; } if (! onType.equals(currentClass.getType())) return false; ResolvedMember explicitConstructor = newConstructorTypeMunger.getExplicitConstructor(); //int declaredParameterCount = newConstructorTypeMunger.getDeclaredParameterCount(); LazyMethodGen mg = makeMethodGen(currentClass, newConstructorMember); mg.setEffectiveSignature(newConstructorTypeMunger.getSignature(),Shadow.ConstructorExecution,true); // pr98901 // For copying the annotations across, we have to discover the real member in the aspect // which is holding them. if (weaver.getWorld().isInJava5Mode()){ ResolvedMember interMethodDispatcher =AjcMemberMaker.postIntroducedConstructor(aspectType,onType,newConstructorTypeMunger.getSignature().getParameterTypes()); AnnotationX annotationsOnRealMember[] = null; ResolvedMember realMember = getRealMemberForITDFromAspect(aspectType,interMethodDispatcher); if (realMember==null) throw new BCException("Couldn't find ITD holder member '"+ interMethodDispatcher+"' on aspect "+aspectType); annotationsOnRealMember = realMember.getAnnotations(); if (annotationsOnRealMember!=null) { for (int i = 0; i < annotationsOnRealMember.length; i++) { AnnotationX annotationX = annotationsOnRealMember[i]; Annotation a = annotationX.getBcelAnnotation(); AnnotationGen ag = new AnnotationGen(a,weaver.getLazyClassGen().getConstantPoolGen(),true); mg.addAnnotation(new AnnotationX(ag.getAnnotation(),weaver.getWorld())); } } // the below loop fixes the very special (and very stupid) // case where an aspect declares an annotation // on an ITD it declared on itself. List allDecams = weaver.getWorld().getDeclareAnnotationOnMethods(); for (Iterator i = allDecams.iterator(); i.hasNext();){ DeclareAnnotation decaMC = (DeclareAnnotation) i.next(); if (decaMC.matches(explicitConstructor,weaver.getWorld()) && mg.getEnclosingClass().getType() == aspectType) { mg.addAnnotation(decaMC.getAnnotationX()); } } } currentClass.addMethodGen(mg); //weaver.addLazyMethodGen(freshConstructor); InstructionList body = mg.getBody(); // add to body: push arts for call to pre, from actual args starting at 1 (skipping this), going to // declared argcount + 1 UnresolvedType[] declaredParams = newConstructorTypeMunger.getSignature().getParameterTypes(); Type[] paramTypes = mg.getArgumentTypes(); int frameIndex = 1; for (int i = 0, len = declaredParams.length; i < len; i++) { body.append(InstructionFactory.createLoad(paramTypes[i], frameIndex)); frameIndex += paramTypes[i].getSize(); } // do call to pre Member preMethod = AjcMemberMaker.preIntroducedConstructor(aspectType, onType, declaredParams); body.append(Utility.createInvoke(fact, null, preMethod)); // create a local, and store return pre stuff into it. int arraySlot = mg.allocateLocal(1); body.append(InstructionFactory.createStore(Type.OBJECT, arraySlot)); // put this on the stack body.append(InstructionConstants.ALOAD_0); // unpack pre args onto stack UnresolvedType[] superParamTypes = explicitConstructor.getParameterTypes(); for (int i = 0, len = superParamTypes.length; i < len; i++) { body.append(InstructionFactory.createLoad(Type.OBJECT, arraySlot)); body.append(Utility.createConstant(fact, i)); body.append(InstructionFactory.createArrayLoad(Type.OBJECT)); body.append( Utility.createConversion( fact, Type.OBJECT, BcelWorld.makeBcelType(superParamTypes[i]))); } // call super/this body.append(Utility.createInvoke(fact, null, explicitConstructor)); // put this back on the stack body.append(InstructionConstants.ALOAD_0); // unpack params onto stack Member postMethod = AjcMemberMaker.postIntroducedConstructor(aspectType, onType, declaredParams); UnresolvedType[] postParamTypes = postMethod.getParameterTypes(); for (int i = 1, len = postParamTypes.length; i < len; i++) { body.append(InstructionFactory.createLoad(Type.OBJECT, arraySlot)); body.append(Utility.createConstant(fact, superParamTypes.length + i-1)); body.append(InstructionFactory.createArrayLoad(Type.OBJECT)); body.append( Utility.createConversion( fact, Type.OBJECT, BcelWorld.makeBcelType(postParamTypes[i]))); } // call post body.append(Utility.createInvoke(fact, null, postMethod)); // don't forget to return!! body.append(InstructionConstants.RETURN); return true; } private static LazyMethodGen makeDispatcher( LazyClassGen onGen, String dispatchName, ResolvedMember superMethod, BcelWorld world, boolean isSuper) { Type[] paramTypes = BcelWorld.makeBcelTypes(superMethod.getParameterTypes()); Type returnType = BcelWorld.makeBcelType(superMethod.getReturnType()); int modifiers = Modifier.PUBLIC; if (onGen.isInterface()) modifiers |= Modifier.ABSTRACT; LazyMethodGen mg = new LazyMethodGen( modifiers, returnType, dispatchName, paramTypes, UnresolvedType.getNames(superMethod.getExceptions()), onGen); InstructionList body = mg.getBody(); if (onGen.isInterface()) return mg; // assert (!superMethod.isStatic()) InstructionFactory fact = onGen.getFactory(); int pos = 0; body.append(InstructionFactory.createThis()); pos++; for (int i = 0, len = paramTypes.length; i < len; i++) { Type paramType = paramTypes[i]; body.append(InstructionFactory.createLoad(paramType, pos)); pos+=paramType.getSize(); } if (isSuper) { body.append(Utility.createSuperInvoke(fact, world, superMethod)); } else { body.append(Utility.createInvoke(fact, world, superMethod)); } body.append(InstructionFactory.createReturn(returnType)); return mg; } private boolean mungeNewField(BcelClassWeaver weaver, NewFieldTypeMunger munger) { /*ResolvedMember initMethod = */munger.getInitMethod(aspectType); LazyClassGen gen = weaver.getLazyClassGen(); ResolvedMember field = munger.getSignature(); ResolvedType onType = weaver.getWorld().resolve(field.getDeclaringType(),munger.getSourceLocation()); if (onType.isRawType()) onType = onType.getGenericType(); boolean onInterface = onType.isInterface(); if (onType.isAnnotation()) { signalError(WeaverMessages.ITDF_ON_ANNOTATION_NOT_ALLOWED,weaver,onType); return false; } if (onType.isEnum()) { signalError(WeaverMessages.ITDF_ON_ENUM_NOT_ALLOWED,weaver,onType); return false; } ResolvedMember interMethodBody = munger.getInitMethod(aspectType); AnnotationX annotationsOnRealMember[] = null; // pr98901 // For copying the annotations across, we have to discover the real member in the aspect // which is holding them. if (weaver.getWorld().isInJava5Mode()){ // the below line just gets the method with the same name in aspectType.getDeclaredMethods(); ResolvedType toLookOn = aspectType; if (aspectType.isRawType()) toLookOn = aspectType.getGenericType(); ResolvedMember realMember = getRealMemberForITDFromAspect(toLookOn,interMethodBody); if (realMember==null) throw new BCException("Couldn't find ITD init member '"+ interMethodBody+"' on aspect "+aspectType); annotationsOnRealMember = realMember.getAnnotations(); } if (onType.equals(gen.getType())) { if (onInterface) { LazyMethodGen mg = makeMethodGen(gen, AjcMemberMaker.interFieldInterfaceGetter(field, onType, aspectType)); gen.addMethodGen(mg); LazyMethodGen mg1 = makeMethodGen(gen, AjcMemberMaker.interFieldInterfaceSetter(field, onType, aspectType)); gen.addMethodGen(mg1); } else { weaver.addInitializer(this); FieldGen fg = makeFieldGen(gen, AjcMemberMaker.interFieldClassField(field, aspectType)); if (annotationsOnRealMember!=null) { for (int i = 0; i < annotationsOnRealMember.length; i++) { AnnotationX annotationX = annotationsOnRealMember[i]; Annotation a = annotationX.getBcelAnnotation(); AnnotationGen ag = new AnnotationGen(a,weaver.getLazyClassGen().getConstantPoolGen(),true); fg.addAnnotation(ag); } } gen.addField(fg.getField(),getSourceLocation()); } return true; } else if (onInterface && gen.getType().isTopmostImplementor(onType)) { // wew know that we can't be static since we don't allow statics on interfaces if (field.isStatic()) throw new RuntimeException("unimplemented"); weaver.addInitializer(this); //System.err.println("impl body on " + gen.getType() + " for " + munger); Type fieldType = BcelWorld.makeBcelType(field.getType()); FieldGen fg = makeFieldGen(gen, AjcMemberMaker.interFieldInterfaceField(field, onType, aspectType)); gen.addField(fg.getField(),getSourceLocation()); //this uses a shadow munger to add init method to constructors //weaver.getShadowMungers().add(makeInitCallShadowMunger(initMethod)); LazyMethodGen mg = makeMethodGen(gen, AjcMemberMaker.interFieldInterfaceGetter(field, gen.getType(), aspectType)); InstructionList il = new InstructionList(); InstructionFactory fact = gen.getFactory(); if (field.isStatic()) { il.append(fact.createFieldAccess( gen.getClassName(), fg.getName(), fieldType, Constants.GETSTATIC)); } else { il.append(InstructionConstants.ALOAD_0); il.append(fact.createFieldAccess( gen.getClassName(), fg.getName(), fieldType, Constants.GETFIELD)); } il.append(InstructionFactory.createReturn(fieldType)); mg.getBody().insert(il); gen.addMethodGen(mg); LazyMethodGen mg1 = makeMethodGen(gen, AjcMemberMaker.interFieldInterfaceSetter(field, gen.getType(), aspectType)); InstructionList il1 = new InstructionList(); if (field.isStatic()) { il1.append(InstructionFactory.createLoad(fieldType, 0)); il1.append(fact.createFieldAccess( gen.getClassName(), fg.getName(), fieldType, Constants.PUTSTATIC)); } else { il1.append(InstructionConstants.ALOAD_0); il1.append(InstructionFactory.createLoad(fieldType, 1)); il1.append(fact.createFieldAccess( gen.getClassName(), fg.getName(), fieldType, Constants.PUTFIELD)); } il1.append(InstructionFactory.createReturn(Type.VOID)); mg1.getBody().insert(il1); gen.addMethodGen(mg1); return true; } else { return false; } } }
102,212
Bug 102212 [itds] abstract synchronized: compile error expected
when using intertype declaration, the compiler doesn't check for illegal modifier combinations such as "abstract synchronized". another manifestation of this problem is when using intertype declaration to add a synchronized method to an interface. the problem is more severe in this case because conceptually, this method is not abstract at all. interface Interface {} abstract class Parent {} class Child extends Parent implements Interface {} aspect Bug { // illegal modifier combination not caught by ajc public abstract synchronized void Parent._abstract(); public synchronized void Child._abstract() {} // the following has the same effect, but is easier to miss public /* implicit abstract */ synchronized void Interface._interface() {} // use Child to make java complain: "illegal modifiers: 0x421" // (this corresponds to "public abstract synchronized") public static void main(String[] args) { new Child(); } }
resolved fixed
b17ff4e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-02T14:38:11Z
2005-06-29T21:20:00Z
weaver/src/org/aspectj/weaver/bcel/LazyMethodGen.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.bcel; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Set; import java.util.Stack; 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.Method; import org.aspectj.apache.bcel.classfile.Synthetic; import org.aspectj.apache.bcel.classfile.annotation.Annotation; import org.aspectj.apache.bcel.generic.BranchHandle; import org.aspectj.apache.bcel.generic.BranchInstruction; import org.aspectj.apache.bcel.generic.CPInstruction; import org.aspectj.apache.bcel.generic.ClassGenException; import org.aspectj.apache.bcel.generic.CodeExceptionGen; import org.aspectj.apache.bcel.generic.ConstantPoolGen; import org.aspectj.apache.bcel.generic.Instruction; import org.aspectj.apache.bcel.generic.InstructionHandle; import org.aspectj.apache.bcel.generic.InstructionList; import org.aspectj.apache.bcel.generic.InstructionTargeter; import org.aspectj.apache.bcel.generic.LineNumberGen; import org.aspectj.apache.bcel.generic.LocalVariableGen; import org.aspectj.apache.bcel.generic.LocalVariableInstruction; import org.aspectj.apache.bcel.generic.MethodGen; import org.aspectj.apache.bcel.generic.ObjectType; import org.aspectj.apache.bcel.generic.Select; import org.aspectj.apache.bcel.generic.Type; import org.aspectj.apache.bcel.generic.annotation.AnnotationGen; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.AnnotationX; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.MemberImpl; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.AjAttribute.EffectiveSignatureAttribute; import org.aspectj.weaver.AjAttribute.WeaverVersionInfo; /** * A LazyMethodGen should be treated as a MethodGen. It's our way of abstracting over the * low-level Method objects. It converts through {@link MethodGen} to create * and to serialize, but that's it. * * <p> At any rate, there are two ways to create LazyMethodGens. * One is from a method, which * does work through MethodGen to do the correct thing. * The other is the creation of a completely empty * LazyMethodGen, and it is used when we're constructing code from scratch. * * <p> We stay away from targeters for rangey things like Shadows and Exceptions. */ public final class LazyMethodGen { private int accessFlags; private Type returnType; private final String name; private Type[] argumentTypes; //private final String[] argumentNames; private String[] declaredExceptions; private InstructionList body; // leaving null for abstracts private Attribute[] attributes; private List newAnnotations; private final LazyClassGen enclosingClass; private BcelMethod memberView; private AjAttribute.EffectiveSignatureAttribute effectiveSignature; int highestLineNumber = 0; /** This is nonnull if this method is the result of an "inlining". We currently * copy methods into other classes for around advice. We add this field so * we can get JSR45 information correct. If/when we do _actual_ inlining, * we'll need to subtype LineNumberTag to have external line numbers. */ String fromFilename = null; private int maxLocals; private boolean canInline = true; private boolean hasExceptionHandlers; private boolean isSynthetic = false; /** * only used by {@link BcelClassWeaver} */ List /*ShadowMungers*/ matchedShadows; List /*Test*/ matchedShadowTests; // Used for interface introduction // this is the type of the interface the method is technically on public ResolvedType definingType = null; public LazyMethodGen( int accessFlags, Type returnType, String name, Type[] paramTypes, String[] declaredExceptions, LazyClassGen enclosingClass) { //System.err.println("raw create of: " + name + ", " + enclosingClass.getName() + ", " + returnType); this.memberView = null; // ??? should be okay, since constructed ones aren't woven into this.accessFlags = accessFlags; this.returnType = returnType; this.name = name; this.argumentTypes = paramTypes; //this.argumentNames = Utility.makeArgNames(paramTypes.length); this.declaredExceptions = declaredExceptions; if (!Modifier.isAbstract(accessFlags)) { body = new InstructionList(); setMaxLocals(calculateMaxLocals()); } else { body = null; } this.attributes = new Attribute[0]; this.enclosingClass = enclosingClass; assertGoodBody(); // @AJ advice are not inlined by default since requires further analysis // and weaving ordering control // TODO AV - improve - note: no room for improvement as long as aspects are reweavable // since the inlined version with wrappers and an to be done annotation to keep // inline state will be garbaged due to reweavable impl if (memberView != null && isAdviceMethod()) { if (enclosingClass.getType().isAnnotationStyleAspect()) { //TODO we could check for @Around advice as well this.canInline = false; } } } private int calculateMaxLocals() { int ret = 0; if (!Modifier.isStatic(accessFlags)) ret++; for (int i = 0, len = argumentTypes.length; i < len; i++) { ret += argumentTypes[i].getSize(); } return ret; } private Method savedMethod = null; // build from an existing method, lazy build saves most work for initialization public LazyMethodGen(Method m, LazyClassGen enclosingClass) { savedMethod = m; this.enclosingClass = enclosingClass; if (!(m.isAbstract() || m.isNative()) && m.getCode() == null) { throw new RuntimeException("bad non-abstract method with no code: " + m + " on " + enclosingClass); } if ((m.isAbstract() || m.isNative()) && m.getCode() != null) { throw new RuntimeException("bad abstract method with code: " + m + " on " + enclosingClass); } this.memberView = new BcelMethod(enclosingClass.getBcelObjectType(), m); this.accessFlags = m.getAccessFlags(); this.name = m.getName(); // @AJ advice are not inlined by default since requires further analysis // and weaving ordering control // TODO AV - improve - note: no room for improvement as long as aspects are reweavable // since the inlined version with wrappers and an to be done annotation to keep // inline state will be garbaged due to reweavable impl if (memberView != null && isAdviceMethod()) { if (enclosingClass.getType().isAnnotationStyleAspect()) { //TODO we could check for @Around advice as well this.canInline = false; } } } public boolean hasDeclaredLineNumberInfo() { return (memberView != null && memberView.hasDeclarationLineNumberInfo()); } public int getDeclarationLineNumber() { if (hasDeclaredLineNumberInfo()) { return memberView.getDeclarationLineNumber(); } else { return -1; } } public int getDeclarationOffset() { if (hasDeclaredLineNumberInfo()) { return memberView.getDeclarationOffset(); } else { return 0; } } public void addAnnotation(AnnotationX ax) { initialize(); if (memberView==null) { // If member view is null, we manage them in newAnnotations if (newAnnotations==null) newAnnotations = new ArrayList(); newAnnotations.add(ax); } else { memberView.addAnnotation(ax); } } public boolean hasAnnotation(UnresolvedType annotationTypeX) { initialize(); if (memberView==null) { // Check local annotations first if (newAnnotations!=null) { for (Iterator iter = newAnnotations.iterator(); iter.hasNext();) { AnnotationX element = (AnnotationX) iter.next(); if (element.getBcelAnnotation().getTypeName().equals(annotationTypeX.getName())) return true; } } memberView = new BcelMethod(getEnclosingClass().getBcelObjectType(), getMethod()); return memberView.hasAnnotation(annotationTypeX); } return memberView.hasAnnotation(annotationTypeX); } private void initialize() { if (returnType != null) return; //System.err.println("initializing: " + getName() + ", " + enclosingClass.getName() + ", " + returnType + ", " + savedMethod); MethodGen gen = new MethodGen(savedMethod, enclosingClass.getName(), enclosingClass.getConstantPoolGen()); this.returnType = gen.getReturnType(); this.argumentTypes = gen.getArgumentTypes(); this.declaredExceptions = gen.getExceptions(); this.attributes = gen.getAttributes(); //this.annotations = gen.getAnnotations(); this.maxLocals = gen.getMaxLocals(); // this.returnType = BcelWorld.makeBcelType(memberView.getReturnType()); // this.argumentTypes = BcelWorld.makeBcelTypes(memberView.getParameterTypes()); // // this.declaredExceptions = UnresolvedType.getNames(memberView.getExceptions()); //gen.getExceptions(); // this.attributes = new Attribute[0]; //gen.getAttributes(); // this.maxLocals = savedMethod.getCode().getMaxLocals(); if (gen.isAbstract() || gen.isNative()) { body = null; } else { //body = new InstructionList(savedMethod.getCode().getCode()); body = gen.getInstructionList(); unpackHandlers(gen); unpackLineNumbers(gen); unpackLocals(gen); } assertGoodBody(); //System.err.println("initialized: " + this.getClassName() + "." + this.getName()); } // XXX we're relying on the javac promise I've just made up that we won't have an early exception // in the list mask a later exception: That is, for two exceptions E and F, // if E preceeds F, then either E \cup F = {}, or E \nonstrictsubset F. So when we add F, // we add it on the _OUTSIDE_ of any handlers that share starts or ends with it. // with that in mind, we merrily go adding ranges for exceptions. private void unpackHandlers(MethodGen gen) { CodeExceptionGen[] exns = gen.getExceptionHandlers(); if (exns != null) { int len = exns.length; if (len > 0) hasExceptionHandlers = true; int priority = len - 1; for (int i = 0; i < len; i++, priority--) { CodeExceptionGen exn = exns[i]; InstructionHandle start = Range.genStart( body, getOutermostExceptionStart(exn.getStartPC())); InstructionHandle end = Range.genEnd(body, getOutermostExceptionEnd(exn.getEndPC())); // this doesn't necessarily handle overlapping correctly!!! ExceptionRange er = new ExceptionRange( body, exn.getCatchType() == null ? null : BcelWorld.fromBcel(exn.getCatchType()), priority); er.associateWithTargets(start, end, exn.getHandlerPC()); exn.setStartPC(null); // also removes from target exn.setEndPC(null); // also removes from target exn.setHandlerPC(null); // also removes from target } gen.removeExceptionHandlers(); } } private InstructionHandle getOutermostExceptionStart(InstructionHandle ih) { while (true) { if (ExceptionRange.isExceptionStart(ih.getPrev())) { ih = ih.getPrev(); } else { return ih; } } } private InstructionHandle getOutermostExceptionEnd(InstructionHandle ih) { while (true) { if (ExceptionRange.isExceptionEnd(ih.getNext())) { ih = ih.getNext(); } else { return ih; } } } private void unpackLineNumbers(MethodGen gen) { LineNumberTag lr = null; for (InstructionHandle ih = body.getStart(); ih != null; ih = ih.getNext()) { InstructionTargeter[] targeters = ih.getTargeters(); if (targeters != null) { for (int i = targeters.length - 1; i >= 0; i--) { InstructionTargeter targeter = targeters[i]; if (targeter instanceof LineNumberGen) { LineNumberGen lng = (LineNumberGen) targeter; lng.updateTarget(ih, null); int lineNumber = lng.getSourceLine(); if (highestLineNumber < lineNumber) highestLineNumber = lineNumber; lr = new LineNumberTag(lineNumber); } } } if (lr != null) { ih.addTargeter(lr); } } gen.removeLineNumbers(); } private void unpackLocals(MethodGen gen) { Set locals = new HashSet(); for (InstructionHandle ih = body.getStart(); ih != null; ih = ih.getNext()) { InstructionTargeter[] targeters = ih.getTargeters(); List ends = new ArrayList(0); if (targeters != null) { for (int i = targeters.length - 1; i >= 0; i--) { InstructionTargeter targeter = targeters[i]; if (targeter instanceof LocalVariableGen) { LocalVariableGen lng = (LocalVariableGen) targeter; LocalVariableTag lr = new LocalVariableTag(BcelWorld.fromBcel(lng.getType()), lng.getName(), lng.getIndex()); if (lng.getStart() == ih) { locals.add(lr); } else { ends.add(lr); } } } } for (Iterator i = locals.iterator(); i.hasNext(); ) { ih.addTargeter((LocalVariableTag) i.next()); } locals.removeAll(ends); } gen.removeLocalVariables(); } // =============== public int allocateLocal(Type type) { return allocateLocal(type.getSize()); } public int allocateLocal(int slots) { int max = getMaxLocals(); setMaxLocals(max + slots); return max; } public Method getMethod() { if (savedMethod != null) return savedMethod; //??? this relies on gentle treatment of constant pool try { MethodGen gen = pack(); return gen.getMethod(); } catch (ClassGenException e) { enclosingClass.getBcelObjectType().getResolvedTypeX().getWorld().showMessage( IMessage.ERROR, WeaverMessages.format(WeaverMessages.PROBLEM_GENERATING_METHOD, this.getClassName(), this.getName(), e.getMessage()), this.getMemberView() == null ? null : this.getMemberView().getSourceLocation(), null); // throw e; PR 70201.... let the normal problem reporting infrastructure deal with this rather than crashing. body = null; MethodGen gen = pack(); return gen.getMethod(); } } public void markAsChanged() { initialize(); savedMethod = null; } // ============================= public String toString() { WeaverVersionInfo weaverVersion = enclosingClass.getBcelObjectType().getWeaverVersionAttribute(); return toLongString(weaverVersion); } public String toShortString() { String access = org.aspectj.apache.bcel.classfile.Utility.accessToString(getAccessFlags()); StringBuffer buf = new StringBuffer(); if (!access.equals("")) { buf.append(access); buf.append(" "); } buf.append( org.aspectj.apache.bcel.classfile.Utility.signatureToString( getReturnType().getSignature(), true)); buf.append(" "); buf.append(getName()); buf.append("("); { int len = argumentTypes.length; if (len > 0) { buf.append( org.aspectj.apache.bcel.classfile.Utility.signatureToString( argumentTypes[0].getSignature(), true)); for (int i = 1; i < argumentTypes.length; i++) { buf.append(", "); buf.append( org.aspectj.apache.bcel.classfile.Utility.signatureToString( argumentTypes[i].getSignature(), true)); } } } buf.append(")"); { int len = declaredExceptions != null ? declaredExceptions.length : 0; if (len > 0) { buf.append(" throws "); buf.append(declaredExceptions[0]); for (int i = 1; i < declaredExceptions.length; i++) { buf.append(", "); buf.append(declaredExceptions[i]); } } } return buf.toString(); } public String toLongString(WeaverVersionInfo weaverVersion) { ByteArrayOutputStream s = new ByteArrayOutputStream(); print(new PrintStream(s),weaverVersion); return new String(s.toByteArray()); } public void print(WeaverVersionInfo weaverVersion) { print(System.out,weaverVersion); } public void print(PrintStream out, WeaverVersionInfo weaverVersion) { out.print(" " + toShortString()); printAspectAttributes(out,weaverVersion); InstructionList body = getBody(); if (body == null) { out.println(";"); return; } out.println(":"); new BodyPrinter(out).run(); out.println(" end " + toShortString()); } private void printAspectAttributes(PrintStream out, WeaverVersionInfo weaverVersion) { ISourceContext context = null; if (enclosingClass != null && enclosingClass.getType() != null) { context = enclosingClass.getType().getSourceContext(); } List as = BcelAttributes.readAjAttributes(getClassName(),attributes, context,null,weaverVersion); if (! as.isEmpty()) { out.println(" " + as.get(0)); // XXX assuming exactly one attribute, munger... } } private class BodyPrinter { Map prefixMap = new HashMap(); Map suffixMap = new HashMap(); Map labelMap = new HashMap(); InstructionList body; PrintStream out; ConstantPool pool; List ranges; BodyPrinter(PrintStream out) { this.pool = enclosingClass.getConstantPoolGen().getConstantPool(); this.body = getBody(); this.out = out; } void run() { //killNops(); assignLabels(); print(); } // label assignment void assignLabels() { LinkedList exnTable = new LinkedList(); String pendingLabel = null; // boolean hasPendingTargeters = false; int lcounter = 0; for (InstructionHandle ih = body.getStart(); ih != null; ih = ih.getNext()) { InstructionTargeter[] targeters = ih.getTargeters(); if (targeters != null) { for (int i = targeters.length - 1; i >= 0; i--) { InstructionTargeter t = targeters[i]; if (t instanceof ExceptionRange) { // assert isRangeHandle(h); ExceptionRange r = (ExceptionRange) t; if (r.getStart() == ih) { insertHandler(r, exnTable); } } else if (t instanceof BranchInstruction) { if (pendingLabel == null) { pendingLabel = "L" + lcounter++; } } else { // assert isRangeHandle(h) } } } if (pendingLabel != null) { labelMap.put(ih, pendingLabel); if (! Range.isRangeHandle(ih)) { pendingLabel = null; } } } int ecounter = 0; for (Iterator i = exnTable.iterator(); i.hasNext();) { ExceptionRange er = (ExceptionRange) i.next(); String exceptionLabel = "E" + ecounter++; labelMap.put(Range.getRealStart(er.getHandler()), exceptionLabel); labelMap.put(er.getHandler(), exceptionLabel); } } // printing void print() { int depth = 0; int currLine = -1; bodyPrint: for (InstructionHandle ih = body.getStart(); ih != null; ih = ih.getNext()) { if (Range.isRangeHandle(ih)) { Range r = Range.getRange(ih); // don't print empty ranges, that is, ranges who contain no actual instructions for (InstructionHandle xx = r.getStart(); Range.isRangeHandle(xx); xx = xx.getNext()) { if (xx == r.getEnd()) continue bodyPrint; } // doesn't handle nested: if (r.getStart().getNext() == r.getEnd()) continue; if (r.getStart() == ih) { printRangeString(r, depth++); } else { if (r.getEnd() != ih) throw new RuntimeException("bad"); printRangeString(r, --depth); } } else { printInstruction(ih, depth); int line = getLineNumber(ih, currLine); if (line != currLine) { currLine = line; out.println(" (line " + line + ")"); } else { out.println(); } } } } void printRangeString(Range r, int depth) { printDepth(depth); out.println(getRangeString(r, labelMap)); } String getRangeString(Range r, Map labelMap) { if (r instanceof ExceptionRange) { ExceptionRange er = (ExceptionRange) r; return er.toString() + " -> " + labelMap.get(er.getHandler()); // // + " PRI " + er.getPriority(); } else { return r.toString(); } } void printDepth(int depth) { pad(BODY_INDENT); while (depth > 0) { out.print("| "); depth--; } } void printLabel(String s, int depth) { int space = Math.max(CODE_INDENT - depth * 2, 0); if (s == null) { pad(space); } else { space = Math.max(space - (s.length() + 2), 0); pad(space); out.print(s); out.print(": "); } } void printInstruction(InstructionHandle h, int depth) { printDepth(depth); printLabel((String) labelMap.get(h), depth); Instruction inst = h.getInstruction(); if (inst instanceof CPInstruction) { CPInstruction cpinst = (CPInstruction) inst; out.print(Constants.OPCODE_NAMES[cpinst.getOpcode()].toUpperCase()); out.print(" "); out.print(pool.constantToString(pool.getConstant(cpinst.getIndex()))); } else if (inst instanceof Select) { Select sinst = (Select) inst; out.println(Constants.OPCODE_NAMES[sinst.getOpcode()].toUpperCase()); int[] matches = sinst.getMatchs(); InstructionHandle[] targets = sinst.getTargets(); InstructionHandle defaultTarget = sinst.getTarget(); for (int i = 0, len = matches.length; i < len; i++) { printDepth(depth); printLabel(null, depth); out.print(" "); out.print(matches[i]); out.print(": \t"); out.println(labelMap.get(targets[i])); } printDepth(depth); printLabel(null, depth); out.print(" "); out.print("default: \t"); out.print(labelMap.get(defaultTarget)); } else if (inst instanceof BranchInstruction) { BranchInstruction brinst = (BranchInstruction) inst; out.print(Constants.OPCODE_NAMES[brinst.getOpcode()].toUpperCase()); out.print(" "); out.print(labelMap.get(brinst.getTarget())); } else if (inst instanceof LocalVariableInstruction) { LocalVariableInstruction lvinst = (LocalVariableInstruction) inst; out.print(inst.toString(false).toUpperCase()); int index = lvinst.getIndex(); LocalVariableTag tag = getLocalVariableTag(h, index); if (tag != null) { out.print(" // "); out.print(tag.getType()); out.print(" "); out.print(tag.getName()); } } else { out.print(inst.toString(false).toUpperCase()); } } static final int BODY_INDENT = 4; static final int CODE_INDENT = 16; void pad(int size) { for (int i = 0; i < size; i++) { out.print(" "); } } } static LocalVariableTag getLocalVariableTag( InstructionHandle ih, int index) { InstructionTargeter[] targeters = ih.getTargeters(); if (targeters == null) return null; for (int i = targeters.length - 1; i >= 0; i--) { InstructionTargeter t = targeters[i]; if (t instanceof LocalVariableTag) { LocalVariableTag lvt = (LocalVariableTag) t; if (lvt.getSlot() == index) return lvt; } } return null; } static int getLineNumber( InstructionHandle ih, int prevLine) { InstructionTargeter[] targeters = ih.getTargeters(); if (targeters == null) return prevLine; for (int i = targeters.length - 1; i >= 0; i--) { InstructionTargeter t = targeters[i]; if (t instanceof LineNumberTag) { return ((LineNumberTag)t).getLineNumber(); } } return prevLine; } public boolean isStatic() { return Modifier.isStatic(getAccessFlags()); } public boolean isAbstract() { return Modifier.isAbstract(getAccessFlags()); } public boolean isBridgeMethod() { return (getAccessFlags() & Constants.ACC_BRIDGE) != 0; } public void addExceptionHandler( InstructionHandle start, InstructionHandle end, InstructionHandle handlerStart, ObjectType catchType, boolean highPriority) { InstructionHandle start1 = Range.genStart(body, start); InstructionHandle end1 = Range.genEnd(body, end); ExceptionRange er = new ExceptionRange(body, BcelWorld.fromBcel(catchType), highPriority); er.associateWithTargets(start1, end1, handlerStart); } public int getAccessFlags() { return accessFlags; } public Type[] getArgumentTypes() { initialize(); return argumentTypes; } public LazyClassGen getEnclosingClass() { return enclosingClass; } public int getMaxLocals() { return maxLocals; } public String getName() { return name; } public Type getReturnType() { initialize(); return returnType; } public void setMaxLocals(int maxLocals) { this.maxLocals = maxLocals; } public InstructionList getBody() { markAsChanged(); return body; } public boolean hasBody() { if (savedMethod != null) return savedMethod.getCode() != null; return body != null; } public Attribute[] getAttributes() { return attributes; } public String[] getDeclaredExceptions() { return declaredExceptions; } public String getClassName() { return enclosingClass.getName(); } // ---- packing! public MethodGen pack() { //killNops(); MethodGen gen = new MethodGen( getAccessFlags(), getReturnType(), getArgumentTypes(), null, //getArgumentNames(), getName(), getEnclosingClass().getName(), new InstructionList(), getEnclosingClass().getConstantPoolGen()); for (int i = 0, len = declaredExceptions.length; i < len; i++) { gen.addException(declaredExceptions[i]); } for (int i = 0, len = attributes.length; i < len; i++) { gen.addAttribute(attributes[i]); } if (newAnnotations!=null) { for (Iterator iter = newAnnotations.iterator(); iter.hasNext();) { AnnotationX element = (AnnotationX) iter.next(); gen.addAnnotation(new AnnotationGen(element.getBcelAnnotation(),gen.getConstantPool(),true)); } } if (memberView!=null && memberView.getAnnotations()!=null && memberView.getAnnotations().length!=0) { AnnotationX[] ans = memberView.getAnnotations(); for (int i = 0, len = ans.length; i < len; i++) { Annotation a= ans[i].getBcelAnnotation(); gen.addAnnotation(new AnnotationGen(a,gen.getConstantPool(),true)); } } if (isSynthetic) { ConstantPoolGen cpg = gen.getConstantPool(); int index = cpg.addUtf8("Synthetic"); gen.addAttribute(new Synthetic(index, 0, new byte[0], cpg.getConstantPool())); } if (hasBody()) { packBody(gen); gen.setMaxLocals(); gen.setMaxStack(); } else { gen.setInstructionList(null); } return gen; } public void makeSynthetic() { isSynthetic = true; } /** fill the newly created method gen with our body, * inspired by InstructionList.copy() */ public void packBody(MethodGen gen) { HashMap map = new HashMap(); InstructionList fresh = gen.getInstructionList(); /* Make copies of all instructions, append them to the new list * and associate old instruction references with the new ones, i.e., * a 1:1 mapping. */ for (InstructionHandle ih = getBody().getStart(); ih != null; ih = ih.getNext()) { if (Range.isRangeHandle(ih)) { continue; } Instruction i = ih.getInstruction(); Instruction c = Utility.copyInstruction(i); if (c instanceof BranchInstruction) map.put(ih, fresh.append((BranchInstruction) c)); else map.put(ih, fresh.append(c)); } // at this point, no rangeHandles are in fresh. Let's use that... /* Update branch targets and insert various attributes. * Insert our exceptionHandlers * into a sorted list, so they can be added in order later. */ InstructionHandle ih = getBody().getStart(); InstructionHandle jh = fresh.getStart(); LinkedList exnList = new LinkedList(); // map from localvariabletag to instruction handle Map localVariableStarts = new HashMap(); Map localVariableEnds = new HashMap(); int currLine = -1; while (ih != null) { if (map.get(ih) == null) { // we're a range instruction Range r = Range.getRange(ih); if (r instanceof ExceptionRange) { ExceptionRange er = (ExceptionRange) r; if (er.getStart() == ih) { //System.err.println("er " + er); if (!er.isEmpty()){ // order is important, insert handlers in order of start insertHandler(er, exnList); } } } else { // we must be a shadow range or something equally useless, // so forget about doing anything } // just increment ih. ih = ih.getNext(); } else { // assert map.get(ih) == jh Instruction i = ih.getInstruction(); Instruction j = jh.getInstruction(); if (i instanceof BranchInstruction) { BranchInstruction bi = (BranchInstruction) i; BranchInstruction bj = (BranchInstruction) j; InstructionHandle itarget = bi.getTarget(); // old target // try { // New target is in hash map bj.setTarget(remap(itarget, map)); // } catch (NullPointerException e) { // print(); // System.out.println("Was trying to remap " + bi); // System.out.println("who's target was supposedly " + itarget); // throw e; // } if (bi instanceof Select) { // Either LOOKUPSWITCH or TABLESWITCH InstructionHandle[] itargets = ((Select) bi).getTargets(); InstructionHandle[] jtargets = ((Select) bj).getTargets(); for (int k = itargets.length - 1; k >= 0; k--) { // Update all targets jtargets[k] = remap(itargets[k], map); jtargets[k].addTargeter(bj); } } } // now deal with line numbers // and store up info for local variables InstructionTargeter[] targeters = ih.getTargeters(); int lineNumberOffset = (fromFilename == null) ? 0 : getEnclosingClass().getSourceDebugExtensionOffset(fromFilename); if (targeters != null) { for (int k = targeters.length - 1; k >= 0; k--) { InstructionTargeter targeter = targeters[k]; if (targeter instanceof LineNumberTag) { int line = ((LineNumberTag)targeter).getLineNumber(); if (line != currLine) { gen.addLineNumber(jh, line + lineNumberOffset); currLine = line; } } else if (targeter instanceof LocalVariableTag) { LocalVariableTag lvt = (LocalVariableTag) targeter; if (localVariableStarts.get(lvt) == null) { localVariableStarts.put(lvt, jh); } localVariableEnds.put(lvt, jh); } } } // now continue ih = ih.getNext(); jh = jh.getNext(); } } // now add exception handlers for (Iterator iter = exnList.iterator(); iter.hasNext();) { ExceptionRange r = (ExceptionRange) iter.next(); if (r.isEmpty()) continue; gen.addExceptionHandler( remap(r.getRealStart(), map), remap(r.getRealEnd(), map), remap(r.getHandler(), map), (r.getCatchType() == null) ? null : (ObjectType) BcelWorld.makeBcelType(r.getCatchType())); } // now add local variables gen.removeLocalVariables(); // this next iteration _might_ be overkill, but we had problems with // bcel before with duplicate local variables. Now that we're patching // bcel we should be able to do without it if we're paranoid enough // through the rest of the compiler. Map duplicatedLocalMap = new HashMap(); List keys = new ArrayList(); keys.addAll(localVariableStarts.keySet()); for (Iterator iter = keys.iterator(); iter.hasNext(); ) { LocalVariableTag tag = (LocalVariableTag) iter.next(); // have we already added one with the same slot number and start location? // if so, just continue. InstructionHandle start = (InstructionHandle) localVariableStarts.get(tag); Set slots = (Set) duplicatedLocalMap.get(start); if (slots == null) { slots = new HashSet(); duplicatedLocalMap.put(start, slots); } if (slots.contains(new Integer(tag.getSlot()))) { // we already have a var starting at this tag with this slot continue; } slots.add(new Integer(tag.getSlot())); gen.addLocalVariable( tag.getName(), BcelWorld.makeBcelType(tag.getType()), tag.getSlot(), (InstructionHandle) localVariableStarts.get(tag), (InstructionHandle) localVariableEnds.get(tag)); } // JAVAC adds line number tables (with just one entry) to generated accessor methods - this // keeps some tools that rely on finding at least some form of linenumbertable happy. // Let's check if we have one - if we don't then let's add one. // TODO Could be made conditional on whether line debug info is being produced if (gen.getLineNumbers().length==0) { gen.addLineNumber(gen.getInstructionList().getStart(),1); } } /** This procedure should not currently be used. */ // public void killNops() { // InstructionHandle curr = body.getStart(); // while (true) { // if (curr == null) break; // InstructionHandle next = curr.getNext(); // if (curr.getInstruction() instanceof NOP) { // InstructionTargeter[] targeters = curr.getTargeters(); // if (targeters != null) { // for (int i = 0, len = targeters.length; i < len; i++) { // InstructionTargeter targeter = targeters[i]; // targeter.updateTarget(curr, next); // } // } // try { // body.delete(curr); // } catch (TargetLostException e) { // } // } // curr = next; // } // } private static InstructionHandle remap(InstructionHandle ih, Map map) { while (true) { Object ret = map.get(ih); if (ret == null) { ih = ih.getNext(); } else { return (InstructionHandle) ret; } } } // Update to all these comments, ASC 11-01-2005 // The right thing to do may be to do more with priorities as // we create new exception handlers, but that is a relatively // complex task. In the meantime, just taking account of the // priority here enables a couple of bugs to be fixed to do // with using return or break in code that contains a finally // block (pr78021,pr79554). // exception ordering. // What we should be doing is dealing with priority inversions way earlier than we are // and counting on the tree structure. In which case, the below code is in fact right. // XXX THIS COMMENT BELOW IS CURRENTLY WRONG. // An exception A preceeds an exception B in the exception table iff: // * A and B were in the original method, and A preceeded B in the original exception table // * If A has a higher priority than B, than it preceeds B. // * If A and B have the same priority, then the one whose START happens EARLIEST has LEAST priority. // in short, the outermost exception has least priority. // we implement this with a LinkedList. We could possibly implement this with a java.util.SortedSet, // but I don't trust the only implementation, TreeSet, to do the right thing. /* private */ static void insertHandler(ExceptionRange fresh, LinkedList l) { // Old implementation, simply: l.add(0,fresh); for (ListIterator iter = l.listIterator(); iter.hasNext();) { ExceptionRange r = (ExceptionRange) iter.next(); int freal = fresh.getRealStart().getPosition(); int rreal = r.getRealStart().getPosition(); if (fresh.getPriority() >= r.getPriority()) { iter.previous(); iter.add(fresh); return; } } // we have reached the end l.add(fresh); } public boolean isPrivate() { return Modifier.isPrivate(getAccessFlags()); } public boolean isProtected() { return Modifier.isProtected(getAccessFlags()); } public boolean isDefault() { return !(isProtected() || isPrivate() || isPublic()); } public boolean isPublic() { return Modifier.isPublic(getAccessFlags()); } // ---- /** A good body is a body with the following properties: * * <ul> * <li> For each branch instruction S in body, target T of S is in body. * <li> For each branch instruction S in body, target T of S has S as a targeter. * <li> For each instruction T in body, for each branch instruction S that is a * targeter of T, S is in body. * <li> For each non-range-handle instruction T in body, for each instruction S * that is a targeter of T, S is * either a branch instruction, an exception range or a tag * <li> For each range-handle instruction T in body, there is exactly one targeter S * that is a range. * <li> For each range-handle instruction T in body, the range R targeting T is in body. * <li> For each instruction T in body, for each exception range R targeting T, R is * in body. * <li> For each exception range R in body, let T := R.handler. T is in body, and R is one * of T's targeters * <li> All ranges are properly nested: For all ranges Q and R, if Q.start preceeds * R.start, then R.end preceeds Q.end. * </ul> * * Where the shorthand "R is in body" means "R.start is in body, R.end is in body, and * any InstructionHandle stored in a field of R (such as an exception handle) is in body". */ public void assertGoodBody() { if (true) return; // only enable for debugging, consider using cheaper toString() assertGoodBody(getBody(), toString()); //definingType.getNameAsIdentifier() + "." + getName()); //toString()); } public static void assertGoodBody(InstructionList il, String from) { if (true) return; // only to be enabled for debugging if (il == null) return; Set body = new HashSet(); Stack ranges = new Stack(); for (InstructionHandle ih = il.getStart(); ih != null; ih = ih.getNext()) { body.add(ih); if (ih.getInstruction() instanceof BranchInstruction) { body.add(ih.getInstruction()); } } for (InstructionHandle ih = il.getStart(); ih != null; ih = ih.getNext()) { assertGoodHandle(ih, body, ranges, from); InstructionTargeter[] ts = ih.getTargeters(); if (ts != null) { for (int i = ts.length - 1; i >= 0; i--) { assertGoodTargeter(ts[i], ih, body, from); } } } } private static void assertGoodHandle(InstructionHandle ih, Set body, Stack ranges, String from) { Instruction inst = ih.getInstruction(); if ((inst instanceof BranchInstruction) ^ (ih instanceof BranchHandle)) { throw new BCException("bad instruction/handle pair in " + from); } if (Range.isRangeHandle(ih)) { assertGoodRangeHandle(ih, body, ranges, from); } else if (inst instanceof BranchInstruction) { assertGoodBranchInstruction((BranchHandle) ih, (BranchInstruction) inst, body, ranges, from); } } private static void assertGoodBranchInstruction( BranchHandle ih, BranchInstruction inst, Set body, Stack ranges, String from) { if (ih.getTarget() != inst.getTarget()) { throw new BCException("bad branch instruction/handle pair in " + from); } InstructionHandle target = ih.getTarget(); assertInBody(target, body, from); assertTargetedBy(target, inst, from); if (inst instanceof Select) { Select sel = (Select) inst; InstructionHandle[] itargets = sel.getTargets(); for (int k = itargets.length - 1; k >= 0; k--) { assertInBody(itargets[k], body, from); assertTargetedBy(itargets[k], inst, from); } } } /** ih is an InstructionHandle or a BranchInstruction */ private static void assertInBody(Object ih, Set body, String from) { if (! body.contains(ih)) throw new BCException("thing not in body in " + from); } private static void assertGoodRangeHandle(InstructionHandle ih, Set body, Stack ranges, String from) { Range r = getRangeAndAssertExactlyOne(ih, from); assertGoodRange(r, body, from); if (r.getStart() == ih) { ranges.push(r); } else if (r.getEnd() == ih) { if (ranges.peek() != r) throw new BCException("bad range inclusion in " + from); ranges.pop(); } } private static void assertGoodRange(Range r, Set body, String from) { assertInBody(r.getStart(), body, from); assertRangeHandle(r.getStart(), from); assertTargetedBy(r.getStart(), r, from); assertInBody(r.getEnd(), body, from); assertRangeHandle(r.getEnd(), from); assertTargetedBy(r.getEnd(), r, from); if (r instanceof ExceptionRange) { ExceptionRange er = (ExceptionRange) r; assertInBody(er.getHandler(), body, from); assertTargetedBy(er.getHandler(), r, from); } } private static void assertRangeHandle(InstructionHandle ih, String from) { if (! Range.isRangeHandle(ih)) throw new BCException("bad range handle " + ih + " in " + from); } private static void assertTargetedBy( InstructionHandle target, InstructionTargeter targeter, String from) { InstructionTargeter[] ts = target.getTargeters(); if (ts == null) throw new BCException("bad targeting relationship in " + from); for (int i = ts.length - 1; i >= 0; i--) { if (ts[i] == targeter) return; } throw new RuntimeException("bad targeting relationship in " + from); } private static void assertTargets(InstructionTargeter targeter, InstructionHandle target, String from) { if (targeter instanceof Range) { Range r = (Range) targeter; if (r.getStart() == target || r.getEnd() == target) return; if (r instanceof ExceptionRange) { if (((ExceptionRange)r).getHandler() == target) return; } } else if (targeter instanceof BranchInstruction) { BranchInstruction bi = (BranchInstruction) targeter; if (bi.getTarget() == target) return; if (targeter instanceof Select) { Select sel = (Select) targeter; InstructionHandle[] itargets = sel.getTargets(); for (int k = itargets.length - 1; k >= 0; k--) { if (itargets[k] == target) return; } } } else if (targeter instanceof Tag) { return; } throw new BCException(targeter + " doesn't target " + target + " in " + from ); } private static Range getRangeAndAssertExactlyOne(InstructionHandle ih, String from) { Range ret = null; InstructionTargeter[] ts = ih.getTargeters(); if (ts == null) throw new BCException("range handle with no range in " + from); for (int i = ts.length - 1; i >= 0; i--) { if (ts[i] instanceof Range) { if (ret != null) throw new BCException("range handle with multiple ranges in " + from); ret = (Range) ts[i]; } } if (ret == null) throw new BCException("range handle with no range in " + from); return ret; } private static void assertGoodTargeter( InstructionTargeter t, InstructionHandle ih, Set body, String from) { assertTargets(t, ih, from); if (t instanceof Range) { assertGoodRange((Range) t, body, from); } else if (t instanceof BranchInstruction) { assertInBody(t, body, from); } } // ---- boolean isAdviceMethod() { return memberView.getAssociatedShadowMunger() != null; } boolean isAjSynthetic() { if (memberView == null) return true; return memberView.isAjSynthetic(); } public ISourceLocation getSourceLocation() { if (memberView!=null) return memberView.getSourceLocation(); return null; } public AjAttribute.EffectiveSignatureAttribute getEffectiveSignature() { //if (memberView == null) return null; if (effectiveSignature != null) return effectiveSignature; return memberView.getEffectiveSignature(); } public void setEffectiveSignature(ResolvedMember member, Shadow.Kind kind, boolean shouldWeave) { this.effectiveSignature = new AjAttribute.EffectiveSignatureAttribute(member,kind,shouldWeave); } public String getSignature() { if (memberView!=null) return memberView.getSignature(); return MemberImpl.typesToSignature(BcelWorld.fromBcel(getReturnType()), BcelWorld.fromBcel(getArgumentTypes()),false); } public String getParameterSignature() { if (memberView!=null) return memberView.getParameterSignature(); return MemberImpl.typesToSignature(BcelWorld.fromBcel(getArgumentTypes())); } public BcelMethod getMemberView() { return memberView; } public void forcePublic() { markAsChanged(); accessFlags = Utility.makePublic(accessFlags); } public boolean getCanInline() { return canInline; } public void setCanInline(boolean canInline) { this.canInline = canInline; } /** * Adds an attribute to the method * @param attr */ public void addAttribute(Attribute attr) { Attribute[] newAttributes = new Attribute[attributes.length + 1]; System.arraycopy(attributes, 0, newAttributes, 0, attributes.length); newAttributes[attributes.length] = attr; attributes = newAttributes; } }
101,606
Bug 101606 AspectJ compiler does not process unused code compiler options properly for aspects
In Eclipse (3.0) click 'Window' > 'Preferences' > 'Java' > 'Compiler'. Select the 'Unused Code' tab on the compiler preference page. Change 'Unused or unread private members' to Warning or Error. Create a project that contains an aspect with some private pointcuts. You will see warnings or errors for these pointcuts saying that they are unused.
resolved fixed
2c88c59
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-02T14:44:26Z
2005-06-24T08:00:00Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/problem/AjProblemReporter.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.ajdt.internal.compiler.problem; import java.lang.reflect.Modifier; import java.util.Iterator; import java.util.List; import org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration; import org.aspectj.ajdt.internal.compiler.ast.PointcutDeclaration; import org.aspectj.ajdt.internal.compiler.ast.Proceed; import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory; import org.aspectj.ajdt.internal.compiler.lookup.InterTypeMethodBinding; import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation; import org.aspectj.org.eclipse.jdt.core.compiler.IProblem; import org.aspectj.org.eclipse.jdt.internal.compiler.CompilationResult; import org.aspectj.org.eclipse.jdt.internal.compiler.IErrorHandlingPolicy; import org.aspectj.org.eclipse.jdt.internal.compiler.IProblemFactory; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.ASTNode; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Annotation; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.ExplicitConstructorCall; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.impl.CompilerOptions; import org.aspectj.org.eclipse.jdt.internal.compiler.impl.ReferenceContext; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ArrayBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.MethodBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TagBits; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.problem.ProblemReporter; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.ConcreteTypeMunger; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.patterns.DeclareAnnotation; import org.aspectj.weaver.patterns.DeclareSoft; /** * Extends problem reporter to support compiler-side implementation of declare soft. * Also overrides error reporting for the need to implement abstract methods to * account for inter-type declarations and pointcut declarations. This second * job might be better done directly in the SourceTypeBinding/ClassScope classes. * * @author Jim Hugunin */ public class AjProblemReporter extends ProblemReporter { private static final boolean DUMP_STACK = false; public EclipseFactory factory; public AjProblemReporter( IErrorHandlingPolicy policy, CompilerOptions options, IProblemFactory problemFactory) { super(policy, options, problemFactory); } public void unhandledException( TypeBinding exceptionType, ASTNode location) { if (!factory.getWorld().getDeclareSoft().isEmpty()) { Shadow callSite = factory.makeShadow(location, referenceContext); Shadow enclosingExec = factory.makeShadow(referenceContext); // PR 72157 - calls to super / this within a constructor are not part of the cons join point. if ((callSite == null) && (enclosingExec.getKind() == Shadow.ConstructorExecution) && (location instanceof ExplicitConstructorCall)) { super.unhandledException(exceptionType, location); return; } // System.err.println("about to show error for unhandled exception: " + new String(exceptionType.sourceName()) + // " at " + location + " in " + referenceContext); for (Iterator i = factory.getWorld().getDeclareSoft().iterator(); i.hasNext(); ) { DeclareSoft d = (DeclareSoft)i.next(); // We need the exceptionType to match the type in the declare soft statement // This means it must either be the same type or a subtype ResolvedType throwException = factory.fromEclipse((ReferenceBinding)exceptionType); FuzzyBoolean isExceptionTypeOrSubtype = d.getException().matchesInstanceof(throwException); if (!isExceptionTypeOrSubtype.alwaysTrue() ) continue; if (callSite != null) { FuzzyBoolean match = d.getPointcut().match(callSite); if (match.alwaysTrue()) { //System.err.println("matched callSite: " + callSite + " with " + d); return; } else if (!match.alwaysFalse()) { //!!! need this check to happen much sooner //throw new RuntimeException("unimplemented, shouldn't have fuzzy match here"); } } if (enclosingExec != null) { FuzzyBoolean match = d.getPointcut().match(enclosingExec); if (match.alwaysTrue()) { //System.err.println("matched enclosingExec: " + enclosingExec + " with " + d); return; } else if (!match.alwaysFalse()) { //!!! need this check to happen much sooner //throw new RuntimeException("unimplemented, shouldn't have fuzzy match here"); } } } } //??? is this always correct if (location instanceof Proceed) { return; } super.unhandledException(exceptionType, location); } private boolean isPointcutDeclaration(MethodBinding binding) { return CharOperation.prefixEquals(PointcutDeclaration.mangledPrefix, binding.selector); } private boolean isIntertypeDeclaration(MethodBinding binding) { return (binding instanceof InterTypeMethodBinding); } public void abstractMethodCannotBeOverridden( SourceTypeBinding type, MethodBinding concreteMethod) { if (isPointcutDeclaration(concreteMethod)) { return; } super.abstractMethodCannotBeOverridden(type, concreteMethod); } public void inheritedMethodReducesVisibility(SourceTypeBinding type, MethodBinding concreteMethod, MethodBinding[] abstractMethods) { // if we implemented this method by a public inter-type declaration, then there is no error ResolvedType onTypeX = null; // If the type is anonymous, look at its supertype if (!type.isAnonymousType()) { onTypeX = factory.fromEclipse(type); } else { // Hmmm. If the ITD is on an interface that is being 'instantiated' using an anonymous type, // we sort it out elsewhere and don't come into this method - // so we don't have to worry about interfaces, just the superclass. onTypeX = factory.fromEclipse(type.superclass()); //abstractMethod.declaringClass); } for (Iterator i = onTypeX.getInterTypeMungersIncludingSupers().iterator(); i.hasNext(); ) { ConcreteTypeMunger m = (ConcreteTypeMunger)i.next(); ResolvedMember sig = m.getSignature(); if (!Modifier.isAbstract(sig.getModifiers())) { if (ResolvedType .matches( AjcMemberMaker.interMethod( sig, m.getAspectType(), sig.getDeclaringType().resolve(factory.getWorld()).isInterface()), factory.makeResolvedMember(concreteMethod))) { return; } } } super.inheritedMethodReducesVisibility(type,concreteMethod,abstractMethods); } // if either of the MethodBinding is an ITD, we have already reported it. public void staticAndInstanceConflict(MethodBinding currentMethod, MethodBinding inheritedMethod) { if (currentMethod instanceof InterTypeMethodBinding) return; if (inheritedMethod instanceof InterTypeMethodBinding) return; super.staticAndInstanceConflict(currentMethod, inheritedMethod); } public void abstractMethodMustBeImplemented( SourceTypeBinding type, MethodBinding abstractMethod) { // if this is a PointcutDeclaration then there is no error if (isPointcutDeclaration(abstractMethod)) return; if (isIntertypeDeclaration(abstractMethod)) return; // when there is a problem with an ITD not being implemented, it will be reported elsewhere if (CharOperation.prefixEquals("ajc$interField".toCharArray(), abstractMethod.selector)) { //??? think through how this could go wrong return; } // if we implemented this method by an inter-type declaration, then there is no error //??? be sure this is always right ResolvedType onTypeX = null; // If the type is anonymous, look at its supertype if (!type.isAnonymousType()) { onTypeX = factory.fromEclipse(type); } else { // Hmmm. If the ITD is on an interface that is being 'instantiated' using an anonymous type, // we sort it out elsewhere and don't come into this method - // so we don't have to worry about interfaces, just the superclass. onTypeX = factory.fromEclipse(type.superclass()); //abstractMethod.declaringClass); } for (Iterator i = onTypeX.getInterTypeMungersIncludingSupers().iterator(); i.hasNext(); ) { ConcreteTypeMunger m = (ConcreteTypeMunger)i.next(); ResolvedMember sig = m.getSignature(); if (!Modifier.isAbstract(sig.getModifiers())) { if (ResolvedType .matches( AjcMemberMaker.interMethod( sig, m.getAspectType(), sig.getDeclaringType().resolve(factory.getWorld()).isInterface()), factory.makeResolvedMember(abstractMethod))) { return; } } } super.abstractMethodMustBeImplemented(type, abstractMethod); } /* (non-Javadoc) * @see org.aspectj.org.eclipse.jdt.internal.compiler.problem.ProblemReporter#disallowedTargetForAnnotation(org.aspectj.org.eclipse.jdt.internal.compiler.ast.Annotation) */ public void disallowedTargetForAnnotation(Annotation annotation) { // if the annotation's recipient is an ITD, it might be allowed after all... if (annotation.recipient instanceof MethodBinding) { MethodBinding binding = (MethodBinding) annotation.recipient; String name = new String(binding.selector); if (name.startsWith("ajc$")) { long metaTagBits = annotation.resolvedType.getAnnotationTagBits(); // could be forward reference if (name.indexOf("interField") != -1) { if ((metaTagBits & TagBits.AnnotationForField) != 0) return; } else if (name.indexOf("interConstructor") != -1) { if ((metaTagBits & TagBits.AnnotationForConstructor) != 0) return; } else if (name.indexOf("interMethod") != -1) { if ((metaTagBits & TagBits.AnnotationForMethod) != 0) return; } else if (name.indexOf("declare_"+DeclareAnnotation.AT_TYPE+"_")!=-1) { if ((metaTagBits & TagBits.AnnotationForAnnotationType)!=0 || (metaTagBits & TagBits.AnnotationForType)!=0) return; } else if (name.indexOf("declare_"+DeclareAnnotation.AT_FIELD+"_")!=-1) { if ((metaTagBits & TagBits.AnnotationForField)!=0) return; } else if (name.indexOf("declare_"+DeclareAnnotation.AT_CONSTRUCTOR+"_")!=-1) { if ((metaTagBits & TagBits.AnnotationForConstructor)!=0) return; } else if (name.indexOf("declare_eow") != -1) { if ((metaTagBits & TagBits.AnnotationForField) != 0) return; } } } // not our special case, report the problem... super.disallowedTargetForAnnotation(annotation); } public void handle( int problemId, String[] problemArguments, String[] messageArguments, int severity, int problemStartPosition, int problemEndPosition, ReferenceContext referenceContext, CompilationResult unitResult) { if (severity != Ignore && DUMP_STACK) { Thread.dumpStack(); } super.handle( problemId, problemArguments, messageArguments, severity, problemStartPosition, problemEndPosition, referenceContext, unitResult); } // PR71076 public void javadocMissingParamTag(char[] name, int sourceStart, int sourceEnd, int modifiers) { boolean reportIt = true; String sName = new String(name); if (sName.startsWith("ajc$")) reportIt = false; if (sName.equals("thisJoinPoint")) reportIt = false; if (sName.equals("thisJoinPointStaticPart")) reportIt = false; if (sName.equals("thisEnclosingJoinPointStaticPart")) reportIt = false; if (sName.equals("ajc_aroundClosure")) reportIt = false; if (reportIt) super.javadocMissingParamTag(name,sourceStart,sourceEnd,modifiers); } public void abstractMethodInAbstractClass(SourceTypeBinding type, AbstractMethodDeclaration methodDecl) { String abstractMethodName = new String(methodDecl.selector); if (abstractMethodName.startsWith("ajc$pointcut")) { // This will already have been reported, see: PointcutDeclaration.postParse() return; } String[] arguments = new String[] {new String(type.sourceName()), abstractMethodName}; super.handle( IProblem.AbstractMethodInAbstractClass, arguments, arguments, methodDecl.sourceStart, methodDecl.sourceEnd,this.referenceContext, this.referenceContext == null ? null : this.referenceContext.compilationResult()); } /** * Called when there is an ITD marked @override that doesn't override a supertypes method. * The method and the binding are passed - some information is useful from each. The 'method' * knows about source offsets for the message, the 'binding' has the signature of what the * ITD is trying to be in the target class. */ public void itdMethodMustOverride(AbstractMethodDeclaration method,MethodBinding binding) { this.handle( IProblem.MethodMustOverride, new String[] {new String(binding.selector), typesAsString(binding.isVarargs(), binding.parameters, false), new String(binding.declaringClass.readableName()), }, new String[] {new String(binding.selector), typesAsString(binding.isVarargs(), binding.parameters, true), new String(binding.declaringClass.shortReadableName()),}, method.sourceStart, method.sourceEnd, this.referenceContext, this.referenceContext == null ? null : this.referenceContext.compilationResult()); } /** * Overrides the implementation in ProblemReporter and is ITD aware. * To report a *real* problem with an ITD marked @override, the other methodMustOverride() method is used. */ public void methodMustOverride(AbstractMethodDeclaration method) { MethodBinding binding = method.binding; // ignore ajc$ methods if (new String(method.selector).startsWith("ajc$")) return; ResolvedMember possiblyErroneousRm = factory.makeResolvedMember(method.binding); ResolvedType onTypeX = factory.fromEclipse(method.binding.declaringClass); // Can't use 'getInterTypeMungersIncludingSupers()' since that will exclude abstract ITDs // on any super classes - so we have to trawl up ourselves.. I wonder if this problem // affects other code in the problem reporter that looks through ITDs... ResolvedType supertypeToLookAt = onTypeX.getSuperclass(); while (supertypeToLookAt!=null) { List itMungers = supertypeToLookAt.getInterTypeMungers(); for (Iterator i = itMungers.iterator(); i.hasNext(); ) { ConcreteTypeMunger m = (ConcreteTypeMunger)i.next(); ResolvedMember sig = m.getSignature(); ResolvedMember rm = AjcMemberMaker.interMethod(sig,m.getAspectType(), sig.getDeclaringType().resolve(factory.getWorld()).isInterface()); if (ResolvedType.matches(rm,possiblyErroneousRm)) { // match, so dont need to report a problem! return; } } supertypeToLookAt = supertypeToLookAt.getSuperclass(); } // report the error... super.methodMustOverride(method); } private String typesAsString(boolean isVarargs, TypeBinding[] types, boolean makeShort) { StringBuffer buffer = new StringBuffer(10); for (int i = 0, length = types.length; i < length; i++) { if (i != 0) buffer.append(", "); //$NON-NLS-1$ TypeBinding type = types[i]; boolean isVarargType = isVarargs && i == length-1; if (isVarargType) type = ((ArrayBinding)type).elementsType(); buffer.append(new String(makeShort ? type.shortReadableName() : type.readableName())); if (isVarargType) buffer.append("..."); //$NON-NLS-1$ } return buffer.toString(); } public void visibilityConflict(MethodBinding currentMethod, MethodBinding inheritedMethod) { // Not quite sure if the conditions on this test are right - basically I'm saying // DONT WORRY if its ITDs since the error will be reported another way... if (isIntertypeDeclaration(currentMethod) && isIntertypeDeclaration(inheritedMethod) && Modifier.isPrivate(currentMethod.modifiers) && Modifier.isPrivate(inheritedMethod.modifiers)) { return; } super.visibilityConflict(currentMethod,inheritedMethod); } public void unusedPrivateType(TypeDeclaration typeDecl) { // don't output unused type warnings for aspects! if (!(typeDecl instanceof AspectDeclaration)) super.unusedPrivateType(typeDecl); } }
101,606
Bug 101606 AspectJ compiler does not process unused code compiler options properly for aspects
In Eclipse (3.0) click 'Window' > 'Preferences' > 'Java' > 'Compiler'. Select the 'Unused Code' tab on the compiler preference page. Change 'Unused or unread private members' to Warning or Error. Create a project that contains an aspect with some private pointcuts. You will see warnings or errors for these pointcuts saying that they are unused.
resolved fixed
2c88c59
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-02T14:44:26Z
2005-06-24T08:00:00Z
tests/src/org/aspectj/systemtest/ajc150/Ajc150Tests.java
/******************************************************************************* * Copyright (c) 2004 IBM * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Andy Clement - initial API and implementation *******************************************************************************/ package org.aspectj.systemtest.ajc150; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import junit.framework.Test; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.apache.bcel.classfile.Method; import org.aspectj.apache.bcel.util.ClassPath; import org.aspectj.apache.bcel.util.SyntheticRepository; import org.aspectj.asm.AsmManager; import org.aspectj.testing.XMLBasedAjcTestCase; import org.aspectj.util.LangUtil; /** * These are tests that will run on Java 1.4 and use the old harness format for test specification. */ public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase { public static Test suite() { return XMLBasedAjcTestCase.loadSuite(Ajc150Tests.class); } protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml"); } public void test_typeProcessingOrderWhenDeclareParents() { runTest("Order of types passed to compiler determines weaving behavior"); } public void test_aroundMethod() { runTest("method called around in class"); } public void test_aroundMethodAspect() { runTest("method called around in aspect"); } public void test_ambiguousBindingsDetection() { runTest("Various kinds of ambiguous bindings"); } public void test_ambiguousArgsDetection() { runTest("ambiguous args"); } public void testIncorrectExceptionTableWhenBreakInMethod_pr78021() { runTest("Injecting exception into while loop with break statement causes catch block to be ignored"); } public void testIncorrectExceptionTableWhenReturnInMethod_pr79554() { runTest("Return in try-block disables catch-block if final-block is present"); } public void testMissingDebugInfoForGeneratedMethods_pr82570() throws ClassNotFoundException { runTest("Weaved code does not include debug lines"); boolean f = false; JavaClass jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1"); Method[] meths = jc.getMethods(); for (int i = 0; i < meths.length; i++) { Method method = meths[i]; if (f) System.err.println("Line number table for "+method.getName()+method.getSignature()+" = "+method.getLineNumberTable()); assertTrue("Didn't find a line number table for method "+method.getName()+method.getSignature(), method.getLineNumberTable()!=null); } // This test would determine the info isn't there if you pass -g:none ... // cR = ajc(baseDir,new String[]{"PR82570_1.java","-g:none"}); // assertTrue("Expected no compile problem:"+cR,!cR.hasErrorMessages()); // System.err.println(cR.getStandardError()); // jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1"); // meths = jc.getMethods(); // for (int i = 0; i < meths.length; i++) { // Method method = meths[i]; // assertTrue("Found a line number table for method "+method.getName(), // method.getLineNumberTable()==null); // } } public void testCanOverrideProtectedMethodsViaITDandDecp_pr83303() { runTest("compiler error when mixing inheritance, overriding and polymorphism"); } public void testPerTypeWithinMissesNamedInnerTypes() { runTest("pertypewithin() handing of inner classes (1)"); } public void testPerTypeWithinMissesAnonymousInnerTypes() { runTest("pertypewithin() handing of inner classes (2)"); } public void testPerTypeWithinIncorrectlyMatchingInterfaces() { runTest("pertypewithin({interface}) illegal field modifier"); } public void test051_arrayCloningInJava5() { runTest("AJC possible bug with static nested classes"); } public void testBadASMforEnums() throws IOException { runTest("bad asm for enums"); if (LangUtil.is15VMOrGreater()) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintWriter pw = new PrintWriter(baos); AsmManager.dumptree(pw,AsmManager.getDefault().getHierarchy().getRoot(),0); pw.flush(); String tree = baos.toString(); assertTrue("Expected 'Red [enumvalue]' somewhere in here:"+tree,tree.indexOf("Red [enumvalue]")!=-1); } } public void npeOnTypeNotFound() { runTest("structure model npe on type not found"); } public void testNoRuntimeExceptionSoftening() { runTest("declare soft of runtime exception"); } public void testRuntimeNoSoftenWithHandler() { runTest("declare soft w. catch block"); } public void testSyntaxError() { runTest("invalid cons syntax"); } public void testVarargsInConsBug() { runTest("varargs in constructor sig"); } public void testAspectpathdirs() { runTest("dirs on aspectpath"); } public void testIntroSample() { runTest("introduction sample"); } public void testPTWInterface() { runTest("pertypewithin({interface}) illegal field modifier"); } public void testEnumCalledEnumEtc() { runTest("enum called Enum, annotation called Annotation, etc"); } public void testInternalCompilerError_pr86832() { runTest("Internal compiler error"); } public void testCloneMethod_pr83311() { runTest("overriding/polymorphism error on interface method introduction"); } /** * IfPointcut.findResidueInternal() was modified to make this test complete in a short amount * of time - if you see it hanging, someone has messed with the optimization. */ public void testIfEvaluationExplosion_pr94086() { runTest("Exploding compile time with if() statements in pointcut"); } public void testReflectNPE_pr94167() {runTest("NPE in reflect implementation");} public void testStaticImports_pr84260() {runTest("static import failures");} public void testGenerics_pr99089() {runTest("ArrayIndexOutOfBoundsException - Generics in privileged aspects");} public void testGenerics_pr95993() {runTest("NPE at ClassScope.java:660 when compiling generic class");} public void testItdGenerics_pr99228() {runTest("ITD of a field into a generic class");} public void testItdGenerics_pr98320() {runTest("intertype with nested generic type");} public void testItdGenerics_pr100227() {runTest("inner class with generic enclosing class");} public void testItdGenerics_pr100260() {runTest("methods inherited from a generic parent");} public void testSyntaxErrorNPE_pr103266() {runTest("NPE on syntax error");} public void testIllegalStateExceptionOnNestedParameterizedType_pr106634() { runTest("IllegalStateException unpacking signature of nested parameterized type"); } public void testParseErrorOnAnnotationStarPlusPattern() { runTest("(@Foo *)+ type pattern parse error"); } public void test_pr106130_tooManyLocals() { runTest("test weaving with > 256 locals"); } public void testMissingNamePattern_pr106461() { runTest("missing name pattern"); } public void testMissingNamePattern_pr107059() { runTest("parser crashes on call(void (@a *)(..)"); } public void testIntermediateAnnotationMatching() { runTest("intermediate annotation matching"); } public void testBadRuntimeTestGeneration() { runTest("target(@Foo *)"); } public void testErrorMessageOnITDWithTypePatterns() { runTest("clear error message on itd with type pattern"); } public void testAjKeywordsAsIdentifiers() { runTest("before and after are valid identifiers in classes"); } public void testAjKeywordsAsIdentifiers2() { runTest("before and after are valid identifiers in classes, part 2"); } public void testNoBeforeReturningAdvice() { runTest("before returning advice not allowed!"); } public void testDetectVoidFieldType() { runTest("void field type in pointcut expression"); } public void testPointcutOverriding() { runTest("overriding final pointcut from super-aspect"); } public void testAtSuppressWarnings() { runTest("@SuppressWarnings should suppress"); } public void testDEOWWithBindingPointcut() { runTest("declare warning : foo(str) : ...;"); } public void testAroundAdviceAndInterfaceInitializer() { runTest("around advice on interface initializer"); } public void testGoodErrorMessageOnUnmatchedMemberSyntax() { runTest("good error message for unmatched member syntax"); } public void testITDWithNoExceptionAndIntermediary() { runTest("itd override with no exception clause"); } public void testAnonymousInnerClasses() { runTest("anonymous inner classes"); } public void testMultipleAnonymousInnerClasses() { runTest("multiple anonymous inner classes"); } public void testPrivilegedMethodAccessorsGetRightExceptions_pr82989() { runTest("Compiler error due to a wrong exception check in try blocks"); } public void testAnonymousInnerClassWithMethodReturningTypeParameter_pr107898() { runTest("anonymous inner class with method returning type parameter"); } public void testMatchingOfObjectArray() { runTest("matching against Object[]"); } public void testMultipleAnonymousInnerClasses_pr108104() { runTest("multiple anonymous inner classes 2"); } public void testSignatureMatchingInMultipleOverrideScenario() { runTest("signature matching in override scenario"); } public void testWildcardAnnotationMatching_pr108245() { runTest("wildcard annotation matching - pr108245"); } public void testInnerTypesAndTypeVariables() { runTest("inner types and type variables"); } public void testAtAfterThrowingWithNoFormal() { runTest("@AfterThrowing with no formal specified"); } public void testParameterizedVarArgsMatch() { runTest("varargs with type variable"); } public void testFieldAccessInsideITDM() { runTest("itd field access inside itd method"); } public void testTypeVarWithTypeVarBound() { runTest("type variable with type variable bound"); } public void testEnumSwitchInITD() { runTest("switch on enum inside ITD method"); } public void testInnerTypeOfGeneric() { runTest("inner type of generic interface reference from parameterized type"); } public void testDeclareParentsIntroducingCovariantReturnType() { runTest("declare parents introducing override with covariance"); } public void testInnerClassPassedToVarargs() { runTest("inner class passed as argument to varargs method"); } public void testInlinedFieldAccessInProceedCall() { runTest("inlined field access in proceed call"); } public void testVisibiltyInSignatureMatchingWithOverridesPart1() { runTest("visibility in signature matching with overrides - 1"); } public void testVisibiltyInSignatureMatchingWithOverridesPart2() { runTest("visibility in signature matching with overrides - 2"); } public void testVisibiltyInSignatureMatchingWithOverridesPart3() { runTest("visibility in signature matching with overrides - 3"); } public void testArgsGeneratedCorrectlyForAdviceExecution() { runTest("args generated correctly for advice execution join point"); } public void testNoUnusedWarningsOnAspectTypes() { runTest("no unused warnings on aspect types"); } public void testSyntheticArgumentsOnITDConstructorsNotUsedInMatching() { runTest("synthetic arguments on itd cons are not used in matching"); } public void testParsingOfGenericTypeSignature() { runTest("parse generic type signature with parameterized type in interface"); } public void testOverrideAndCovarianceWithDecPRuntime() { runTest("override and covariance with decp - runtime"); } public void testOverrideAndCovarianceWithDecPRuntimeMultiFiles() { runTest("override and covariance with decp - runtime separate files"); } public void testAbstractSynchronizedITDMethods() { runTest("abstract synchronized itdms not detected"); } public void testSynchronizedITDInterfaceMethods() { runTest("synchronized itd interface methods"); } // helper methods..... public SyntheticRepository createRepos(File cpentry) { ClassPath cp = new ClassPath(cpentry+File.pathSeparator+System.getProperty("java.class.path")); return SyntheticRepository.getInstance(cp); } protected JavaClass getClassFrom(File where,String clazzname) throws ClassNotFoundException { SyntheticRepository repos = createRepos(where); return repos.loadClass(clazzname); } }
99,125
Bug 99125 Repetitive method name/signature in class file
This is what the VM sais: java.lang.ClassFormatError: Repetitive method name/signature in class file com/ netvisor/metadata_view/ComponentFactory at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:620) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java: 124) at java.net.URLClassLoader.defineClass(URLClassLoader.java:260) at java.net.URLClassLoader.access$100(URLClassLoader.java:56) at java.net.URLClassLoader$1.run(URLClassLoader.java:195) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:188) at java.lang.ClassLoader.loadClass(ClassLoader.java:306) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:268) at java.lang.ClassLoader.loadClass(ClassLoader.java:251) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319) And this is why: I've got an interface (ComponentFactory) and an aspect that adds various ITD methods trough that interface. I've added some methods to both the interface and the aspect, some other methods are only added trough the aspect. (The situation is a bit more complex, I've got a base interface/aspect with these two methods and the subaspects implement the problematic two methods .) And those methods that are both in the interface and the aspect are the ones that get duplicated in the interface class file. This is working fine in the old CVS branch (1.2.*). Hope it helps, good luck!
resolved fixed
df46c6f
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-02T17:12:43Z
2005-06-09T09:40:00Z
tests/bugs150/pr99125/p/I.java
99,125
Bug 99125 Repetitive method name/signature in class file
This is what the VM sais: java.lang.ClassFormatError: Repetitive method name/signature in class file com/ netvisor/metadata_view/ComponentFactory at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:620) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java: 124) at java.net.URLClassLoader.defineClass(URLClassLoader.java:260) at java.net.URLClassLoader.access$100(URLClassLoader.java:56) at java.net.URLClassLoader$1.run(URLClassLoader.java:195) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:188) at java.lang.ClassLoader.loadClass(ClassLoader.java:306) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:268) at java.lang.ClassLoader.loadClass(ClassLoader.java:251) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319) And this is why: I've got an interface (ComponentFactory) and an aspect that adds various ITD methods trough that interface. I've added some methods to both the interface and the aspect, some other methods are only added trough the aspect. (The situation is a bit more complex, I've got a base interface/aspect with these two methods and the subaspects implement the problematic two methods .) And those methods that are both in the interface and the aspect are the ones that get duplicated in the interface class file. This is working fine in the old CVS branch (1.2.*). Hope it helps, good luck!
resolved fixed
df46c6f
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-02T17:12:43Z
2005-06-09T09:40:00Z
tests/bugs150/pr99125/p/J.java
99,125
Bug 99125 Repetitive method name/signature in class file
This is what the VM sais: java.lang.ClassFormatError: Repetitive method name/signature in class file com/ netvisor/metadata_view/ComponentFactory at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:620) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java: 124) at java.net.URLClassLoader.defineClass(URLClassLoader.java:260) at java.net.URLClassLoader.access$100(URLClassLoader.java:56) at java.net.URLClassLoader$1.run(URLClassLoader.java:195) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:188) at java.lang.ClassLoader.loadClass(ClassLoader.java:306) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:268) at java.lang.ClassLoader.loadClass(ClassLoader.java:251) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319) And this is why: I've got an interface (ComponentFactory) and an aspect that adds various ITD methods trough that interface. I've added some methods to both the interface and the aspect, some other methods are only added trough the aspect. (The situation is a bit more complex, I've got a base interface/aspect with these two methods and the subaspects implement the problematic two methods .) And those methods that are both in the interface and the aspect are the ones that get duplicated in the interface class file. This is working fine in the old CVS branch (1.2.*). Hope it helps, good luck!
resolved fixed
df46c6f
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-02T17:12:43Z
2005-06-09T09:40:00Z
tests/src/org/aspectj/systemtest/ajc150/Ajc150Tests.java
/******************************************************************************* * Copyright (c) 2004 IBM * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Andy Clement - initial API and implementation *******************************************************************************/ package org.aspectj.systemtest.ajc150; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import junit.framework.Test; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.apache.bcel.classfile.Method; import org.aspectj.apache.bcel.util.ClassPath; import org.aspectj.apache.bcel.util.SyntheticRepository; import org.aspectj.asm.AsmManager; import org.aspectj.testing.XMLBasedAjcTestCase; import org.aspectj.util.LangUtil; /** * These are tests that will run on Java 1.4 and use the old harness format for test specification. */ public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase { public static Test suite() { return XMLBasedAjcTestCase.loadSuite(Ajc150Tests.class); } protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml"); } public void test_typeProcessingOrderWhenDeclareParents() { runTest("Order of types passed to compiler determines weaving behavior"); } public void test_aroundMethod() { runTest("method called around in class"); } public void test_aroundMethodAspect() { runTest("method called around in aspect"); } public void test_ambiguousBindingsDetection() { runTest("Various kinds of ambiguous bindings"); } public void test_ambiguousArgsDetection() { runTest("ambiguous args"); } public void testIncorrectExceptionTableWhenBreakInMethod_pr78021() { runTest("Injecting exception into while loop with break statement causes catch block to be ignored"); } public void testIncorrectExceptionTableWhenReturnInMethod_pr79554() { runTest("Return in try-block disables catch-block if final-block is present"); } public void testMissingDebugInfoForGeneratedMethods_pr82570() throws ClassNotFoundException { runTest("Weaved code does not include debug lines"); boolean f = false; JavaClass jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1"); Method[] meths = jc.getMethods(); for (int i = 0; i < meths.length; i++) { Method method = meths[i]; if (f) System.err.println("Line number table for "+method.getName()+method.getSignature()+" = "+method.getLineNumberTable()); assertTrue("Didn't find a line number table for method "+method.getName()+method.getSignature(), method.getLineNumberTable()!=null); } // This test would determine the info isn't there if you pass -g:none ... // cR = ajc(baseDir,new String[]{"PR82570_1.java","-g:none"}); // assertTrue("Expected no compile problem:"+cR,!cR.hasErrorMessages()); // System.err.println(cR.getStandardError()); // jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1"); // meths = jc.getMethods(); // for (int i = 0; i < meths.length; i++) { // Method method = meths[i]; // assertTrue("Found a line number table for method "+method.getName(), // method.getLineNumberTable()==null); // } } public void testCanOverrideProtectedMethodsViaITDandDecp_pr83303() { runTest("compiler error when mixing inheritance, overriding and polymorphism"); } public void testPerTypeWithinMissesNamedInnerTypes() { runTest("pertypewithin() handing of inner classes (1)"); } public void testPerTypeWithinMissesAnonymousInnerTypes() { runTest("pertypewithin() handing of inner classes (2)"); } public void testPerTypeWithinIncorrectlyMatchingInterfaces() { runTest("pertypewithin({interface}) illegal field modifier"); } public void test051_arrayCloningInJava5() { runTest("AJC possible bug with static nested classes"); } public void testBadASMforEnums() throws IOException { runTest("bad asm for enums"); if (LangUtil.is15VMOrGreater()) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintWriter pw = new PrintWriter(baos); AsmManager.dumptree(pw,AsmManager.getDefault().getHierarchy().getRoot(),0); pw.flush(); String tree = baos.toString(); assertTrue("Expected 'Red [enumvalue]' somewhere in here:"+tree,tree.indexOf("Red [enumvalue]")!=-1); } } public void npeOnTypeNotFound() { runTest("structure model npe on type not found"); } public void testNoRuntimeExceptionSoftening() { runTest("declare soft of runtime exception"); } public void testRuntimeNoSoftenWithHandler() { runTest("declare soft w. catch block"); } public void testSyntaxError() { runTest("invalid cons syntax"); } public void testVarargsInConsBug() { runTest("varargs in constructor sig"); } public void testAspectpathdirs() { runTest("dirs on aspectpath"); } public void testIntroSample() { runTest("introduction sample"); } public void testPTWInterface() { runTest("pertypewithin({interface}) illegal field modifier"); } public void testEnumCalledEnumEtc() { runTest("enum called Enum, annotation called Annotation, etc"); } public void testInternalCompilerError_pr86832() { runTest("Internal compiler error"); } public void testCloneMethod_pr83311() { runTest("overriding/polymorphism error on interface method introduction"); } /** * IfPointcut.findResidueInternal() was modified to make this test complete in a short amount * of time - if you see it hanging, someone has messed with the optimization. */ public void testIfEvaluationExplosion_pr94086() { runTest("Exploding compile time with if() statements in pointcut"); } public void testReflectNPE_pr94167() {runTest("NPE in reflect implementation");} public void testStaticImports_pr84260() {runTest("static import failures");} public void testGenerics_pr99089() {runTest("ArrayIndexOutOfBoundsException - Generics in privileged aspects");} public void testGenerics_pr95993() {runTest("NPE at ClassScope.java:660 when compiling generic class");} public void testItdGenerics_pr99228() {runTest("ITD of a field into a generic class");} public void testItdGenerics_pr98320() {runTest("intertype with nested generic type");} public void testItdGenerics_pr100227() {runTest("inner class with generic enclosing class");} public void testItdGenerics_pr100260() {runTest("methods inherited from a generic parent");} public void testSyntaxErrorNPE_pr103266() {runTest("NPE on syntax error");} public void testIllegalStateExceptionOnNestedParameterizedType_pr106634() { runTest("IllegalStateException unpacking signature of nested parameterized type"); } public void testParseErrorOnAnnotationStarPlusPattern() { runTest("(@Foo *)+ type pattern parse error"); } public void test_pr106130_tooManyLocals() { runTest("test weaving with > 256 locals"); } public void testMissingNamePattern_pr106461() { runTest("missing name pattern"); } public void testMissingNamePattern_pr107059() { runTest("parser crashes on call(void (@a *)(..)"); } public void testIntermediateAnnotationMatching() { runTest("intermediate annotation matching"); } public void testBadRuntimeTestGeneration() { runTest("target(@Foo *)"); } public void testErrorMessageOnITDWithTypePatterns() { runTest("clear error message on itd with type pattern"); } public void testAjKeywordsAsIdentifiers() { runTest("before and after are valid identifiers in classes"); } public void testAjKeywordsAsIdentifiers2() { runTest("before and after are valid identifiers in classes, part 2"); } public void testNoBeforeReturningAdvice() { runTest("before returning advice not allowed!"); } public void testDetectVoidFieldType() { runTest("void field type in pointcut expression"); } public void testPointcutOverriding() { runTest("overriding final pointcut from super-aspect"); } public void testAtSuppressWarnings() { runTest("@SuppressWarnings should suppress"); } public void testDEOWWithBindingPointcut() { runTest("declare warning : foo(str) : ...;"); } public void testAroundAdviceAndInterfaceInitializer() { runTest("around advice on interface initializer"); } public void testGoodErrorMessageOnUnmatchedMemberSyntax() { runTest("good error message for unmatched member syntax"); } public void testITDWithNoExceptionAndIntermediary() { runTest("itd override with no exception clause"); } public void testAnonymousInnerClasses() { runTest("anonymous inner classes"); } public void testMultipleAnonymousInnerClasses() { runTest("multiple anonymous inner classes"); } public void testPrivilegedMethodAccessorsGetRightExceptions_pr82989() { runTest("Compiler error due to a wrong exception check in try blocks"); } public void testAnonymousInnerClassWithMethodReturningTypeParameter_pr107898() { runTest("anonymous inner class with method returning type parameter"); } public void testMatchingOfObjectArray() { runTest("matching against Object[]"); } public void testMultipleAnonymousInnerClasses_pr108104() { runTest("multiple anonymous inner classes 2"); } public void testSignatureMatchingInMultipleOverrideScenario() { runTest("signature matching in override scenario"); } public void testWildcardAnnotationMatching_pr108245() { runTest("wildcard annotation matching - pr108245"); } public void testInnerTypesAndTypeVariables() { runTest("inner types and type variables"); } public void testAtAfterThrowingWithNoFormal() { runTest("@AfterThrowing with no formal specified"); } public void testParameterizedVarArgsMatch() { runTest("varargs with type variable"); } public void testFieldAccessInsideITDM() { runTest("itd field access inside itd method"); } public void testTypeVarWithTypeVarBound() { runTest("type variable with type variable bound"); } public void testEnumSwitchInITD() { runTest("switch on enum inside ITD method"); } public void testInnerTypeOfGeneric() { runTest("inner type of generic interface reference from parameterized type"); } public void testDeclareParentsIntroducingCovariantReturnType() { runTest("declare parents introducing override with covariance"); } public void testInnerClassPassedToVarargs() { runTest("inner class passed as argument to varargs method"); } public void testInlinedFieldAccessInProceedCall() { runTest("inlined field access in proceed call"); } public void testVisibiltyInSignatureMatchingWithOverridesPart1() { runTest("visibility in signature matching with overrides - 1"); } public void testVisibiltyInSignatureMatchingWithOverridesPart2() { runTest("visibility in signature matching with overrides - 2"); } public void testVisibiltyInSignatureMatchingWithOverridesPart3() { runTest("visibility in signature matching with overrides - 3"); } public void testArgsGeneratedCorrectlyForAdviceExecution() { runTest("args generated correctly for advice execution join point"); } public void testNoUnusedWarningsOnAspectTypes() { runTest("no unused warnings on aspect types"); } public void testSyntheticArgumentsOnITDConstructorsNotUsedInMatching() { runTest("synthetic arguments on itd cons are not used in matching"); } public void testParsingOfGenericTypeSignature() { runTest("parse generic type signature with parameterized type in interface"); } public void testOverrideAndCovarianceWithDecPRuntime() { runTest("override and covariance with decp - runtime"); } public void testOverrideAndCovarianceWithDecPRuntimeMultiFiles() { runTest("override and covariance with decp - runtime separate files"); } public void testAbstractSynchronizedITDMethods() { runTest("abstract synchronized itdms not detected"); } public void testSynchronizedITDInterfaceMethods() { runTest("synchronized itd interface methods"); } public void testNoWarningOnUnusedPointcut() { runTest("unused private pointcuts"); } // helper methods..... public SyntheticRepository createRepos(File cpentry) { ClassPath cp = new ClassPath(cpentry+File.pathSeparator+System.getProperty("java.class.path")); return SyntheticRepository.getInstance(cp); } protected JavaClass getClassFrom(File where,String clazzname) throws ClassNotFoundException { SyntheticRepository repos = createRepos(where); return repos.loadClass(clazzname); } }
99,125
Bug 99125 Repetitive method name/signature in class file
This is what the VM sais: java.lang.ClassFormatError: Repetitive method name/signature in class file com/ netvisor/metadata_view/ComponentFactory at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:620) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java: 124) at java.net.URLClassLoader.defineClass(URLClassLoader.java:260) at java.net.URLClassLoader.access$100(URLClassLoader.java:56) at java.net.URLClassLoader$1.run(URLClassLoader.java:195) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:188) at java.lang.ClassLoader.loadClass(ClassLoader.java:306) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:268) at java.lang.ClassLoader.loadClass(ClassLoader.java:251) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319) And this is why: I've got an interface (ComponentFactory) and an aspect that adds various ITD methods trough that interface. I've added some methods to both the interface and the aspect, some other methods are only added trough the aspect. (The situation is a bit more complex, I've got a base interface/aspect with these two methods and the subaspects implement the problematic two methods .) And those methods that are both in the interface and the aspect are the ones that get duplicated in the interface class file. This is working fine in the old CVS branch (1.2.*). Hope it helps, good luck!
resolved fixed
df46c6f
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-02T17:12:43Z
2005-06-09T09:40:00Z
weaver/src/org/aspectj/weaver/bcel/BcelTypeMunger.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.bcel; import java.lang.reflect.Modifier; import java.util.Iterator; import java.util.List; import java.util.Set; import org.aspectj.apache.bcel.Constants; import org.aspectj.apache.bcel.classfile.annotation.Annotation; import org.aspectj.apache.bcel.generic.ConstantPoolGen; import org.aspectj.apache.bcel.generic.FieldGen; import org.aspectj.apache.bcel.generic.INVOKESPECIAL; import org.aspectj.apache.bcel.generic.InstructionConstants; import org.aspectj.apache.bcel.generic.InstructionFactory; import org.aspectj.apache.bcel.generic.InstructionHandle; import org.aspectj.apache.bcel.generic.InstructionList; import org.aspectj.apache.bcel.generic.Type; import org.aspectj.apache.bcel.generic.annotation.AnnotationGen; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; import org.aspectj.bridge.WeaveMessage; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.AnnotationOnTypeMunger; import org.aspectj.weaver.AnnotationX; import org.aspectj.weaver.AsmRelationshipProvider; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ConcreteTypeMunger; import org.aspectj.weaver.Member; import org.aspectj.weaver.NameMangler; import org.aspectj.weaver.NewConstructorTypeMunger; import org.aspectj.weaver.NewFieldTypeMunger; import org.aspectj.weaver.NewMethodTypeMunger; import org.aspectj.weaver.NewParentTypeMunger; import org.aspectj.weaver.PerObjectInterfaceTypeMunger; import org.aspectj.weaver.PrivilegedAccessMunger; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.ResolvedTypeMunger; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.WeaverStateInfo; import org.aspectj.weaver.AjAttribute.EffectiveSignatureAttribute; import org.aspectj.weaver.patterns.DeclareAnnotation; import org.aspectj.weaver.patterns.Pointcut; //XXX addLazyMethodGen is probably bad everywhere public class BcelTypeMunger extends ConcreteTypeMunger { public BcelTypeMunger(ResolvedTypeMunger munger, ResolvedType aspectType) { super(munger, aspectType); } public String toString() { return "(BcelTypeMunger " + getMunger() + ")"; } public boolean munge(BcelClassWeaver weaver) { boolean changed = false; boolean worthReporting = true; if (munger.getKind() == ResolvedTypeMunger.Field) { changed = mungeNewField(weaver, (NewFieldTypeMunger)munger); } else if (munger.getKind() == ResolvedTypeMunger.Method) { changed = mungeNewMethod(weaver, (NewMethodTypeMunger)munger); } else if (munger.getKind() == ResolvedTypeMunger.PerObjectInterface) { changed = mungePerObjectInterface(weaver, (PerObjectInterfaceTypeMunger)munger); worthReporting = false; } else if (munger.getKind() == ResolvedTypeMunger.PerTypeWithinInterface) { // PTWIMPL Transform the target type (add the aspect instance field) changed = mungePerTypeWithinTransformer(weaver); worthReporting = false; } else if (munger.getKind() == ResolvedTypeMunger.PrivilegedAccess) { changed = mungePrivilegedAccess(weaver, (PrivilegedAccessMunger)munger); worthReporting = false; } else if (munger.getKind() == ResolvedTypeMunger.Constructor) { changed = mungeNewConstructor(weaver, (NewConstructorTypeMunger)munger); } else if (munger.getKind() == ResolvedTypeMunger.Parent) { changed = mungeNewParent(weaver, (NewParentTypeMunger)munger); } else if (munger.getKind() == ResolvedTypeMunger.AnnotationOnType) { changed = mungeNewAnnotationOnType(weaver,(AnnotationOnTypeMunger)munger); } else { throw new RuntimeException("unimplemented"); } if (changed && munger.changesPublicSignature()) { WeaverStateInfo info = weaver.getLazyClassGen().getOrCreateWeaverStateInfo(); info.addConcreteMunger(this); } // Whilst type mungers aren't persisting their source locations, we add this relationship during // compilation time (see other reference to ResolvedTypeMunger.persist) if (ResolvedTypeMunger.persistSourceLocation) { if (changed && worthReporting) { if (munger.getKind().equals(ResolvedTypeMunger.Parent)) { AsmRelationshipProvider.getDefault().addRelationship(weaver.getLazyClassGen().getType(), munger,getAspectType()); } else { AsmRelationshipProvider.getDefault().addRelationship(weaver.getLazyClassGen().getType(), munger,getAspectType()); } } } // TAG: WeavingMessage if (changed && worthReporting && munger!=null && !weaver.getWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)) { String tName = weaver.getLazyClassGen().getType().getSourceLocation().getSourceFile().getName(); if (tName.indexOf("no debug info available")!=-1) tName = "no debug info available"; else tName = getShortname(weaver.getLazyClassGen().getType().getSourceLocation().getSourceFile().getPath()); String fName = getShortname(getAspectType().getSourceLocation().getSourceFile().getPath()); if (munger.getKind().equals(ResolvedTypeMunger.Parent)) { // This message could come out of AjLookupEnvironment.addParent if doing parents // munging at compile time only... NewParentTypeMunger parentTM = (NewParentTypeMunger)munger; if (parentTM.getNewParent().isInterface()) { weaver.getWorld().getMessageHandler().handleMessage(WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_DECLAREPARENTSIMPLEMENTS, new String[]{weaver.getLazyClassGen().getType().getName(), tName,parentTM.getNewParent().getName(),fName}, weaver.getLazyClassGen().getClassName(), getAspectType().getName())); } else { weaver.getWorld().getMessageHandler().handleMessage( WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_DECLAREPARENTSEXTENDS, new String[]{weaver.getLazyClassGen().getType().getName(), tName,parentTM.getNewParent().getName(),fName })); // TAG: WeavingMessage DECLARE PARENTS: EXTENDS // reportDeclareParentsMessage(WeaveMessage.WEAVEMESSAGE_DECLAREPARENTSEXTENDS,sourceType,parent); } } else { weaver.getWorld().getMessageHandler().handleMessage(WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_ITD, new String[]{weaver.getLazyClassGen().getType().getName(), tName,munger.getKind().toString().toLowerCase(), getAspectType().getName(), fName+":'"+munger.getSignature()+"'"}, weaver.getLazyClassGen().getClassName(), getAspectType().getName())); } } return changed; } private String getShortname(String path) { int takefrom = path.lastIndexOf('/'); if (takefrom == -1) { takefrom = path.lastIndexOf('\\'); } return path.substring(takefrom+1); } private boolean mungeNewAnnotationOnType(BcelClassWeaver weaver,AnnotationOnTypeMunger munger) { // FIXME asc this has already been done up front, need to do it here too? weaver.getLazyClassGen().addAnnotation(munger.getNewAnnotation().getBcelAnnotation()); return true; } /** * For a long time, AspectJ did not allow binary weaving of declare parents. This restriction is now lifted * but could do with more testing! */ private boolean mungeNewParent(BcelClassWeaver weaver, NewParentTypeMunger munger) { LazyClassGen newParentTarget = weaver.getLazyClassGen(); ResolvedType newParent = munger.getNewParent(); boolean cont = true; // Set to false when we error, so we don't actually *do* the munge cont = enforceDecpRule1_abstractMethodsImplemented(weaver, munger.getSourceLocation(),newParentTarget, newParent); cont = enforceDecpRule2_cantExtendFinalClass(weaver,munger.getSourceLocation(),newParentTarget,newParent) && cont; List methods = newParent.getMethodsWithoutIterator(false); for (Iterator iter = methods.iterator(); iter.hasNext();) { ResolvedMember superMethod = (ResolvedMember) iter.next(); if (!superMethod.getName().equals("<init>")) { LazyMethodGen subMethod = findMatchingMethod(newParentTarget, superMethod); if (subMethod!=null) { cont = enforceDecpRule3_visibilityChanges(weaver, newParent, superMethod, subMethod) && cont; cont = enforceDecpRule4_compatibleReturnTypes(weaver, superMethod, subMethod) && cont; cont = enforceDecpRule5_cantChangeFromStaticToNonstatic(weaver,munger.getSourceLocation(),superMethod,subMethod) && cont; } } } if (!cont) return false; // A rule was violated and an error message already reported if (newParent.isClass()) { // Changing the supertype if (!attemptToModifySuperCalls(weaver,newParentTarget,newParent)) return false; newParentTarget.setSuperClass(newParent); } else { // Adding a new interface newParentTarget.addInterface(newParent,getSourceLocation()); } return true; } /** * Rule 1: For the declare parents to be allowed, the target type must override and implement * inherited abstract methods (if the type is not declared abstract) */ private boolean enforceDecpRule1_abstractMethodsImplemented(BcelClassWeaver weaver, ISourceLocation mungerLoc,LazyClassGen newParentTarget, ResolvedType newParent) { boolean ruleCheckingSucceeded = true; if (!(newParentTarget.isAbstract() || newParentTarget.isInterface())) { // Ignore abstract classes or interfaces List methods = newParent.getMethodsWithoutIterator(false); for (Iterator i = methods.iterator(); i.hasNext();) { ResolvedMember o = (ResolvedMember)i.next(); if (o.isAbstract() && !o.getName().startsWith("ajc$interField")) { // Ignore abstract methods of ajc$interField prefixed methods ResolvedMember discoveredImpl = null; List newParentTargetMethods = newParentTarget.getType().getMethodsWithoutIterator(false); for (Iterator ii = newParentTargetMethods.iterator(); ii.hasNext() && discoveredImpl==null;) { ResolvedMember gen2 = (ResolvedMember) ii.next(); if (gen2.getName().equals(o.getName()) && gen2.getParameterSignature().equals(o.getParameterSignature()) && !gen2.isAbstract()) { discoveredImpl = gen2; // Found a valid implementation ! } } if (discoveredImpl == null) { // didnt find a valid implementation, lets check the ITDs on this type to see if they satisfy it boolean satisfiedByITD = false; for (Iterator ii = newParentTarget.getType().getInterTypeMungersIncludingSupers().iterator(); ii.hasNext(); ) { ConcreteTypeMunger m = (ConcreteTypeMunger)ii.next(); if (m.getMunger() instanceof NewMethodTypeMunger) { ResolvedMember sig = m.getSignature(); if (!Modifier.isAbstract(sig.getModifiers())) { if (ResolvedType .matches( AjcMemberMaker.interMethod( sig,m.getAspectType(),sig.getDeclaringType().resolve(weaver.getWorld()).isInterface()),o)) { satisfiedByITD = true; } } } } if (!satisfiedByITD) { error(weaver, "The type " + newParentTarget.getName() + " must implement the inherited abstract method "+o.getDeclaringType()+"."+o.getName()+o.getParameterSignature(), newParentTarget.getType().getSourceLocation(),new ISourceLocation[]{o.getSourceLocation(),mungerLoc}); ruleCheckingSucceeded=false; } } } } } return ruleCheckingSucceeded; } /** * Rule 2. Can't extend final types */ private boolean enforceDecpRule2_cantExtendFinalClass(BcelClassWeaver weaver, ISourceLocation mungerLoc, LazyClassGen newParentTarget, ResolvedType newParent) { if (newParent.isFinal()) { error(weaver,"Cannot make type "+newParentTarget.getName()+" extend final class "+newParent.getName(), newParentTarget.getType().getSourceLocation(), new ISourceLocation[]{mungerLoc}); return false; } return true; } /** * Rule 3. Can't narrow visibility of methods when overriding */ private boolean enforceDecpRule3_visibilityChanges(BcelClassWeaver weaver, ResolvedType newParent, ResolvedMember superMethod, LazyMethodGen subMethod) { boolean cont = true; if (superMethod.isPublic()) { if (subMethod.isProtected() || subMethod.isDefault() || subMethod.isPrivate()) { weaver.getWorld().getMessageHandler().handleMessage(MessageUtil.error( "Cannot reduce the visibility of the inherited method '"+superMethod+"' from "+newParent.getName(), superMethod.getSourceLocation())); cont=false; } } else if (superMethod.isProtected()) { if (subMethod.isDefault() || subMethod.isPrivate()) { weaver.getWorld().getMessageHandler().handleMessage(MessageUtil.error( "Cannot reduce the visibility of the inherited method '"+superMethod+"' from "+newParent.getName(), superMethod.getSourceLocation())); cont=false; } } else if (superMethod.isDefault()) { if (subMethod.isPrivate()) { weaver.getWorld().getMessageHandler().handleMessage(MessageUtil.error( "Cannot reduce the visibility of the inherited method '"+superMethod+"' from "+newParent.getName(), superMethod.getSourceLocation())); cont=false; } } return cont; } /** * Rule 4. Can't have incompatible return types */ private boolean enforceDecpRule4_compatibleReturnTypes(BcelClassWeaver weaver, ResolvedMember superMethod, LazyMethodGen subMethod) { boolean cont = true; String superReturnTypeSig = superMethod.getReturnType().getSignature(); String subReturnTypeSig = subMethod.getReturnType().getSignature(); if (!superReturnTypeSig.equals(subReturnTypeSig)) { // Allow for covariance - wish I could test this (need Java5...) ResolvedType subType = weaver.getWorld().resolve(subMethod.getReturnType()); ResolvedType superType = weaver.getWorld().resolve(superMethod.getReturnType()); if (!superType.isAssignableFrom(subType)) { ISourceLocation sloc = subMethod.getSourceLocation(); weaver.getWorld().getMessageHandler().handleMessage(MessageUtil.error( "The return type is incompatible with "+superMethod.getDeclaringType()+"."+superMethod.getName()+superMethod.getParameterSignature(), subMethod.getSourceLocation())); cont=false; } } return cont; } /** * Rule5. Method overrides can't change the staticality (word?) - you can't override and make an instance * method static or override and make a static method an instance method. */ private boolean enforceDecpRule5_cantChangeFromStaticToNonstatic(BcelClassWeaver weaver,ISourceLocation mungerLoc,ResolvedMember superMethod, LazyMethodGen subMethod ) { if (superMethod.isStatic() && !subMethod.isStatic()) { error(weaver,"This instance method "+subMethod.getName()+subMethod.getParameterSignature()+ " cannot override the static method from "+superMethod.getDeclaringType().getName(), subMethod.getSourceLocation(),new ISourceLocation[]{mungerLoc}); return false; } else if (!superMethod.isStatic() && subMethod.isStatic()) { error(weaver,"The static method "+subMethod.getName()+subMethod.getParameterSignature()+ " cannot hide the instance method from "+superMethod.getDeclaringType().getName(), subMethod.getSourceLocation(),new ISourceLocation[]{mungerLoc}); return false; } return true; } public void error(BcelClassWeaver weaver,String text,ISourceLocation primaryLoc,ISourceLocation[] extraLocs) { IMessage msg = new Message(text, primaryLoc, true, extraLocs); weaver.getWorld().getMessageHandler().handleMessage(msg); } private LazyMethodGen findMatchingMethod(LazyClassGen newParentTarget, ResolvedMember m) { LazyMethodGen found = null; // Search the type for methods overriding super methods (methods that come from the new parent) // Don't use the return value in the comparison as overriding doesnt for (Iterator i = newParentTarget.getMethodGens().iterator(); i.hasNext() && found==null;) { LazyMethodGen gen = (LazyMethodGen) i.next(); if (gen.getName().equals(m.getName()) && gen.getParameterSignature().equals(m.getParameterSignature())) { found = gen; } } return found; } /** * The main part of implementing declare parents extends. Modify super ctor calls to target the new type. */ public boolean attemptToModifySuperCalls(BcelClassWeaver weaver,LazyClassGen newParentTarget, ResolvedType newParent) { String currentParent = newParentTarget.getSuperClassname(); List mgs = newParentTarget.getMethodGens(); // Look for ctors to modify for (Iterator iter = mgs.iterator(); iter.hasNext();) { LazyMethodGen aMethod = (LazyMethodGen) iter.next(); if (aMethod.getName().equals("<init>")) { InstructionList insList = aMethod.getBody(); InstructionHandle handle = insList.getStart(); while (handle!= null) { if (handle.getInstruction() instanceof INVOKESPECIAL) { ConstantPoolGen cpg = newParentTarget.getConstantPoolGen(); INVOKESPECIAL invokeSpecial = (INVOKESPECIAL)handle.getInstruction(); if (invokeSpecial.getClassName(cpg).equals(currentParent) && invokeSpecial.getMethodName(cpg).equals("<init>")) { // System.err.println("Transforming super call '<init>"+sp.getSignature(cpg)+"'"); // 1. Check there is a ctor in the new parent with the same signature ResolvedMember newCtor = getConstructorWithSignature(newParent,invokeSpecial.getSignature(cpg)); if (newCtor == null) { // 2. Check ITDCs to see if the necessary ctor is provided that way boolean satisfiedByITDC = false; for (Iterator ii = newParentTarget.getType().getInterTypeMungersIncludingSupers().iterator(); ii.hasNext() && !satisfiedByITDC; ) { ConcreteTypeMunger m = (ConcreteTypeMunger)ii.next(); if (m.getMunger() instanceof NewConstructorTypeMunger) { if (m.getSignature().getSignature().equals(invokeSpecial.getSignature(cpg))) { satisfiedByITDC = true; } } } if (!satisfiedByITDC) { String csig = createReadableCtorSig(newParent, cpg, invokeSpecial); weaver.getWorld().getMessageHandler().handleMessage(MessageUtil.error( "Unable to modify hierarchy for "+newParentTarget.getClassName()+" - the constructor "+ csig+" is missing",this.getSourceLocation())); return false; } } int idx = cpg.addMethodref(newParent.getClassName(), invokeSpecial.getMethodName(cpg), invokeSpecial.getSignature(cpg)); invokeSpecial.setIndex(idx); } } handle = handle.getNext(); } } } return true; } /** * Creates a nice signature for the ctor, something like "(int,Integer,String)" */ private String createReadableCtorSig(ResolvedType newParent, ConstantPoolGen cpg, INVOKESPECIAL invokeSpecial) { StringBuffer sb = new StringBuffer(); Type[] ctorArgs = invokeSpecial.getArgumentTypes(cpg); sb.append(newParent.getClassName()); sb.append("("); for (int i = 0; i < ctorArgs.length; i++) { String argtype = ctorArgs[i].toString(); if (argtype.lastIndexOf(".")!=-1) sb.append(argtype.substring(argtype.lastIndexOf(".")+1)); else sb.append(argtype); if (i+1<ctorArgs.length) sb.append(","); } sb.append(")"); return sb.toString(); } private ResolvedMember getConstructorWithSignature(ResolvedType tx,String signature) { ResolvedMember[] mems = tx.getDeclaredJavaMethods(); for (int i = 0; i < mems.length; i++) { ResolvedMember rm = mems[i]; if (rm.getName().equals("<init>")) { if (rm.getSignature().equals(signature)) return rm; } } return null; } private boolean mungePrivilegedAccess( BcelClassWeaver weaver, PrivilegedAccessMunger munger) { LazyClassGen gen = weaver.getLazyClassGen(); ResolvedMember member = munger.getMember(); ResolvedType onType = weaver.getWorld().resolve(member.getDeclaringType(),munger.getSourceLocation()); if (onType.isRawType()) onType = onType.getGenericType(); //System.out.println("munging: " + gen + " with " + member); if (onType.equals(gen.getType())) { if (member.getKind() == Member.FIELD) { //System.out.println("matched: " + gen); addFieldGetter(gen, member, AjcMemberMaker.privilegedAccessMethodForFieldGet(aspectType, member)); addFieldSetter(gen, member, AjcMemberMaker.privilegedAccessMethodForFieldSet(aspectType, member)); return true; } else if (member.getKind() == Member.METHOD) { addMethodDispatch(gen, member, AjcMemberMaker.privilegedAccessMethodForMethod(aspectType, member)); return true; } else if (member.getKind() == Member.CONSTRUCTOR) { for (Iterator i = gen.getMethodGens().iterator(); i.hasNext(); ) { LazyMethodGen m = (LazyMethodGen)i.next(); if (m.getMemberView() != null && m.getMemberView().getKind() == Member.CONSTRUCTOR) { // m.getMemberView().equals(member)) { m.forcePublic(); //return true; } } return true; //throw new BCException("no match for " + member + " in " + gen); } else if (member.getKind() == Member.STATIC_INITIALIZATION) { gen.forcePublic(); return true; } else { throw new RuntimeException("unimplemented"); } } return false; } private void addFieldGetter( LazyClassGen gen, ResolvedMember field, ResolvedMember accessMethod) { LazyMethodGen mg = makeMethodGen(gen, accessMethod); InstructionList il = new InstructionList(); InstructionFactory fact = gen.getFactory(); if (field.isStatic()) { il.append(fact.createFieldAccess( gen.getClassName(), field.getName(), BcelWorld.makeBcelType(field.getType()), Constants.GETSTATIC)); } else { il.append(InstructionConstants.ALOAD_0); il.append(fact.createFieldAccess( gen.getClassName(), field.getName(), BcelWorld.makeBcelType(field.getType()), Constants.GETFIELD)); } il.append(InstructionFactory.createReturn(BcelWorld.makeBcelType(field.getType()))); mg.getBody().insert(il); gen.addMethodGen(mg,getSignature().getSourceLocation()); } private void addFieldSetter( LazyClassGen gen, ResolvedMember field, ResolvedMember accessMethod) { LazyMethodGen mg = makeMethodGen(gen, accessMethod); InstructionList il = new InstructionList(); InstructionFactory fact = gen.getFactory(); Type fieldType = BcelWorld.makeBcelType(field.getType()); if (field.isStatic()) { il.append(InstructionFactory.createLoad(fieldType, 0)); il.append(fact.createFieldAccess( gen.getClassName(), field.getName(), fieldType, Constants.PUTSTATIC)); } else { il.append(InstructionConstants.ALOAD_0); il.append(InstructionFactory.createLoad(fieldType, 1)); il.append(fact.createFieldAccess( gen.getClassName(), field.getName(), fieldType, Constants.PUTFIELD)); } il.append(InstructionFactory.createReturn(Type.VOID)); mg.getBody().insert(il); gen.addMethodGen(mg,getSignature().getSourceLocation()); } private void addMethodDispatch( LazyClassGen gen, ResolvedMember method, ResolvedMember accessMethod) { LazyMethodGen mg = makeMethodGen(gen, accessMethod); InstructionList il = new InstructionList(); InstructionFactory fact = gen.getFactory(); //Type fieldType = BcelWorld.makeBcelType(field.getType()); Type[] paramTypes = BcelWorld.makeBcelTypes(method.getParameterTypes()); int pos = 0; if (!method.isStatic()) { il.append(InstructionConstants.ALOAD_0); pos++; } for (int i = 0, len = paramTypes.length; i < len; i++) { Type paramType = paramTypes[i]; il.append(InstructionFactory.createLoad(paramType, pos)); pos+=paramType.getSize(); } il.append(Utility.createInvoke(fact, (BcelWorld)aspectType.getWorld(), method)); il.append(InstructionFactory.createReturn(BcelWorld.makeBcelType(method.getReturnType()))); mg.getBody().insert(il); gen.addMethodGen(mg); } protected LazyMethodGen makeMethodGen(LazyClassGen gen, ResolvedMember member) { LazyMethodGen ret = new LazyMethodGen( member.getModifiers(), BcelWorld.makeBcelType(member.getReturnType()), member.getName(), BcelWorld.makeBcelTypes(member.getParameterTypes()), UnresolvedType.getNames(member.getExceptions()), gen); // 43972 : Static crosscutting makes interfaces unusable for javac // ret.makeSynthetic(); return ret; } protected FieldGen makeFieldGen(LazyClassGen gen, ResolvedMember member) { return new FieldGen( member.getModifiers(), BcelWorld.makeBcelType(member.getReturnType()), member.getName(), gen.getConstantPoolGen()); } private boolean mungePerObjectInterface( BcelClassWeaver weaver, PerObjectInterfaceTypeMunger munger) { LazyClassGen gen = weaver.getLazyClassGen(); if (couldMatch(gen.getBcelObjectType(), munger.getTestPointcut())) { FieldGen fg = makeFieldGen(gen, AjcMemberMaker.perObjectField(gen.getType(), aspectType)); gen.addField(fg.getField(),getSourceLocation()); Type fieldType = BcelWorld.makeBcelType(aspectType); LazyMethodGen mg = new LazyMethodGen( Modifier.PUBLIC, fieldType, NameMangler.perObjectInterfaceGet(aspectType), new Type[0], new String[0], gen); InstructionList il = new InstructionList(); InstructionFactory fact = gen.getFactory(); il.append(InstructionConstants.ALOAD_0); il.append(fact.createFieldAccess( gen.getClassName(), fg.getName(), fieldType, Constants.GETFIELD)); il.append(InstructionFactory.createReturn(fieldType)); mg.getBody().insert(il); gen.addMethodGen(mg); LazyMethodGen mg1 = new LazyMethodGen( Modifier.PUBLIC, Type.VOID, NameMangler.perObjectInterfaceSet(aspectType), new Type[]{fieldType,}, new String[0], gen); InstructionList il1 = new InstructionList(); il1.append(InstructionConstants.ALOAD_0); il1.append(InstructionFactory.createLoad(fieldType, 1)); il1.append(fact.createFieldAccess( gen.getClassName(), fg.getName(), fieldType, Constants.PUTFIELD)); il1.append(InstructionFactory.createReturn(Type.VOID)); mg1.getBody().insert(il1); gen.addMethodGen(mg1); gen.addInterface(munger.getInterfaceType(),getSourceLocation()); return true; } else { return false; } } // PTWIMPL Add field to hold aspect instance and an accessor private boolean mungePerTypeWithinTransformer(BcelClassWeaver weaver) { LazyClassGen gen = weaver.getLazyClassGen(); // if (couldMatch(gen.getBcelObjectType(), munger.getTestPointcut())) { // Add (to the target type) the field that will hold the aspect instance // e.g ajc$com_blah_SecurityAspect$ptwAspectInstance FieldGen fg = makeFieldGen(gen, AjcMemberMaker.perTypeWithinField(gen.getType(), aspectType)); gen.addField(fg.getField(),getSourceLocation()); // Add an accessor for this new field, the ajc$<aspectname>$localAspectOf() method // e.g. "public com_blah_SecurityAspect ajc$com_blah_SecurityAspect$localAspectOf()" Type fieldType = BcelWorld.makeBcelType(aspectType); LazyMethodGen mg = new LazyMethodGen( Modifier.PUBLIC | Modifier.STATIC,fieldType, NameMangler.perTypeWithinLocalAspectOf(aspectType), new Type[0], new String[0],gen); InstructionList il = new InstructionList(); //PTWIMPL ?? Should check if it is null and throw NoAspectBoundException InstructionFactory fact = gen.getFactory(); il.append(fact.createFieldAccess( gen.getClassName(), fg.getName(), fieldType, Constants.GETSTATIC)); il.append(InstructionFactory.createReturn(fieldType)); mg.getBody().insert(il); gen.addMethodGen(mg); return true; // } else { // return false; // } } // ??? Why do we have this method? I thought by now we would know if it matched or not private boolean couldMatch( BcelObjectType bcelObjectType, Pointcut pointcut) { return !bcelObjectType.isInterface(); } private boolean mungeNewMethod(BcelClassWeaver weaver, NewMethodTypeMunger munger) { ResolvedMember unMangledInterMethod = munger.getSignature(); // do matching on the unMangled one, but actually add them to the mangled method ResolvedMember interMethodBody = munger.getInterMethodBody(aspectType); ResolvedMember interMethodDispatcher = munger.getInterMethodDispatcher(aspectType); LazyClassGen gen = weaver.getLazyClassGen(); boolean mungingInterface = gen.isInterface(); ResolvedType onType = weaver.getWorld().resolve(unMangledInterMethod.getDeclaringType(),munger.getSourceLocation()); if (onType.isRawType()) onType = onType.getGenericType(); boolean onInterface = onType.isInterface(); if (onType.isAnnotation()) { signalError(WeaverMessages.ITDM_ON_ANNOTATION_NOT_ALLOWED,weaver,onType); return false; } if (onType.isEnum()) { signalError(WeaverMessages.ITDM_ON_ENUM_NOT_ALLOWED,weaver,onType); return false; } if (onType.equals(gen.getType())) { ResolvedMember mangledInterMethod = AjcMemberMaker.interMethod(unMangledInterMethod, aspectType, onInterface); LazyMethodGen mg = makeMethodGen(gen, mangledInterMethod); if (mungingInterface) { // we want the modifiers of the ITD to be used for all *implementors* of the // interface, but the method itself we add to the interface must be public abstract mg.setAccessFlags(Modifier.PUBLIC | Modifier.ABSTRACT); } // pr98901 // For copying the annotations across, we have to discover the real member in the aspect // which is holding them. if (weaver.getWorld().isInJava5Mode()){ AnnotationX annotationsOnRealMember[] = null; ResolvedType toLookOn = aspectType; if (aspectType.isRawType()) toLookOn = aspectType.getGenericType(); ResolvedMember realMember = getRealMemberForITDFromAspect(toLookOn,interMethodDispatcher); if (realMember==null) throw new BCException("Couldn't find ITD holder member '"+ interMethodDispatcher+"' on aspect "+aspectType); annotationsOnRealMember = realMember.getAnnotations(); if (annotationsOnRealMember!=null) { for (int i = 0; i < annotationsOnRealMember.length; i++) { AnnotationX annotationX = annotationsOnRealMember[i]; Annotation a = annotationX.getBcelAnnotation(); AnnotationGen ag = new AnnotationGen(a,weaver.getLazyClassGen().getConstantPoolGen(),true); mg.addAnnotation(new AnnotationX(ag.getAnnotation(),weaver.getWorld())); } } // the below loop fixes the very special (and very stupid) // case where an aspect declares an annotation // on an ITD it declared on itself. List allDecams = weaver.getWorld().getDeclareAnnotationOnMethods(); for (Iterator i = allDecams.iterator(); i.hasNext();){ DeclareAnnotation decaMC = (DeclareAnnotation) i.next(); if (decaMC.matches(unMangledInterMethod,weaver.getWorld()) && mg.getEnclosingClass().getType() == aspectType) { mg.addAnnotation(decaMC.getAnnotationX()); } } } if (!onInterface && !Modifier.isAbstract(mangledInterMethod.getModifiers())) { InstructionList body = mg.getBody(); InstructionFactory fact = gen.getFactory(); int pos = 0; if (!unMangledInterMethod.isStatic()) { body.append(InstructionFactory.createThis()); pos++; } Type[] paramTypes = BcelWorld.makeBcelTypes(mangledInterMethod.getParameterTypes()); for (int i = 0, len = paramTypes.length; i < len; i++) { Type paramType = paramTypes[i]; body.append(InstructionFactory.createLoad(paramType, pos)); pos+=paramType.getSize(); } body.append(Utility.createInvoke(fact, weaver.getWorld(), interMethodBody)); body.append( InstructionFactory.createReturn( BcelWorld.makeBcelType(mangledInterMethod.getReturnType()))); } else { //??? this is okay //if (!(mg.getBody() == null)) throw new RuntimeException("bas"); } // XXX make sure to check that we set exceptions properly on this guy. weaver.addLazyMethodGen(mg); weaver.getLazyClassGen().warnOnAddedMethod(mg.getMethod(),getSignature().getSourceLocation()); addNeededSuperCallMethods(weaver, onType, munger.getSuperMethodsCalled()); return true; } else if (onInterface && !Modifier.isAbstract(unMangledInterMethod.getModifiers())) { // This means the 'gen' should be the top most implementor // - if it is *not* then something went wrong after we worked // out that it was the top most implementor (see pr49657) if (!gen.getType().isTopmostImplementor(onType)) { ResolvedType rtx = gen.getType().getTopmostImplementor(onType); if (!rtx.isExposedToWeaver()) { ISourceLocation sLoc = munger.getSourceLocation(); weaver.getWorld().getMessageHandler().handleMessage(MessageUtil.error( WeaverMessages.format(WeaverMessages.ITD_NON_EXPOSED_IMPLEMENTOR,rtx,getAspectType().getName()), (sLoc==null?getAspectType().getSourceLocation():sLoc))); } else { // XXX what does this state mean? // We have incorrectly identified what is the top most implementor and its not because // a type wasn't exposed to the weaver } return false; } else { ResolvedMember mangledInterMethod = AjcMemberMaker.interMethod(unMangledInterMethod, aspectType, false); LazyMethodGen mg = makeMethodGen(gen, mangledInterMethod); if (mungingInterface) { // we want the modifiers of the ITD to be used for all *implementors* of the // interface, but the method itself we add to the interface must be public abstract mg.setAccessFlags(Modifier.PUBLIC | Modifier.ABSTRACT); } Type[] paramTypes = BcelWorld.makeBcelTypes(mangledInterMethod.getParameterTypes()); Type returnType = BcelWorld.makeBcelType(mangledInterMethod.getReturnType()); InstructionList body = mg.getBody(); InstructionFactory fact = gen.getFactory(); int pos = 0; if (!mangledInterMethod.isStatic()) { body.append(InstructionFactory.createThis()); pos++; } for (int i = 0, len = paramTypes.length; i < len; i++) { Type paramType = paramTypes[i]; body.append(InstructionFactory.createLoad(paramType, pos)); pos+=paramType.getSize(); } body.append(Utility.createInvoke(fact, weaver.getWorld(), interMethodBody)); body.append(InstructionFactory.createReturn(returnType)); mg.definingType = onType; weaver.addOrReplaceLazyMethodGen(mg); addNeededSuperCallMethods(weaver, onType, munger.getSuperMethodsCalled()); return true; } } else { return false; } } private ResolvedMember getRealMemberForITDFromAspect(ResolvedType aspectType,ResolvedMember lookingFor) { ResolvedMember aspectMethods[] = aspectType.getDeclaredMethods(); UnresolvedType [] lookingForParams = lookingFor.getParameterTypes(); ResolvedMember realMember = null; for (int i = 0; realMember==null && i < aspectMethods.length; i++) { ResolvedMember member = aspectMethods[i]; if (member.getName().equals(lookingFor.getName())){ UnresolvedType [] memberParams = member.getParameterTypes(); if (memberParams.length == lookingForParams.length){ boolean matchOK = true; for (int j = 0; j < memberParams.length && matchOK; j++){ UnresolvedType memberParam = memberParams[j]; UnresolvedType lookingForParam = lookingForParams[j].resolve(aspectType.getWorld()); if (lookingForParam.isTypeVariableReference()) lookingForParam = lookingForParam.getUpperBound(); if (!memberParam.equals(lookingForParam)){ matchOK=false; } } if (matchOK) realMember = member; } } } return realMember; } private void addNeededSuperCallMethods( BcelClassWeaver weaver, ResolvedType onType, Set neededSuperCalls) { LazyClassGen gen = weaver.getLazyClassGen(); for (Iterator iter = neededSuperCalls.iterator(); iter.hasNext();) { ResolvedMember superMethod = (ResolvedMember) iter.next(); if (weaver.addDispatchTarget(superMethod)) { //System.err.println("super type: " + superMethod.getDeclaringType() + ", " + gen.getType()); boolean isSuper = !superMethod.getDeclaringType().equals(gen.getType()); String dispatchName; if (isSuper) dispatchName = NameMangler.superDispatchMethod(onType, superMethod.getName()); else dispatchName = NameMangler.protectedDispatchMethod( onType, superMethod.getName()); LazyMethodGen dispatcher = makeDispatcher( gen, dispatchName, superMethod, weaver.getWorld(), isSuper); weaver.addLazyMethodGen(dispatcher); } } } private void signalError(String msgid,BcelClassWeaver weaver,UnresolvedType onType) { IMessage msg = MessageUtil.error( WeaverMessages.format(msgid,onType.getName()),getSourceLocation()); weaver.getWorld().getMessageHandler().handleMessage(msg); } private boolean mungeNewConstructor( BcelClassWeaver weaver, NewConstructorTypeMunger newConstructorTypeMunger) { final LazyClassGen currentClass = weaver.getLazyClassGen(); final InstructionFactory fact = currentClass.getFactory(); ResolvedMember newConstructorMember = newConstructorTypeMunger.getSyntheticConstructor(); ResolvedType onType = newConstructorMember.getDeclaringType().resolve(weaver.getWorld()); if (onType.isRawType()) onType = onType.getGenericType(); if (onType.isAnnotation()) { signalError(WeaverMessages.ITDC_ON_ANNOTATION_NOT_ALLOWED,weaver,onType); return false; } if (onType.isEnum()) { signalError(WeaverMessages.ITDC_ON_ENUM_NOT_ALLOWED,weaver,onType); return false; } if (! onType.equals(currentClass.getType())) return false; ResolvedMember explicitConstructor = newConstructorTypeMunger.getExplicitConstructor(); //int declaredParameterCount = newConstructorTypeMunger.getDeclaredParameterCount(); LazyMethodGen mg = makeMethodGen(currentClass, newConstructorMember); mg.setEffectiveSignature(newConstructorTypeMunger.getSignature(),Shadow.ConstructorExecution,true); // pr98901 // For copying the annotations across, we have to discover the real member in the aspect // which is holding them. if (weaver.getWorld().isInJava5Mode()){ ResolvedMember interMethodDispatcher =AjcMemberMaker.postIntroducedConstructor(aspectType,onType,newConstructorTypeMunger.getSignature().getParameterTypes()); AnnotationX annotationsOnRealMember[] = null; ResolvedMember realMember = getRealMemberForITDFromAspect(aspectType,interMethodDispatcher); if (realMember==null) throw new BCException("Couldn't find ITD holder member '"+ interMethodDispatcher+"' on aspect "+aspectType); annotationsOnRealMember = realMember.getAnnotations(); if (annotationsOnRealMember!=null) { for (int i = 0; i < annotationsOnRealMember.length; i++) { AnnotationX annotationX = annotationsOnRealMember[i]; Annotation a = annotationX.getBcelAnnotation(); AnnotationGen ag = new AnnotationGen(a,weaver.getLazyClassGen().getConstantPoolGen(),true); mg.addAnnotation(new AnnotationX(ag.getAnnotation(),weaver.getWorld())); } } // the below loop fixes the very special (and very stupid) // case where an aspect declares an annotation // on an ITD it declared on itself. List allDecams = weaver.getWorld().getDeclareAnnotationOnMethods(); for (Iterator i = allDecams.iterator(); i.hasNext();){ DeclareAnnotation decaMC = (DeclareAnnotation) i.next(); if (decaMC.matches(explicitConstructor,weaver.getWorld()) && mg.getEnclosingClass().getType() == aspectType) { mg.addAnnotation(decaMC.getAnnotationX()); } } } currentClass.addMethodGen(mg); //weaver.addLazyMethodGen(freshConstructor); InstructionList body = mg.getBody(); // add to body: push arts for call to pre, from actual args starting at 1 (skipping this), going to // declared argcount + 1 UnresolvedType[] declaredParams = newConstructorTypeMunger.getSignature().getParameterTypes(); Type[] paramTypes = mg.getArgumentTypes(); int frameIndex = 1; for (int i = 0, len = declaredParams.length; i < len; i++) { body.append(InstructionFactory.createLoad(paramTypes[i], frameIndex)); frameIndex += paramTypes[i].getSize(); } // do call to pre Member preMethod = AjcMemberMaker.preIntroducedConstructor(aspectType, onType, declaredParams); body.append(Utility.createInvoke(fact, null, preMethod)); // create a local, and store return pre stuff into it. int arraySlot = mg.allocateLocal(1); body.append(InstructionFactory.createStore(Type.OBJECT, arraySlot)); // put this on the stack body.append(InstructionConstants.ALOAD_0); // unpack pre args onto stack UnresolvedType[] superParamTypes = explicitConstructor.getParameterTypes(); for (int i = 0, len = superParamTypes.length; i < len; i++) { body.append(InstructionFactory.createLoad(Type.OBJECT, arraySlot)); body.append(Utility.createConstant(fact, i)); body.append(InstructionFactory.createArrayLoad(Type.OBJECT)); body.append( Utility.createConversion( fact, Type.OBJECT, BcelWorld.makeBcelType(superParamTypes[i]))); } // call super/this body.append(Utility.createInvoke(fact, null, explicitConstructor)); // put this back on the stack body.append(InstructionConstants.ALOAD_0); // unpack params onto stack Member postMethod = AjcMemberMaker.postIntroducedConstructor(aspectType, onType, declaredParams); UnresolvedType[] postParamTypes = postMethod.getParameterTypes(); for (int i = 1, len = postParamTypes.length; i < len; i++) { body.append(InstructionFactory.createLoad(Type.OBJECT, arraySlot)); body.append(Utility.createConstant(fact, superParamTypes.length + i-1)); body.append(InstructionFactory.createArrayLoad(Type.OBJECT)); body.append( Utility.createConversion( fact, Type.OBJECT, BcelWorld.makeBcelType(postParamTypes[i]))); } // call post body.append(Utility.createInvoke(fact, null, postMethod)); // don't forget to return!! body.append(InstructionConstants.RETURN); return true; } private static LazyMethodGen makeDispatcher( LazyClassGen onGen, String dispatchName, ResolvedMember superMethod, BcelWorld world, boolean isSuper) { Type[] paramTypes = BcelWorld.makeBcelTypes(superMethod.getParameterTypes()); Type returnType = BcelWorld.makeBcelType(superMethod.getReturnType()); int modifiers = Modifier.PUBLIC; if (onGen.isInterface()) modifiers |= Modifier.ABSTRACT; LazyMethodGen mg = new LazyMethodGen( modifiers, returnType, dispatchName, paramTypes, UnresolvedType.getNames(superMethod.getExceptions()), onGen); InstructionList body = mg.getBody(); if (onGen.isInterface()) return mg; // assert (!superMethod.isStatic()) InstructionFactory fact = onGen.getFactory(); int pos = 0; body.append(InstructionFactory.createThis()); pos++; for (int i = 0, len = paramTypes.length; i < len; i++) { Type paramType = paramTypes[i]; body.append(InstructionFactory.createLoad(paramType, pos)); pos+=paramType.getSize(); } if (isSuper) { body.append(Utility.createSuperInvoke(fact, world, superMethod)); } else { body.append(Utility.createInvoke(fact, world, superMethod)); } body.append(InstructionFactory.createReturn(returnType)); return mg; } private boolean mungeNewField(BcelClassWeaver weaver, NewFieldTypeMunger munger) { /*ResolvedMember initMethod = */munger.getInitMethod(aspectType); LazyClassGen gen = weaver.getLazyClassGen(); ResolvedMember field = munger.getSignature(); ResolvedType onType = weaver.getWorld().resolve(field.getDeclaringType(),munger.getSourceLocation()); if (onType.isRawType()) onType = onType.getGenericType(); boolean onInterface = onType.isInterface(); if (onType.isAnnotation()) { signalError(WeaverMessages.ITDF_ON_ANNOTATION_NOT_ALLOWED,weaver,onType); return false; } if (onType.isEnum()) { signalError(WeaverMessages.ITDF_ON_ENUM_NOT_ALLOWED,weaver,onType); return false; } ResolvedMember interMethodBody = munger.getInitMethod(aspectType); AnnotationX annotationsOnRealMember[] = null; // pr98901 // For copying the annotations across, we have to discover the real member in the aspect // which is holding them. if (weaver.getWorld().isInJava5Mode()){ // the below line just gets the method with the same name in aspectType.getDeclaredMethods(); ResolvedType toLookOn = aspectType; if (aspectType.isRawType()) toLookOn = aspectType.getGenericType(); ResolvedMember realMember = getRealMemberForITDFromAspect(toLookOn,interMethodBody); if (realMember==null) throw new BCException("Couldn't find ITD init member '"+ interMethodBody+"' on aspect "+aspectType); annotationsOnRealMember = realMember.getAnnotations(); } if (onType.equals(gen.getType())) { if (onInterface) { LazyMethodGen mg = makeMethodGen(gen, AjcMemberMaker.interFieldInterfaceGetter(field, onType, aspectType)); gen.addMethodGen(mg); LazyMethodGen mg1 = makeMethodGen(gen, AjcMemberMaker.interFieldInterfaceSetter(field, onType, aspectType)); gen.addMethodGen(mg1); } else { weaver.addInitializer(this); FieldGen fg = makeFieldGen(gen, AjcMemberMaker.interFieldClassField(field, aspectType)); if (annotationsOnRealMember!=null) { for (int i = 0; i < annotationsOnRealMember.length; i++) { AnnotationX annotationX = annotationsOnRealMember[i]; Annotation a = annotationX.getBcelAnnotation(); AnnotationGen ag = new AnnotationGen(a,weaver.getLazyClassGen().getConstantPoolGen(),true); fg.addAnnotation(ag); } } gen.addField(fg.getField(),getSourceLocation()); } return true; } else if (onInterface && gen.getType().isTopmostImplementor(onType)) { // wew know that we can't be static since we don't allow statics on interfaces if (field.isStatic()) throw new RuntimeException("unimplemented"); weaver.addInitializer(this); //System.err.println("impl body on " + gen.getType() + " for " + munger); Type fieldType = BcelWorld.makeBcelType(field.getType()); FieldGen fg = makeFieldGen(gen, AjcMemberMaker.interFieldInterfaceField(field, onType, aspectType)); gen.addField(fg.getField(),getSourceLocation()); //this uses a shadow munger to add init method to constructors //weaver.getShadowMungers().add(makeInitCallShadowMunger(initMethod)); LazyMethodGen mg = makeMethodGen(gen, AjcMemberMaker.interFieldInterfaceGetter(field, gen.getType(), aspectType)); InstructionList il = new InstructionList(); InstructionFactory fact = gen.getFactory(); if (field.isStatic()) { il.append(fact.createFieldAccess( gen.getClassName(), fg.getName(), fieldType, Constants.GETSTATIC)); } else { il.append(InstructionConstants.ALOAD_0); il.append(fact.createFieldAccess( gen.getClassName(), fg.getName(), fieldType, Constants.GETFIELD)); } il.append(InstructionFactory.createReturn(fieldType)); mg.getBody().insert(il); gen.addMethodGen(mg); LazyMethodGen mg1 = makeMethodGen(gen, AjcMemberMaker.interFieldInterfaceSetter(field, gen.getType(), aspectType)); InstructionList il1 = new InstructionList(); if (field.isStatic()) { il1.append(InstructionFactory.createLoad(fieldType, 0)); il1.append(fact.createFieldAccess( gen.getClassName(), fg.getName(), fieldType, Constants.PUTSTATIC)); } else { il1.append(InstructionConstants.ALOAD_0); il1.append(InstructionFactory.createLoad(fieldType, 1)); il1.append(fact.createFieldAccess( gen.getClassName(), fg.getName(), fieldType, Constants.PUTFIELD)); } il1.append(InstructionFactory.createReturn(Type.VOID)); mg1.getBody().insert(il1); gen.addMethodGen(mg1); return true; } else { return false; } } }
99,125
Bug 99125 Repetitive method name/signature in class file
This is what the VM sais: java.lang.ClassFormatError: Repetitive method name/signature in class file com/ netvisor/metadata_view/ComponentFactory at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:620) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java: 124) at java.net.URLClassLoader.defineClass(URLClassLoader.java:260) at java.net.URLClassLoader.access$100(URLClassLoader.java:56) at java.net.URLClassLoader$1.run(URLClassLoader.java:195) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:188) at java.lang.ClassLoader.loadClass(ClassLoader.java:306) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:268) at java.lang.ClassLoader.loadClass(ClassLoader.java:251) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319) And this is why: I've got an interface (ComponentFactory) and an aspect that adds various ITD methods trough that interface. I've added some methods to both the interface and the aspect, some other methods are only added trough the aspect. (The situation is a bit more complex, I've got a base interface/aspect with these two methods and the subaspects implement the problematic two methods .) And those methods that are both in the interface and the aspect are the ones that get duplicated in the interface class file. This is working fine in the old CVS branch (1.2.*). Hope it helps, good luck!
resolved fixed
df46c6f
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-02T17:12:43Z
2005-06-09T09:40:00Z
weaver/src/org/aspectj/weaver/bcel/LazyClassGen.java
/* ******************************************************************* * Copyright (c) 2002 Contributors * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * Andy Clement 6Jul05 generics - signature attribute * ******************************************************************/ package org.aspectj.weaver.bcel; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import org.aspectj.apache.bcel.Constants; import org.aspectj.apache.bcel.classfile.Attribute; import org.aspectj.apache.bcel.classfile.ConstantUtf8; import org.aspectj.apache.bcel.classfile.Field; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.apache.bcel.classfile.Method; import org.aspectj.apache.bcel.classfile.Signature; import org.aspectj.apache.bcel.classfile.Unknown; import org.aspectj.apache.bcel.classfile.annotation.Annotation; import org.aspectj.apache.bcel.generic.ClassGen; import org.aspectj.apache.bcel.generic.ConstantPoolGen; import org.aspectj.apache.bcel.generic.FieldGen; import org.aspectj.apache.bcel.generic.InstructionConstants; import org.aspectj.apache.bcel.generic.InstructionFactory; import org.aspectj.apache.bcel.generic.InstructionHandle; import org.aspectj.apache.bcel.generic.InstructionList; import org.aspectj.apache.bcel.generic.ObjectType; import org.aspectj.apache.bcel.generic.PUSH; import org.aspectj.apache.bcel.generic.RETURN; import org.aspectj.apache.bcel.generic.Type; import org.aspectj.apache.bcel.generic.annotation.AnnotationGen; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.SourceLocation; import org.aspectj.util.CollectionUtil; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.BCException; import org.aspectj.weaver.Member; import org.aspectj.weaver.NameMangler; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.TypeVariable; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.WeaverStateInfo; import org.aspectj.weaver.World; import org.aspectj.weaver.AjAttribute.WeaverVersionInfo; /** * Lazy lazy lazy. * We don't unpack the underlying class unless necessary. Things * like new methods and annotations accumulate in here until they * must be written out, don't add them to the underlying MethodGen! * Things are slightly different if this represents an Aspect. */ public final class LazyClassGen { int highestLineNumber = 0; // ---- JSR 45 info private SortedMap /* <String, InlinedSourceFileInfo> */ inlinedFiles = new TreeMap(); private boolean regenerateGenericSignatureAttribute = false; private BcelObjectType myType; // XXX is not set for types we create private ClassGen myGen; private ConstantPoolGen constantPoolGen; private List /*LazyMethodGen*/ methodGens = new ArrayList(); private List /*LazyClassGen*/ classGens = new ArrayList(); private List /*AnnotationGen*/ annotations = new ArrayList(); private int childCounter = 0; private InstructionFactory fact; private boolean isSerializable = false; private boolean hasSerialVersionUIDField = false; private boolean hasClinit = false; // --- static class InlinedSourceFileInfo { int highestLineNumber; int offset; // calculated InlinedSourceFileInfo(int highestLineNumber) { this.highestLineNumber = highestLineNumber; } } void addInlinedSourceFileInfo(String fullpath, int highestLineNumber) { Object o = inlinedFiles.get(fullpath); if (o != null) { InlinedSourceFileInfo info = (InlinedSourceFileInfo) o; if (info.highestLineNumber < highestLineNumber) { info.highestLineNumber = highestLineNumber; } } else { inlinedFiles.put(fullpath, new InlinedSourceFileInfo(highestLineNumber)); } } void calculateSourceDebugExtensionOffsets() { int i = roundUpToHundreds(highestLineNumber); for (Iterator iter = inlinedFiles.values().iterator(); iter.hasNext();) { InlinedSourceFileInfo element = (InlinedSourceFileInfo) iter.next(); element.offset = i; i = roundUpToHundreds(i + element.highestLineNumber); } } private static int roundUpToHundreds(int i) { return ((i / 100) + 1) * 100; } int getSourceDebugExtensionOffset(String fullpath) { return ((InlinedSourceFileInfo) inlinedFiles.get(fullpath)).offset; } private Unknown getSourceDebugExtensionAttribute() { int nameIndex = constantPoolGen.addUtf8("SourceDebugExtension"); String data = getSourceDebugExtensionString(); //System.err.println(data); byte[] bytes = Utility.stringToUTF(data); int length = bytes.length; return new Unknown(nameIndex, length, bytes, constantPoolGen.getConstantPool()); } // private LazyClassGen() {} // public static void main(String[] args) { // LazyClassGen m = new LazyClassGen(); // m.highestLineNumber = 37; // m.inlinedFiles.put("boo/baz/foo.java", new InlinedSourceFileInfo( 83)); // m.inlinedFiles.put("boo/barz/foo.java", new InlinedSourceFileInfo(292)); // m.inlinedFiles.put("boo/baz/moo.java", new InlinedSourceFileInfo(128)); // m.calculateSourceDebugExtensionOffsets(); // System.err.println(m.getSourceDebugExtensionString()); // } // For the entire pathname, we're using package names. This is probably wrong. private String getSourceDebugExtensionString() { StringBuffer out = new StringBuffer(); String myFileName = getFileName(); // header section out.append("SMAP\n"); out.append(myFileName); out.append("\nAspectJ\n"); // stratum section out.append("*S AspectJ\n"); // file section out.append("*F\n"); out.append("1 "); out.append(myFileName); out.append("\n"); int i = 2; for (Iterator iter = inlinedFiles.keySet().iterator(); iter.hasNext();) { String element = (String) iter.next(); int ii = element.lastIndexOf('/'); if (ii == -1) { out.append(i++); out.append(' '); out.append(element); out.append('\n'); } else { out.append("+ "); out.append(i++); out.append(' '); out.append(element.substring(ii+1)); out.append('\n'); out.append(element); out.append('\n'); } } // emit line section out.append("*L\n"); out.append("1#1,"); out.append(highestLineNumber); out.append(":1,1\n"); i = 2; for (Iterator iter = inlinedFiles.values().iterator(); iter.hasNext();) { InlinedSourceFileInfo element = (InlinedSourceFileInfo) iter.next(); out.append("1#"); out.append(i++); out.append(','); out.append(element.highestLineNumber); out.append(":"); out.append(element.offset + 1); out.append(",1\n"); } // end section out.append("*E\n"); // and finish up... return out.toString(); } // ---- end JSR45-related stuff /** Emit disassembled class and newline to out */ public static void disassemble(String path, String name, PrintStream out) throws IOException { if (null == out) { return; } //out.println("classPath: " + classPath); BcelWorld world = new BcelWorld(path); LazyClassGen clazz = new LazyClassGen(BcelWorld.getBcelObjectType(world.resolve(name))); clazz.print(out); out.println(); } public int getNewGeneratedNameTag() { return childCounter++; } // ---- public LazyClassGen( String class_name, String super_class_name, String file_name, int access_flags, String[] interfaces) { myGen = new ClassGen(class_name, super_class_name, file_name, access_flags, interfaces); constantPoolGen = myGen.getConstantPool(); fact = new InstructionFactory(myGen, constantPoolGen); regenerateGenericSignatureAttribute = true; } //Non child type, so it comes from a real type in the world. public LazyClassGen(BcelObjectType myType) { myGen = new ClassGen(myType.getJavaClass()); constantPoolGen = myGen.getConstantPool(); fact = new InstructionFactory(myGen, constantPoolGen); this.myType = myType; /* Does this class support serialization */ if (UnresolvedType.SERIALIZABLE.resolve(getType().getWorld()).isAssignableFrom(getType())) { isSerializable = true; // ResolvedMember[] fields = getType().getDeclaredFields(); // for (int i = 0; i < fields.length; i++) { // ResolvedMember field = fields[i]; // if (field.getName().equals("serialVersionUID") // && field.isStatic() && field.getType().equals(ResolvedType.LONG)) { // hasSerialVersionUIDField = true; // } // } hasSerialVersionUIDField = hasSerialVersionUIDField(getType()); ResolvedMember[] methods = getType().getDeclaredMethods(); for (int i = 0; i < methods.length; i++) { ResolvedMember method = methods[i]; if (method.getName().equals("<clinit>")) { hasClinit = true; } } } Method[] methods = myGen.getMethods(); for (int i = 0; i < methods.length; i++) { addMethodGen(new LazyMethodGen(methods[i], this)); } } public static boolean hasSerialVersionUIDField (ResolvedType type) { ResolvedMember[] fields = type.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { ResolvedMember field = fields[i]; if (field.getName().equals("serialVersionUID") && field.isStatic() && field.getType().equals(ResolvedType.LONG)) { return true; } } return false; } // public void addAttribute(Attribute i) { // myGen.addAttribute(i); // } // ---- public String getInternalClassName() { return getConstantPoolGen().getConstantPool().getConstantString( myGen.getClassNameIndex(), Constants.CONSTANT_Class); } public String getInternalFileName() { String str = getInternalClassName(); int index = str.lastIndexOf('/'); if (index == -1) { return getFileName(); } else { return str.substring(0, index + 1) + getFileName(); } } public File getPackagePath(File root) { String str = getInternalClassName(); int index = str.lastIndexOf('/'); if (index == -1) return root; return new File(root, str.substring(0, index)); } public String getClassId() { String str = getInternalClassName(); int index = str.lastIndexOf('/'); if (index == -1) return str; return str.substring(index + 1); } public void addMethodGen(LazyMethodGen gen) { //assert gen.getClassName() == super.getClassName(); methodGens.add(gen); if (highestLineNumber < gen.highestLineNumber) highestLineNumber = gen.highestLineNumber; } public void addMethodGen(LazyMethodGen gen, ISourceLocation sourceLocation) { addMethodGen(gen); if (!gen.getMethod().isPrivate()) { warnOnAddedMethod(gen.getMethod(),sourceLocation); } } public void errorOnAddedField (Field field, ISourceLocation sourceLocation) { if (isSerializable && !hasSerialVersionUIDField) { getWorld().getLint().serialVersionUIDBroken.signal( new String[] { myType.getResolvedTypeX().getName().toString(), field.getName() }, sourceLocation, null); } } public void warnOnAddedInterface (String name, ISourceLocation sourceLocation) { warnOnModifiedSerialVersionUID(sourceLocation,"added interface " + name); } public void warnOnAddedMethod (Method method, ISourceLocation sourceLocation) { warnOnModifiedSerialVersionUID(sourceLocation,"added non-private method " + method.getName()); } public void warnOnAddedStaticInitializer (Shadow shadow, ISourceLocation sourceLocation) { if (!hasClinit) { warnOnModifiedSerialVersionUID(sourceLocation,"added static initializer"); } } public void warnOnModifiedSerialVersionUID (ISourceLocation sourceLocation, String reason) { if (isSerializable && !hasSerialVersionUIDField) getWorld().getLint().needsSerialVersionUIDField.signal( new String[] { myType.getResolvedTypeX().getName().toString(), reason }, sourceLocation, null); } public World getWorld () { return myType.getResolvedTypeX().getWorld(); } public List getMethodGens() { return methodGens; //???Collections.unmodifiableList(methodGens); } // FIXME asc Should be collection returned here public Field[] getFieldGens() { return myGen.getFields(); } // FIXME asc How do the ones on the underlying class surface if this just returns new ones added? // FIXME asc ...although no one calls this right now ! public List getAnnotations() { return annotations; } private void writeBack(BcelWorld world) { if (getConstantPoolGen().getSize() > Short.MAX_VALUE) { reportClassTooBigProblem(); return; } if (annotations.size()>0) { for (Iterator iter = annotations.iterator(); iter.hasNext();) { AnnotationGen element = (AnnotationGen) iter.next(); myGen.addAnnotation(element); } // Attribute[] annAttributes = org.aspectj.apache.bcel.classfile.Utility.getAnnotationAttributes(getConstantPoolGen(),annotations); // for (int i = 0; i < annAttributes.length; i++) { // Attribute attribute = annAttributes[i]; // System.err.println("Adding attribute for "+attribute); // myGen.addAttribute(attribute); // } } // Add a weaver version attribute to the file being produced (if necessary...) boolean hasVersionAttribute = false; Attribute[] attrs = myGen.getAttributes(); for (int i = 0; i < attrs.length && !hasVersionAttribute; i++) { Attribute attribute = attrs[i]; if (attribute.getName().equals("org.aspectj.weaver.WeaverVersion")) hasVersionAttribute=true; } if (!hasVersionAttribute) myGen.addAttribute(BcelAttributes.bcelAttribute(new AjAttribute.WeaverVersionInfo(),getConstantPoolGen())); if (myType != null && myType.getWeaverState() != null) { myGen.addAttribute(BcelAttributes.bcelAttribute( new AjAttribute.WeaverState(myType.getWeaverState()), getConstantPoolGen())); } //FIXME ATAJ needed only for slow Aspects.aspectOf() - keep or remove //make a lot of test fail since the test compare weaved class file // based on some test data as text files... // if (!myGen.isInterface()) { // addAjClassField(); // } addAjcInitializers(); int len = methodGens.size(); myGen.setMethods(new Method[0]); calculateSourceDebugExtensionOffsets(); for (int i = 0; i < len; i++) { LazyMethodGen gen = (LazyMethodGen) methodGens.get(i); // we skip empty clinits if (isEmptyClinit(gen)) continue; myGen.addMethod(gen.getMethod()); } if (inlinedFiles.size() != 0) { if (hasSourceDebugExtensionAttribute(myGen)) { world.showMessage( IMessage.WARNING, WeaverMessages.format(WeaverMessages.OVERWRITE_JSR45,getFileName()), null, null); } // 17Feb05 - ASC - Skip this for now - it crashes IBM 1.4.2 jvms (pr80430). Will be revisited when contents // of attribute are confirmed to be correct. // myGen.addAttribute(getSourceDebugExtensionAttribute()); } fixupGenericSignatureAttribute(); } /** * When working with 1.5 generics, a signature attribute is attached to the type which indicates * how it was declared. This routine ensures the signature attribute for what we are about * to write out is correct. Basically its responsibilities are: * 1. Checking whether the attribute needs changing (i.e. did weaving change the type hierarchy) * 2. If it did, removing the old attribute * 3. Check if we need an attribute at all, are we generic? are our supertypes parameterized/generic? * 4. Build the new attribute which includes all typevariable, supertype and superinterface information */ private void fixupGenericSignatureAttribute () { // TODO asc generics Temporarily assume that types we generate dont need a signature attribute (closure/etc).. will need revisiting no doubt... if (myType==null) return; // 1. Has anything changed that would require us to modify this attribute? if (!regenerateGenericSignatureAttribute) return; // 2. Find the old attribute Signature sigAttr = null; if (myType!=null) { // if null, this is a type built from scratch, it won't already have a sig attribute Attribute[] as = myGen.getAttributes(); for (int i = 0; i < as.length; i++) { Attribute attribute = as[i]; if (attribute.getName().equals("Signature")) sigAttr = (Signature)attribute; } } // 3. Do we need an attribute? boolean needAttribute = false; if (sigAttr!=null) needAttribute = true; // If we had one before, we definetly still need one as types can't be 'removed' from the hierarchy // check the interfaces if (!needAttribute) { if (myType==null) { boolean stop = true; } ResolvedType[] interfaceRTXs = myType.getDeclaredInterfaces(); for (int i = 0; i < interfaceRTXs.length; i++) { ResolvedType typeX = interfaceRTXs[i]; if (typeX.isGenericType() || typeX.isParameterizedType()) needAttribute = true; } // check the supertype ResolvedType superclassRTX = myType.getSuperclass(); if (superclassRTX.isGenericType() || superclassRTX.isParameterizedType()) needAttribute = true; } if (needAttribute) { StringBuffer signature = new StringBuffer(); // first, the type variables... TypeVariable[] tVars = myType.getTypeVariables(); if (tVars.length>0) { signature.append("<"); for (int i = 0; i < tVars.length; i++) { TypeVariable variable = tVars[i]; if (i!=0) signature.append(","); signature.append(variable.getSignature()); } signature.append(">"); } // now the supertype signature.append(myType.getSuperclass().getSignature()); ResolvedType[] interfaceRTXs = myType.getDeclaredInterfaces(); for (int i = 0; i < interfaceRTXs.length; i++) { String s = interfaceRTXs[i].getSignatureForAttribute(); signature.append(s); } myGen.addAttribute(createSignatureAttribute(signature.toString())); } // TODO asc generics The 'old' signature is left in the constant pool - I wonder how safe it would be to // remove it since we don't know what else (if anything) is referring to it } /** * Helper method to create a signature attribute based on a string signature: * e.g. "Ljava/lang/Object;LI<Ljava/lang/Double;>;" */ private Signature createSignatureAttribute(String signature) { int nameIndex = constantPoolGen.addUtf8("Signature"); int sigIndex = constantPoolGen.addUtf8(signature); return new Signature(nameIndex,2,sigIndex,constantPoolGen.getConstantPool()); } /** * */ private void reportClassTooBigProblem() { // PR 59208 // we've generated a class that is just toooooooooo big (you've been generating programs // again haven't you? come on, admit it, no-one writes classes this big by hand). // create an empty myGen so that we can give back a return value that doesn't upset the // rest of the process. myGen = new ClassGen(myGen.getClassName(), myGen.getSuperclassName(), myGen.getFileName(), myGen.getAccessFlags(), myGen.getInterfaceNames()); // raise an error against this compilation unit. getWorld().showMessage( IMessage.ERROR, WeaverMessages.format(WeaverMessages.CLASS_TOO_BIG, this.getClassName()), new SourceLocation(new File(myGen.getFileName()),0), null ); } private static boolean hasSourceDebugExtensionAttribute(ClassGen gen) { ConstantPoolGen pool = gen.getConstantPool(); Attribute[] attrs = gen.getAttributes(); for (int i = 0; i < attrs.length; i++) { if ("SourceDebugExtension" .equals(((ConstantUtf8) pool.getConstant(attrs[i].getNameIndex())).getBytes())) { return true; } } return false; } public JavaClass getJavaClass(BcelWorld world) { writeBack(world); return myGen.getJavaClass(); } public void addGeneratedInner(LazyClassGen newClass) { classGens.add(newClass); } public void addInterface(UnresolvedType typeX, ISourceLocation sourceLocation) { regenerateGenericSignatureAttribute = true; myGen.addInterface(typeX.getRawName()); if (!typeX.equals(UnresolvedType.SERIALIZABLE)) warnOnAddedInterface(typeX.getName(),sourceLocation); } public void setSuperClass(UnresolvedType typeX) { regenerateGenericSignatureAttribute = true; myGen.setSuperclassName(typeX.getName()); } public String getSuperClassname() { return myGen.getSuperclassName(); } // non-recursive, may be a bug, ha ha. private List getClassGens() { List ret = new ArrayList(); ret.add(this); ret.addAll(classGens); return ret; } public List getChildClasses(BcelWorld world) { if (classGens.isEmpty()) return Collections.EMPTY_LIST; List ret = new ArrayList(); for (Iterator i = classGens.iterator(); i.hasNext();) { LazyClassGen clazz = (LazyClassGen) i.next(); byte[] bytes = clazz.getJavaClass(world).getBytes(); String name = clazz.getName(); int index = name.lastIndexOf('$'); // XXX this could be bad, check use of dollar signs. name = name.substring(index+1); ret.add(new UnwovenClassFile.ChildClass(name, bytes)); } return ret; } public String toString() { return toShortString(); } public String toShortString() { String s = org.aspectj.apache.bcel.classfile.Utility.accessToString(myGen.getAccessFlags(), true); if (s != "") s += " "; s += org.aspectj.apache.bcel.classfile.Utility.classOrInterface(myGen.getAccessFlags()); s += " "; s += myGen.getClassName(); return s; } public String toLongString() { ByteArrayOutputStream s = new ByteArrayOutputStream(); print(new PrintStream(s)); return new String(s.toByteArray()); } public void print() { print(System.out); } public void print(PrintStream out) { List classGens = getClassGens(); for (Iterator iter = classGens.iterator(); iter.hasNext();) { LazyClassGen element = (LazyClassGen) iter.next(); element.printOne(out); if (iter.hasNext()) out.println(); } } private void printOne(PrintStream out) { out.print(toShortString()); out.print(" extends "); out.print( org.aspectj.apache.bcel.classfile.Utility.compactClassName( myGen.getSuperclassName(), false)); int size = myGen.getInterfaces().length; if (size > 0) { out.print(" implements "); for (int i = 0; i < size; i++) { out.print(myGen.getInterfaceNames()[i]); if (i < size - 1) out.print(", "); } } out.print(":"); out.println(); // XXX make sure to pass types correctly around, so this doesn't happen. if (myType != null) { myType.printWackyStuff(out); } Field[] fields = myGen.getFields(); for (int i = 0, len = fields.length; i < len; i++) { out.print(" "); out.println(fields[i]); } List methodGens = getMethodGens(); for (Iterator iter = methodGens.iterator(); iter.hasNext();) { LazyMethodGen gen = (LazyMethodGen) iter.next(); // we skip empty clinits if (isEmptyClinit(gen)) continue; gen.print(out, (myType != null ? myType.getWeaverVersionAttribute() : WeaverVersionInfo.UNKNOWN)); if (iter.hasNext()) out.println(); } // out.println(" ATTRIBS: " + Arrays.asList(myGen.getAttributes())); out.println("end " + toShortString()); } private boolean isEmptyClinit(LazyMethodGen gen) { if (!gen.getName().equals("<clinit>")) return false; //System.err.println("checking clinig: " + gen); InstructionHandle start = gen.getBody().getStart(); while (start != null) { if (Range.isRangeHandle(start) || (start.getInstruction() instanceof RETURN)) { start = start.getNext(); } else { return false; } } return true; } public ConstantPoolGen getConstantPoolGen() { return constantPoolGen; } public String getName() { return myGen.getClassName(); } public boolean isWoven() { return myType.getWeaverState() != null; } public boolean isReweavable() { if (myType.getWeaverState()==null) return false; return myType.getWeaverState().isReweavable(); } public Set getAspectsAffectingType() { if (myType.getWeaverState()==null) return null; return myType.getWeaverState().getAspectsAffectingType(); } public WeaverStateInfo getOrCreateWeaverStateInfo() { WeaverStateInfo ret = myType.getWeaverState(); if (ret != null) return ret; ret = new WeaverStateInfo(); myType.setWeaverState(ret); return ret; } public InstructionFactory getFactory() { return fact; } public LazyMethodGen getStaticInitializer() { for (Iterator i = methodGens.iterator(); i.hasNext();) { LazyMethodGen gen = (LazyMethodGen) i.next(); if (gen.getName().equals("<clinit>")) return gen; } LazyMethodGen clinit = new LazyMethodGen( Modifier.STATIC, Type.VOID, "<clinit>", new Type[0], CollectionUtil.NO_STRINGS, this); clinit.getBody().insert(InstructionConstants.RETURN); methodGens.add(clinit); return clinit; } public LazyMethodGen getAjcPreClinit() { for (Iterator i = methodGens.iterator(); i.hasNext();) { LazyMethodGen gen = (LazyMethodGen) i.next(); if (gen.getName().equals(NameMangler.AJC_PRE_CLINIT_NAME)) return gen; } LazyMethodGen ajcClinit = new LazyMethodGen( Modifier.STATIC, Type.VOID, NameMangler.AJC_PRE_CLINIT_NAME, new Type[0], CollectionUtil.NO_STRINGS, this); ajcClinit.getBody().insert(InstructionConstants.RETURN); methodGens.add(ajcClinit); getStaticInitializer().getBody().insert(Utility.createInvoke(getFactory(), ajcClinit)); return ajcClinit; } // reflective thisJoinPoint support Map/*BcelShadow, Field*/ tjpFields = new HashMap(); public static final ObjectType proceedingTjpType = new ObjectType("org.aspectj.lang.ProceedingJoinPoint"); public static final ObjectType tjpType = new ObjectType("org.aspectj.lang.JoinPoint"); public static final ObjectType staticTjpType = new ObjectType("org.aspectj.lang.JoinPoint$StaticPart"); public static final ObjectType enclosingStaticTjpType = new ObjectType("org.aspectj.lang.JoinPoint$EnclosingStaticPart"); private static final ObjectType sigType = new ObjectType("org.aspectj.lang.Signature"); // private static final ObjectType slType = // new ObjectType("org.aspectj.lang.reflect.SourceLocation"); private static final ObjectType factoryType = new ObjectType("org.aspectj.runtime.reflect.Factory"); private static final ObjectType classType = new ObjectType("java.lang.Class"); public Field getTjpField(BcelShadow shadow, final boolean isEnclosingJp) { Field ret = (Field)tjpFields.get(shadow); if (ret != null) return ret; int modifiers = Modifier.STATIC | Modifier.FINAL; // XXX - Do we ever inline before or after advice? If we do, then we // better include them in the check below. (or just change it to // shadow.getEnclosingMethod().getCanInline()) // If the enclosing method is around advice, we could inline the join point // that has led to this shadow. If we do that then the TJP we are creating // here must be PUBLIC so it is visible to the type in which the // advice is inlined. (PR71377) LazyMethodGen encMethod = shadow.getEnclosingMethod(); boolean shadowIsInAroundAdvice = false; if (encMethod!=null && encMethod.getName().startsWith(NameMangler.PREFIX+"around")) { shadowIsInAroundAdvice = true; } if (getType().isInterface() || shadowIsInAroundAdvice) { modifiers |= Modifier.PUBLIC; } else { modifiers |= Modifier.PRIVATE; } ret = new FieldGen(modifiers, isEnclosingJp?enclosingStaticTjpType:staticTjpType, "ajc$tjp_" + tjpFields.size(), getConstantPoolGen()).getField(); addField(ret); tjpFields.put(shadow, ret); return ret; } //FIXME ATAJ needed only for slow Aspects.aspectOf - keep or remove // private void addAjClassField() { // // Andy: Why build it again?? // Field ajClassField = new FieldGen( // Modifier.PRIVATE | Modifier.FINAL | Modifier.STATIC, // classType, // "aj$class", // getConstantPoolGen()).getField(); // addField(ajClassField); // // InstructionList il = new InstructionList(); // il.append(new PUSH(getConstantPoolGen(), getClassName())); // il.append(fact.createInvoke("java.lang.Class", "forName", classType, // new Type[] {Type.STRING}, Constants.INVOKESTATIC)); // il.append(fact.createFieldAccess(getClassName(), ajClassField.getName(), // classType, Constants.PUTSTATIC)); // // getStaticInitializer().getBody().insert(il); // } private void addAjcInitializers() { if (tjpFields.size() == 0) return; InstructionList il = initializeAllTjps(); getStaticInitializer().getBody().insert(il); } private InstructionList initializeAllTjps() { InstructionList list = new InstructionList(); InstructionFactory fact = getFactory(); // make a new factory list.append(fact.createNew(factoryType)); list.append(InstructionFactory.createDup(1)); list.append(new PUSH(getConstantPoolGen(), getFileName())); // load the current Class object //XXX check that this works correctly for inners/anonymous list.append(new PUSH(getConstantPoolGen(), getClassName())); //XXX do we need to worry about the fact the theorectically this could throw //a ClassNotFoundException list.append(fact.createInvoke("java.lang.Class", "forName", classType, new Type[] {Type.STRING}, Constants.INVOKESTATIC)); list.append(fact.createInvoke(factoryType.getClassName(), "<init>", Type.VOID, new Type[] {Type.STRING, classType}, Constants.INVOKESPECIAL)); list.append(InstructionFactory.createStore(factoryType, 0)); List entries = new ArrayList(tjpFields.entrySet()); Collections.sort(entries, new Comparator() { public int compare(Object a, Object b) { Map.Entry ae = (Map.Entry) a; Map.Entry be = (Map.Entry) b; return ((Field) ae.getValue()) .getName() .compareTo(((Field)be.getValue()).getName()); } }); for (Iterator i = entries.iterator(); i.hasNext(); ) { Map.Entry entry = (Map.Entry)i.next(); initializeTjp(fact, list, (Field)entry.getValue(), (BcelShadow)entry.getKey()); } return list; } private void initializeTjp(InstructionFactory fact, InstructionList list, Field field, BcelShadow shadow) { Member sig = shadow.getSignature(); //ResolvedMember mem = shadow.getSignature().resolve(shadow.getWorld()); // load the factory list.append(InstructionFactory.createLoad(factoryType, 0)); // load the kind list.append(new PUSH(getConstantPoolGen(), shadow.getKind().getName())); // create the signature list.append(InstructionFactory.createLoad(factoryType, 0)); if (sig.getKind().equals(Member.METHOD)) { BcelWorld w = shadow.getWorld(); // For methods, push the parts of the signature on. list.append(new PUSH(getConstantPoolGen(),makeString(sig.getModifiers(w)))); list.append(new PUSH(getConstantPoolGen(),sig.getName())); list.append(new PUSH(getConstantPoolGen(),makeString(sig.getDeclaringType()))); list.append(new PUSH(getConstantPoolGen(),makeString(sig.getParameterTypes()))); list.append(new PUSH(getConstantPoolGen(),makeString(sig.getParameterNames(w)))); list.append(new PUSH(getConstantPoolGen(),makeString(sig.getExceptions(w)))); list.append(new PUSH(getConstantPoolGen(),makeString(sig.getReturnType()))); // And generate a call to the variant of makeMethodSig() that takes 7 strings list.append(fact.createInvoke(factoryType.getClassName(), sig.getSignatureMakerName(), new ObjectType(sig.getSignatureType()), new Type[] { Type.STRING,Type.STRING,Type.STRING,Type.STRING,Type.STRING,Type.STRING,Type.STRING }, Constants.INVOKEVIRTUAL)); } else if (sig.getKind().equals(Member.HANDLER)) { BcelWorld w = shadow.getWorld(); list.append(new PUSH(getConstantPoolGen(),makeString(sig.getDeclaringType()))); list.append(new PUSH(getConstantPoolGen(),makeString(sig.getParameterTypes()))); list.append(new PUSH(getConstantPoolGen(),makeString(sig.getParameterNames(w)))); list.append(fact.createInvoke(factoryType.getClassName(), sig.getSignatureMakerName(), new ObjectType(sig.getSignatureType()), new Type[] { Type.STRING, Type.STRING, Type.STRING }, Constants.INVOKEVIRTUAL)); } else if(sig.getKind().equals(Member.CONSTRUCTOR)) { BcelWorld w = shadow.getWorld(); list.append(new PUSH(getConstantPoolGen(),makeString(sig.getModifiers(w)))); list.append(new PUSH(getConstantPoolGen(),makeString(sig.getDeclaringType()))); list.append(new PUSH(getConstantPoolGen(),makeString(sig.getParameterTypes()))); list.append(new PUSH(getConstantPoolGen(),makeString(sig.getParameterNames(w)))); list.append(new PUSH(getConstantPoolGen(),makeString(sig.getExceptions(w)))); list.append(fact.createInvoke(factoryType.getClassName(), sig.getSignatureMakerName(), new ObjectType(sig.getSignatureType()), new Type[] { Type.STRING, Type.STRING, Type.STRING, Type.STRING, Type.STRING }, Constants.INVOKEVIRTUAL)); } else if(sig.getKind().equals(Member.FIELD)) { BcelWorld w = shadow.getWorld(); list.append(new PUSH(getConstantPoolGen(),makeString(sig.getModifiers(w)))); list.append(new PUSH(getConstantPoolGen(),sig.getName())); list.append(new PUSH(getConstantPoolGen(),makeString(sig.getDeclaringType()))); list.append(new PUSH(getConstantPoolGen(),makeString(sig.getReturnType()))); list.append(fact.createInvoke(factoryType.getClassName(), sig.getSignatureMakerName(), new ObjectType(sig.getSignatureType()), new Type[] { Type.STRING, Type.STRING, Type.STRING, Type.STRING }, Constants.INVOKEVIRTUAL)); } else if(sig.getKind().equals(Member.ADVICE)) { BcelWorld w = shadow.getWorld(); list.append(new PUSH(getConstantPoolGen(),makeString(sig.getModifiers(w)))); list.append(new PUSH(getConstantPoolGen(),sig.getName())); list.append(new PUSH(getConstantPoolGen(),makeString(sig.getDeclaringType()))); list.append(new PUSH(getConstantPoolGen(),makeString(sig.getParameterTypes()))); list.append(new PUSH(getConstantPoolGen(),makeString(sig.getParameterNames(w)))); list.append(new PUSH(getConstantPoolGen(),makeString(sig.getExceptions(w)))); list.append(new PUSH(getConstantPoolGen(),makeString((sig.getReturnType())))); list.append(fact.createInvoke(factoryType.getClassName(), sig.getSignatureMakerName(), new ObjectType(sig.getSignatureType()), new Type[] { Type.STRING, Type.STRING, Type.STRING, Type.STRING, Type.STRING, Type.STRING, Type.STRING }, Constants.INVOKEVIRTUAL)); } else if(sig.getKind().equals(Member.STATIC_INITIALIZATION)) { BcelWorld w = shadow.getWorld(); list.append(new PUSH(getConstantPoolGen(),makeString(sig.getModifiers(w)))); list.append(new PUSH(getConstantPoolGen(),makeString(sig.getDeclaringType()))); list.append(fact.createInvoke(factoryType.getClassName(), sig.getSignatureMakerName(), new ObjectType(sig.getSignatureType()), new Type[] { Type.STRING, Type.STRING }, Constants.INVOKEVIRTUAL)); } else { list.append(new PUSH(getConstantPoolGen(), sig.getSignatureString(shadow.getWorld()))); list.append(fact.createInvoke(factoryType.getClassName(), sig.getSignatureMakerName(), new ObjectType(sig.getSignatureType()), new Type[] { Type.STRING }, Constants.INVOKEVIRTUAL)); } //XXX should load source location from shadow list.append(Utility.createConstant(fact, shadow.getSourceLine())); final String factoryMethod; if (staticTjpType.equals(field.getType())) { factoryMethod = "makeSJP"; } else if (enclosingStaticTjpType.equals(field.getType())) { factoryMethod = "makeESJP"; } else { throw new Error("should not happen"); } list.append(fact.createInvoke(factoryType.getClassName(), factoryMethod, field.getType(), new Type[] { Type.STRING, sigType, Type.INT}, Constants.INVOKEVIRTUAL)); // put it in the field list.append(fact.createFieldAccess(getClassName(), field.getName(), field.getType(), Constants.PUTSTATIC)); } protected String makeString(int i) { return Integer.toString(i, 16); //??? expensive } protected String makeString(UnresolvedType t) { // this is the inverse of the odd behavior for Class.forName w/ arrays if (t.isArray()) { // this behavior matches the string used by the eclipse compiler for Foo.class literals return t.getSignature().replace('/', '.'); } else { return t.getName(); } } protected String makeString(UnresolvedType[] types) { if (types == null) return ""; StringBuffer buf = new StringBuffer(); for (int i = 0, len=types.length; i < len; i++) { buf.append(makeString(types[i])); buf.append(':'); } return buf.toString(); } protected String makeString(String[] names) { if (names == null) return ""; StringBuffer buf = new StringBuffer(); for (int i = 0, len=names.length; i < len; i++) { buf.append(names[i]); buf.append(':'); } return buf.toString(); } public ResolvedType getType() { if (myType == null) return null; return myType.getResolvedTypeX(); } public BcelObjectType getBcelObjectType() { return myType; } public String getFileName() { return myGen.getFileName(); } private void addField(Field field) { myGen.addField(field); } public void replaceField(Field oldF, Field newF){ myGen.removeField(oldF); myGen.addField(newF); } public void addField(Field field, ISourceLocation sourceLocation) { addField(field); if (!(field.isPrivate() && (field.isStatic() || field.isTransient()))) { errorOnAddedField(field,sourceLocation); } } public String getClassName() { return myGen.getClassName(); } public boolean isInterface() { return myGen.isInterface(); } public boolean isAbstract() { return myGen.isAbstract(); } public LazyMethodGen getLazyMethodGen(Member m) { return getLazyMethodGen(m.getName(), m.getSignature()); } public LazyMethodGen getLazyMethodGen(String name, String signature) { for (Iterator i = methodGens.iterator(); i.hasNext();) { LazyMethodGen gen = (LazyMethodGen) i.next(); if (gen.getName().equals(name) && gen.getSignature().equals(signature)) return gen; } throw new BCException("Class " + this.getName() + " does not have a method " + name + " with signature " + signature); } public void forcePublic() { myGen.setAccessFlags(Utility.makePublic(myGen.getAccessFlags())); } public boolean hasAnnotation(UnresolvedType t) { // annotations on the real thing AnnotationGen agens[] = myGen.getAnnotations(); if (agens==null) return false; for (int i = 0; i < agens.length; i++) { AnnotationGen gen = agens[i]; if (t.equals(UnresolvedType.forSignature(gen.getTypeSignature()))) return true; } // annotations added during this weave return false; } public void addAnnotation(Annotation a) { if (!hasAnnotation(UnresolvedType.forSignature(a.getTypeSignature()))) { annotations.add(new AnnotationGen(a,getConstantPoolGen(),true)); } } }
108,816
Bug 108816 AspectJ 1.5.0 Development Compiler Chokes on Advice with Cflow
null
resolved fixed
71771ab
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-06T13:08:19Z
2005-09-06T07:00:00Z
tests/src/org/aspectj/systemtest/ajc150/Ajc150Tests.java
/******************************************************************************* * Copyright (c) 2004 IBM * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Andy Clement - initial API and implementation *******************************************************************************/ package org.aspectj.systemtest.ajc150; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import junit.framework.Test; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.apache.bcel.classfile.Method; import org.aspectj.apache.bcel.util.ClassPath; import org.aspectj.apache.bcel.util.SyntheticRepository; import org.aspectj.asm.AsmManager; import org.aspectj.testing.XMLBasedAjcTestCase; import org.aspectj.util.LangUtil; /** * These are tests that will run on Java 1.4 and use the old harness format for test specification. */ public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase { public static Test suite() { return XMLBasedAjcTestCase.loadSuite(Ajc150Tests.class); } protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml"); } public void test_typeProcessingOrderWhenDeclareParents() { runTest("Order of types passed to compiler determines weaving behavior"); } public void test_aroundMethod() { runTest("method called around in class"); } public void test_aroundMethodAspect() { runTest("method called around in aspect"); } public void test_ambiguousBindingsDetection() { runTest("Various kinds of ambiguous bindings"); } public void test_ambiguousArgsDetection() { runTest("ambiguous args"); } public void testIncorrectExceptionTableWhenBreakInMethod_pr78021() { runTest("Injecting exception into while loop with break statement causes catch block to be ignored"); } public void testIncorrectExceptionTableWhenReturnInMethod_pr79554() { runTest("Return in try-block disables catch-block if final-block is present"); } public void testMissingDebugInfoForGeneratedMethods_pr82570() throws ClassNotFoundException { runTest("Weaved code does not include debug lines"); boolean f = false; JavaClass jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1"); Method[] meths = jc.getMethods(); for (int i = 0; i < meths.length; i++) { Method method = meths[i]; if (f) System.err.println("Line number table for "+method.getName()+method.getSignature()+" = "+method.getLineNumberTable()); assertTrue("Didn't find a line number table for method "+method.getName()+method.getSignature(), method.getLineNumberTable()!=null); } // This test would determine the info isn't there if you pass -g:none ... // cR = ajc(baseDir,new String[]{"PR82570_1.java","-g:none"}); // assertTrue("Expected no compile problem:"+cR,!cR.hasErrorMessages()); // System.err.println(cR.getStandardError()); // jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1"); // meths = jc.getMethods(); // for (int i = 0; i < meths.length; i++) { // Method method = meths[i]; // assertTrue("Found a line number table for method "+method.getName(), // method.getLineNumberTable()==null); // } } public void testCanOverrideProtectedMethodsViaITDandDecp_pr83303() { runTest("compiler error when mixing inheritance, overriding and polymorphism"); } public void testPerTypeWithinMissesNamedInnerTypes() { runTest("pertypewithin() handing of inner classes (1)"); } public void testPerTypeWithinMissesAnonymousInnerTypes() { runTest("pertypewithin() handing of inner classes (2)"); } public void testPerTypeWithinIncorrectlyMatchingInterfaces() { runTest("pertypewithin({interface}) illegal field modifier"); } public void test051_arrayCloningInJava5() { runTest("AJC possible bug with static nested classes"); } public void testBadASMforEnums() throws IOException { runTest("bad asm for enums"); if (LangUtil.is15VMOrGreater()) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintWriter pw = new PrintWriter(baos); AsmManager.dumptree(pw,AsmManager.getDefault().getHierarchy().getRoot(),0); pw.flush(); String tree = baos.toString(); assertTrue("Expected 'Red [enumvalue]' somewhere in here:"+tree,tree.indexOf("Red [enumvalue]")!=-1); } } public void npeOnTypeNotFound() { runTest("structure model npe on type not found"); } public void testNoRuntimeExceptionSoftening() { runTest("declare soft of runtime exception"); } public void testRuntimeNoSoftenWithHandler() { runTest("declare soft w. catch block"); } public void testSyntaxError() { runTest("invalid cons syntax"); } public void testVarargsInConsBug() { runTest("varargs in constructor sig"); } public void testAspectpathdirs() { runTest("dirs on aspectpath"); } public void testIntroSample() { runTest("introduction sample"); } public void testPTWInterface() { runTest("pertypewithin({interface}) illegal field modifier"); } public void testEnumCalledEnumEtc() { runTest("enum called Enum, annotation called Annotation, etc"); } public void testInternalCompilerError_pr86832() { runTest("Internal compiler error"); } public void testCloneMethod_pr83311() { runTest("overriding/polymorphism error on interface method introduction"); } /** * IfPointcut.findResidueInternal() was modified to make this test complete in a short amount * of time - if you see it hanging, someone has messed with the optimization. */ public void testIfEvaluationExplosion_pr94086() { runTest("Exploding compile time with if() statements in pointcut"); } public void testReflectNPE_pr94167() {runTest("NPE in reflect implementation");} public void testStaticImports_pr84260() {runTest("static import failures");} public void testGenerics_pr99089() {runTest("ArrayIndexOutOfBoundsException - Generics in privileged aspects");} public void testGenerics_pr95993() {runTest("NPE at ClassScope.java:660 when compiling generic class");} public void testItdGenerics_pr99228() {runTest("ITD of a field into a generic class");} public void testItdGenerics_pr98320() {runTest("intertype with nested generic type");} public void testItdGenerics_pr100227() {runTest("inner class with generic enclosing class");} public void testItdGenerics_pr100260() {runTest("methods inherited from a generic parent");} public void testSyntaxErrorNPE_pr103266() {runTest("NPE on syntax error");} public void testIllegalStateExceptionOnNestedParameterizedType_pr106634() { runTest("IllegalStateException unpacking signature of nested parameterized type"); } public void testParseErrorOnAnnotationStarPlusPattern() { runTest("(@Foo *)+ type pattern parse error"); } public void test_pr106130_tooManyLocals() { runTest("test weaving with > 256 locals"); } public void testMissingNamePattern_pr106461() { runTest("missing name pattern"); } public void testMissingNamePattern_pr107059() { runTest("parser crashes on call(void (@a *)(..)"); } public void testIntermediateAnnotationMatching() { runTest("intermediate annotation matching"); } public void testBadRuntimeTestGeneration() { runTest("target(@Foo *)"); } public void testErrorMessageOnITDWithTypePatterns() { runTest("clear error message on itd with type pattern"); } public void testAjKeywordsAsIdentifiers() { runTest("before and after are valid identifiers in classes"); } public void testAjKeywordsAsIdentifiers2() { runTest("before and after are valid identifiers in classes, part 2"); } public void testNoBeforeReturningAdvice() { runTest("before returning advice not allowed!"); } public void testDetectVoidFieldType() { runTest("void field type in pointcut expression"); } public void testPointcutOverriding() { runTest("overriding final pointcut from super-aspect"); } public void testAtSuppressWarnings() { runTest("@SuppressWarnings should suppress"); } public void testDEOWWithBindingPointcut() { runTest("declare warning : foo(str) : ...;"); } public void testAroundAdviceAndInterfaceInitializer() { runTest("around advice on interface initializer"); } public void testGoodErrorMessageOnUnmatchedMemberSyntax() { runTest("good error message for unmatched member syntax"); } public void testITDWithNoExceptionAndIntermediary() { runTest("itd override with no exception clause"); } public void testAnonymousInnerClasses() { runTest("anonymous inner classes"); } public void testMultipleAnonymousInnerClasses() { runTest("multiple anonymous inner classes"); } public void testPrivilegedMethodAccessorsGetRightExceptions_pr82989() { runTest("Compiler error due to a wrong exception check in try blocks"); } public void testAnonymousInnerClassWithMethodReturningTypeParameter_pr107898() { runTest("anonymous inner class with method returning type parameter"); } public void testMatchingOfObjectArray() { runTest("matching against Object[]"); } public void testMultipleAnonymousInnerClasses_pr108104() { runTest("multiple anonymous inner classes 2"); } public void testSignatureMatchingInMultipleOverrideScenario() { runTest("signature matching in override scenario"); } public void testWildcardAnnotationMatching_pr108245() { runTest("wildcard annotation matching - pr108245"); } public void testInnerTypesAndTypeVariables() { runTest("inner types and type variables"); } public void testAtAfterThrowingWithNoFormal() { runTest("@AfterThrowing with no formal specified"); } public void testParameterizedVarArgsMatch() { runTest("varargs with type variable"); } public void testFieldAccessInsideITDM() { runTest("itd field access inside itd method"); } public void testTypeVarWithTypeVarBound() { runTest("type variable with type variable bound"); } public void testEnumSwitchInITD() { runTest("switch on enum inside ITD method"); } public void testInnerTypeOfGeneric() { runTest("inner type of generic interface reference from parameterized type"); } public void testDeclareParentsIntroducingCovariantReturnType() { runTest("declare parents introducing override with covariance"); } public void testInnerClassPassedToVarargs() { runTest("inner class passed as argument to varargs method"); } public void testInlinedFieldAccessInProceedCall() { runTest("inlined field access in proceed call"); } public void testVisibiltyInSignatureMatchingWithOverridesPart1() { runTest("visibility in signature matching with overrides - 1"); } public void testVisibiltyInSignatureMatchingWithOverridesPart2() { runTest("visibility in signature matching with overrides - 2"); } public void testVisibiltyInSignatureMatchingWithOverridesPart3() { runTest("visibility in signature matching with overrides - 3"); } public void testArgsGeneratedCorrectlyForAdviceExecution() { runTest("args generated correctly for advice execution join point"); } public void testNoUnusedWarningsOnAspectTypes() { runTest("no unused warnings on aspect types"); } public void testSyntheticArgumentsOnITDConstructorsNotUsedInMatching() { runTest("synthetic arguments on itd cons are not used in matching"); } public void testParsingOfGenericTypeSignature() { runTest("parse generic type signature with parameterized type in interface"); } public void testOverrideAndCovarianceWithDecPRuntime() { runTest("override and covariance with decp - runtime"); } public void testOverrideAndCovarianceWithDecPRuntimeMultiFiles() { runTest("override and covariance with decp - runtime separate files"); } public void testAbstractSynchronizedITDMethods() { runTest("abstract synchronized itdms not detected"); } public void testSynchronizedITDInterfaceMethods() { runTest("synchronized itd interface methods"); } public void testNoWarningOnUnusedPointcut() { runTest("unused private pointcuts"); } public void testITDOnInterfaceWithExistingMember() { runTest("itd interface method already existing on interface"); } public void testFinalITDMOnInterface() { runTest("final itd methods on interfaces"); } public void testPrivatePointcutOverriding() { runTest("can't override private pointcut in abstract aspect"); } // helper methods..... public SyntheticRepository createRepos(File cpentry) { ClassPath cp = new ClassPath(cpentry+File.pathSeparator+System.getProperty("java.class.path")); return SyntheticRepository.getInstance(cp); } protected JavaClass getClassFrom(File where,String clazzname) throws ClassNotFoundException { SyntheticRepository repos = createRepos(where); return repos.loadClass(clazzname); } }
108,816
Bug 108816 AspectJ 1.5.0 Development Compiler Chokes on Advice with Cflow
null
resolved fixed
71771ab
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-06T13:08:19Z
2005-09-06T07:00:00Z
weaver/src/org/aspectj/weaver/patterns/ArgsPointcut.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataOutputStream; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Set; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.reflect.CodeSignature; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.BetaException; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.World; import org.aspectj.weaver.ast.Literal; import org.aspectj.weaver.ast.Test; import org.aspectj.weaver.internal.tools.PointcutExpressionImpl; /** * args(arguments) * * @author Erik Hilsdale * @author Jim Hugunin */ public class ArgsPointcut extends NameBindingPointcut { private static final String ASPECTJ_JP_SIGNATURE_PREFIX = "Lorg/aspectj/lang/JoinPoint"; private static final String ASPECTJ_SYNTHETIC_SIGNATURE_PREFIX = "Lorg/aspectj/runtime/internal/"; private TypePatternList arguments; public ArgsPointcut(TypePatternList arguments) { this.arguments = arguments; this.pointcutKind = ARGS; } public TypePatternList getArguments() { return arguments; } public Set couldMatchKinds() { return Shadow.ALL_SHADOW_KINDS; // empty args() matches jps with no args } public FuzzyBoolean fastMatch(FastMatchInfo type) { return FuzzyBoolean.MAYBE; } public FuzzyBoolean fastMatch(Class targetType) { return FuzzyBoolean.MAYBE; } protected FuzzyBoolean matchInternal(Shadow shadow) { ResolvedType[] argumentsToMatchAgainst = getArgumentsToMatchAgainst(shadow); FuzzyBoolean ret = arguments.matches(argumentsToMatchAgainst, TypePattern.DYNAMIC); return ret; } private ResolvedType[] getArgumentsToMatchAgainst(Shadow shadow) { ResolvedType[] argumentsToMatchAgainst = shadow.getIWorld().resolve(shadow.getGenericArgTypes()); // special treatment for adviceexecution which may have synthetic arguments we // want to ignore. if (shadow.getKind() == Shadow.AdviceExecution) { int numExtraArgs = 0; for (int i = 0; i < argumentsToMatchAgainst.length; i++) { String argumentSignature = argumentsToMatchAgainst[i].getSignature(); if (argumentSignature.startsWith(ASPECTJ_JP_SIGNATURE_PREFIX) || argumentSignature.startsWith(ASPECTJ_SYNTHETIC_SIGNATURE_PREFIX)) { numExtraArgs++; } else { // normal arg after AJ type means earlier arg was NOT synthetic numExtraArgs = 0; } } if (numExtraArgs > 0) { int newArgLength = argumentsToMatchAgainst.length - numExtraArgs; ResolvedType[] argsSubset = new ResolvedType[newArgLength]; System.arraycopy(argumentsToMatchAgainst, 0, argsSubset, 0, newArgLength); argumentsToMatchAgainst = argsSubset; } } else if (shadow.getKind() == Shadow.ConstructorExecution) { if (shadow.getMatchingSignature().getParameterTypes().length < argumentsToMatchAgainst.length) { // there are one or more synthetic args on the end, caused by non-public itd constructor int newArgLength = shadow.getMatchingSignature().getParameterTypes().length; ResolvedType[] argsSubset = new ResolvedType[newArgLength]; System.arraycopy(argumentsToMatchAgainst, 0, argsSubset, 0, newArgLength); argumentsToMatchAgainst = argsSubset; } } return argumentsToMatchAgainst; } public FuzzyBoolean match(JoinPoint jp, JoinPoint.StaticPart jpsp) { FuzzyBoolean ret = arguments.matches(jp.getArgs(),TypePattern.DYNAMIC); // this may have given a false match (e.g. args(int) may have matched a call to doIt(Integer x)) due to boxing // check for this... if (ret == FuzzyBoolean.YES) { // are the sigs compatible too... CodeSignature sig = (CodeSignature)jp.getSignature(); Class[] pTypes = sig.getParameterTypes(); ret = checkSignatureMatch(pTypes); } return ret; } /** * @param ret * @param pTypes * @return */ private FuzzyBoolean checkSignatureMatch(Class[] pTypes) { Collection tps = arguments.getExactTypes(); int sigIndex = 0; for (Iterator iter = tps.iterator(); iter.hasNext();) { UnresolvedType tp = (UnresolvedType) iter.next(); Class lookForClass = getPossiblyBoxed(tp); if (lookForClass != null) { boolean foundMatchInSig = false; while (sigIndex < pTypes.length && !foundMatchInSig) { if (pTypes[sigIndex++] == lookForClass) foundMatchInSig = true; } if (!foundMatchInSig) { return FuzzyBoolean.NO; } } } return FuzzyBoolean.YES; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#matchesDynamically(java.lang.Object, java.lang.Object, java.lang.Object[]) */ public boolean matchesDynamically(Object thisObject, Object targetObject, Object[] args) { return (arguments.matches(args,TypePattern.DYNAMIC) == FuzzyBoolean.YES); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#matchesStatically(java.lang.String, java.lang.reflect.Member, java.lang.Class, java.lang.Class, java.lang.reflect.Member) */ public FuzzyBoolean matchesStatically(String joinpointKind, Member member, Class thisClass, Class targetClass, Member withinCode) { Class[] paramTypes = new Class[0]; if (member instanceof Method) { paramTypes = ((Method)member).getParameterTypes(); } else if (member instanceof Constructor) { paramTypes = ((Constructor)member).getParameterTypes(); } else if (member instanceof PointcutExpressionImpl.Handler){ paramTypes = new Class[] {((PointcutExpressionImpl.Handler)member).getHandledExceptionType()}; } else if (member instanceof Field) { if (joinpointKind.equals(Shadow.FieldGet.getName())) return FuzzyBoolean.NO; // no args here paramTypes = new Class[] {((Field)member).getType()}; } else { return FuzzyBoolean.NO; } return arguments.matchesArgsPatternSubset(paramTypes); } private Class getPossiblyBoxed(UnresolvedType tp) { Class ret = (Class) ExactTypePattern.primitiveTypesMap.get(tp.getName()); if (ret == null) ret = (Class) ExactTypePattern.boxedPrimitivesMap.get(tp.getName()); return ret; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.NameBindingPointcut#getBindingAnnotationTypePatterns() */ public List getBindingAnnotationTypePatterns() { return Collections.EMPTY_LIST; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.NameBindingPointcut#getBindingTypePatterns() */ public List getBindingTypePatterns() { List l = new ArrayList(); TypePattern[] pats = arguments.getTypePatterns(); for (int i = 0; i < pats.length; i++) { if (pats[i] instanceof BindingTypePattern) { l.add(pats[i]); } } return l; } public void write(DataOutputStream s) throws IOException { s.writeByte(Pointcut.ARGS); arguments.write(s); writeLocation(s); } public static Pointcut read(VersionedDataInputStream s, ISourceContext context) throws IOException { ArgsPointcut ret = new ArgsPointcut(TypePatternList.read(s, context)); ret.readLocation(context, s); return ret; } public boolean equals(Object other) { if (!(other instanceof ArgsPointcut)) return false; ArgsPointcut o = (ArgsPointcut)other; return o.arguments.equals(this.arguments); } public int hashCode() { return arguments.hashCode(); } public void resolveBindings(IScope scope, Bindings bindings) { arguments.resolveBindings(scope, bindings, true, true); if (arguments.ellipsisCount > 1) { scope.message(IMessage.ERROR, this, "uses more than one .. in args (compiler limitation)"); } } public void resolveBindingsFromRTTI() { arguments.resolveBindingsFromRTTI(true, true); if (arguments.ellipsisCount > 1) { throw new UnsupportedOperationException("uses more than one .. in args (compiler limitation)"); } } public void postRead(ResolvedType enclosingType) { arguments.postRead(enclosingType); } public Pointcut concretize1(ResolvedType inAspect, ResolvedType declaringType, IntMap bindings) { if (isDeclare(bindings.getEnclosingAdvice())) { // Enforce rule about which designators are supported in declare inAspect.getWorld().showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ARGS_IN_DECLARE), bindings.getEnclosingAdvice().getSourceLocation(), null); return Pointcut.makeMatchesNothing(Pointcut.CONCRETE); } TypePatternList args = arguments.resolveReferences(bindings); if (inAspect.crosscuttingMembers != null) { inAspect.crosscuttingMembers.exposeTypes(args.getExactTypes()); } Pointcut ret = new ArgsPointcut(args); ret.copyLocationFrom(this); return ret; } private Test findResidueNoEllipsis(Shadow shadow, ExposedState state, TypePattern[] patterns) { ResolvedType[] argumentsToMatchAgainst = getArgumentsToMatchAgainst(shadow); int len = argumentsToMatchAgainst.length; //System.err.println("boudn to : " + len + ", " + patterns.length); if (patterns.length != len) { return Literal.FALSE; } Test ret = Literal.TRUE; for (int i=0; i < len; i++) { UnresolvedType argType = shadow.getGenericArgTypes()[i]; TypePattern type = patterns[i]; ResolvedType argRTX = shadow.getIWorld().resolve(argType,true); if (!(type instanceof BindingTypePattern)) { if (argRTX == ResolvedType.MISSING) { IMessage msg = new Message( WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_ARG_TYPE,argType.getName()), "",IMessage.ERROR,shadow.getSourceLocation(),null,new ISourceLocation[]{getSourceLocation()}); } if (type.matchesInstanceof(argRTX).alwaysTrue()) { continue; } } else { BindingTypePattern btp = (BindingTypePattern)type; // Check if we have already bound something to this formal if ((state.get(btp.getFormalIndex())!=null) &&(lastMatchedShadowId != shadow.shadowId)) { // ISourceLocation isl = getSourceLocation(); // Message errorMessage = new Message( // "Ambiguous binding of type "+type.getExactType().toString()+ // " using args(..) at this line - formal is already bound"+ // ". See secondary source location for location of args(..)", // shadow.getSourceLocation(),true,new ISourceLocation[]{getSourceLocation()}); // shadow.getIWorld().getMessageHandler().handleMessage(errorMessage); state.setErroneousVar(btp.getFormalIndex()); } } World world = shadow.getIWorld(); ResolvedType typeToExpose = type.getExactType().resolve(world); if (typeToExpose.isParameterizedType()) { boolean inDoubt = (type.matchesInstanceof(argRTX) == FuzzyBoolean.MAYBE); if (inDoubt && world.getLint().uncheckedArgument.isEnabled()) { String uncheckedMatchWith = typeToExpose.getSimpleBaseName(); if (argRTX.isParameterizedType() && (argRTX.getRawType() == typeToExpose.getRawType())) { uncheckedMatchWith = argRTX.getSimpleName(); } if (!isUncheckedArgumentWarningSuppressed()) { world.getLint().uncheckedArgument.signal( new String[] { typeToExpose.getSimpleName(), uncheckedMatchWith, typeToExpose.getSimpleBaseName(), shadow.toResolvedString(world)}, getSourceLocation(), new ISourceLocation[] {shadow.getSourceLocation()}); } } } ret = Test.makeAnd(ret, exposeStateForVar(shadow.getArgVar(i), type, state,shadow.getIWorld())); } return ret; } /** * We need to find out if someone has put the @SuppressAjWarnings{"uncheckedArgument"} * annotation somewhere. That somewhere is going to be an a piece of advice that uses this * pointcut. But how do we find it??? * @return */ private boolean isUncheckedArgumentWarningSuppressed() { return false; } protected Test findResidueInternal(Shadow shadow, ExposedState state) { if (arguments.matches(getArgumentsToMatchAgainst(shadow), TypePattern.DYNAMIC).alwaysFalse()) { return Literal.FALSE; } int ellipsisCount = arguments.ellipsisCount; if (ellipsisCount == 0) { return findResidueNoEllipsis(shadow, state, arguments.getTypePatterns()); } else if (ellipsisCount == 1) { TypePattern[] patternsWithEllipsis = arguments.getTypePatterns(); TypePattern[] patternsWithoutEllipsis = new TypePattern[shadow.getArgCount()]; int lenWithEllipsis = patternsWithEllipsis.length; int lenWithoutEllipsis = patternsWithoutEllipsis.length; // l1+1 >= l0 int indexWithEllipsis = 0; int indexWithoutEllipsis = 0; while (indexWithoutEllipsis < lenWithoutEllipsis) { TypePattern p = patternsWithEllipsis[indexWithEllipsis++]; if (p == TypePattern.ELLIPSIS) { int newLenWithoutEllipsis = lenWithoutEllipsis - (lenWithEllipsis-indexWithEllipsis); while (indexWithoutEllipsis < newLenWithoutEllipsis) { patternsWithoutEllipsis[indexWithoutEllipsis++] = TypePattern.ANY; } } else { patternsWithoutEllipsis[indexWithoutEllipsis++] = p; } } return findResidueNoEllipsis(shadow, state, patternsWithoutEllipsis); } else { throw new BetaException("unimplemented"); } } public String toString() { return "args" + arguments.toString() + ""; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } }
108,902
Bug 108902 Type mismatch: cannot convert from Collection to Collection
(From aspectj-users) The program below produces the erroneous message: [iajc] D:\workdir\DPsample\main\src\com\designpattern\observer\ObserverProt ocol.aj:39 [error] Type mismatch: cannot convert from Collection to Collection [iajc] return observers; [iajc] ^^^^^ //Subject.java interface Subject { public void addObserver(Observer observer); public void removeObserver(Observer observer); public Collection getObservers(); } //Observer.java interface Observer { public void update(); } //ObserverProtocol public abstract aspect ObserverProtocol{ abstract pointcut stateChange(Subject subject); after(Subject subject):stateChange(subject){ Iterator it=subject.getObservers().iterator(); while(it.hasNext()){ Observer observer=(Observer)it.next(); observer.update(); } } private Collection Subject.observers=new ArrayList(); public void Subject.addObserver(Observer observer){ observers.add(observer); } public void Subject.removeObserver(Observer observer){ observers.remove(observer); } public Collection Subject.getObservers() { return observers; } }
resolved fixed
2505485
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-08T13:40:33Z
2005-09-07T08:00:00Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/InterTypeMethodDeclaration.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.ajdt.internal.compiler.ast; import java.lang.reflect.Modifier; import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory; import org.aspectj.ajdt.internal.compiler.lookup.EclipseTypeMunger; import org.aspectj.ajdt.internal.compiler.problem.AjProblemReporter; import org.aspectj.org.eclipse.jdt.internal.compiler.ClassFile; import org.aspectj.org.eclipse.jdt.internal.compiler.CompilationResult; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeReference; import org.aspectj.org.eclipse.jdt.internal.compiler.codegen.CodeStream; import org.aspectj.org.eclipse.jdt.internal.compiler.flow.FlowInfo; import org.aspectj.org.eclipse.jdt.internal.compiler.flow.InitializationFlowContext; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ClassScope; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.MethodBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TagBits; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.parser.Parser; import org.aspectj.org.eclipse.jdt.internal.compiler.problem.AbortCompilationUnit; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.NameMangler; import org.aspectj.weaver.NewMethodTypeMunger; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.UnresolvedType; /** * An inter-type method declaration. * * @author Jim Hugunin */ public class InterTypeMethodDeclaration extends InterTypeDeclaration { public InterTypeMethodDeclaration(CompilationResult result, TypeReference onType) { super(result, onType); } public void parseStatements(Parser parser, CompilationUnitDeclaration unit) { if (ignoreFurtherInvestigation) return; if (!Modifier.isAbstract(declaredModifiers)) { parser.parse(this, unit); } } protected char[] getPrefix() { return (NameMangler.ITD_PREFIX + "interMethod$").toCharArray(); } public boolean isFinal() { return (declaredModifiers & AccFinal) != 0; } public void analyseCode( ClassScope currentScope, InitializationFlowContext flowContext, FlowInfo flowInfo) { if (Modifier.isAbstract(declaredModifiers)) return; super.analyseCode(currentScope, flowContext, flowInfo); } public void resolve(ClassScope upperScope) { if (munger == null) ignoreFurtherInvestigation = true; if (ignoreFurtherInvestigation) return; if (!Modifier.isStatic(declaredModifiers)) { this.arguments = AstUtil.insert( AstUtil.makeFinalArgument("ajc$this_".toCharArray(), onTypeBinding), this.arguments); binding.parameters = AstUtil.insert(onTypeBinding, binding.parameters); } super.resolve(upperScope); } public void resolveStatements() { checkAndSetModifiersForMethod(); if ((modifiers & AccSemicolonBody) != 0) { if ((declaredModifiers & AccAbstract) == 0) scope.problemReporter().methodNeedBody(this); } else { // the method HAS a body --> abstract native modifiers are forbiden if (((declaredModifiers & AccAbstract) != 0)) scope.problemReporter().methodNeedingNoBody(this); } // check @Override annotation - based on MethodDeclaration.resolveStatements() @Override processing checkOverride: { if (this.binding == null) break checkOverride; if (this.scope.compilerOptions().sourceLevel < JDK1_5) break checkOverride; int bindingModifiers = this.binding.modifiers; boolean hasOverrideAnnotation = (this.binding.tagBits & TagBits.AnnotationOverride) != 0; // Need to verify if (hasOverrideAnnotation) { // Work out the real method binding that we can use for comparison EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(scope); MethodBinding realthing = world.makeMethodBinding(munger.getSignature()); boolean reportError = true; // Go up the hierarchy, looking for something we override ReferenceBinding supertype = onTypeBinding.superclass(); while (supertype!=null && reportError) { MethodBinding[] possibles = supertype.getMethods(declaredSelector); for (int i = 0; i < possibles.length; i++) { MethodBinding mb = possibles[i]; boolean couldBeMatch = true; if (mb.parameters.length!=realthing.parameters.length) couldBeMatch=false; else { for (int j = 0; j < mb.parameters.length && couldBeMatch; j++) { if (!mb.parameters[j].equals(realthing.parameters[j])) couldBeMatch=false; } } // return types compatible? (allow for covariance) if (couldBeMatch && !returnType.resolvedType.isCompatibleWith(mb.returnType)) couldBeMatch=false; if (couldBeMatch) reportError = false; } supertype = supertype.superclass(); // superclass of object is null } // If we couldn't find something we override, report the error if (reportError) ((AjProblemReporter)this.scope.problemReporter()).itdMethodMustOverride(this,realthing); } } if (!Modifier.isAbstract(declaredModifiers)) super.resolveStatements(); if (Modifier.isStatic(declaredModifiers)) { // Check the target for ITD is not an interface if (onTypeBinding.isInterface()) { scope.problemReporter().signalError(sourceStart, sourceEnd, "methods in interfaces cannot be declared static"); } } } public EclipseTypeMunger build(ClassScope classScope) { EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(classScope); resolveOnType(classScope); if (ignoreFurtherInvestigation) return null; binding = classScope.referenceContext.binding.resolveTypesFor(binding); if (binding == null) { // if binding is null, we failed to find a type used in the method params, this error // has already been reported. this.ignoreFurtherInvestigation = true; //return null; throw new AbortCompilationUnit(compilationResult,null); } if (isTargetAnnotation(classScope,"method")) return null; // Error message output in isTargetAnnotation if (isTargetEnum(classScope,"method")) return null; // Error message output in isTargetEnum // This signature represents what we want consumers of the targetted type to 'see' // must use the factory method to build it since there may be typevariables from the binding // referred to in the parameters/returntype ResolvedMember sig = world.makeResolvedMember(binding,onTypeBinding); sig.resetName(new String(declaredSelector)); sig.resetModifiers(declaredModifiers); NewMethodTypeMunger myMunger = new NewMethodTypeMunger(sig, null); setMunger(myMunger); ResolvedType aspectType = world.fromEclipse(classScope.referenceContext.binding); ResolvedMember me = myMunger.getInterMethodBody(aspectType); this.selector = binding.selector = me.getName().toCharArray(); return new EclipseTypeMunger(world, myMunger, aspectType, this); } private AjAttribute makeAttribute() { return new AjAttribute.TypeMunger(munger); } public void generateCode(ClassScope classScope, ClassFile classFile) { if (ignoreFurtherInvestigation) { //System.err.println("no code for " + this); return; } classFile.extraAttributes.add(new EclipseAttributeAdapter(makeAttribute())); if (!Modifier.isAbstract(declaredModifiers)) { super.generateCode(classScope, classFile); // this makes the interMethodBody } // annotations on the ITD declaration get put on this method generateDispatchMethod(classScope, classFile); } public void generateDispatchMethod(ClassScope classScope, ClassFile classFile) { EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(classScope); UnresolvedType aspectType = world.fromBinding(classScope.referenceContext.binding); ResolvedMember signature = munger.getSignature(); ResolvedMember dispatchMember = AjcMemberMaker.interMethodDispatcher(signature, aspectType); MethodBinding dispatchBinding = world.makeMethodBinding(dispatchMember); MethodBinding introducedMethod = world.makeMethodBinding(AjcMemberMaker.interMethod(signature, aspectType, onTypeBinding.isInterface())); classFile.generateMethodInfoHeader(dispatchBinding); int methodAttributeOffset = classFile.contentsOffset; // Watch out! We are passing in 'binding' here (instead of dispatchBinding) so that // the dispatch binding attributes will include the annotations from the 'binding'. // There is a chance that something else on the binding (e.g. throws clause) might // damage the attributes generated for the dispatch binding. int attributeNumber = classFile.generateMethodInfoAttribute(binding, false, makeEffectiveSignatureAttribute(signature, Shadow.MethodCall, false)); int codeAttributeOffset = classFile.contentsOffset; classFile.generateCodeAttributeHeader(); CodeStream codeStream = classFile.codeStream; codeStream.reset(this, classFile); codeStream.initializeMaxLocals(dispatchBinding); MethodBinding methodBinding = introducedMethod; TypeBinding[] parameters = methodBinding.parameters; int length = parameters.length; int resolvedPosition; if (methodBinding.isStatic()) resolvedPosition = 0; else { codeStream.aload_0(); resolvedPosition = 1; } for (int i = 0; i < length; i++) { codeStream.load(parameters[i], resolvedPosition); if ((parameters[i] == DoubleBinding) || (parameters[i] == LongBinding)) resolvedPosition += 2; else resolvedPosition++; } // TypeBinding type; if (methodBinding.isStatic()) codeStream.invokestatic(methodBinding); else { if (methodBinding.declaringClass.isInterface()){ codeStream.invokeinterface(methodBinding); } else { codeStream.invokevirtual(methodBinding); } } AstUtil.generateReturn(dispatchBinding.returnType, codeStream); classFile.completeCodeAttribute(codeAttributeOffset); attributeNumber++; classFile.completeMethodInfo(methodAttributeOffset, attributeNumber); } protected Shadow.Kind getShadowKindForBody() { return Shadow.MethodExecution; } // XXX this code is copied from MethodScope, with a few adjustments for ITDs... private void checkAndSetModifiersForMethod() { // for reported problems, we want the user to see the declared selector char[] realSelector = this.selector; this.selector = declaredSelector; final ReferenceBinding declaringClass = this.binding.declaringClass; if ((declaredModifiers & AccAlternateModifierProblem) != 0) scope.problemReporter().duplicateModifierForMethod(onTypeBinding, this); // after this point, tests on the 16 bits reserved. int realModifiers = declaredModifiers & AccJustFlag; // check for abnormal modifiers int unexpectedModifiers = ~(AccPublic | AccPrivate | AccProtected | AccAbstract | AccStatic | AccFinal | AccSynchronized | AccNative | AccStrictfp); if ((realModifiers & unexpectedModifiers) != 0) { scope.problemReporter().illegalModifierForMethod(this); declaredModifiers &= ~AccJustFlag | ~unexpectedModifiers; } // check for incompatible modifiers in the visibility bits, isolate the visibility bits int accessorBits = realModifiers & (AccPublic | AccProtected | AccPrivate); if ((accessorBits & (accessorBits - 1)) != 0) { scope.problemReporter().illegalVisibilityModifierCombinationForMethod(onTypeBinding, this); // need to keep the less restrictive so disable Protected/Private as necessary if ((accessorBits & AccPublic) != 0) { if ((accessorBits & AccProtected) != 0) declaredModifiers &= ~AccProtected; if ((accessorBits & AccPrivate) != 0) declaredModifiers &= ~AccPrivate; } else if ((accessorBits & AccProtected) != 0 && (accessorBits & AccPrivate) != 0) { declaredModifiers &= ~AccPrivate; } } // check for modifiers incompatible with abstract modifier if ((declaredModifiers & AccAbstract) != 0) { int incompatibleWithAbstract = AccStatic | AccFinal | AccSynchronized | AccNative | AccStrictfp; if ((declaredModifiers & incompatibleWithAbstract) != 0) scope.problemReporter().illegalAbstractModifierCombinationForMethod(onTypeBinding, this); if (!onTypeBinding.isAbstract()) scope.problemReporter().abstractMethodInAbstractClass((SourceTypeBinding) onTypeBinding, this); } /* DISABLED for backward compatibility with javac (if enabled should also mark private methods as final) // methods from a final class are final : 8.4.3.3 if (methodBinding.declaringClass.isFinal()) modifiers |= AccFinal; */ // native methods cannot also be tagged as strictfp if ((declaredModifiers & AccNative) != 0 && (declaredModifiers & AccStrictfp) != 0) scope.problemReporter().nativeMethodsCannotBeStrictfp(onTypeBinding, this); // static members are only authorized in a static member or top level type if (((realModifiers & AccStatic) != 0) && declaringClass.isNestedType() && !declaringClass.isStatic()) scope.problemReporter().unexpectedStaticModifierForMethod(onTypeBinding, this); // restore the true selector now that any problems have been reported this.selector = realSelector; } }
108,902
Bug 108902 Type mismatch: cannot convert from Collection to Collection
(From aspectj-users) The program below produces the erroneous message: [iajc] D:\workdir\DPsample\main\src\com\designpattern\observer\ObserverProt ocol.aj:39 [error] Type mismatch: cannot convert from Collection to Collection [iajc] return observers; [iajc] ^^^^^ //Subject.java interface Subject { public void addObserver(Observer observer); public void removeObserver(Observer observer); public Collection getObservers(); } //Observer.java interface Observer { public void update(); } //ObserverProtocol public abstract aspect ObserverProtocol{ abstract pointcut stateChange(Subject subject); after(Subject subject):stateChange(subject){ Iterator it=subject.getObservers().iterator(); while(it.hasNext()){ Observer observer=(Observer)it.next(); observer.update(); } } private Collection Subject.observers=new ArrayList(); public void Subject.addObserver(Observer observer){ observers.add(observer); } public void Subject.removeObserver(Observer observer){ observers.remove(observer); } public Collection Subject.getObservers() { return observers; } }
resolved fixed
2505485
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-08T13:40:33Z
2005-09-07T08:00:00Z
tests/bugs150/pr108902/Observer.java
108,902
Bug 108902 Type mismatch: cannot convert from Collection to Collection
(From aspectj-users) The program below produces the erroneous message: [iajc] D:\workdir\DPsample\main\src\com\designpattern\observer\ObserverProt ocol.aj:39 [error] Type mismatch: cannot convert from Collection to Collection [iajc] return observers; [iajc] ^^^^^ //Subject.java interface Subject { public void addObserver(Observer observer); public void removeObserver(Observer observer); public Collection getObservers(); } //Observer.java interface Observer { public void update(); } //ObserverProtocol public abstract aspect ObserverProtocol{ abstract pointcut stateChange(Subject subject); after(Subject subject):stateChange(subject){ Iterator it=subject.getObservers().iterator(); while(it.hasNext()){ Observer observer=(Observer)it.next(); observer.update(); } } private Collection Subject.observers=new ArrayList(); public void Subject.addObserver(Observer observer){ observers.add(observer); } public void Subject.removeObserver(Observer observer){ observers.remove(observer); } public Collection Subject.getObservers() { return observers; } }
resolved fixed
2505485
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-08T13:40:33Z
2005-09-07T08:00:00Z
tests/bugs150/pr108902/Subject.java
108,902
Bug 108902 Type mismatch: cannot convert from Collection to Collection
(From aspectj-users) The program below produces the erroneous message: [iajc] D:\workdir\DPsample\main\src\com\designpattern\observer\ObserverProt ocol.aj:39 [error] Type mismatch: cannot convert from Collection to Collection [iajc] return observers; [iajc] ^^^^^ //Subject.java interface Subject { public void addObserver(Observer observer); public void removeObserver(Observer observer); public Collection getObservers(); } //Observer.java interface Observer { public void update(); } //ObserverProtocol public abstract aspect ObserverProtocol{ abstract pointcut stateChange(Subject subject); after(Subject subject):stateChange(subject){ Iterator it=subject.getObservers().iterator(); while(it.hasNext()){ Observer observer=(Observer)it.next(); observer.update(); } } private Collection Subject.observers=new ArrayList(); public void Subject.addObserver(Observer observer){ observers.add(observer); } public void Subject.removeObserver(Observer observer){ observers.remove(observer); } public Collection Subject.getObservers() { return observers; } }
resolved fixed
2505485
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-08T13:40:33Z
2005-09-07T08:00:00Z
tests/src/org/aspectj/systemtest/ajc150/Ajc150Tests.java
/******************************************************************************* * Copyright (c) 2004 IBM * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Andy Clement - initial API and implementation *******************************************************************************/ package org.aspectj.systemtest.ajc150; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import junit.framework.Test; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.apache.bcel.classfile.Method; import org.aspectj.apache.bcel.util.ClassPath; import org.aspectj.apache.bcel.util.SyntheticRepository; import org.aspectj.asm.AsmManager; import org.aspectj.testing.XMLBasedAjcTestCase; import org.aspectj.util.LangUtil; /** * These are tests that will run on Java 1.4 and use the old harness format for test specification. */ public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase { public static Test suite() { return XMLBasedAjcTestCase.loadSuite(Ajc150Tests.class); } protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml"); } public void test_typeProcessingOrderWhenDeclareParents() { runTest("Order of types passed to compiler determines weaving behavior"); } public void test_aroundMethod() { runTest("method called around in class"); } public void test_aroundMethodAspect() { runTest("method called around in aspect"); } public void test_ambiguousBindingsDetection() { runTest("Various kinds of ambiguous bindings"); } public void test_ambiguousArgsDetection() { runTest("ambiguous args"); } public void testIncorrectExceptionTableWhenBreakInMethod_pr78021() { runTest("Injecting exception into while loop with break statement causes catch block to be ignored"); } public void testIncorrectExceptionTableWhenReturnInMethod_pr79554() { runTest("Return in try-block disables catch-block if final-block is present"); } public void testMissingDebugInfoForGeneratedMethods_pr82570() throws ClassNotFoundException { runTest("Weaved code does not include debug lines"); boolean f = false; JavaClass jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1"); Method[] meths = jc.getMethods(); for (int i = 0; i < meths.length; i++) { Method method = meths[i]; if (f) System.err.println("Line number table for "+method.getName()+method.getSignature()+" = "+method.getLineNumberTable()); assertTrue("Didn't find a line number table for method "+method.getName()+method.getSignature(), method.getLineNumberTable()!=null); } // This test would determine the info isn't there if you pass -g:none ... // cR = ajc(baseDir,new String[]{"PR82570_1.java","-g:none"}); // assertTrue("Expected no compile problem:"+cR,!cR.hasErrorMessages()); // System.err.println(cR.getStandardError()); // jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1"); // meths = jc.getMethods(); // for (int i = 0; i < meths.length; i++) { // Method method = meths[i]; // assertTrue("Found a line number table for method "+method.getName(), // method.getLineNumberTable()==null); // } } public void testCanOverrideProtectedMethodsViaITDandDecp_pr83303() { runTest("compiler error when mixing inheritance, overriding and polymorphism"); } public void testPerTypeWithinMissesNamedInnerTypes() { runTest("pertypewithin() handing of inner classes (1)"); } public void testPerTypeWithinMissesAnonymousInnerTypes() { runTest("pertypewithin() handing of inner classes (2)"); } public void testPerTypeWithinIncorrectlyMatchingInterfaces() { runTest("pertypewithin({interface}) illegal field modifier"); } public void test051_arrayCloningInJava5() { runTest("AJC possible bug with static nested classes"); } public void testBadASMforEnums() throws IOException { runTest("bad asm for enums"); if (LangUtil.is15VMOrGreater()) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintWriter pw = new PrintWriter(baos); AsmManager.dumptree(pw,AsmManager.getDefault().getHierarchy().getRoot(),0); pw.flush(); String tree = baos.toString(); assertTrue("Expected 'Red [enumvalue]' somewhere in here:"+tree,tree.indexOf("Red [enumvalue]")!=-1); } } public void npeOnTypeNotFound() { runTest("structure model npe on type not found"); } public void testNoRuntimeExceptionSoftening() { runTest("declare soft of runtime exception"); } public void testRuntimeNoSoftenWithHandler() { runTest("declare soft w. catch block"); } public void testSyntaxError() { runTest("invalid cons syntax"); } public void testVarargsInConsBug() { runTest("varargs in constructor sig"); } public void testAspectpathdirs() { runTest("dirs on aspectpath"); } public void testIntroSample() { runTest("introduction sample"); } public void testPTWInterface() { runTest("pertypewithin({interface}) illegal field modifier"); } public void testEnumCalledEnumEtc() { runTest("enum called Enum, annotation called Annotation, etc"); } public void testInternalCompilerError_pr86832() { runTest("Internal compiler error"); } public void testCloneMethod_pr83311() { runTest("overriding/polymorphism error on interface method introduction"); } /** * IfPointcut.findResidueInternal() was modified to make this test complete in a short amount * of time - if you see it hanging, someone has messed with the optimization. */ public void testIfEvaluationExplosion_pr94086() { runTest("Exploding compile time with if() statements in pointcut"); } public void testReflectNPE_pr94167() {runTest("NPE in reflect implementation");} public void testStaticImports_pr84260() {runTest("static import failures");} public void testGenerics_pr99089() {runTest("ArrayIndexOutOfBoundsException - Generics in privileged aspects");} public void testGenerics_pr95993() {runTest("NPE at ClassScope.java:660 when compiling generic class");} public void testItdGenerics_pr99228() {runTest("ITD of a field into a generic class");} public void testItdGenerics_pr98320() {runTest("intertype with nested generic type");} public void testItdGenerics_pr100227() {runTest("inner class with generic enclosing class");} public void testItdGenerics_pr100260() {runTest("methods inherited from a generic parent");} public void testSyntaxErrorNPE_pr103266() {runTest("NPE on syntax error");} public void testIllegalStateExceptionOnNestedParameterizedType_pr106634() { runTest("IllegalStateException unpacking signature of nested parameterized type"); } public void testParseErrorOnAnnotationStarPlusPattern() { runTest("(@Foo *)+ type pattern parse error"); } public void test_pr106130_tooManyLocals() { runTest("test weaving with > 256 locals"); } public void testMissingNamePattern_pr106461() { runTest("missing name pattern"); } public void testMissingNamePattern_pr107059() { runTest("parser crashes on call(void (@a *)(..)"); } public void testIntermediateAnnotationMatching() { runTest("intermediate annotation matching"); } public void testBadRuntimeTestGeneration() { runTest("target(@Foo *)"); } public void testErrorMessageOnITDWithTypePatterns() { runTest("clear error message on itd with type pattern"); } public void testAjKeywordsAsIdentifiers() { runTest("before and after are valid identifiers in classes"); } public void testAjKeywordsAsIdentifiers2() { runTest("before and after are valid identifiers in classes, part 2"); } public void testNoBeforeReturningAdvice() { runTest("before returning advice not allowed!"); } public void testDetectVoidFieldType() { runTest("void field type in pointcut expression"); } public void testPointcutOverriding() { runTest("overriding final pointcut from super-aspect"); } public void testAtSuppressWarnings() { runTest("@SuppressWarnings should suppress"); } public void testDEOWWithBindingPointcut() { runTest("declare warning : foo(str) : ...;"); } public void testAroundAdviceAndInterfaceInitializer() { runTest("around advice on interface initializer"); } public void testGoodErrorMessageOnUnmatchedMemberSyntax() { runTest("good error message for unmatched member syntax"); } public void testITDWithNoExceptionAndIntermediary() { runTest("itd override with no exception clause"); } public void testAnonymousInnerClasses() { runTest("anonymous inner classes"); } public void testMultipleAnonymousInnerClasses() { runTest("multiple anonymous inner classes"); } public void testPrivilegedMethodAccessorsGetRightExceptions_pr82989() { runTest("Compiler error due to a wrong exception check in try blocks"); } public void testAnonymousInnerClassWithMethodReturningTypeParameter_pr107898() { runTest("anonymous inner class with method returning type parameter"); } public void testMatchingOfObjectArray() { runTest("matching against Object[]"); } public void testMultipleAnonymousInnerClasses_pr108104() { runTest("multiple anonymous inner classes 2"); } public void testSignatureMatchingInMultipleOverrideScenario() { runTest("signature matching in override scenario"); } public void testWildcardAnnotationMatching_pr108245() { runTest("wildcard annotation matching - pr108245"); } public void testInnerTypesAndTypeVariables() { runTest("inner types and type variables"); } public void testAtAfterThrowingWithNoFormal() { runTest("@AfterThrowing with no formal specified"); } public void testParameterizedVarArgsMatch() { runTest("varargs with type variable"); } public void testFieldAccessInsideITDM() { runTest("itd field access inside itd method"); } public void testTypeVarWithTypeVarBound() { runTest("type variable with type variable bound"); } public void testEnumSwitchInITD() { runTest("switch on enum inside ITD method"); } public void testInnerTypeOfGeneric() { runTest("inner type of generic interface reference from parameterized type"); } public void testDeclareParentsIntroducingCovariantReturnType() { runTest("declare parents introducing override with covariance"); } public void testInnerClassPassedToVarargs() { runTest("inner class passed as argument to varargs method"); } public void testInlinedFieldAccessInProceedCall() { runTest("inlined field access in proceed call"); } public void testVisibiltyInSignatureMatchingWithOverridesPart1() { runTest("visibility in signature matching with overrides - 1"); } public void testVisibiltyInSignatureMatchingWithOverridesPart2() { runTest("visibility in signature matching with overrides - 2"); } public void testVisibiltyInSignatureMatchingWithOverridesPart3() { runTest("visibility in signature matching with overrides - 3"); } public void testArgsGeneratedCorrectlyForAdviceExecution() { runTest("args generated correctly for advice execution join point"); } public void testNoUnusedWarningsOnAspectTypes() { runTest("no unused warnings on aspect types"); } public void testSyntheticArgumentsOnITDConstructorsNotUsedInMatching() { runTest("synthetic arguments on itd cons are not used in matching"); } public void testParsingOfGenericTypeSignature() { runTest("parse generic type signature with parameterized type in interface"); } public void testOverrideAndCovarianceWithDecPRuntime() { runTest("override and covariance with decp - runtime"); } public void testOverrideAndCovarianceWithDecPRuntimeMultiFiles() { runTest("override and covariance with decp - runtime separate files"); } public void testAbstractSynchronizedITDMethods() { runTest("abstract synchronized itdms not detected"); } public void testSynchronizedITDInterfaceMethods() { runTest("synchronized itd interface methods"); } public void testNoWarningOnUnusedPointcut() { runTest("unused private pointcuts"); } public void testITDOnInterfaceWithExistingMember() { runTest("itd interface method already existing on interface"); } public void testFinalITDMOnInterface() { runTest("final itd methods on interfaces"); } public void testPrivatePointcutOverriding() { runTest("can't override private pointcut in abstract aspect"); } public void testAdviceOnCflow() { runTest("advising cflow advice execution"); } // helper methods..... public SyntheticRepository createRepos(File cpentry) { ClassPath cp = new ClassPath(cpentry+File.pathSeparator+System.getProperty("java.class.path")); return SyntheticRepository.getInstance(cp); } protected JavaClass getClassFrom(File where,String clazzname) throws ClassNotFoundException { SyntheticRepository repos = createRepos(where); return repos.loadClass(clazzname); } }
109,042
Bug 109042 parameter ajc_aroundclosure is never read
null
resolved fixed
08d6a5d
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-08T14:09:18Z
2005-09-08T11:46:40Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/problem/AjProblemReporter.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.ajdt.internal.compiler.problem; import java.lang.reflect.Modifier; import java.util.Iterator; import java.util.List; import org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration; import org.aspectj.ajdt.internal.compiler.ast.PointcutDeclaration; import org.aspectj.ajdt.internal.compiler.ast.Proceed; import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory; import org.aspectj.ajdt.internal.compiler.lookup.InterTypeMethodBinding; import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation; import org.aspectj.org.eclipse.jdt.core.compiler.IProblem; import org.aspectj.org.eclipse.jdt.internal.compiler.CompilationResult; import org.aspectj.org.eclipse.jdt.internal.compiler.IErrorHandlingPolicy; import org.aspectj.org.eclipse.jdt.internal.compiler.IProblemFactory; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.ASTNode; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Annotation; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.ExplicitConstructorCall; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.impl.CompilerOptions; import org.aspectj.org.eclipse.jdt.internal.compiler.impl.ReferenceContext; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ArrayBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.MethodBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TagBits; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.problem.ProblemReporter; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.ConcreteTypeMunger; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.patterns.DeclareAnnotation; import org.aspectj.weaver.patterns.DeclareSoft; /** * Extends problem reporter to support compiler-side implementation of declare soft. * Also overrides error reporting for the need to implement abstract methods to * account for inter-type declarations and pointcut declarations. This second * job might be better done directly in the SourceTypeBinding/ClassScope classes. * * @author Jim Hugunin */ public class AjProblemReporter extends ProblemReporter { private static final boolean DUMP_STACK = false; public EclipseFactory factory; public AjProblemReporter( IErrorHandlingPolicy policy, CompilerOptions options, IProblemFactory problemFactory) { super(policy, options, problemFactory); } public void unhandledException( TypeBinding exceptionType, ASTNode location) { if (!factory.getWorld().getDeclareSoft().isEmpty()) { Shadow callSite = factory.makeShadow(location, referenceContext); Shadow enclosingExec = factory.makeShadow(referenceContext); // PR 72157 - calls to super / this within a constructor are not part of the cons join point. if ((callSite == null) && (enclosingExec.getKind() == Shadow.ConstructorExecution) && (location instanceof ExplicitConstructorCall)) { super.unhandledException(exceptionType, location); return; } // System.err.println("about to show error for unhandled exception: " + new String(exceptionType.sourceName()) + // " at " + location + " in " + referenceContext); for (Iterator i = factory.getWorld().getDeclareSoft().iterator(); i.hasNext(); ) { DeclareSoft d = (DeclareSoft)i.next(); // We need the exceptionType to match the type in the declare soft statement // This means it must either be the same type or a subtype ResolvedType throwException = factory.fromEclipse((ReferenceBinding)exceptionType); FuzzyBoolean isExceptionTypeOrSubtype = d.getException().matchesInstanceof(throwException); if (!isExceptionTypeOrSubtype.alwaysTrue() ) continue; if (callSite != null) { FuzzyBoolean match = d.getPointcut().match(callSite); if (match.alwaysTrue()) { //System.err.println("matched callSite: " + callSite + " with " + d); return; } else if (!match.alwaysFalse()) { //!!! need this check to happen much sooner //throw new RuntimeException("unimplemented, shouldn't have fuzzy match here"); } } if (enclosingExec != null) { FuzzyBoolean match = d.getPointcut().match(enclosingExec); if (match.alwaysTrue()) { //System.err.println("matched enclosingExec: " + enclosingExec + " with " + d); return; } else if (!match.alwaysFalse()) { //!!! need this check to happen much sooner //throw new RuntimeException("unimplemented, shouldn't have fuzzy match here"); } } } } //??? is this always correct if (location instanceof Proceed) { return; } super.unhandledException(exceptionType, location); } private boolean isPointcutDeclaration(MethodBinding binding) { return CharOperation.prefixEquals(PointcutDeclaration.mangledPrefix, binding.selector); } private boolean isIntertypeDeclaration(MethodBinding binding) { return (binding instanceof InterTypeMethodBinding); } public void abstractMethodCannotBeOverridden( SourceTypeBinding type, MethodBinding concreteMethod) { if (isPointcutDeclaration(concreteMethod)) { return; } super.abstractMethodCannotBeOverridden(type, concreteMethod); } public void inheritedMethodReducesVisibility(SourceTypeBinding type, MethodBinding concreteMethod, MethodBinding[] abstractMethods) { // if we implemented this method by a public inter-type declaration, then there is no error ResolvedType onTypeX = null; // If the type is anonymous, look at its supertype if (!type.isAnonymousType()) { onTypeX = factory.fromEclipse(type); } else { // Hmmm. If the ITD is on an interface that is being 'instantiated' using an anonymous type, // we sort it out elsewhere and don't come into this method - // so we don't have to worry about interfaces, just the superclass. onTypeX = factory.fromEclipse(type.superclass()); //abstractMethod.declaringClass); } for (Iterator i = onTypeX.getInterTypeMungersIncludingSupers().iterator(); i.hasNext(); ) { ConcreteTypeMunger m = (ConcreteTypeMunger)i.next(); ResolvedMember sig = m.getSignature(); if (!Modifier.isAbstract(sig.getModifiers())) { if (ResolvedType .matches( AjcMemberMaker.interMethod( sig, m.getAspectType(), sig.getDeclaringType().resolve(factory.getWorld()).isInterface()), factory.makeResolvedMember(concreteMethod))) { return; } } } super.inheritedMethodReducesVisibility(type,concreteMethod,abstractMethods); } // if either of the MethodBinding is an ITD, we have already reported it. public void staticAndInstanceConflict(MethodBinding currentMethod, MethodBinding inheritedMethod) { if (currentMethod instanceof InterTypeMethodBinding) return; if (inheritedMethod instanceof InterTypeMethodBinding) return; super.staticAndInstanceConflict(currentMethod, inheritedMethod); } public void abstractMethodMustBeImplemented( SourceTypeBinding type, MethodBinding abstractMethod) { // if this is a PointcutDeclaration then there is no error if (isPointcutDeclaration(abstractMethod)) return; if (isIntertypeDeclaration(abstractMethod)) return; // when there is a problem with an ITD not being implemented, it will be reported elsewhere if (CharOperation.prefixEquals("ajc$interField".toCharArray(), abstractMethod.selector)) { //??? think through how this could go wrong return; } // if we implemented this method by an inter-type declaration, then there is no error //??? be sure this is always right ResolvedType onTypeX = null; // If the type is anonymous, look at its supertype if (!type.isAnonymousType()) { onTypeX = factory.fromEclipse(type); } else { // Hmmm. If the ITD is on an interface that is being 'instantiated' using an anonymous type, // we sort it out elsewhere and don't come into this method - // so we don't have to worry about interfaces, just the superclass. onTypeX = factory.fromEclipse(type.superclass()); //abstractMethod.declaringClass); } for (Iterator i = onTypeX.getInterTypeMungersIncludingSupers().iterator(); i.hasNext(); ) { ConcreteTypeMunger m = (ConcreteTypeMunger)i.next(); ResolvedMember sig = m.getSignature(); if (!Modifier.isAbstract(sig.getModifiers())) { if (ResolvedType .matches( AjcMemberMaker.interMethod( sig, m.getAspectType(), sig.getDeclaringType().resolve(factory.getWorld()).isInterface()), factory.makeResolvedMember(abstractMethod))) { return; } } } super.abstractMethodMustBeImplemented(type, abstractMethod); } /* (non-Javadoc) * @see org.aspectj.org.eclipse.jdt.internal.compiler.problem.ProblemReporter#disallowedTargetForAnnotation(org.aspectj.org.eclipse.jdt.internal.compiler.ast.Annotation) */ public void disallowedTargetForAnnotation(Annotation annotation) { // if the annotation's recipient is an ITD, it might be allowed after all... if (annotation.recipient instanceof MethodBinding) { MethodBinding binding = (MethodBinding) annotation.recipient; String name = new String(binding.selector); if (name.startsWith("ajc$")) { long metaTagBits = annotation.resolvedType.getAnnotationTagBits(); // could be forward reference if (name.indexOf("interField") != -1) { if ((metaTagBits & TagBits.AnnotationForField) != 0) return; } else if (name.indexOf("interConstructor") != -1) { if ((metaTagBits & TagBits.AnnotationForConstructor) != 0) return; } else if (name.indexOf("interMethod") != -1) { if ((metaTagBits & TagBits.AnnotationForMethod) != 0) return; } else if (name.indexOf("declare_"+DeclareAnnotation.AT_TYPE+"_")!=-1) { if ((metaTagBits & TagBits.AnnotationForAnnotationType)!=0 || (metaTagBits & TagBits.AnnotationForType)!=0) return; } else if (name.indexOf("declare_"+DeclareAnnotation.AT_FIELD+"_")!=-1) { if ((metaTagBits & TagBits.AnnotationForField)!=0) return; } else if (name.indexOf("declare_"+DeclareAnnotation.AT_CONSTRUCTOR+"_")!=-1) { if ((metaTagBits & TagBits.AnnotationForConstructor)!=0) return; } else if (name.indexOf("declare_eow") != -1) { if ((metaTagBits & TagBits.AnnotationForField) != 0) return; } } } // not our special case, report the problem... super.disallowedTargetForAnnotation(annotation); } public void handle( int problemId, String[] problemArguments, String[] messageArguments, int severity, int problemStartPosition, int problemEndPosition, ReferenceContext referenceContext, CompilationResult unitResult) { if (severity != Ignore && DUMP_STACK) { Thread.dumpStack(); } super.handle( problemId, problemArguments, messageArguments, severity, problemStartPosition, problemEndPosition, referenceContext, unitResult); } // PR71076 public void javadocMissingParamTag(char[] name, int sourceStart, int sourceEnd, int modifiers) { boolean reportIt = true; String sName = new String(name); if (sName.startsWith("ajc$")) reportIt = false; if (sName.equals("thisJoinPoint")) reportIt = false; if (sName.equals("thisJoinPointStaticPart")) reportIt = false; if (sName.equals("thisEnclosingJoinPointStaticPart")) reportIt = false; if (sName.equals("ajc_aroundClosure")) reportIt = false; if (reportIt) super.javadocMissingParamTag(name,sourceStart,sourceEnd,modifiers); } public void abstractMethodInAbstractClass(SourceTypeBinding type, AbstractMethodDeclaration methodDecl) { String abstractMethodName = new String(methodDecl.selector); if (abstractMethodName.startsWith("ajc$pointcut")) { // This will already have been reported, see: PointcutDeclaration.postParse() return; } String[] arguments = new String[] {new String(type.sourceName()), abstractMethodName}; super.handle( IProblem.AbstractMethodInAbstractClass, arguments, arguments, methodDecl.sourceStart, methodDecl.sourceEnd,this.referenceContext, this.referenceContext == null ? null : this.referenceContext.compilationResult()); } /** * Called when there is an ITD marked @override that doesn't override a supertypes method. * The method and the binding are passed - some information is useful from each. The 'method' * knows about source offsets for the message, the 'binding' has the signature of what the * ITD is trying to be in the target class. */ public void itdMethodMustOverride(AbstractMethodDeclaration method,MethodBinding binding) { this.handle( IProblem.MethodMustOverride, new String[] {new String(binding.selector), typesAsString(binding.isVarargs(), binding.parameters, false), new String(binding.declaringClass.readableName()), }, new String[] {new String(binding.selector), typesAsString(binding.isVarargs(), binding.parameters, true), new String(binding.declaringClass.shortReadableName()),}, method.sourceStart, method.sourceEnd, this.referenceContext, this.referenceContext == null ? null : this.referenceContext.compilationResult()); } /** * Overrides the implementation in ProblemReporter and is ITD aware. * To report a *real* problem with an ITD marked @override, the other methodMustOverride() method is used. */ public void methodMustOverride(AbstractMethodDeclaration method) { MethodBinding binding = method.binding; // ignore ajc$ methods if (new String(method.selector).startsWith("ajc$")) return; ResolvedMember possiblyErroneousRm = factory.makeResolvedMember(method.binding); ResolvedType onTypeX = factory.fromEclipse(method.binding.declaringClass); // Can't use 'getInterTypeMungersIncludingSupers()' since that will exclude abstract ITDs // on any super classes - so we have to trawl up ourselves.. I wonder if this problem // affects other code in the problem reporter that looks through ITDs... ResolvedType supertypeToLookAt = onTypeX.getSuperclass(); while (supertypeToLookAt!=null) { List itMungers = supertypeToLookAt.getInterTypeMungers(); for (Iterator i = itMungers.iterator(); i.hasNext(); ) { ConcreteTypeMunger m = (ConcreteTypeMunger)i.next(); ResolvedMember sig = m.getSignature(); ResolvedMember rm = AjcMemberMaker.interMethod(sig,m.getAspectType(), sig.getDeclaringType().resolve(factory.getWorld()).isInterface()); if (ResolvedType.matches(rm,possiblyErroneousRm)) { // match, so dont need to report a problem! return; } } supertypeToLookAt = supertypeToLookAt.getSuperclass(); } // report the error... super.methodMustOverride(method); } private String typesAsString(boolean isVarargs, TypeBinding[] types, boolean makeShort) { StringBuffer buffer = new StringBuffer(10); for (int i = 0, length = types.length; i < length; i++) { if (i != 0) buffer.append(", "); //$NON-NLS-1$ TypeBinding type = types[i]; boolean isVarargType = isVarargs && i == length-1; if (isVarargType) type = ((ArrayBinding)type).elementsType(); buffer.append(new String(makeShort ? type.shortReadableName() : type.readableName())); if (isVarargType) buffer.append("..."); //$NON-NLS-1$ } return buffer.toString(); } public void visibilityConflict(MethodBinding currentMethod, MethodBinding inheritedMethod) { // Not quite sure if the conditions on this test are right - basically I'm saying // DONT WORRY if its ITDs since the error will be reported another way... if (isIntertypeDeclaration(currentMethod) && isIntertypeDeclaration(inheritedMethod) && Modifier.isPrivate(currentMethod.modifiers) && Modifier.isPrivate(inheritedMethod.modifiers)) { return; } super.visibilityConflict(currentMethod,inheritedMethod); } public void unusedPrivateType(TypeDeclaration typeDecl) { // don't output unused type warnings for aspects! if (!(typeDecl instanceof AspectDeclaration)) super.unusedPrivateType(typeDecl); } public void unusedPrivateMethod(AbstractMethodDeclaration methodDecl) { // don't output unused warnings for pointcuts... if (!(methodDecl instanceof PointcutDeclaration)) super.unusedPrivateMethod(methodDecl); } /** * A side-effect of the way that we handle itds on default methods on top-most implementors * of interfaces is that a class acquiring a final default ITD will erroneously report * that it can't override its own member. This method detects that situation. */ public void finalMethodCannotBeOverridden(MethodBinding currentMethod, MethodBinding inheritedMethod) { if (currentMethod == inheritedMethod) return; super.finalMethodCannotBeOverridden(currentMethod, inheritedMethod); } }
109,042
Bug 109042 parameter ajc_aroundclosure is never read
null
resolved fixed
08d6a5d
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-08T14:09:18Z
2005-09-08T11:46:40Z
tests/src/org/aspectj/systemtest/ajc150/Ajc150Tests.java
/******************************************************************************* * Copyright (c) 2004 IBM * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Andy Clement - initial API and implementation *******************************************************************************/ package org.aspectj.systemtest.ajc150; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import junit.framework.Test; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.apache.bcel.classfile.Method; import org.aspectj.apache.bcel.util.ClassPath; import org.aspectj.apache.bcel.util.SyntheticRepository; import org.aspectj.asm.AsmManager; import org.aspectj.testing.XMLBasedAjcTestCase; import org.aspectj.util.LangUtil; /** * These are tests that will run on Java 1.4 and use the old harness format for test specification. */ public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase { public static Test suite() { return XMLBasedAjcTestCase.loadSuite(Ajc150Tests.class); } protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml"); } public void test_typeProcessingOrderWhenDeclareParents() { runTest("Order of types passed to compiler determines weaving behavior"); } public void test_aroundMethod() { runTest("method called around in class"); } public void test_aroundMethodAspect() { runTest("method called around in aspect"); } public void test_ambiguousBindingsDetection() { runTest("Various kinds of ambiguous bindings"); } public void test_ambiguousArgsDetection() { runTest("ambiguous args"); } public void testIncorrectExceptionTableWhenBreakInMethod_pr78021() { runTest("Injecting exception into while loop with break statement causes catch block to be ignored"); } public void testIncorrectExceptionTableWhenReturnInMethod_pr79554() { runTest("Return in try-block disables catch-block if final-block is present"); } public void testMissingDebugInfoForGeneratedMethods_pr82570() throws ClassNotFoundException { runTest("Weaved code does not include debug lines"); boolean f = false; JavaClass jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1"); Method[] meths = jc.getMethods(); for (int i = 0; i < meths.length; i++) { Method method = meths[i]; if (f) System.err.println("Line number table for "+method.getName()+method.getSignature()+" = "+method.getLineNumberTable()); assertTrue("Didn't find a line number table for method "+method.getName()+method.getSignature(), method.getLineNumberTable()!=null); } // This test would determine the info isn't there if you pass -g:none ... // cR = ajc(baseDir,new String[]{"PR82570_1.java","-g:none"}); // assertTrue("Expected no compile problem:"+cR,!cR.hasErrorMessages()); // System.err.println(cR.getStandardError()); // jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1"); // meths = jc.getMethods(); // for (int i = 0; i < meths.length; i++) { // Method method = meths[i]; // assertTrue("Found a line number table for method "+method.getName(), // method.getLineNumberTable()==null); // } } public void testCanOverrideProtectedMethodsViaITDandDecp_pr83303() { runTest("compiler error when mixing inheritance, overriding and polymorphism"); } public void testPerTypeWithinMissesNamedInnerTypes() { runTest("pertypewithin() handing of inner classes (1)"); } public void testPerTypeWithinMissesAnonymousInnerTypes() { runTest("pertypewithin() handing of inner classes (2)"); } public void testPerTypeWithinIncorrectlyMatchingInterfaces() { runTest("pertypewithin({interface}) illegal field modifier"); } public void test051_arrayCloningInJava5() { runTest("AJC possible bug with static nested classes"); } public void testBadASMforEnums() throws IOException { runTest("bad asm for enums"); if (LangUtil.is15VMOrGreater()) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintWriter pw = new PrintWriter(baos); AsmManager.dumptree(pw,AsmManager.getDefault().getHierarchy().getRoot(),0); pw.flush(); String tree = baos.toString(); assertTrue("Expected 'Red [enumvalue]' somewhere in here:"+tree,tree.indexOf("Red [enumvalue]")!=-1); } } public void npeOnTypeNotFound() { runTest("structure model npe on type not found"); } public void testNoRuntimeExceptionSoftening() { runTest("declare soft of runtime exception"); } public void testRuntimeNoSoftenWithHandler() { runTest("declare soft w. catch block"); } public void testSyntaxError() { runTest("invalid cons syntax"); } public void testVarargsInConsBug() { runTest("varargs in constructor sig"); } public void testAspectpathdirs() { runTest("dirs on aspectpath"); } public void testIntroSample() { runTest("introduction sample"); } public void testPTWInterface() { runTest("pertypewithin({interface}) illegal field modifier"); } public void testEnumCalledEnumEtc() { runTest("enum called Enum, annotation called Annotation, etc"); } public void testInternalCompilerError_pr86832() { runTest("Internal compiler error"); } public void testCloneMethod_pr83311() { runTest("overriding/polymorphism error on interface method introduction"); } /** * IfPointcut.findResidueInternal() was modified to make this test complete in a short amount * of time - if you see it hanging, someone has messed with the optimization. */ public void testIfEvaluationExplosion_pr94086() { runTest("Exploding compile time with if() statements in pointcut"); } public void testReflectNPE_pr94167() {runTest("NPE in reflect implementation");} public void testStaticImports_pr84260() {runTest("static import failures");} public void testGenerics_pr99089() {runTest("ArrayIndexOutOfBoundsException - Generics in privileged aspects");} public void testGenerics_pr95993() {runTest("NPE at ClassScope.java:660 when compiling generic class");} public void testItdGenerics_pr99228() {runTest("ITD of a field into a generic class");} public void testItdGenerics_pr98320() {runTest("intertype with nested generic type");} public void testItdGenerics_pr100227() {runTest("inner class with generic enclosing class");} public void testItdGenerics_pr100260() {runTest("methods inherited from a generic parent");} public void testSyntaxErrorNPE_pr103266() {runTest("NPE on syntax error");} public void testIllegalStateExceptionOnNestedParameterizedType_pr106634() { runTest("IllegalStateException unpacking signature of nested parameterized type"); } public void testParseErrorOnAnnotationStarPlusPattern() { runTest("(@Foo *)+ type pattern parse error"); } public void test_pr106130_tooManyLocals() { runTest("test weaving with > 256 locals"); } public void testMissingNamePattern_pr106461() { runTest("missing name pattern"); } public void testMissingNamePattern_pr107059() { runTest("parser crashes on call(void (@a *)(..)"); } public void testIntermediateAnnotationMatching() { runTest("intermediate annotation matching"); } public void testBadRuntimeTestGeneration() { runTest("target(@Foo *)"); } public void testErrorMessageOnITDWithTypePatterns() { runTest("clear error message on itd with type pattern"); } public void testAjKeywordsAsIdentifiers() { runTest("before and after are valid identifiers in classes"); } public void testAjKeywordsAsIdentifiers2() { runTest("before and after are valid identifiers in classes, part 2"); } public void testNoBeforeReturningAdvice() { runTest("before returning advice not allowed!"); } public void testDetectVoidFieldType() { runTest("void field type in pointcut expression"); } public void testPointcutOverriding() { runTest("overriding final pointcut from super-aspect"); } public void testAtSuppressWarnings() { runTest("@SuppressWarnings should suppress"); } public void testDEOWWithBindingPointcut() { runTest("declare warning : foo(str) : ...;"); } public void testAroundAdviceAndInterfaceInitializer() { runTest("around advice on interface initializer"); } public void testGoodErrorMessageOnUnmatchedMemberSyntax() { runTest("good error message for unmatched member syntax"); } public void testITDWithNoExceptionAndIntermediary() { runTest("itd override with no exception clause"); } public void testAnonymousInnerClasses() { runTest("anonymous inner classes"); } public void testMultipleAnonymousInnerClasses() { runTest("multiple anonymous inner classes"); } public void testPrivilegedMethodAccessorsGetRightExceptions_pr82989() { runTest("Compiler error due to a wrong exception check in try blocks"); } public void testAnonymousInnerClassWithMethodReturningTypeParameter_pr107898() { runTest("anonymous inner class with method returning type parameter"); } public void testMatchingOfObjectArray() { runTest("matching against Object[]"); } public void testMultipleAnonymousInnerClasses_pr108104() { runTest("multiple anonymous inner classes 2"); } public void testSignatureMatchingInMultipleOverrideScenario() { runTest("signature matching in override scenario"); } public void testWildcardAnnotationMatching_pr108245() { runTest("wildcard annotation matching - pr108245"); } public void testInnerTypesAndTypeVariables() { runTest("inner types and type variables"); } public void testAtAfterThrowingWithNoFormal() { runTest("@AfterThrowing with no formal specified"); } public void testParameterizedVarArgsMatch() { runTest("varargs with type variable"); } public void testFieldAccessInsideITDM() { runTest("itd field access inside itd method"); } public void testTypeVarWithTypeVarBound() { runTest("type variable with type variable bound"); } public void testEnumSwitchInITD() { runTest("switch on enum inside ITD method"); } public void testInnerTypeOfGeneric() { runTest("inner type of generic interface reference from parameterized type"); } public void testDeclareParentsIntroducingCovariantReturnType() { runTest("declare parents introducing override with covariance"); } public void testInnerClassPassedToVarargs() { runTest("inner class passed as argument to varargs method"); } public void testInlinedFieldAccessInProceedCall() { runTest("inlined field access in proceed call"); } public void testVisibiltyInSignatureMatchingWithOverridesPart1() { runTest("visibility in signature matching with overrides - 1"); } public void testVisibiltyInSignatureMatchingWithOverridesPart2() { runTest("visibility in signature matching with overrides - 2"); } public void testVisibiltyInSignatureMatchingWithOverridesPart3() { runTest("visibility in signature matching with overrides - 3"); } public void testArgsGeneratedCorrectlyForAdviceExecution() { runTest("args generated correctly for advice execution join point"); } public void testNoUnusedWarningsOnAspectTypes() { runTest("no unused warnings on aspect types"); } public void testSyntheticArgumentsOnITDConstructorsNotUsedInMatching() { runTest("synthetic arguments on itd cons are not used in matching"); } public void testParsingOfGenericTypeSignature() { runTest("parse generic type signature with parameterized type in interface"); } public void testOverrideAndCovarianceWithDecPRuntime() { runTest("override and covariance with decp - runtime"); } public void testOverrideAndCovarianceWithDecPRuntimeMultiFiles() { runTest("override and covariance with decp - runtime separate files"); } public void testAbstractSynchronizedITDMethods() { runTest("abstract synchronized itdms not detected"); } public void testSynchronizedITDInterfaceMethods() { runTest("synchronized itd interface methods"); } public void testNoWarningOnUnusedPointcut() { runTest("unused private pointcuts"); } public void testITDOnInterfaceWithExistingMember() { runTest("itd interface method already existing on interface"); } public void testFinalITDMOnInterface() { runTest("final itd methods on interfaces"); } public void testPrivatePointcutOverriding() { runTest("can't override private pointcut in abstract aspect"); } public void testAdviceOnCflow() { runTest("advising cflow advice execution"); } public void testNoTypeMismatchOnSameGenericTypes() { runTest("no type mismatch on generic types in itds"); } public void testSuperCallInITD() { runTest("super call in ITD"); } // helper methods..... public SyntheticRepository createRepos(File cpentry) { ClassPath cp = new ClassPath(cpentry+File.pathSeparator+System.getProperty("java.class.path")); return SyntheticRepository.getInstance(cp); } protected JavaClass getClassFrom(File where,String clazzname) throws ClassNotFoundException { SyntheticRepository repos = createRepos(where); return repos.loadClass(clazzname); } }
108,886
Bug 108886 Getting Exception during compilation : java.lang.RuntimeException: Internal Compiler Error: Unexpected null source location passed as 'see also' location.
Am attaching a small test case to reproduce the error (Not sure how to attach it - hopefully should be feasible to do so after I log the bug).
resolved fixed
2d21db0
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-08T16:57:15Z
2005-09-06T23:40:00Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/AjLookupEnvironment.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.ajdt.internal.compiler.lookup; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration; import org.aspectj.ajdt.internal.compiler.ast.PointcutDeclaration; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.WeaveMessage; import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Annotation; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.QualifiedTypeReference; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.SingleTypeReference; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.env.AccessRestriction; import org.aspectj.org.eclipse.jdt.internal.compiler.env.IBinaryType; import org.aspectj.org.eclipse.jdt.internal.compiler.env.INameEnvironment; import org.aspectj.org.eclipse.jdt.internal.compiler.impl.CompilerOptions; import org.aspectj.org.eclipse.jdt.internal.compiler.impl.ITypeRequestor; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.BinaryTypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ClassScope; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.CompilationUnitScope; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.LocalTypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.MethodBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.PackageBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TagBits; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.problem.ProblemReporter; import org.aspectj.weaver.AsmRelationshipProvider; import org.aspectj.weaver.ConcreteTypeMunger; import org.aspectj.weaver.ReferenceType; import org.aspectj.weaver.ResolvedTypeMunger; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.WeaverStateInfo; import org.aspectj.weaver.World; import org.aspectj.weaver.bcel.LazyClassGen; import org.aspectj.weaver.patterns.DeclareAnnotation; import org.aspectj.weaver.patterns.DeclareParents; /** * Overrides the default eclipse LookupEnvironment for two purposes. * * 1. To provide some additional phases to <code>completeTypeBindings</code> * that weave declare parents and inter-type declarations at the correct time. * * 2. To intercept the loading of new binary types to ensure the they will have * declare parents and inter-type declarations woven when appropriate. * * @author Jim Hugunin */ public class AjLookupEnvironment extends LookupEnvironment implements AnonymousClassCreationListener { public EclipseFactory factory = null; // private boolean builtInterTypesAndPerClauses = false; private List pendingTypesToWeave = new ArrayList(); private Map dangerousInterfaces = new HashMap(); public AjLookupEnvironment( ITypeRequestor typeRequestor, CompilerOptions options, ProblemReporter problemReporter, INameEnvironment nameEnvironment) { super(typeRequestor, options, problemReporter, nameEnvironment); } //??? duplicates some of super's code public void completeTypeBindings() { // builtInterTypesAndPerClauses = false; //pendingTypesToWeave = new ArrayList(); stepCompleted = BUILD_TYPE_HIERARCHY; for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) { units[i].scope.checkAndSetImports(); } stepCompleted = CHECK_AND_SET_IMPORTS; for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) { units[i].scope.connectTypeHierarchy(); } stepCompleted = CONNECT_TYPE_HIERARCHY; for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) { units[i].scope.buildFieldsAndMethods(); } // would like to gather up all TypeDeclarations at this point and put them in the factory for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) { SourceTypeBinding[] b = units[i].scope.topLevelTypes; for (int j = 0; j < b.length; j++) { factory.addSourceTypeBinding(b[j]); } } // We won't find out about anonymous types until later though, so register to be // told about them when they turn up. AnonymousClassPublisher.aspectOf().setAnonymousClassCreationListener(this); // need to build inter-type declarations for all AspectDeclarations at this point for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) { SourceTypeBinding[] b = units[i].scope.topLevelTypes; for (int j = 0; j < b.length; j++) { buildInterTypeAndPerClause(b[j].scope); addCrosscuttingStructures(b[j].scope); } } factory.finishTypeMungers(); // now do weaving Collection typeMungers = factory.getTypeMungers(); Collection declareParents = factory.getDeclareParents(); Collection declareAnnotationOnTypes = factory.getDeclareAnnotationOnTypes(); doPendingWeaves(); // We now have some list of types to process, and we are about to apply the type mungers. // There can be situations where the order of types passed to the compiler causes the // output from the compiler to vary - THIS IS BAD. For example, if we have class A // and class B extends A. Also, an aspect that 'declare parents: A+ implements Serializable' // then depending on whether we see A first, we may or may not make B serializable. // The fix is to process them in the right order, ensuring that for a type we process its // supertypes and superinterfaces first. This algorithm may have problems with: // - partial hierarchies (e.g. suppose types A,B,C are in a hierarchy and A and C are to be woven but not B) // - weaving that brings new types in for processing (see pendingTypesToWeave.add() calls) after we thought // we had the full list. // // but these aren't common cases (he bravely said...) boolean typeProcessingOrderIsImportant = declareParents.size()>0 || declareAnnotationOnTypes.size()>0; //DECAT if (typeProcessingOrderIsImportant) { List typesToProcess = new ArrayList(); for (int i=lastCompletedUnitIndex+1; i<=lastUnitIndex; i++) { CompilationUnitScope cus = units[i].scope; SourceTypeBinding[] stbs = cus.topLevelTypes; for (int j=0; j<stbs.length; j++) { SourceTypeBinding stb = stbs[j]; typesToProcess.add(stb); } } while (typesToProcess.size()>0) { // A side effect of weaveIntertypes() is that the processed type is removed from the collection weaveIntertypes(typesToProcess,(SourceTypeBinding)typesToProcess.get(0),typeMungers,declareParents,declareAnnotationOnTypes); } } else { // Order isn't important for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) { //System.err.println("Working on "+new String(units[i].getFileName())); weaveInterTypeDeclarations(units[i].scope, typeMungers, declareParents,declareAnnotationOnTypes); } } for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) { SourceTypeBinding[] b = units[i].scope.topLevelTypes; for (int j = 0; j < b.length; j++) { resolvePointcutDeclarations(b[j].scope); } } for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) { SourceTypeBinding[] b = units[i].scope.topLevelTypes; for (int j = 0; j < b.length; j++) { addAdviceLikeDeclares(b[j].scope); } } for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) { units[i] = null; // release unnecessary reference to the parsed unit } stepCompleted = BUILD_FIELDS_AND_METHODS; lastCompletedUnitIndex = lastUnitIndex; } /** * Weave the parents and intertype decls into a given type. This method looks at the * supertype and superinterfaces for the specified type and recurses to weave those first * if they are in the full list of types we are going to process during this compile... it stops recursing * the first time it hits a type we aren't going to process during this compile. This could cause problems * if you supply 'pieces' of a hierarchy, i.e. the bottom and the top, but not the middle - but what the hell * are you doing if you do that? */ private void weaveIntertypes(List typesToProcess,SourceTypeBinding typeToWeave,Collection typeMungers, Collection declareParents,Collection declareAnnotationOnTypes) { // Look at the supertype first ReferenceBinding superType = typeToWeave.superclass(); if (typesToProcess.contains(superType) && superType instanceof SourceTypeBinding) { //System.err.println("Recursing to supertype "+new String(superType.getFileName())); weaveIntertypes(typesToProcess,(SourceTypeBinding)superType,typeMungers,declareParents,declareAnnotationOnTypes); } // Then look at the superinterface list ReferenceBinding[] interfaceTypes = typeToWeave.superInterfaces(); for (int i = 0; i < interfaceTypes.length; i++) { ReferenceBinding binding = interfaceTypes[i]; if (typesToProcess.contains(binding) && binding instanceof SourceTypeBinding) { //System.err.println("Recursing to superinterface "+new String(binding.getFileName())); weaveIntertypes(typesToProcess,(SourceTypeBinding)binding,typeMungers,declareParents,declareAnnotationOnTypes); } } weaveInterTypeDeclarations(typeToWeave,typeMungers,declareParents,declareAnnotationOnTypes,false); typesToProcess.remove(typeToWeave); } private void doPendingWeaves() { for (Iterator i = pendingTypesToWeave.iterator(); i.hasNext(); ) { SourceTypeBinding t = (SourceTypeBinding)i.next(); weaveInterTypeDeclarations(t); } pendingTypesToWeave.clear(); } private void addAdviceLikeDeclares(ClassScope s) { TypeDeclaration dec = s.referenceContext; if (dec instanceof AspectDeclaration) { ResolvedType typeX = factory.fromEclipse(dec.binding); factory.getWorld().getCrosscuttingMembersSet().addAdviceLikeDeclares(typeX); } SourceTypeBinding sourceType = s.referenceContext.binding; ReferenceBinding[] memberTypes = sourceType.memberTypes; for (int i = 0, length = memberTypes.length; i < length; i++) { addAdviceLikeDeclares(((SourceTypeBinding) memberTypes[i]).scope); } } private void addCrosscuttingStructures(ClassScope s) { TypeDeclaration dec = s.referenceContext; if (dec instanceof AspectDeclaration) { ResolvedType typeX = factory.fromEclipse(dec.binding); factory.getWorld().getCrosscuttingMembersSet().addOrReplaceAspect(typeX); if (typeX.getSuperclass().isAspect() && !typeX.getSuperclass().isExposedToWeaver()) { factory.getWorld().getCrosscuttingMembersSet().addOrReplaceAspect(typeX.getSuperclass()); } } SourceTypeBinding sourceType = s.referenceContext.binding; ReferenceBinding[] memberTypes = sourceType.memberTypes; for (int i = 0, length = memberTypes.length; i < length; i++) { addCrosscuttingStructures(((SourceTypeBinding) memberTypes[i]).scope); } } private void resolvePointcutDeclarations(ClassScope s) { TypeDeclaration dec = s.referenceContext; SourceTypeBinding sourceType = s.referenceContext.binding; boolean hasPointcuts = false; AbstractMethodDeclaration[] methods = dec.methods; boolean initializedMethods = false; if (methods != null) { for (int i=0; i < methods.length; i++) { if (methods[i] instanceof PointcutDeclaration) { hasPointcuts = true; if (!initializedMethods) { sourceType.methods(); //force initialization initializedMethods = true; } ((PointcutDeclaration)methods[i]).resolvePointcut(s); } } } if (hasPointcuts || dec instanceof AspectDeclaration) { ReferenceType name = (ReferenceType)factory.fromEclipse(sourceType); EclipseSourceType eclipseSourceType = (EclipseSourceType)name.getDelegate(); eclipseSourceType.checkPointcutDeclarations(); } ReferenceBinding[] memberTypes = sourceType.memberTypes; for (int i = 0, length = memberTypes.length; i < length; i++) { resolvePointcutDeclarations(((SourceTypeBinding) memberTypes[i]).scope); } } private void buildInterTypeAndPerClause(ClassScope s) { TypeDeclaration dec = s.referenceContext; if (dec instanceof AspectDeclaration) { ((AspectDeclaration)dec).buildInterTypeAndPerClause(s); } SourceTypeBinding sourceType = s.referenceContext.binding; // test classes don't extend aspects if (sourceType.superclass != null) { ResolvedType parent = factory.fromEclipse(sourceType.superclass); if (parent.isAspect() && !isAspect(dec)) { factory.showMessage(IMessage.ERROR, "class \'" + new String(sourceType.sourceName) + "\' can not extend aspect \'" + parent.getName() + "\'", factory.fromEclipse(sourceType).getSourceLocation(), null); } } ReferenceBinding[] memberTypes = sourceType.memberTypes; for (int i = 0, length = memberTypes.length; i < length; i++) { buildInterTypeAndPerClause(((SourceTypeBinding) memberTypes[i]).scope); } } private boolean isAspect(TypeDeclaration decl) { if ((decl instanceof AspectDeclaration)) { return true; } else if (decl.annotations == null) { return false; } else { for (int i = 0; i < decl.annotations.length; i++) { Annotation ann = decl.annotations[i]; if (ann.type instanceof SingleTypeReference) { if (CharOperation.equals("Aspect".toCharArray(),((SingleTypeReference)ann.type).token)) return true; } else if (ann.type instanceof QualifiedTypeReference) { QualifiedTypeReference qtr = (QualifiedTypeReference) ann.type; if (qtr.tokens.length != 5) return false; if (!CharOperation.equals("org".toCharArray(),qtr.tokens[0])) return false; if (!CharOperation.equals("aspectj".toCharArray(),qtr.tokens[1])) return false; if (!CharOperation.equals("lang".toCharArray(),qtr.tokens[2])) return false; if (!CharOperation.equals("annotation".toCharArray(),qtr.tokens[3])) return false; if (!CharOperation.equals("Aspect".toCharArray(),qtr.tokens[4])) return false; return true; } } } return false; } private void weaveInterTypeDeclarations(CompilationUnitScope unit, Collection typeMungers, Collection declareParents, Collection declareAnnotationOnTypes) { for (int i = 0, length = unit.topLevelTypes.length; i < length; i++) { weaveInterTypeDeclarations(unit.topLevelTypes[i], typeMungers, declareParents, declareAnnotationOnTypes,false); } } private void weaveInterTypeDeclarations(SourceTypeBinding sourceType) { if (!factory.areTypeMungersFinished()) { if (!pendingTypesToWeave.contains(sourceType)) pendingTypesToWeave.add(sourceType); } else { weaveInterTypeDeclarations(sourceType, factory.getTypeMungers(), factory.getDeclareParents(), factory.getDeclareAnnotationOnTypes(),true); } } private void weaveInterTypeDeclarations(SourceTypeBinding sourceType, Collection typeMungers, Collection declareParents, Collection declareAnnotationOnTypes, boolean skipInners) { ResolvedType onType = factory.fromEclipse(sourceType); // AMC we shouldn't need this when generic sigs are fixed?? if (onType.isRawType()) onType = onType.getGenericType(); WeaverStateInfo info = onType.getWeaverState(); if (info != null && !info.isOldStyle()) { Collection mungers = onType.getWeaverState().getTypeMungers(onType); //System.out.println(onType + " mungers: " + mungers); for (Iterator i = mungers.iterator(); i.hasNext(); ) { ConcreteTypeMunger m = (ConcreteTypeMunger)i.next(); EclipseTypeMunger munger = factory.makeEclipseTypeMunger(m); if (munger.munge(sourceType,onType)) { if (onType.isInterface() && munger.getMunger().needsAccessToTopmostImplementor()) { if (!onType.getWorld().getCrosscuttingMembersSet().containsAspect(munger.getAspectType())) { dangerousInterfaces.put(onType, "implementors of " + onType + " must be woven by " + munger.getAspectType()); } } } } return; } //System.out.println("dangerousInterfaces: " + dangerousInterfaces); for (Iterator i = dangerousInterfaces.entrySet().iterator(); i.hasNext();) { Map.Entry entry = (Map.Entry) i.next(); ResolvedType interfaceType = (ResolvedType)entry.getKey(); if (onType.isTopmostImplementor(interfaceType)) { factory.showMessage(IMessage.ERROR, onType + ": " + entry.getValue(), onType.getSourceLocation(), null); } } boolean needOldStyleWarning = (info != null && info.isOldStyle()); onType.clearInterTypeMungers(); // FIXME asc perf Could optimize here, after processing the expected set of types we may bring // binary types that are not exposed to the weaver, there is no need to attempt declare parents // or declare annotation really - unless we want to report the not-exposed to weaver // messages... List decpToRepeat = new ArrayList(); List decaToRepeat = new ArrayList(); boolean anyNewParents = false; boolean anyNewAnnotations = false; // first pass // try and apply all decps - if they match, then great. If they don't then // check if they are starred-annotation patterns. If they are not starred // annotation patterns then they might match later...remember that... for (Iterator i = declareParents.iterator(); i.hasNext();) { DeclareParents decp = (DeclareParents)i.next(); boolean didSomething = doDeclareParents(decp, sourceType); if (didSomething) { anyNewParents = true; } else { if (!decp.getChild().isStarAnnotation()) decpToRepeat.add(decp); } } for (Iterator i = declareAnnotationOnTypes.iterator(); i.hasNext();) { DeclareAnnotation deca = (DeclareAnnotation)i.next(); boolean didSomething = doDeclareAnnotations(deca, sourceType,true); if (didSomething) { anyNewAnnotations = true; } else { if (!deca.getTypePattern().isStar()) decaToRepeat.add(deca); } } // now lets loop over and over until we have done all we can while ((anyNewAnnotations || anyNewParents) && (!decpToRepeat.isEmpty() || !decaToRepeat.isEmpty())) { anyNewParents = anyNewAnnotations = false; List forRemoval = new ArrayList(); for (Iterator i = decpToRepeat.iterator(); i.hasNext();) { DeclareParents decp = (DeclareParents)i.next(); boolean didSomething = doDeclareParents(decp, sourceType); if (didSomething) { anyNewParents = true; forRemoval.add(decp); } } decpToRepeat.removeAll(forRemoval); forRemoval = new ArrayList(); for (Iterator i = declareAnnotationOnTypes.iterator(); i.hasNext();) { DeclareAnnotation deca = (DeclareAnnotation)i.next(); boolean didSomething = doDeclareAnnotations(deca, sourceType,false); if (didSomething) { anyNewAnnotations = true; forRemoval.add(deca); } } decaToRepeat.removeAll(forRemoval); } for (Iterator i = typeMungers.iterator(); i.hasNext();) { EclipseTypeMunger munger = (EclipseTypeMunger) i.next(); if (munger.matches(onType)) { if (needOldStyleWarning) { factory.showMessage(IMessage.WARNING, "The class for " + onType + " should be recompiled with ajc-1.1.1 for best results", onType.getSourceLocation(), null); needOldStyleWarning = false; } onType.addInterTypeMunger(munger); //TODO: Andy Should be done at weave time. // Unfortunately we can't do it at weave time unless the type mungers remember where // they came from. Thats why we do it here during complation because at this time // they do know their source location. I've put a flag in ResolvedTypeMunger that // records whether type mungers are currently set to remember their source location. // The flag is currently set to false, it should be set to true when we do the // work to version all AspectJ attributes. // (When done at weave time, it is done by invoking addRelationship() on // AsmRelationshipProvider (see BCELTypeMunger) if (!ResolvedTypeMunger.persistSourceLocation) // Do it up front if we bloody have to AsmInterTypeRelationshipProvider.getDefault().addRelationship(onType, munger); } } //???onType.checkInterTypeMungers(); onType.checkInterTypeMungers(); for (Iterator i = onType.getInterTypeMungers().iterator(); i.hasNext();) { EclipseTypeMunger munger = (EclipseTypeMunger) i.next(); //System.out.println("applying: " + munger + " to " + new String(sourceType.sourceName)); munger.munge(sourceType,onType); } // Call if you would like to do source weaving of declare @method/@constructor // at source time... no need to do this as it can't impact anything, but left here for // future generations to enjoy. Method source is commented out at the end of this module // doDeclareAnnotationOnMethods(); // Call if you would like to do source weaving of declare @field // at source time... no need to do this as it can't impact anything, but left here for // future generations to enjoy. Method source is commented out at the end of this module // doDeclareAnnotationOnFields(); if (skipInners) return; ReferenceBinding[] memberTypes = sourceType.memberTypes; for (int i = 0, length = memberTypes.length; i < length; i++) { if (memberTypes[i] instanceof SourceTypeBinding) { weaveInterTypeDeclarations((SourceTypeBinding) memberTypes[i], typeMungers, declareParents,declareAnnotationOnTypes, false); } } } private boolean doDeclareParents(DeclareParents declareParents, SourceTypeBinding sourceType) { List newParents = declareParents.findMatchingNewParents(factory.fromEclipse(sourceType),false); if (!newParents.isEmpty()) { for (Iterator i = newParents.iterator(); i.hasNext(); ) { ResolvedType parent = (ResolvedType)i.next(); if (dangerousInterfaces.containsKey(parent)) { ResolvedType onType = factory.fromEclipse(sourceType); factory.showMessage(IMessage.ERROR, onType + ": " + dangerousInterfaces.get(parent), onType.getSourceLocation(), null); } if (Modifier.isFinal(parent.getModifiers())) { factory.showMessage(IMessage.ERROR,"cannot extend final class " + parent.getClassName(),declareParents.getSourceLocation(),null); } else { AsmRelationshipProvider.getDefault().addDeclareParentsRelationship(declareParents.getSourceLocation(),factory.fromEclipse(sourceType), newParents); addParent(sourceType, parent); } } return true; } return false; } private String stringifyTargets(long bits) { if ((bits & TagBits.AnnotationTargetMASK)==0) return ""; Set s = new HashSet(); if ((bits&TagBits.AnnotationForAnnotationType)!=0) s.add("ANNOTATION_TYPE"); if ((bits&TagBits.AnnotationForConstructor)!=0) s.add("CONSTRUCTOR"); if ((bits&TagBits.AnnotationForField)!=0) s.add("FIELD"); if ((bits&TagBits.AnnotationForLocalVariable)!=0) s.add("LOCAL_VARIABLE"); if ((bits&TagBits.AnnotationForMethod)!=0) s.add("METHOD"); if ((bits&TagBits.AnnotationForPackage)!=0) s.add("PACKAGE"); if ((bits&TagBits.AnnotationForParameter)!=0) s.add("PARAMETER"); if ((bits&TagBits.AnnotationForType)!=0) s.add("TYPE"); StringBuffer sb = new StringBuffer(); sb.append("{"); for (Iterator iter = s.iterator(); iter.hasNext();) { String element = (String) iter.next(); sb.append(element); if (iter.hasNext()) sb.append(","); } sb.append("}"); return sb.toString(); } private boolean doDeclareAnnotations(DeclareAnnotation decA, SourceTypeBinding sourceType,boolean reportProblems) { ResolvedType rtx = factory.fromEclipse(sourceType); if (!decA.matches(rtx)) return false; if (!rtx.isExposedToWeaver()) return false; // Get the annotation specified in the declare TypeBinding tb = factory.makeTypeBinding(decA.getAspect()); SourceTypeBinding stb = null; // TODO asc determine if there really is a problem here (see comment below) // ClassCastException here means we probably have either a parameterized type or a raw type, we need the // commented out code to get it to work ... currently uncommented because I've not seen a case where its // required yet ... stb = (SourceTypeBinding)tb; MethodBinding[] mbs = stb.getMethods(decA.getAnnotationMethod().toCharArray()); long abits = mbs[0].getAnnotationTagBits(); // ensure resolved TypeDeclaration typeDecl = ((SourceTypeBinding)mbs[0].declaringClass).scope.referenceContext; AbstractMethodDeclaration methodDecl = typeDecl.declarationOf(mbs[0]); Annotation[] toAdd = methodDecl.annotations; // this is what to add abits = toAdd[0].resolvedType.getAnnotationTagBits(); Annotation currentAnnotations[] = sourceType.scope.referenceContext.annotations; if (currentAnnotations!=null) for (int i = 0; i < currentAnnotations.length; i++) { Annotation annotation = currentAnnotations[i]; String a = CharOperation.toString(annotation.type.getTypeName()); String b = CharOperation.toString(toAdd[0].type.getTypeName()); // FIXME asc we have a lint for attempting to add an annotation twice to a method, // we could put it out here *if* we can resolve the problem of errors coming out // multiple times if we have cause to loop through here if (a.equals(b)) return false; } if (((abits & TagBits.AnnotationTargetMASK)!=0)) { if ( (abits & (TagBits.AnnotationForAnnotationType | TagBits.AnnotationForType))==0) { // this means it specifies something other than annotation or normal type - error will have been already reported, just resolution process above return false; } if ( (sourceType.isAnnotationType() && (abits & TagBits.AnnotationForAnnotationType)==0) || (!sourceType.isAnnotationType() && (abits & TagBits.AnnotationForType)==0) ) { if (reportProblems) { if (decA.isExactPattern()) { factory.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.INCORRECT_TARGET_FOR_DECLARE_ANNOTATION,rtx.getName(),toAdd[0].type,stringifyTargets(abits)), decA.getSourceLocation(), null); } // dont put out the lint - the weaving process will do that // else { // if (factory.getWorld().getLint().invalidTargetForAnnotation.isEnabled()) { // factory.getWorld().getLint().invalidTargetForAnnotation.signal(new String[]{rtx.getName(),toAdd[0].type.toString(),stringifyTargets(abits)},decA.getSourceLocation(),null); // } // } } return false; } } // Build a new array of annotations // FIXME asc Should be caching the old set of annotations in the type so the class file // generated doesn't have the annotation, it will then be added again during // binary weaving? (similar to declare parents handling...) AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decA.getSourceLocation(),rtx.getSourceLocation()); Annotation abefore[] = sourceType.scope.referenceContext.annotations; Annotation[] newset = new Annotation[toAdd.length+(abefore==null?0:abefore.length)]; System.arraycopy(toAdd,0,newset,0,toAdd.length); if (abefore!=null) { System.arraycopy(abefore,0,newset,toAdd.length,abefore.length); } sourceType.scope.referenceContext.annotations = newset; return true; } private void reportDeclareParentsMessage(WeaveMessage.WeaveMessageKind wmk,SourceTypeBinding sourceType,ResolvedType parent) { if (!factory.getWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)) { String filename = new String(sourceType.getFileName()); int takefrom = filename.lastIndexOf('/'); if (takefrom == -1 ) takefrom = filename.lastIndexOf('\\'); filename = filename.substring(takefrom+1); factory.getWorld().getMessageHandler().handleMessage( WeaveMessage.constructWeavingMessage(wmk, new String[]{CharOperation.toString(sourceType.compoundName), filename, parent.getClassName(), getShortname(parent.getSourceLocation().getSourceFile().getPath())})); } } private String getShortname(String path) { int takefrom = path.lastIndexOf('/'); if (takefrom == -1) { takefrom = path.lastIndexOf('\\'); } return path.substring(takefrom+1); } private void addParent(SourceTypeBinding sourceType, ResolvedType parent) { ReferenceBinding parentBinding = (ReferenceBinding)factory.makeTypeBinding(parent); sourceType.rememberTypeHierarchy(); if (parentBinding.isClass()) { sourceType.superclass = parentBinding; // this used to be true, but I think I've fixed it now, decp is done at weave time! // TAG: WeavingMessage DECLARE PARENTS: EXTENDS // Compiler restriction: Can't do EXTENDS at weave time // So, only see this message if doing a source compilation // reportDeclareParentsMessage(WeaveMessage.WEAVEMESSAGE_DECLAREPARENTSEXTENDS,sourceType,parent); } else { ReferenceBinding[] oldI = sourceType.superInterfaces; ReferenceBinding[] newI; if (oldI == null) { newI = new ReferenceBinding[1]; newI[0] = parentBinding; } else { int n = oldI.length; newI = new ReferenceBinding[n+1]; System.arraycopy(oldI, 0, newI, 0, n); newI[n] = parentBinding; } sourceType.superInterfaces = newI; // warnOnAddedInterface(factory.fromEclipse(sourceType),parent); // now reported at weave time... // this used to be true, but I think I've fixed it now, decp is done at weave time! // TAG: WeavingMessage DECLARE PARENTS: IMPLEMENTS // This message will come out of BcelTypeMunger.munge if doing a binary weave // reportDeclareParentsMessage(WeaveMessage.WEAVEMESSAGE_DECLAREPARENTSIMPLEMENTS,sourceType,parent); } } public void warnOnAddedInterface (ResolvedType type, ResolvedType parent) { World world = factory.getWorld(); ResolvedType serializable = world.getCoreType(UnresolvedType.SERIALIZABLE); if (serializable.isAssignableFrom(type) && !serializable.isAssignableFrom(parent) && !LazyClassGen.hasSerialVersionUIDField(type)) { world.getLint().needsSerialVersionUIDField.signal( new String[] { type.getName().toString(), "added interface " + parent.getName().toString() }, null, null); } } private List pendingTypesToFinish = new ArrayList(); boolean inBinaryTypeCreationAndWeaving = false; boolean processingTheQueue = false; public BinaryTypeBinding createBinaryTypeFrom( IBinaryType binaryType, PackageBinding packageBinding, boolean needFieldsAndMethods, AccessRestriction accessRestriction) { if (inBinaryTypeCreationAndWeaving) { BinaryTypeBinding ret = super.createBinaryTypeFrom( binaryType, packageBinding, needFieldsAndMethods, accessRestriction); pendingTypesToFinish.add(ret); return ret; } inBinaryTypeCreationAndWeaving = true; try { BinaryTypeBinding ret = super.createBinaryTypeFrom( binaryType, packageBinding, needFieldsAndMethods, accessRestriction); weaveInterTypeDeclarations(ret); return ret; } finally { inBinaryTypeCreationAndWeaving = false; // Start processing the list... if (pendingTypesToFinish.size()>0) { processingTheQueue = true; while (!pendingTypesToFinish.isEmpty()) { BinaryTypeBinding nextVictim = (BinaryTypeBinding)pendingTypesToFinish.remove(0); // During this call we may recurse into this method and add // more entries to the pendingTypesToFinish list. weaveInterTypeDeclarations(nextVictim); } processingTheQueue = false; } } } /** * Callback driven when the compiler detects an anonymous type during block resolution. * We need to add it to the weaver so that we don't trip up later. * @param aBinding */ public void anonymousTypeBindingCreated(LocalTypeBinding aBinding) { factory.addSourceTypeBinding(aBinding); } } // commented out, supplied as info on how to manipulate annotations in an eclipse world // // public void doDeclareAnnotationOnMethods() { // Do the declare annotation on fields/methods/ctors //Collection daoms = factory.getDeclareAnnotationOnMethods(); //if (daoms!=null && daoms.size()>0 && !(sourceType instanceof BinaryTypeBinding)) { // System.err.println("Going through the methods on "+sourceType.debugName()+" looking for DECA matches"); // // We better take a look through them... // for (Iterator iter = daoms.iterator(); iter.hasNext();) { // DeclareAnnotation element = (DeclareAnnotation) iter.next(); // System.err.println("Looking for anything that might match "+element+" on "+sourceType.debugName()+" "+getType(sourceType.compoundName).debugName()+" "+(sourceType instanceof BinaryTypeBinding)); // // ReferenceBinding rbb = getType(sourceType.compoundName); // // fix me if we ever uncomment this code... should iterate the other way round, over the methods then over the decas // sourceType.methods(); // MethodBinding sourceMbs[] = sourceType.methods; // for (int i = 0; i < sourceMbs.length; i++) { // MethodBinding sourceMb = sourceMbs[i]; // MethodBinding mbbbb = ((SourceTypeBinding)rbb).getExactMethod(sourceMb.selector,sourceMb.parameters); // boolean isCtor = sourceMb.selector[0]=='<'; // // if ((element.isDeclareAtConstuctor() ^ !isCtor)) { // System.err.println("Checking "+sourceMb+" ... declaringclass="+sourceMb.declaringClass.debugName()+" rbb="+rbb.debugName()+" "+sourceMb.declaringClass.equals(rbb)); // // ResolvedMember rm = null; // rm = EclipseFactory.makeResolvedMember(mbbbb); // if (element.matches(rm,factory.getWorld())) { // System.err.println("MATCH"); // // // Determine the set of annotations that are currently on the method // ReferenceBinding rb = getType(sourceType.compoundName); //// TypeBinding tb = factory.makeTypeBinding(decA.getAspect()); // MethodBinding mb = ((SourceTypeBinding)rb).getExactMethod(sourceMb.selector,sourceMb.parameters); // //long abits = mbs[0].getAnnotationTagBits(); // ensure resolved // TypeDeclaration typeDecl = ((SourceTypeBinding)sourceMb.declaringClass).scope.referenceContext; // AbstractMethodDeclaration methodDecl = typeDecl.declarationOf(sourceMb); // Annotation[] currentlyHas = methodDecl.annotations; // this is what to add // //abits = toAdd[0].resolvedType.getAnnotationTagBits(); // // // Determine the annotations to add to that method // TypeBinding tb = factory.makeTypeBinding(element.getAspect()); // MethodBinding[] aspectMbs = ((SourceTypeBinding)tb).getMethods(element.getAnnotationMethod().toCharArray()); // long abits = aspectMbs[0].getAnnotationTagBits(); // ensure resolved // TypeDeclaration typeDecl2 = ((SourceTypeBinding)aspectMbs[0].declaringClass).scope.referenceContext; // AbstractMethodDeclaration methodDecl2 = typeDecl2.declarationOf(aspectMbs[0]); // Annotation[] toAdd = methodDecl2.annotations; // this is what to add // // abits = toAdd[0].resolvedType.getAnnotationTagBits(); //System.err.println("Has: "+currentlyHas+" toAdd: "+toAdd); // // // fix me? should check if it already has the annotation // //Annotation abefore[] = sourceType.scope.referenceContext.annotations; // Annotation[] newset = new Annotation[(currentlyHas==null?0:currentlyHas.length)+1]; // System.arraycopy(toAdd,0,newset,0,toAdd.length); // if (currentlyHas!=null) { // System.arraycopy(currentlyHas,0,newset,1,currentlyHas.length); // } // methodDecl.annotations = newset; // System.err.println("New set on "+CharOperation.charToString(sourceMb.selector)+" is "+newset); // } else // System.err.println("NO MATCH"); // } // } // } //} //} // commented out, supplied as info on how to manipulate annotations in an eclipse world // // public void doDeclareAnnotationOnFields() { // Collection daofs = factory.getDeclareAnnotationOnFields(); // if (daofs!=null && daofs.size()>0 && !(sourceType instanceof BinaryTypeBinding)) { // System.err.println("Going through the fields on "+sourceType.debugName()+" looking for DECA matches"); // // We better take a look through them... // for (Iterator iter = daofs.iterator(); iter.hasNext();) { // DeclareAnnotation element = (DeclareAnnotation) iter.next(); // System.err.println("Processing deca "+element+" on "+sourceType.debugName()+" "+getType(sourceType.compoundName).debugName()+" "+(sourceType instanceof BinaryTypeBinding)); // // ReferenceBinding rbb = getType(sourceType.compoundName); // // fix me? should iterate the other way round, over the methods then over the decas // sourceType.fields(); // resolve the bloody things // FieldBinding sourceFbs[] = sourceType.fields; // for (int i = 0; i < sourceFbs.length; i++) { // FieldBinding sourceFb = sourceFbs[i]; // //FieldBinding fbbbb = ((SourceTypeBinding)rbb).getgetExactMethod(sourceMb.selector,sourceMb.parameters); // // System.err.println("Checking "+sourceFb+" ... declaringclass="+sourceFb.declaringClass.debugName()+" rbb="+rbb.debugName()); // // ResolvedMember rm = null; // rm = EclipseFactory.makeResolvedMember(sourceFb); // if (element.matches(rm,factory.getWorld())) { // System.err.println("MATCH"); // // // Determine the set of annotations that are currently on the field // ReferenceBinding rb = getType(sourceType.compoundName); //// TypeBinding tb = factory.makeTypeBinding(decA.getAspect()); // FieldBinding fb = ((SourceTypeBinding)rb).getField(sourceFb.name,true); // //long abits = mbs[0].getAnnotationTagBits(); // ensure resolved // TypeDeclaration typeDecl = ((SourceTypeBinding)sourceFb.declaringClass).scope.referenceContext; // FieldDeclaration fd = typeDecl.declarationOf(sourceFb); // //AbstractMethodDeclaration methodDecl = typeDecl.declarationOf(sourceMb); // Annotation[] currentlyHas = fd.annotations; // this is what to add // //abits = toAdd[0].resolvedType.getAnnotationTagBits(); // // // Determine the annotations to add to that method // TypeBinding tb = factory.makeTypeBinding(element.getAspect()); // MethodBinding[] aspectMbs = ((SourceTypeBinding)tb).getMethods(element.getAnnotationMethod().toCharArray()); // long abits = aspectMbs[0].getAnnotationTagBits(); // ensure resolved // TypeDeclaration typeDecl2 = ((SourceTypeBinding)aspectMbs[0].declaringClass).scope.referenceContext; // AbstractMethodDeclaration methodDecl2 = typeDecl2.declarationOf(aspectMbs[0]); // Annotation[] toAdd = methodDecl2.annotations; // this is what to add // // abits = toAdd[0].resolvedType.getAnnotationTagBits(); //System.err.println("Has: "+currentlyHas+" toAdd: "+toAdd); // // // fix me? check if it already has the annotation // // // //Annotation abefore[] = sourceType.scope.referenceContext.annotations; // Annotation[] newset = new Annotation[(currentlyHas==null?0:currentlyHas.length)+1]; // System.arraycopy(toAdd,0,newset,0,toAdd.length); // if (currentlyHas!=null) { // System.arraycopy(currentlyHas,0,newset,1,currentlyHas.length); // } // fd.annotations = newset; // System.err.println("New set on "+CharOperation.charToString(sourceFb.name)+" is "+newset); // } else // System.err.println("NO MATCH"); // } // // } // }
108,886
Bug 108886 Getting Exception during compilation : java.lang.RuntimeException: Internal Compiler Error: Unexpected null source location passed as 'see also' location.
Am attaching a small test case to reproduce the error (Not sure how to attach it - hopefully should be feasible to do so after I log the bug).
resolved fixed
2d21db0
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-08T16:57:15Z
2005-09-06T23:40:00Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/EclipseFactory.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * Mik Kersten 2004-07-26 extended to allow overloading of * hierarchy builder * ******************************************************************/ package org.aspectj.ajdt.internal.compiler.lookup; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration; import org.aspectj.ajdt.internal.compiler.ast.AstUtil; import org.aspectj.ajdt.internal.core.builder.AjBuildManager; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.IMessage.Kind; import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.ASTNode; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.EmptyStatement; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Wildcard; import org.aspectj.org.eclipse.jdt.internal.compiler.impl.Constant; import org.aspectj.org.eclipse.jdt.internal.compiler.impl.ReferenceContext; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.BaseTypes; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.Binding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.FieldBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.LocalTypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.MethodBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ParameterizedTypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.RawTypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.Scope; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeVariableBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.WildcardBinding; import org.aspectj.weaver.BoundedReferenceType; import org.aspectj.weaver.ConcreteTypeMunger; import org.aspectj.weaver.IHasPosition; import org.aspectj.weaver.Member; import org.aspectj.weaver.ReferenceType; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedMemberImpl; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.TypeFactory; import org.aspectj.weaver.TypeVariable; import org.aspectj.weaver.TypeVariableDeclaringElement; import org.aspectj.weaver.TypeVariableReference; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.UnresolvedTypeVariableReferenceType; import org.aspectj.weaver.World; /** * @author Jim Hugunin */ public class EclipseFactory { public static boolean DEBUG = false; private AjBuildManager buildManager; private LookupEnvironment lookupEnvironment; private boolean xSerializableAspects; private World world; private Map/*UnresolvedType, TypeBinding*/ typexToBinding = new HashMap(); //XXX currently unused // private Map/*TypeBinding, ResolvedType*/ bindingToResolvedTypeX = new HashMap(); public static EclipseFactory fromLookupEnvironment(LookupEnvironment env) { AjLookupEnvironment aenv = (AjLookupEnvironment)env; return aenv.factory; } public static EclipseFactory fromScopeLookupEnvironment(Scope scope) { return fromLookupEnvironment(AstUtil.getCompilationUnitScope(scope).environment); } public EclipseFactory(LookupEnvironment lookupEnvironment,AjBuildManager buildManager) { this.lookupEnvironment = lookupEnvironment; this.buildManager = buildManager; this.world = buildManager.getWorld(); this.xSerializableAspects = buildManager.buildConfig.isXserializableAspects(); } public EclipseFactory(LookupEnvironment lookupEnvironment, World world, boolean xSer) { this.lookupEnvironment = lookupEnvironment; this.world = world; this.xSerializableAspects = xSer; this.buildManager = null; } public World getWorld() { return world; } public void showMessage( Kind kind, String message, ISourceLocation loc1, ISourceLocation loc2) { getWorld().showMessage(kind, message, loc1, loc2); } public ResolvedType fromEclipse(ReferenceBinding binding) { if (binding == null) return ResolvedType.MISSING; //??? this seems terribly inefficient //System.err.println("resolving: " + binding.getClass() + ", name = " + getName(binding)); ResolvedType ret = getWorld().resolve(fromBinding(binding)); //System.err.println(" got: " + ret); return ret; } public ResolvedType fromTypeBindingToRTX(TypeBinding tb) { if (tb == null) return ResolvedType.MISSING; ResolvedType ret = getWorld().resolve(fromBinding(tb)); return ret; } public ResolvedType[] fromEclipse(ReferenceBinding[] bindings) { if (bindings == null) { return ResolvedType.NONE; } int len = bindings.length; ResolvedType[] ret = new ResolvedType[len]; for (int i=0; i < len; i++) { ret[i] = fromEclipse(bindings[i]); } return ret; } public static String getName(TypeBinding binding) { if (binding instanceof TypeVariableBinding) { // The first bound may be null - so default to object? TypeVariableBinding tvb = (TypeVariableBinding)binding; if (tvb.firstBound!=null) { return getName(tvb.firstBound); } else { return getName(tvb.superclass); } } if (binding instanceof ReferenceBinding) { return new String( CharOperation.concatWith(((ReferenceBinding)binding).compoundName, '.')); } String packageName = new String(binding.qualifiedPackageName()); String className = new String(binding.qualifiedSourceName()).replace('.', '$'); if (packageName.length() > 0) { className = packageName + "." + className; } //XXX doesn't handle arrays correctly (or primitives?) return new String(className); } /** * Some generics notes: * * Andy 6-May-05 * We were having trouble with parameterized types in a couple of places - due to TypeVariableBindings. When we * see a TypeVariableBinding now we default to either the firstBound if it is specified or java.lang.Object. Not * sure when/if this gets us unstuck? It does mean we forget that it is a type variable when going back * the other way from the UnresolvedType and that would seem a bad thing - but I've yet to see the reason we need to * remember the type variable. * Adrian 10-July-05 * When we forget it's a type variable we come unstuck when getting the declared members of a parameterized * type - since we don't know it's a type variable we can't replace it with the type parameter. */ //??? going back and forth between strings and bindings is a waste of cycles public UnresolvedType fromBinding(TypeBinding binding) { if (binding instanceof HelperInterfaceBinding) { return ((HelperInterfaceBinding) binding).getTypeX(); } if (binding == null || binding.qualifiedSourceName() == null) { return ResolvedType.MISSING; } // first piece of generics support! if (binding instanceof TypeVariableBinding) { return fromTypeVariableBinding((TypeVariableBinding)binding); } if (binding instanceof WildcardBinding) { WildcardBinding eWB = (WildcardBinding) binding; UnresolvedType ut = TypeFactory.createTypeFromSignature(CharOperation.charToString(eWB.genericTypeSignature())); // If the bound for the wildcard is a typevariable, e.g. '? extends E' then // the type variable in the unresolvedtype will be correct only in name. In that // case let's set it correctly based on the one in the eclipse WildcardBinding if (eWB.bound instanceof TypeVariableBinding) { UnresolvedType tVar = fromTypeVariableBinding((TypeVariableBinding)eWB.bound); if (ut.isGenericWildcard() && ut.isSuper()) ut.setLowerBound(tVar); if (ut.isGenericWildcard() && ut.isExtends()) ut.setUpperBound(tVar); } return ut; } if (binding instanceof ParameterizedTypeBinding) { if (binding instanceof RawTypeBinding) { // special case where no parameters are specified! return UnresolvedType.forRawTypeName(getName(binding)); } ParameterizedTypeBinding ptb = (ParameterizedTypeBinding) binding; UnresolvedType[] arguments = null; if (ptb.arguments!=null) { // null can mean this is an inner type of a Parameterized Type with no bounds of its own (pr100227) arguments = new UnresolvedType[ptb.arguments.length]; for (int i = 0; i < arguments.length; i++) { arguments[i] = fromBinding(ptb.arguments[i]); } } String baseTypeSignature = null; ResolvedType baseType = getWorld().resolve(UnresolvedType.forName(getName(binding)),true); if (baseType != ResolvedType.MISSING) { // can legitimately be missing if a bound refers to a type we haven't added to the world yet... if (!baseType.isGenericType() && arguments!=null) baseType = baseType.getGenericType(); baseTypeSignature = baseType.getErasureSignature(); } else { baseTypeSignature = UnresolvedType.forName(getName(binding)).getSignature(); } // Create an unresolved parameterized type. We can't create a resolved one as the // act of resolution here may cause recursion problems since the parameters may // be type variables that we haven't fixed up yet. if (arguments==null) arguments=new UnresolvedType[0]; String parameterizedSig = ResolvedType.PARAMETERIZED_TYPE_IDENTIFIER+CharOperation.charToString(binding.genericTypeSignature()).substring(1); return TypeFactory.createUnresolvedParameterizedType(parameterizedSig,baseTypeSignature,arguments); } // Convert the source type binding for a generic type into a generic UnresolvedType // notice we can easily determine the type variables from the eclipse object // and we can recover the generic signature from it too - so we pass those // to the forGenericType() method. if (binding.isGenericType() && !binding.isParameterizedType() && !binding.isRawType()) { TypeVariableBinding[] tvbs = binding.typeVariables(); TypeVariable[] tVars = new TypeVariable[tvbs.length]; for (int i = 0; i < tvbs.length; i++) { TypeVariableBinding eclipseV = tvbs[i]; String name = CharOperation.charToString(eclipseV.sourceName); tVars[i] = new TypeVariable(name,fromBinding(eclipseV.superclass()),fromBindings(eclipseV.superInterfaces())); } //TODO asc generics - temporary guard.... if (!(binding instanceof SourceTypeBinding)) throw new RuntimeException("Cant get the generic sig for "+binding.debugName()); return UnresolvedType.forGenericType(getName(binding),tVars, CharOperation.charToString(((SourceTypeBinding)binding).genericSignature())); } // LocalTypeBinding have a name $Local$, we can get the real name by using the signature.... if (binding instanceof LocalTypeBinding) { LocalTypeBinding ltb = (LocalTypeBinding) binding; if (ltb.constantPoolName() != null && ltb.constantPoolName().length > 0) { return UnresolvedType.forSignature(new String(binding.signature())); } else { // we're reporting a problem and don't have a resolved name for an // anonymous local type yet, report the issue on the enclosing type return UnresolvedType.forSignature(new String(ltb.enclosingType.signature())); } } return UnresolvedType.forName(getName(binding)); } /** * Some type variables refer to themselves recursively, this enables us to avoid * recursion problems. */ private static Map typeVariableBindingsInProgress = new HashMap(); /** * Convert from the eclipse form of type variable (TypeVariableBinding) to the AspectJ * form (TypeVariable). */ private UnresolvedType fromTypeVariableBinding(TypeVariableBinding aTypeVariableBinding) { // first, check for recursive call to this method for the same tvBinding if (typeVariableBindingsInProgress.containsKey(aTypeVariableBinding)) { return (UnresolvedType) typeVariableBindingsInProgress.get(aTypeVariableBinding); } if (typeVariablesForThisMember.containsKey(new String(aTypeVariableBinding.sourceName))) { return (UnresolvedType)typeVariablesForThisMember.get(new String(aTypeVariableBinding.sourceName)); } // Create the UnresolvedTypeVariableReferenceType for the type variable String name = CharOperation.charToString(aTypeVariableBinding.sourceName()); UnresolvedTypeVariableReferenceType ret = new UnresolvedTypeVariableReferenceType(); typeVariableBindingsInProgress.put(aTypeVariableBinding,ret); // Dont set any bounds here, you'll get in a recursive mess // TODO -- what about lower bounds?? UnresolvedType superclassType = fromBinding(aTypeVariableBinding.superclass()); UnresolvedType[] superinterfaces = new UnresolvedType[aTypeVariableBinding.superInterfaces.length]; for (int i = 0; i < superinterfaces.length; i++) { superinterfaces[i] = fromBinding(aTypeVariableBinding.superInterfaces[i]); } TypeVariable tv = new TypeVariable(name,superclassType,superinterfaces); tv.setUpperBound(superclassType); tv.setAdditionalInterfaceBounds(superinterfaces); tv.setRank(aTypeVariableBinding.rank); if (aTypeVariableBinding.declaringElement instanceof MethodBinding) { tv.setDeclaringElementKind(TypeVariable.METHOD); // tv.setDeclaringElement(fromBinding((MethodBinding)aTypeVariableBinding.declaringElement); } else { tv.setDeclaringElementKind(TypeVariable.TYPE); // // tv.setDeclaringElement(fromBinding(aTypeVariableBinding.declaringElement)); } ret.setTypeVariable(tv); if (aTypeVariableBinding.declaringElement instanceof MethodBinding) typeVariablesForThisMember.put(new String(aTypeVariableBinding.sourceName),ret); typeVariableBindingsInProgress.remove(aTypeVariableBinding); return ret; } public UnresolvedType[] fromBindings(TypeBinding[] bindings) { if (bindings == null) return UnresolvedType.NONE; int len = bindings.length; UnresolvedType[] ret = new UnresolvedType[len]; for (int i=0; i<len; i++) { ret[i] = fromBinding(bindings[i]); } return ret; } public static ASTNode astForLocation(IHasPosition location) { return new EmptyStatement(location.getStart(), location.getEnd()); } public Collection getDeclareParents() { return getWorld().getDeclareParents(); } public Collection getDeclareAnnotationOnTypes() { return getWorld().getDeclareAnnotationOnTypes(); } public Collection getDeclareAnnotationOnFields() { return getWorld().getDeclareAnnotationOnFields(); } public Collection getDeclareAnnotationOnMethods() { return getWorld().getDeclareAnnotationOnMethods(); } public Collection finishedTypeMungers = null; public boolean areTypeMungersFinished() { return finishedTypeMungers != null; } public void finishTypeMungers() { // make sure that type mungers are Collection ret = new ArrayList(); Collection baseTypeMungers = getWorld().getCrosscuttingMembersSet().getTypeMungers(); baseTypeMungers.addAll(getWorld().getCrosscuttingMembersSet().getLateTypeMungers()); for (Iterator i = baseTypeMungers.iterator(); i.hasNext(); ) { ConcreteTypeMunger munger = (ConcreteTypeMunger) i.next(); EclipseTypeMunger etm = makeEclipseTypeMunger(munger); if (etm != null) ret.add(etm); } finishedTypeMungers = ret; } public EclipseTypeMunger makeEclipseTypeMunger(ConcreteTypeMunger concrete) { //System.err.println("make munger: " + concrete); //!!! can't do this if we want incremental to work right //if (concrete instanceof EclipseTypeMunger) return (EclipseTypeMunger)concrete; //System.err.println(" was not eclipse"); if (concrete.getMunger() != null && EclipseTypeMunger.supportsKind(concrete.getMunger().getKind())) { AbstractMethodDeclaration method = null; if (concrete instanceof EclipseTypeMunger) { method = ((EclipseTypeMunger)concrete).getSourceMethod(); } EclipseTypeMunger ret = new EclipseTypeMunger(this, concrete.getMunger(), concrete.getAspectType(), method); if (ret.getSourceLocation() == null) { ret.setSourceLocation(concrete.getSourceLocation()); } return ret; } else { return null; } } public Collection getTypeMungers() { //??? assert finishedTypeMungers != null return finishedTypeMungers; } public ResolvedMember makeResolvedMember(MethodBinding binding) { return makeResolvedMember(binding, binding.declaringClass); } /** * Conversion from a methodbinding (eclipse) to a resolvedmember (aspectj) is now done * in the scope of some type variables. Before converting the parts of a methodbinding * (params, return type) we store the type variables in this structure, then should any * component of the method binding refer to them, we grab them from the map. */ // FIXME asc convert to array, indexed by rank private Map typeVariablesForThisMember = new HashMap(); public ResolvedMember makeResolvedMember(MethodBinding binding, TypeBinding declaringType) { //System.err.println("member for: " + binding + ", " + new String(binding.declaringClass.sourceName)); // Convert the type variables and store them UnresolvedType[] ajTypeRefs = null; typeVariablesForThisMember.clear(); // This is the set of type variables available whilst building the resolved member... if (binding.typeVariables!=null) { ajTypeRefs = new UnresolvedType[binding.typeVariables.length]; for (int i = 0; i < binding.typeVariables.length; i++) { ajTypeRefs[i] = fromBinding(binding.typeVariables[i]); typeVariablesForThisMember.put(new String(binding.typeVariables[i].sourceName),/*new Integer(binding.typeVariables[i].rank),*/ajTypeRefs[i]); } } // AMC these next two lines shouldn't be needed once we sort out generic types properly in the world map ResolvedType realDeclaringType = world.resolve(fromBinding(declaringType)); if (realDeclaringType.isRawType()) realDeclaringType = realDeclaringType.getGenericType(); ResolvedMember ret = new ResolvedMemberImpl( binding.isConstructor() ? Member.CONSTRUCTOR : Member.METHOD, realDeclaringType, binding.modifiers, fromBinding(binding.returnType), new String(binding.selector), fromBindings(binding.parameters), fromBindings(binding.thrownExceptions) ); if (typeVariablesForThisMember.size()!=0) { UnresolvedType[] tvars = new UnresolvedType[typeVariablesForThisMember.size()]; int i =0; for (Iterator iter = typeVariablesForThisMember.values().iterator(); iter.hasNext();) { tvars[i++] = (UnresolvedType)iter.next(); } ret.setTypeVariables(tvars); } typeVariablesForThisMember.clear(); ret.resolve(world); return ret; } public ResolvedMember makeResolvedMember(FieldBinding binding) { return makeResolvedMember(binding, binding.declaringClass); } public ResolvedMember makeResolvedMember(FieldBinding binding, TypeBinding receiverType) { // AMC these next two lines shouldn't be needed once we sort out generic types properly in the world map ResolvedType realDeclaringType = world.resolve(fromBinding(receiverType)); if (realDeclaringType.isRawType()) realDeclaringType = realDeclaringType.getGenericType(); return new ResolvedMemberImpl( Member.FIELD, realDeclaringType, binding.modifiers, world.resolve(fromBinding(binding.type)), new String(binding.name), UnresolvedType.NONE); } public TypeBinding makeTypeBinding(UnresolvedType typeX) { TypeBinding ret = null; // looking up type variables can get us into trouble if (!typeX.isTypeVariableReference()) ret = (TypeBinding)typexToBinding.get(typeX); if (ret == null) { ret = makeTypeBinding1(typeX); // FIXME asc keep type variables *out* of the map for now, they go in typeVariableToTypeBinding if (!(typeX instanceof BoundedReferenceType) && !(typeX instanceof UnresolvedTypeVariableReferenceType)) typexToBinding.put(typeX, ret); } if (ret == null) { System.out.println("can't find: " + typeX); } return ret; } private TypeBinding makeTypeBinding1(UnresolvedType typeX) { if (typeX.isPrimitiveType()) { if (typeX == ResolvedType.BOOLEAN) return BaseTypes.BooleanBinding; if (typeX == ResolvedType.BYTE) return BaseTypes.ByteBinding; if (typeX == ResolvedType.CHAR) return BaseTypes.CharBinding; if (typeX == ResolvedType.DOUBLE) return BaseTypes.DoubleBinding; if (typeX == ResolvedType.FLOAT) return BaseTypes.FloatBinding; if (typeX == ResolvedType.INT) return BaseTypes.IntBinding; if (typeX == ResolvedType.LONG) return BaseTypes.LongBinding; if (typeX == ResolvedType.SHORT) return BaseTypes.ShortBinding; if (typeX == ResolvedType.VOID) return BaseTypes.VoidBinding; throw new RuntimeException("weird primitive type " + typeX); } else if (typeX.isArray()) { int dim = 0; while (typeX.isArray()) { dim++; typeX = typeX.getComponentType(); } return lookupEnvironment.createArrayType(makeTypeBinding(typeX), dim); } else if (typeX.isParameterizedType()) { // Converting back to a binding from a UnresolvedType UnresolvedType[] typeParameters = typeX.getTypeParameters(); ReferenceBinding baseTypeBinding = lookupBinding(typeX.getBaseName()); TypeBinding[] argumentBindings = new TypeBinding[typeParameters.length]; for (int i = 0; i < argumentBindings.length; i++) { argumentBindings[i] = makeTypeBinding(typeParameters[i]); } ParameterizedTypeBinding ptb = lookupEnvironment.createParameterizedType(baseTypeBinding,argumentBindings,baseTypeBinding.enclosingType()); return ptb; } else if (typeX.isTypeVariableReference()) { return makeTypeVariableBinding((TypeVariableReference)typeX); } else if (typeX.isRawType()) { ReferenceBinding baseTypeBinding = lookupBinding(typeX.getBaseName()); RawTypeBinding rtb = lookupEnvironment.createRawType(baseTypeBinding,baseTypeBinding.enclosingType()); return rtb; } else if (typeX.isGenericWildcard()) { // translate from boundedreferencetype to WildcardBinding BoundedReferenceType brt = (BoundedReferenceType)typeX; // Work out 'kind' for the WildcardBinding int boundkind = Wildcard.UNBOUND; TypeBinding bound = null; if (brt.isExtends()) { boundkind = Wildcard.EXTENDS; bound = makeTypeBinding(brt.getUpperBound()); } else if (brt.isSuper()) { boundkind = Wildcard.SUPER; bound = makeTypeBinding(brt.getLowerBound()); } TypeBinding[] otherBounds = null; if (brt.getAdditionalBounds()!=null && brt.getAdditionalBounds().length!=0) otherBounds = makeTypeBindings(brt.getAdditionalBounds()); // FIXME asc rank should not always be 0 ... WildcardBinding wb = lookupEnvironment.createWildcard(null,0,bound,otherBounds,boundkind); return wb; } else { return lookupBinding(typeX.getName()); } } private ReferenceBinding lookupBinding(String sname) { char[][] name = CharOperation.splitOn('.', sname.toCharArray()); ReferenceBinding rb = lookupEnvironment.getType(name); // XXX We do this because the pertypewithin aspectOf(Class) generated method needs it. Without this // we don't get a 'rawtype' as the argument type for a messagesend to aspectOf() and this leads to // a compile error if some client class calls aspectOf(A.class) or similar as it says Class<A> isn't // compatible with Class<T> if (sname.equals("java.lang.Class")) rb = lookupEnvironment.createRawType(rb,rb.enclosingType()); return rb; } public TypeBinding[] makeTypeBindings(UnresolvedType[] types) { int len = types.length; TypeBinding[] ret = new TypeBinding[len]; for (int i = 0; i < len; i++) { ret[i] = makeTypeBinding(types[i]); } return ret; } // just like the code above except it returns an array of ReferenceBindings private ReferenceBinding[] makeReferenceBindings(UnresolvedType[] types) { int len = types.length; ReferenceBinding[] ret = new ReferenceBinding[len]; for (int i = 0; i < len; i++) { ret[i] = (ReferenceBinding)makeTypeBinding(types[i]); } return ret; } public FieldBinding makeFieldBinding(ResolvedMember member) { currentType = (ReferenceBinding)makeTypeBinding(member.getDeclaringType()); FieldBinding fb = new FieldBinding(member.getName().toCharArray(), makeTypeBinding(member.getReturnType()), member.getModifiers(), currentType, Constant.NotAConstant); currentType = null; return fb; } private ReferenceBinding currentType = null; public MethodBinding makeMethodBinding(ResolvedMember member) { typeVariableToTypeBinding.clear(); TypeVariableBinding[] tvbs = null; if (member.getTypeVariables()!=null) { if (member.getTypeVariables().length==0) { tvbs = MethodBinding.NoTypeVariables; } else { tvbs = makeTypeVariableBindings(member.getTypeVariables()); // fixup the declaring element, we couldn't do it whilst processing the typevariables as we'll end up in recursion. for (int i = 0; i < tvbs.length; i++) { TypeVariableBinding binding = tvbs[i]; // if (binding.declaringElement==null && ((TypeVariableReference)member.getTypeVariables()[i]).getTypeVariable().getDeclaringElement() instanceof Member) { // tvbs[i].declaringElement = mb; // } else { // tvbs[i].declaringElement = declaringType; // } } } } ReferenceBinding declaringType = (ReferenceBinding)makeTypeBinding(member.getDeclaringType()); currentType = declaringType; MethodBinding mb = new MethodBinding(member.getModifiers(), member.getName().toCharArray(), makeTypeBinding(member.getReturnType()), makeTypeBindings(member.getParameterTypes()), makeReferenceBindings(member.getExceptions()), declaringType); if (tvbs!=null) mb.typeVariables = tvbs; typeVariableToTypeBinding.clear(); currentType = null; return mb; } /** * Convert a bunch of type variables in one go, from AspectJ form to Eclipse form. */ private TypeVariableBinding[] makeTypeVariableBindings(UnresolvedType[] typeVariables) { int len = typeVariables.length; TypeVariableBinding[] ret = new TypeVariableBinding[len]; for (int i = 0; i < len; i++) { ret[i] = makeTypeVariableBinding((TypeVariableReference)typeVariables[i]); } return ret; } // only accessed through private methods in this class. Ensures all type variables we encounter // map back to the same type binding - this is important later when Eclipse code is processing // a methodbinding trying to come up with possible bindings for the type variables. // key is currently the name of the type variable...is that ok? private Map typeVariableToTypeBinding = new HashMap(); /** * Converts from an TypeVariableReference to a TypeVariableBinding. A TypeVariableReference * in AspectJ world holds a TypeVariable and it is this type variable that is converted * to the TypeVariableBinding. */ private TypeVariableBinding makeTypeVariableBinding(TypeVariableReference tvReference) { TypeVariable tVar = tvReference.getTypeVariable(); TypeVariableBinding tvBinding = (TypeVariableBinding)typeVariableToTypeBinding.get(tVar.getName()); if (currentType!=null) { TypeVariableBinding tvb = currentType.getTypeVariable(tVar.getName().toCharArray()); if (tvb!=null) return tvb; } if (tvBinding==null) { Binding declaringElement = null; // this will cause an infinite loop or NPE... not required yet luckily. // if (tVar.getDeclaringElement() instanceof Member) { // declaringElement = makeMethodBinding((ResolvedMember)tVar.getDeclaringElement()); // } else { // declaringElement = makeTypeBinding((UnresolvedType)tVar.getDeclaringElement()); // } tvBinding = new TypeVariableBinding(tVar.getName().toCharArray(),declaringElement,tVar.getRank()); typeVariableToTypeBinding.put(tVar.getName(),tvBinding); tvBinding.superclass=(ReferenceBinding)makeTypeBinding(tVar.getUpperBound()); tvBinding.firstBound=tvBinding.superclass; // FIXME asc is this correct? possibly it could be first superinterface if (tVar.getAdditionalInterfaceBounds()==null) { tvBinding.superInterfaces=TypeVariableBinding.NoSuperInterfaces; } else { TypeBinding tbs[] = makeTypeBindings(tVar.getAdditionalInterfaceBounds()); ReferenceBinding[] rbs= new ReferenceBinding[tbs.length]; for (int i = 0; i < tbs.length; i++) { rbs[i] = (ReferenceBinding)tbs[i]; } tvBinding.superInterfaces=rbs; } } return tvBinding; } public MethodBinding makeMethodBindingForCall(Member member) { return new MethodBinding(member.getCallsiteModifiers(), member.getName().toCharArray(), makeTypeBinding(member.getReturnType()), makeTypeBindings(member.getParameterTypes()), new ReferenceBinding[0], (ReferenceBinding)makeTypeBinding(member.getDeclaringType())); } public void finishedCompilationUnit(CompilationUnitDeclaration unit) { if ((buildManager != null) && buildManager.doGenerateModel()) { AjBuildManager.getAsmHierarchyBuilder().buildStructureForCompilationUnit(unit, buildManager.getStructureModel(), buildManager.buildConfig); } } public void addTypeBinding(TypeBinding binding) { typexToBinding.put(fromBinding(binding), binding); } public Shadow makeShadow(ASTNode location, ReferenceContext context) { return EclipseShadow.makeShadow(this, location, context); } public Shadow makeShadow(ReferenceContext context) { return EclipseShadow.makeShadow(this, (ASTNode) context, context); } public void addSourceTypeBinding(SourceTypeBinding binding) { TypeDeclaration decl = binding.scope.referenceContext; // Deal with the raw/basic type to give us an entry in the world type map UnresolvedType simpleTx = null; if (binding.isGenericType()) { simpleTx = UnresolvedType.forRawTypeName(getName(binding)); } else if (binding.isLocalType()) { LocalTypeBinding ltb = (LocalTypeBinding) binding; if (ltb.constantPoolName() != null && ltb.constantPoolName().length > 0) { simpleTx = UnresolvedType.forSignature(new String(binding.signature())); } else { simpleTx = UnresolvedType.forName(getName(binding)); } }else { simpleTx = UnresolvedType.forName(getName(binding)); } ReferenceType name = getWorld().lookupOrCreateName(simpleTx); EclipseSourceType t = new EclipseSourceType(name, this, binding, decl); // For generics, go a bit further - build a typex for the generic type // give it the same delegate and link it to the raw type if (binding.isGenericType()) { UnresolvedType complexTx = fromBinding(binding); // fully aware of any generics info ReferenceType complexName = new ReferenceType(complexTx,world);//getWorld().lookupOrCreateName(complexTx); name.setGenericType(complexName); complexName.setDelegate(t); complexName.setSourceContext(t.getResolvedTypeX().getSourceContext()); } name.setDelegate(t); if (decl instanceof AspectDeclaration) { ((AspectDeclaration)decl).typeX = name; ((AspectDeclaration)decl).concreteName = t; } ReferenceBinding[] memberTypes = binding.memberTypes; for (int i = 0, length = memberTypes.length; i < length; i++) { addSourceTypeBinding((SourceTypeBinding) memberTypes[i]); } } // XXX this doesn't feel like it belongs here, but it breaks a hard dependency on // exposing AjBuildManager (needed by AspectDeclaration). public boolean isXSerializableAspects() { return xSerializableAspects; } public ResolvedMember fromBinding(MethodBinding binding) { return new ResolvedMemberImpl(Member.METHOD,fromBinding(binding.declaringClass),binding.modifiers, fromBinding(binding.returnType),CharOperation.charToString(binding.selector),fromBindings(binding.parameters)); } public TypeVariableDeclaringElement fromBinding(Binding declaringElement) { if (declaringElement instanceof TypeBinding) { return fromBinding(((TypeBinding)declaringElement)); } else { return fromBinding((MethodBinding)declaringElement); } } }
108,886
Bug 108886 Getting Exception during compilation : java.lang.RuntimeException: Internal Compiler Error: Unexpected null source location passed as 'see also' location.
Am attaching a small test case to reproduce the error (Not sure how to attach it - hopefully should be feasible to do so after I log the bug).
resolved fixed
2d21db0
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-08T16:57:15Z
2005-09-06T23:40:00Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/EclipseSourceType.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * Alexandre Vasseur support for @AJ perClause * ******************************************************************/ package org.aspectj.ajdt.internal.compiler.lookup; import java.util.*; import org.aspectj.ajdt.internal.compiler.ast.*; import org.aspectj.ajdt.internal.core.builder.EclipseSourceContext; import org.aspectj.bridge.IMessage; //import org.aspectj.bridge.ISourceLocation; import org.aspectj.weaver.*; import org.aspectj.weaver.patterns.PerClause; import org.aspectj.weaver.patterns.PerSingleton; import org.aspectj.weaver.patterns.PerFromSuper; import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Annotation; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.SingleMemberAnnotation; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.StringLiteral; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeParameter; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.*; /** * Supports viewing eclipse TypeDeclarations/SourceTypeBindings as a ResolvedType * * @author Jim Hugunin */ public class EclipseSourceType extends AbstractReferenceTypeDelegate { private static final char[] pointcutSig = "Lorg/aspectj/lang/annotation/Pointcut;".toCharArray(); private static final char[] aspectSig = "Lorg/aspectj/lang/annotation/Aspect;".toCharArray(); protected ResolvedPointcutDefinition[] declaredPointcuts = null; protected ResolvedMember[] declaredMethods = null; protected ResolvedMember[] declaredFields = null; public List declares = new ArrayList(); public List typeMungers = new ArrayList(); private EclipseFactory factory; private SourceTypeBinding binding; private TypeDeclaration declaration; private boolean annotationsResolved = false; private ResolvedType[] resolvedAnnotations = null; protected EclipseFactory eclipseWorld() { return factory; } public EclipseSourceType(ReferenceType resolvedTypeX, EclipseFactory factory, SourceTypeBinding binding, TypeDeclaration declaration) { super(resolvedTypeX, true); this.factory = factory; this.binding = binding; this.declaration = declaration; resolvedTypeX.setSourceContext(new EclipseSourceContext(declaration.compilationResult)); resolvedTypeX.setStartPos(declaration.sourceStart); resolvedTypeX.setEndPos(declaration.sourceEnd); } public boolean isAspect() { final boolean isCodeStyle = declaration instanceof AspectDeclaration; return isCodeStyle?isCodeStyle:isAnnotationStyleAspect(); } public boolean isAnnotationStyleAspect() { if (declaration.annotations == null) { return false; } ResolvedType[] annotations = getAnnotationTypes(); for (int i = 0; i < annotations.length; i++) { if ("org.aspectj.lang.annotation.Aspect".equals(annotations[i].getName())) { return true; } } return false; } private boolean isAnnotationStylePointcut(Annotation[] annotations) { if (annotations == null) return false; for (int i = 0; i < annotations.length; i++) { if (annotations[i].resolvedType == null) continue; // XXX happens if we do this very early from buildInterTypeandPerClause // may prevent us from resolving references made in @Pointcuts to // an @Pointcut in a code-style aspect char[] sig = annotations[i].resolvedType.signature(); if (CharOperation.equals(pointcutSig,sig)) { return true; } } return false; } public WeaverStateInfo getWeaverState() { return null; } public ResolvedType getSuperclass() { if (binding.isInterface()) return getResolvedTypeX().getWorld().getCoreType(UnresolvedType.OBJECT); //XXX what about java.lang.Object return eclipseWorld().fromEclipse(binding.superclass()); } public ResolvedType[] getDeclaredInterfaces() { return eclipseWorld().fromEclipse(binding.superInterfaces()); } protected void fillDeclaredMembers() { List declaredPointcuts = new ArrayList(); List declaredMethods = new ArrayList(); List declaredFields = new ArrayList(); binding.methods(); // the important side-effect of this call is to make sure bindings are completed AbstractMethodDeclaration[] methods = declaration.methods; if (methods != null) { for (int i=0, len=methods.length; i < len; i++) { AbstractMethodDeclaration amd = methods[i]; if (amd == null || amd.ignoreFurtherInvestigation) continue; if (amd instanceof PointcutDeclaration) { PointcutDeclaration d = (PointcutDeclaration)amd; ResolvedPointcutDefinition df = d.makeResolvedPointcutDefinition(factory); declaredPointcuts.add(df); } else if (amd instanceof InterTypeDeclaration) { // these are handled in a separate pass continue; } else if (amd instanceof DeclareDeclaration && !(amd instanceof DeclareAnnotationDeclaration)) { // surfaces the annotated ajc$ method // these are handled in a separate pass continue; } else if (amd instanceof AdviceDeclaration) { // these are ignored during compilation and only used during weaving continue; } else if ((amd.annotations != null) && isAnnotationStylePointcut(amd.annotations)) { // consider pointcuts defined via annotations ResolvedPointcutDefinition df = makeResolvedPointcutDefinition(amd); declaredPointcuts.add(df); } else { if (amd.binding == null || !amd.binding.isValidBinding()) continue; declaredMethods.add(factory.makeResolvedMember(amd.binding)); } } } FieldBinding[] fields = binding.fields(); for (int i=0, len=fields.length; i < len; i++) { FieldBinding f = fields[i]; declaredFields.add(factory.makeResolvedMember(f)); } this.declaredPointcuts = (ResolvedPointcutDefinition[]) declaredPointcuts.toArray(new ResolvedPointcutDefinition[declaredPointcuts.size()]); this.declaredMethods = (ResolvedMember[]) declaredMethods.toArray(new ResolvedMember[declaredMethods.size()]); this.declaredFields = (ResolvedMember[]) declaredFields.toArray(new ResolvedMember[declaredFields.size()]); } private ResolvedPointcutDefinition makeResolvedPointcutDefinition(AbstractMethodDeclaration md) { ResolvedPointcutDefinition resolvedPointcutDeclaration = new ResolvedPointcutDefinition( factory.fromBinding(md.binding.declaringClass), md.modifiers, new String(md.selector), factory.fromBindings(md.binding.parameters), null); //??? might want to use null resolvedPointcutDeclaration.setPosition(md.sourceStart, md.sourceEnd); resolvedPointcutDeclaration.setSourceContext(new EclipseSourceContext(md.compilationResult)); return resolvedPointcutDeclaration; } public ResolvedMember[] getDeclaredFields() { if (declaredFields == null) fillDeclaredMembers(); return declaredFields; } public ResolvedMember[] getDeclaredMethods() { if (declaredMethods == null) fillDeclaredMembers(); return declaredMethods; } public ResolvedMember[] getDeclaredPointcuts() { if (declaredPointcuts == null) fillDeclaredMembers(); return declaredPointcuts; } public int getModifiers() { // only return the real Java modifiers, not the extra eclipse ones return binding.modifiers & CompilerModifiers.AccJustFlag; } public String toString() { return "EclipseSourceType(" + new String(binding.sourceName()) + ")"; } //XXX make sure this is applied to classes and interfaces public void checkPointcutDeclarations() { ResolvedMember[] pointcuts = getDeclaredPointcuts(); boolean sawError = false; for (int i=0, len=pointcuts.length; i < len; i++) { if (pointcuts[i].isAbstract()) { if (!this.isAspect()) { eclipseWorld().showMessage(IMessage.ERROR, "abstract pointcut only allowed in aspect" + pointcuts[i].getName(), pointcuts[i].getSourceLocation(), null); sawError = true; } else if (!binding.isAbstract()) { eclipseWorld().showMessage(IMessage.ERROR, "abstract pointcut in concrete aspect" + pointcuts[i], pointcuts[i].getSourceLocation(), null); sawError = true; } } for (int j=i+1; j < len; j++) { if (pointcuts[i].getName().equals(pointcuts[j].getName())) { eclipseWorld().showMessage(IMessage.ERROR, "duplicate pointcut name: " + pointcuts[j].getName(), pointcuts[i].getSourceLocation(), pointcuts[j].getSourceLocation()); sawError = true; } } } //now check all inherited pointcuts to be sure that they're handled reasonably if (sawError || !isAspect()) return; // find all pointcuts that override ones from super and check override is legal // i.e. same signatures and greater or equal visibility // find all inherited abstract pointcuts and make sure they're concretized if I'm concrete // find all inherited pointcuts and make sure they don't conflict getResolvedTypeX().getExposedPointcuts(); //??? this is an odd construction } //??? // public CrosscuttingMembers collectCrosscuttingMembers() { // return crosscuttingMembers; // } // public ISourceLocation getSourceLocation() { // TypeDeclaration dec = binding.scope.referenceContext; // return new EclipseSourceLocation(dec.compilationResult, dec.sourceStart, dec.sourceEnd); // } public boolean isInterface() { return binding.isInterface(); } // XXXAJ5: Should be constants in the eclipse compiler somewhere, once it supports 1.5 public final static short ACC_ANNOTATION = 0x2000; public final static short ACC_ENUM = 0x4000; public boolean isEnum() { return (binding.getAccessFlags() & ACC_ENUM)!=0; } public boolean isAnnotation() { return (binding.getAccessFlags() & ACC_ANNOTATION)!=0; } public void addAnnotation(AnnotationX annotationX) { // XXX Big hole here - annotationX holds a BCEL annotation but // we need an Eclipse one here, we haven't written the conversion utils // yet. Not sure if this method will be called in practice... throw new RuntimeException("EclipseSourceType.addAnnotation() not implemented"); } public boolean isAnnotationWithRuntimeRetention() { if (!isAnnotation()) { return false; } else { return (binding.getAnnotationTagBits() & TagBits.AnnotationRetentionMASK) == TagBits.AnnotationRuntimeRetention; } } public boolean hasAnnotation(UnresolvedType ofType) { // Make sure they are resolved if (!annotationsResolved) { TypeDeclaration.resolveAnnotations(declaration.staticInitializerScope, declaration.annotations, binding); annotationsResolved = true; } Annotation[] as = declaration.annotations; if (as == null) return false; for (int i = 0; i < as.length; i++) { Annotation annotation = as[i]; if (annotation.resolvedType == null) { // Something has gone wrong - probably we have a 1.4 rt.jar around // which will result in a separate error message. return false; } String tname = CharOperation.charToString(annotation.resolvedType.constantPoolName()); if (UnresolvedType.forName(tname).equals(ofType)) { return true; } } return false; } public AnnotationX[] getAnnotations() { throw new RuntimeException("Missing implementation"); } public ResolvedType[] getAnnotationTypes() { if (resolvedAnnotations!=null) return resolvedAnnotations; // Make sure they are resolved if (!annotationsResolved) { TypeDeclaration.resolveAnnotations(declaration.staticInitializerScope, declaration.annotations, binding); annotationsResolved = true; } if (declaration.annotations == null) { resolvedAnnotations = new ResolvedType[0]; } else { resolvedAnnotations = new ResolvedType[declaration.annotations.length]; Annotation[] as = declaration.annotations; for (int i = 0; i < as.length; i++) { Annotation annotation = as[i]; resolvedAnnotations[i] =factory.fromTypeBindingToRTX(annotation.type.resolvedType); } } return resolvedAnnotations; } public PerClause getPerClause() { //should probably be: ((AspectDeclaration)declaration).perClause; // but we don't need this level of detail, and working with real per clauses // at this stage of compilation is not worth the trouble if (!isAnnotationStyleAspect()) { return new PerSingleton(); } else { // for @Aspect, we do need the real kind though we don't need the real perClause PerClause.Kind kind = getPerClauseForTypeDeclaration(declaration); //returning a perFromSuper is enough to get the correct kind.. (that's really a hack - AV) return new PerFromSuper(kind); } } PerClause.Kind getPerClauseForTypeDeclaration(TypeDeclaration typeDeclaration) { Annotation[] annotations = typeDeclaration.annotations; for (int i = 0; i < annotations.length; i++) { Annotation annotation = annotations[i]; if (CharOperation.equals(aspectSig, annotation.resolvedType.signature())) { // found @Aspect(...) if (annotation.memberValuePairs() == null || annotation.memberValuePairs().length == 0) { // it is an @Aspect or @Aspect() // needs to use PerFromSuper if declaration extends a super aspect PerClause.Kind kind = lookupPerClauseKind(typeDeclaration.binding.superclass); // if no super aspect, we have a @Aspect() means singleton if (kind == null) { return PerClause.SINGLETON; } else { return kind; } } else if (annotation instanceof SingleMemberAnnotation) { // it is an @Aspect(...something...) SingleMemberAnnotation theAnnotation = (SingleMemberAnnotation)annotation; String clause = new String(((StringLiteral)theAnnotation.memberValue).source());//TODO cast safe ? if (clause.startsWith("perthis(")) { return PerClause.PEROBJECT; } else if (clause.startsWith("pertarget(")) { return PerClause.PEROBJECT; } else if (clause.startsWith("percflow(")) { return PerClause.PERCFLOW; } else if (clause.startsWith("percflowbelow(")) { return PerClause.PERCFLOW; } else if (clause.startsWith("pertypewithin(")) { return PerClause.PERTYPEWITHIN; } else if (clause.startsWith("issingleton(")) { return PerClause.SINGLETON; } else { eclipseWorld().showMessage(IMessage.ABORT, "cannot determine perClause '" + clause + "'", new EclipseSourceLocation(typeDeclaration.compilationResult, typeDeclaration.sourceStart, typeDeclaration.sourceEnd), null); return PerClause.SINGLETON;//fallback strategy just to avoid NPE } } else { eclipseWorld().showMessage(IMessage.ABORT, "@Aspect annotation is expected to be SingleMemberAnnotation with 'String value()' as unique element", new EclipseSourceLocation(typeDeclaration.compilationResult, typeDeclaration.sourceStart, typeDeclaration.sourceEnd), null); return PerClause.SINGLETON;//fallback strategy just to avoid NPE } } } return null;//no @Aspect annotation at all (not as aspect) } // adapted from AspectDeclaration private PerClause.Kind lookupPerClauseKind(ReferenceBinding binding) { final PerClause.Kind kind; if (binding instanceof BinaryTypeBinding) { ResolvedType superTypeX = factory.fromEclipse(binding); PerClause perClause = superTypeX.getPerClause(); // clause is null for non aspect classes since coming from BCEL attributes if (perClause != null) { kind = superTypeX.getPerClause().getKind(); } else { kind = null; } } else if (binding instanceof SourceTypeBinding ) { SourceTypeBinding sourceSc = (SourceTypeBinding)binding; if (sourceSc.scope.referenceContext instanceof AspectDeclaration) { //code style kind = ((AspectDeclaration)sourceSc.scope.referenceContext).perClause.getKind(); } else if (sourceSc.scope.referenceContext instanceof TypeDeclaration) { // if @Aspect: perFromSuper, else if @Aspect(..) get from anno value, else null kind = getPerClauseForTypeDeclaration((TypeDeclaration)(sourceSc.scope.referenceContext)); } else { //XXX should not happen kind = null; } } else { //XXX need to handle this too kind = null; } return kind; } public Collection getDeclares() { return declares; } public Collection getPrivilegedAccesses() { return Collections.EMPTY_LIST; } public Collection getTypeMungers() { return typeMungers; } public boolean doesNotExposeShadowMungers() { return true; } public String getDeclaredGenericSignature() { return CharOperation.charToString(binding.genericSignature()); } public boolean isGeneric() { return binding.isGenericType(); } public TypeVariable[] getTypeVariables() { if (declaration.typeParameters == null) return new TypeVariable[0]; TypeVariable[] typeVariables = new TypeVariable[declaration.typeParameters.length]; for (int i = 0; i < typeVariables.length; i++) { typeVariables[i] = typeParameter2TypeVariable(declaration.typeParameters[i]); } return typeVariables; } private TypeVariable typeParameter2TypeVariable(TypeParameter aTypeParameter) { String name = new String(aTypeParameter.name); ReferenceBinding superclassBinding = aTypeParameter.binding.superclass; UnresolvedType superclass = UnresolvedType.forSignature(new String(superclassBinding.signature())); UnresolvedType[] superinterfaces = null; ReferenceBinding[] superInterfaceBindings = aTypeParameter.binding.superInterfaces; if (superInterfaceBindings != null) { superinterfaces = new UnresolvedType[superInterfaceBindings.length]; for (int i = 0; i < superInterfaceBindings.length; i++) { superinterfaces[i] = UnresolvedType.forSignature(new String(superInterfaceBindings[i].signature())); } } // XXX what about lower binding? TypeVariable tv = new TypeVariable(name,superclass,superinterfaces); tv.setDeclaringElement(factory.fromBinding(aTypeParameter.binding.declaringElement)); tv.setRank(aTypeParameter.binding.rank); return tv; } }
108,886
Bug 108886 Getting Exception during compilation : java.lang.RuntimeException: Internal Compiler Error: Unexpected null source location passed as 'see also' location.
Am attaching a small test case to reproduce the error (Not sure how to attach it - hopefully should be feasible to do so after I log the bug).
resolved fixed
2d21db0
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-08T16:57:15Z
2005-09-06T23:40:00Z
weaver/src/org/aspectj/weaver/ResolvedMemberImpl.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver; import java.io.DataOutputStream; import java.io.IOException; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.aspectj.bridge.ISourceLocation; /** * This is the declared member, i.e. it will always correspond to an * actual method/... declaration */ public class ResolvedMemberImpl extends MemberImpl implements IHasPosition, AnnotatedElement, TypeVariableDeclaringElement, ResolvedMember { public String[] parameterNames = null; protected UnresolvedType[] checkedExceptions = UnresolvedType.NONE; /** * if this member is a parameterized version of a member in a generic type, * then this field holds a reference to the member we parameterize. */ protected ResolvedMember backingGenericMember = null; protected Set annotationTypes = null; // Some members are 'created' to represent other things (for example ITDs). These // members have their annotations stored elsewhere, and this flag indicates that is // the case. It is up to the caller to work out where that is! // Once determined the caller may choose to stash the annotations in this member... private boolean isAnnotatedElsewhere = false; // this field is not serialized. private boolean isAjSynthetic = true; // generic methods have type variables private UnresolvedType[] typeVariables; // these three fields hold the source location of this member protected int start, end; protected ISourceContext sourceContext = null; //XXX deprecate this in favor of the constructor below public ResolvedMemberImpl( Kind kind, UnresolvedType declaringType, int modifiers, UnresolvedType returnType, String name, UnresolvedType[] parameterTypes) { super(kind, declaringType, modifiers, returnType, name, parameterTypes); } public ResolvedMemberImpl( Kind kind, UnresolvedType declaringType, int modifiers, UnresolvedType returnType, String name, UnresolvedType[] parameterTypes, UnresolvedType[] checkedExceptions) { super(kind, declaringType, modifiers, returnType, name, parameterTypes); this.checkedExceptions = checkedExceptions; } public ResolvedMemberImpl( Kind kind, UnresolvedType declaringType, int modifiers, UnresolvedType returnType, String name, UnresolvedType[] parameterTypes, UnresolvedType[] checkedExceptions, ResolvedMember backingGenericMember) { this(kind, declaringType, modifiers, returnType, name, parameterTypes,checkedExceptions); this.backingGenericMember = backingGenericMember; this.isAjSynthetic = backingGenericMember.isAjSynthetic(); } public ResolvedMemberImpl( Kind kind, UnresolvedType declaringType, int modifiers, String name, String signature) { super(kind, declaringType, modifiers, name, signature); } /** * Compute the full set of signatures for a member. This walks up the hierarchy * giving the ResolvedMember in each defining type in the hierarchy. A shadowMember * can be created with a target type (declaring type) that does not actually define * the member. This is ok as long as the member is inherited in the declaring type. * Each declaring type in the line to the actual declaring type is added as an additional * signature. For example: * * class A { void foo(); } * class B extends A {} * * shadowMember : void B.foo() * * gives { void B.foo(), void A.foo() } * @param joinPointSignature * @param inAWorld */ public static JoinPointSignature[] getJoinPointSignatures(Member joinPointSignature, World inAWorld) { // Walk up hierarchy creating one member for each type up to and including the // first defining type ResolvedType originalDeclaringType = joinPointSignature.getDeclaringType().resolve(inAWorld); ResolvedMemberImpl firstDefiningMember = (ResolvedMemberImpl) joinPointSignature.resolve(inAWorld); if (firstDefiningMember == null) { return new JoinPointSignature[0]; } // declaringType can be unresolved if we matched a synthetic member generated by Aj... // should be fixed elsewhere but add this resolve call on the end for now so that we can // focus on one problem at a time... ResolvedType firstDefiningType = firstDefiningMember.getDeclaringType().resolve(inAWorld); if (firstDefiningType != originalDeclaringType) { if (joinPointSignature.getKind() == Member.CONSTRUCTOR) { return new JoinPointSignature[0]; } // else if (shadowMember.isStatic()) { // return new ResolvedMember[] {firstDefiningMember}; // } } List declaringTypes = new ArrayList(); accumulateTypesInBetween(originalDeclaringType, firstDefiningType, declaringTypes); Set memberSignatures = new HashSet(); for (Iterator iter = declaringTypes.iterator(); iter.hasNext();) { ResolvedType declaringType = (ResolvedType) iter.next(); ResolvedMember member = firstDefiningMember.withSubstituteDeclaringType(declaringType); memberSignatures.add(member); } if (shouldWalkUpHierarchyFor(firstDefiningMember)) { // now walk up the hierarchy from the firstDefiningMember and include the signature for // every type between the firstDefiningMember and the root defining member. Iterator superTypeIterator = firstDefiningType.getDirectSupertypes(); List typesAlreadyVisited = new ArrayList(); accumulateMembersMatching(firstDefiningMember,superTypeIterator,typesAlreadyVisited,memberSignatures); } JoinPointSignature[] ret = new JoinPointSignature[memberSignatures.size()]; memberSignatures.toArray(ret); return ret; } private static boolean shouldWalkUpHierarchyFor(Member aMember) { if (aMember.getKind() == Member.CONSTRUCTOR) return false; if (aMember.getKind() == Member.FIELD) return false; if (aMember.isStatic()) return false; return true; } /** * Build a list containing every type between subtype and supertype, inclusively. */ private static void accumulateTypesInBetween(ResolvedType subType, ResolvedType superType, List types) { types.add(subType); if (subType == superType) { return; } else { for (Iterator iter = subType.getDirectSupertypes(); iter.hasNext();) { ResolvedType parent = (ResolvedType) iter.next(); if (superType.isAssignableFrom(parent)) { accumulateTypesInBetween(parent, superType,types); } } } } /** * We have a resolved member, possibly with type parameter references as parameters or return * type. We need to find all its ancestor members. When doing this, a type parameter matches * regardless of bounds (bounds can be narrowed down the hierarchy). */ private static void accumulateMembersMatching( ResolvedMemberImpl memberToMatch, Iterator typesToLookIn, List typesAlreadyVisited, Set foundMembers) { while(typesToLookIn.hasNext()) { ResolvedType toLookIn = (ResolvedType) typesToLookIn.next(); if (!typesAlreadyVisited.contains(toLookIn)) { typesAlreadyVisited.add(toLookIn); ResolvedMemberImpl foundMember = (ResolvedMemberImpl) toLookIn.lookupResolvedMember(memberToMatch); if (foundMember != null && isVisibleTo(memberToMatch,foundMember)) { List declaringTypes = new ArrayList(); // declaring type can be unresolved if the member can from an ITD... ResolvedType resolvedDeclaringType = foundMember.getDeclaringType().resolve(toLookIn.getWorld()); accumulateTypesInBetween(toLookIn, resolvedDeclaringType, declaringTypes); for (Iterator iter = declaringTypes.iterator(); iter.hasNext();) { ResolvedType declaringType = (ResolvedType) iter.next(); // typesAlreadyVisited.add(declaringType); ResolvedMember member = foundMember.withSubstituteDeclaringType(declaringType); foundMembers.add(member); } if (toLookIn.isParameterizedType() && (foundMember.backingGenericMember != null)) { foundMembers.add(new JoinPointSignature(foundMember.backingGenericMember,foundMember.declaringType.resolve(toLookIn.getWorld()))); } accumulateMembersMatching(foundMember,toLookIn.getDirectSupertypes(),typesAlreadyVisited,foundMembers); // if this was a parameterized type, look in the generic type that backs it too } } } } /** * Returns true if the parent member is visible to the child member * In the same declaring type this is always true, otherwise if parent is private * it is false. * @param childMember * @param parentMember * @return */ private static boolean isVisibleTo(ResolvedMember childMember, ResolvedMember parentMember) { if (childMember.getDeclaringType().equals(parentMember.getDeclaringType())) return true; if (Modifier.isPrivate(parentMember.getModifiers())) { return false; } else { return true; } } // ---- public final int getModifiers(World world) { return modifiers; } public final int getModifiers() { return modifiers; } // ---- public final UnresolvedType[] getExceptions(World world) { return getExceptions(); } public UnresolvedType[] getExceptions() { return checkedExceptions; } public ShadowMunger getAssociatedShadowMunger() { return null; } // ??? true or false? public boolean isAjSynthetic() { return isAjSynthetic; } public boolean hasAnnotations() { return (annotationTypes!=null); } public boolean hasAnnotation(UnresolvedType ofType) { // The ctors don't allow annotations to be specified ... yet - but // that doesn't mean it is an error to call this method. // Normally the weaver will be working with subtypes of // this type - BcelField/BcelMethod if (annotationTypes==null) return false; return annotationTypes.contains(ofType); } public ResolvedType[] getAnnotationTypes() { // The ctors don't allow annotations to be specified ... yet - but // that doesn't mean it is an error to call this method. // Normally the weaver will be working with subtypes of // this type - BcelField/BcelMethod if (annotationTypes == null) return null; return (ResolvedType[])annotationTypes.toArray(new ResolvedType[]{}); } public void setAnnotationTypes(UnresolvedType[] annotationtypes) { if (annotationTypes == null) annotationTypes = new HashSet(); for (int i = 0; i < annotationtypes.length; i++) { UnresolvedType typeX = annotationtypes[i]; annotationTypes.add(typeX); } } public void addAnnotation(AnnotationX annotation) { // FIXME asc only allows for annotation types, not instances - should it? if (annotationTypes == null) annotationTypes = new HashSet(); annotationTypes.add(annotation.getSignature()); } public boolean isBridgeMethod() { return (modifiers & Constants.ACC_BRIDGE)!=0; } public boolean isVarargsMethod() { return (modifiers & Constants.ACC_VARARGS)!=0; } public boolean isSynthetic() { return false; } public void write(DataOutputStream s) throws IOException { getKind().write(s); getDeclaringType().write(s); s.writeInt(modifiers); s.writeUTF(getName()); s.writeUTF(getSignature()); UnresolvedType.writeArray(getExceptions(), s); s.writeInt(getStart()); s.writeInt(getEnd()); // Write out any type variables... if (typeVariables==null) { s.writeInt(0); } else { s.writeInt(typeVariables.length); for (int i = 0; i < typeVariables.length; i++) { typeVariables[i].write(s); } } } public static void writeArray(ResolvedMember[] members, DataOutputStream s) throws IOException { s.writeInt(members.length); for (int i = 0, len = members.length; i < len; i++) { members[i].write(s); } } public static ResolvedMemberImpl readResolvedMember(VersionedDataInputStream s, ISourceContext sourceContext) throws IOException { ResolvedMemberImpl m = new ResolvedMemberImpl(Kind.read(s), UnresolvedType.read(s), s.readInt(), s.readUTF(), s.readUTF()); m.checkedExceptions = UnresolvedType.readArray(s); m.start = s.readInt(); m.end = s.readInt(); m.sourceContext = sourceContext; // Read in the type variables... if (s.getMajorVersion()>=AjAttribute.WeaverVersionInfo.WEAVER_VERSION_MAJOR_AJ150) { int tvcount = s.readInt(); if (tvcount!=0) { m.typeVariables = new UnresolvedType[tvcount]; for (int i=0;i<tvcount;i++) { m.typeVariables[i]=UnresolvedType.read(s); } } } return m; } public static ResolvedMember[] readResolvedMemberArray(VersionedDataInputStream s, ISourceContext context) throws IOException { int len = s.readInt(); ResolvedMember[] members = new ResolvedMember[len]; for (int i=0; i < len; i++) { members[i] = ResolvedMemberImpl.readResolvedMember(s, context); } return members; } public ResolvedMember resolve(World world) { // make sure all the pieces of a resolvedmember really are resolved if (annotationTypes!=null) { Set r = new HashSet(); for (Iterator iter = annotationTypes.iterator(); iter.hasNext();) { UnresolvedType element = (UnresolvedType) iter.next(); r.add(world.resolve(element)); } annotationTypes = r; } declaringType = declaringType.resolve(world); if (declaringType.isRawType()) declaringType = ((ReferenceType)declaringType).getGenericType(); if (typeVariables!=null && typeVariables.length>0) { for (int i = 0; i < typeVariables.length; i++) { UnresolvedType array_element = typeVariables[i]; typeVariables[i] = typeVariables[i].resolve(world); } } if (parameterTypes!=null && parameterTypes.length>0) { for (int i = 0; i < parameterTypes.length; i++) { UnresolvedType array_element = parameterTypes[i]; parameterTypes[i] = parameterTypes[i].resolve(world); } } returnType = returnType.resolve(world);return this; } public ISourceContext getSourceContext(World world) { return getDeclaringType().resolve(world).getSourceContext(); } public final String[] getParameterNames() { return parameterNames; } public final String[] getParameterNames(World world) { return getParameterNames(); } public AjAttribute.EffectiveSignatureAttribute getEffectiveSignature() { return null; } public ISourceLocation getSourceLocation() { //System.out.println("get context: " + this + " is " + sourceContext); if (sourceContext == null) { //System.err.println("no context: " + this); return null; } return sourceContext.makeSourceLocation(this); } public int getEnd() { return end; } public ISourceContext getSourceContext() { return sourceContext; } public int getStart() { return start; } public void setPosition(int sourceStart, int sourceEnd) { this.start = sourceStart; this.end = sourceEnd; } public void setSourceContext(ISourceContext sourceContext) { this.sourceContext = sourceContext; } public boolean isAbstract() { return Modifier.isAbstract(modifiers); } public boolean isPublic() { return Modifier.isPublic(modifiers); } public boolean isProtected() { return Modifier.isProtected(modifiers); } public boolean isNative() { return Modifier.isNative(modifiers); } public boolean isDefault() { return !(isPublic() || isProtected() || isPrivate()); } public boolean isVisible(ResolvedType fromType) { World world = fromType.getWorld(); return ResolvedType.isVisible(getModifiers(), getDeclaringType().resolve(world), fromType); } public void setCheckedExceptions(UnresolvedType[] checkedExceptions) { this.checkedExceptions = checkedExceptions; } public void setAnnotatedElsewhere(boolean b) { isAnnotatedElsewhere = b; } public boolean isAnnotatedElsewhere() { return isAnnotatedElsewhere; } /** * Get the UnresolvedType for the return type, taking generic signature into account */ public UnresolvedType getGenericReturnType() { return getReturnType(); } /** * Get the TypeXs of the parameter types, taking generic signature into account */ public UnresolvedType[] getGenericParameterTypes() { return getParameterTypes(); } // return a resolved member in which all type variables in the signature of this // member have been replaced with the given bindings. // the isParameterized flag tells us whether we are creating a raw type version or not // if isParameterized List<T> will turn into List<String> (for example), // but if !isParameterized List<T> will turn into List. public ResolvedMemberImpl parameterizedWith(UnresolvedType[] typeParameters,ResolvedType newDeclaringType, boolean isParameterized) { if (!this.getDeclaringType().isGenericType()) { throw new IllegalStateException("Can't ask to parameterize a member of a non-generic type"); } TypeVariable[] typeVariables = getDeclaringType().getTypeVariables(); if (typeVariables.length != typeParameters.length) { throw new IllegalStateException("Wrong number of type parameters supplied"); } Map typeMap = new HashMap(); for (int i = 0; i < typeVariables.length; i++) { typeMap.put(typeVariables[i].getName(), typeParameters[i]); } UnresolvedType parameterizedReturnType = parameterize(getGenericReturnType(),typeMap,isParameterized); UnresolvedType[] parameterizedParameterTypes = new UnresolvedType[getGenericParameterTypes().length]; for (int i = 0; i < parameterizedParameterTypes.length; i++) { parameterizedParameterTypes[i] = parameterize(getGenericParameterTypes()[i], typeMap,isParameterized); } return new ResolvedMemberImpl( getKind(), newDeclaringType, getModifiers(), parameterizedReturnType, getName(), parameterizedParameterTypes, getExceptions(), this ); } public void setTypeVariables(UnresolvedType[] types) { typeVariables = types; } public UnresolvedType[] getTypeVariables() { return typeVariables; } private UnresolvedType parameterize(UnresolvedType aType, Map typeVariableMap, boolean inParameterizedType) { if (aType instanceof TypeVariableReferenceType) { String variableName = ((TypeVariableReferenceType)aType).getTypeVariable().getName(); if (!typeVariableMap.containsKey(variableName)) { return aType; // if the type variable comes from the method (and not the type) thats OK } return (UnresolvedType) typeVariableMap.get(variableName); } else if (aType.isParameterizedType()) { if (inParameterizedType) { return aType.parameterize(typeVariableMap); } else { return aType.getRawType(); } } return aType; } /** * If this member is defined by a parameterized super-type, return the erasure * of that member. * For example: * interface I<T> { T foo(T aTea); } * class C implements I<String> { * String foo(String aString) { return "something"; } * } * The resolved member for C.foo has signature String foo(String). The * erasure of that member is Object foo(Object) -- use upper bound of type * variable. * A type is a supertype of itself. */ public ResolvedMember getErasure() { if (calculatedMyErasure) return myErasure; calculatedMyErasure = true; ResolvedType resolvedDeclaringType = (ResolvedType) getDeclaringType(); // this next test is fast, and the result is cached. if (!resolvedDeclaringType.hasParameterizedSuperType()) { return null; } else { // we have one or more parameterized super types. // this member may be defined by one of them... we need to find out. Collection declaringTypes = this.getDeclaringTypes(resolvedDeclaringType.getWorld()); for (Iterator iter = declaringTypes.iterator(); iter.hasNext();) { ResolvedType aDeclaringType = (ResolvedType) iter.next(); if (aDeclaringType.isParameterizedType()) { // we've found the (a?) parameterized type that defines this member. // now get the erasure of it ResolvedMemberImpl matchingMember = (ResolvedMemberImpl) aDeclaringType.lookupMemberNoSupers(this); if (matchingMember != null && matchingMember.backingGenericMember != null) { myErasure = matchingMember.backingGenericMember; return myErasure; } } } } return null; } private ResolvedMember myErasure = null; private boolean calculatedMyErasure = false; /** * For ITDs, we use the default factory methods to build a resolved member, then alter a couple of characteristics * using this method - this is safe. */ public void resetName(String newName) {this.name = newName;} public void resetKind(Kind newKind) {this.kind=newKind; } public void resetModifiers(int newModifiers) {this.modifiers=newModifiers;} public void resetReturnTypeToObjectArray() { returnType = UnresolvedType.OBJECTARRAY; } /** * Returns a copy of this member but with the declaring type swapped. * Copy only needs to be shallow. * @param newDeclaringType */ private JoinPointSignature withSubstituteDeclaringType(ResolvedType newDeclaringType) { JoinPointSignature ret = new JoinPointSignature(this,newDeclaringType); return ret; } /** * Returns true if this member matches the other. The matching takes into account * name and parameter types only. When comparing parameter types, we allow any type * variable to match any other type variable regardless of bounds. */ public boolean matches(ResolvedMember aCandidateMatch) { ResolvedMemberImpl candidateMatchImpl = (ResolvedMemberImpl)aCandidateMatch; if (!getName().equals(aCandidateMatch.getName())) return false; UnresolvedType[] myParameterTypes = getGenericParameterTypes(); UnresolvedType[] candidateParameterTypes = aCandidateMatch.getGenericParameterTypes(); if (myParameterTypes.length != candidateParameterTypes.length) return false; String myParameterSignature = getParameterSigWithBoundsRemoved(); String candidateParameterSignature = candidateMatchImpl.getParameterSigWithBoundsRemoved(); if (myParameterSignature.equals(candidateParameterSignature)) { return true; } else { // try erasure myParameterSignature = getParameterSigErasure(); candidateParameterSignature = candidateMatchImpl.getParameterSigErasure(); return myParameterSignature.equals(candidateParameterSignature); } } /** converts e.g. <T extends Number>.... List<T> to just Ljava/util/List<T;>; * whereas the full signature would be Ljava/util/List<T:Ljava/lang/Number;>; */ private String myParameterSignatureWithBoundsRemoved = null; /** * converts e.g. <T extends Number>.... List<T> to just Ljava/util/List; */ private String myParameterSignatureErasure = null; // does NOT produce a meaningful java signature, but does give a unique string suitable for // comparison. private String getParameterSigWithBoundsRemoved() { if (myParameterSignatureWithBoundsRemoved != null) return myParameterSignatureWithBoundsRemoved; StringBuffer sig = new StringBuffer(); UnresolvedType[] myParameterTypes = getGenericParameterTypes(); for (int i = 0; i < myParameterTypes.length; i++) { appendSigWithTypeVarBoundsRemoved(myParameterTypes[i], sig); } myParameterSignatureWithBoundsRemoved = sig.toString(); return myParameterSignatureWithBoundsRemoved; } private String getParameterSigErasure() { if (myParameterSignatureErasure != null) return myParameterSignatureErasure; StringBuffer sig = new StringBuffer(); UnresolvedType[] myParameterTypes = getParameterTypes(); for (int i = 0; i < myParameterTypes.length; i++) { UnresolvedType thisParameter = myParameterTypes[i]; if (thisParameter.isTypeVariableReference()) { sig.append(thisParameter.getUpperBound().getSignature()); } else { sig.append(thisParameter.getSignature()); } } myParameterSignatureErasure = sig.toString(); return myParameterSignatureErasure; } // does NOT produce a meaningful java signature, but does give a unique string suitable for // comparison. private void appendSigWithTypeVarBoundsRemoved(UnresolvedType aType, StringBuffer toBuffer) { if (aType.isTypeVariableReference()) { toBuffer.append("T;"); } else if (aType.isParameterizedType()) { toBuffer.append(aType.getRawType().getSignature()); toBuffer.append("<"); for (int i = 0; i < aType.getTypeParameters().length; i++) { appendSigWithTypeVarBoundsRemoved(aType.getTypeParameters()[i], toBuffer); } toBuffer.append(">;"); } else { toBuffer.append(aType.getSignature()); } } public String toGenericString() { StringBuffer buf = new StringBuffer(); buf.append(getGenericReturnType().getSimpleName()); buf.append(' '); buf.append(declaringType.getName()); buf.append('.'); buf.append(name); if (kind != FIELD) { buf.append("("); UnresolvedType[] params = getGenericParameterTypes(); if (params.length != 0) { buf.append(params[0].getSimpleName()); for (int i=1, len = params.length; i < len; i++) { buf.append(", "); buf.append(params[i].getSimpleName()); } } buf.append(")"); } return buf.toString(); } }
108,886
Bug 108886 Getting Exception during compilation : java.lang.RuntimeException: Internal Compiler Error: Unexpected null source location passed as 'see also' location.
Am attaching a small test case to reproduce the error (Not sure how to attach it - hopefully should be feasible to do so after I log the bug).
resolved fixed
2d21db0
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-08T16:57:15Z
2005-09-06T23:40:00Z
weaver/src/org/aspectj/weaver/ResolvedType.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.patterns.Declare; import org.aspectj.weaver.patterns.PerClause; public abstract class ResolvedType extends UnresolvedType implements AnnotatedElement { private static final ResolvedType[] EMPTY_RESOLVED_TYPE_ARRAY = new ResolvedType[0]; public static final String PARAMETERIZED_TYPE_IDENTIFIER = "P"; private ResolvedType[] resolvedTypeParams; protected World world; protected ResolvedType(String signature, World world) { super(signature); this.world = world; } protected ResolvedType(String signature, String signatureErasure, World world) { super(signature,signatureErasure); this.world = world; } // ---- things that don't require a world /** * Returns an iterator through ResolvedType objects representing all the direct * supertypes of this type. That is, through the superclass, if any, and * all declared interfaces. */ public final Iterator getDirectSupertypes() { Iterator ifacesIterator = Iterators.array(getDeclaredInterfaces()); ResolvedType superclass = getSuperclass(); if (superclass == null) { return ifacesIterator; } else { return Iterators.snoc(ifacesIterator, superclass); } } public abstract ResolvedMember[] getDeclaredFields(); public abstract ResolvedMember[] getDeclaredMethods(); public abstract ResolvedType[] getDeclaredInterfaces(); public abstract ResolvedMember[] getDeclaredPointcuts(); /** * Returns a ResolvedType object representing the superclass of this type, or null. * If this represents a java.lang.Object, a primitive type, or void, this * method returns null. */ public abstract ResolvedType getSuperclass(); /** * Returns the modifiers for this type. * * See {@link java.lang.Class#getModifiers()} for a description * of the weirdness of this methods on primitives and arrays. * * @param world the {@link World} in which the lookup is made. * @return an int representing the modifiers for this type * @see java.lang.reflect.Modifier */ public abstract int getModifiers(); public ResolvedType[] getAnnotationTypes() { return EMPTY_RESOLVED_TYPE_ARRAY; } public final UnresolvedType getSuperclass(World world) { return getSuperclass(); } // This set contains pairs of types whose signatures are concatenated // together, this means with a fast lookup we can tell if two types // are equivalent. static Set validBoxing = new HashSet(); static { validBoxing.add("Ljava/lang/Byte;B"); validBoxing.add("Ljava/lang/Character;C"); validBoxing.add("Ljava/lang/Double;D"); validBoxing.add("Ljava/lang/Float;F"); validBoxing.add("Ljava/lang/Integer;I"); validBoxing.add("Ljava/lang/Long;J"); validBoxing.add("Ljava/lang/Short;S"); validBoxing.add("Ljava/lang/Boolean;Z"); validBoxing.add("BLjava/lang/Byte;"); validBoxing.add("CLjava/lang/Character;"); validBoxing.add("DLjava/lang/Double;"); validBoxing.add("FLjava/lang/Float;"); validBoxing.add("ILjava/lang/Integer;"); validBoxing.add("JLjava/lang/Long;"); validBoxing.add("SLjava/lang/Short;"); validBoxing.add("ZLjava/lang/Boolean;"); } // utilities public ResolvedType getResolvedComponentType() { return null; } public World getWorld() { return world; } // ---- things from object public final boolean equals(Object other) { if (other instanceof ResolvedType) { return this == other; } else { return super.equals(other); } } // ---- difficult things /** * returns an iterator through all of the fields of this type, in order * for checking from JVM spec 2ed 5.4.3.2. This means that the order is * * <ul><li> fields from current class </li> * <li> recur into direct superinterfaces </li> * <li> recur into superclass </li> * </ul> * * We keep a hashSet of interfaces that we've visited so we don't spiral * out into 2^n land. */ public Iterator getFields() { final Iterators.Filter dupFilter = Iterators.dupFilter(); Iterators.Getter typeGetter = new Iterators.Getter() { public Iterator get(Object o) { return dupFilter.filter( ((ResolvedType)o).getDirectSupertypes()); } }; Iterators.Getter fieldGetter = new Iterators.Getter() { public Iterator get(Object o) { return Iterators.array(((ResolvedType)o).getDeclaredFields()); } }; return Iterators.mapOver( Iterators.recur(this, typeGetter), fieldGetter); } /** * returns an iterator through all of the methods of this type, in order * for checking from JVM spec 2ed 5.4.3.3. This means that the order is * * <ul><li> methods from current class </li> * <li> recur into superclass, all the way up, not touching interfaces </li> * <li> recur into all superinterfaces, in some unspecified order </li> * </ul> * * We keep a hashSet of interfaces that we've visited so we don't spiral * out into 2^n land. * NOTE: Take a look at the javadoc on getMethodsWithoutIterator() to see if * you are sensitive to a quirk in getMethods() */ public Iterator getMethods() { final Iterators.Filter dupFilter = Iterators.dupFilter(); Iterators.Getter ifaceGetter = new Iterators.Getter() { public Iterator get(Object o) { return dupFilter.filter( Iterators.array(((ResolvedType)o).getDeclaredInterfaces()) ); } }; Iterators.Getter methodGetter = new Iterators.Getter() { public Iterator get(Object o) { return Iterators.array(((ResolvedType)o).getDeclaredMethods()); } }; return Iterators.mapOver( Iterators.append( new Iterator() { ResolvedType curr = ResolvedType.this; public boolean hasNext() { return curr != null; } public Object next() { ResolvedType ret = curr; curr = curr.getSuperclass(); return ret; } public void remove() { throw new UnsupportedOperationException(); } }, Iterators.recur(this, ifaceGetter)), methodGetter); } /** * Return a list of methods, first those declared on this class, then those declared on the superclass (recurse) and then those declared * on the superinterfaces. The getMethods() call above doesn't quite work the same as it will (through the iterator) return methods * declared on *this* class twice, once at the start and once at the end - I couldn't debug that problem, so created this alternative. */ public List getMethodsWithoutIterator(boolean includeITDs) { List methods = new ArrayList(); Set knowninterfaces = new HashSet(); addAndRecurse(knowninterfaces,methods,this,includeITDs); return methods; } private void addAndRecurse(Set knowninterfaces,List collector, ResolvedType rtx, boolean includeITDs) { collector.addAll(Arrays.asList(rtx.getDeclaredMethods())); // Add the methods declared on this type // now add all the inter-typed members too if (includeITDs && rtx.interTypeMungers != null) { for (Iterator i = interTypeMungers.iterator(); i.hasNext();) { ConcreteTypeMunger tm = (ConcreteTypeMunger) i.next(); ResolvedMember rm = tm.getSignature(); if (rm != null) { // new parent type munger can have null signature... collector.add(tm.getSignature()); } } } if (!rtx.equals(ResolvedType.OBJECT)) { ResolvedType superType = rtx.getSuperclass(); if (rtx == null || rtx == ResolvedType.MISSING) { // can't find type message - with context! world.showMessage(Message.ERROR, WeaverMessages.format(WeaverMessages.CANT_FIND_PARENT_TYPE,rtx.getSignature()), null,null); } else { addAndRecurse(knowninterfaces,collector,superType,includeITDs); // Recurse if we aren't at the top } } ResolvedType[] interfaces = rtx.getDeclaredInterfaces(); // Go through the interfaces on the way back down for (int i = 0; i < interfaces.length; i++) { ResolvedType iface = interfaces[i]; if (!knowninterfaces.contains(iface)) { // Dont do interfaces more than once knowninterfaces.add(iface); addAndRecurse(knowninterfaces,collector,iface,includeITDs); } } } public ResolvedType[] getResolvedTypeParameters() { if (resolvedTypeParams == null) { resolvedTypeParams = world.resolve(typeParameters); } return resolvedTypeParams; } /** * described in JVM spec 2ed 5.4.3.2 */ public ResolvedMember lookupField(Member m) { return lookupMember(m, getFields()); } /** * described in JVM spec 2ed 5.4.3.3. * Doesnt check ITDs. */ public ResolvedMember lookupMethod(Member m) { return lookupMember(m, getMethods()); } public ResolvedMember lookupMethodInITDs(Member m) { if (interTypeMungers != null) { for (Iterator i = interTypeMungers.iterator(); i.hasNext();) { ConcreteTypeMunger tm = (ConcreteTypeMunger) i.next(); if (matches(tm.getSignature(), m)) { return tm.getSignature(); } } } return null; } /** return null if not found */ private ResolvedMember lookupMember(Member m, Iterator i) { while (i.hasNext()) { ResolvedMember f = (ResolvedMember) i.next(); if (matches(f, m)) return f; } return null; //ResolvedMember.Missing; //throw new BCException("can't find " + m); } /** return null if not found */ private ResolvedMember lookupMember(Member m, ResolvedMember[] a) { for (int i = 0; i < a.length; i++) { ResolvedMember f = a[i]; if (matches(f, m)) return f; } return null; } /** * Looks for the first member in the hierarchy matching aMember. This method * differs from lookupMember(Member) in that it takes into account parameters * which are type variables - which clearly an unresolved Member cannot do since * it does not know anything about type variables. */ public ResolvedMember lookupResolvedMember(ResolvedMember aMember) { Iterator toSearch = null; ResolvedMember found = null; if ((aMember.getKind() == Member.METHOD) || (aMember.getKind() == Member.CONSTRUCTOR)) { toSearch = getMethodsWithoutIterator(true).iterator(); } else { if (aMember.getKind() != Member.FIELD) throw new IllegalStateException("I didn't know you would look for members of kind " + aMember.getKind()); toSearch = getFields(); } while(toSearch.hasNext()) { ResolvedMemberImpl candidate = (ResolvedMemberImpl) toSearch.next(); if (candidate.matches(aMember)) { found = candidate; break; } } return found; } public static boolean matches(Member m1, Member m2) { if (m1 == null) return m2 == null; if (m2 == null) return false; // Check the names boolean equalNames = m1.getName().equals(m2.getName()); if (!equalNames) return false; // Check the signatures boolean equalSignatures = m1.getSignature().equals(m2.getSignature()); if (equalSignatures) return true; // If they aren't the same, we need to allow for covariance ... where one sig might be ()LCar; and // the subsig might be ()LFastCar; - where FastCar is a subclass of Car boolean equalCovariantSignatures = m1.getParameterSignature().equals(m2.getParameterSignature()); if (equalCovariantSignatures) return true; return false; } public static boolean conflictingSignature(Member m1, Member m2) { if (m1 == null || m2 == null) return false; if (!m1.getName().equals(m2.getName())) { return false; } if (m1.getKind() != m2.getKind()) { return false; } if (m1.getKind() == Member.FIELD) { return m1.getDeclaringType().equals(m2.getDeclaringType()); } else if (m1.getKind() == Member.POINTCUT) { return true; } UnresolvedType[] p1 = m1.getParameterTypes(); UnresolvedType[] p2 = m2.getParameterTypes(); int n = p1.length; if (n != p2.length) return false; for (int i=0; i < n; i++) { if (!p1[i].equals(p2[i])) return false; } return true; } /** * returns an iterator through all of the pointcuts of this type, in order * for checking from JVM spec 2ed 5.4.3.2 (as for fields). This means that the order is * * <ul><li> pointcuts from current class </li> * <li> recur into direct superinterfaces </li> * <li> recur into superclass </li> * </ul> * * We keep a hashSet of interfaces that we've visited so we don't spiral * out into 2^n land. */ public Iterator getPointcuts() { final Iterators.Filter dupFilter = Iterators.dupFilter(); // same order as fields Iterators.Getter typeGetter = new Iterators.Getter() { public Iterator get(Object o) { return dupFilter.filter( ((ResolvedType)o).getDirectSupertypes()); } }; Iterators.Getter pointcutGetter = new Iterators.Getter() { public Iterator get(Object o) { //System.err.println("getting for " + o); return Iterators.array(((ResolvedType)o).getDeclaredPointcuts()); } }; return Iterators.mapOver( Iterators.recur(this, typeGetter), pointcutGetter); } public ResolvedPointcutDefinition findPointcut(String name) { //System.err.println("looking for pointcuts " + this); for (Iterator i = getPointcuts(); i.hasNext(); ) { ResolvedPointcutDefinition f = (ResolvedPointcutDefinition) i.next(); //System.err.println(f); if (name.equals(f.getName())) { return f; } } return null; // should we throw an exception here? } // all about collecting CrosscuttingMembers //??? collecting data-structure, shouldn't really be a field public CrosscuttingMembers crosscuttingMembers; public CrosscuttingMembers collectCrosscuttingMembers() { crosscuttingMembers = new CrosscuttingMembers(this); crosscuttingMembers.setPerClause(getPerClause()); crosscuttingMembers.addShadowMungers(collectShadowMungers()); crosscuttingMembers.addTypeMungers(getTypeMungers()); //FIXME AV - skip but needed ?? or ?? crosscuttingMembers.addLateTypeMungers(getLateTypeMungers()); crosscuttingMembers.addDeclares(collectDeclares(!this.doesNotExposeShadowMungers())); crosscuttingMembers.addPrivilegedAccesses(getPrivilegedAccesses()); //System.err.println("collected cc members: " + this + ", " + collectDeclares()); return crosscuttingMembers; } public final Collection collectDeclares(boolean includeAdviceLike) { if (! this.isAspect() ) return Collections.EMPTY_LIST; ArrayList ret = new ArrayList(); //if (this.isAbstract()) { // for (Iterator i = getDeclares().iterator(); i.hasNext();) { // Declare dec = (Declare) i.next(); // if (!dec.isAdviceLike()) ret.add(dec); // } // // if (!includeAdviceLike) return ret; if (!this.isAbstract()) { //ret.addAll(getDeclares()); final Iterators.Filter dupFilter = Iterators.dupFilter(); Iterators.Getter typeGetter = new Iterators.Getter() { public Iterator get(Object o) { return dupFilter.filter( ((ResolvedType)o).getDirectSupertypes()); } }; Iterator typeIterator = Iterators.recur(this, typeGetter); while (typeIterator.hasNext()) { ResolvedType ty = (ResolvedType) typeIterator.next(); //System.out.println("super: " + ty + ", " + ); for (Iterator i = ty.getDeclares().iterator(); i.hasNext();) { Declare dec = (Declare) i.next(); if (dec.isAdviceLike()) { if (includeAdviceLike) ret.add(dec); } else { ret.add(dec); } } } } return ret; } private final Collection collectShadowMungers() { if (! this.isAspect() || this.isAbstract() || this.doesNotExposeShadowMungers()) return Collections.EMPTY_LIST; ArrayList acc = new ArrayList(); final Iterators.Filter dupFilter = Iterators.dupFilter(); Iterators.Getter typeGetter = new Iterators.Getter() { public Iterator get(Object o) { return dupFilter.filter( ((ResolvedType)o).getDirectSupertypes()); } }; Iterator typeIterator = Iterators.recur(this, typeGetter); while (typeIterator.hasNext()) { ResolvedType ty = (ResolvedType) typeIterator.next(); acc.addAll(ty.getDeclaredShadowMungers()); } return acc; } protected boolean doesNotExposeShadowMungers() { return false; } public PerClause getPerClause() { return null; } protected Collection getDeclares() { return Collections.EMPTY_LIST; } protected Collection getTypeMungers() { return Collections.EMPTY_LIST; } protected Collection getPrivilegedAccesses() { return Collections.EMPTY_LIST; } // ---- useful things public final boolean isInterface() { return Modifier.isInterface(getModifiers()); } public final boolean isAbstract() { return Modifier.isAbstract(getModifiers()); } public boolean isClass() { return false; } public boolean isAspect() { return false; } public boolean isAnnotationStyleAspect() { return false; } /** * Note: Only overridden by Name subtype. */ public boolean isEnum() { return false; } /** * Note: Only overridden by Name subtype. */ public boolean isAnnotation() { return false; } /** * Note: Only overridden by Name subtype */ public void addAnnotation(AnnotationX annotationX) { throw new RuntimeException("ResolvedType.addAnnotation() should never be called"); } /** * Note: Only overridden by Name subtype */ public AnnotationX[] getAnnotations() { throw new RuntimeException("ResolvedType.getAnnotations() should never be called"); } /** * Note: Only overridden by Name subtype. */ public boolean isAnnotationWithRuntimeRetention() { return false; } public boolean isSynthetic() { return signature.indexOf("$ajc") != -1; } public final boolean isFinal() { return Modifier.isFinal(getModifiers()); } protected Map /*Type variable name -> UnresolvedType*/ getMemberParameterizationMap() { if (!isParameterizedType()) return Collections.EMPTY_MAP; TypeVariable[] tvs = getGenericType().getTypeVariables(); Map parameterizationMap = new HashMap(); for (int i = 0; i < tvs.length; i++) { parameterizationMap.put(tvs[i].getName(), typeParameters[i]); } return parameterizationMap; } public Collection getDeclaredAdvice() { List l = new ArrayList(); ResolvedMember[] methods = getDeclaredMethods(); if (isParameterizedType()) methods = getGenericType().getDeclaredMethods(); Map typeVariableMap = getMemberParameterizationMap(); for (int i=0, len = methods.length; i < len; i++) { ShadowMunger munger = methods[i].getAssociatedShadowMunger(); if (munger != null) { if (this.isParameterizedType()) { munger.setPointcut(munger.getPointcut().parameterizeWith(typeVariableMap)); } munger.setDeclaringType(this); l.add(munger); } } return l; } public Collection getDeclaredShadowMungers() { Collection c = getDeclaredAdvice(); return c; } // ---- only for testing! public ResolvedMember[] getDeclaredJavaFields() { return filterInJavaVisible(getDeclaredFields()); } public ResolvedMember[] getDeclaredJavaMethods() { return filterInJavaVisible(getDeclaredMethods()); } public ShadowMunger[] getDeclaredShadowMungersArray() { List l = (List) getDeclaredShadowMungers(); return (ShadowMunger[]) l.toArray(new ShadowMunger[l.size()]); } private ResolvedMember[] filterInJavaVisible(ResolvedMember[] ms) { List l = new ArrayList(); for (int i=0, len = ms.length; i < len; i++) { if (! ms[i].isAjSynthetic() && ms[i].getAssociatedShadowMunger() == null) { l.add(ms[i]); } } return (ResolvedMember[]) l.toArray(new ResolvedMember[l.size()]); } public abstract ISourceContext getSourceContext(); // ---- fields public static final ResolvedType[] NONE = new ResolvedType[0]; public static final Primitive BYTE = new Primitive("B", 1, 0); public static final Primitive CHAR = new Primitive("C", 1, 1); public static final Primitive DOUBLE = new Primitive("D", 2, 2); public static final Primitive FLOAT = new Primitive("F", 1, 3); public static final Primitive INT = new Primitive("I", 1, 4); public static final Primitive LONG = new Primitive("J", 2, 5); public static final Primitive SHORT = new Primitive("S", 1, 6); public static final Primitive VOID = new Primitive("V", 0, 8); public static final Primitive BOOLEAN = new Primitive("Z", 1, 7); public static final Missing MISSING = new Missing(); // ---- types public static ResolvedType makeArray(ResolvedType type, int dim) { if (dim == 0) return type; ResolvedType array = new Array("[" + type.getSignature(),type.getWorld(),type); return makeArray(array,dim-1); } static class Array extends ResolvedType { ResolvedType componentType; Array(String s, World world, ResolvedType componentType) { super(s, world); this.componentType = componentType; } public final ResolvedMember[] getDeclaredFields() { return ResolvedMember.NONE; } public final ResolvedMember[] getDeclaredMethods() { // ??? should this return clone? Probably not... // If it ever does, here is the code: // ResolvedMember cloneMethod = // new ResolvedMember(Member.METHOD,this,Modifier.PUBLIC,UnresolvedType.OBJECT,"clone",new UnresolvedType[]{}); // return new ResolvedMember[]{cloneMethod}; return ResolvedMember.NONE; } public final ResolvedType[] getDeclaredInterfaces() { return new ResolvedType[] { world.getCoreType(CLONEABLE), world.getCoreType(SERIALIZABLE) }; } public final ResolvedMember[] getDeclaredPointcuts() { return ResolvedMember.NONE; } public boolean hasAnnotation(UnresolvedType ofType) { return false; } public final ResolvedType getSuperclass() { return world.getCoreType(OBJECT); } public final boolean isAssignableFrom(ResolvedType o) { if (! o.isArray()) return false; if (o.getComponentType().isPrimitiveType()) { return o.equals(this); } else { return getComponentType().resolve(world).isAssignableFrom(o.getComponentType().resolve(world)); } } public final boolean isCoerceableFrom(ResolvedType o) { if (o.equals(UnresolvedType.OBJECT) || o.equals(UnresolvedType.SERIALIZABLE) || o.equals(UnresolvedType.CLONEABLE)) { return true; } if (! o.isArray()) return false; if (o.getComponentType().isPrimitiveType()) { return o.equals(this); } else { return getComponentType().resolve(world).isCoerceableFrom(o.getComponentType().resolve(world)); } } public final int getModifiers() { int mask = Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED; return (componentType.getModifiers() & mask) | Modifier.FINAL; } public UnresolvedType getComponentType() { return componentType; } public ResolvedType getResolvedComponentType() { return componentType; } public ISourceContext getSourceContext() { return getResolvedComponentType().getSourceContext(); } } static class Primitive extends ResolvedType { private int size; private int index; Primitive(String signature, int size, int index) { super(signature, null); this.size = size; this.index = index; } public final int getSize() { return size; } public final int getModifiers() { return Modifier.PUBLIC | Modifier.FINAL; } public final boolean isPrimitiveType() { return true; } public boolean hasAnnotation(UnresolvedType ofType) { return false; } public final boolean isAssignableFrom(ResolvedType other) { if (!other.isPrimitiveType()) { if (!world.isInJava5Mode()) return false; return validBoxing.contains(this.getSignature()+other.getSignature()); } return assignTable[((Primitive)other).index][index]; } public final boolean isCoerceableFrom(ResolvedType other) { if (this == other) return true; if (! other.isPrimitiveType()) return false; if (index > 6 || ((Primitive)other).index > 6) return false; return true; } public ResolvedType resolve(World world) { this.world = world; return super.resolve(world); } public final boolean needsNoConversionFrom(ResolvedType other) { if (! other.isPrimitiveType()) return false; return noConvertTable[((Primitive)other).index][index]; } private static final boolean[][] assignTable = {// to: B C D F I J S V Z from { true , true , true , true , true , true , true , false, false }, // B { false, true , true , true , true , true , false, false, false }, // C { false, false, true , false, false, false, false, false, false }, // D { false, false, true , true , false, false, false, false, false }, // F { false, false, true , true , true , true , false, false, false }, // I { false, false, true , true , false, true , false, false, false }, // J { false, false, true , true , true , true , true , false, false }, // S { false, false, false, false, false, false, false, true , false }, // V { false, false, false, false, false, false, false, false, true }, // Z }; private static final boolean[][] noConvertTable = {// to: B C D F I J S V Z from { true , true , false, false, true , false, true , false, false }, // B { false, true , false, false, true , false, false, false, false }, // C { false, false, true , false, false, false, false, false, false }, // D { false, false, false, true , false, false, false, false, false }, // F { false, false, false, false, true , false, false, false, false }, // I { false, false, false, false, false, true , false, false, false }, // J { false, false, false, false, true , false, true , false, false }, // S { false, false, false, false, false, false, false, true , false }, // V { false, false, false, false, false, false, false, false, true }, // Z }; // ---- public final ResolvedMember[] getDeclaredFields() { return ResolvedMember.NONE; } public final ResolvedMember[] getDeclaredMethods() { return ResolvedMember.NONE; } public final ResolvedType[] getDeclaredInterfaces() { return ResolvedType.NONE; } public final ResolvedMember[] getDeclaredPointcuts() { return ResolvedMember.NONE; } public final ResolvedType getSuperclass() { return null; } public ISourceContext getSourceContext() { return null; } } static class Missing extends ResolvedType { Missing() { super(MISSING_NAME, null); } // public final String toString() { // return "<missing>"; // } public final String getName() { return MISSING_NAME; } public boolean hasAnnotation(UnresolvedType ofType) { return false; } public final ResolvedMember[] getDeclaredFields() { return ResolvedMember.NONE; } public final ResolvedMember[] getDeclaredMethods() { return ResolvedMember.NONE; } public final ResolvedType[] getDeclaredInterfaces() { return ResolvedType.NONE; } public final ResolvedMember[] getDeclaredPointcuts() { return ResolvedMember.NONE; } public final ResolvedType getSuperclass() { return null; } public final int getModifiers() { return 0; } public final boolean isAssignableFrom(ResolvedType other) { return false; } public final boolean isCoerceableFrom(ResolvedType other) { return false; } public boolean needsNoConversionFrom(ResolvedType other) { return false; } public ISourceContext getSourceContext() { return null; } } /** * Look up a member, takes into account any ITDs on this type. * return null if not found */ public ResolvedMember lookupMemberNoSupers(Member member) { ResolvedMember ret = lookupDirectlyDeclaredMemberNoSupers(member); if (ret == null && interTypeMungers != null) { for (Iterator i = interTypeMungers.iterator(); i.hasNext();) { ConcreteTypeMunger tm = (ConcreteTypeMunger) i.next(); if (matches(tm.getSignature(), member)) { return tm.getSignature(); } } } return ret; } /** * as lookupMemberNoSupers, but does not include ITDs * @param member * @return */ public ResolvedMember lookupDirectlyDeclaredMemberNoSupers(Member member) { ResolvedMember ret; if (member.getKind() == Member.FIELD) { ret = lookupMember(member, getDeclaredFields()); } else { // assert member.getKind() == Member.METHOD || member.getKind() == Member.CONSTRUCTOR ret = lookupMember(member, getDeclaredMethods()); } return ret; } /** * This lookup has specialized behaviour - a null result tells the * EclipseTypeMunger that it should make a default implementation of a * method on this type. * @param member * @return */ public ResolvedMember lookupMemberIncludingITDsOnInterfaces(Member member) { return lookupMemberIncludingITDsOnInterfaces(member, this); } private ResolvedMember lookupMemberIncludingITDsOnInterfaces(Member member, ResolvedType onType) { ResolvedMember ret = onType.lookupMemberNoSupers(member); if (ret != null) { return ret; } else { ResolvedType superType = onType.getSuperclass(); if (superType != null) { ret = lookupMemberIncludingITDsOnInterfaces(member,superType); } if (ret == null) { // try interfaces then, but only ITDs now... ResolvedType[] superInterfaces = onType.getDeclaredInterfaces(); for (int i = 0; i < superInterfaces.length; i++) { ret = superInterfaces[i].lookupMethodInITDs(member); if (ret != null) return ret; } } } return ret; } protected List interTypeMungers = new ArrayList(0); public List getInterTypeMungers() { return interTypeMungers; } public List getInterTypeParentMungers() { List l = new ArrayList(); for (Iterator iter = interTypeMungers.iterator(); iter.hasNext();) { ConcreteTypeMunger element = (ConcreteTypeMunger) iter.next(); if (element.getMunger() instanceof NewParentTypeMunger) l.add(element); } return l; } /** * ??? This method is O(N*M) where N = number of methods and M is number of * inter-type declarations in my super */ public List getInterTypeMungersIncludingSupers() { ArrayList ret = new ArrayList(); collectInterTypeMungers(ret); return ret; } public List getInterTypeParentMungersIncludingSupers() { ArrayList ret = new ArrayList(); collectInterTypeParentMungers(ret); return ret; } private void collectInterTypeParentMungers(List collector) { for (Iterator iter = getDirectSupertypes(); iter.hasNext();) { ResolvedType superType = (ResolvedType) iter.next(); superType.collectInterTypeParentMungers(collector); } collector.addAll(getInterTypeParentMungers()); } private void collectInterTypeMungers(List collector) { for (Iterator iter = getDirectSupertypes(); iter.hasNext();) { ResolvedType superType = (ResolvedType) iter.next(); superType.collectInterTypeMungers(collector); } outer: for (Iterator iter1 = collector.iterator(); iter1.hasNext(); ) { ConcreteTypeMunger superMunger = (ConcreteTypeMunger) iter1.next(); if ( superMunger.getSignature() == null) continue; if ( !superMunger.getSignature().isAbstract()) continue; for (Iterator iter = getInterTypeMungers().iterator(); iter.hasNext();) { ConcreteTypeMunger myMunger = (ConcreteTypeMunger) iter.next(); if (conflictingSignature(myMunger.getSignature(), superMunger.getSignature())) { iter1.remove(); continue outer; } } if (!superMunger.getSignature().isPublic()) continue; for (Iterator iter = getMethods(); iter.hasNext(); ) { ResolvedMember method = (ResolvedMember)iter.next(); if (conflictingSignature(method, superMunger.getSignature())) { iter1.remove(); continue outer; } } } collector.addAll(getInterTypeMungers()); } /** * Check: * 1) That we don't have any abstract type mungers unless this type is abstract. * 2) That an abstract ITDM on an interface is declared public. (Compiler limitation) (PR70794) */ public void checkInterTypeMungers() { if (isAbstract()) return; boolean itdProblem = false; for (Iterator iter = getInterTypeMungersIncludingSupers().iterator(); iter.hasNext();) { ConcreteTypeMunger munger = (ConcreteTypeMunger) iter.next(); itdProblem = checkAbstractDeclaration(munger) || itdProblem; // Rule 2 } if (itdProblem) return; // If the rules above are broken, return right now for (Iterator iter = getInterTypeMungersIncludingSupers().iterator(); iter.hasNext();) { ConcreteTypeMunger munger = (ConcreteTypeMunger) iter.next(); if (munger.getSignature() != null && munger.getSignature().isAbstract()) { // Rule 1 world.getMessageHandler().handleMessage( new Message("must implement abstract inter-type declaration: " + munger.getSignature(), "", IMessage.ERROR, getSourceLocation(), null, new ISourceLocation[] { getMungerLocation(munger) })); } } } /** * See PR70794. This method checks that if an abstract inter-type method declaration is made on * an interface then it must also be public. * This is a compiler limitation that could be made to work in the future (if someone * provides a worthwhile usecase) * * @return indicates if the munger failed the check */ private boolean checkAbstractDeclaration(ConcreteTypeMunger munger) { if (munger.getMunger()!=null && (munger.getMunger() instanceof NewMethodTypeMunger)) { ResolvedMember itdMember = munger.getSignature(); ResolvedType onType = itdMember.getDeclaringType().resolve(world); if (onType.isInterface() && itdMember.isAbstract() && !itdMember.isPublic()) { world.getMessageHandler().handleMessage( new Message(WeaverMessages.format(WeaverMessages.ITD_ABSTRACT_MUST_BE_PUBLIC_ON_INTERFACE,munger.getSignature(),onType),"", Message.ERROR,getSourceLocation(),null, new ISourceLocation[]{getMungerLocation(munger)}) ); return true; } } return false; } /** * Get a source location for the munger. * Until intertype mungers remember where they came from, the source location * for the munger itself is null. In these cases use the * source location for the aspect containing the ITD. * */ private ISourceLocation getMungerLocation(ConcreteTypeMunger munger) { ISourceLocation sloc = munger.getSourceLocation(); if (sloc == null) { sloc = munger.getAspectType().getSourceLocation(); } return sloc; } /** * Returns a ResolvedType object representing the declaring type of this type, or * null if this type does not represent a non-package-level-type. * * <strong>Warning</strong>: This is guaranteed to work for all member types. * For anonymous/local types, the only guarantee is given in JLS 13.1, where * it guarantees that if you call getDeclaringType() repeatedly, you will eventually * get the top-level class, but it does not say anything about classes in between. * * @return the declaring UnresolvedType object, or null. */ public ResolvedType getDeclaringType() { if (isArray()) return null; String name = getName(); int lastDollar = name.lastIndexOf('$'); while (lastDollar != -1) { ResolvedType ret = world.resolve(UnresolvedType.forName(name.substring(0, lastDollar)), true); if (ret != ResolvedType.MISSING) return ret; lastDollar = name.lastIndexOf('$', lastDollar-1); } return null; } public static boolean isVisible(int modifiers, ResolvedType targetType, ResolvedType fromType) { //System.err.println("mod: " + modifiers + ", " + targetType + " and " + fromType); if (Modifier.isPublic(modifiers)) { return true; } else if (Modifier.isPrivate(modifiers)) { return targetType.getOutermostType().equals(fromType.getOutermostType()); } else if (Modifier.isProtected(modifiers)) { return samePackage(targetType, fromType) || targetType.isAssignableFrom(fromType); } else { // package-visible return samePackage(targetType, fromType); } } public static boolean hasBridgeModifier(int modifiers) { return (modifiers & Constants.ACC_BRIDGE)!=0; } private static boolean samePackage( ResolvedType targetType, ResolvedType fromType) { String p1 = targetType.getPackageName(); String p2 = fromType.getPackageName(); if (p1 == null) return p2 == null; if (p2 == null) return false; return p1.equals(p2); } public void addInterTypeMunger(ConcreteTypeMunger munger) { ResolvedMember sig = munger.getSignature(); if (sig == null || munger.getMunger() == null || munger.getMunger().getKind() == ResolvedTypeMunger.PrivilegedAccess) { interTypeMungers.add(munger); return; } //System.err.println("add: " + munger + " to " + this.getClassName() + " with " + interTypeMungers); if (sig.getKind() == Member.METHOD) { if (!compareToExistingMembers(munger, getMethodsWithoutIterator(false) /*getMethods()*/)) return; if (this.isInterface()) { if (!compareToExistingMembers(munger, Arrays.asList(world.getCoreType(OBJECT).getDeclaredMethods()).iterator())) return; } } else if (sig.getKind() == Member.FIELD) { if (!compareToExistingMembers(munger, Arrays.asList(getDeclaredFields()).iterator())) return; } else { if (!compareToExistingMembers(munger, Arrays.asList(getDeclaredMethods()).iterator())) return; } // now compare to existingMungers for (Iterator i = interTypeMungers.iterator(); i.hasNext(); ) { ConcreteTypeMunger existingMunger = (ConcreteTypeMunger)i.next(); if (conflictingSignature(existingMunger.getSignature(), munger.getSignature())) { //System.err.println("match " + munger + " with " + existingMunger); if (isVisible(munger.getSignature().getModifiers(), munger.getAspectType(), existingMunger.getAspectType())) { //System.err.println(" is visible"); int c = compareMemberPrecedence(sig, existingMunger.getSignature()); if (c == 0) { c = getWorld().compareByPrecedenceAndHierarchy(munger.getAspectType(), existingMunger.getAspectType()); } //System.err.println(" compare: " + c); if (c < 0) { // the existing munger dominates the new munger checkLegalOverride(munger.getSignature(), existingMunger.getSignature()); return; } else if (c > 0) { // the new munger dominates the existing one checkLegalOverride(existingMunger.getSignature(), munger.getSignature()); i.remove(); break; } else { interTypeConflictError(munger, existingMunger); interTypeConflictError(existingMunger, munger); return; } } } } //System.err.println("adding: " + munger + " to " + this); interTypeMungers.add(munger); } private boolean compareToExistingMembers(ConcreteTypeMunger munger, List existingMembersList) { return compareToExistingMembers(munger,existingMembersList.iterator()); } //??? returning too soon private boolean compareToExistingMembers(ConcreteTypeMunger munger, Iterator existingMembers) { ResolvedMember sig = munger.getSignature(); while (existingMembers.hasNext()) { ResolvedMember existingMember = (ResolvedMember)existingMembers.next(); //System.err.println("Comparing munger: "+sig+" with member "+existingMember); if (conflictingSignature(existingMember, munger.getSignature())) { //System.err.println("conflict: existingMember=" + existingMember + " typeMunger=" + munger); //System.err.println(munger.getSourceLocation() + ", " + munger.getSignature() + ", " + munger.getSignature().getSourceLocation()); if (isVisible(existingMember.getModifiers(), this, munger.getAspectType())) { int c = compareMemberPrecedence(sig, existingMember); //System.err.println(" c: " + c); if (c < 0) { // existingMember dominates munger checkLegalOverride(munger.getSignature(), existingMember); return false; } else if (c > 0) { // munger dominates existingMember checkLegalOverride(existingMember, munger.getSignature()); //interTypeMungers.add(munger); //??? might need list of these overridden abstracts continue; } else { // bridge methods can differ solely in return type. // FIXME this whole method seems very hokey - unaware of covariance/varargs/bridging - it // could do with a rewrite ! boolean sameReturnTypes = (existingMember.getReturnType().equals(sig.getReturnType())); if (sameReturnTypes) getWorld().getMessageHandler().handleMessage( MessageUtil.error(WeaverMessages.format(WeaverMessages.ITD_MEMBER_CONFLICT,munger.getAspectType().getName(), existingMember), munger.getSourceLocation()) ); } } else if (isDuplicateMemberWithinTargetType(existingMember,this,sig)) { getWorld().getMessageHandler().handleMessage( MessageUtil.error(WeaverMessages.format(WeaverMessages.ITD_MEMBER_CONFLICT,munger.getAspectType().getName(), existingMember), munger.getSourceLocation()) );; } //return; } } return true; } // we know that the member signature matches, but that the member in the target type is not visible to the aspect. // this may still be disallowed if it would result in two members within the same declaring type with the same // signature AND more than one of them is concrete AND they are both visible within the target type. private boolean isDuplicateMemberWithinTargetType(ResolvedMember existingMember, ResolvedType targetType,ResolvedMember itdMember) { if ( (existingMember.isAbstract() || itdMember.isAbstract())) return false; UnresolvedType declaringType = existingMember.getDeclaringType(); if (!targetType.equals(declaringType)) return false; // now have to test that itdMember is visible from targetType if (itdMember.isPrivate()) return false; if (itdMember.isPublic()) return true; // must be in same package to be visible then... if (!targetType.getPackageName().equals(itdMember.getDeclaringType().getPackageName())) return false; // trying to put two members with the same signature into the exact same type..., and both visible in that type. return true; } /** * @return true if the override is legal * note: calling showMessage with two locations issues TWO messages, not ONE message * with an additional source location. */ public boolean checkLegalOverride(ResolvedMember parent, ResolvedMember child) { //System.err.println("check: " + child.getDeclaringType() + " overrides " + parent.getDeclaringType()); if (Modifier.isFinal(parent.getModifiers())) { // XXX horrible test, if we're in eclipes, child.getSourceLocation will be // null, and this message will have already been issued. if (child.getSourceLocation() == null) return false; world.showMessage(Message.ERROR, WeaverMessages.format(WeaverMessages.CANT_OVERRIDE_FINAL_MEMBER,parent), child.getSourceLocation(),null); return false; } boolean incompatibleReturnTypes = false; // In 1.5 mode, allow for covariance on return type if (world.isInJava5Mode() && parent.getKind()==Member.METHOD) { ResolvedType rtParentReturnType = parent.getReturnType().resolve(world); ResolvedType rtChildReturnType = child.getReturnType().resolve(world); incompatibleReturnTypes = !rtParentReturnType.isAssignableFrom(rtChildReturnType); } else { incompatibleReturnTypes =!parent.getReturnType().equals(child.getReturnType()); } if (incompatibleReturnTypes) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ITD_RETURN_TYPE_MISMATCH,parent,child), child.getSourceLocation(), parent.getSourceLocation()); return false; } if (parent.getKind() == Member.POINTCUT) { UnresolvedType[] pTypes = parent.getParameterTypes(); UnresolvedType[] cTypes = child.getParameterTypes(); if (!Arrays.equals(pTypes, cTypes)) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ITD_PARAM_TYPE_MISMATCH,parent,child), child.getSourceLocation(), parent.getSourceLocation()); return false; } } //System.err.println("check: " + child.getModifiers() + " more visible " + parent.getModifiers()); if (isMoreVisible(parent.getModifiers(), child.getModifiers())) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ITD_VISIBILITY_REDUCTION,parent,child), child.getSourceLocation(), parent.getSourceLocation()); return false; } // check declared exceptions ResolvedType[] childExceptions = world.resolve(child.getExceptions()); ResolvedType[] parentExceptions = world.resolve(parent.getExceptions()); ResolvedType runtimeException = world.resolve("java.lang.RuntimeException"); ResolvedType error = world.resolve("java.lang.Error"); outer: for (int i=0, leni = childExceptions.length; i < leni; i++) { //System.err.println("checking: " + childExceptions[i]); if (runtimeException.isAssignableFrom(childExceptions[i])) continue; if (error.isAssignableFrom(childExceptions[i])) continue; for (int j = 0, lenj = parentExceptions.length; j < lenj; j++) { if (parentExceptions[j].isAssignableFrom(childExceptions[i])) continue outer; } // this message is now better handled my MethodVerifier in JDT core. // world.showMessage(IMessage.ERROR, // WeaverMessages.format(WeaverMessages.ITD_DOESNT_THROW,childExceptions[i].getName()), // child.getSourceLocation(), null); return false; } if (parent.isStatic() && !child.isStatic()) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ITD_OVERRIDDEN_STATIC,child,parent), child.getSourceLocation(),null); return false; } else if (child.isStatic() && !parent.isStatic()) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ITD_OVERIDDING_STATIC,child,parent), child.getSourceLocation(),null); return false; } return true; } private int compareMemberPrecedence(ResolvedMember m1, ResolvedMember m2) { //if (!m1.getReturnType().equals(m2.getReturnType())) return 0; // need to allow for the special case of 'clone' - which is like abstract but is // not marked abstract. The code below this next line seems to make assumptions // about what will have gotten through the compiler based on the normal // java rules. clone goes against these... if (m2.isProtected() && m2.isNative() && m2.getName().equals("clone")) return +1; if (Modifier.isAbstract(m1.getModifiers())) return -1; if (Modifier.isAbstract(m2.getModifiers())) return +1; if (m1.getDeclaringType().equals(m2.getDeclaringType())) return 0; ResolvedType t1 = m1.getDeclaringType().resolve(world); ResolvedType t2 = m2.getDeclaringType().resolve(world); if (t1.isAssignableFrom(t2)) { return -1; } if (t2.isAssignableFrom(t1)) { return +1; } return 0; } public static boolean isMoreVisible(int m1, int m2) { if (Modifier.isPrivate(m1)) return false; if (isPackage(m1)) return Modifier.isPrivate(m2); if (Modifier.isProtected(m1)) return /* private package */ (Modifier.isPrivate(m2) || isPackage(m2)); if (Modifier.isPublic(m1)) return /* private package protected */ ! Modifier.isPublic(m2); throw new RuntimeException("bad modifier: " + m1); } private static boolean isPackage(int i) { return (0 == (i & (Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED))); } private void interTypeConflictError( ConcreteTypeMunger m1, ConcreteTypeMunger m2) { //XXX this works only if we ignore separate compilation issues //XXX dual errors possible if (this instanceof BcelObjectType) return; //System.err.println("conflict at " + m2.getSourceLocation()); getWorld().showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ITD_CONFLICT,m1.getAspectType().getName(), m2.getSignature(),m2.getAspectType().getName()), m2.getSourceLocation(), getSourceLocation()); } public ResolvedMember lookupSyntheticMember(Member member) { //??? horribly inefficient //for (Iterator i = //System.err.println("lookup " + member + " in " + interTypeMungers); for (Iterator i = interTypeMungers.iterator(); i.hasNext(); ) { ConcreteTypeMunger m = (ConcreteTypeMunger)i.next(); ResolvedMember ret = m.getMatchingSyntheticMember(member); if (ret != null) { //System.err.println(" found: " + ret); return ret; } } return null; } public void clearInterTypeMungers() { if (isRawType()) getGenericType().clearInterTypeMungers(); interTypeMungers = new ArrayList(); } public boolean isTopmostImplementor(ResolvedType interfaceType) { if (isInterface()) return false; if (!interfaceType.isAssignableFrom(this)) return false; // check that I'm truly the topmost implementor if (interfaceType.isAssignableFrom(this.getSuperclass())) { return false; } return true; } public ResolvedType getTopmostImplementor(ResolvedType interfaceType) { if (isInterface()) return null; if (!interfaceType.isAssignableFrom(this)) return null; // Check if my super class is an implementor? ResolvedType higherType = this.getSuperclass().getTopmostImplementor(interfaceType); if (higherType!=null) return higherType; return this; } private ResolvedType findHigher(ResolvedType other) { if (this == other) return this; for(Iterator i = other.getDirectSupertypes(); i.hasNext(); ) { ResolvedType rtx = (ResolvedType)i.next(); boolean b = this.isAssignableFrom(rtx); if (b) return rtx; } return null; } public List getExposedPointcuts() { List ret = new ArrayList(); if (getSuperclass() != null) ret.addAll(getSuperclass().getExposedPointcuts()); for (Iterator i = Arrays.asList(getDeclaredInterfaces()).iterator(); i.hasNext(); ) { ResolvedType t = (ResolvedType)i.next(); addPointcutsResolvingConflicts(ret, Arrays.asList(t.getDeclaredPointcuts()), false); } addPointcutsResolvingConflicts(ret, Arrays.asList(getDeclaredPointcuts()), true); for (Iterator i = ret.iterator(); i.hasNext(); ) { ResolvedPointcutDefinition inherited = (ResolvedPointcutDefinition)i.next(); // System.err.println("looking at: " + inherited + " in " + this); // System.err.println(" " + inherited.isAbstract() + " in " + this.isAbstract()); if (inherited.isAbstract()) { if (!this.isAbstract()) { getWorld().showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.POINCUT_NOT_CONCRETE,inherited,this.getName()), inherited.getSourceLocation(), this.getSourceLocation()); } } } return ret; } private void addPointcutsResolvingConflicts(List acc, List added, boolean isOverriding) { for (Iterator i = added.iterator(); i.hasNext();) { ResolvedPointcutDefinition toAdd = (ResolvedPointcutDefinition) i.next(); //System.err.println("adding: " + toAdd); for (Iterator j = acc.iterator(); j.hasNext();) { ResolvedPointcutDefinition existing = (ResolvedPointcutDefinition) j.next(); if (existing == toAdd) continue; if (!isVisible(existing.getModifiers(), existing.getDeclaringType().resolve(getWorld()), this)) { continue; } if (conflictingSignature(existing, toAdd)) { if (isOverriding) { checkLegalOverride(existing, toAdd); j.remove(); } else { getWorld().showMessage( IMessage.ERROR, WeaverMessages.format(WeaverMessages.CONFLICTING_INHERITED_POINTCUTS,this.getName() + toAdd.getSignature()), existing.getSourceLocation(), toAdd.getSourceLocation()); j.remove(); } } } acc.add(toAdd); } } public ISourceLocation getSourceLocation() { return null; } public boolean isExposedToWeaver() { return false; } public WeaverStateInfo getWeaverState() { return null; } /** * Overridden by ReferenceType to return a sensible answer for parameterized and raw types. * @return */ public ResolvedType getGenericType() { if (!(isParameterizedType() || isRawType())) throw new BCException("The type "+getBaseName()+" is not parameterized or raw - it has no generic type"); return null; } public ResolvedType parameterizedWith(UnresolvedType[] typeParameters) { if (!(isGenericType() || isParameterizedType())) return this; return TypeFactory.createParameterizedType(this.getGenericType(), typeParameters, getWorld()); } /** * Iff I am a parameterized type, and any of my parameters are type variable * references, return a version with those type parameters replaced in accordance * with the passed bindings. */ public UnresolvedType parameterize(Map typeBindings) { if (!isParameterizedType()) throw new IllegalStateException("Can't parameterize a type that is not a parameterized type"); boolean workToDo = false; for (int i = 0; i < typeParameters.length; i++) { if (typeParameters[i].isTypeVariableReference()) { workToDo = true; } } if (!workToDo) { return this; } else { UnresolvedType[] newTypeParams = new UnresolvedType[typeParameters.length]; for (int i = 0; i < newTypeParams.length; i++) { newTypeParams[i] = typeParameters[i]; if (newTypeParams[i].isTypeVariableReference()) { TypeVariableReferenceType tvrt = (TypeVariableReferenceType) newTypeParams[i]; UnresolvedType binding = (UnresolvedType) typeBindings.get(tvrt.getTypeVariable().getName()); if (binding != null) newTypeParams[i] = binding; } } return TypeFactory.createParameterizedType(getGenericType(), newTypeParams, getWorld()); } } public boolean hasParameterizedSuperType() { getParameterizedSuperTypes(); return parameterizedSuperTypes.length > 0; } public boolean hasGenericSuperType() { ResolvedType[] superTypes = getDeclaredInterfaces(); for (int i = 0; i < superTypes.length; i++) { if (superTypes[i].isGenericType()) return true; } return false; } private ResolvedType[] parameterizedSuperTypes = null; /** * Similar to the above method, but accumulates the super types * @return */ public ResolvedType[] getParameterizedSuperTypes() { if (parameterizedSuperTypes != null) return parameterizedSuperTypes; List accumulatedTypes = new ArrayList(); accumulateParameterizedSuperTypes(this,accumulatedTypes); ResolvedType[] ret = new ResolvedType[accumulatedTypes.size()]; parameterizedSuperTypes = (ResolvedType[]) accumulatedTypes.toArray(ret); return parameterizedSuperTypes; } private void accumulateParameterizedSuperTypes(ResolvedType forType, List parameterizedTypeList) { if (forType.isParameterizedType()) { parameterizedTypeList.add(forType); } if (forType.getSuperclass() != null) { accumulateParameterizedSuperTypes(forType.getSuperclass(), parameterizedTypeList); } ResolvedType[] interfaces = forType.getDeclaredInterfaces(); for (int i = 0; i < interfaces.length; i++) { accumulateParameterizedSuperTypes(interfaces[i], parameterizedTypeList); } } /** * Types may have pointcuts just as they have methods and fields. */ public ResolvedPointcutDefinition findPointcut(String name, World world) { throw new UnsupportedOperationException("Not yet implemenented"); } /** * Determines if variables of this type could be assigned values of another * with lots of help. * java.lang.Object is convertable from all types. * A primitive type is convertable from X iff it's assignable from X. * A reference type is convertable from X iff it's coerceable from X. * In other words, X isConvertableFrom Y iff the compiler thinks that _some_ value of Y * could be assignable to a variable of type X without loss of precision. * * @param other the other type * @param world the {@link World} in which the possible assignment should be checked. * @return true iff variables of this type could be assigned values of other with possible conversion */ public final boolean isConvertableFrom(ResolvedType other) { // // version from TypeX // if (this.equals(OBJECT)) return true; // if (this.isPrimitiveType() || other.isPrimitiveType()) return this.isAssignableFrom(other); // return this.isCoerceableFrom(other); // // version from ResolvedTypeX if (this.equals(OBJECT)) return true; if (world.isInJava5Mode()) { if (this.isPrimitiveType()^other.isPrimitiveType()) { // If one is primitive and the other isnt if (validBoxing.contains(this.getSignature()+other.getSignature())) return true; } } if (this.isPrimitiveType() || other.isPrimitiveType()) return this.isAssignableFrom(other); return this.isCoerceableFrom(other); } /** * Determines if the variables of this type could be assigned values * of another type without casting. This still allows for assignment conversion * as per JLS 2ed 5.2. For object types, this means supertypeOrEqual(THIS, OTHER). * * @param other the other type * @param world the {@link World} in which the possible assignment should be checked. * @return true iff variables of this type could be assigned values of other without casting * @exception NullPointerException if other is null */ public abstract boolean isAssignableFrom(ResolvedType other); /** * Determines if values of another type could possibly be cast to * this type. The rules followed are from JLS 2ed 5.5, "Casting Conversion". * * <p> This method should be commutative, i.e., for all UnresolvedType a, b and all World w: * * <blockquote><pre> * a.isCoerceableFrom(b, w) == b.isCoerceableFrom(a, w) * </pre></blockquote> * * @param other the other type * @param world the {@link World} in which the possible coersion should be checked. * @return true iff values of other could possibly be cast to this type. * @exception NullPointerException if other is null. */ public abstract boolean isCoerceableFrom(ResolvedType other); public boolean needsNoConversionFrom(ResolvedType o) { return isAssignableFrom(o); } /** * Implemented by ReferenceTypes */ public String getSignatureForAttribute() { throw new RuntimeException("Cannot ask this type "+this+" for a generic sig attribute"); } private FuzzyBoolean parameterizedWithAMemberTypeVariable = FuzzyBoolean.MAYBE; /** * return true if the parameterization of this type includes a member type variable. Member * type variables occur in generic methods/ctors. */ public boolean isParameterizedWithAMemberTypeVariable() { // MAYBE means we haven't worked it out yet... if (parameterizedWithAMemberTypeVariable==FuzzyBoolean.MAYBE) { // if there are no type parameters then we cant be... if (typeParameters==null || typeParameters.length==0) { parameterizedWithAMemberTypeVariable = FuzzyBoolean.NO; return false; } for (int i = 0; i < typeParameters.length; i++) { UnresolvedType aType = (ResolvedType)typeParameters[i]; if (aType.isTypeVariableReference() && ((TypeVariableReference)aType).getTypeVariable().getDeclaringElementKind()==TypeVariable.METHOD) { parameterizedWithAMemberTypeVariable = FuzzyBoolean.YES; return true; } if (aType.isParameterizedType()) { boolean b = aType.isParameterizedWithAMemberTypeVariable(); if (b) { parameterizedWithAMemberTypeVariable = FuzzyBoolean.YES; return true; } } if (aType.isGenericWildcard()) { if (aType.isExtends()) { boolean b = false; UnresolvedType upperBound = aType.getUpperBound(); if (upperBound.isParameterizedType()) { b = upperBound.isParameterizedWithAMemberTypeVariable(); } else if (upperBound.isTypeVariableReference() && ((TypeVariableReference)upperBound).getTypeVariable().getDeclaringElementKind()==TypeVariable.METHOD) { b = true; } if (b) { parameterizedWithAMemberTypeVariable = FuzzyBoolean.YES; return true; } // FIXME asc need to check additional interface bounds } if (aType.isSuper()) { boolean b = false; UnresolvedType lowerBound = aType.getLowerBound(); if (lowerBound.isParameterizedType()) { b = lowerBound.isParameterizedWithAMemberTypeVariable(); } else if (lowerBound.isTypeVariableReference() && ((TypeVariableReference)lowerBound).getTypeVariable().getDeclaringElementKind()==TypeVariable.METHOD) { b = true; } if (b) { parameterizedWithAMemberTypeVariable = FuzzyBoolean.YES; return true; } } } } parameterizedWithAMemberTypeVariable=FuzzyBoolean.NO; } return parameterizedWithAMemberTypeVariable.alwaysTrue(); } }
109,016
Bug 109016 NullPointerException when building configuration
The exception below seems to be happening with any .lst file: Message: NullPointerException thrown: null Stack trace: java.lang.NullPointerException at org.aspectj.ajde.internal.CompilerAdapter.configureBuildOptions(CompilerAdapter.java:296) at org.aspectj.ajde.internal.CompilerAdapter.genBuildConfig(CompilerAdapter.java:170) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:95) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191)
resolved fixed
5187437
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-08T19:19:11Z
2005-09-08T00:40:00Z
ajde/src/org/aspectj/ajde/internal/CompilerAdapter.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC), * 2003 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Xerox/PARC initial implementation * AMC 01.20.2003 extended to support new AspectJ 1.1 options, * bugzilla #29769 * ******************************************************************/ package org.aspectj.ajde.internal; import java.io.File; import java.util.*; import org.aspectj.ajde.*; import org.aspectj.ajdt.ajc.*; import org.aspectj.ajdt.internal.core.builder.*; import org.aspectj.bridge.*; import org.aspectj.util.LangUtil; //import org.eclipse.core.runtime.OperationCanceledException; import org.aspectj.org.eclipse.jdt.internal.compiler.impl.CompilerOptions; public class CompilerAdapter { private static final Set DEFAULT__AJDE_WARNINGS; static { DEFAULT__AJDE_WARNINGS = new HashSet(); DEFAULT__AJDE_WARNINGS.add(BuildOptionsAdapter.WARN_ASSERT_IDENITIFIER); DEFAULT__AJDE_WARNINGS.add(BuildOptionsAdapter.WARN_CONSTRUCTOR_NAME); DEFAULT__AJDE_WARNINGS.add(BuildOptionsAdapter.WARN_DEPRECATION); DEFAULT__AJDE_WARNINGS.add(BuildOptionsAdapter.WARN_MASKED_CATCH_BLOCKS); DEFAULT__AJDE_WARNINGS.add(BuildOptionsAdapter.WARN_PACKAGE_DEFAULT_METHOD); DEFAULT__AJDE_WARNINGS.add(BuildOptionsAdapter.WARN_UNUSED_IMPORTS); // DEFAULT__AJDE_WARNINGS.put(BuildOptionsAdapter.WARN_); // DEFAULT__AJDE_WARNINGS.put(BuildOptionsAdapter.WARN_); } // private Map optionsMap; private AjBuildManager buildManager = null; private IMessageHandler messageHandler = null; private BuildNotifierAdapter currNotifier = null; private boolean initialized = false; private boolean structureDirty = true; private boolean showInfoMessages = false; // set to false in incremental mode to re-do initial build private boolean nextBuild = false; public CompilerAdapter() { super(); } public void showInfoMessages(boolean show) { // XXX surface in GUI showInfoMessages = show; } public boolean getShowInfoMessages() { return showInfoMessages; } public void nextBuildFresh() { if (nextBuild) { nextBuild = false; } } public void requestCompileExit() { if (currNotifier != null) { currNotifier.cancelBuild(); } else { signalText("unable to cancel build process"); } } public boolean isStructureDirty() { return structureDirty; } public void setStructureDirty(boolean structureDirty) { this.structureDirty = structureDirty; } public boolean compile(String configFile, BuildProgressMonitor progressMonitor, boolean buildModel) { if (configFile == null) { Ajde.getDefault().getErrorHandler().handleError("Tried to build null config file."); } init(); try { AjBuildConfig buildConfig = genBuildConfig(configFile); if (buildConfig == null) { return false; } buildConfig.setGenerateModelMode(buildModel); currNotifier = new BuildNotifierAdapter(progressMonitor, buildManager); buildManager.setProgressListener(currNotifier); String rtInfo = buildManager.checkRtJar(buildConfig); // !!! will get called twice if (rtInfo != null) { Ajde.getDefault().getErrorHandler().handleWarning( "AspectJ Runtime error: " + rtInfo + " Please place a valid aspectjrt.jar on the classpath."); return false; } boolean incrementalEnabled = buildConfig.isIncrementalMode() || buildConfig.isIncrementalFileMode(); boolean successfulBuild; if (incrementalEnabled && nextBuild) { successfulBuild = buildManager.incrementalBuild(buildConfig, messageHandler); } else { if (incrementalEnabled) { nextBuild = incrementalEnabled; } successfulBuild = buildManager.batchBuild(buildConfig, messageHandler); } IncrementalStateManager.recordSuccessfulBuild(configFile,buildManager.getState()); return successfulBuild; // } catch (OperationCanceledException ce) { // Ajde.getDefault().getErrorHandler().handleWarning( // "build cancelled by user"); // return false; } catch (AbortException e) { final IMessage message = e.getIMessage(); if (null == message) { signalThrown(e); } else if (null != message.getMessage()) { Ajde.getDefault().getErrorHandler().handleWarning(message.getMessage()); } else if (null != message.getThrown()) { signalThrown(message.getThrown()); } else { signalThrown(e); } return false; } catch (Throwable t) { signalThrown(t); return false; } } /** * Generate AjBuildConfig from the local configFile parameter * plus global project and build options. * Errors signalled using signal... methods. * @param configFile * @return null if invalid configuration, * corresponding AjBuildConfig otherwise */ public AjBuildConfig genBuildConfig(String configFilePath) { init(); File configFile = new File(configFilePath); if (!configFile.exists()) { Ajde.getDefault().getErrorHandler().handleError( "Config file \"" + configFile + "\" does not exist." ); return null; } String[] args = new String[] { "@" + configFile.getAbsolutePath() }; CountingMessageHandler handler = CountingMessageHandler.makeCountingMessageHandler(messageHandler); BuildArgParser parser = new BuildArgParser(handler); AjBuildConfig config = new AjBuildConfig(); parser.populateBuildConfig(config, args, false, configFile); configureBuildOptions(config,Ajde.getDefault().getBuildManager().getBuildOptions(),handler); configureProjectOptions(config, Ajde.getDefault().getProjectProperties()); // !!! not what the API intended // // -- get globals, treat as defaults used if no local values // AjBuildConfig global = new AjBuildConfig(); // // AMC refactored into two methods to populate buildConfig from buildOptions and // // project properties - bugzilla 29769. // BuildOptionsAdapter buildOptions // = Ajde.getDefault().getBuildManager().getBuildOptions(); // if (!configureBuildOptions(/* global */ config, buildOptions, handler)) { // return null; // } // ProjectPropertiesAdapter projectOptions = // Ajde.getDefault().getProjectProperties(); // configureProjectOptions(global, projectOptions); // config.installGlobals(global); ISourceLocation location = null; if (config.getConfigFile() != null) { location = new SourceLocation(config.getConfigFile(), 0); } String message = parser.getOtherMessages(true); if (null != message) { IMessage m = new Message(message, IMessage.ERROR, null, location); handler.handleMessage(m); } // always force model generation in AJDE config.setGenerateModelMode(true); if (Ajde.getDefault().getBuildManager().getBuildOptions().getJavaOptionsMap() != null) { config.getOptions().set(Ajde.getDefault().getBuildManager().getBuildOptions().getJavaOptionsMap()); } return config; // return fixupBuildConfig(config); } // /** // * Fix up build configuration just before using to compile. // * This should be delegated to a BuildAdapter callback (XXX) // * for implementation-specific value checks // * (e.g., to force use of project classpath rather // * than local config classpath). // * This implementation does no checks and returns local. // * @param local the AjBuildConfig generated to validate // * @param global // * @param buildOptions // * @param projectOptions // * @return null if unable to fix problems or fixed AjBuildConfig if no errors // * // */ // protected AjBuildConfig fixupBuildConfig(AjBuildConfig local) { // if (Ajde.getDefault().getBuildManager().getBuildOptions().getJavaOptionsMap() != null) { // local.getJavaOptions().putAll(Ajde.getDefault().getBuildManager().getBuildOptions().getJavaOptionsMap()); // } // return local; // } // /** signal error text to user */ // protected void signalError(String text) { // } // /** signal warning text to user */ // protected void signalWarning(String text) { // // } /** signal text to user */ protected void signalText(String text) { Ajde.getDefault().getIdeUIAdapter().displayStatusInformation(text); } /** signal Throwable to user (summary in GUI, trace to stdout). */ protected void signalThrown(Throwable t) { // nothing to error handler? String text = LangUtil.unqualifiedClassName(t) + " thrown: " + t.getMessage(); Ajde.getDefault().getErrorHandler().handleError(text, t); } /** * Populate options in a build configuration, using the Ajde BuildOptionsAdapter. * Added by AMC 01.20.2003, bugzilla #29769 */ private static boolean configureBuildOptions( AjBuildConfig config, BuildOptionsAdapter options, IMessageHandler handler) { LangUtil.throwIaxIfNull(options, "options"); LangUtil.throwIaxIfNull(config, "config"); Map optionsToSet = new HashMap(); LangUtil.throwIaxIfNull(optionsToSet, "javaOptions"); if (options.getSourceCompatibilityLevel() != null && options.getSourceCompatibilityLevel().equals(CompilerOptions.VERSION_1_5)) { optionsToSet.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_5); optionsToSet.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_5); } else if (options.getSourceOnePointFourMode() || options.getSourceCompatibilityLevel() != null && options.getSourceCompatibilityLevel().equals(CompilerOptions.VERSION_1_4)) { optionsToSet.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_4); optionsToSet.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_4); } String enc = options.getCharacterEncoding(); if (!LangUtil.isEmpty(enc)) { optionsToSet.put(CompilerOptions.OPTION_Encoding, enc ); } String compliance = options.getComplianceLevel(); if (!LangUtil.isEmpty(compliance)) { String version = CompilerOptions.VERSION_1_4; if ( compliance.equals( BuildOptionsAdapter.VERSION_13 ) ) { version = CompilerOptions.VERSION_1_3; } optionsToSet.put(CompilerOptions.OPTION_Compliance, version ); optionsToSet.put(CompilerOptions.OPTION_Source, version ); } String sourceLevel = options.getSourceCompatibilityLevel(); if (!LangUtil.isEmpty(sourceLevel)) { String slVersion = CompilerOptions.VERSION_1_4; if ( sourceLevel.equals( BuildOptionsAdapter.VERSION_13 ) ) { slVersion = CompilerOptions.VERSION_1_3; } // never set a lower source level than compliance level // Mik: prepended with 1.5 check if (sourceLevel.equals(CompilerOptions.VERSION_1_5)) { optionsToSet.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_5); } else { String setCompliance = (String) optionsToSet.get( CompilerOptions.OPTION_Compliance); if ( ! (setCompliance.equals(CompilerOptions.VERSION_1_4 ) && slVersion.equals(CompilerOptions.VERSION_1_3)) ) { optionsToSet.put(CompilerOptions.OPTION_Source, slVersion); } } } Set warnings = options.getWarnings(); if (!LangUtil.isEmpty(warnings)) { // turn off all warnings disableWarnings( optionsToSet ); // then selectively enable those in the set enableWarnings( optionsToSet, warnings ); } else if (warnings == null) { // set default warnings on... enableWarnings( optionsToSet, DEFAULT__AJDE_WARNINGS); } Set debugOptions = options.getDebugLevel(); if (!LangUtil.isEmpty(debugOptions)) { // default is all options on, so just need to selectively // disable boolean sourceLine = false; boolean varAttr = false; boolean lineNo = false; Iterator it = debugOptions.iterator(); while (it.hasNext()){ String debug = (String) it.next(); if ( debug.equals( BuildOptionsAdapter.DEBUG_ALL )) { sourceLine = true; varAttr = true; lineNo = true; } else if ( debug.equals( BuildOptionsAdapter.DEBUG_LINES )) { lineNo = true; } else if ( debug.equals( BuildOptionsAdapter.DEBUG_SOURCE )) { sourceLine = true; } else if ( debug.equals( BuildOptionsAdapter.DEBUG_VARS)) { varAttr = true; } } if (sourceLine) optionsToSet.put(CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE); if (varAttr) optionsToSet.put(CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.GENERATE); if (lineNo) optionsToSet.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE); } //XXX we can't turn off import errors in 3.0 stream // if ( options.getNoImportError() ) { // javaOptions.put( CompilerOptions.OPTION_ReportInvalidImport, // CompilerOptions.WARNING); // } if ( options.getPreserveAllLocals() ) { optionsToSet.put( CompilerOptions.OPTION_PreserveUnusedLocal, CompilerOptions.PRESERVE); } if ( !config.isIncrementalMode() && options.getIncrementalMode() ) { config.setIncrementalMode(true); } Map jom = options.getJavaOptionsMap(); if (jom!=null) { String version = (String)jom.get(CompilerOptions.OPTION_Compliance); if (version!=null && version.equals(CompilerOptions.VERSION_1_5)) { config.setBehaveInJava5Way(true); } } config.getOptions().set(optionsToSet); String toAdd = options.getNonStandardOptions(); return LangUtil.isEmpty(toAdd) ? true : configureNonStandardOptions( config, toAdd, handler ); // ignored: lenient, porting, preprocess, strict, usejavac, workingdir } /** * Helper method for configureBuildOptions */ private static void disableWarnings( Map options ) { options.put( CompilerOptions.OPTION_ReportOverridingPackageDefaultMethod, CompilerOptions.IGNORE); options.put( CompilerOptions.OPTION_ReportMethodWithConstructorName, CompilerOptions.IGNORE); options.put( CompilerOptions.OPTION_ReportDeprecation, CompilerOptions.IGNORE); options.put( CompilerOptions.OPTION_ReportHiddenCatchBlock, CompilerOptions.IGNORE); options.put( CompilerOptions.OPTION_ReportUnusedLocal, CompilerOptions.IGNORE); options.put( CompilerOptions.OPTION_ReportUnusedParameter, CompilerOptions.IGNORE); options.put( CompilerOptions.OPTION_ReportSyntheticAccessEmulation, CompilerOptions.IGNORE); options.put( CompilerOptions.OPTION_ReportNonExternalizedStringLiteral, CompilerOptions.IGNORE); options.put( CompilerOptions.OPTION_ReportAssertIdentifier, CompilerOptions.IGNORE); options.put( CompilerOptions.OPTION_ReportUnusedImport, CompilerOptions.IGNORE); } /** * Helper method for configureBuildOptions */ private static void enableWarnings( Map options, Set warnings ) { Iterator it = warnings.iterator(); while (it.hasNext() ) { String thisWarning = (String) it.next(); if ( thisWarning.equals( BuildOptionsAdapter.WARN_ASSERT_IDENITIFIER )) { options.put( CompilerOptions.OPTION_ReportAssertIdentifier, CompilerOptions.WARNING ); } else if ( thisWarning.equals( BuildOptionsAdapter.WARN_CONSTRUCTOR_NAME )) { options.put( CompilerOptions.OPTION_ReportMethodWithConstructorName, CompilerOptions.WARNING ); } else if ( thisWarning.equals( BuildOptionsAdapter.WARN_DEPRECATION )) { options.put( CompilerOptions.OPTION_ReportDeprecation, CompilerOptions.WARNING ); } else if ( thisWarning.equals( BuildOptionsAdapter.WARN_MASKED_CATCH_BLOCKS )) { options.put( CompilerOptions.OPTION_ReportHiddenCatchBlock, CompilerOptions.WARNING ); } else if ( thisWarning.equals( BuildOptionsAdapter.WARN_PACKAGE_DEFAULT_METHOD )) { options.put( CompilerOptions.OPTION_ReportOverridingPackageDefaultMethod, CompilerOptions.WARNING ); } else if ( thisWarning.equals( BuildOptionsAdapter.WARN_SYNTHETIC_ACCESS )) { options.put( CompilerOptions.OPTION_ReportSyntheticAccessEmulation, CompilerOptions.WARNING ); } else if ( thisWarning.equals( BuildOptionsAdapter.WARN_UNUSED_ARGUMENTS )) { options.put( CompilerOptions.OPTION_ReportUnusedParameter, CompilerOptions.WARNING ); } else if ( thisWarning.equals( BuildOptionsAdapter.WARN_UNUSED_IMPORTS )) { options.put( CompilerOptions.OPTION_ReportUnusedImport, CompilerOptions.WARNING ); } else if ( thisWarning.equals( BuildOptionsAdapter.WARN_UNUSED_LOCALS )) { options.put( CompilerOptions.OPTION_ReportUnusedLocal, CompilerOptions.WARNING ); } else if ( thisWarning.equals( BuildOptionsAdapter.WARN_NLS )) { options.put( CompilerOptions.OPTION_ReportNonExternalizedStringLiteral, CompilerOptions.WARNING ); } } } /** Local helper method for splitting option strings */ private static List tokenizeString(String str) { List tokens = new ArrayList(); StringTokenizer tok = new StringTokenizer(str); while ( tok.hasMoreTokens() ) { tokens.add(tok.nextToken()); } return tokens; } /** * Helper method for configure build options. * This reads all command-line options specified * in the non-standard options text entry and * sets any corresponding unset values in config. * @return false if config failed */ private static boolean configureNonStandardOptions( AjBuildConfig config, String nonStdOptions, IMessageHandler messageHandler ) { if (LangUtil.isEmpty(nonStdOptions)) { return true; } // Break a string into a string array of non-standard options. // Allows for one option to include a ' '. i.e. assuming it has been quoted, it // won't accidentally get treated as a pair of options (can be needed for xlint props file option) List tokens = new ArrayList(); int ind = nonStdOptions.indexOf('\"'); int ind2 = nonStdOptions.indexOf('\"',ind+1); if ((ind > -1) && (ind2 > -1)) { // dont tokenize within double quotes String pre = nonStdOptions.substring(0,ind); String quoted = nonStdOptions.substring(ind+1,ind2); String post = nonStdOptions.substring(ind2+1,nonStdOptions.length()); tokens.addAll(tokenizeString(pre)); tokens.add(quoted); tokens.addAll(tokenizeString(post)); } else { tokens.addAll(tokenizeString(nonStdOptions)); } String[] args = (String[])tokens.toArray(new String[]{}); // set the non-standard options in an alternate build config // (we don't want to lose the settings we already have) CountingMessageHandler counter = CountingMessageHandler.makeCountingMessageHandler(messageHandler); AjBuildConfig altConfig = AjdtCommand.genBuildConfig(args, counter); if (counter.hasErrors()) { return false; } // copy globals where local is not set config.installGlobals(altConfig); return true; } /** * Add new options from the ProjectPropertiesAdapter to the configuration. * <ul> * <li>New list entries are added if not duplicates in, * for classpath, aspectpath, injars, inpath and sourceroots</li> * <li>Set only one new entry for output dir or output jar * only if there is no output dir/jar entry in the config</li> * </ul> * Subsequent changes to the ProjectPropertiesAdapter will not affect * the configuration. * <p>Added by AMC 01.20.2003, bugzilla #29769 */ private void configureProjectOptions( AjBuildConfig config, ProjectPropertiesAdapter properties ) { // XXX no error handling in copying project properties // Handle regular classpath String propcp = properties.getClasspath(); if (!LangUtil.isEmpty(propcp)) { StringTokenizer st = new StringTokenizer(propcp, File.pathSeparator); List configClasspath = config.getClasspath(); ArrayList toAdd = new ArrayList(); while (st.hasMoreTokens()) { String entry = st.nextToken(); if (!configClasspath.contains(entry)) { toAdd.add(entry); } } if (0 < toAdd.size()) { ArrayList both = new ArrayList(configClasspath.size() + toAdd.size()); both.addAll(configClasspath); both.addAll(toAdd); config.setClasspath(both); Ajde.getDefault().logEvent("building with classpath: " + both); } } // Handle boot classpath propcp = properties.getBootClasspath(); if (!LangUtil.isEmpty(propcp)) { StringTokenizer st = new StringTokenizer(propcp, File.pathSeparator); List configClasspath = config.getBootclasspath(); ArrayList toAdd = new ArrayList(); while (st.hasMoreTokens()) { String entry = st.nextToken(); if (!configClasspath.contains(entry)) { toAdd.add(entry); } } if (0 < toAdd.size()) { ArrayList both = new ArrayList(configClasspath.size() + toAdd.size()); both.addAll(configClasspath); both.addAll(toAdd); config.setBootclasspath(both); Ajde.getDefault().logEvent("building with boot classpath: " + both); } } // set outputdir and outputjar only if both not set if ((null == config.getOutputDir() && (null == config.getOutputJar()))) { String outPath = properties.getOutputPath(); if (!LangUtil.isEmpty(outPath)) { config.setOutputDir(new File(outPath)); } String outJar = properties.getOutJar(); if (!LangUtil.isEmpty(outJar)) { config.setOutputJar(new File( outJar ) ); } } join(config.getSourceRoots(), properties.getSourceRoots()); join(config.getInJars(), properties.getInJars()); join(config.getInpath(),properties.getInpath()); config.setSourcePathResources(properties.getSourcePathResources()); join(config.getAspectpath(), properties.getAspectPath()); } void join(Collection target, Collection source) { // XXX dup Util if ((null == target) || (null == source)) { return; } for (Iterator iter = source.iterator(); iter.hasNext();) { Object next = iter.next(); if (! target.contains(next)) { target.add(next); } } } private void init() { if (!initialized) { // XXX plug into AJDE initialization // Ajde.getDefault().setErrorHandler(new DebugErrorHandler()); if (Ajde.getDefault().getMessageHandler() != null) { this.messageHandler = Ajde.getDefault().getMessageHandler(); } else { this.messageHandler = new MessageHandlerAdapter(); } buildManager = new AjBuildManager(messageHandler); // XXX need to remove the properties file each time! initialized = true; } } class MessageHandlerAdapter extends MessageHandler { private TaskListManager taskListManager; public MessageHandlerAdapter() { this.taskListManager = Ajde.getDefault().getTaskListManager(); } public boolean handleMessage(IMessage message) throws AbortException { IMessage.Kind kind = message.getKind(); if (isIgnoring(kind) || (!showInfoMessages && IMessage.INFO.equals(kind))) { return true; } taskListManager.addSourcelineTask(message); return super.handleMessage(message); // also store... } } public void setState(AjState buildState) { buildManager.setState(buildState); buildManager.setStructureModel(buildState.getStructureModel()); } }
109,124
Bug 109124 VerifyError with inner classes
null
resolved fixed
a9ca915
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-09T10:48:58Z
2005-09-09T10:00:00Z
tests/src/org/aspectj/systemtest/ajc150/Ajc150Tests.java
/******************************************************************************* * Copyright (c) 2004 IBM * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Andy Clement - initial API and implementation *******************************************************************************/ package org.aspectj.systemtest.ajc150; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import junit.framework.Test; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.apache.bcel.classfile.Method; import org.aspectj.apache.bcel.util.ClassPath; import org.aspectj.apache.bcel.util.SyntheticRepository; import org.aspectj.asm.AsmManager; import org.aspectj.testing.XMLBasedAjcTestCase; import org.aspectj.util.LangUtil; /** * These are tests that will run on Java 1.4 and use the old harness format for test specification. */ public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase { public static Test suite() { return XMLBasedAjcTestCase.loadSuite(Ajc150Tests.class); } protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml"); } public void test_typeProcessingOrderWhenDeclareParents() { runTest("Order of types passed to compiler determines weaving behavior"); } public void test_aroundMethod() { runTest("method called around in class"); } public void test_aroundMethodAspect() { runTest("method called around in aspect"); } public void test_ambiguousBindingsDetection() { runTest("Various kinds of ambiguous bindings"); } public void test_ambiguousArgsDetection() { runTest("ambiguous args"); } public void testIncorrectExceptionTableWhenBreakInMethod_pr78021() { runTest("Injecting exception into while loop with break statement causes catch block to be ignored"); } public void testIncorrectExceptionTableWhenReturnInMethod_pr79554() { runTest("Return in try-block disables catch-block if final-block is present"); } public void testMissingDebugInfoForGeneratedMethods_pr82570() throws ClassNotFoundException { runTest("Weaved code does not include debug lines"); boolean f = false; JavaClass jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1"); Method[] meths = jc.getMethods(); for (int i = 0; i < meths.length; i++) { Method method = meths[i]; if (f) System.err.println("Line number table for "+method.getName()+method.getSignature()+" = "+method.getLineNumberTable()); assertTrue("Didn't find a line number table for method "+method.getName()+method.getSignature(), method.getLineNumberTable()!=null); } // This test would determine the info isn't there if you pass -g:none ... // cR = ajc(baseDir,new String[]{"PR82570_1.java","-g:none"}); // assertTrue("Expected no compile problem:"+cR,!cR.hasErrorMessages()); // System.err.println(cR.getStandardError()); // jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1"); // meths = jc.getMethods(); // for (int i = 0; i < meths.length; i++) { // Method method = meths[i]; // assertTrue("Found a line number table for method "+method.getName(), // method.getLineNumberTable()==null); // } } public void testCanOverrideProtectedMethodsViaITDandDecp_pr83303() { runTest("compiler error when mixing inheritance, overriding and polymorphism"); } public void testPerTypeWithinMissesNamedInnerTypes() { runTest("pertypewithin() handing of inner classes (1)"); } public void testPerTypeWithinMissesAnonymousInnerTypes() { runTest("pertypewithin() handing of inner classes (2)"); } public void testPerTypeWithinIncorrectlyMatchingInterfaces() { runTest("pertypewithin({interface}) illegal field modifier"); } public void test051_arrayCloningInJava5() { runTest("AJC possible bug with static nested classes"); } public void testBadASMforEnums() throws IOException { runTest("bad asm for enums"); if (LangUtil.is15VMOrGreater()) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintWriter pw = new PrintWriter(baos); AsmManager.dumptree(pw,AsmManager.getDefault().getHierarchy().getRoot(),0); pw.flush(); String tree = baos.toString(); assertTrue("Expected 'Red [enumvalue]' somewhere in here:"+tree,tree.indexOf("Red [enumvalue]")!=-1); } } public void npeOnTypeNotFound() { runTest("structure model npe on type not found"); } public void testNoRuntimeExceptionSoftening() { runTest("declare soft of runtime exception"); } public void testRuntimeNoSoftenWithHandler() { runTest("declare soft w. catch block"); } public void testSyntaxError() { runTest("invalid cons syntax"); } public void testVarargsInConsBug() { runTest("varargs in constructor sig"); } public void testAspectpathdirs() { runTest("dirs on aspectpath"); } public void testIntroSample() { runTest("introduction sample"); } public void testPTWInterface() { runTest("pertypewithin({interface}) illegal field modifier"); } public void testEnumCalledEnumEtc() { runTest("enum called Enum, annotation called Annotation, etc"); } public void testInternalCompilerError_pr86832() { runTest("Internal compiler error"); } public void testCloneMethod_pr83311() { runTest("overriding/polymorphism error on interface method introduction"); } /** * IfPointcut.findResidueInternal() was modified to make this test complete in a short amount * of time - if you see it hanging, someone has messed with the optimization. */ public void testIfEvaluationExplosion_pr94086() { runTest("Exploding compile time with if() statements in pointcut"); } public void testReflectNPE_pr94167() {runTest("NPE in reflect implementation");} public void testStaticImports_pr84260() {runTest("static import failures");} public void testGenerics_pr99089() {runTest("ArrayIndexOutOfBoundsException - Generics in privileged aspects");} public void testGenerics_pr95993() {runTest("NPE at ClassScope.java:660 when compiling generic class");} public void testItdGenerics_pr99228() {runTest("ITD of a field into a generic class");} public void testItdGenerics_pr98320() {runTest("intertype with nested generic type");} public void testItdGenerics_pr100227() {runTest("inner class with generic enclosing class");} public void testItdGenerics_pr100260() {runTest("methods inherited from a generic parent");} public void testSyntaxErrorNPE_pr103266() {runTest("NPE on syntax error");} public void testIllegalStateExceptionOnNestedParameterizedType_pr106634() { runTest("IllegalStateException unpacking signature of nested parameterized type"); } public void testParseErrorOnAnnotationStarPlusPattern() { runTest("(@Foo *)+ type pattern parse error"); } public void test_pr106130_tooManyLocals() { runTest("test weaving with > 256 locals"); } public void testMissingNamePattern_pr106461() { runTest("missing name pattern"); } public void testMissingNamePattern_pr107059() { runTest("parser crashes on call(void (@a *)(..)"); } public void testIntermediateAnnotationMatching() { runTest("intermediate annotation matching"); } public void testBadRuntimeTestGeneration() { runTest("target(@Foo *)"); } public void testErrorMessageOnITDWithTypePatterns() { runTest("clear error message on itd with type pattern"); } public void testAjKeywordsAsIdentifiers() { runTest("before and after are valid identifiers in classes"); } public void testAjKeywordsAsIdentifiers2() { runTest("before and after are valid identifiers in classes, part 2"); } public void testNoBeforeReturningAdvice() { runTest("before returning advice not allowed!"); } public void testDetectVoidFieldType() { runTest("void field type in pointcut expression"); } public void testPointcutOverriding() { runTest("overriding final pointcut from super-aspect"); } public void testAtSuppressWarnings() { runTest("@SuppressWarnings should suppress"); } public void testDEOWWithBindingPointcut() { runTest("declare warning : foo(str) : ...;"); } public void testAroundAdviceAndInterfaceInitializer() { runTest("around advice on interface initializer"); } public void testGoodErrorMessageOnUnmatchedMemberSyntax() { runTest("good error message for unmatched member syntax"); } public void testITDWithNoExceptionAndIntermediary() { runTest("itd override with no exception clause"); } public void testAnonymousInnerClasses() { runTest("anonymous inner classes"); } public void testMultipleAnonymousInnerClasses() { runTest("multiple anonymous inner classes"); } public void testPrivilegedMethodAccessorsGetRightExceptions_pr82989() { runTest("Compiler error due to a wrong exception check in try blocks"); } public void testAnonymousInnerClassWithMethodReturningTypeParameter_pr107898() { runTest("anonymous inner class with method returning type parameter"); } public void testMatchingOfObjectArray() { runTest("matching against Object[]"); } public void testMultipleAnonymousInnerClasses_pr108104() { runTest("multiple anonymous inner classes 2"); } public void testSignatureMatchingInMultipleOverrideScenario() { runTest("signature matching in override scenario"); } public void testWildcardAnnotationMatching_pr108245() { runTest("wildcard annotation matching - pr108245"); } public void testInnerTypesAndTypeVariables() { runTest("inner types and type variables"); } public void testAtAfterThrowingWithNoFormal() { runTest("@AfterThrowing with no formal specified"); } public void testParameterizedVarArgsMatch() { runTest("varargs with type variable"); } public void testFieldAccessInsideITDM() { runTest("itd field access inside itd method"); } public void testTypeVarWithTypeVarBound() { runTest("type variable with type variable bound"); } public void testEnumSwitchInITD() { runTest("switch on enum inside ITD method"); } public void testInnerTypeOfGeneric() { runTest("inner type of generic interface reference from parameterized type"); } public void testDeclareParentsIntroducingCovariantReturnType() { runTest("declare parents introducing override with covariance"); } public void testInnerClassPassedToVarargs() { runTest("inner class passed as argument to varargs method"); } public void testInlinedFieldAccessInProceedCall() { runTest("inlined field access in proceed call"); } public void testVisibiltyInSignatureMatchingWithOverridesPart1() { runTest("visibility in signature matching with overrides - 1"); } public void testVisibiltyInSignatureMatchingWithOverridesPart2() { runTest("visibility in signature matching with overrides - 2"); } public void testVisibiltyInSignatureMatchingWithOverridesPart3() { runTest("visibility in signature matching with overrides - 3"); } public void testArgsGeneratedCorrectlyForAdviceExecution() { runTest("args generated correctly for advice execution join point"); } public void testNoUnusedWarningsOnAspectTypes() { runTest("no unused warnings on aspect types"); } public void testSyntheticArgumentsOnITDConstructorsNotUsedInMatching() { runTest("synthetic arguments on itd cons are not used in matching"); } public void testParsingOfGenericTypeSignature() { runTest("parse generic type signature with parameterized type in interface"); } public void testOverrideAndCovarianceWithDecPRuntime() { runTest("override and covariance with decp - runtime"); } public void testOverrideAndCovarianceWithDecPRuntimeMultiFiles() { runTest("override and covariance with decp - runtime separate files"); } public void testAbstractSynchronizedITDMethods() { runTest("abstract synchronized itdms not detected"); } public void testSynchronizedITDInterfaceMethods() { runTest("synchronized itd interface methods"); } public void testNoWarningOnUnusedPointcut() { runTest("unused private pointcuts"); } public void testITDOnInterfaceWithExistingMember() { runTest("itd interface method already existing on interface"); } public void testFinalITDMOnInterface() { runTest("final itd methods on interfaces"); } public void testPrivatePointcutOverriding() { runTest("can't override private pointcut in abstract aspect"); } public void testAdviceOnCflow() { runTest("advising cflow advice execution"); } public void testNoTypeMismatchOnSameGenericTypes() { runTest("no type mismatch on generic types in itds"); } public void testSuperCallInITD() { runTest("super call in ITD"); } public void testNoUnusedParameterWarningsForSyntheticAdviceArgs() { runTest("no unused parameter warnings for synthetic advice args"); } // helper methods..... public SyntheticRepository createRepos(File cpentry) { ClassPath cp = new ClassPath(cpentry+File.pathSeparator+System.getProperty("java.class.path")); return SyntheticRepository.getInstance(cp); } protected JavaClass getClassFrom(File where,String clazzname) throws ClassNotFoundException { SyntheticRepository repos = createRepos(where); return repos.loadClass(clazzname); } }
109,124
Bug 109124 VerifyError with inner classes
null
resolved fixed
a9ca915
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-09T10:48:58Z
2005-09-09T10:00:00Z
weaver/src/org/aspectj/weaver/bcel/BcelField.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.bcel; import java.util.HashSet; import java.util.Iterator; import java.util.List; import org.aspectj.apache.bcel.classfile.Attribute; import org.aspectj.apache.bcel.classfile.Field; import org.aspectj.apache.bcel.classfile.GenericSignatureParser; import org.aspectj.apache.bcel.classfile.Signature; import org.aspectj.apache.bcel.classfile.Synthetic; import org.aspectj.apache.bcel.classfile.annotation.Annotation; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.AnnotationX; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ResolvedMemberImpl; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.World; import org.aspectj.weaver.bcel.BcelGenericSignatureToTypeXConverter.GenericSignatureFormatException; final class BcelField extends ResolvedMemberImpl { private Field field; private boolean isAjSynthetic; private boolean isSynthetic = false; private AnnotationX[] annotations; private World world; private BcelObjectType bcelObjectType; private UnresolvedType genericFieldType = null; private boolean unpackedGenericSignature = false; BcelField(BcelObjectType declaringType, Field field) { super( FIELD, declaringType.getResolvedTypeX(), field.getAccessFlags(), field.getName(), field.getSignature()); this.field = field; this.world = declaringType.getResolvedTypeX().getWorld(); this.bcelObjectType = declaringType; unpackAttributes(world); checkedExceptions = UnresolvedType.NONE; } // ---- private void unpackAttributes(World world) { Attribute[] attrs = field.getAttributes(); List as = BcelAttributes.readAjAttributes(getDeclaringType().getClassName(),attrs, getSourceContext(world),world.getMessageHandler(),bcelObjectType.getWeaverVersionAttribute()); as.addAll(AtAjAttributes.readAj5FieldAttributes(field, world.resolve(getDeclaringType()), getSourceContext(world), world.getMessageHandler())); for (Iterator iter = as.iterator(); iter.hasNext();) { AjAttribute a = (AjAttribute) iter.next(); if (a instanceof AjAttribute.AjSynthetic) { isAjSynthetic = true; } else { throw new BCException("weird field attribute " + a); } } isAjSynthetic = false; for (int i = attrs.length - 1; i >= 0; i--) { if (attrs[i] instanceof Synthetic) isSynthetic = true; } } public boolean isAjSynthetic() { return isAjSynthetic; // || getName().startsWith(NameMangler.PREFIX); } public boolean isSynthetic() { return isSynthetic; } public boolean hasAnnotation(UnresolvedType ofType) { ensureAnnotationTypesRetrieved(); for (Iterator iter = annotationTypes.iterator(); iter.hasNext();) { ResolvedType aType = (ResolvedType) iter.next(); if (aType.equals(ofType)) return true; } return false; } public ResolvedType[] getAnnotationTypes() { ensureAnnotationTypesRetrieved(); ResolvedType[] ret = new ResolvedType[annotationTypes.size()]; annotationTypes.toArray(ret); return ret; } private void ensureAnnotationTypesRetrieved() { if (annotationTypes == null) { Annotation annos[] = field.getAnnotations(); annotationTypes = new HashSet(); annotations = new AnnotationX[annos.length]; for (int i = 0; i < annos.length; i++) { Annotation annotation = annos[i]; ResolvedType rtx = world.resolve(UnresolvedType.forName(annotation.getTypeName())); annotationTypes.add(rtx); annotations[i] = new AnnotationX(annotation,world); } } } public void addAnnotation(AnnotationX annotation) { ensureAnnotationTypesRetrieved(); // Add it to the set of annotations int len = annotations.length; AnnotationX[] ret = new AnnotationX[len+1]; System.arraycopy(annotations, 0, ret, 0, len); ret[len] = annotation; annotations = ret; // Add it to the set of annotation types annotationTypes.add(UnresolvedType.forName(annotation.getTypeName()).resolve(world)); // FIXME asc this call here suggests we are managing the annotations at // too many levels, here in BcelField we keep a set and in the lower 'field' // object we keep a set - we should think about reducing this to one // level?? field.addAnnotation(annotation.getBcelAnnotation()); } /** * Unpack the generic signature attribute if there is one and we haven't already * done so, then find the true field type of this field (eg. List<String>). */ public UnresolvedType getGenericReturnType() { unpackGenericSignature(); return genericFieldType; } private void unpackGenericSignature() { if (unpackedGenericSignature) return; unpackedGenericSignature = true; String gSig = field.getGenericSignature(); if (gSig != null) { // get from generic Signature.FieldTypeSignature fts = new GenericSignatureParser().parseAsFieldSignature(gSig); Signature.ClassSignature genericTypeSig = bcelObjectType.getGenericClassTypeSignature(); Signature.FormalTypeParameter[] parentFormals = bcelObjectType.getAllFormals(); Signature.FormalTypeParameter[] typeVars = ((genericTypeSig == null) ? new Signature.FormalTypeParameter[0] : genericTypeSig.formalTypeParameters); Signature.FormalTypeParameter[] formals = new Signature.FormalTypeParameter[parentFormals.length + typeVars.length]; // put method formal in front of type formals for overriding in // lookup System.arraycopy(typeVars, 0, formals, 0, typeVars.length); System.arraycopy(parentFormals, 0, formals, typeVars.length,parentFormals.length); try { genericFieldType = BcelGenericSignatureToTypeXConverter .fieldTypeSignature2TypeX(fts, formals, world); } catch (GenericSignatureFormatException e) { // development bug, fail fast with good info throw new IllegalStateException( "While determing the generic field type of " + this.toString() + " with generic signature " + gSig + " the following error was detected: " + e.getMessage()); } } else { genericFieldType = getReturnType(); } } }
108,826
Bug 108826 AJDT Error: Can't find type
In Eclipse 3.1, using the latest AspectJ build (1.5.0_M3a compiler and 1.3.0 plugin) I get an error "can't find type test.T" , using the following code: =============== package test; public class CantFindType { public <T> T[] method(T[] array) { return null; } } ================ The error occurs, if the return type, or the parameter is an array of a generic type. The code compiles fine, but Eclipse shows the error, but doesn't show the folder or the location for the error.
resolved fixed
2942ca0
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-09T14:19:19Z
2005-09-06T12:33:20Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/EclipseFactory.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * Mik Kersten 2004-07-26 extended to allow overloading of * hierarchy builder * ******************************************************************/ package org.aspectj.ajdt.internal.compiler.lookup; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration; import org.aspectj.ajdt.internal.compiler.ast.AstUtil; import org.aspectj.ajdt.internal.core.builder.AjBuildManager; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.IMessage.Kind; import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation; import org.aspectj.org.eclipse.jdt.internal.compiler.CompilationResult; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.ASTNode; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.EmptyStatement; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Wildcard; import org.aspectj.org.eclipse.jdt.internal.compiler.impl.Constant; import org.aspectj.org.eclipse.jdt.internal.compiler.impl.ReferenceContext; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.BaseTypes; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.Binding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.FieldBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.LocalTypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.MethodBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ParameterizedTypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.RawTypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.Scope; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeVariableBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.WildcardBinding; import org.aspectj.weaver.BoundedReferenceType; import org.aspectj.weaver.ConcreteTypeMunger; import org.aspectj.weaver.IHasPosition; import org.aspectj.weaver.Member; import org.aspectj.weaver.ReferenceType; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedMemberImpl; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.TypeFactory; import org.aspectj.weaver.TypeVariable; import org.aspectj.weaver.TypeVariableDeclaringElement; import org.aspectj.weaver.TypeVariableReference; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.UnresolvedTypeVariableReferenceType; import org.aspectj.weaver.World; /** * @author Jim Hugunin */ public class EclipseFactory { public static boolean DEBUG = false; private AjBuildManager buildManager; private LookupEnvironment lookupEnvironment; private boolean xSerializableAspects; private World world; private Map/*UnresolvedType, TypeBinding*/ typexToBinding = new HashMap(); //XXX currently unused // private Map/*TypeBinding, ResolvedType*/ bindingToResolvedTypeX = new HashMap(); public static EclipseFactory fromLookupEnvironment(LookupEnvironment env) { AjLookupEnvironment aenv = (AjLookupEnvironment)env; return aenv.factory; } public static EclipseFactory fromScopeLookupEnvironment(Scope scope) { return fromLookupEnvironment(AstUtil.getCompilationUnitScope(scope).environment); } public EclipseFactory(LookupEnvironment lookupEnvironment,AjBuildManager buildManager) { this.lookupEnvironment = lookupEnvironment; this.buildManager = buildManager; this.world = buildManager.getWorld(); this.xSerializableAspects = buildManager.buildConfig.isXserializableAspects(); } public EclipseFactory(LookupEnvironment lookupEnvironment, World world, boolean xSer) { this.lookupEnvironment = lookupEnvironment; this.world = world; this.xSerializableAspects = xSer; this.buildManager = null; } public World getWorld() { return world; } public void showMessage( Kind kind, String message, ISourceLocation loc1, ISourceLocation loc2) { getWorld().showMessage(kind, message, loc1, loc2); } public ResolvedType fromEclipse(ReferenceBinding binding) { if (binding == null) return ResolvedType.MISSING; //??? this seems terribly inefficient //System.err.println("resolving: " + binding.getClass() + ", name = " + getName(binding)); ResolvedType ret = getWorld().resolve(fromBinding(binding)); //System.err.println(" got: " + ret); return ret; } public ResolvedType fromTypeBindingToRTX(TypeBinding tb) { if (tb == null) return ResolvedType.MISSING; ResolvedType ret = getWorld().resolve(fromBinding(tb)); return ret; } public ResolvedType[] fromEclipse(ReferenceBinding[] bindings) { if (bindings == null) { return ResolvedType.NONE; } int len = bindings.length; ResolvedType[] ret = new ResolvedType[len]; for (int i=0; i < len; i++) { ret[i] = fromEclipse(bindings[i]); } return ret; } public static String getName(TypeBinding binding) { if (binding instanceof TypeVariableBinding) { // The first bound may be null - so default to object? TypeVariableBinding tvb = (TypeVariableBinding)binding; if (tvb.firstBound!=null) { return getName(tvb.firstBound); } else { return getName(tvb.superclass); } } if (binding instanceof ReferenceBinding) { return new String( CharOperation.concatWith(((ReferenceBinding)binding).compoundName, '.')); } String packageName = new String(binding.qualifiedPackageName()); String className = new String(binding.qualifiedSourceName()).replace('.', '$'); if (packageName.length() > 0) { className = packageName + "." + className; } //XXX doesn't handle arrays correctly (or primitives?) return new String(className); } /** * Some generics notes: * * Andy 6-May-05 * We were having trouble with parameterized types in a couple of places - due to TypeVariableBindings. When we * see a TypeVariableBinding now we default to either the firstBound if it is specified or java.lang.Object. Not * sure when/if this gets us unstuck? It does mean we forget that it is a type variable when going back * the other way from the UnresolvedType and that would seem a bad thing - but I've yet to see the reason we need to * remember the type variable. * Adrian 10-July-05 * When we forget it's a type variable we come unstuck when getting the declared members of a parameterized * type - since we don't know it's a type variable we can't replace it with the type parameter. */ //??? going back and forth between strings and bindings is a waste of cycles public UnresolvedType fromBinding(TypeBinding binding) { if (binding instanceof HelperInterfaceBinding) { return ((HelperInterfaceBinding) binding).getTypeX(); } if (binding == null || binding.qualifiedSourceName() == null) { return ResolvedType.MISSING; } // first piece of generics support! if (binding instanceof TypeVariableBinding) { return fromTypeVariableBinding((TypeVariableBinding)binding); } if (binding instanceof WildcardBinding) { WildcardBinding eWB = (WildcardBinding) binding; UnresolvedType ut = TypeFactory.createTypeFromSignature(CharOperation.charToString(eWB.genericTypeSignature())); // If the bound for the wildcard is a typevariable, e.g. '? extends E' then // the type variable in the unresolvedtype will be correct only in name. In that // case let's set it correctly based on the one in the eclipse WildcardBinding if (eWB.bound instanceof TypeVariableBinding) { UnresolvedType tVar = fromTypeVariableBinding((TypeVariableBinding)eWB.bound); if (ut.isGenericWildcard() && ut.isSuper()) ut.setLowerBound(tVar); if (ut.isGenericWildcard() && ut.isExtends()) ut.setUpperBound(tVar); } return ut; } if (binding instanceof ParameterizedTypeBinding) { if (binding instanceof RawTypeBinding) { // special case where no parameters are specified! return UnresolvedType.forRawTypeName(getName(binding)); } ParameterizedTypeBinding ptb = (ParameterizedTypeBinding) binding; UnresolvedType[] arguments = null; if (ptb.arguments!=null) { // null can mean this is an inner type of a Parameterized Type with no bounds of its own (pr100227) arguments = new UnresolvedType[ptb.arguments.length]; for (int i = 0; i < arguments.length; i++) { arguments[i] = fromBinding(ptb.arguments[i]); } } String baseTypeSignature = null; ResolvedType baseType = getWorld().resolve(UnresolvedType.forName(getName(binding)),true); if (baseType != ResolvedType.MISSING) { // can legitimately be missing if a bound refers to a type we haven't added to the world yet... if (!baseType.isGenericType() && arguments!=null) baseType = baseType.getGenericType(); baseTypeSignature = baseType.getErasureSignature(); } else { baseTypeSignature = UnresolvedType.forName(getName(binding)).getSignature(); } // Create an unresolved parameterized type. We can't create a resolved one as the // act of resolution here may cause recursion problems since the parameters may // be type variables that we haven't fixed up yet. if (arguments==null) arguments=new UnresolvedType[0]; String parameterizedSig = ResolvedType.PARAMETERIZED_TYPE_IDENTIFIER+CharOperation.charToString(binding.genericTypeSignature()).substring(1); return TypeFactory.createUnresolvedParameterizedType(parameterizedSig,baseTypeSignature,arguments); } // Convert the source type binding for a generic type into a generic UnresolvedType // notice we can easily determine the type variables from the eclipse object // and we can recover the generic signature from it too - so we pass those // to the forGenericType() method. if (binding.isGenericType() && !binding.isParameterizedType() && !binding.isRawType()) { TypeVariableBinding[] tvbs = binding.typeVariables(); TypeVariable[] tVars = new TypeVariable[tvbs.length]; for (int i = 0; i < tvbs.length; i++) { TypeVariableBinding eclipseV = tvbs[i]; String name = CharOperation.charToString(eclipseV.sourceName); tVars[i] = new TypeVariable(name,fromBinding(eclipseV.superclass()),fromBindings(eclipseV.superInterfaces())); } //TODO asc generics - temporary guard.... if (!(binding instanceof SourceTypeBinding)) throw new RuntimeException("Cant get the generic sig for "+binding.debugName()); return UnresolvedType.forGenericType(getName(binding),tVars, CharOperation.charToString(((SourceTypeBinding)binding).genericSignature())); } // LocalTypeBinding have a name $Local$, we can get the real name by using the signature.... if (binding instanceof LocalTypeBinding) { LocalTypeBinding ltb = (LocalTypeBinding) binding; if (ltb.constantPoolName() != null && ltb.constantPoolName().length > 0) { return UnresolvedType.forSignature(new String(binding.signature())); } else { // we're reporting a problem and don't have a resolved name for an // anonymous local type yet, report the issue on the enclosing type return UnresolvedType.forSignature(new String(ltb.enclosingType.signature())); } } return UnresolvedType.forName(getName(binding)); } /** * Some type variables refer to themselves recursively, this enables us to avoid * recursion problems. */ private static Map typeVariableBindingsInProgress = new HashMap(); /** * Convert from the eclipse form of type variable (TypeVariableBinding) to the AspectJ * form (TypeVariable). */ private UnresolvedType fromTypeVariableBinding(TypeVariableBinding aTypeVariableBinding) { // first, check for recursive call to this method for the same tvBinding if (typeVariableBindingsInProgress.containsKey(aTypeVariableBinding)) { return (UnresolvedType) typeVariableBindingsInProgress.get(aTypeVariableBinding); } if (typeVariablesForThisMember.containsKey(new String(aTypeVariableBinding.sourceName))) { return (UnresolvedType)typeVariablesForThisMember.get(new String(aTypeVariableBinding.sourceName)); } // Create the UnresolvedTypeVariableReferenceType for the type variable String name = CharOperation.charToString(aTypeVariableBinding.sourceName()); UnresolvedTypeVariableReferenceType ret = new UnresolvedTypeVariableReferenceType(); typeVariableBindingsInProgress.put(aTypeVariableBinding,ret); // Dont set any bounds here, you'll get in a recursive mess // TODO -- what about lower bounds?? UnresolvedType superclassType = fromBinding(aTypeVariableBinding.superclass()); UnresolvedType[] superinterfaces = new UnresolvedType[aTypeVariableBinding.superInterfaces.length]; for (int i = 0; i < superinterfaces.length; i++) { superinterfaces[i] = fromBinding(aTypeVariableBinding.superInterfaces[i]); } TypeVariable tv = new TypeVariable(name,superclassType,superinterfaces); tv.setUpperBound(superclassType); tv.setAdditionalInterfaceBounds(superinterfaces); tv.setRank(aTypeVariableBinding.rank); if (aTypeVariableBinding.declaringElement instanceof MethodBinding) { tv.setDeclaringElementKind(TypeVariable.METHOD); // tv.setDeclaringElement(fromBinding((MethodBinding)aTypeVariableBinding.declaringElement); } else { tv.setDeclaringElementKind(TypeVariable.TYPE); // // tv.setDeclaringElement(fromBinding(aTypeVariableBinding.declaringElement)); } ret.setTypeVariable(tv); if (aTypeVariableBinding.declaringElement instanceof MethodBinding) typeVariablesForThisMember.put(new String(aTypeVariableBinding.sourceName),ret); typeVariableBindingsInProgress.remove(aTypeVariableBinding); return ret; } public UnresolvedType[] fromBindings(TypeBinding[] bindings) { if (bindings == null) return UnresolvedType.NONE; int len = bindings.length; UnresolvedType[] ret = new UnresolvedType[len]; for (int i=0; i<len; i++) { ret[i] = fromBinding(bindings[i]); } return ret; } public static ASTNode astForLocation(IHasPosition location) { return new EmptyStatement(location.getStart(), location.getEnd()); } public Collection getDeclareParents() { return getWorld().getDeclareParents(); } public Collection getDeclareAnnotationOnTypes() { return getWorld().getDeclareAnnotationOnTypes(); } public Collection getDeclareAnnotationOnFields() { return getWorld().getDeclareAnnotationOnFields(); } public Collection getDeclareAnnotationOnMethods() { return getWorld().getDeclareAnnotationOnMethods(); } public Collection finishedTypeMungers = null; public boolean areTypeMungersFinished() { return finishedTypeMungers != null; } public void finishTypeMungers() { // make sure that type mungers are Collection ret = new ArrayList(); Collection baseTypeMungers = getWorld().getCrosscuttingMembersSet().getTypeMungers(); baseTypeMungers.addAll(getWorld().getCrosscuttingMembersSet().getLateTypeMungers()); for (Iterator i = baseTypeMungers.iterator(); i.hasNext(); ) { ConcreteTypeMunger munger = (ConcreteTypeMunger) i.next(); EclipseTypeMunger etm = makeEclipseTypeMunger(munger); if (etm != null) ret.add(etm); } finishedTypeMungers = ret; } public EclipseTypeMunger makeEclipseTypeMunger(ConcreteTypeMunger concrete) { //System.err.println("make munger: " + concrete); //!!! can't do this if we want incremental to work right //if (concrete instanceof EclipseTypeMunger) return (EclipseTypeMunger)concrete; //System.err.println(" was not eclipse"); if (concrete.getMunger() != null && EclipseTypeMunger.supportsKind(concrete.getMunger().getKind())) { AbstractMethodDeclaration method = null; if (concrete instanceof EclipseTypeMunger) { method = ((EclipseTypeMunger)concrete).getSourceMethod(); } EclipseTypeMunger ret = new EclipseTypeMunger(this, concrete.getMunger(), concrete.getAspectType(), method); if (ret.getSourceLocation() == null) { ret.setSourceLocation(concrete.getSourceLocation()); } return ret; } else { return null; } } public Collection getTypeMungers() { //??? assert finishedTypeMungers != null return finishedTypeMungers; } public ResolvedMember makeResolvedMember(MethodBinding binding) { return makeResolvedMember(binding, binding.declaringClass); } /** * Conversion from a methodbinding (eclipse) to a resolvedmember (aspectj) is now done * in the scope of some type variables. Before converting the parts of a methodbinding * (params, return type) we store the type variables in this structure, then should any * component of the method binding refer to them, we grab them from the map. */ // FIXME asc convert to array, indexed by rank private Map typeVariablesForThisMember = new HashMap(); public ResolvedMember makeResolvedMember(MethodBinding binding, TypeBinding declaringType) { //System.err.println("member for: " + binding + ", " + new String(binding.declaringClass.sourceName)); // Convert the type variables and store them UnresolvedType[] ajTypeRefs = null; typeVariablesForThisMember.clear(); // This is the set of type variables available whilst building the resolved member... if (binding.typeVariables!=null) { ajTypeRefs = new UnresolvedType[binding.typeVariables.length]; for (int i = 0; i < binding.typeVariables.length; i++) { ajTypeRefs[i] = fromBinding(binding.typeVariables[i]); typeVariablesForThisMember.put(new String(binding.typeVariables[i].sourceName),/*new Integer(binding.typeVariables[i].rank),*/ajTypeRefs[i]); } } // AMC these next two lines shouldn't be needed once we sort out generic types properly in the world map ResolvedType realDeclaringType = world.resolve(fromBinding(declaringType)); if (realDeclaringType.isRawType()) realDeclaringType = realDeclaringType.getGenericType(); ResolvedMember ret = new ResolvedMemberImpl( binding.isConstructor() ? Member.CONSTRUCTOR : Member.METHOD, realDeclaringType, binding.modifiers, fromBinding(binding.returnType), new String(binding.selector), fromBindings(binding.parameters), fromBindings(binding.thrownExceptions) ); if (typeVariablesForThisMember.size()!=0) { UnresolvedType[] tvars = new UnresolvedType[typeVariablesForThisMember.size()]; int i =0; for (Iterator iter = typeVariablesForThisMember.values().iterator(); iter.hasNext();) { tvars[i++] = (UnresolvedType)iter.next(); } ret.setTypeVariables(tvars); } typeVariablesForThisMember.clear(); ret.resolve(world); return ret; } public ResolvedMember makeResolvedMember(FieldBinding binding) { return makeResolvedMember(binding, binding.declaringClass); } public ResolvedMember makeResolvedMember(FieldBinding binding, TypeBinding receiverType) { // AMC these next two lines shouldn't be needed once we sort out generic types properly in the world map ResolvedType realDeclaringType = world.resolve(fromBinding(receiverType)); if (realDeclaringType.isRawType()) realDeclaringType = realDeclaringType.getGenericType(); return new ResolvedMemberImpl( Member.FIELD, realDeclaringType, binding.modifiers, world.resolve(fromBinding(binding.type)), new String(binding.name), UnresolvedType.NONE); } public TypeBinding makeTypeBinding(UnresolvedType typeX) { TypeBinding ret = null; // looking up type variables can get us into trouble if (!typeX.isTypeVariableReference()) ret = (TypeBinding)typexToBinding.get(typeX); if (ret == null) { ret = makeTypeBinding1(typeX); // FIXME asc keep type variables *out* of the map for now, they go in typeVariableToTypeBinding if (!(typeX instanceof BoundedReferenceType) && !(typeX instanceof UnresolvedTypeVariableReferenceType)) typexToBinding.put(typeX, ret); } if (ret == null) { System.out.println("can't find: " + typeX); } return ret; } private TypeBinding makeTypeBinding1(UnresolvedType typeX) { if (typeX.isPrimitiveType()) { if (typeX == ResolvedType.BOOLEAN) return BaseTypes.BooleanBinding; if (typeX == ResolvedType.BYTE) return BaseTypes.ByteBinding; if (typeX == ResolvedType.CHAR) return BaseTypes.CharBinding; if (typeX == ResolvedType.DOUBLE) return BaseTypes.DoubleBinding; if (typeX == ResolvedType.FLOAT) return BaseTypes.FloatBinding; if (typeX == ResolvedType.INT) return BaseTypes.IntBinding; if (typeX == ResolvedType.LONG) return BaseTypes.LongBinding; if (typeX == ResolvedType.SHORT) return BaseTypes.ShortBinding; if (typeX == ResolvedType.VOID) return BaseTypes.VoidBinding; throw new RuntimeException("weird primitive type " + typeX); } else if (typeX.isArray()) { int dim = 0; while (typeX.isArray()) { dim++; typeX = typeX.getComponentType(); } return lookupEnvironment.createArrayType(makeTypeBinding(typeX), dim); } else if (typeX.isParameterizedType()) { // Converting back to a binding from a UnresolvedType UnresolvedType[] typeParameters = typeX.getTypeParameters(); ReferenceBinding baseTypeBinding = lookupBinding(typeX.getBaseName()); TypeBinding[] argumentBindings = new TypeBinding[typeParameters.length]; for (int i = 0; i < argumentBindings.length; i++) { argumentBindings[i] = makeTypeBinding(typeParameters[i]); } ParameterizedTypeBinding ptb = lookupEnvironment.createParameterizedType(baseTypeBinding,argumentBindings,baseTypeBinding.enclosingType()); return ptb; } else if (typeX.isTypeVariableReference()) { return makeTypeVariableBinding((TypeVariableReference)typeX); } else if (typeX.isRawType()) { ReferenceBinding baseTypeBinding = lookupBinding(typeX.getBaseName()); RawTypeBinding rtb = lookupEnvironment.createRawType(baseTypeBinding,baseTypeBinding.enclosingType()); return rtb; } else if (typeX.isGenericWildcard()) { // translate from boundedreferencetype to WildcardBinding BoundedReferenceType brt = (BoundedReferenceType)typeX; // Work out 'kind' for the WildcardBinding int boundkind = Wildcard.UNBOUND; TypeBinding bound = null; if (brt.isExtends()) { boundkind = Wildcard.EXTENDS; bound = makeTypeBinding(brt.getUpperBound()); } else if (brt.isSuper()) { boundkind = Wildcard.SUPER; bound = makeTypeBinding(brt.getLowerBound()); } TypeBinding[] otherBounds = null; if (brt.getAdditionalBounds()!=null && brt.getAdditionalBounds().length!=0) otherBounds = makeTypeBindings(brt.getAdditionalBounds()); // FIXME asc rank should not always be 0 ... WildcardBinding wb = lookupEnvironment.createWildcard(null,0,bound,otherBounds,boundkind); return wb; } else { return lookupBinding(typeX.getName()); } } private ReferenceBinding lookupBinding(String sname) { char[][] name = CharOperation.splitOn('.', sname.toCharArray()); ReferenceBinding rb = lookupEnvironment.getType(name); // XXX We do this because the pertypewithin aspectOf(Class) generated method needs it. Without this // we don't get a 'rawtype' as the argument type for a messagesend to aspectOf() and this leads to // a compile error if some client class calls aspectOf(A.class) or similar as it says Class<A> isn't // compatible with Class<T> if (sname.equals("java.lang.Class")) rb = lookupEnvironment.createRawType(rb,rb.enclosingType()); return rb; } public TypeBinding[] makeTypeBindings(UnresolvedType[] types) { int len = types.length; TypeBinding[] ret = new TypeBinding[len]; for (int i = 0; i < len; i++) { ret[i] = makeTypeBinding(types[i]); } return ret; } // just like the code above except it returns an array of ReferenceBindings private ReferenceBinding[] makeReferenceBindings(UnresolvedType[] types) { int len = types.length; ReferenceBinding[] ret = new ReferenceBinding[len]; for (int i = 0; i < len; i++) { ret[i] = (ReferenceBinding)makeTypeBinding(types[i]); } return ret; } public FieldBinding makeFieldBinding(ResolvedMember member) { currentType = (ReferenceBinding)makeTypeBinding(member.getDeclaringType()); FieldBinding fb = new FieldBinding(member.getName().toCharArray(), makeTypeBinding(member.getReturnType()), member.getModifiers(), currentType, Constant.NotAConstant); currentType = null; return fb; } private ReferenceBinding currentType = null; public MethodBinding makeMethodBinding(ResolvedMember member) { typeVariableToTypeBinding.clear(); TypeVariableBinding[] tvbs = null; if (member.getTypeVariables()!=null) { if (member.getTypeVariables().length==0) { tvbs = MethodBinding.NoTypeVariables; } else { tvbs = makeTypeVariableBindings(member.getTypeVariables()); // fixup the declaring element, we couldn't do it whilst processing the typevariables as we'll end up in recursion. for (int i = 0; i < tvbs.length; i++) { TypeVariableBinding binding = tvbs[i]; // if (binding.declaringElement==null && ((TypeVariableReference)member.getTypeVariables()[i]).getTypeVariable().getDeclaringElement() instanceof Member) { // tvbs[i].declaringElement = mb; // } else { // tvbs[i].declaringElement = declaringType; // } } } } ReferenceBinding declaringType = (ReferenceBinding)makeTypeBinding(member.getDeclaringType()); currentType = declaringType; MethodBinding mb = new MethodBinding(member.getModifiers(), member.getName().toCharArray(), makeTypeBinding(member.getReturnType()), makeTypeBindings(member.getParameterTypes()), makeReferenceBindings(member.getExceptions()), declaringType); if (tvbs!=null) mb.typeVariables = tvbs; typeVariableToTypeBinding.clear(); currentType = null; return mb; } /** * Convert a bunch of type variables in one go, from AspectJ form to Eclipse form. */ private TypeVariableBinding[] makeTypeVariableBindings(UnresolvedType[] typeVariables) { int len = typeVariables.length; TypeVariableBinding[] ret = new TypeVariableBinding[len]; for (int i = 0; i < len; i++) { ret[i] = makeTypeVariableBinding((TypeVariableReference)typeVariables[i]); } return ret; } // only accessed through private methods in this class. Ensures all type variables we encounter // map back to the same type binding - this is important later when Eclipse code is processing // a methodbinding trying to come up with possible bindings for the type variables. // key is currently the name of the type variable...is that ok? private Map typeVariableToTypeBinding = new HashMap(); /** * Converts from an TypeVariableReference to a TypeVariableBinding. A TypeVariableReference * in AspectJ world holds a TypeVariable and it is this type variable that is converted * to the TypeVariableBinding. */ private TypeVariableBinding makeTypeVariableBinding(TypeVariableReference tvReference) { TypeVariable tVar = tvReference.getTypeVariable(); TypeVariableBinding tvBinding = (TypeVariableBinding)typeVariableToTypeBinding.get(tVar.getName()); if (currentType!=null) { TypeVariableBinding tvb = currentType.getTypeVariable(tVar.getName().toCharArray()); if (tvb!=null) return tvb; } if (tvBinding==null) { Binding declaringElement = null; // this will cause an infinite loop or NPE... not required yet luckily. // if (tVar.getDeclaringElement() instanceof Member) { // declaringElement = makeMethodBinding((ResolvedMember)tVar.getDeclaringElement()); // } else { // declaringElement = makeTypeBinding((UnresolvedType)tVar.getDeclaringElement()); // } tvBinding = new TypeVariableBinding(tVar.getName().toCharArray(),declaringElement,tVar.getRank()); typeVariableToTypeBinding.put(tVar.getName(),tvBinding); tvBinding.superclass=(ReferenceBinding)makeTypeBinding(tVar.getUpperBound()); tvBinding.firstBound=tvBinding.superclass; // FIXME asc is this correct? possibly it could be first superinterface if (tVar.getAdditionalInterfaceBounds()==null) { tvBinding.superInterfaces=TypeVariableBinding.NoSuperInterfaces; } else { TypeBinding tbs[] = makeTypeBindings(tVar.getAdditionalInterfaceBounds()); ReferenceBinding[] rbs= new ReferenceBinding[tbs.length]; for (int i = 0; i < tbs.length; i++) { rbs[i] = (ReferenceBinding)tbs[i]; } tvBinding.superInterfaces=rbs; } } return tvBinding; } public MethodBinding makeMethodBindingForCall(Member member) { return new MethodBinding(member.getCallsiteModifiers(), member.getName().toCharArray(), makeTypeBinding(member.getReturnType()), makeTypeBindings(member.getParameterTypes()), new ReferenceBinding[0], (ReferenceBinding)makeTypeBinding(member.getDeclaringType())); } public void finishedCompilationUnit(CompilationUnitDeclaration unit) { if ((buildManager != null) && buildManager.doGenerateModel()) { AjBuildManager.getAsmHierarchyBuilder().buildStructureForCompilationUnit(unit, buildManager.getStructureModel(), buildManager.buildConfig); } } public void addTypeBinding(TypeBinding binding) { typexToBinding.put(fromBinding(binding), binding); } public Shadow makeShadow(ASTNode location, ReferenceContext context) { return EclipseShadow.makeShadow(this, location, context); } public Shadow makeShadow(ReferenceContext context) { return EclipseShadow.makeShadow(this, (ASTNode) context, context); } public void addSourceTypeBinding(SourceTypeBinding binding, CompilationUnitDeclaration unit) { TypeDeclaration decl = binding.scope.referenceContext; // Deal with the raw/basic type to give us an entry in the world type map UnresolvedType simpleTx = null; if (binding.isGenericType()) { simpleTx = UnresolvedType.forRawTypeName(getName(binding)); } else if (binding.isLocalType()) { LocalTypeBinding ltb = (LocalTypeBinding) binding; if (ltb.constantPoolName() != null && ltb.constantPoolName().length > 0) { simpleTx = UnresolvedType.forSignature(new String(binding.signature())); } else { simpleTx = UnresolvedType.forName(getName(binding)); } }else { simpleTx = UnresolvedType.forName(getName(binding)); } ReferenceType name = getWorld().lookupOrCreateName(simpleTx); EclipseSourceType t = new EclipseSourceType(name, this, binding, decl, unit); // For generics, go a bit further - build a typex for the generic type // give it the same delegate and link it to the raw type if (binding.isGenericType()) { UnresolvedType complexTx = fromBinding(binding); // fully aware of any generics info ReferenceType complexName = new ReferenceType(complexTx,world);//getWorld().lookupOrCreateName(complexTx); name.setGenericType(complexName); complexName.setDelegate(t); complexName.setSourceContext(t.getResolvedTypeX().getSourceContext()); } name.setDelegate(t); if (decl instanceof AspectDeclaration) { ((AspectDeclaration)decl).typeX = name; ((AspectDeclaration)decl).concreteName = t; } ReferenceBinding[] memberTypes = binding.memberTypes; for (int i = 0, length = memberTypes.length; i < length; i++) { addSourceTypeBinding((SourceTypeBinding) memberTypes[i], unit); } } // XXX this doesn't feel like it belongs here, but it breaks a hard dependency on // exposing AjBuildManager (needed by AspectDeclaration). public boolean isXSerializableAspects() { return xSerializableAspects; } public ResolvedMember fromBinding(MethodBinding binding) { return new ResolvedMemberImpl(Member.METHOD,fromBinding(binding.declaringClass),binding.modifiers, fromBinding(binding.returnType),CharOperation.charToString(binding.selector),fromBindings(binding.parameters)); } public TypeVariableDeclaringElement fromBinding(Binding declaringElement) { if (declaringElement instanceof TypeBinding) { return fromBinding(((TypeBinding)declaringElement)); } else { return fromBinding((MethodBinding)declaringElement); } } }
108,826
Bug 108826 AJDT Error: Can't find type
In Eclipse 3.1, using the latest AspectJ build (1.5.0_M3a compiler and 1.3.0 plugin) I get an error "can't find type test.T" , using the following code: =============== package test; public class CantFindType { public <T> T[] method(T[] array) { return null; } } ================ The error occurs, if the return type, or the parameter is an array of a generic type. The code compiles fine, but Eclipse shows the error, but doesn't show the folder or the location for the error.
resolved fixed
2942ca0
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-09T14:19:19Z
2005-09-06T12:33:20Z
tests/src/org/aspectj/systemtest/ajc150/Ajc150Tests.java
/******************************************************************************* * Copyright (c) 2004 IBM * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Andy Clement - initial API and implementation *******************************************************************************/ package org.aspectj.systemtest.ajc150; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import junit.framework.Test; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.apache.bcel.classfile.Method; import org.aspectj.apache.bcel.util.ClassPath; import org.aspectj.apache.bcel.util.SyntheticRepository; import org.aspectj.asm.AsmManager; import org.aspectj.testing.XMLBasedAjcTestCase; import org.aspectj.util.LangUtil; /** * These are tests that will run on Java 1.4 and use the old harness format for test specification. */ public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase { public static Test suite() { return XMLBasedAjcTestCase.loadSuite(Ajc150Tests.class); } protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml"); } public void test_typeProcessingOrderWhenDeclareParents() { runTest("Order of types passed to compiler determines weaving behavior"); } public void test_aroundMethod() { runTest("method called around in class"); } public void test_aroundMethodAspect() { runTest("method called around in aspect"); } public void test_ambiguousBindingsDetection() { runTest("Various kinds of ambiguous bindings"); } public void test_ambiguousArgsDetection() { runTest("ambiguous args"); } public void testIncorrectExceptionTableWhenBreakInMethod_pr78021() { runTest("Injecting exception into while loop with break statement causes catch block to be ignored"); } public void testIncorrectExceptionTableWhenReturnInMethod_pr79554() { runTest("Return in try-block disables catch-block if final-block is present"); } public void testMissingDebugInfoForGeneratedMethods_pr82570() throws ClassNotFoundException { runTest("Weaved code does not include debug lines"); boolean f = false; JavaClass jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1"); Method[] meths = jc.getMethods(); for (int i = 0; i < meths.length; i++) { Method method = meths[i]; if (f) System.err.println("Line number table for "+method.getName()+method.getSignature()+" = "+method.getLineNumberTable()); assertTrue("Didn't find a line number table for method "+method.getName()+method.getSignature(), method.getLineNumberTable()!=null); } // This test would determine the info isn't there if you pass -g:none ... // cR = ajc(baseDir,new String[]{"PR82570_1.java","-g:none"}); // assertTrue("Expected no compile problem:"+cR,!cR.hasErrorMessages()); // System.err.println(cR.getStandardError()); // jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1"); // meths = jc.getMethods(); // for (int i = 0; i < meths.length; i++) { // Method method = meths[i]; // assertTrue("Found a line number table for method "+method.getName(), // method.getLineNumberTable()==null); // } } public void testCanOverrideProtectedMethodsViaITDandDecp_pr83303() { runTest("compiler error when mixing inheritance, overriding and polymorphism"); } public void testPerTypeWithinMissesNamedInnerTypes() { runTest("pertypewithin() handing of inner classes (1)"); } public void testPerTypeWithinMissesAnonymousInnerTypes() { runTest("pertypewithin() handing of inner classes (2)"); } public void testPerTypeWithinIncorrectlyMatchingInterfaces() { runTest("pertypewithin({interface}) illegal field modifier"); } public void test051_arrayCloningInJava5() { runTest("AJC possible bug with static nested classes"); } public void testBadASMforEnums() throws IOException { runTest("bad asm for enums"); if (LangUtil.is15VMOrGreater()) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintWriter pw = new PrintWriter(baos); AsmManager.dumptree(pw,AsmManager.getDefault().getHierarchy().getRoot(),0); pw.flush(); String tree = baos.toString(); assertTrue("Expected 'Red [enumvalue]' somewhere in here:"+tree,tree.indexOf("Red [enumvalue]")!=-1); } } public void npeOnTypeNotFound() { runTest("structure model npe on type not found"); } public void testNoRuntimeExceptionSoftening() { runTest("declare soft of runtime exception"); } public void testRuntimeNoSoftenWithHandler() { runTest("declare soft w. catch block"); } public void testSyntaxError() { runTest("invalid cons syntax"); } public void testVarargsInConsBug() { runTest("varargs in constructor sig"); } public void testAspectpathdirs() { runTest("dirs on aspectpath"); } public void testIntroSample() { runTest("introduction sample"); } public void testPTWInterface() { runTest("pertypewithin({interface}) illegal field modifier"); } public void testEnumCalledEnumEtc() { runTest("enum called Enum, annotation called Annotation, etc"); } public void testInternalCompilerError_pr86832() { runTest("Internal compiler error"); } public void testCloneMethod_pr83311() { runTest("overriding/polymorphism error on interface method introduction"); } /** * IfPointcut.findResidueInternal() was modified to make this test complete in a short amount * of time - if you see it hanging, someone has messed with the optimization. */ public void testIfEvaluationExplosion_pr94086() { runTest("Exploding compile time with if() statements in pointcut"); } public void testReflectNPE_pr94167() {runTest("NPE in reflect implementation");} public void testStaticImports_pr84260() {runTest("static import failures");} public void testGenerics_pr99089() {runTest("ArrayIndexOutOfBoundsException - Generics in privileged aspects");} public void testGenerics_pr95993() {runTest("NPE at ClassScope.java:660 when compiling generic class");} public void testItdGenerics_pr99228() {runTest("ITD of a field into a generic class");} public void testItdGenerics_pr98320() {runTest("intertype with nested generic type");} public void testItdGenerics_pr100227() {runTest("inner class with generic enclosing class");} public void testItdGenerics_pr100260() {runTest("methods inherited from a generic parent");} public void testSyntaxErrorNPE_pr103266() {runTest("NPE on syntax error");} public void testIllegalStateExceptionOnNestedParameterizedType_pr106634() { runTest("IllegalStateException unpacking signature of nested parameterized type"); } public void testParseErrorOnAnnotationStarPlusPattern() { runTest("(@Foo *)+ type pattern parse error"); } public void test_pr106130_tooManyLocals() { runTest("test weaving with > 256 locals"); } public void testMissingNamePattern_pr106461() { runTest("missing name pattern"); } public void testMissingNamePattern_pr107059() { runTest("parser crashes on call(void (@a *)(..)"); } public void testIntermediateAnnotationMatching() { runTest("intermediate annotation matching"); } public void testBadRuntimeTestGeneration() { runTest("target(@Foo *)"); } public void testErrorMessageOnITDWithTypePatterns() { runTest("clear error message on itd with type pattern"); } public void testAjKeywordsAsIdentifiers() { runTest("before and after are valid identifiers in classes"); } public void testAjKeywordsAsIdentifiers2() { runTest("before and after are valid identifiers in classes, part 2"); } public void testNoBeforeReturningAdvice() { runTest("before returning advice not allowed!"); } public void testDetectVoidFieldType() { runTest("void field type in pointcut expression"); } public void testPointcutOverriding() { runTest("overriding final pointcut from super-aspect"); } public void testAtSuppressWarnings() { runTest("@SuppressWarnings should suppress"); } public void testDEOWWithBindingPointcut() { runTest("declare warning : foo(str) : ...;"); } public void testAroundAdviceAndInterfaceInitializer() { runTest("around advice on interface initializer"); } public void testGoodErrorMessageOnUnmatchedMemberSyntax() { runTest("good error message for unmatched member syntax"); } public void testITDWithNoExceptionAndIntermediary() { runTest("itd override with no exception clause"); } public void testAnonymousInnerClasses() { runTest("anonymous inner classes"); } public void testMultipleAnonymousInnerClasses() { runTest("multiple anonymous inner classes"); } public void testPrivilegedMethodAccessorsGetRightExceptions_pr82989() { runTest("Compiler error due to a wrong exception check in try blocks"); } public void testAnonymousInnerClassWithMethodReturningTypeParameter_pr107898() { runTest("anonymous inner class with method returning type parameter"); } public void testMatchingOfObjectArray() { runTest("matching against Object[]"); } public void testMultipleAnonymousInnerClasses_pr108104() { runTest("multiple anonymous inner classes 2"); } public void testSignatureMatchingInMultipleOverrideScenario() { runTest("signature matching in override scenario"); } public void testWildcardAnnotationMatching_pr108245() { runTest("wildcard annotation matching - pr108245"); } public void testInnerTypesAndTypeVariables() { runTest("inner types and type variables"); } public void testAtAfterThrowingWithNoFormal() { runTest("@AfterThrowing with no formal specified"); } public void testParameterizedVarArgsMatch() { runTest("varargs with type variable"); } public void testFieldAccessInsideITDM() { runTest("itd field access inside itd method"); } public void testTypeVarWithTypeVarBound() { runTest("type variable with type variable bound"); } public void testEnumSwitchInITD() { runTest("switch on enum inside ITD method"); } public void testInnerTypeOfGeneric() { runTest("inner type of generic interface reference from parameterized type"); } public void testDeclareParentsIntroducingCovariantReturnType() { runTest("declare parents introducing override with covariance"); } public void testInnerClassPassedToVarargs() { runTest("inner class passed as argument to varargs method"); } public void testInlinedFieldAccessInProceedCall() { runTest("inlined field access in proceed call"); } public void testVisibiltyInSignatureMatchingWithOverridesPart1() { runTest("visibility in signature matching with overrides - 1"); } public void testVisibiltyInSignatureMatchingWithOverridesPart2() { runTest("visibility in signature matching with overrides - 2"); } public void testVisibiltyInSignatureMatchingWithOverridesPart3() { runTest("visibility in signature matching with overrides - 3"); } public void testArgsGeneratedCorrectlyForAdviceExecution() { runTest("args generated correctly for advice execution join point"); } public void testNoUnusedWarningsOnAspectTypes() { runTest("no unused warnings on aspect types"); } public void testSyntheticArgumentsOnITDConstructorsNotUsedInMatching() { runTest("synthetic arguments on itd cons are not used in matching"); } public void testParsingOfGenericTypeSignature() { runTest("parse generic type signature with parameterized type in interface"); } public void testOverrideAndCovarianceWithDecPRuntime() { runTest("override and covariance with decp - runtime"); } public void testOverrideAndCovarianceWithDecPRuntimeMultiFiles() { runTest("override and covariance with decp - runtime separate files"); } public void testAbstractSynchronizedITDMethods() { runTest("abstract synchronized itdms not detected"); } public void testSynchronizedITDInterfaceMethods() { runTest("synchronized itd interface methods"); } public void testNoWarningOnUnusedPointcut() { runTest("unused private pointcuts"); } public void testITDOnInterfaceWithExistingMember() { runTest("itd interface method already existing on interface"); } public void testFinalITDMOnInterface() { runTest("final itd methods on interfaces"); } public void testPrivatePointcutOverriding() { runTest("can't override private pointcut in abstract aspect"); } public void testAdviceOnCflow() { runTest("advising cflow advice execution"); } public void testNoTypeMismatchOnSameGenericTypes() { runTest("no type mismatch on generic types in itds"); } public void testSuperCallInITD() { runTest("super call in ITD"); } public void testNoUnusedParameterWarningsForSyntheticAdviceArgs() { runTest("no unused parameter warnings for synthetic advice args"); } public void testNoVerifyErrorWithSetOnInnerType() { runTest("no verify error with set on inner type"); } // helper methods..... public SyntheticRepository createRepos(File cpentry) { ClassPath cp = new ClassPath(cpentry+File.pathSeparator+System.getProperty("java.class.path")); return SyntheticRepository.getInstance(cp); } protected JavaClass getClassFrom(File where,String clazzname) throws ClassNotFoundException { SyntheticRepository repos = createRepos(where); return repos.loadClass(clazzname); } }
103,740
Bug 103740 Compiler failure on @annotation
I'm using the ajc embedded in the latest dev build of AJDT (build 20050713163417) This small example illustrates the problem: public abstract aspect AbstractRequestMonitor { public pointcut requestExecution(RequestContext requestContext) : execution(* RequestContext.execute(..)) && this(requestContext); public abstract class RequestContext { public abstract Object execute(); } after(RequestContext requestContext) throwing (Throwable t) : requestExecution(requestContext) { } } import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Retention(RetentionPolicy.RUNTIME) public @interface AroundAdvice { } public aspect ErrorHandling { declare soft: Exception: !@annotation(AroundAdvice) && !withincode(* * (..)); Object around() : adviceexecution() && !@annotation(AroundAdvice) { try { return proceed(); } catch (Exception e) { return null; } } } Here's the stack trace I get: org.aspectj.weaver.BCException: bad at org.aspectj.weaver.bcel.BcelRenderer.visit(BcelRenderer.java:228) at org.aspectj.weaver.ast.Literal.accept(Literal.java:29) at org.aspectj.weaver.bcel.BcelRenderer.recur(BcelRenderer.java:151) at org.aspectj.weaver.bcel.BcelRenderer.renderTest (BcelRenderer.java:117) at org.aspectj.weaver.bcel.BcelAdvice.getTestInstructions (BcelAdvice.java:445) at org.aspectj.weaver.bcel.BcelShadow.weaveAroundClosure (BcelShadow.java:2585) at org.aspectj.weaver.bcel.BcelAdvice.implementOn(BcelAdvice.java:182) at org.aspectj.weaver.Shadow.implementMungers(Shadow.java:480) at org.aspectj.weaver.Shadow.implement(Shadow.java:358) at org.aspectj.weaver.bcel.BcelClassWeaver.implement (BcelClassWeaver.java:1703) at org.aspectj.weaver.bcel.BcelClassWeaver.weave (BcelClassWeaver.java:389) at org.aspectj.weaver.bcel.BcelClassWeaver.weave (BcelClassWeaver.java:94) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1362) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump (BcelWeaver.java:1327) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify (BcelWeaver.java:1106) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:981) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave (AjCompilerAdapter.java:286) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling (AjCompilerAdapter.java:165) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$afterReturning$org_aspec tj_ajdt_internal_compiler_CompilerAdapter$2$f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:368) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:727) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:206) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBuildManager.java:140) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:121) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:191)
resolved fixed
2ae4f53
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-12T13:37:56Z
2005-07-14T00:13:20Z
tests/src/org/aspectj/systemtest/ajc150/Ajc150Tests.java
/******************************************************************************* * Copyright (c) 2004 IBM * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Andy Clement - initial API and implementation *******************************************************************************/ package org.aspectj.systemtest.ajc150; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import junit.framework.Test; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.apache.bcel.classfile.Method; import org.aspectj.apache.bcel.util.ClassPath; import org.aspectj.apache.bcel.util.SyntheticRepository; import org.aspectj.asm.AsmManager; import org.aspectj.testing.XMLBasedAjcTestCase; import org.aspectj.util.LangUtil; /** * These are tests that will run on Java 1.4 and use the old harness format for test specification. */ public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase { public static Test suite() { return XMLBasedAjcTestCase.loadSuite(Ajc150Tests.class); } protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml"); } public void test_typeProcessingOrderWhenDeclareParents() { runTest("Order of types passed to compiler determines weaving behavior"); } public void test_aroundMethod() { runTest("method called around in class"); } public void test_aroundMethodAspect() { runTest("method called around in aspect"); } public void test_ambiguousBindingsDetection() { runTest("Various kinds of ambiguous bindings"); } public void test_ambiguousArgsDetection() { runTest("ambiguous args"); } public void testIncorrectExceptionTableWhenBreakInMethod_pr78021() { runTest("Injecting exception into while loop with break statement causes catch block to be ignored"); } public void testIncorrectExceptionTableWhenReturnInMethod_pr79554() { runTest("Return in try-block disables catch-block if final-block is present"); } public void testMissingDebugInfoForGeneratedMethods_pr82570() throws ClassNotFoundException { runTest("Weaved code does not include debug lines"); boolean f = false; JavaClass jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1"); Method[] meths = jc.getMethods(); for (int i = 0; i < meths.length; i++) { Method method = meths[i]; if (f) System.err.println("Line number table for "+method.getName()+method.getSignature()+" = "+method.getLineNumberTable()); assertTrue("Didn't find a line number table for method "+method.getName()+method.getSignature(), method.getLineNumberTable()!=null); } // This test would determine the info isn't there if you pass -g:none ... // cR = ajc(baseDir,new String[]{"PR82570_1.java","-g:none"}); // assertTrue("Expected no compile problem:"+cR,!cR.hasErrorMessages()); // System.err.println(cR.getStandardError()); // jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1"); // meths = jc.getMethods(); // for (int i = 0; i < meths.length; i++) { // Method method = meths[i]; // assertTrue("Found a line number table for method "+method.getName(), // method.getLineNumberTable()==null); // } } public void testCanOverrideProtectedMethodsViaITDandDecp_pr83303() { runTest("compiler error when mixing inheritance, overriding and polymorphism"); } public void testPerTypeWithinMissesNamedInnerTypes() { runTest("pertypewithin() handing of inner classes (1)"); } public void testPerTypeWithinMissesAnonymousInnerTypes() { runTest("pertypewithin() handing of inner classes (2)"); } public void testPerTypeWithinIncorrectlyMatchingInterfaces() { runTest("pertypewithin({interface}) illegal field modifier"); } public void test051_arrayCloningInJava5() { runTest("AJC possible bug with static nested classes"); } public void testBadASMforEnums() throws IOException { runTest("bad asm for enums"); if (LangUtil.is15VMOrGreater()) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintWriter pw = new PrintWriter(baos); AsmManager.dumptree(pw,AsmManager.getDefault().getHierarchy().getRoot(),0); pw.flush(); String tree = baos.toString(); assertTrue("Expected 'Red [enumvalue]' somewhere in here:"+tree,tree.indexOf("Red [enumvalue]")!=-1); } } public void npeOnTypeNotFound() { runTest("structure model npe on type not found"); } public void testNoRuntimeExceptionSoftening() { runTest("declare soft of runtime exception"); } public void testRuntimeNoSoftenWithHandler() { runTest("declare soft w. catch block"); } public void testSyntaxError() { runTest("invalid cons syntax"); } public void testVarargsInConsBug() { runTest("varargs in constructor sig"); } public void testAspectpathdirs() { runTest("dirs on aspectpath"); } public void testIntroSample() { runTest("introduction sample"); } public void testPTWInterface() { runTest("pertypewithin({interface}) illegal field modifier"); } public void testEnumCalledEnumEtc() { runTest("enum called Enum, annotation called Annotation, etc"); } public void testInternalCompilerError_pr86832() { runTest("Internal compiler error"); } public void testCloneMethod_pr83311() { runTest("overriding/polymorphism error on interface method introduction"); } /** * IfPointcut.findResidueInternal() was modified to make this test complete in a short amount * of time - if you see it hanging, someone has messed with the optimization. */ public void testIfEvaluationExplosion_pr94086() { runTest("Exploding compile time with if() statements in pointcut"); } public void testReflectNPE_pr94167() {runTest("NPE in reflect implementation");} public void testStaticImports_pr84260() {runTest("static import failures");} public void testGenerics_pr99089() {runTest("ArrayIndexOutOfBoundsException - Generics in privileged aspects");} public void testGenerics_pr95993() {runTest("NPE at ClassScope.java:660 when compiling generic class");} public void testItdGenerics_pr99228() {runTest("ITD of a field into a generic class");} public void testItdGenerics_pr98320() {runTest("intertype with nested generic type");} public void testItdGenerics_pr100227() {runTest("inner class with generic enclosing class");} public void testItdGenerics_pr100260() {runTest("methods inherited from a generic parent");} public void testSyntaxErrorNPE_pr103266() {runTest("NPE on syntax error");} public void testIllegalStateExceptionOnNestedParameterizedType_pr106634() { runTest("IllegalStateException unpacking signature of nested parameterized type"); } public void testParseErrorOnAnnotationStarPlusPattern() { runTest("(@Foo *)+ type pattern parse error"); } public void test_pr106130_tooManyLocals() { runTest("test weaving with > 256 locals"); } public void testMissingNamePattern_pr106461() { runTest("missing name pattern"); } public void testMissingNamePattern_pr107059() { runTest("parser crashes on call(void (@a *)(..)"); } public void testIntermediateAnnotationMatching() { runTest("intermediate annotation matching"); } public void testBadRuntimeTestGeneration() { runTest("target(@Foo *)"); } public void testErrorMessageOnITDWithTypePatterns() { runTest("clear error message on itd with type pattern"); } public void testAjKeywordsAsIdentifiers() { runTest("before and after are valid identifiers in classes"); } public void testAjKeywordsAsIdentifiers2() { runTest("before and after are valid identifiers in classes, part 2"); } public void testNoBeforeReturningAdvice() { runTest("before returning advice not allowed!"); } public void testDetectVoidFieldType() { runTest("void field type in pointcut expression"); } public void testPointcutOverriding() { runTest("overriding final pointcut from super-aspect"); } public void testAtSuppressWarnings() { runTest("@SuppressWarnings should suppress"); } public void testDEOWWithBindingPointcut() { runTest("declare warning : foo(str) : ...;"); } public void testAroundAdviceAndInterfaceInitializer() { runTest("around advice on interface initializer"); } public void testGoodErrorMessageOnUnmatchedMemberSyntax() { runTest("good error message for unmatched member syntax"); } public void testITDWithNoExceptionAndIntermediary() { runTest("itd override with no exception clause"); } public void testAnonymousInnerClasses() { runTest("anonymous inner classes"); } public void testMultipleAnonymousInnerClasses() { runTest("multiple anonymous inner classes"); } public void testPrivilegedMethodAccessorsGetRightExceptions_pr82989() { runTest("Compiler error due to a wrong exception check in try blocks"); } public void testAnonymousInnerClassWithMethodReturningTypeParameter_pr107898() { runTest("anonymous inner class with method returning type parameter"); } public void testMatchingOfObjectArray() { runTest("matching against Object[]"); } public void testMultipleAnonymousInnerClasses_pr108104() { runTest("multiple anonymous inner classes 2"); } public void testSignatureMatchingInMultipleOverrideScenario() { runTest("signature matching in override scenario"); } public void testWildcardAnnotationMatching_pr108245() { runTest("wildcard annotation matching - pr108245"); } public void testInnerTypesAndTypeVariables() { runTest("inner types and type variables"); } public void testAtAfterThrowingWithNoFormal() { runTest("@AfterThrowing with no formal specified"); } public void testParameterizedVarArgsMatch() { runTest("varargs with type variable"); } public void testFieldAccessInsideITDM() { runTest("itd field access inside itd method"); } public void testTypeVarWithTypeVarBound() { runTest("type variable with type variable bound"); } public void testEnumSwitchInITD() { runTest("switch on enum inside ITD method"); } public void testInnerTypeOfGeneric() { runTest("inner type of generic interface reference from parameterized type"); } public void testDeclareParentsIntroducingCovariantReturnType() { runTest("declare parents introducing override with covariance"); } public void testInnerClassPassedToVarargs() { runTest("inner class passed as argument to varargs method"); } public void testInlinedFieldAccessInProceedCall() { runTest("inlined field access in proceed call"); } public void testVisibiltyInSignatureMatchingWithOverridesPart1() { runTest("visibility in signature matching with overrides - 1"); } public void testVisibiltyInSignatureMatchingWithOverridesPart2() { runTest("visibility in signature matching with overrides - 2"); } public void testVisibiltyInSignatureMatchingWithOverridesPart3() { runTest("visibility in signature matching with overrides - 3"); } public void testArgsGeneratedCorrectlyForAdviceExecution() { runTest("args generated correctly for advice execution join point"); } public void testNoUnusedWarningsOnAspectTypes() { runTest("no unused warnings on aspect types"); } public void testSyntheticArgumentsOnITDConstructorsNotUsedInMatching() { runTest("synthetic arguments on itd cons are not used in matching"); } public void testParsingOfGenericTypeSignature() { runTest("parse generic type signature with parameterized type in interface"); } public void testOverrideAndCovarianceWithDecPRuntime() { runTest("override and covariance with decp - runtime"); } public void testOverrideAndCovarianceWithDecPRuntimeMultiFiles() { runTest("override and covariance with decp - runtime separate files"); } public void testAbstractSynchronizedITDMethods() { runTest("abstract synchronized itdms not detected"); } public void testSynchronizedITDInterfaceMethods() { runTest("synchronized itd interface methods"); } public void testNoWarningOnUnusedPointcut() { runTest("unused private pointcuts"); } public void testITDOnInterfaceWithExistingMember() { runTest("itd interface method already existing on interface"); } public void testFinalITDMOnInterface() { runTest("final itd methods on interfaces"); } public void testPrivatePointcutOverriding() { runTest("can't override private pointcut in abstract aspect"); } public void testAdviceOnCflow() { runTest("advising cflow advice execution"); } public void testNoTypeMismatchOnSameGenericTypes() { runTest("no type mismatch on generic types in itds"); } public void testSuperCallInITD() { runTest("super call in ITD"); } public void testSuperCallInITDPart2() { runTest("super call in ITD - part 2"); } public void testNoUnusedParameterWarningsForSyntheticAdviceArgs() { runTest("no unused parameter warnings for synthetic advice args"); } public void testNoVerifyErrorWithSetOnInnerType() { runTest("no verify error with set on inner type"); } public void testCantFindTypeErrorWithGenericReturnTypeOrParameter() { runTest("cant find type error with generic return type or parameter"); } // currently failing... // public void testNoVerifyErrorOnGenericCollectionMemberAccess() { // runTest("no verify error on generic collection member access"); // } // helper methods..... public SyntheticRepository createRepos(File cpentry) { ClassPath cp = new ClassPath(cpentry+File.pathSeparator+System.getProperty("java.class.path")); return SyntheticRepository.getInstance(cp); } protected JavaClass getClassFrom(File where,String clazzname) throws ClassNotFoundException { SyntheticRepository repos = createRepos(where); return repos.loadClass(clazzname); } }
103,740
Bug 103740 Compiler failure on @annotation
I'm using the ajc embedded in the latest dev build of AJDT (build 20050713163417) This small example illustrates the problem: public abstract aspect AbstractRequestMonitor { public pointcut requestExecution(RequestContext requestContext) : execution(* RequestContext.execute(..)) && this(requestContext); public abstract class RequestContext { public abstract Object execute(); } after(RequestContext requestContext) throwing (Throwable t) : requestExecution(requestContext) { } } import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Retention(RetentionPolicy.RUNTIME) public @interface AroundAdvice { } public aspect ErrorHandling { declare soft: Exception: !@annotation(AroundAdvice) && !withincode(* * (..)); Object around() : adviceexecution() && !@annotation(AroundAdvice) { try { return proceed(); } catch (Exception e) { return null; } } } Here's the stack trace I get: org.aspectj.weaver.BCException: bad at org.aspectj.weaver.bcel.BcelRenderer.visit(BcelRenderer.java:228) at org.aspectj.weaver.ast.Literal.accept(Literal.java:29) at org.aspectj.weaver.bcel.BcelRenderer.recur(BcelRenderer.java:151) at org.aspectj.weaver.bcel.BcelRenderer.renderTest (BcelRenderer.java:117) at org.aspectj.weaver.bcel.BcelAdvice.getTestInstructions (BcelAdvice.java:445) at org.aspectj.weaver.bcel.BcelShadow.weaveAroundClosure (BcelShadow.java:2585) at org.aspectj.weaver.bcel.BcelAdvice.implementOn(BcelAdvice.java:182) at org.aspectj.weaver.Shadow.implementMungers(Shadow.java:480) at org.aspectj.weaver.Shadow.implement(Shadow.java:358) at org.aspectj.weaver.bcel.BcelClassWeaver.implement (BcelClassWeaver.java:1703) at org.aspectj.weaver.bcel.BcelClassWeaver.weave (BcelClassWeaver.java:389) at org.aspectj.weaver.bcel.BcelClassWeaver.weave (BcelClassWeaver.java:94) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1362) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump (BcelWeaver.java:1327) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify (BcelWeaver.java:1106) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:981) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave (AjCompilerAdapter.java:286) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling (AjCompilerAdapter.java:165) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$afterReturning$org_aspec tj_ajdt_internal_compiler_CompilerAdapter$2$f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:368) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:727) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:206) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBuildManager.java:140) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:121) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:191)
resolved fixed
2ae4f53
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-12T13:37:56Z
2005-07-14T00:13:20Z
weaver/src/org/aspectj/weaver/patterns/AnnotationPointcut.java
/* ******************************************************************* * Copyright (c) 2004 IBM Corporation. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Set; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.AnnotatedElement; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.Member; import org.aspectj.weaver.NameMangler; import org.aspectj.weaver.NewFieldTypeMunger; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.ast.Literal; import org.aspectj.weaver.ast.Test; import org.aspectj.weaver.ast.Var; import org.aspectj.weaver.bcel.BcelTypeMunger; /** * @annotation(@Foo) or @annotation(foo) * * Matches any join point where the subject of the join point has an * annotation matching the annotationTypePattern: * * Join Point Kind Subject * ================================ * method call the target method * method execution the method * constructor call the constructor * constructor execution the constructor * get the target field * set the target field * adviceexecution the advice * initialization the constructor * preinitialization the constructor * staticinitialization the type being initialized * handler the declared type of the handled exception */ public class AnnotationPointcut extends NameBindingPointcut { private ExactAnnotationTypePattern annotationTypePattern; private ShadowMunger munger = null; // only set after concretization public AnnotationPointcut(ExactAnnotationTypePattern type) { super(); this.annotationTypePattern = type; this.pointcutKind = Pointcut.ANNOTATION; } public AnnotationPointcut(ExactAnnotationTypePattern type, ShadowMunger munger) { this(type); this.munger = munger; } public ExactAnnotationTypePattern getAnnotationTypePattern() { return annotationTypePattern; } public Set couldMatchKinds() { return Shadow.ALL_SHADOW_KINDS; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#fastMatch(org.aspectj.weaver.patterns.FastMatchInfo) */ public FuzzyBoolean fastMatch(FastMatchInfo info) { if (info.getKind() == Shadow.StaticInitialization) { return annotationTypePattern.fastMatches(info.getType()); } else { return FuzzyBoolean.MAYBE; } } public FuzzyBoolean fastMatch(Class targetType) { // TODO AMC return FuzzyBoolean.MAYBE; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#match(org.aspectj.weaver.Shadow) */ protected FuzzyBoolean matchInternal(Shadow shadow) { AnnotatedElement toMatchAgainst = null; Member member = shadow.getSignature(); ResolvedMember rMember = member.resolve(shadow.getIWorld()); if (rMember == null) { if (member.getName().startsWith(NameMangler.PREFIX)) { return FuzzyBoolean.NO; } shadow.getIWorld().getLint().unresolvableMember.signal(member.toString(), getSourceLocation()); return FuzzyBoolean.NO; } Shadow.Kind kind = shadow.getKind(); if (kind == Shadow.StaticInitialization) { toMatchAgainst = rMember.getDeclaringType().resolve(shadow.getIWorld()); } else if ( (kind == Shadow.ExceptionHandler)) { toMatchAgainst = rMember.getParameterTypes()[0].resolve(shadow.getIWorld()); } else { toMatchAgainst = rMember; // FIXME asc I'd like to get rid of this bit of logic altogether, shame ITD fields don't have an effective sig attribute // FIXME asc perf cache the result of discovering the member that contains the real annotations if (rMember.isAnnotatedElsewhere()) { if (kind==Shadow.FieldGet || kind==Shadow.FieldSet) { List mungers = rMember.getDeclaringType().resolve(shadow.getIWorld()).getInterTypeMungers(); // FIXME asc should include supers with getInterTypeMungersIncludingSupers? for (Iterator iter = mungers.iterator(); iter.hasNext();) { BcelTypeMunger typeMunger = (BcelTypeMunger) iter.next(); if (typeMunger.getMunger() instanceof NewFieldTypeMunger) { ResolvedMember fakerm = typeMunger.getSignature(); if (fakerm.equals(member)) { ResolvedMember ajcMethod = AjcMemberMaker.interFieldInitializer(fakerm,typeMunger.getAspectType()); ResolvedMember rmm = findMethod(typeMunger.getAspectType(),ajcMethod); toMatchAgainst = rmm; } } } } } } annotationTypePattern.resolve(shadow.getIWorld()); return annotationTypePattern.matches(toMatchAgainst); } private ResolvedMember findMethod(ResolvedType aspectType, ResolvedMember ajcMethod) { ResolvedMember decMethods[] = aspectType.getDeclaredMethods(); for (int i = 0; i < decMethods.length; i++) { ResolvedMember member = decMethods[i]; if (member.equals(ajcMethod)) return member; } return null; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#resolveBindings(org.aspectj.weaver.patterns.IScope, org.aspectj.weaver.patterns.Bindings) */ protected void resolveBindings(IScope scope, Bindings bindings) { annotationTypePattern = (ExactAnnotationTypePattern) annotationTypePattern.resolveBindings(scope,bindings,true); // must be either a Var, or an annotation type pattern } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#resolveBindingsFromRTTI() */ protected void resolveBindingsFromRTTI() { // TODO Auto-generated method stub } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#concretize1(org.aspectj.weaver.ResolvedType, org.aspectj.weaver.IntMap) */ protected Pointcut concretize1(ResolvedType inAspect, ResolvedType declaringType, IntMap bindings) { ExactAnnotationTypePattern newType = (ExactAnnotationTypePattern) annotationTypePattern.remapAdviceFormals(bindings); Pointcut ret = new AnnotationPointcut(newType, bindings.getEnclosingAdvice()); ret.copyLocationFrom(this); return ret; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#findResidue(org.aspectj.weaver.Shadow, org.aspectj.weaver.patterns.ExposedState) */ protected Test findResidueInternal(Shadow shadow, ExposedState state) { if (annotationTypePattern instanceof BindingAnnotationTypePattern) { BindingAnnotationTypePattern btp = (BindingAnnotationTypePattern)annotationTypePattern; UnresolvedType annotationType = btp.getAnnotationType(); Var var = shadow.getKindedAnnotationVar(annotationType); // This should not happen, we shouldn't have gotten this far // if we weren't going to find the annotation if (var == null) throw new BCException("Impossible! annotation=["+annotationType+ "] shadow=["+shadow+" at "+shadow.getSourceLocation()+ "] pointcut is at ["+getSourceLocation()+"]");//return Literal.FALSE; // Check if we have already bound something to this formal if ((state.get(btp.getFormalIndex())!=null) &&(lastMatchedShadowId == shadow.shadowId)) { // ISourceLocation pcdSloc = getSourceLocation(); // ISourceLocation shadowSloc = shadow.getSourceLocation(); // Message errorMessage = new Message( // "Cannot use @pointcut to match at this location and bind a formal to type '"+var.getType()+ // "' - the formal is already bound to type '"+state.get(btp.getFormalIndex()).getType()+"'"+ // ". The secondary source location points to the problematic binding.", // shadowSloc,true,new ISourceLocation[]{pcdSloc}); // shadow.getIWorld().getMessageHandler().handleMessage(errorMessage); state.setErroneousVar(btp.getFormalIndex()); } state.set(btp.getFormalIndex(),var); } return Literal.TRUE; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.NameBindingPointcut#getBindingAnnotationTypePatterns() */ public List getBindingAnnotationTypePatterns() { if (annotationTypePattern instanceof BindingAnnotationTypePattern) { List l = new ArrayList(); l.add(annotationTypePattern); return l; } else return Collections.EMPTY_LIST; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.NameBindingPointcut#getBindingTypePatterns() */ public List getBindingTypePatterns() { return Collections.EMPTY_LIST; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.PatternNode#write(java.io.DataOutputStream) */ public void write(DataOutputStream s) throws IOException { s.writeByte(Pointcut.ANNOTATION); annotationTypePattern.write(s); writeLocation(s); } public static Pointcut read(VersionedDataInputStream s, ISourceContext context) throws IOException { AnnotationTypePattern type = AnnotationTypePattern.read(s, context); AnnotationPointcut ret = new AnnotationPointcut((ExactAnnotationTypePattern)type); ret.readLocation(context, s); return ret; } public boolean equals(Object other) { if (!(other instanceof AnnotationPointcut)) return false; AnnotationPointcut o = (AnnotationPointcut)other; return o.annotationTypePattern.equals(this.annotationTypePattern); } public int hashCode() { int result = 17; result = 37*result + annotationTypePattern.hashCode(); return result; } public String toString() { StringBuffer buf = new StringBuffer(); buf.append("@annotation("); String annPatt = annotationTypePattern.toString(); buf.append(annPatt.startsWith("@") ? annPatt.substring(1) : annPatt); buf.append(")"); return buf.toString(); } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } }
109,486
Bug 109486 Internal compiler error (ClassParser.java:242)
Testcase: A.aj containing: final abstract aspect A {} This causes the compiler to abort with an internal compiler error: C:\Documents and Settings\mchapman\A.aj [error] Internal compiler error org.aspectj.apache.bcel.classfile.ClassFormatException: Class can't be both final and abstract at org.aspectj.apache.bcel.classfile.ClassParser.readClassInfo(ClassPars er.java:242) at org.aspectj.apache.bcel.classfile.ClassParser.parse(ClassParser.java: 165) at org.aspectj.weaver.bcel.Utility.makeJavaClass(Utility.java:489) at org.aspectj.weaver.bcel.UnwovenClassFile.getJavaClass(UnwovenClassFil e.java:63) at org.aspectj.weaver.bcel.UnwovenClassFile.getClassName(UnwovenClassFil e.java:147) at org.aspectj.ajdt.internal.core.builder.AjState.noteResult(AjState.jav a:497) at org.aspectj.ajdt.internal.core.builder.AjBuildManager$3.acceptResult( AjBuildManager.java:748) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterProcessing( AjCompilerAdapter.java:186) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$afterReturning $org_aspectj_ajdt_internal_compiler_CompilerAdapter$4$6b855184(CompilerAdapter.a j:89) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.process(Compil er.java:528) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compil er.java:329) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilat ion(AjBuildManager.java:728) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuild Manager.java:206) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBu ildManager.java:140) at org.aspectj.ajdt.ajc.AjdtCommand.doCommand(AjdtCommand.java:112) at org.aspectj.ajdt.ajc.AjdtCommand.runCommand(AjdtCommand.java:60) at org.aspectj.tools.ajc.Main.run(Main.java:324) at org.aspectj.tools.ajc.Main.runMain(Main.java:238) at org.aspectj.tools.ajc.Main.main(Main.java:82) (no source information available) C:\Documents and Settings\mchapman\A.aj:1 [error] The class A can be either abst ract or final, not both final abstract aspect A {} ABORT Exception thrown from AspectJ DEVELOPMENT C:\Documents and Settings\mchapman>ajc -version AspectJ Compiler DEVELOPMENT built on Tuesday Sep 13, 2005 at 22:31:40 GMT The expected behaviour is naturally just to get a regular compiler errror saying "The aspect A can be either abstract or final, not both".
resolved fixed
87e5c2e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-14T11:10:52Z
2005-09-14T09:26:40Z
bcel-builder/src/org/aspectj/apache/bcel/classfile/ClassParser.java
package org.aspectj.apache.bcel.classfile; /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Apache" and "Apache Software Foundation" and * "Apache BCEL" must not be used to endorse or promote products * derived from this software without prior written permission. For * written permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * "Apache BCEL", nor may "Apache" appear in their name, without * prior written permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ import org.aspectj.apache.bcel.Constants; import java.io.*; import java.util.zip.*; /** * Wrapper class that parses a given Java .class file. The method <A * href ="#parse">parse</A> returns a <A href ="JavaClass.html"> * JavaClass</A> object on success. When an I/O error or an * inconsistency occurs an appropiate exception is propagated back to * the caller. * * The structure and the names comply, except for a few conveniences, * exactly with the <A href="ftp://java.sun.com/docs/specs/vmspec.ps"> * JVM specification 1.0</a>. See this paper for * further details about the structure of a bytecode file. * * @version $Id: ClassParser.java,v 1.2 2004/11/19 16:45:18 aclement Exp $ * @author <A HREF="mailto:[email protected]">M. Dahm</A> */ public final class ClassParser { private DataInputStream file; private ZipFile zip; private String file_name; private int class_name_index, superclass_name_index; private int major, minor; // Compiler version private int access_flags; // Access rights of parsed class private int[] interfaces; // Names of implemented interfaces private ConstantPool constant_pool; // collection of constants private Field[] fields; // class fields, i.e., its variables private Method[] methods; // methods defined in the class private Attribute[] attributes; // attributes defined in the class private boolean is_zip; // Loaded from zip file private static final int BUFSIZE = 8192; /** * Parse class from the given stream. * * @param file Input stream * @param file_name File name */ public ClassParser(InputStream file, String file_name) { this.file_name = file_name; String clazz = file.getClass().getName(); // Not a very clean solution ... is_zip = clazz.startsWith("java.util.zip.") || clazz.startsWith("java.util.jar."); if(file instanceof DataInputStream) // Is already a data stream this.file = (DataInputStream)file; else this.file = new DataInputStream(new BufferedInputStream(file, BUFSIZE)); } /** Parse class from given .class file. * * @param file_name file name * @throws IOException */ public ClassParser(String file_name) throws IOException { is_zip = false; this.file_name = file_name; file = new DataInputStream(new BufferedInputStream (new FileInputStream(file_name), BUFSIZE)); } /** Parse class from given .class file in a ZIP-archive * * @param file_name file name * @throws IOException */ public ClassParser(String zip_file, String file_name) throws IOException { is_zip = true; zip = new ZipFile(zip_file); ZipEntry entry = zip.getEntry(file_name); this.file_name = file_name; file = new DataInputStream(new BufferedInputStream(zip.getInputStream(entry), BUFSIZE)); } /** * Parse the given Java class file and return an object that represents * the contained data, i.e., constants, methods, fields and commands. * A <em>ClassFormatException</em> is raised, if the file is not a valid * .class file. (This does not include verification of the byte code as it * is performed by the java interpreter). * * @return Class object representing the parsed class file * @throws IOException * @throws ClassFormatException */ public JavaClass parse() throws IOException, ClassFormatException { /****************** Read headers ********************************/ // Check magic tag of class file readID(); // Get compiler version readVersion(); /****************** Read constant pool and related **************/ // Read constant pool entries readConstantPool(); // Get class information readClassInfo(); // Get interface information, i.e., implemented interfaces readInterfaces(); /****************** Read class fields and methods ***************/ // Read class fields, i.e., the variables of the class readFields(); // Read class methods, i.e., the functions in the class readMethods(); // Read class attributes readAttributes(); // Check for unknown variables //Unknown[] u = Unknown.getUnknownAttributes(); //for(int i=0; i < u.length; i++) // System.err.println("WARNING: " + u[i]); // Everything should have been read now // if(file.available() > 0) { // int bytes = file.available(); // byte[] buf = new byte[bytes]; // file.read(buf); // if(!(is_zip && (buf.length == 1))) { // System.err.println("WARNING: Trailing garbage at end of " + file_name); // System.err.println(bytes + " extra bytes: " + Utility.toHexString(buf)); // } // } // Read everything of interest, so close the file file.close(); if(zip != null) zip.close(); // Return the information we have gathered in a new object return new JavaClass(class_name_index, superclass_name_index, file_name, major, minor, access_flags, constant_pool, interfaces, fields, methods, attributes, is_zip? JavaClass.ZIP : JavaClass.FILE); } /** * Read information about the attributes of the class. * @throws IOException * @throws ClassFormatException */ private final void readAttributes() throws IOException, ClassFormatException { int attributes_count; attributes_count = file.readUnsignedShort(); attributes = new Attribute[attributes_count]; for(int i=0; i < attributes_count; i++) attributes[i] = Attribute.readAttribute(file, constant_pool); } /** * Read information about the class and its super class. * @throws IOException * @throws ClassFormatException */ private final void readClassInfo() throws IOException, ClassFormatException { access_flags = file.readUnsignedShort(); /* Interfaces are implicitely abstract, the flag should be set * according to the JVM specification. */ if((access_flags & Constants.ACC_INTERFACE) != 0) access_flags |= Constants.ACC_ABSTRACT; if(((access_flags & Constants.ACC_ABSTRACT) != 0) && ((access_flags & Constants.ACC_FINAL) != 0 )) throw new ClassFormatException("Class can't be both final and abstract"); class_name_index = file.readUnsignedShort(); superclass_name_index = file.readUnsignedShort(); } /** * Read constant pool entries. * @throws IOException * @throws ClassFormatException */ private final void readConstantPool() throws IOException, ClassFormatException { constant_pool = new ConstantPool(file); } /** * Read information about the fields of the class, i.e., its variables. * @throws IOException * @throws ClassFormatException */ private final void readFields() throws IOException, ClassFormatException { int fields_count; fields_count = file.readUnsignedShort(); fields = new Field[fields_count]; for(int i=0; i < fields_count; i++) fields[i] = new Field(file, constant_pool); } /******************** Private utility methods **********************/ /** * Check whether the header of the file is ok. * Of course, this has to be the first action on successive file reads. * @throws IOException * @throws ClassFormatException */ private final void readID() throws IOException, ClassFormatException { int magic = 0xCAFEBABE; if(file.readInt() != magic) throw new ClassFormatException(file_name + " is not a Java .class file"); } /** * Read information about the interfaces implemented by this class. * @throws IOException * @throws ClassFormatException */ private final void readInterfaces() throws IOException, ClassFormatException { int interfaces_count; interfaces_count = file.readUnsignedShort(); interfaces = new int[interfaces_count]; for(int i=0; i < interfaces_count; i++) interfaces[i] = file.readUnsignedShort(); } /** * Read information about the methods of the class. * @throws IOException * @throws ClassFormatException */ private final void readMethods() throws IOException, ClassFormatException { int methods_count; methods_count = file.readUnsignedShort(); methods = new Method[methods_count]; for(int i=0; i < methods_count; i++) methods[i] = new Method(file, constant_pool); } /** * Read major and minor version of compiler which created the file. * @throws IOException * @throws ClassFormatException */ private final void readVersion() throws IOException, ClassFormatException { minor = file.readUnsignedShort(); major = file.readUnsignedShort(); } }
109,486
Bug 109486 Internal compiler error (ClassParser.java:242)
Testcase: A.aj containing: final abstract aspect A {} This causes the compiler to abort with an internal compiler error: C:\Documents and Settings\mchapman\A.aj [error] Internal compiler error org.aspectj.apache.bcel.classfile.ClassFormatException: Class can't be both final and abstract at org.aspectj.apache.bcel.classfile.ClassParser.readClassInfo(ClassPars er.java:242) at org.aspectj.apache.bcel.classfile.ClassParser.parse(ClassParser.java: 165) at org.aspectj.weaver.bcel.Utility.makeJavaClass(Utility.java:489) at org.aspectj.weaver.bcel.UnwovenClassFile.getJavaClass(UnwovenClassFil e.java:63) at org.aspectj.weaver.bcel.UnwovenClassFile.getClassName(UnwovenClassFil e.java:147) at org.aspectj.ajdt.internal.core.builder.AjState.noteResult(AjState.jav a:497) at org.aspectj.ajdt.internal.core.builder.AjBuildManager$3.acceptResult( AjBuildManager.java:748) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterProcessing( AjCompilerAdapter.java:186) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$afterReturning $org_aspectj_ajdt_internal_compiler_CompilerAdapter$4$6b855184(CompilerAdapter.a j:89) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.process(Compil er.java:528) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compil er.java:329) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilat ion(AjBuildManager.java:728) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuild Manager.java:206) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBu ildManager.java:140) at org.aspectj.ajdt.ajc.AjdtCommand.doCommand(AjdtCommand.java:112) at org.aspectj.ajdt.ajc.AjdtCommand.runCommand(AjdtCommand.java:60) at org.aspectj.tools.ajc.Main.run(Main.java:324) at org.aspectj.tools.ajc.Main.runMain(Main.java:238) at org.aspectj.tools.ajc.Main.main(Main.java:82) (no source information available) C:\Documents and Settings\mchapman\A.aj:1 [error] The class A can be either abst ract or final, not both final abstract aspect A {} ABORT Exception thrown from AspectJ DEVELOPMENT C:\Documents and Settings\mchapman>ajc -version AspectJ Compiler DEVELOPMENT built on Tuesday Sep 13, 2005 at 22:31:40 GMT The expected behaviour is naturally just to get a regular compiler errror saying "The aspect A can be either abstract or final, not both".
resolved fixed
87e5c2e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-14T11:10:52Z
2005-09-14T09:26:40Z
tests/bugs150/PR109486.java
109,486
Bug 109486 Internal compiler error (ClassParser.java:242)
Testcase: A.aj containing: final abstract aspect A {} This causes the compiler to abort with an internal compiler error: C:\Documents and Settings\mchapman\A.aj [error] Internal compiler error org.aspectj.apache.bcel.classfile.ClassFormatException: Class can't be both final and abstract at org.aspectj.apache.bcel.classfile.ClassParser.readClassInfo(ClassPars er.java:242) at org.aspectj.apache.bcel.classfile.ClassParser.parse(ClassParser.java: 165) at org.aspectj.weaver.bcel.Utility.makeJavaClass(Utility.java:489) at org.aspectj.weaver.bcel.UnwovenClassFile.getJavaClass(UnwovenClassFil e.java:63) at org.aspectj.weaver.bcel.UnwovenClassFile.getClassName(UnwovenClassFil e.java:147) at org.aspectj.ajdt.internal.core.builder.AjState.noteResult(AjState.jav a:497) at org.aspectj.ajdt.internal.core.builder.AjBuildManager$3.acceptResult( AjBuildManager.java:748) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterProcessing( AjCompilerAdapter.java:186) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$afterReturning $org_aspectj_ajdt_internal_compiler_CompilerAdapter$4$6b855184(CompilerAdapter.a j:89) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.process(Compil er.java:528) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compil er.java:329) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilat ion(AjBuildManager.java:728) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuild Manager.java:206) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBu ildManager.java:140) at org.aspectj.ajdt.ajc.AjdtCommand.doCommand(AjdtCommand.java:112) at org.aspectj.ajdt.ajc.AjdtCommand.runCommand(AjdtCommand.java:60) at org.aspectj.tools.ajc.Main.run(Main.java:324) at org.aspectj.tools.ajc.Main.runMain(Main.java:238) at org.aspectj.tools.ajc.Main.main(Main.java:82) (no source information available) C:\Documents and Settings\mchapman\A.aj:1 [error] The class A can be either abst ract or final, not both final abstract aspect A {} ABORT Exception thrown from AspectJ DEVELOPMENT C:\Documents and Settings\mchapman>ajc -version AspectJ Compiler DEVELOPMENT built on Tuesday Sep 13, 2005 at 22:31:40 GMT The expected behaviour is naturally just to get a regular compiler errror saying "The aspect A can be either abstract or final, not both".
resolved fixed
87e5c2e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-14T11:10:52Z
2005-09-14T09:26:40Z
tests/src/org/aspectj/systemtest/ajc150/Ajc150Tests.java
/******************************************************************************* * Copyright (c) 2004 IBM * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Andy Clement - initial API and implementation *******************************************************************************/ package org.aspectj.systemtest.ajc150; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import junit.framework.Test; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.apache.bcel.classfile.Method; import org.aspectj.apache.bcel.util.ClassPath; import org.aspectj.apache.bcel.util.SyntheticRepository; import org.aspectj.asm.AsmManager; import org.aspectj.testing.XMLBasedAjcTestCase; import org.aspectj.util.LangUtil; /** * These are tests that will run on Java 1.4 and use the old harness format for test specification. */ public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase { public static Test suite() { return XMLBasedAjcTestCase.loadSuite(Ajc150Tests.class); } protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml"); } public void test_typeProcessingOrderWhenDeclareParents() { runTest("Order of types passed to compiler determines weaving behavior"); } public void test_aroundMethod() { runTest("method called around in class"); } public void test_aroundMethodAspect() { runTest("method called around in aspect"); } public void test_ambiguousBindingsDetection() { runTest("Various kinds of ambiguous bindings"); } public void test_ambiguousArgsDetection() { runTest("ambiguous args"); } public void testIncorrectExceptionTableWhenBreakInMethod_pr78021() { runTest("Injecting exception into while loop with break statement causes catch block to be ignored"); } public void testIncorrectExceptionTableWhenReturnInMethod_pr79554() { runTest("Return in try-block disables catch-block if final-block is present"); } public void testMissingDebugInfoForGeneratedMethods_pr82570() throws ClassNotFoundException { runTest("Weaved code does not include debug lines"); boolean f = false; JavaClass jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1"); Method[] meths = jc.getMethods(); for (int i = 0; i < meths.length; i++) { Method method = meths[i]; if (f) System.err.println("Line number table for "+method.getName()+method.getSignature()+" = "+method.getLineNumberTable()); assertTrue("Didn't find a line number table for method "+method.getName()+method.getSignature(), method.getLineNumberTable()!=null); } // This test would determine the info isn't there if you pass -g:none ... // cR = ajc(baseDir,new String[]{"PR82570_1.java","-g:none"}); // assertTrue("Expected no compile problem:"+cR,!cR.hasErrorMessages()); // System.err.println(cR.getStandardError()); // jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1"); // meths = jc.getMethods(); // for (int i = 0; i < meths.length; i++) { // Method method = meths[i]; // assertTrue("Found a line number table for method "+method.getName(), // method.getLineNumberTable()==null); // } } public void testCanOverrideProtectedMethodsViaITDandDecp_pr83303() { runTest("compiler error when mixing inheritance, overriding and polymorphism"); } public void testPerTypeWithin_pr106554() {runTest("Problem in staticinitialization with pertypewithin aspect");} public void testPerTypeWithinMissesNamedInnerTypes() { runTest("pertypewithin() handing of inner classes (1)"); } public void testPerTypeWithinMissesAnonymousInnerTypes() { runTest("pertypewithin() handing of inner classes (2)"); } public void testPerTypeWithinIncorrectlyMatchingInterfaces() { runTest("pertypewithin({interface}) illegal field modifier"); } public void test051_arrayCloningInJava5() { runTest("AJC possible bug with static nested classes"); } public void testBadASMforEnums() throws IOException { runTest("bad asm for enums"); if (LangUtil.is15VMOrGreater()) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintWriter pw = new PrintWriter(baos); AsmManager.dumptree(pw,AsmManager.getDefault().getHierarchy().getRoot(),0); pw.flush(); String tree = baos.toString(); assertTrue("Expected 'Red [enumvalue]' somewhere in here:"+tree,tree.indexOf("Red [enumvalue]")!=-1); } } public void npeOnTypeNotFound() { runTest("structure model npe on type not found"); } public void testNoRuntimeExceptionSoftening() { runTest("declare soft of runtime exception"); } public void testRuntimeNoSoftenWithHandler() { runTest("declare soft w. catch block"); } public void testSyntaxError() { runTest("invalid cons syntax"); } public void testVarargsInConsBug() { runTest("varargs in constructor sig"); } public void testAspectpathdirs() { runTest("dirs on aspectpath"); } public void testIntroSample() { runTest("introduction sample"); } public void testPTWInterface() { runTest("pertypewithin({interface}) illegal field modifier"); } public void testEnumCalledEnumEtc() { runTest("enum called Enum, annotation called Annotation, etc"); } public void testInternalCompilerError_pr86832() { runTest("Internal compiler error"); } public void testCloneMethod_pr83311() { runTest("overriding/polymorphism error on interface method introduction"); } /** * IfPointcut.findResidueInternal() was modified to make this test complete in a short amount * of time - if you see it hanging, someone has messed with the optimization. */ public void testIfEvaluationExplosion_pr94086() { runTest("Exploding compile time with if() statements in pointcut"); } public void testReflectNPE_pr94167() {runTest("NPE in reflect implementation");} public void testStaticImports_pr84260() {runTest("static import failures");} public void testGenerics_pr99089() {runTest("ArrayIndexOutOfBoundsException - Generics in privileged aspects");} public void testGenerics_pr95993() {runTest("NPE at ClassScope.java:660 when compiling generic class");} public void testItdGenerics_pr99228() {runTest("ITD of a field into a generic class");} public void testItdGenerics_pr98320() {runTest("intertype with nested generic type");} public void testItdGenerics_pr100227() {runTest("inner class with generic enclosing class");} public void testItdGenerics_pr100260() {runTest("methods inherited from a generic parent");} public void testSyntaxErrorNPE_pr103266() {runTest("NPE on syntax error");} public void testIllegalStateExceptionOnNestedParameterizedType_pr106634() { runTest("IllegalStateException unpacking signature of nested parameterized type"); } public void testParseErrorOnAnnotationStarPlusPattern() { runTest("(@Foo *)+ type pattern parse error"); } public void test_pr106130_tooManyLocals() { runTest("test weaving with > 256 locals"); } public void testMissingNamePattern_pr106461() { runTest("missing name pattern"); } public void testMissingNamePattern_pr107059() { runTest("parser crashes on call(void (@a *)(..)"); } public void testIntermediateAnnotationMatching() { runTest("intermediate annotation matching"); } public void testBadRuntimeTestGeneration() { runTest("target(@Foo *)"); } public void testErrorMessageOnITDWithTypePatterns() { runTest("clear error message on itd with type pattern"); } public void testAjKeywordsAsIdentifiers() { runTest("before and after are valid identifiers in classes"); } public void testAjKeywordsAsIdentifiers2() { runTest("before and after are valid identifiers in classes, part 2"); } public void testNoBeforeReturningAdvice() { runTest("before returning advice not allowed!"); } public void testDetectVoidFieldType() { runTest("void field type in pointcut expression"); } public void testPointcutOverriding() { runTest("overriding final pointcut from super-aspect"); } public void testAtSuppressWarnings() { runTest("@SuppressWarnings should suppress"); } public void testDEOWWithBindingPointcut() { runTest("declare warning : foo(str) : ...;"); } public void testAroundAdviceAndInterfaceInitializer() { runTest("around advice on interface initializer"); } public void testGoodErrorMessageOnUnmatchedMemberSyntax() { runTest("good error message for unmatched member syntax"); } public void testITDWithNoExceptionAndIntermediary() { runTest("itd override with no exception clause"); } public void testAnonymousInnerClasses() { runTest("anonymous inner classes"); } public void testMultipleAnonymousInnerClasses() { runTest("multiple anonymous inner classes"); } public void testPrivilegedMethodAccessorsGetRightExceptions_pr82989() { runTest("Compiler error due to a wrong exception check in try blocks"); } public void testAnonymousInnerClassWithMethodReturningTypeParameter_pr107898() { runTest("anonymous inner class with method returning type parameter"); } public void testMatchingOfObjectArray() { runTest("matching against Object[]"); } public void testMultipleAnonymousInnerClasses_pr108104() { runTest("multiple anonymous inner classes 2"); } public void testSignatureMatchingInMultipleOverrideScenario() { runTest("signature matching in override scenario"); } public void testWildcardAnnotationMatching_pr108245() { runTest("wildcard annotation matching - pr108245"); } public void testInnerTypesAndTypeVariables() { runTest("inner types and type variables"); } public void testAtAfterThrowingWithNoFormal() { runTest("@AfterThrowing with no formal specified"); } public void testParameterizedVarArgsMatch() { runTest("varargs with type variable"); } public void testFieldAccessInsideITDM() { runTest("itd field access inside itd method"); } public void testTypeVarWithTypeVarBound() { runTest("type variable with type variable bound"); } public void testEnumSwitchInITD() { runTest("switch on enum inside ITD method"); } public void testInnerTypeOfGeneric() { runTest("inner type of generic interface reference from parameterized type"); } public void testDeclareParentsIntroducingCovariantReturnType() { runTest("declare parents introducing override with covariance"); } public void testInnerClassPassedToVarargs() { runTest("inner class passed as argument to varargs method"); } public void testInlinedFieldAccessInProceedCall() { runTest("inlined field access in proceed call"); } public void testVisibiltyInSignatureMatchingWithOverridesPart1() { runTest("visibility in signature matching with overrides - 1"); } public void testVisibiltyInSignatureMatchingWithOverridesPart2() { runTest("visibility in signature matching with overrides - 2"); } public void testVisibiltyInSignatureMatchingWithOverridesPart3() { runTest("visibility in signature matching with overrides - 3"); } public void testArgsGeneratedCorrectlyForAdviceExecution() { runTest("args generated correctly for advice execution join point"); } public void testNoUnusedWarningsOnAspectTypes() { runTest("no unused warnings on aspect types"); } public void testSyntheticArgumentsOnITDConstructorsNotUsedInMatching() { runTest("synthetic arguments on itd cons are not used in matching"); } public void testParsingOfGenericTypeSignature() { runTest("parse generic type signature with parameterized type in interface"); } public void testOverrideAndCovarianceWithDecPRuntime() { runTest("override and covariance with decp - runtime"); } public void testOverrideAndCovarianceWithDecPRuntimeMultiFiles() { runTest("override and covariance with decp - runtime separate files"); } public void testAbstractSynchronizedITDMethods() { runTest("abstract synchronized itdms not detected"); } public void testSynchronizedITDInterfaceMethods() { runTest("synchronized itd interface methods"); } public void testNoWarningOnUnusedPointcut() { runTest("unused private pointcuts"); } public void testITDOnInterfaceWithExistingMember() { runTest("itd interface method already existing on interface"); } public void testFinalITDMOnInterface() { runTest("final itd methods on interfaces"); } public void testPrivatePointcutOverriding() { runTest("can't override private pointcut in abstract aspect"); } public void testAdviceOnCflow() { runTest("advising cflow advice execution"); } public void testNoTypeMismatchOnSameGenericTypes() { runTest("no type mismatch on generic types in itds"); } public void testSuperCallInITD() { runTest("super call in ITD"); } public void testSuperCallInITDPart2() { runTest("super call in ITD - part 2"); } public void testAtAnnotationBadTest_pr103740() { runTest("Compiler failure on at_annotation"); } public void testNoUnusedParameterWarningsForSyntheticAdviceArgs() { runTest("no unused parameter warnings for synthetic advice args"); } public void testNoVerifyErrorWithSetOnInnerType() { runTest("no verify error with set on inner type"); } public void testCantFindTypeErrorWithGenericReturnTypeOrParameter() { runTest("cant find type error with generic return type or parameter"); } public void testNoVerifyErrorOnGenericCollectionMemberAccess() { runTest("no verify error on generic collection member access"); } public void testRawAndGenericTypeConversionITDCons() { runTest("raw and generic type conversion with itd cons"); } // helper methods..... public SyntheticRepository createRepos(File cpentry) { ClassPath cp = new ClassPath(cpentry+File.pathSeparator+System.getProperty("java.class.path")); return SyntheticRepository.getInstance(cp); } protected JavaClass getClassFrom(File where,String clazzname) throws ClassNotFoundException { SyntheticRepository repos = createRepos(where); return repos.loadClass(clazzname); } }
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26:40Z
aspectj5rt/java5-src/org/aspectj/internal/lang/reflect/AjTypeImpl.java
/* ******************************************************************* * Copyright (c) 2005 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * Adrian Colyer Initial implementation * ******************************************************************/ package org.aspectj.internal.lang.reflect; import java.lang.annotation.Annotation; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.util.ArrayList; import java.util.Arrays; import java.util.EnumSet; import java.util.List; import java.util.Set; import org.aspectj.internal.lang.annotation.ajcDeclareEoW; import org.aspectj.internal.lang.annotation.ajcPrivileged; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.AfterThrowing; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.DeclareError; import org.aspectj.lang.annotation.DeclareWarning; import org.aspectj.lang.reflect.Advice; import org.aspectj.lang.reflect.AdviceType; import org.aspectj.lang.reflect.AjType; import org.aspectj.lang.reflect.AjTypeSystem; import org.aspectj.lang.reflect.DeclareAnnotation; import org.aspectj.lang.reflect.DeclareErrorOrWarning; import org.aspectj.lang.reflect.DeclareParents; import org.aspectj.lang.reflect.DeclarePrecedence; import org.aspectj.lang.reflect.DeclareSoft; import org.aspectj.lang.reflect.InterTypeConstructorDeclaration; import org.aspectj.lang.reflect.InterTypeFieldDeclaration; import org.aspectj.lang.reflect.InterTypeMethodDeclaration; import org.aspectj.lang.reflect.NoSuchAdviceException; import org.aspectj.lang.reflect.NoSuchPointcutException; import org.aspectj.lang.reflect.PerClause; import org.aspectj.lang.reflect.PerClauseKind; import org.aspectj.lang.reflect.Pointcut; /** * @author colyer * */ public class AjTypeImpl<T> implements AjType { private static final String ajcMagic = "ajc$"; private Class<T> clazz; private Pointcut[] declaredPointcuts = null; private Pointcut[] pointcuts = null; private Advice[] declaredAdvice = null; private Advice[] advice = null; public AjTypeImpl(Class<T> fromClass) { this.clazz = fromClass; } /* (non-Javadoc) * @see org.aspectj.lang.reflect.AjType#getName() */ public String getName() { return clazz.getName(); } /* (non-Javadoc) * @see org.aspectj.lang.reflect.AjType#getPackage() */ public Package getPackage() { return clazz.getPackage(); } /* (non-Javadoc) * @see org.aspectj.lang.reflect.AjType#getInterfaces() */ public Class[] getInterfaces() { return clazz.getInterfaces(); } /* (non-Javadoc) * @see org.aspectj.lang.reflect.AjType#getModifiers() */ public int getModifiers() { return clazz.getModifiers(); } /* (non-Javadoc) * @see org.aspectj.lang.reflect.AjType#getSupertype() */ public AjType getSupertype() { return new AjTypeImpl(clazz.getSuperclass()); } /* (non-Javadoc) * @see org.aspectj.lang.reflect.AjType#getGenericSupertype() */ public Type getGenericSupertype() { return clazz.getGenericSuperclass(); } /* (non-Javadoc) * @see org.aspectj.lang.reflect.AjType#getEnclosingMethod() */ public Method getEnclosingMethod() { return clazz.getEnclosingMethod(); } /* (non-Javadoc) * @see org.aspectj.lang.reflect.AjType#getEnclosingConstructor() */ public Constructor getEnclosingConstructor() { return clazz.getEnclosingConstructor(); } /* (non-Javadoc) * @see org.aspectj.lang.reflect.AjType#getEnclosingType() */ public AjType getEnclosingType() { Class<?> enc = clazz.getEnclosingClass(); return enc != null ? new AjTypeImpl(enc) : null; } /* (non-Javadoc) * @see org.aspectj.lang.reflect.AjType#getDeclaringType() */ public AjType getDeclaringType() { Class dec = clazz.getDeclaringClass(); return dec != null ? new AjTypeImpl(dec) : null; } public PerClause getPerClause() { if (isAspect()) { Aspect aspectAnn = clazz.getAnnotation(Aspect.class); String perClause = aspectAnn.value(); if (perClause.equals("")) { return new PerClauseImpl(PerClauseKind.SINGLETON,""); } else if (perClause.startsWith("perthis(")) { return new PerClauseImpl(PerClauseKind.PERTHIS,perClause.substring("perthis(".length(),perClause.length() - 1)); } else if (perClause.startsWith("pertarget(")) { return new PerClauseImpl(PerClauseKind.PERTARGET,perClause.substring("pertarget(".length(),perClause.length() - 1)); } else if (perClause.startsWith("percflow(")) { return new PerClauseImpl(PerClauseKind.PERCFLOW,perClause.substring("percflow(".length(),perClause.length() - 1)); } else if (perClause.startsWith("percflowbelow(")) { return new PerClauseImpl(PerClauseKind.PERCFLOWBELOW,perClause.substring("percflowbelow(".length(),perClause.length() - 1)); } else if (perClause.startsWith("pertypewithin")) { return new PerClauseImpl(PerClauseKind.PERTYPEWITHIN,perClause.substring("pertypewithin(".length(),perClause.length() - 1)); } else { throw new IllegalStateException("Per-clause not recognized: " + perClause); } } else { return null; } } /* (non-Javadoc) * @see org.aspectj.lang.reflect.AjType#isAnnotationPresent(java.lang.Class) */ public boolean isAnnotationPresent(Class annotationType) { return clazz.isAnnotationPresent(annotationType); } public Annotation getAnnotation(Class annotationType) { return clazz.getAnnotation(annotationType); } /* (non-Javadoc) * @see org.aspectj.lang.reflect.AjType#getAnnotations() */ public Annotation[] getAnnotations() { return clazz.getAnnotations(); } /* (non-Javadoc) * @see org.aspectj.lang.reflect.AjType#getDeclaredAnnotations() */ public Annotation[] getDeclaredAnnotations() { return clazz.getDeclaredAnnotations(); } /* (non-Javadoc) * @see org.aspectj.lang.reflect.AjType#getAspects() */ public AjType[] getAjTypes() { Class[] classes = clazz.getClasses(); AjType[] ret = new AjType[classes.length]; for (int i = 0; i < ret.length; i++) { ret[i] = new AjTypeImpl(classes[i]); } return ret; } /* (non-Javadoc) * @see org.aspectj.lang.reflect.AjType#getDeclaredAspects() */ public AjType[] getDeclaredAjTypes() { Class[] classes = clazz.getDeclaredClasses(); AjType[] ret = new AjType[classes.length]; for (int i = 0; i < ret.length; i++) { ret[i] = new AjTypeImpl(classes[i]); } return ret; } /* (non-Javadoc) * @see org.aspectj.lang.reflect.AjType#getConstructor(java.lang.Class...) */ public Constructor getConstructor(Class... parameterTypes) throws NoSuchMethodException { return clazz.getConstructor(parameterTypes); } /* (non-Javadoc) * @see org.aspectj.lang.reflect.AjType#getConstructors() */ public Constructor[] getConstructors() { return clazz.getConstructors(); } /* (non-Javadoc) * @see org.aspectj.lang.reflect.AjType#getDeclaredConstructor(java.lang.Class...) */ public Constructor getDeclaredConstructor(Class... parameterTypes) throws NoSuchMethodException { return clazz.getDeclaredConstructor(parameterTypes); } /* (non-Javadoc) * @see org.aspectj.lang.reflect.AjType#getDeclaredConstructors() */ public Constructor[] getDeclaredConstructors() { return clazz.getDeclaredConstructors(); } /* (non-Javadoc) * @see org.aspectj.lang.reflect.AjType#getDeclaredField(java.lang.String) */ public Field getDeclaredField(String name) throws NoSuchFieldException { Field f = clazz.getDeclaredField(name); if (f.getName().startsWith(ajcMagic)) throw new NoSuchFieldException(name); return f; } /* (non-Javadoc) * @see org.aspectj.lang.reflect.AjType#getDeclaredFields() */ public Field[] getDeclaredFields() { Field[] fields = clazz.getDeclaredFields(); List<Field> filteredFields = new ArrayList<Field>(); for (Field field : fields) if (!field.getName().startsWith(ajcMagic) && !field.isAnnotationPresent(DeclareWarning.class) && !field.isAnnotationPresent(DeclareError.class)) { filteredFields.add(field); } Field[] ret = new Field[filteredFields.size()]; filteredFields.toArray(ret); return ret; } /* (non-Javadoc) * @see org.aspectj.lang.reflect.AjType#getField(java.lang.String) */ public Field getField(String name) throws NoSuchFieldException { Field f = clazz.getDeclaredField(name); if (f.getName().startsWith(ajcMagic)) throw new NoSuchFieldException(name); return f; } /* (non-Javadoc) * @see org.aspectj.lang.reflect.AjType#getFields() */ public Field[] getFields() { Field[] fields = clazz.getFields(); List<Field> filteredFields = new ArrayList<Field>(); for (Field field : fields) if (!field.getName().startsWith(ajcMagic) && !field.isAnnotationPresent(DeclareWarning.class) && !field.isAnnotationPresent(DeclareError.class)) { filteredFields.add(field); } Field[] ret = new Field[filteredFields.size()]; filteredFields.toArray(ret); return ret; } /* (non-Javadoc) * @see org.aspectj.lang.reflect.AjType#getDeclaredMethod(java.lang.String, java.lang.Class...) */ public Method getDeclaredMethod(String name, Class... parameterTypes) throws NoSuchMethodException { Method m = clazz.getDeclaredMethod(name,parameterTypes); if (!isReallyAMethod(m)) throw new NoSuchMethodException(name); return m; } /* (non-Javadoc) * @see org.aspectj.lang.reflect.AjType#getMethod(java.lang.String, java.lang.Class...) */ public Method getMethod(String name, Class... parameterTypes) throws NoSuchMethodException { Method m = clazz.getMethod(name,parameterTypes); if (!isReallyAMethod(m)) throw new NoSuchMethodException(name); return m; } /* (non-Javadoc) * @see org.aspectj.lang.reflect.AjType#getDeclaredMethods() */ public Method[] getDeclaredMethods() { Method[] methods = clazz.getDeclaredMethods(); List<Method> filteredMethods = new ArrayList<Method>(); for (Method method : methods) { if (isReallyAMethod(method)) filteredMethods.add(method); } Method[] ret = new Method[filteredMethods.size()]; filteredMethods.toArray(ret); return ret; } /* (non-Javadoc) * @see org.aspectj.lang.reflect.AjType#getMethods() */ public Method[] getMethods() { Method[] methods = clazz.getMethods(); List<Method> filteredMethods = new ArrayList<Method>(); for (Method method : methods) { if (isReallyAMethod(method)) filteredMethods.add(method); } Method[] ret = new Method[filteredMethods.size()]; filteredMethods.toArray(ret); return ret; } private boolean isReallyAMethod(Method method) { if (method.getName().startsWith(ajcMagic)) return false; if (method.isAnnotationPresent(org.aspectj.lang.annotation.Pointcut.class)) return false; if (method.isAnnotationPresent(Before.class)) return false; if (method.isAnnotationPresent(After.class)) return false; if (method.isAnnotationPresent(AfterReturning.class)) return false; if (method.isAnnotationPresent(AfterThrowing.class)) return false; if (method.isAnnotationPresent(Around.class)) return false; return true; } /* (non-Javadoc) * @see org.aspectj.lang.reflect.AjType#getDeclaredPointcut(java.lang.String) */ public Pointcut getDeclaredPointcut(String name) throws NoSuchPointcutException { Pointcut[] pcs = getDeclaredPointcuts(); for (Pointcut pc : pcs) if (pc.getName().equals(name)) return pc; throw new NoSuchPointcutException(name); } /* (non-Javadoc) * @see org.aspectj.lang.reflect.AjType#getPointcut(java.lang.String) */ public Pointcut getPointcut(String name) throws NoSuchPointcutException { Pointcut[] pcs = getDeclaredPointcuts(); for (Pointcut pc : pcs) if (pc.getName().equals(name)) return pc; throw new NoSuchPointcutException(name); } /* (non-Javadoc) * @see org.aspectj.lang.reflect.AjType#getDeclaredPointcuts() */ public Pointcut[] getDeclaredPointcuts() { if (declaredPointcuts != null) return declaredPointcuts; List<Pointcut> pointcuts = new ArrayList<Pointcut>(); Method[] methods = clazz.getDeclaredMethods(); for (Method method : methods) { Pointcut pc = asPointcut(method); if (pc != null) pointcuts.add(pc); } Pointcut[] ret = new Pointcut[pointcuts.size()]; pointcuts.toArray(ret); declaredPointcuts = ret; return ret; } /* (non-Javadoc) * @see org.aspectj.lang.reflect.AjType#getPointcuts() */ public Pointcut[] getPointcuts() { if (pointcuts != null) return pointcuts; List<Pointcut> pcuts = new ArrayList<Pointcut>(); Method[] methods = clazz.getMethods(); for (Method method : methods) { Pointcut pc = asPointcut(method); if (pc != null) pcuts.add(pc); } Pointcut[] ret = new Pointcut[pcuts.size()]; pcuts.toArray(ret); pointcuts = ret; return ret; } private Pointcut asPointcut(Method method) { org.aspectj.lang.annotation.Pointcut pcAnn = method.getAnnotation(org.aspectj.lang.annotation.Pointcut.class); if (pcAnn != null) { String name = method.getName(); if (name.startsWith(ajcMagic)) { // extract real name int nameStart = name.indexOf("$$"); name = name.substring(nameStart +2,name.length()); int nextDollar = name.indexOf("$"); if (nextDollar != -1) name = name.substring(0,nextDollar); } return new PointcutImpl(name,pcAnn.value(),method,AjTypeSystem.getAjType(method.getDeclaringClass())); } else { return null; } } public Advice[] getDeclaredAdvice(AdviceType... ofType) { Set<AdviceType> types; if (ofType.length == 0) { types = EnumSet.allOf(AdviceType.class); } else { types = EnumSet.noneOf(AdviceType.class); types.addAll(Arrays.asList(ofType)); } return getDeclaredAdvice(types); } public Advice[] getAdvice(AdviceType... ofType) { Set<AdviceType> types; if (ofType.length == 0) { types = EnumSet.allOf(AdviceType.class); } else { types = EnumSet.noneOf(AdviceType.class); types.addAll(Arrays.asList(ofType)); } return getAdvice(types); } /* (non-Javadoc) * @see org.aspectj.lang.reflect.AjType#getDeclaredAdvice(org.aspectj.lang.reflect.AdviceType) */ private Advice[] getDeclaredAdvice(Set ofAdviceTypes) { if (declaredAdvice == null) initDeclaredAdvice(); List<Advice> adviceList = new ArrayList<Advice>(); for (Advice a : declaredAdvice) { if (ofAdviceTypes.contains(a.getKind())) adviceList.add(a); } Advice[] ret = new Advice[adviceList.size()]; adviceList.toArray(ret); return ret; } private void initDeclaredAdvice() { Method[] methods = clazz.getDeclaredMethods(); List<Advice> adviceList = new ArrayList<Advice>(); for (Method method : methods) { Advice advice = asAdvice(method); if (advice != null) adviceList.add(advice); } declaredAdvice = new Advice[adviceList.size()]; adviceList.toArray(declaredAdvice); } /* (non-Javadoc) * @see org.aspectj.lang.reflect.AjType#getDeclaredAdvice(org.aspectj.lang.reflect.AdviceType) */ private Advice[] getAdvice(Set ofAdviceTypes) { if (advice == null) initAdvice(); List<Advice> adviceList = new ArrayList<Advice>(); for (Advice a : advice) { if (ofAdviceTypes.contains(a.getKind())) adviceList.add(a); } Advice[] ret = new Advice[adviceList.size()]; adviceList.toArray(ret); return ret; } private void initAdvice() { Method[] methods = clazz.getDeclaredMethods(); List<Advice> adviceList = new ArrayList<Advice>(); for (Method method : methods) { Advice advice = asAdvice(method); if (advice != null) adviceList.add(advice); } advice = new Advice[adviceList.size()]; adviceList.toArray(advice); } public Advice getAdvice(String name) throws NoSuchAdviceException { if (name.equals("")) throw new IllegalArgumentException("use getAdvice(AdviceType...) instead for un-named advice"); if (advice == null) initAdvice(); for (Advice a : advice) { if (a.getName().equals(name)) return a; } throw new NoSuchAdviceException(name); } public Advice getDeclaredAdvice(String name) throws NoSuchAdviceException { if (name.equals("")) throw new IllegalArgumentException("use getAdvice(AdviceType...) instead for un-named advice"); if (declaredAdvice == null) initDeclaredAdvice(); for (Advice a : declaredAdvice) { if (a.getName().equals(name)) return a; } throw new NoSuchAdviceException(name); } private Advice asAdvice(Method method) { if (method.getAnnotations().length == 0) return null; Before beforeAnn = method.getAnnotation(Before.class); if (beforeAnn != null) return new AdviceImpl(method,beforeAnn.value(),AdviceType.BEFORE); After afterAnn = method.getAnnotation(After.class); if (afterAnn != null) return new AdviceImpl(method,afterAnn.value(),AdviceType.AFTER); AfterReturning afterReturningAnn = method.getAnnotation(AfterReturning.class); if (afterReturningAnn != null) { String pcExpr = afterReturningAnn.pointcut(); if (pcExpr.equals("")) pcExpr = afterReturningAnn.value(); return new AdviceImpl(method,pcExpr,AdviceType.AFTER_RETURNING); } AfterThrowing afterThrowingAnn = method.getAnnotation(AfterThrowing.class); if (afterThrowingAnn != null) { String pcExpr = afterThrowingAnn.pointcut(); if (pcExpr == null) pcExpr = afterThrowingAnn.value(); return new AdviceImpl(method,pcExpr,AdviceType.AFTER_THROWING); } Around aroundAnn = method.getAnnotation(Around.class); if (aroundAnn != null) return new AdviceImpl(method,aroundAnn.value(),AdviceType.AROUND); return null; } /* (non-Javadoc) * @see org.aspectj.lang.reflect.AjType#getDeclaredITDMethod(java.lang.String, java.lang.Class, java.lang.Class...) */ public InterTypeMethodDeclaration getDeclaredITDMethod(String name, Class target, Class... parameterTypes) { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see org.aspectj.lang.reflect.AjType#getDeclaredITDMethods() */ public InterTypeMethodDeclaration[] getDeclaredITDMethods() { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see org.aspectj.lang.reflect.AjType#getITDMethod(java.lang.String, java.lang.Class, java.lang.Class...) */ public InterTypeMethodDeclaration getITDMethod(String name, Class target, Class... parameterTypes) { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see org.aspectj.lang.reflect.AjType#getITDMethods() */ public InterTypeMethodDeclaration[] getITDMethods() { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see org.aspectj.lang.reflect.AjType#getDeclaredITDConstructor(java.lang.Class, java.lang.Class...) */ public InterTypeConstructorDeclaration getDeclaredITDConstructor( Class target, Class... parameterTypes) { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see org.aspectj.lang.reflect.AjType#getDeclaredITDConstructors() */ public InterTypeConstructorDeclaration[] getDeclaredITDConstructors() { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see org.aspectj.lang.reflect.AjType#getITDConstructor(java.lang.Class, java.lang.Class...) */ public InterTypeConstructorDeclaration getITDConstructor(Class target, Class... parameterTypes) { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see org.aspectj.lang.reflect.AjType#getITDConstructors() */ public InterTypeConstructorDeclaration[] getITDConstructors() { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see org.aspectj.lang.reflect.AjType#getDeclaredITDField(java.lang.String, java.lang.Class) */ public InterTypeFieldDeclaration getDeclaredITDField(String name, Class target) { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see org.aspectj.lang.reflect.AjType#getDeclaredITDFields() */ public InterTypeFieldDeclaration[] getDeclaredITDFields() { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see org.aspectj.lang.reflect.AjType#getITDField(java.lang.String, java.lang.Class) */ public InterTypeFieldDeclaration getITDField(String name, Class target) { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see org.aspectj.lang.reflect.AjType#getITDFields() */ public InterTypeFieldDeclaration[] getITDFields() { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see org.aspectj.lang.reflect.AjType#getDeclareErrorOrWarnings() */ public DeclareErrorOrWarning[] getDeclareErrorOrWarnings() { List<DeclareErrorOrWarning> deows = new ArrayList<DeclareErrorOrWarning>(); for (Field field : clazz.getDeclaredFields()) { try { if (field.isAnnotationPresent(DeclareWarning.class)) { DeclareWarning dw = field.getAnnotation(DeclareWarning.class); if (Modifier.isPublic(field.getModifiers()) && Modifier.isStatic(field.getModifiers())) { String message = (String) field.get(null); DeclareErrorOrWarningImpl deow = new DeclareErrorOrWarningImpl(dw.value(),message,false); deows.add(deow); } } else if (field.isAnnotationPresent(DeclareError.class)) { DeclareError de = field.getAnnotation(DeclareError.class); if (Modifier.isPublic(field.getModifiers()) && Modifier.isStatic(field.getModifiers())) { String message = (String) field.get(null); DeclareErrorOrWarningImpl deow = new DeclareErrorOrWarningImpl(de.value(),message,true); deows.add(deow); } } } catch (IllegalArgumentException e) { // just move on to the next field } catch (IllegalAccessException e) { // just move on to the next field } } for (Method method : clazz.getDeclaredMethods()) { if (method.isAnnotationPresent(ajcDeclareEoW.class)) { ajcDeclareEoW deowAnn = method.getAnnotation(ajcDeclareEoW.class); DeclareErrorOrWarning deow = new DeclareErrorOrWarningImpl(deowAnn.pointcut(),deowAnn.message(),deowAnn.isError()); deows.add(deow); } } DeclareErrorOrWarning[] ret = new DeclareErrorOrWarning[deows.size()]; deows.toArray(ret); return ret; } /* (non-Javadoc) * @see org.aspectj.lang.reflect.AjType#getDeclareParents() */ public DeclareParents[] getDeclareParents() { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see org.aspectj.lang.reflect.AjType#getDeclareSofts() */ public DeclareSoft[] getDeclareSofts() { return null; } /* (non-Javadoc) * @see org.aspectj.lang.reflect.AjType#getDeclareAnnotations() */ public DeclareAnnotation[] getDeclareAnnotations() { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see org.aspectj.lang.reflect.AjType#getDeclarePrecedence() */ public DeclarePrecedence[] getDeclarePrecedence() { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see org.aspectj.lang.reflect.AjType#getEnumConstants() */ public Object[] getEnumConstants() { return clazz.getEnumConstants(); } /* (non-Javadoc) * @see org.aspectj.lang.reflect.AjType#getTypeParameters() */ public TypeVariable[] getTypeParameters() { return clazz.getTypeParameters(); } /* (non-Javadoc) * @see org.aspectj.lang.reflect.AjType#isEnum() */ public boolean isEnum() { return clazz.isEnum(); } /* (non-Javadoc) * @see org.aspectj.lang.reflect.AjType#isInstance(java.lang.Object) */ public boolean isInstance(Object o) { return clazz.isInstance(o); } /* (non-Javadoc) * @see org.aspectj.lang.reflect.AjType#isInterface() */ public boolean isInterface() { return clazz.isInterface(); } /* (non-Javadoc) * @see org.aspectj.lang.reflect.AjType#isLocalClass() */ public boolean isLocalClass() { return clazz.isLocalClass() && !isAspect(); } /* (non-Javadoc) * @see org.aspectj.lang.reflect.AjType#isMemberClass() */ public boolean isMemberClass() { return clazz.isMemberClass() && !isAspect(); } /* (non-Javadoc) * @see org.aspectj.lang.reflect.AjType#isArray() */ public boolean isArray() { return clazz.isArray(); } /* (non-Javadoc) * @see org.aspectj.lang.reflect.AjType#isPrimitive() */ public boolean isPrimitive() { return clazz.isPrimitive(); } /* (non-Javadoc) * @see org.aspectj.lang.reflect.AjType#isAspect() */ public boolean isAspect() { return clazz.getAnnotation(Aspect.class) != null; } /* (non-Javadoc) * @see org.aspectj.lang.reflect.AjType#isMemberAspect() */ public boolean isMemberAspect() { return clazz.isMemberClass() && isAspect(); } public boolean isPrivileged() { return isAspect() && clazz.isAnnotationPresent(ajcPrivileged.class); } @Override public boolean equals(Object obj) { if (!(obj instanceof AjTypeImpl)) return false; AjTypeImpl other = (AjTypeImpl) obj; return other.clazz.equals(clazz); } @Override public int hashCode() { return clazz.hashCode(); } }
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26:40Z
aspectj5rt/java5-src/org/aspectj/internal/lang/reflect/PointcutImpl.java
/* ******************************************************************* * Copyright (c) 2005 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * Adrian Colyer Initial implementation * ******************************************************************/ package org.aspectj.internal.lang.reflect; import java.lang.reflect.Method; import org.aspectj.lang.reflect.AjType; import org.aspectj.lang.reflect.Pointcut; import org.aspectj.lang.reflect.PointcutExpression; /** * @author colyer * */ public class PointcutImpl implements Pointcut { private final String name; private final PointcutExpression pc; private final Method baseMethod; private final AjType declaringType; protected PointcutImpl(String name, String pc, Method method, AjType declaringType) { this.name = name; this.pc = new PointcutExpressionImpl(pc); this.baseMethod = method; this.declaringType = declaringType; } /* (non-Javadoc) * @see org.aspectj.lang.reflect.Pointcut#getPointcutExpression() */ public PointcutExpression getPointcutExpression() { return pc; } public String getName() { return name; } public int getModifiers() { return baseMethod.getModifiers(); } public Class<?>[] getParameterTypes() { return baseMethod.getParameterTypes(); } public AjType getDeclaringType() { return declaringType; } }
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26:40Z
aspectj5rt/java5-src/org/aspectj/lang/annotation/Pointcut.java
/******************************************************************************* * Copyright (c) 2005 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * initial implementation Alexandre Vasseur *******************************************************************************/ package org.aspectj.lang.annotation; import java.lang.annotation.Target; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * Pointcut declaration * * @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a> */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface Pointcut { /** * The pointcut expression */ String value(); }
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26:40Z
aspectj5rt/java5-src/org/aspectj/lang/reflect/Pointcut.java
/* ******************************************************************* * Copyright (c) 2005 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * Adrian Colyer Initial implementation * ******************************************************************/ package org.aspectj.lang.reflect; public interface Pointcut { PointcutExpression getPointcutExpression(); String getName(); int getModifiers(); Class<?>[] getParameterTypes(); AjType getDeclaringType(); }
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26:40Z
bcel-builder/src/org/aspectj/apache/bcel/classfile/JavaClass.java
package org.aspectj.apache.bcel.classfile; /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Apache" and "Apache Software Foundation" and * "Apache BCEL" must not be used to endorse or promote products * derived from this software without prior written permission. For * written permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * "Apache BCEL", nor may "Apache" appear in their name, without * prior written permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ import org.aspectj.apache.bcel.Constants; import org.aspectj.apache.bcel.util.SyntheticRepository; import org.aspectj.apache.bcel.util.ClassVector; import org.aspectj.apache.bcel.util.ClassQueue; import org.aspectj.apache.bcel.classfile.annotation.Annotation; import org.aspectj.apache.bcel.classfile.annotation.RuntimeAnnotations; import org.aspectj.apache.bcel.generic.Type; import java.io.*; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; /** * Represents a Java class, i.e., the data structures, constant pool, * fields, methods and commands contained in a Java .class file. * See <a href="ftp://java.sun.com/docs/specs/">JVM * specification</a> for details. * The intent of this class is to represent a parsed or otherwise existing * class file. Those interested in programatically generating classes * should see the <a href="../generic/ClassGen.html">ClassGen</a> class. * @version $Id: JavaClass.java,v 1.6 2005/07/08 15:17:23 aclement Exp $ * @see org.aspectj.apache.bcel.generic.ClassGen * @author <A HREF="mailto:[email protected]">M. Dahm</A> */ public class JavaClass extends AccessFlags implements Cloneable, Node { private String file_name; private String package_name; private String source_file_name = "<Unknown>"; private int class_name_index; private int superclass_name_index; private String class_name; private String superclass_name; private int major, minor; // Compiler version private ConstantPool constant_pool; // Constant pool private int[] interfaces; // implemented interfaces private String[] interface_names; private Field[] fields; // Fields, i.e., variables of class private Method[] methods; // methods defined in the class private Attribute[] attributes; // attributes defined in the class private Annotation[] annotations; // annotations defined on the class private byte source = HEAP; // Generated in memory private boolean isGeneric = false; public static final byte HEAP = 1; public static final byte FILE = 2; public static final byte ZIP = 3; static boolean debug = false; // Debugging on/off static char sep = '/'; // directory separator // Annotations are collected from certain attributes, don't do it more than necessary! private boolean annotationsOutOfDate = true; // state for dealing with generic signature string private String signatureAttributeString = null; private Signature signatureAttribute = null; private boolean searchedForSignatureAttribute = false; /** * In cases where we go ahead and create something, * use the default SyntheticRepository, because we * don't know any better. */ private transient org.aspectj.apache.bcel.util.Repository repository = null; /** * Constructor gets all contents as arguments. * * @param class_name_index Index into constant pool referencing a * ConstantClass that represents this class. * @param superclass_name_index Index into constant pool referencing a * ConstantClass that represents this class's superclass. * @param file_name File name * @param major Major compiler version * @param minor Minor compiler version * @param access_flags Access rights defined by bit flags * @param constant_pool Array of constants * @param interfaces Implemented interfaces * @param fields Class fields * @param methods Class methods * @param attributes Class attributes * @param source Read from file or generated in memory? */ public JavaClass(int class_name_index, int superclass_name_index, String file_name, int major, int minor, int access_flags, ConstantPool constant_pool, int[] interfaces, Field[] fields, Method[] methods, Attribute[] attributes, byte source) { if(interfaces == null) // Allowed for backward compatibility interfaces = new int[0]; if(attributes == null) this.attributes = new Attribute[0]; if(fields == null) fields = new Field[0]; if(methods == null) methods = new Method[0]; this.class_name_index = class_name_index; this.superclass_name_index = superclass_name_index; this.file_name = file_name; this.major = major; this.minor = minor; this.access_flags = access_flags; this.constant_pool = constant_pool; this.interfaces = interfaces; this.fields = fields; this.methods = methods; this.attributes = attributes; annotationsOutOfDate = true; this.source = source; // Get source file name if available for(int i=0; i < attributes.length; i++) { if(attributes[i] instanceof SourceFile) { source_file_name = ((SourceFile)attributes[i]).getSourceFileName(); break; } } /* According to the specification the following entries must be of type * `ConstantClass' but we check that anyway via the * `ConstPool.getConstant' method. */ class_name = constant_pool.getConstantString(class_name_index, Constants.CONSTANT_Class); class_name = Utility.compactClassName(class_name, false); int index = class_name.lastIndexOf('.'); if(index < 0) package_name = ""; else package_name = class_name.substring(0, index); if(superclass_name_index > 0) { // May be zero -> class is java.lang.Object superclass_name = constant_pool.getConstantString(superclass_name_index, Constants.CONSTANT_Class); superclass_name = Utility.compactClassName(superclass_name, false); } else superclass_name = "java.lang.Object"; interface_names = new String[interfaces.length]; for(int i=0; i < interfaces.length; i++) { String str = constant_pool.getConstantString(interfaces[i], Constants.CONSTANT_Class); interface_names[i] = Utility.compactClassName(str, false); } } /** * Constructor gets all contents as arguments. * * @param class_name_index Class name * @param superclass_name_index Superclass name * @param file_name File name * @param major Major compiler version * @param minor Minor compiler version * @param access_flags Access rights defined by bit flags * @param constant_pool Array of constants * @param interfaces Implemented interfaces * @param fields Class fields * @param methods Class methods * @param attributes Class attributes */ public JavaClass(int class_name_index, int superclass_name_index, String file_name, int major, int minor, int access_flags, ConstantPool constant_pool, int[] interfaces, Field[] fields, Method[] methods, Attribute[] attributes) { this(class_name_index, superclass_name_index, file_name, major, minor, access_flags, constant_pool, interfaces, fields, methods, attributes, HEAP); } /** * Called by objects that are traversing the nodes of the tree implicitely * defined by the contents of a Java class. I.e., the hierarchy of methods, * fields, attributes, etc. spawns a tree of objects. * * @param v Visitor object */ public void accept(Visitor v) { v.visitJavaClass(this); } /* Print debug information depending on `JavaClass.debug' */ static final void Debug(String str) { if(debug) System.out.println(str); } /** * Dump class to a file. * * @param file Output file * @throws IOException */ public void dump(File file) throws IOException { String parent = file.getParent(); if(parent != null) { File dir = new File(parent); if(dir != null) dir.mkdirs(); } dump(new DataOutputStream(new FileOutputStream(file))); } /** * Dump class to a file named file_name. * * @param file_name Output file name * @exception IOException */ public void dump(String file_name) throws IOException { dump(new File(file_name)); } /** * @return class in binary format */ public byte[] getBytes() { ByteArrayOutputStream s = new ByteArrayOutputStream(); DataOutputStream ds = new DataOutputStream(s); try { dump(ds); } catch(IOException e) { e.printStackTrace(); } finally { try { ds.close(); } catch(IOException e2) { e2.printStackTrace(); } } return s.toByteArray(); } /** * Dump Java class to output stream in binary format. * * @param file Output stream * @exception IOException */ public void dump(OutputStream file) throws IOException { dump(new DataOutputStream(file)); } /** * Dump Java class to output stream in binary format. * * @param file Output stream * @exception IOException */ public void dump(DataOutputStream file) throws IOException { file.writeInt(0xcafebabe); file.writeShort(minor); file.writeShort(major); constant_pool.dump(file); file.writeShort(access_flags); file.writeShort(class_name_index); file.writeShort(superclass_name_index); file.writeShort(interfaces.length); for(int i=0; i < interfaces.length; i++) file.writeShort(interfaces[i]); file.writeShort(fields.length); for(int i=0; i < fields.length; i++) fields[i].dump(file); file.writeShort(methods.length); for(int i=0; i < methods.length; i++) methods[i].dump(file); if(attributes != null) { file.writeShort(attributes.length); for(int i=0; i < attributes.length; i++) attributes[i].dump(file); } else file.writeShort(0); file.close(); } /** * @return Attributes of the class. */ public Attribute[] getAttributes() { return attributes; } public Annotation[] getAnnotations() { if (annotationsOutOfDate) { // Find attributes that contain annotation data Attribute[] attrs = getAttributes(); List accumulatedAnnotations = new ArrayList(); for (int i = 0; i < attrs.length; i++) { Attribute attribute = attrs[i]; if (attribute instanceof RuntimeAnnotations) { RuntimeAnnotations runtimeAnnotations = (RuntimeAnnotations)attribute; accumulatedAnnotations.addAll(runtimeAnnotations.getAnnotations()); } } annotations = (Annotation[])accumulatedAnnotations.toArray(new Annotation[]{}); annotationsOutOfDate = false; } return annotations; } /** * @return Class name. */ public String getClassName() { return class_name; } /** * @return Package name. */ public String getPackageName() { return package_name; } /** * @return Class name index. */ public int getClassNameIndex() { return class_name_index; } /** * @return Constant pool. */ public ConstantPool getConstantPool() { return constant_pool; } /** * @return Fields, i.e., variables of the class. Like the JVM spec * mandates for the classfile format, these fields are those specific to * this class, and not those of the superclass or superinterfaces. */ public Field[] getFields() { return fields; } /** * @return File name of class, aka SourceFile attribute value */ public String getFileName() { return file_name; } /** * @return Names of implemented interfaces. */ public String[] getInterfaceNames() { return interface_names; } /** * @return Indices in constant pool of implemented interfaces. */ public int[] getInterfaceIndices() { return interfaces; } /** * @return Major number of class file version. */ public int getMajor() { return major; } /** * @return Methods of the class. */ public Method[] getMethods() { return methods; } /** * @return A org.aspectj.apache.bcel.classfile.Method corresponding to * java.lang.reflect.Method if any */ public Method getMethod(java.lang.reflect.Method m) { for(int i = 0; i < methods.length; i++) { Method method = methods[i]; if(m.getName().equals(method.getName()) && (m.getModifiers() == method.getModifiers()) && Type.getSignature(m).equals(method.getSignature())) { return method; } } return null; } /** * @return Minor number of class file version. */ public int getMinor() { return minor; } /** * @return sbsolute path to file where this class was read from */ public String getSourceFileName() { return source_file_name; } /** * @return Superclass name. */ public String getSuperclassName() { return superclass_name; } /** * @return Class name index. */ public int getSuperclassNameIndex() { return superclass_name_index; } static { // Debugging ... on/off String debug = System.getProperty("JavaClass.debug"); if(debug != null) JavaClass.debug = new Boolean(debug).booleanValue(); // Get path separator either / or \ usually String sep = System.getProperty("file.separator"); if(sep != null) try { JavaClass.sep = sep.charAt(0); } catch(StringIndexOutOfBoundsException e) {} // Never reached } /** * @param attributes . */ public void setAttributes(Attribute[] attributes) { this.attributes = attributes; annotationsOutOfDate = true; } /** * @param class_name . */ public void setClassName(String class_name) { this.class_name = class_name; } /** * @param class_name_index . */ public void setClassNameIndex(int class_name_index) { this.class_name_index = class_name_index; } /** * @param constant_pool . */ public void setConstantPool(ConstantPool constant_pool) { this.constant_pool = constant_pool; } /** * @param fields . */ public void setFields(Field[] fields) { this.fields = fields; } /** * Set File name of class, aka SourceFile attribute value */ public void setFileName(String file_name) { this.file_name = file_name; } /** * @param interface_names . */ public void setInterfaceNames(String[] interface_names) { this.interface_names = interface_names; } /** * @param interfaces . */ public void setInterfaces(int[] interfaces) { this.interfaces = interfaces; } /** * @param major . */ public void setMajor(int major) { this.major = major; } /** * @param methods . */ public void setMethods(Method[] methods) { this.methods = methods; } /** * @param minor . */ public void setMinor(int minor) { this.minor = minor; } /** * Set absolute path to file this class was read from. */ public void setSourceFileName(String source_file_name) { this.source_file_name = source_file_name; } /** * @param superclass_name . */ public void setSuperclassName(String superclass_name) { this.superclass_name = superclass_name; } /** * @param superclass_name_index . */ public void setSuperclassNameIndex(int superclass_name_index) { this.superclass_name_index = superclass_name_index; } /** * @return String representing class contents. */ public String toString() { String access = Utility.accessToString(access_flags, true); access = access.equals("")? "" : (access + " "); StringBuffer buf = new StringBuffer(access + Utility.classOrInterface(access_flags) + " " + class_name + " extends " + Utility.compactClassName(superclass_name, false) + '\n'); int size = interfaces.length; if(size > 0) { buf.append("implements\t\t"); for(int i=0; i < size; i++) { buf.append(interface_names[i]); if(i < size - 1) buf.append(", "); } buf.append('\n'); } buf.append("filename\t\t" + file_name + '\n'); buf.append("compiled from\t\t" + source_file_name + '\n'); buf.append("compiler version\t" + major + "." + minor + '\n'); buf.append("access flags\t\t" + access_flags + '\n'); buf.append("constant pool\t\t" + constant_pool.getLength() + " entries\n"); buf.append("ACC_SUPER flag\t\t" + isSuper() + "\n"); if(attributes.length > 0) { buf.append("\nAttribute(s):\n"); for(int i=0; i < attributes.length; i++) buf.append(indent(attributes[i])); } if (annotations!=null && annotations.length>0) { buf.append("\nAnnotation(s):\n"); for (int i=0; i<annotations.length; i++) buf.append(indent(annotations[i])); } if(fields.length > 0) { buf.append("\n" + fields.length + " fields:\n"); for(int i=0; i < fields.length; i++) buf.append("\t" + fields[i] + '\n'); } if(methods.length > 0) { buf.append("\n" + methods.length + " methods:\n"); for(int i=0; i < methods.length; i++) buf.append("\t" + methods[i] + '\n'); } return buf.toString(); } private static final String indent(Object obj) { StringTokenizer tok = new StringTokenizer(obj.toString(), "\n"); StringBuffer buf = new StringBuffer(); while(tok.hasMoreTokens()) buf.append("\t" + tok.nextToken() + "\n"); return buf.toString(); } /** * @return deep copy of this class */ public JavaClass copy() { JavaClass c = null; try { c = (JavaClass)clone(); } catch(CloneNotSupportedException e) {} c.constant_pool = constant_pool.copy(); c.interfaces = (int[])interfaces.clone(); c.interface_names = (String[])interface_names.clone(); c.fields = new Field[fields.length]; for(int i=0; i < fields.length; i++) c.fields[i] = fields[i].copy(c.constant_pool); c.methods = new Method[methods.length]; for(int i=0; i < methods.length; i++) c.methods[i] = methods[i].copy(c.constant_pool); c.attributes = new Attribute[attributes.length]; for(int i=0; i < attributes.length; i++) c.attributes[i] = attributes[i].copy(c.constant_pool); //J5SUPPORT: As the annotations exist as attributes against the class, copying // the attributes will copy the annotations across, so we don't have to // also copy them individually. return c; } public final boolean isSuper() { return (access_flags & Constants.ACC_SUPER) != 0; } public final boolean isClass() { return (access_flags & Constants.ACC_INTERFACE) == 0; } // J5SUPPORT: /** * Returns true if this class represents an annotation, i.e. it was a * 'public @interface blahblah' declaration */ public final boolean isAnnotation() { return (access_flags & Constants.ACC_ANNOTATION) != 0; } /** * Returns true if this class represents an enum type */ public final boolean isEnum() { return (access_flags & Constants.ACC_ENUM) != 0; } /** @return returns either HEAP (generated), FILE, or ZIP */ public final byte getSource() { return source; } /********************* New repository functionality *********************/ /** * Gets the ClassRepository which holds its definition. By default * this is the same as SyntheticRepository.getInstance(); */ public org.aspectj.apache.bcel.util.Repository getRepository() { if (repository == null) repository = SyntheticRepository.getInstance(); return repository; } /** * Sets the ClassRepository which loaded the JavaClass. * Should be called immediately after parsing is done. */ public void setRepository(org.aspectj.apache.bcel.util.Repository repository) { this.repository = repository; } /** Equivalent to runtime "instanceof" operator. * * @return true if this JavaClass is derived from teh super class */ public final boolean instanceOf(JavaClass super_class) { if(this.equals(super_class)) return true; JavaClass[] super_classes = getSuperClasses(); for(int i=0; i < super_classes.length; i++) { if(super_classes[i].equals(super_class)) { return true; } } if(super_class.isInterface()) { return implementationOf(super_class); } return false; } /** * @return true, if clazz is an implementation of interface inter */ public boolean implementationOf(JavaClass inter) { if(!inter.isInterface()) { throw new IllegalArgumentException(inter.getClassName() + " is no interface"); } if(this.equals(inter)) { return true; } JavaClass[] super_interfaces = getAllInterfaces(); for(int i=0; i < super_interfaces.length; i++) { if(super_interfaces[i].equals(inter)) { return true; } } return false; } /** * @return the superclass for this JavaClass object, or null if this * is java.lang.Object */ public JavaClass getSuperClass() { if("java.lang.Object".equals(getClassName())) { return null; } try { return getRepository().loadClass(getSuperclassName()); } catch(ClassNotFoundException e) { System.err.println(e); return null; } } /** * @return list of super classes of this class in ascending order, i.e., * java.lang.Object is always the last element */ public JavaClass[] getSuperClasses() { JavaClass clazz = this; ClassVector vec = new ClassVector(); for(clazz = clazz.getSuperClass(); clazz != null; clazz = clazz.getSuperClass()) { vec.addElement(clazz); } return vec.toArray(); } /** * Get interfaces directly implemented by this JavaClass. */ public JavaClass[] getInterfaces() { String[] interfaces = getInterfaceNames(); JavaClass[] classes = new JavaClass[interfaces.length]; try { for(int i = 0; i < interfaces.length; i++) { classes[i] = getRepository().loadClass(interfaces[i]); } } catch(ClassNotFoundException e) { System.err.println(e); return null; } return classes; } /** * Get all interfaces implemented by this JavaClass (transitively). */ public JavaClass[] getAllInterfaces() { ClassQueue queue = new ClassQueue(); ClassVector vec = new ClassVector(); queue.enqueue(this); while(!queue.empty()) { JavaClass clazz = queue.dequeue(); JavaClass souper = clazz.getSuperClass(); JavaClass[] interfaces = clazz.getInterfaces(); if(clazz.isInterface()) { vec.addElement(clazz); } else { if(souper != null) { queue.enqueue(souper); } } for(int i = 0; i < interfaces.length; i++) { queue.enqueue(interfaces[i]); } } return vec.toArray(); } /** * Hunts for a signature attribute on the member and returns its contents. So where the 'regular' signature * may be Ljava/util/Vector; the signature attribute will tell us * e.g. "<E:>Ljava/lang/Object". We can learn the type variable names, their bounds, * and the true superclass and superinterface types (including any parameterizations) * Coded for performance - searches for the attribute only when requested - only searches for it once. */ public final String getGenericSignature() { loadGenericSignatureInfoIfNecessary(); return signatureAttributeString; } public boolean isGeneric() { loadGenericSignatureInfoIfNecessary(); return isGeneric; } private void loadGenericSignatureInfoIfNecessary() { if (!searchedForSignatureAttribute) { boolean found=false; for(int i=0; !found && i < attributes.length; i++) { if(attributes[i] instanceof Signature) { signatureAttribute = ((Signature)attributes[i]); signatureAttributeString = signatureAttribute.getSignature(); found=true; } } isGeneric = found && signatureAttributeString.charAt(0)=='<'; searchedForSignatureAttribute=true; } } /** * the parsed version of the above */ public final Signature.ClassSignature getGenericClassTypeSignature() { loadGenericSignatureInfoIfNecessary(); if (signatureAttribute != null) { return signatureAttribute.asClassSignature(); } else { return null; } } }
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26:40Z
bcel-builder/src/org/aspectj/apache/bcel/generic/Type.java
package org.aspectj.apache.bcel.generic; /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Apache" and "Apache Software Foundation" and * "Apache BCEL" must not be used to endorse or promote products * derived from this software without prior written permission. For * written permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * "Apache BCEL", nor may "Apache" appear in their name, without * prior written permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ import java.util.ArrayList; 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.5 2005/06/01 14:57:23 aclement Exp $ * @author <A HREF="mailto:[email protected]">M. Dahm</A> * * 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 STRINGBUFFER = new ObjectType("java.lang.StringBuffer"); public static final ObjectType THROWABLE = new ObjectType("java.lang.Throwable"); 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,"<unknown object>"){}; 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(); } // private static int consumed_chars=0; // Remember position in string, see getArgumentTypes public static final Type getType(String signature) { TypeHolder th = getTypeInternal(signature); return th.getType(); } /** * 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('/','.'); } // 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 */ 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; } /** 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 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;} } }
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26:40Z
bcel-builder/testsrc/org/aspectj/apache/bcel/classfile/tests/GetReflectMembersTest.java
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26:40Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/AtAspectJAnnotationFactory.java
/* ******************************************************************* * Copyright (c) 2005 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * Adrian Colyer Initial implementation * ******************************************************************/ package org.aspectj.ajdt.internal.compiler.ast; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Annotation; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Expression; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.MemberValuePair; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.NormalAnnotation; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.QualifiedTypeReference; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.StringLiteral; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TrueLiteral; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.FalseLiteral; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeReference; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TagBits; /** * @author colyer * Creates @AspectJ annotations for use by AtAspectJVisitor */ public class AtAspectJAnnotationFactory { static final char[] org = "org".toCharArray(); static final char[] aspectj = "aspectj".toCharArray(); static final char[] lang = "lang".toCharArray(); static final char[] internal = "internal".toCharArray(); static final char[] annotation = "annotation".toCharArray(); static final char[] value = "value".toCharArray(); static final char[] aspect = "Aspect".toCharArray(); static final char[] privileged = "ajcPrivileged".toCharArray(); static final char[] before = "Before".toCharArray(); static final char[] after = "After".toCharArray(); static final char[] afterReturning = "AfterReturning".toCharArray(); static final char[] afterThrowing = "AfterThrowing".toCharArray(); static final char[] around = "Around".toCharArray(); static final char[] pointcut = "Pointcut".toCharArray(); static final char[] declareErrorOrWarning = "ajcDeclareEoW".toCharArray(); /** * Create an @Aspect annotation for a code style aspect declaration starting at * the given position in the source file */ public static Annotation createAspectAnnotation(String perclause, int pos) { char[][] typeName = new char[][] {org,aspectj,lang,annotation,aspect}; long[] positions = new long[] {pos,pos,pos,pos,pos}; TypeReference orgAspectJLangAnnotationAspect = new QualifiedTypeReference(typeName,positions); NormalAnnotation atAspectAnnotation = new NormalAnnotation(orgAspectJLangAnnotationAspect,pos); if (!perclause.equals("")) { // we have to set the value Expression perclauseExpr = new StringLiteral(perclause.toCharArray(),pos,pos); MemberValuePair[] mvps = new MemberValuePair[1]; mvps[0] = new MemberValuePair(value,pos,pos,perclauseExpr); atAspectAnnotation.memberValuePairs = mvps; } return atAspectAnnotation; } public static Annotation createPrivilegedAnnotation(int pos) { char[][] typeName = new char[][] {org,aspectj,internal,lang,annotation,privileged}; long[] positions = new long[] {pos,pos,pos,pos,pos,pos}; TypeReference annType = new QualifiedTypeReference(typeName,positions); NormalAnnotation ann = new NormalAnnotation(annType,pos); return ann; } public static Annotation createBeforeAnnotation(String pointcutExpression, int pos) { char[][] typeName = new char[][] {org,aspectj,lang,annotation,before}; return makeSingleStringMemberAnnotation(typeName, pos, pointcutExpression); } public static Annotation createAfterAnnotation(String pointcutExpression, int pos) { char[][] typeName = new char[][] {org,aspectj,lang,annotation,after}; return makeSingleStringMemberAnnotation(typeName, pos, pointcutExpression); } public static Annotation createAfterReturningAnnotation(String pointcutExpression, String extraArgumentName, int pos) { char[][] typeName = new char[][] {org,aspectj,lang,annotation,afterReturning}; long[] positions = new long[] {pos,pos,pos,pos,pos}; TypeReference annType = new QualifiedTypeReference(typeName,positions); NormalAnnotation ann = new NormalAnnotation(annType,pos); Expression pcExpr = new StringLiteral(pointcutExpression.toCharArray(),pos,pos); MemberValuePair[] mvps = new MemberValuePair[2]; mvps[0] = new MemberValuePair("pointcut".toCharArray(),pos,pos,pcExpr); Expression argExpr = new StringLiteral(extraArgumentName.toCharArray(),pos,pos); mvps[1] = new MemberValuePair("returning".toCharArray(),pos,pos,argExpr); ann.memberValuePairs = mvps; return ann; } public static Annotation createAfterThrowingAnnotation(String pointcutExpression, String extraArgumentName, int pos) { char[][] typeName = new char[][] {org,aspectj,lang,annotation,afterThrowing}; long[] positions = new long[] {pos,pos,pos,pos,pos}; TypeReference annType = new QualifiedTypeReference(typeName,positions); NormalAnnotation ann = new NormalAnnotation(annType,pos); Expression pcExpr = new StringLiteral(pointcutExpression.toCharArray(),pos,pos); MemberValuePair[] mvps = new MemberValuePair[2]; mvps[0] = new MemberValuePair("pointcut".toCharArray(),pos,pos,pcExpr); Expression argExpr = new StringLiteral(extraArgumentName.toCharArray(),pos,pos); mvps[1] = new MemberValuePair("throwing".toCharArray(),pos,pos,argExpr); ann.memberValuePairs = mvps; return ann; } public static Annotation createAroundAnnotation(String pointcutExpression, int pos) { char[][] typeName = new char[][] {org,aspectj,lang,annotation,around}; return makeSingleStringMemberAnnotation(typeName, pos, pointcutExpression); } public static Annotation createPointcutAnnotation(String pointcutExpression, int pos) { char[][] typeName = new char[][] {org,aspectj,lang,annotation,pointcut}; return makeSingleStringMemberAnnotation(typeName, pos, pointcutExpression); } public static Annotation createDeclareErrorOrWarningAnnotation(String pointcutExpression, String message, boolean isError, int pos) { char[][] typeName = new char[][] {org,aspectj,internal,lang,annotation,declareErrorOrWarning}; long[] positions = new long[typeName.length]; for (int i = 0; i < positions.length; i++) positions[i] = pos; TypeReference annType = new QualifiedTypeReference(typeName,positions); NormalAnnotation ann = new NormalAnnotation(annType,pos); Expression pcutExpr = new StringLiteral(pointcutExpression.toCharArray(),pos,pos); Expression msgExpr = new StringLiteral(message.toCharArray(),pos,pos); Expression isErrorExpr; if (isError) { isErrorExpr = new TrueLiteral(pos,pos); } else { isErrorExpr = new FalseLiteral(pos,pos); } MemberValuePair[] mvps = new MemberValuePair[3]; mvps[0] = new MemberValuePair("pointcut".toCharArray(),pos,pos,pcutExpr); mvps[1] = new MemberValuePair("message".toCharArray(),pos,pos,msgExpr); mvps[2] = new MemberValuePair("isError".toCharArray(),pos,pos,isErrorExpr); ann.memberValuePairs = mvps; return ann; } private static Annotation makeSingleStringMemberAnnotation(char[][] name, int pos, String annValue) { long[] positions = new long[name.length]; for (int i = 0; i < positions.length; i++) positions[i] = pos; TypeReference annType = new QualifiedTypeReference(name,positions); NormalAnnotation ann = new NormalAnnotation(annType,pos); Expression valueExpr = new StringLiteral(annValue.toCharArray(),pos,pos); MemberValuePair[] mvps = new MemberValuePair[1]; mvps[0] = new MemberValuePair(value,pos,pos,valueExpr); ann.memberValuePairs = mvps; return ann; } public static void addAnnotation(AjMethodDeclaration decl, Annotation annotation) { if (decl.annotations == null) { decl.annotations = new Annotation[] { annotation }; } else { Annotation[] old = decl.annotations; decl.annotations = new Annotation[old.length +1]; System.arraycopy(old,0,decl.annotations,0,old.length); decl.annotations[old.length] = annotation; } if (decl.binding!= null) { decl.binding.tagBits -= TagBits.AnnotationResolved; } } }
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26:40Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/PointcutDeclaration.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.ajdt.internal.compiler.ast; import java.lang.reflect.Modifier; import java.util.Iterator; import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory; import org.aspectj.ajdt.internal.core.builder.EclipseSourceContext; import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation; import org.aspectj.org.eclipse.jdt.internal.compiler.ClassFile; import org.aspectj.org.eclipse.jdt.internal.compiler.CompilationResult; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Annotation; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Argument; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeReference; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ClassScope; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TagBits; import org.aspectj.org.eclipse.jdt.internal.compiler.parser.Parser; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.ResolvedPointcutDefinition; import org.aspectj.weaver.patterns.Pointcut; /** * pointcut [declaredModifiers] [declaredName]([arguments]): [pointcutDesignator]; * * <p>No method will actually be generated for this node but an attribute * will be added to the enclosing class.</p> * * @author Jim Hugunin */ public class PointcutDeclaration extends AjMethodDeclaration { public static final char[] mangledPrefix = "ajc$pointcut$".toCharArray(); public PointcutDesignator pointcutDesignator; private int declaredModifiers; private String declaredName; private boolean generateSyntheticPointcutMethod = false; private EclipseFactory world = null; //private boolean mangleSelector = true; private ResolvedPointcutDefinition resolvedPointcutDeclaration = null; public PointcutDeclaration(CompilationResult compilationResult) { super(compilationResult); this.returnType = TypeReference.baseTypeReference(T_void, 0); } private Pointcut getPointcut() { if (pointcutDesignator == null) { return Pointcut.makeMatchesNothing(Pointcut.RESOLVED); } else { return pointcutDesignator.getPointcut(); } } public void parseStatements( Parser parser, CompilationUnitDeclaration unit) { // do nothing } public void postParse(TypeDeclaration typeDec) { if (arguments == null) arguments = new Argument[0]; this.declaredModifiers = modifiers; this.declaredName = new String(selector); // amc - if we set mangle selector to false, then the generated bytecode has the // pointcut method name that the user of an @Pointcut would expect. // But then we will unpack it again in the weaver which may cause redundant // error messages to be issued. This seems the better trade-off... //if (mangleSelector) { selector = CharOperation.concat(mangledPrefix, '$', selector, '$', Integer.toHexString(sourceStart).toCharArray()); //} if (Modifier.isAbstract(this.declaredModifiers)) { if (!(typeDec instanceof AspectDeclaration)) { typeDec.scope.problemReporter().signalError(sourceStart, sourceEnd, "The abstract pointcut " + new String(declaredName) + " can only be defined in an aspect"); ignoreFurtherInvestigation = true; return; } else if (!Modifier.isAbstract(typeDec.modifiers)) { typeDec.scope.problemReporter().signalError(sourceStart, sourceEnd, "The abstract pointcut " + new String(declaredName) + " can only be defined in an abstract aspect"); ignoreFurtherInvestigation = true; return; } } if (pointcutDesignator != null) { pointcutDesignator.postParse(typeDec, this); } } /** * Called from the AtAspectJVisitor to create the @Pointcut annotation * (and corresponding method) for this pointcut * */ public void addAtAspectJAnnotations() { Annotation pcutAnnotation = AtAspectJAnnotationFactory.createPointcutAnnotation(getPointcut().toString(),declarationSourceStart);; if (annotations == null) { annotations = new Annotation[] { pcutAnnotation }; } else { Annotation[] old = annotations; annotations = new Annotation[old.length +1]; System.arraycopy(old,0,annotations,0,old.length); annotations[old.length] = pcutAnnotation; } generateSyntheticPointcutMethod = true; } // coming from an @Pointcut declaration public void setGenerateSyntheticPointcutMethod() { generateSyntheticPointcutMethod = true; //mangleSelector = false; } public void resolve(ClassScope upperScope) { // we attempted to resolve annotations below, but that was too early, so we do it again // now at the 'right' time. if (binding!= null) { binding.tagBits -= TagBits.AnnotationResolved; resolveAnnotations(scope, this.annotations, this.binding); } // for the rest of the resolution process, this method should do nothing, use the entry point below... } public void resolvePointcut(ClassScope upperScope) { this.world = EclipseFactory.fromScopeLookupEnvironment(upperScope); super.resolve(upperScope); } public void resolveStatements() { if (isAbstract()) { this.modifiers |= AccSemicolonBody; } if (binding == null || ignoreFurtherInvestigation) return; if (Modifier.isAbstract(this.declaredModifiers)&& (pointcutDesignator != null)) { scope.problemReporter().signalError(sourceStart, sourceEnd, "abstract pointcut can't have body"); ignoreFurtherInvestigation = true; return; } if (pointcutDesignator != null) { pointcutDesignator.finishResolveTypes(this, this.binding, arguments.length, scope.enclosingSourceType()); } //System.out.println("resolved: " + getPointcut() + ", " + getPointcut().state); makeResolvedPointcutDefinition(world); resolvedPointcutDeclaration.setPointcut(getPointcut()); super.resolveStatements(); } public ResolvedPointcutDefinition makeResolvedPointcutDefinition(EclipseFactory inWorld) { if (resolvedPointcutDeclaration != null) return resolvedPointcutDeclaration; //System.out.println("pc: " + getPointcut() + ", " + getPointcut().state); resolvedPointcutDeclaration = new ResolvedPointcutDefinition( inWorld.fromBinding(this.binding.declaringClass), declaredModifiers, declaredName, inWorld.fromBindings(this.binding.parameters), getPointcut()); //??? might want to use null resolvedPointcutDeclaration.setPosition(sourceStart, sourceEnd); resolvedPointcutDeclaration.setSourceContext(new EclipseSourceContext(compilationResult)); return resolvedPointcutDeclaration; } public AjAttribute makeAttribute() { return new AjAttribute.PointcutDeclarationAttribute(makeResolvedPointcutDefinition(world)); } /** * A pointcut declaration exists in a classfile only as an attibute on the * class. Unlike advice and inter-type declarations, it has no corresponding * method. */ public void generateCode(ClassScope classScope, ClassFile classFile) { this.world = EclipseFactory.fromScopeLookupEnvironment(classScope); if (ignoreFurtherInvestigation) return ; classFile.extraAttributes.add(new EclipseAttributeAdapter(makeAttribute())); addVersionAttributeIfNecessary(classFile); if (generateSyntheticPointcutMethod) { super.generateCode(classScope,classFile); } return; } /** * Normally, pointcuts occur in aspects - aspects are always tagged with a weaver version attribute, * see AspectDeclaration. However, pointcuts can also occur in regular classes and in this case there * is no AspectDeclaration to ensure the attribute is added. So, this method adds the attribute * if someone else hasn't already. */ private void addVersionAttributeIfNecessary(ClassFile classFile) { for (Iterator iter = classFile.extraAttributes.iterator(); iter.hasNext();) { EclipseAttributeAdapter element = (EclipseAttributeAdapter) iter.next(); if (CharOperation.equals(element.getNameChars(),weaverVersionChars)) return; } classFile.extraAttributes.add(new EclipseAttributeAdapter(new AjAttribute.WeaverVersionInfo())); } private static char[] weaverVersionChars = "org.aspectj.weaver.WeaverVersion".toCharArray(); protected int generateInfoAttributes(ClassFile classFile) { return super.generateInfoAttributes(classFile,true); } public StringBuffer printReturnType(int indent, StringBuffer output) { return output.append("pointcut"); } /* (non-Javadoc) * @see org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration#printBody(int, java.lang.StringBuffer) */ public StringBuffer printBody(int indent, StringBuffer output) { output.append(": "); output.append(getPointcut()); output.append(";"); return output; } }
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26:40Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/PointcutDesignator.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.ajdt.internal.compiler.ast; import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory; import org.aspectj.ajdt.internal.compiler.lookup.EclipseScope; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.ASTNode; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Argument; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.MethodDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.MethodBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.parser.Parser; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.patterns.FormalBinding; import org.aspectj.weaver.patterns.Pointcut; public class PointcutDesignator extends ASTNode { private Pointcut pointcut; private PseudoTokens tokens; //XXX redundant private boolean isError = false; public PointcutDesignator(Parser parser, PseudoTokens tokens) { super(); sourceStart = tokens.sourceStart; sourceEnd = tokens.sourceEnd; this.tokens = tokens; Pointcut pc = tokens.parsePointcut(parser); if (pc.toString().equals("")) { //??? is this a good signal isError = true; } pointcut = pc; } // called by AtAspectJVisitor public PointcutDesignator(Pointcut pc) { this.pointcut = pc; } public void postParse(TypeDeclaration typeDec, MethodDeclaration enclosingDec) { if (tokens != null) tokens.postParse(typeDec, enclosingDec); } public boolean finishResolveTypes(final AbstractMethodDeclaration dec, MethodBinding method, final int baseArgumentCount, SourceTypeBinding sourceTypeBinding) { //System.err.println("resolving: " + this); //Thread.currentThread().dumpStack(); //XXX why do we need this test // AMC added concrete too. Needed because declare declarations concretize their // shadow mungers early. if (pointcut.state == Pointcut.RESOLVED || pointcut.state == Pointcut.CONCRETE) return true; EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(dec.scope); TypeBinding[] parameters = method.parameters; Argument[] arguments = dec.arguments; FormalBinding[] bindings = new FormalBinding[baseArgumentCount]; for (int i = 0, len = baseArgumentCount; i < len; i++) { Argument arg = arguments[i]; String name = new String(arg.name); UnresolvedType type = world.fromBinding(parameters[i]); bindings[i] = new FormalBinding(type, name, i, arg.sourceStart, arg.sourceEnd, "unknown"); } EclipseScope scope = new EclipseScope(bindings, dec.scope); pointcut = pointcut.resolve(scope); return true; } public Pointcut getPointcut() { return pointcut; } public boolean isError() { return isError; } /* (non-Javadoc) * @see org.eclipse.jdt.internal.compiler.ast.ASTNode#print(int, java.lang.StringBuffer) */ public StringBuffer print(int indent, StringBuffer output) { if (pointcut == null) return output.append("<pcd>"); return output.append(pointcut.toString()); } }
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26:40Z
tests/java5/ataspectj/annotationGen/RuntimePointcuts.java
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26:40Z
tests/src/org/aspectj/systemtest/ajc150/Ajc150Tests.java
/******************************************************************************* * Copyright (c) 2004 IBM * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Andy Clement - initial API and implementation *******************************************************************************/ package org.aspectj.systemtest.ajc150; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import junit.framework.Test; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.apache.bcel.classfile.Method; import org.aspectj.apache.bcel.util.ClassPath; import org.aspectj.apache.bcel.util.SyntheticRepository; import org.aspectj.asm.AsmManager; import org.aspectj.testing.XMLBasedAjcTestCase; import org.aspectj.util.LangUtil; /** * These are tests that will run on Java 1.4 and use the old harness format for test specification. */ public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase { public static Test suite() { return XMLBasedAjcTestCase.loadSuite(Ajc150Tests.class); } protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml"); } public void test_typeProcessingOrderWhenDeclareParents() { runTest("Order of types passed to compiler determines weaving behavior"); } public void test_aroundMethod() { runTest("method called around in class"); } public void test_aroundMethodAspect() { runTest("method called around in aspect"); } public void test_ambiguousBindingsDetection() { runTest("Various kinds of ambiguous bindings"); } public void test_ambiguousArgsDetection() { runTest("ambiguous args"); } public void testIncorrectExceptionTableWhenBreakInMethod_pr78021() { runTest("Injecting exception into while loop with break statement causes catch block to be ignored"); } public void testIncorrectExceptionTableWhenReturnInMethod_pr79554() { runTest("Return in try-block disables catch-block if final-block is present"); } public void testMissingDebugInfoForGeneratedMethods_pr82570() throws ClassNotFoundException { runTest("Weaved code does not include debug lines"); boolean f = false; JavaClass jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1"); Method[] meths = jc.getMethods(); for (int i = 0; i < meths.length; i++) { Method method = meths[i]; if (f) System.err.println("Line number table for "+method.getName()+method.getSignature()+" = "+method.getLineNumberTable()); assertTrue("Didn't find a line number table for method "+method.getName()+method.getSignature(), method.getLineNumberTable()!=null); } // This test would determine the info isn't there if you pass -g:none ... // cR = ajc(baseDir,new String[]{"PR82570_1.java","-g:none"}); // assertTrue("Expected no compile problem:"+cR,!cR.hasErrorMessages()); // System.err.println(cR.getStandardError()); // jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1"); // meths = jc.getMethods(); // for (int i = 0; i < meths.length; i++) { // Method method = meths[i]; // assertTrue("Found a line number table for method "+method.getName(), // method.getLineNumberTable()==null); // } } public void testCanOverrideProtectedMethodsViaITDandDecp_pr83303() { runTest("compiler error when mixing inheritance, overriding and polymorphism"); } public void testPerTypeWithin_pr106554() {runTest("Problem in staticinitialization with pertypewithin aspect");} public void testPerTypeWithinMissesNamedInnerTypes() { runTest("pertypewithin() handing of inner classes (1)"); } public void testPerTypeWithinMissesAnonymousInnerTypes() { runTest("pertypewithin() handing of inner classes (2)"); } public void testPerTypeWithinIncorrectlyMatchingInterfaces() { runTest("pertypewithin({interface}) illegal field modifier"); } public void test051_arrayCloningInJava5() { runTest("AJC possible bug with static nested classes"); } public void testBadASMforEnums() throws IOException { runTest("bad asm for enums"); if (LangUtil.is15VMOrGreater()) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintWriter pw = new PrintWriter(baos); AsmManager.dumptree(pw,AsmManager.getDefault().getHierarchy().getRoot(),0); pw.flush(); String tree = baos.toString(); assertTrue("Expected 'Red [enumvalue]' somewhere in here:"+tree,tree.indexOf("Red [enumvalue]")!=-1); } } public void npeOnTypeNotFound() { runTest("structure model npe on type not found"); } public void testNoRuntimeExceptionSoftening() { runTest("declare soft of runtime exception"); } public void testRuntimeNoSoftenWithHandler() { runTest("declare soft w. catch block"); } public void testSyntaxError() { runTest("invalid cons syntax"); } public void testVarargsInConsBug() { runTest("varargs in constructor sig"); } public void testAspectpathdirs() { runTest("dirs on aspectpath"); } public void testIntroSample() { runTest("introduction sample"); } public void testPTWInterface() { runTest("pertypewithin({interface}) illegal field modifier"); } public void testEnumCalledEnumEtc() { runTest("enum called Enum, annotation called Annotation, etc"); } public void testInternalCompilerError_pr86832() { runTest("Internal compiler error"); } public void testCloneMethod_pr83311() { runTest("overriding/polymorphism error on interface method introduction"); } /** * IfPointcut.findResidueInternal() was modified to make this test complete in a short amount * of time - if you see it hanging, someone has messed with the optimization. */ public void testIfEvaluationExplosion_pr94086() { runTest("Exploding compile time with if() statements in pointcut"); } public void testReflectNPE_pr94167() {runTest("NPE in reflect implementation");} public void testStaticImports_pr84260() {runTest("static import failures");} public void testGenerics_pr99089() {runTest("ArrayIndexOutOfBoundsException - Generics in privileged aspects");} public void testGenerics_pr95993() {runTest("NPE at ClassScope.java:660 when compiling generic class");} public void testItdGenerics_pr99228() {runTest("ITD of a field into a generic class");} public void testItdGenerics_pr98320() {runTest("intertype with nested generic type");} public void testItdGenerics_pr100227() {runTest("inner class with generic enclosing class");} public void testItdGenerics_pr100260() {runTest("methods inherited from a generic parent");} public void testSyntaxErrorNPE_pr103266() {runTest("NPE on syntax error");} public void testFinalAbstractClass_pr109486() { runTest("Internal compiler error (ClassParser.java:242)");} //public void testComplexBinding_pr102210() { runTest("NullPointerException trying to compile");} public void testIllegalStateExceptionOnNestedParameterizedType_pr106634() { runTest("IllegalStateException unpacking signature of nested parameterized type"); } public void testParseErrorOnAnnotationStarPlusPattern() { runTest("(@Foo *)+ type pattern parse error"); } public void test_pr106130_tooManyLocals() { runTest("test weaving with > 256 locals"); } public void testMissingNamePattern_pr106461() { runTest("missing name pattern"); } public void testMissingNamePattern_pr107059() { runTest("parser crashes on call(void (@a *)(..)"); } public void testIntermediateAnnotationMatching() { runTest("intermediate annotation matching"); } public void testBadRuntimeTestGeneration() { runTest("target(@Foo *)"); } public void testErrorMessageOnITDWithTypePatterns() { runTest("clear error message on itd with type pattern"); } public void testAjKeywordsAsIdentifiers() { runTest("before and after are valid identifiers in classes"); } public void testAjKeywordsAsIdentifiers2() { runTest("before and after are valid identifiers in classes, part 2"); } public void testNoBeforeReturningAdvice() { runTest("before returning advice not allowed!"); } public void testDetectVoidFieldType() { runTest("void field type in pointcut expression"); } public void testPointcutOverriding() { runTest("overriding final pointcut from super-aspect"); } public void testAtSuppressWarnings() { runTest("@SuppressWarnings should suppress"); } public void testDEOWWithBindingPointcut() { runTest("declare warning : foo(str) : ...;"); } public void testAroundAdviceAndInterfaceInitializer() { runTest("around advice on interface initializer"); } public void testGoodErrorMessageOnUnmatchedMemberSyntax() { runTest("good error message for unmatched member syntax"); } public void testITDWithNoExceptionAndIntermediary() { runTest("itd override with no exception clause"); } public void testAnonymousInnerClasses() { runTest("anonymous inner classes"); } public void testMultipleAnonymousInnerClasses() { runTest("multiple anonymous inner classes"); } public void testPrivilegedMethodAccessorsGetRightExceptions_pr82989() { runTest("Compiler error due to a wrong exception check in try blocks"); } public void testAnonymousInnerClassWithMethodReturningTypeParameter_pr107898() { runTest("anonymous inner class with method returning type parameter"); } public void testMatchingOfObjectArray() { runTest("matching against Object[]"); } public void testMultipleAnonymousInnerClasses_pr108104() { runTest("multiple anonymous inner classes 2"); } public void testSignatureMatchingInMultipleOverrideScenario() { runTest("signature matching in override scenario"); } public void testWildcardAnnotationMatching_pr108245() { runTest("wildcard annotation matching - pr108245"); } public void testInnerTypesAndTypeVariables() { runTest("inner types and type variables"); } public void testAtAfterThrowingWithNoFormal() { runTest("@AfterThrowing with no formal specified"); } public void testParameterizedVarArgsMatch() { runTest("varargs with type variable"); } public void testFieldAccessInsideITDM() { runTest("itd field access inside itd method"); } public void testTypeVarWithTypeVarBound() { runTest("type variable with type variable bound"); } public void testEnumSwitchInITD() { runTest("switch on enum inside ITD method"); } public void testInnerTypeOfGeneric() { runTest("inner type of generic interface reference from parameterized type"); } public void testDeclareParentsIntroducingCovariantReturnType() { runTest("declare parents introducing override with covariance"); } public void testInnerClassPassedToVarargs() { runTest("inner class passed as argument to varargs method"); } public void testInlinedFieldAccessInProceedCall() { runTest("inlined field access in proceed call"); } public void testVisibiltyInSignatureMatchingWithOverridesPart1() { runTest("visibility in signature matching with overrides - 1"); } public void testVisibiltyInSignatureMatchingWithOverridesPart2() { runTest("visibility in signature matching with overrides - 2"); } public void testVisibiltyInSignatureMatchingWithOverridesPart3() { runTest("visibility in signature matching with overrides - 3"); } public void testArgsGeneratedCorrectlyForAdviceExecution() { runTest("args generated correctly for advice execution join point"); } public void testNoUnusedWarningsOnAspectTypes() { runTest("no unused warnings on aspect types"); } public void testSyntheticArgumentsOnITDConstructorsNotUsedInMatching() { runTest("synthetic arguments on itd cons are not used in matching"); } public void testParsingOfGenericTypeSignature() { runTest("parse generic type signature with parameterized type in interface"); } public void testOverrideAndCovarianceWithDecPRuntime() { runTest("override and covariance with decp - runtime"); } public void testOverrideAndCovarianceWithDecPRuntimeMultiFiles() { runTest("override and covariance with decp - runtime separate files"); } public void testAbstractSynchronizedITDMethods() { runTest("abstract synchronized itdms not detected"); } public void testSynchronizedITDInterfaceMethods() { runTest("synchronized itd interface methods"); } public void testNoWarningOnUnusedPointcut() { runTest("unused private pointcuts"); } public void testITDOnInterfaceWithExistingMember() { runTest("itd interface method already existing on interface"); } public void testFinalITDMOnInterface() { runTest("final itd methods on interfaces"); } public void testPrivatePointcutOverriding() { runTest("can't override private pointcut in abstract aspect"); } public void testAdviceOnCflow() { runTest("advising cflow advice execution"); } public void testNoTypeMismatchOnSameGenericTypes() { runTest("no type mismatch on generic types in itds"); } public void testSuperCallInITD() { runTest("super call in ITD"); } public void testSuperCallInITDPart2() { runTest("super call in ITD - part 2"); } public void testAtAnnotationBadTest_pr103740() { runTest("Compiler failure on at_annotation"); } public void testNoUnusedParameterWarningsForSyntheticAdviceArgs() { runTest("no unused parameter warnings for synthetic advice args"); } public void testNoVerifyErrorWithSetOnInnerType() { runTest("no verify error with set on inner type"); } public void testCantFindTypeErrorWithGenericReturnTypeOrParameter() { runTest("cant find type error with generic return type or parameter"); } public void testNoVerifyErrorOnGenericCollectionMemberAccess() { runTest("no verify error on generic collection member access"); } public void testRawAndGenericTypeConversionITDCons() { runTest("raw and generic type conversion with itd cons"); } public void testUnableToBuildShadows_pr109728() { runTest("Unable to build shadows");} // helper methods..... public SyntheticRepository createRepos(File cpentry) { ClassPath cp = new ClassPath(cpentry+File.pathSeparator+System.getProperty("java.class.path")); return SyntheticRepository.getInstance(cp); } protected JavaClass getClassFrom(File where,String clazzname) throws ClassNotFoundException { SyntheticRepository repos = createRepos(where); return repos.loadClass(clazzname); } }
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26:40Z
tests/src/org/aspectj/systemtest/ajc150/ataspectj/AtAjAnnotationGenTests.java
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26:40Z
weaver/java5-src/org/aspectj/weaver/reflect/Java15AnnotationFinder.java
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26:40Z
weaver/java5-src/org/aspectj/weaver/reflect/Java15ReflectionBasedReferenceTypeDelegate.java
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26:40Z
weaver/java5-testsrc/org/aspectj/weaver/tools/Java15PointcutExpressionTest.java
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26:40Z
weaver/src/org/aspectj/weaver/Shadow.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver; import java.io.DataInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import org.aspectj.asm.IRelationship; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; import org.aspectj.bridge.WeaveMessage; import org.aspectj.lang.JoinPoint; import org.aspectj.util.PartialOrder; import org.aspectj.util.TypeSafeEnum; import org.aspectj.weaver.ast.Var; import org.aspectj.weaver.bcel.BcelAdvice; /* * The superclass of anything representing a the shadow of a join point. A shadow represents * some bit of code, and encompasses both entry and exit from that code. All shadows have a kind * and a signature. */ public abstract class Shadow { // every Shadow has a unique id, doesn't matter if it wraps... private static int nextShadowID = 100; // easier to spot than zero. private final Kind kind; private final Member signature; private Member matchingSignature; private ResolvedMember resolvedSignature; protected final Shadow enclosingShadow; protected List mungers = new ArrayList(1); public int shadowId = nextShadowID++; // every time we build a shadow, it gets a new id // ---- protected Shadow(Kind kind, Member signature, Shadow enclosingShadow) { this.kind = kind; this.signature = signature; this.enclosingShadow = enclosingShadow; } // ---- public abstract World getIWorld(); public List /*ShadowMunger*/ getMungers() { return mungers; } /** * could this(*) pcd ever match */ public final boolean hasThis() { if (getKind().neverHasThis()) { return false; } else if (getKind().isEnclosingKind()) { return !getSignature().isStatic(); } else if (enclosingShadow == null) { return false; } else { return enclosingShadow.hasThis(); } } /** * the type of the this object here * * @throws IllegalStateException if there is no this here */ public final UnresolvedType getThisType() { if (!hasThis()) throw new IllegalStateException("no this"); if (getKind().isEnclosingKind()) { return getSignature().getDeclaringType(); } else { return enclosingShadow.getThisType(); } } /** * a var referencing this * * @throws IllegalStateException if there is no target here */ public abstract Var getThisVar(); /** * could target(*) pcd ever match */ public final boolean hasTarget() { if (getKind().neverHasTarget()) { return false; } else if (getKind().isTargetSameAsThis()) { return hasThis(); } else { return !getSignature().isStatic(); } } /** * the type of the target object here * * @throws IllegalStateException if there is no target here */ public final UnresolvedType getTargetType() { if (!hasTarget()) throw new IllegalStateException("no target"); return getSignature().getDeclaringType(); } /** * a var referencing the target * * @throws IllegalStateException if there is no target here */ public abstract Var getTargetVar(); public UnresolvedType[] getArgTypes() { if (getKind() == FieldSet) return new UnresolvedType[] { getSignature().getReturnType() }; return getSignature().getParameterTypes(); } public UnresolvedType[] getGenericArgTypes() { if (getKind() == FieldSet) return new UnresolvedType[] { getResolvedSignature().getGenericReturnType() }; return getResolvedSignature().getGenericParameterTypes(); } public UnresolvedType getArgType(int arg) { if (getKind() == FieldSet) return getSignature().getReturnType(); return getSignature().getParameterTypes()[arg]; } public int getArgCount() { if (getKind() == FieldSet) return 1; return getSignature() .getParameterTypes().length; } public abstract UnresolvedType getEnclosingType(); public abstract Var getArgVar(int i); public abstract Var getThisJoinPointVar(); public abstract Var getThisJoinPointStaticPartVar(); public abstract Var getThisEnclosingJoinPointStaticPartVar(); // annotation variables public abstract Var getKindedAnnotationVar(UnresolvedType forAnnotationType); public abstract Var getWithinAnnotationVar(UnresolvedType forAnnotationType); public abstract Var getWithinCodeAnnotationVar(UnresolvedType forAnnotationType); public abstract Var getThisAnnotationVar(UnresolvedType forAnnotationType); public abstract Var getTargetAnnotationVar(UnresolvedType forAnnotationType); public abstract Var getArgAnnotationVar(int i, UnresolvedType forAnnotationType); public abstract Member getEnclosingCodeSignature(); /** returns the kind of shadow this is, representing what happens under this shadow */ public Kind getKind() { return kind; } /** returns the signature of the thing under this shadow */ public Member getSignature() { return signature; } /** * returns the signature of the thing under this shadow, with * any synthetic arguments removed */ public Member getMatchingSignature() { return matchingSignature != null ? matchingSignature : signature; } public void setMatchingSignature(Member member) { this.matchingSignature = member; } /** * returns the resolved signature of the thing under this shadow * */ public ResolvedMember getResolvedSignature() { if (resolvedSignature == null) { resolvedSignature = signature.resolve(getIWorld()); } return resolvedSignature; } public UnresolvedType getReturnType() { if (kind == ConstructorCall) return getSignature().getDeclaringType(); else if (kind == FieldSet) return ResolvedType.VOID; return getResolvedSignature().getGenericReturnType(); } /** * These names are the ones that will be returned by thisJoinPoint.getKind() * Those need to be documented somewhere */ public static final Kind MethodCall = new Kind(JoinPoint.METHOD_CALL, 1, true); public static final Kind ConstructorCall = new Kind(JoinPoint.CONSTRUCTOR_CALL, 2, true); public static final Kind MethodExecution = new Kind(JoinPoint.METHOD_EXECUTION, 3, false); public static final Kind ConstructorExecution = new Kind(JoinPoint.CONSTRUCTOR_EXECUTION, 4, false); public static final Kind FieldGet = new Kind(JoinPoint.FIELD_GET, 5, true); public static final Kind FieldSet = new Kind(JoinPoint.FIELD_SET, 6, true); public static final Kind StaticInitialization = new Kind(JoinPoint.STATICINITIALIZATION, 7, false); public static final Kind PreInitialization = new Kind(JoinPoint.PREINTIALIZATION, 8, false); public static final Kind AdviceExecution = new Kind(JoinPoint.ADVICE_EXECUTION, 9, false); public static final Kind Initialization = new Kind(JoinPoint.INITIALIZATION, 10, false); public static final Kind ExceptionHandler = new Kind(JoinPoint.EXCEPTION_HANDLER, 11, true); public static final int MAX_SHADOW_KIND = 11; public static final Kind[] SHADOW_KINDS = new Kind[] { MethodCall, ConstructorCall, MethodExecution, ConstructorExecution, FieldGet, FieldSet, StaticInitialization, PreInitialization, AdviceExecution, Initialization, ExceptionHandler, }; public static final Set ALL_SHADOW_KINDS = new HashSet(); static { for (int i = 0; i < SHADOW_KINDS.length; i++) { ALL_SHADOW_KINDS.add(SHADOW_KINDS[i]); } } /** A type-safe enum representing the kind of shadows */ public static final class Kind extends TypeSafeEnum { private boolean argsOnStack; //XXX unused public Kind(String name, int key, boolean argsOnStack) { super(name, key); this.argsOnStack = argsOnStack; } public String toLegalJavaIdentifier() { return getName().replace('-', '_'); } public boolean argsOnStack() { return !isTargetSameAsThis(); } // !!! this is false for handlers! public boolean allowsExtraction() { return true; } // XXX revisit along with removal of priorities public boolean hasHighPriorityExceptions() { return !isTargetSameAsThis(); } /** * These are all the shadows that contains other shadows within them and * are often directly associated with methods. */ public boolean isEnclosingKind() { return this == MethodExecution || this == ConstructorExecution || this == AdviceExecution || this == StaticInitialization || this == Initialization; } public boolean isTargetSameAsThis() { return this == MethodExecution || this == ConstructorExecution || this == StaticInitialization || this == PreInitialization || this == AdviceExecution || this == Initialization; } public boolean neverHasTarget() { return this == ConstructorCall || this == ExceptionHandler || this == PreInitialization || this == StaticInitialization; } public boolean neverHasThis() { return this == PreInitialization || this == StaticInitialization; } public String getSimpleName() { int dash = getName().lastIndexOf('-'); if (dash == -1) return getName(); else return getName().substring(dash+1); } public static Kind read(DataInputStream s) throws IOException { int key = s.readByte(); switch(key) { case 1: return MethodCall; case 2: return ConstructorCall; case 3: return MethodExecution; case 4: return ConstructorExecution; case 5: return FieldGet; case 6: return FieldSet; case 7: return StaticInitialization; case 8: return PreInitialization; case 9: return AdviceExecution; case 10: return Initialization; case 11: return ExceptionHandler; } throw new BCException("unknown kind: " + key); } } /** * Only does the check if the munger requires it (@AJ aspects don't) * * @param munger * @return */ protected boolean checkMunger(ShadowMunger munger) { if (munger.mustCheckExceptions()) { for (Iterator i = munger.getThrownExceptions().iterator(); i.hasNext(); ) { if (!checkCanThrow(munger, (ResolvedType)i.next() )) return false; } } return true; } protected boolean checkCanThrow(ShadowMunger munger, ResolvedType resolvedTypeX) { if (getKind() == ExceptionHandler) { //XXX much too lenient rules here, need to walk up exception handlers return true; } if (!isDeclaredException(resolvedTypeX, getSignature())) { getIWorld().showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.CANT_THROW_CHECKED,resolvedTypeX,this), // from advice in \'" + munger. + "\'", getSourceLocation(), munger.getSourceLocation()); } return true; } private boolean isDeclaredException( ResolvedType resolvedTypeX, Member member) { ResolvedType[] excs = getIWorld().resolve(member.getExceptions(getIWorld())); for (int i=0, len=excs.length; i < len; i++) { if (excs[i].isAssignableFrom(resolvedTypeX)) return true; } return false; } public void addMunger(ShadowMunger munger) { if (checkMunger(munger)) this.mungers.add(munger); } public final void implement() { sortMungers(); if (mungers == null) return; prepareForMungers(); implementMungers(); } private void sortMungers() { List sorted = PartialOrder.sort(mungers); if (sorted == null) { // this means that we have circular dependencies for (Iterator i = mungers.iterator(); i.hasNext(); ) { ShadowMunger m = (ShadowMunger)i.next(); getIWorld().getMessageHandler().handleMessage( MessageUtil.error( WeaverMessages.format(WeaverMessages.CIRCULAR_DEPENDENCY,this), m.getSourceLocation())); } } mungers = sorted; } /** Prepare the shadow for implementation. After this is done, the shadow * should be in such a position that each munger simply needs to be implemented. */ protected void prepareForMungers() { throw new RuntimeException("Generic shadows cannot be prepared"); } /* * Ensure we report a nice source location - particular in the case * where the source info is missing (binary weave). */ private String beautifyLocation(ISourceLocation isl) { StringBuffer nice = new StringBuffer(); if (isl==null || isl.getSourceFile()==null || isl.getSourceFile().getName().indexOf("no debug info available")!=-1) { nice.append("no debug info available"); } else { // can't use File.getName() as this fails when a Linux box encounters a path created on Windows and vice-versa int takeFrom = isl.getSourceFile().getPath().lastIndexOf('/'); if (takeFrom == -1) { takeFrom = isl.getSourceFile().getPath().lastIndexOf('\\'); } nice.append(isl.getSourceFile().getPath().substring(takeFrom +1)); if (isl.getLine()!=0) nice.append(":").append(isl.getLine()); } return nice.toString(); } /* * Report a message about the advice weave that has occurred. Some messing about * to make it pretty ! This code is just asking for an NPE to occur ... */ private void reportWeavingMessage(ShadowMunger munger) { Advice advice = (Advice)munger; AdviceKind aKind = advice.getKind(); // Only report on interesting advice kinds ... if (aKind == null || advice.getConcreteAspect()==null) { // We suspect someone is programmatically driving the weaver // (e.g. IdWeaveTestCase in the weaver testcases) return; } if (!( aKind.equals(AdviceKind.Before) || aKind.equals(AdviceKind.After) || aKind.equals(AdviceKind.AfterReturning) || aKind.equals(AdviceKind.AfterThrowing) || aKind.equals(AdviceKind.Around) || aKind.equals(AdviceKind.Softener))) return; String description = advice.getKind().toString(); String advisedType = this.getEnclosingType().getName(); String advisingType= advice.getConcreteAspect().getName(); Message msg = null; if (advice.getKind().equals(AdviceKind.Softener)) { msg = WeaveMessage.constructWeavingMessage( WeaveMessage.WEAVEMESSAGE_SOFTENS, new String[]{advisedType,beautifyLocation(getSourceLocation()), advisingType,beautifyLocation(munger.getSourceLocation())}, advisedType, advisingType); } else { boolean runtimeTest = ((BcelAdvice)advice).hasDynamicTests(); String joinPointDescription = this.toString(); msg = WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_ADVISES, new String[]{ joinPointDescription, advisedType, beautifyLocation(getSourceLocation()), description, advisingType,beautifyLocation(munger.getSourceLocation()), (runtimeTest?" [with runtime test]":"")}, advisedType, advisingType); // Boolean.toString(runtimeTest)}); } getIWorld().getMessageHandler().handleMessage(msg); } public IRelationship.Kind determineRelKind(ShadowMunger munger) { AdviceKind ak = ((Advice)munger).getKind(); if (ak.getKey()==AdviceKind.Before.getKey()) return IRelationship.Kind.ADVICE_BEFORE; else if (ak.getKey()==AdviceKind.After.getKey()) return IRelationship.Kind.ADVICE_AFTER; else if (ak.getKey()==AdviceKind.AfterThrowing.getKey()) return IRelationship.Kind.ADVICE_AFTERTHROWING; else if (ak.getKey()==AdviceKind.AfterReturning.getKey()) return IRelationship.Kind.ADVICE_AFTERRETURNING; else if (ak.getKey()==AdviceKind.Around.getKey()) return IRelationship.Kind.ADVICE_AROUND; else if (ak.getKey()==AdviceKind.CflowEntry.getKey() || ak.getKey()==AdviceKind.CflowBelowEntry.getKey() || ak.getKey()==AdviceKind.InterInitializer.getKey() || ak.getKey()==AdviceKind.PerCflowEntry.getKey() || ak.getKey()==AdviceKind.PerCflowBelowEntry.getKey() || ak.getKey()==AdviceKind.PerThisEntry.getKey() || ak.getKey()==AdviceKind.PerTargetEntry.getKey() || ak.getKey()==AdviceKind.Softener.getKey() || ak.getKey()==AdviceKind.PerTypeWithinEntry.getKey()) { //System.err.println("Dont want a message about this: "+ak); return null; } throw new RuntimeException("Shadow.determineRelKind: What the hell is it? "+ak); } /** Actually implement the (non-empty) mungers associated with this shadow */ private void implementMungers() { World world = getIWorld(); for (Iterator iter = mungers.iterator(); iter.hasNext();) { ShadowMunger munger = (ShadowMunger) iter.next(); munger.implementOn(this); if (world.getCrossReferenceHandler() != null) { world.getCrossReferenceHandler().addCrossReference( munger.getSourceLocation(), // What is being applied this.getSourceLocation(), // Where is it being applied determineRelKind(munger), // What kind of advice? ((BcelAdvice)munger).hasDynamicTests() // Is a runtime test being stuffed in the code? ); } // TAG: WeavingMessage if (!getIWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)) { reportWeavingMessage(munger); } if (world.getModel() != null) { //System.err.println("munger: " + munger + " on " + this); AsmRelationshipProvider.getDefault().adviceMunger(world.getModel(), this, munger); } } } public String makeReflectiveFactoryString() { return null; //XXX } public abstract ISourceLocation getSourceLocation(); // ---- utility public String toString() { return getKind() + "(" + getSignature() + ")"; // + getSourceLines(); } public String toResolvedString(World world) { return getKind() + "(" + world.resolve(getSignature()).toGenericString() + ")"; } }
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26:40Z
weaver/src/org/aspectj/weaver/UnresolvedType.java
/* ******************************************************************* * Copyright (c) 2002,2005 Contributors * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * Andy Clement start of generics upgrade... * Adrian Colyer - overhaul * ******************************************************************/ package org.aspectj.weaver; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.Map; import org.aspectj.apache.bcel.classfile.GenericSignatureParser; import org.aspectj.apache.bcel.classfile.Signature; import org.aspectj.apache.bcel.classfile.Signature.ClassSignature; /** * A UnresolvedType represents a type to the weaver. It has a basic signature that knows * nothing about type variables, type parameters, etc.. TypeXs are resolved in some World * (a repository of types). When a UnresolvedType is resolved it turns into a * ResolvedType which may be a primitive type, an array type or a ReferenceType. * ReferenceTypes may refer to simple, generic, parameterized or type-variable * based reference types. A ReferenceType is backed by a delegate that provides * information about the type based on some repository (currently either BCEL * or an EclipseSourceType, but in the future we probably need to support * java.lang.reflect based delegates too). * * Every UnresolvedType has a signature, the unique key for the type in the world. * * * TypeXs are fully aware of their complete type information (there is no * erasure in the UnresolvedType world). To achieve this, the signature of TypeXs * combines the basic Java signature and the generic signature information * into one complete signature. * * The format of a UnresolvedType signature is as follows: * * a simple (non-generic, non-parameterized) type has the as its signature * the Java signature. * e.g. Ljava/lang/String; * * a generic type has signature: * TypeParamsOpt ClassSig SuperClassSig SuperIntfListOpt * * following the Generic signature grammar in the JVM spec., but with the * addition of the ClassSignature (which is not in the generic signature). In addition * type variable names are replaced by a simple number which represents their * declaration order in the type declaration. * * e.g. public class Foo<T extends Number> would have signature: * <1:Ljava/lang/Number>Lorg.xyz.Foo;Ljava/lang/Object; * * A parameterized type is a distinct type in the world with its own signature * following the grammar: * * TypeParamsOpt ClassSig<ParamSigList>; * * but with the L for the class sig replaced by "P". For example List<String> has * signature * * Pjava/util/List<Ljava/lang/String>; * * and List<T> in the following class : * class Foo<T> { List<T> lt; } * * has signature: * <1:>Pjava/util/List<T1;>; * * A typex that represents a type variable has its own unique signature, * following the grammar for a FormalTypeParameter in the JVM spec. * * A generic typex has its true signature and also an erasure signature. * Both of these are keys pointing to the same UnresolvedType in the world. For example * List has signature: * * <1:>Ljava/util/List;Ljava/lang/Object; * * and the erasure signature * * Ljava/util/List; * * Generics wildcards introduce their own special signatures for type parameters. * The wildcard ? has signature * * The wildcard ? extends Foo has signature +LFoo; * The wildcard ? super Foo has signature -LFoo; */ public class UnresolvedType implements TypeVariableDeclaringElement { // common types referred to by the weaver public static final UnresolvedType[] NONE = new UnresolvedType[0]; public static final UnresolvedType OBJECT = forSignature("Ljava/lang/Object;"); public static final UnresolvedType OBJECTARRAY = forSignature("[Ljava/lang/Object;"); public static final UnresolvedType CLONEABLE = forSignature("Ljava/lang/Cloneable;"); public static final UnresolvedType SERIALIZABLE = forSignature("Ljava/io/Serializable;"); public static final UnresolvedType THROWABLE = forSignature("Ljava/lang/Throwable;"); public static final UnresolvedType RUNTIME_EXCEPTION = forSignature("Ljava/lang/RuntimeException;"); public static final UnresolvedType ERROR = forSignature("Ljava/lang/Error;"); public static final UnresolvedType AT_INHERITED = forSignature("Ljava/lang/annotation/Inherited;"); public static final UnresolvedType AT_RETENTION = forSignature("Ljava/lang/annotation/Retention;"); public static final UnresolvedType ENUM = forSignature("Ljava/lang/Enum;"); public static final UnresolvedType ANNOTATION = forSignature("Ljava/lang/annotation/Annotation;"); public static final UnresolvedType JAVA_LANG_CLASS = forSignature("Ljava/lang/Class;"); public static final UnresolvedType JAVA_LANG_EXCEPTION = forSignature("Ljava/lang/Exception;"); public static final UnresolvedType JAVA_LANG_REFLECT_METHOD = forSignature("Ljava/lang/reflect/Method;"); public static final UnresolvedType SUPPRESS_AJ_WARNINGS = forSignature("Lorg/aspectj/lang/annotation/SuppressAjWarnings;"); public static final UnresolvedType AT_TARGET = forSignature("Ljava/lang/annotation/Target;"); public static final UnresolvedType SOMETHING = new UnresolvedType("?"); // this doesn't belong here and will get moved to ResolvedType later in the refactoring public static final String MISSING_NAME = "@missing@"; protected TypeKind typeKind = TypeKind.SIMPLE; // what kind of type am I? /** * THE SIGNATURE - see the comments above for how this is defined */ protected String signature; /** * The erasure of the signature. Contains only the Java signature of the type * with all supertype, superinterface, type variable, and parameter information * removed. */ protected String signatureErasure; /** * Iff isParameterized(), then these are the type parameters */ protected UnresolvedType[] typeParameters; /** * Iff isGeneric(), then these are the type variables declared on the type * Iff isParameterized(), then these are the type variables bound as parameters * in the type */ protected TypeVariable[] typeVariables; /** * Iff isGenericWildcard, then this is the upper bound type for ? extends Foo */ private UnresolvedType upperBound; /** * Iff isGenericWildcard, then this is the lower bound type for ? super Foo */ private UnresolvedType lowerBound; /** * for wildcards '? extends' or for type variables 'T extends' */ private boolean isSuper = false; private boolean isExtends = false; /** * Determines if this represents a primitive type. A primitive type * is one of nine predefined resolved types. * * @return true iff this type represents a primitive type * * @see ResolvedType#Boolean * @see ResolvedType#Character * @see ResolvedType#Byte * @see ResolvedType#Short * @see ResolvedType#Integer * @see ResolvedType#Long * @see ResolvedType#Float * @see ResolvedType#Double * @see ResolvedType#Void */ public boolean isPrimitiveType() { return typeKind == TypeKind.PRIMITIVE; } public boolean isSimpleType() { return typeKind == TypeKind.SIMPLE; } public boolean isRawType() { return typeKind == TypeKind.RAW; } public boolean isGenericType() { return typeKind == TypeKind.GENERIC; } public boolean isParameterizedType() { return typeKind == TypeKind.PARAMETERIZED; } public boolean isTypeVariableReference() { return typeKind == TypeKind.TYPE_VARIABLE; } public boolean isGenericWildcard() { return typeKind == TypeKind.WILDCARD; } public boolean isExtends() { return isExtends;} public boolean isSuper() { return isSuper; } // for any reference type, we can get some extra information... public final boolean isArray() { return signature.startsWith("["); } /** * Equality is checked based on the underlying signature. * {@link ResolvedType} objects' equals is by reference. */ public boolean equals(Object other) { if (! (other instanceof UnresolvedType)) return false; return signature.equals(((UnresolvedType) other).signature); } /** * Equality is checked based on the underlying signature, so the hash code * of a particular type is the hash code of its signature string. */ public final int hashCode() { return signature.hashCode(); } /** * Return a version of this parameterized type in which any type parameters * that are type variable references are replaced by their matching type variable * binding. */ public UnresolvedType parameterize(Map typeBindings) { throw new UnsupportedOperationException("resolve this type first"); } /** * protected constructor for use only within UnresolvedType hierarchy. Use * one of the UnresolvedType.forXXX static methods for normal creation of * TypeXs. * Picks apart the signature string to set the type kind and calculates the * corresponding signatureErasure. A SIMPLE type created from a plain * Java signature may turn into a GENERIC type when it is resolved. * * This method should never be called for a primitive type. (UnresolvedType. forSignature * deals with those). * * @param signature in the form described in the class comment at the * top of this file. */ // protected UnresolvedType(String aSignature) { // this.signature = aSignature; // // // } // ----------------------------- // old stuff... /** * @param signature the bytecode string representation of this Type */ protected UnresolvedType(String signature) { super(); this.signature = signature; this.signatureErasure = signature; if (signature.charAt(0)=='-') isSuper = true; if (signature.charAt(0)=='+') isExtends = true; } protected UnresolvedType(String signature, String signatureErasure) { this.signature = signature; this.signatureErasure = signatureErasure; if (signature.charAt(0)=='-') isSuper = true; if (signature.charAt(0)=='+') isExtends = true; } // called from TypeFactory public UnresolvedType(String signature, String signatureErasure, UnresolvedType[] typeParams) { this.signature = signature; this.signatureErasure = signatureErasure; this.typeParameters = typeParams; if (typeParams != null) this.typeKind = TypeKind.PARAMETERIZED; } // ---- Things we can do without a world /** * This is the size of this type as used in JVM. */ public int getSize() { return 1; } public static UnresolvedType makeArray(UnresolvedType base, int dims) { StringBuffer sig = new StringBuffer(); for (int i=0; i < dims; i++) sig.append("["); sig.append(base.getSignature()); return UnresolvedType.forSignature(sig.toString()); } /** * NOTE: Use forSignature() if you can, it'll be cheaper ! * Constructs a UnresolvedType for a java language type name. For example: * * <blockquote><pre> * UnresolvedType.forName("java.lang.Thread[]") * UnresolvedType.forName("int") * </pre></blockquote> * * Types may equivalently be produced by this or by {@link #forSignature(String)}. * * <blockquote><pre> * UnresolvedType.forName("java.lang.Thread[]").equals(Type.forSignature("[Ljava/lang/Thread;") * UnresolvedType.forName("int").equals(Type.forSignature("I")) * </pre></blockquote> * * @param name the java language type name in question. * @return a type object representing that java language type. */ public static UnresolvedType forName(String name) { return forSignature(nameToSignature(name)); } /** Constructs a UnresolvedType for each java language type name in an incoming array. * * @param names an array of java language type names. * @return an array of UnresolvedType objects. * @see #forName(String) */ public static UnresolvedType[] forNames(String[] names) { UnresolvedType[] ret = new UnresolvedType[names.length]; for (int i = 0, len = names.length; i < len; i++) { ret[i] = UnresolvedType.forName(names[i]); } return ret; } public static UnresolvedType forGenericType(String name,TypeVariable[] tvbs,String genericSig) { // TODO asc generics needs a declared sig String sig = nameToSignature(name); UnresolvedType ret = UnresolvedType.forSignature(sig); ret.typeKind=TypeKind.GENERIC; ret.typeVariables = tvbs; ret.signatureErasure = sig; return ret; } public static UnresolvedType forGenericTypeSignature(String sig,String declaredGenericSig) { UnresolvedType ret = UnresolvedType.forSignature(sig); ret.typeKind=TypeKind.GENERIC; ClassSignature csig = new GenericSignatureParser().parseAsClassSignature(declaredGenericSig); Signature.FormalTypeParameter[] ftps = csig.formalTypeParameters; ret.typeVariables = new TypeVariable[ftps.length]; for (int i = 0; i < ftps.length; i++) { Signature.FormalTypeParameter parameter = ftps[i]; Signature.ClassTypeSignature cts = (Signature.ClassTypeSignature)parameter.classBound; ret.typeVariables[i]=new TypeVariable(ftps[i].identifier,UnresolvedType.forSignature(cts.outerType.identifier+";")); } ret.signatureErasure = sig; ret.signature = ret.signatureErasure; return ret; } public static UnresolvedType forRawTypeName(String name) { UnresolvedType ret = UnresolvedType.forName(name); ret.typeKind = TypeKind.RAW; return ret; } /** * Creates a new type array with a fresh type appended to the end. * * @param types the left hand side of the new array * @param end the right hand side of the new array */ public static UnresolvedType[] add(UnresolvedType[] types, UnresolvedType end) { int len = types.length; UnresolvedType[] ret = new UnresolvedType[len + 1]; System.arraycopy(types, 0, ret, 0, len); ret[len] = end; return ret; } /** * Creates a new type array with a fresh type inserted at the beginning. * * * @param start the left hand side of the new array * @param types the right hand side of the new array */ public static UnresolvedType[] insert(UnresolvedType start, UnresolvedType[] types) { int len = types.length; UnresolvedType[] ret = new UnresolvedType[len + 1]; ret[0] = start; System.arraycopy(types, 0, ret, 1, len); return ret; } /** * Constructs a Type for a JVM bytecode signature string. For example: * * <blockquote><pre> * UnresolvedType.forSignature("[Ljava/lang/Thread;") * UnresolvedType.forSignature("I"); * </pre></blockquote> * * Types may equivalently be produced by this or by {@link #forName(String)}. * * <blockquote><pre> * UnresolvedType.forName("java.lang.Thread[]").equals(Type.forSignature("[Ljava/lang/Thread;") * UnresolvedType.forName("int").equals(Type.forSignature("I")) * </pre></blockquote> * * @param signature the JVM bytecode signature string for the desired type. * @return a type object represnting that JVM bytecode signature. */ public static UnresolvedType forSignature(String signature) { switch (signature.charAt(0)) { case 'B': return ResolvedType.BYTE; case 'C': return ResolvedType.CHAR; case 'D': return ResolvedType.DOUBLE; case 'F': return ResolvedType.FLOAT; case 'I': return ResolvedType.INT; case 'J': return ResolvedType.LONG; case 'L': return TypeFactory.createTypeFromSignature(signature); case 'P': return TypeFactory.createTypeFromSignature(signature); case 'S': return ResolvedType.SHORT; case 'V': return ResolvedType.VOID; case 'Z': return ResolvedType.BOOLEAN; case '[': return TypeFactory.createTypeFromSignature(signature); case '+': return TypeFactory.createTypeFromSignature(signature); case '-' : return TypeFactory.createTypeFromSignature(signature); case '?' : return TypeFactory.createTypeFromSignature(signature); case 'T' : return TypeFactory.createTypeFromSignature(signature); default: throw new BCException("Bad type signature " + signature); } } /** Constructs a UnresolvedType for each JVM bytecode type signature in an incoming array. * * @param names an array of JVM bytecode type signatures * @return an array of UnresolvedType objects. * @see #forSignature(String) */ public static UnresolvedType[] forSignatures(String[] sigs) { UnresolvedType[] ret = new UnresolvedType[sigs.length]; for (int i = 0, len = sigs.length; i < len; i++) { ret[i] = UnresolvedType.forSignature(sigs[i]); } return ret; } /** * Returns the name of this type in java language form (e.g. java.lang.Thread or boolean[]). * This produces a more esthetically pleasing string than {@link java.lang.Class#getName()}. * * @return the java language name of this type. */ public String getName() { return signatureToName(signature); } public String getSimpleName() { String name = getRawName(); int lastDot = name.lastIndexOf('.'); if (lastDot != -1) { name = name.substring(lastDot+1); } if (isParameterizedType()) { StringBuffer sb = new StringBuffer(name); sb.append("<"); for (int i = 0; i < (typeParameters.length -1); i++) { sb.append(typeParameters[i].getSimpleName()); sb.append(","); } sb.append(typeParameters[typeParameters.length -1].getSimpleName()); sb.append(">"); name = sb.toString(); } return name; } public String getRawName() { return signatureToName((signatureErasure==null?signature:signatureErasure)); } public String getBaseName() { String name = getName(); if (isParameterizedType() || isGenericType()) { if (typeParameters==null) return name; else return name.substring(0,name.indexOf("<")); } else { return name; } } public String getSimpleBaseName() { String name = getBaseName(); int lastDot = name.lastIndexOf('.'); if (lastDot != -1) { name = name.substring(lastDot+1); } return name; } /** * Returns an array of strings representing the java langauge names of * an array of types. * * @param types an array of UnresolvedType objects * @return an array of Strings fo the java language names of types. * @see #getName() */ public static String[] getNames(UnresolvedType[] types) { String[] ret = new String[types.length]; for (int i = 0, len = types.length; i < len; i++) { ret[i] = types[i].getName(); } return ret; } /** * Returns the name of this type in JVM signature form. For all * UnresolvedType t: * * <blockquote><pre> * UnresolvedType.forSignature(t.getSignature()).equals(t) * </pre></blockquote> * * and for all String s where s is a lexically valid JVM type signature string: * * <blockquote><pre> * UnresolvedType.forSignature(s).getSignature().equals(s) * </pre></blockquote> * * @return the java JVM signature string for this type. */ public String getSignature() { return signature; } // public String getParameterizedSignature() { // return signature; // } /** * For parameterized types, return the signature for the raw type */ public String getErasureSignature() { if (signatureErasure==null) return signature; return signatureErasure; } public UnresolvedType getRawType() { return UnresolvedType.forSignature(getErasureSignature()); } /** * Get the upper bound for a generic wildcard */ public UnresolvedType getUpperBound() { return upperBound; } /** * Get the lower bound for a generic wildcard */ public UnresolvedType getLowerBound() { return lowerBound; } /** * Set the upper bound for a generic wildcard */ public void setUpperBound(UnresolvedType aBound) { this.upperBound = aBound; } /** * Set the lower bound for a generic wildcard */ public void setLowerBound(UnresolvedType aBound) { this.lowerBound = aBound; } /** * Returns a UnresolvedType object representing the effective outermost enclosing type * for a name type. For all other types, this will return the type itself. * * The only guarantee is given in JLS 13.1 where code generated according to * those rules will have type names that can be split apart in this way. * @return the outermost enclosing UnresolvedType object or this. */ public UnresolvedType getOutermostType() { if (isArray() || isPrimitiveType()) return this; String sig = getSignature(); int dollar = sig.indexOf('$'); if (dollar != -1) { return UnresolvedType.forSignature(sig.substring(0, dollar) + ';'); } else { return this; } } /** * Returns a UnresolvedType object representing the component type of this array, or * null if this type does not represent an array type. * * @return the component UnresolvedType object, or null. */ public UnresolvedType getComponentType() { if (isArray()) { return forSignature(signature.substring(1)); } else { return null; } } /** * Returns a java language string representation of this type. */ public String toString() { return getName(); // + " - " + getKind(); } // ---- requires worlds /** * Returns a resolved version of this type according to a particular world. * * @param world thie {@link World} within which to resolve. * @return a resolved type representing this type in the appropriate world. */ public ResolvedType resolve(World world) { return world.resolve(this); } // ---- helpers private static String signatureToName(String signature) { switch (signature.charAt(0)) { case 'B': return "byte"; case 'C': return "char"; case 'D': return "double"; case 'F': return "float"; case 'I': return "int"; case 'J': return "long"; case 'L': String name = signature.substring(1, signature.length() - 1).replace('/', '.'); return name; case 'T': StringBuffer nameBuff2 = new StringBuffer(); int colon = signature.indexOf(";"); String tvarName = signature.substring(1,colon); nameBuff2.append(tvarName); return nameBuff2.toString(); case 'P': // it's one of our parameterized type sigs StringBuffer nameBuff = new StringBuffer(); // signature for parameterized types is e.g. // List<String> -> Ljava/util/List<Ljava/lang/String;>; // Map<String,List<Integer>> -> Ljava/util/Map<java/lang/String;Ljava/util/List<Ljava/lang/Integer;>;>; int paramNestLevel = 0; for (int i = 1 ; i < signature.length(); i++) { char c = signature.charAt(i); switch (c) { case '/' : nameBuff.append('.'); break; case '<' : nameBuff.append("<"); paramNestLevel++; StringBuffer innerBuff = new StringBuffer(); while(paramNestLevel > 0) { c = signature.charAt(++i); if (c == '<') paramNestLevel++; if (c == '>') paramNestLevel--; if (paramNestLevel > 0) innerBuff.append(c); if (c == ';' && paramNestLevel == 1) { nameBuff.append(signatureToName(innerBuff.toString())); if (signature.charAt(i+1) != '>') nameBuff.append(','); innerBuff = new StringBuffer(); } } nameBuff.append(">"); break; case ';' : break; default: nameBuff.append(c); } } return nameBuff.toString(); case 'S': return "short"; case 'V': return "void"; case 'Z': return "boolean"; case '[': return signatureToName(signature.substring(1, signature.length())) + "[]"; // case '<': // // its a generic! // if (signature.charAt(1)=='>') return signatureToName(signature.substring(2)); case '+' : return "? extends " + signatureToName(signature.substring(1, signature.length())); case '-' : return "? super " + signatureToName(signature.substring(1, signature.length())); case '?' : return "?"; default: throw new BCException("Bad type signature: " + signature); } } private static String nameToSignature(String name) { if (name.equals("byte")) return "B"; if (name.equals("char")) return "C"; if (name.equals("double")) return "D"; if (name.equals("float")) return "F"; if (name.equals("int")) return "I"; if (name.equals("long")) return "J"; if (name.equals("short")) return "S"; if (name.equals("boolean")) return "Z"; if (name.equals("void")) return "V"; if (name.equals("?")) return name; if (name.endsWith("[]")) return "[" + nameToSignature(name.substring(0, name.length() - 2)); if (name.length() != 0) { // lots more tests could be made here... // check if someone is calling us with something that is a signature already if (name.charAt(0)=='[') { throw new BCException("Do not call nameToSignature with something that looks like a signature (descriptor): '"+name+"'"); } if (name.indexOf("<") == -1) { // not parameterised return "L" + name.replace('.', '/') + ";"; } else { StringBuffer nameBuff = new StringBuffer(); int nestLevel = 0; nameBuff.append("P"); for (int i = 0; i < name.length(); i++) { char c = name.charAt(i); switch (c) { case '.' : nameBuff.append('/'); break; case '<' : nameBuff.append("<"); nestLevel++; StringBuffer innerBuff = new StringBuffer(); while(nestLevel > 0) { c = name.charAt(++i); if (c == '<') nestLevel++; if (c == '>') nestLevel--; if (c == ',' && nestLevel == 1) { nameBuff.append(nameToSignature(innerBuff.toString())); innerBuff = new StringBuffer(); } else { if (nestLevel > 0) innerBuff.append(c); } } nameBuff.append(nameToSignature(innerBuff.toString())); nameBuff.append('>'); break; case '>' : throw new IllegalStateException("Should by matched by <"); case ',' : throw new IllegalStateException("Should only happen inside <...>"); default: nameBuff.append(c); } } nameBuff.append(";"); return nameBuff.toString(); } } else throw new BCException("Bad type name: " + name); } public void write(DataOutputStream s) throws IOException { s.writeUTF(getSignature()); } public static UnresolvedType read(DataInputStream s) throws IOException { String sig = s.readUTF(); if (sig.equals(MISSING_NAME)) { return ResolvedType.MISSING; } else { return UnresolvedType.forSignature(sig); } } public static void writeArray(UnresolvedType[] types, DataOutputStream s) throws IOException { int len = types.length; s.writeShort(len); for (int i=0; i < len; i++) { types[i].write(s); } } public static UnresolvedType[] readArray(DataInputStream s) throws IOException { int len = s.readShort(); UnresolvedType[] types = new UnresolvedType[len]; for (int i=0; i < len; i++) { types[i] = UnresolvedType.read(s); } return types; } public String getNameAsIdentifier() { return getName().replace('.', '_'); } public String getPackageNameAsIdentifier() { String name = getName(); int index = name.lastIndexOf('.'); if (index == -1) { return ""; } else { return name.substring(0, index).replace('.', '_'); } } public String getPackageName() { String name = getName(); int index = name.lastIndexOf('.'); if (index == -1) { return null; } else { return name.substring(0, index); } } public UnresolvedType[] getTypeParameters() { return typeParameters == null ? new UnresolvedType[0] : typeParameters; } /** * Doesn't include the package */ public String getClassName() { String name = getName(); int index = name.lastIndexOf('.'); if (index == -1) { return name; } else { return name.substring(index+1); } } public TypeVariable[] getTypeVariables() { return typeVariables; } public static class TypeKind { // Note: It is not sufficient to say that a parameterized type with no type parameters in fact // represents a raw type - a parameterized type with no type parameters can represent // an inner type of a parameterized type that specifies no type parameters of its own. public final static TypeKind PRIMITIVE = new TypeKind("primitive"); public final static TypeKind SIMPLE = new TypeKind("simple"); // a type with NO type parameters/vars public final static TypeKind RAW = new TypeKind("raw"); // the erasure of a generic type public final static TypeKind GENERIC = new TypeKind("generic"); // a generic type public final static TypeKind PARAMETERIZED= new TypeKind("parameterized"); // a parameterized type public final static TypeKind TYPE_VARIABLE= new TypeKind("type_variable"); // a type variable public final static TypeKind WILDCARD = new TypeKind("wildcard"); // a generic wildcard type public String toString() { return type; } private TypeKind(String type) { this.type = type; } private final String type; } /** * Will return true if the type being represented is parameterized with a type variable * from a generic method/ctor rather than a type variable from a generic type. * Only subclasses know the answer... */ public boolean isParameterizedWithAMemberTypeVariable() { throw new RuntimeException("I dont know - you should ask a resolved version of me: "+this); } }
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26:40Z
weaver/src/org/aspectj/weaver/World.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * 2005 Contributors * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * Adrian Colyer, Andy Clement, overhaul for generics * ******************************************************************/ package org.aspectj.weaver; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.WeakHashMap; import org.aspectj.asm.IHierarchy; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.IMessageHandler; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; import org.aspectj.bridge.IMessage.Kind; import org.aspectj.weaver.UnresolvedType.TypeKind; import org.aspectj.weaver.patterns.DeclarePrecedence; import org.aspectj.weaver.patterns.PerClause; import org.aspectj.weaver.patterns.Pointcut; /** * A World is a collection of known types and crosscutting members. */ public abstract class World implements Dump.INode { /** handler for any messages produced during resolution etc. */ private IMessageHandler messageHandler = IMessageHandler.SYSTEM_ERR; /** handler for cross-reference information produced during the weaving process */ private ICrossReferenceHandler xrefHandler = null; /** The heart of the world, a map from type signatures to resolved types */ protected TypeMap typeMap = new TypeMap(); // Signature to ResolvedType /** Calculator for working out aspect precedence */ private AspectPrecedenceCalculator precedenceCalculator; /** All of the type and shadow mungers known to us */ private CrosscuttingMembersSet crosscuttingMembersSet = new CrosscuttingMembersSet(this); /** Model holds ASM relationships */ private IHierarchy model = null; /** for processing Xlint messages */ private Lint lint = new Lint(this); /** XnoInline option setting passed down to weaver */ private boolean XnoInline; /** XlazyTjp option setting passed down to weaver */ private boolean XlazyTjp; /** XhasMember option setting passed down to weaver */ private boolean XhasMember = false; /** When behaving in a Java 5 way autoboxing is considered */ private boolean behaveInJava5Way = false; /** * A list of RuntimeExceptions containing full stack information for every * type we couldn't find. */ private List dumpState_cantFindTypeExceptions = null; /** * Play God. * On the first day, God created the primitive types and put them in the type * map. */ protected World() { super(); Dump.registerNode(this.getClass(),this); typeMap.put("B", ResolvedType.BYTE); typeMap.put("S", ResolvedType.SHORT); typeMap.put("I", ResolvedType.INT); typeMap.put("J", ResolvedType.LONG); typeMap.put("F", ResolvedType.FLOAT); typeMap.put("D", ResolvedType.DOUBLE); typeMap.put("C", ResolvedType.CHAR); typeMap.put("Z", ResolvedType.BOOLEAN); typeMap.put("V", ResolvedType.VOID); precedenceCalculator = new AspectPrecedenceCalculator(this); } /** * Dump processing when a fatal error occurs */ public void accept (Dump.IVisitor visitor) { visitor.visitString("Shadow mungers:"); visitor.visitList(crosscuttingMembersSet.getShadowMungers()); visitor.visitString("Type mungers:"); visitor.visitList(crosscuttingMembersSet.getTypeMungers()); visitor.visitString("Late Type mungers:"); visitor.visitList(crosscuttingMembersSet.getLateTypeMungers()); if (dumpState_cantFindTypeExceptions!=null) { visitor.visitString("Cant find type problems:"); visitor.visitList(dumpState_cantFindTypeExceptions); dumpState_cantFindTypeExceptions = null; } } // ============================================================================= // T Y P E R E S O L U T I O N // ============================================================================= /** * Resolve a type that we require to be present in the world */ public ResolvedType resolve(UnresolvedType ty) { return resolve(ty, false); } /** * Attempt to resolve a type - the source location gives you some context in which * resolution is taking place. In the case of an error where we can't find the * type - we can then at least report why (source location) we were trying to resolve it. */ public ResolvedType resolve(UnresolvedType ty,ISourceLocation isl) { ResolvedType ret = resolve(ty,true); if (ty == ResolvedType.MISSING) { IMessage msg = null; if (isl!=null) { msg = MessageUtil.error(WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE,ty.getName()),isl); } else { msg = MessageUtil.error(WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE,ty.getName())); } messageHandler.handleMessage(msg); } return ret; } /** * Convenience method for resolving an array of unresolved types * in one hit. Useful for e.g. resolving type parameters in signatures. */ public ResolvedType[] resolve(UnresolvedType[] types) { if (types == null) return new ResolvedType[0]; ResolvedType[] ret = new ResolvedType[types.length]; for (int i=0; i<types.length; i++) { ret[i] = resolve(types[i]); } return ret; } /** * Resolve a type. This the hub of type resolution. The resolved type is added * to the type map by signature. */ public ResolvedType resolve(UnresolvedType ty, boolean allowMissing) { // special resolution processing for already resolved types. if (ty instanceof ResolvedType) { ResolvedType rty = (ResolvedType) ty; rty = resolve(rty); return rty; } // dispatch back to the type variable reference to resolve its constituent parts // don't do this for other unresolved types otherwise you'll end up in a loop if (ty.isTypeVariableReference()) { return ty.resolve(this); } // if we've already got a resolved type for the signature, just return it // after updating the world String signature = ty.getSignature(); ResolvedType ret = typeMap.get(signature); if (ret != null) { ret.world = this; // Set the world for the RTX return ret; } else if ( signature.equals("?") || signature.equals("*")) { // might be a problem here, not sure '?' should make it to here as a signature, the // proper signature for wildcard '?' is '*' // fault in generic wildcard, can't be done earlier because of init issues ResolvedType something = new BoundedReferenceType("?",this); typeMap.put("?",something); return something; } // no existing resolved type, create one if (ty.isArray()) { ret = new ResolvedType.Array(signature, this, resolve(ty.getComponentType(), allowMissing)); } else { ret = resolveToReferenceType(ty); if (!allowMissing && ret == ResolvedType.MISSING) { handleRequiredMissingTypeDuringResolution(ty); } } // Pulling in the type may have already put the right entry in the map if (typeMap.get(signature)==null && ret != ResolvedType.MISSING) { typeMap.put(signature, ret); } return ret; } /** * We tried to resolve a type and couldn't find it... */ private void handleRequiredMissingTypeDuringResolution(UnresolvedType ty) { MessageUtil.error(messageHandler, WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE,ty.getName())); if (dumpState_cantFindTypeExceptions==null) { dumpState_cantFindTypeExceptions = new ArrayList(); } dumpState_cantFindTypeExceptions.add(new RuntimeException("Can't find type "+ty.getName())); } /** * Some TypeFactory operations create resolved types directly, but these won't be * in the typeMap - this resolution process puts them there. Resolved types are * also told their world which is needed for the special autoboxing resolved types. */ public ResolvedType resolve(ResolvedType ty) { if (ty.isTypeVariableReference()) return ty; // until type variables have proper sigs... ResolvedType resolved = typeMap.get(ty.getSignature()); if (resolved == null) { typeMap.put(ty.getSignature(), ty); resolved = ty; } resolved.world = this; return resolved; } /** * Convenience method for finding a type by name and resolving it in one step. */ public ResolvedType resolve(String name) { return resolve(UnresolvedType.forName(name)); } public ResolvedType resolve(String name,boolean allowMissing) { return resolve(UnresolvedType.forName(name),allowMissing); } /** * Resolve to a ReferenceType - simple, raw, parameterized, or generic. * Raw, parameterized, and generic versions of a type share a delegate. */ private final ResolvedType resolveToReferenceType(UnresolvedType ty) { if (ty.isParameterizedType()) { // ======= parameterized types ================ ReferenceType genericType = (ReferenceType)resolveGenericTypeFor(ty,false); ReferenceType parameterizedType = TypeFactory.createParameterizedType(genericType, ty.typeParameters, this); return parameterizedType; } else if (ty.isGenericType()) { // ======= generic types ====================== ReferenceType genericType = (ReferenceType)resolveGenericTypeFor(ty,false); return genericType; } else if (ty.isGenericWildcard()) { // ======= generic wildcard types ============= return resolveGenericWildcardFor(ty); } else { // ======= simple and raw types =============== String erasedSignature = ty.getErasureSignature(); ReferenceType simpleOrRawType = new ReferenceType(erasedSignature, this); ReferenceTypeDelegate delegate = resolveDelegate(simpleOrRawType); if (delegate == null) return ResolvedType.MISSING; if (delegate.isGeneric() && behaveInJava5Way) { // ======== raw type =========== simpleOrRawType.typeKind = TypeKind.RAW; ReferenceType genericType = new ReferenceType( UnresolvedType.forGenericTypeSignature(erasedSignature,delegate.getDeclaredGenericSignature()),this); // name = ReferenceType.fromTypeX(UnresolvedType.forRawTypeNames(ty.getName()),this); simpleOrRawType.setDelegate(delegate); genericType.setDelegate(delegate); simpleOrRawType.setGenericType(genericType); return simpleOrRawType; } else { // ======== simple type ========= simpleOrRawType.setDelegate(delegate); return simpleOrRawType; } } } /** * Attempt to resolve a type that should be a generic type. */ public ResolvedType resolveGenericTypeFor(UnresolvedType anUnresolvedType, boolean allowMissing) { // Look up the raw type by signature String rawSignature = anUnresolvedType.getRawType().getSignature(); ResolvedType rawType = (ResolvedType) typeMap.get(rawSignature); if (rawType==null) { rawType = resolve(UnresolvedType.forSignature(rawSignature),false); typeMap.put(rawSignature,rawType); } // Does the raw type know its generic form? (It will if we created the // raw type from a source type, it won't if its been created just through // being referenced, e.g. java.util.List ResolvedType genericType = rawType.getGenericType(); // There is a special case to consider here (testGenericsBang_pr95993 highlights it) // You may have an unresolvedType for a parameterized type but it // is backed by a simple type rather than a generic type. This occurs for // inner types of generic types that inherit their enclosing types // type variables. if (rawType.isSimpleType() && anUnresolvedType.typeParameters.length==0) { rawType.world = this; return rawType; } if (genericType != null) { genericType.world = this; return genericType; } else { // Fault in the generic that underpins the raw type ;) ReferenceTypeDelegate delegate = resolveDelegate((ReferenceType)rawType); ReferenceType genericRefType = new ReferenceType( UnresolvedType.forGenericTypeSignature(rawType.getSignature(),delegate.getDeclaredGenericSignature()),this); ((ReferenceType)rawType).setGenericType(genericRefType); genericRefType.setDelegate(delegate); ((ReferenceType)rawType).setDelegate(delegate); return genericRefType; } } /** * Go from an unresolved generic wildcard (represented by UnresolvedType) to a resolved version (BoundedReferenceType). */ private ReferenceType resolveGenericWildcardFor(UnresolvedType aType) { BoundedReferenceType ret = null; // FIXME asc doesnt take account of additional interface bounds (e.g. ? super R & Serializable - can you do that?) if (aType.isExtends()) { ReferenceType upperBound = (ReferenceType)resolve(aType.getUpperBound()); ret = new BoundedReferenceType(upperBound,true,this); } else if (aType.isSuper()) { ReferenceType lowerBound = (ReferenceType) resolve(aType.getLowerBound()); ret = new BoundedReferenceType(lowerBound,false,this); } else { // must be ? on its own! } return ret; } /** * Find the ReferenceTypeDelegate behind this reference type so that it can * fulfill its contract. */ protected abstract ReferenceTypeDelegate resolveDelegate(ReferenceType ty); /** * Special resolution for "core" types like OBJECT. These are resolved just like * any other type, but if they are not found it is more serious and we issue an * error message immediately. */ public ResolvedType getCoreType(UnresolvedType tx) { ResolvedType coreTy = resolve(tx,true); if (coreTy == ResolvedType.MISSING) { MessageUtil.error(messageHandler, WeaverMessages.format(WeaverMessages.CANT_FIND_CORE_TYPE,tx.getName())); } return coreTy; } /** * Lookup a type by signature, if not found then build one and put it in the * map. */ public ReferenceType lookupOrCreateName(UnresolvedType ty) { String signature = ty.getSignature(); ReferenceType ret = lookupBySignature(signature); if (ret == null) { ret = ReferenceType.fromTypeX(ty, this); typeMap.put(signature, ret); } return ret; } /** * Lookup a reference type in the world by its signature. Returns * null if not found. */ public ReferenceType lookupBySignature(String signature) { return (ReferenceType) typeMap.get(signature); } // ============================================================================= // T Y P E R E S O L U T I O N -- E N D // ============================================================================= /** * Member resolution is achieved by resolving the declaring type and then * looking up the member in the resolved declaring type. */ public ResolvedMember resolve(Member member) { ResolvedType declaring = member.getDeclaringType().resolve(this); if (declaring.isRawType()) declaring = declaring.getGenericType(); ResolvedMember ret; if (member.getKind() == Member.FIELD) { ret = declaring.lookupField(member); } else { ret = declaring.lookupMethod(member); } if (ret != null) return ret; return declaring.lookupSyntheticMember(member); } // Methods for creating various cross-cutting members... // =========================================================== /** * Create an advice shadow munger from the given advice attribute */ public abstract Advice createAdviceMunger( AjAttribute.AdviceAttribute attribute, Pointcut pointcut, Member signature); /** * Create an advice shadow munger for the given advice kind */ public final Advice createAdviceMunger( AdviceKind kind, Pointcut p, Member signature, int extraParameterFlags, IHasSourceLocation loc) { AjAttribute.AdviceAttribute attribute = new AjAttribute.AdviceAttribute(kind, p, extraParameterFlags, loc.getStart(), loc.getEnd(), loc.getSourceContext()); return createAdviceMunger(attribute, p, signature); } public abstract ConcreteTypeMunger makeCflowStackFieldAdder(ResolvedMember cflowField); public abstract ConcreteTypeMunger makeCflowCounterFieldAdder(ResolvedMember cflowField); /** * Register a munger for perclause @AJ aspect so that we add aspectOf(..) to them as needed * @see org.aspectj.weaver.bcel.BcelWorld#makePerClauseAspect(ResolvedType, org.aspectj.weaver.patterns.PerClause.Kind) */ public abstract ConcreteTypeMunger makePerClauseAspect(ResolvedType aspect, PerClause.Kind kind); public abstract ConcreteTypeMunger concreteTypeMunger(ResolvedTypeMunger munger, ResolvedType aspectType); /** * Same signature as org.aspectj.util.PartialOrder.PartialComparable.compareTo */ public int compareByPrecedence(ResolvedType aspect1, ResolvedType aspect2) { return precedenceCalculator.compareByPrecedence(aspect1, aspect2); } /** * compares by precedence with the additional rule that a super-aspect is * sorted before its sub-aspects */ public int compareByPrecedenceAndHierarchy(ResolvedType aspect1, ResolvedType aspect2) { return precedenceCalculator.compareByPrecedenceAndHierarchy(aspect1, aspect2); } // simple property getter and setters // =========================================================== /** * Nobody should hold onto a copy of this message handler, or setMessageHandler won't * work right. */ public IMessageHandler getMessageHandler() { return messageHandler; } public void setMessageHandler(IMessageHandler messageHandler) { this.messageHandler = messageHandler; } /** * convenenience method for creating and issuing messages via the message handler */ public void showMessage( Kind kind, String message, ISourceLocation loc1, ISourceLocation loc2) { if (loc1 != null) { messageHandler.handleMessage(new Message(message, kind, null, loc1)); if (loc2 != null) { messageHandler.handleMessage(new Message(message, kind, null, loc2)); } } else { messageHandler.handleMessage(new Message(message, kind, null, loc2)); } } public void setCrossReferenceHandler(ICrossReferenceHandler xrefHandler) { this.xrefHandler = xrefHandler; } /** * Get the cross-reference handler for the world, may be null. */ public ICrossReferenceHandler getCrossReferenceHandler() { return this.xrefHandler; } public List getDeclareParents() { return crosscuttingMembersSet.getDeclareParents(); } public List getDeclareAnnotationOnTypes() { return crosscuttingMembersSet.getDeclareAnnotationOnTypes(); } public List getDeclareAnnotationOnFields() { return crosscuttingMembersSet.getDeclareAnnotationOnFields(); } public List getDeclareAnnotationOnMethods() { return crosscuttingMembersSet.getDeclareAnnotationOnMethods(); } public List getDeclareSoft() { return crosscuttingMembersSet.getDeclareSofts(); } public CrosscuttingMembersSet getCrosscuttingMembersSet() { return crosscuttingMembersSet; } public IHierarchy getModel() { return model; } public void setModel(IHierarchy model) { this.model = model; } public Lint getLint() { return lint; } public void setLint(Lint lint) { this.lint = lint; } public boolean isXnoInline() { return XnoInline; } public void setXnoInline(boolean xnoInline) { XnoInline = xnoInline; } public boolean isXlazyTjp() { return XlazyTjp; } public void setXlazyTjp(boolean b) { XlazyTjp = b; } public boolean isHasMemberSupportEnabled() { return XhasMember; } public void setXHasMemberSupportEnabled(boolean b) { XhasMember = b; } public void setBehaveInJava5Way(boolean b) { behaveInJava5Way = b; } public boolean isInJava5Mode() { return behaveInJava5Way; } /* * Map of types in the world, with soft links to expendable ones. * An expendable type is a reference type that is not exposed to the weaver (ie * just pulled in for type resolution purposes). */ protected static class TypeMap { /** Map of types that never get thrown away */ private Map tMap = new HashMap(); /** Map of types that may be ejected from the cache if we need space */ private Map expendableMap = new WeakHashMap(); private static final boolean debug = false; /** * Add a new type into the map, the key is the type signature. * Some types do *not* go in the map, these are ones involving * *member* type variables. The reason is that when all you have is the * signature which gives you a type variable name, you cannot * guarantee you are using the type variable in the same way * as someone previously working with a similarly * named type variable. So, these do not go into the map: * - TypeVariableReferenceType. * - ParameterizedType where a member type variable is involved. * - BoundedReferenceType when one of the bounds is a type variable. * * definition: "member type variables" - a tvar declared on a generic * method/ctor as opposed to those you see declared on a generic type. */ public ResolvedType put(String key, ResolvedType type) { if (type.isParameterizedType() && type.isParameterizedWithAMemberTypeVariable()) { if (debug) System.err.println("Not putting a parameterized type that utilises member declared type variables into the typemap: key="+key+" type="+type); return type; } if (type.isTypeVariableReference()) { if (debug) System.err.println("Not putting a type variable reference type into the typemap: key="+key+" type="+type); return type; } // this test should be improved - only avoid putting them in if one of the // bounds is a member type variable if (type instanceof BoundedReferenceType) { if (debug) System.err.println("Not putting a bounded reference type into the typemap: key="+key+" type="+type); return type; } if (isExpendable(type)) { return (ResolvedType) expendableMap.put(key,type); } else { return (ResolvedType) tMap.put(key,type); } } /** Lookup a type by its signature */ public ResolvedType get(String key) { ResolvedType ret = (ResolvedType) tMap.get(key); if (ret == null) ret = (ResolvedType) expendableMap.get(key); return ret; } /** Remove a type from the map */ public ResolvedType remove(String key) { ResolvedType ret = (ResolvedType) tMap.remove(key); if (ret == null) ret = (ResolvedType) expendableMap.remove(key); return ret; } /** Reference types we don't intend to weave may be ejected from * the cache if we need the space. */ private boolean isExpendable(ResolvedType type) { return ( (type != null) && (!type.isExposedToWeaver()) && (!type.isPrimitiveType()) ); } public String toString() { StringBuffer sb = new StringBuffer(); sb.append("types:\n"); sb.append(dumpthem(tMap)); sb.append("expendables:\n"); sb.append(dumpthem(expendableMap)); return sb.toString(); } private String dumpthem(Map m) { StringBuffer sb = new StringBuffer(); Set keys = m.keySet(); for (Iterator iter = keys.iterator(); iter.hasNext();) { String k = (String) iter.next(); sb.append(k+"="+m.get(k)).append("\n"); } return sb.toString(); } } /** * This class is used to compute and store precedence relationships between * aspects. */ private static class AspectPrecedenceCalculator { private World world; private Map cachedResults; public AspectPrecedenceCalculator(World forSomeWorld) { this.world = forSomeWorld; this.cachedResults = new HashMap(); } /** * Ask every declare precedence in the world to order the two aspects. * If more than one declare precedence gives an ordering, and the orderings * conflict, then that's an error. */ public int compareByPrecedence(ResolvedType firstAspect, ResolvedType secondAspect) { PrecedenceCacheKey key = new PrecedenceCacheKey(firstAspect,secondAspect); if (cachedResults.containsKey(key)) { return ((Integer) cachedResults.get(key)).intValue(); } else { int order = 0; DeclarePrecedence orderer = null; // Records the declare precedence statement that gives the first ordering for (Iterator i = world.getCrosscuttingMembersSet().getDeclareDominates().iterator(); i.hasNext(); ) { DeclarePrecedence d = (DeclarePrecedence)i.next(); int thisOrder = d.compare(firstAspect, secondAspect); if (thisOrder != 0) { if (orderer==null) orderer = d; if (order != 0 && order != thisOrder) { ISourceLocation[] isls = new ISourceLocation[2]; isls[0]=orderer.getSourceLocation(); isls[1]=d.getSourceLocation(); Message m = new Message("conflicting declare precedence orderings for aspects: "+ firstAspect.getName()+" and "+secondAspect.getName(),null,true,isls); world.getMessageHandler().handleMessage(m); } else { order = thisOrder; } } } cachedResults.put(key, new Integer(order)); return order; } } public int compareByPrecedenceAndHierarchy(ResolvedType firstAspect, ResolvedType secondAspect) { if (firstAspect.equals(secondAspect)) return 0; int ret = compareByPrecedence(firstAspect, secondAspect); if (ret != 0) return ret; if (firstAspect.isAssignableFrom(secondAspect)) return -1; else if (secondAspect.isAssignableFrom(firstAspect)) return +1; return 0; } private static class PrecedenceCacheKey { public ResolvedType aspect1; public ResolvedType aspect2; public PrecedenceCacheKey(ResolvedType a1, ResolvedType a2) { this.aspect1 = a1; this.aspect2 = a2; } public boolean equals(Object obj) { if (!(obj instanceof PrecedenceCacheKey)) return false; PrecedenceCacheKey other = (PrecedenceCacheKey) obj; return (aspect1 == other.aspect1 && aspect2 == other.aspect2); } public int hashCode() { return aspect1.hashCode() + aspect2.hashCode(); } } } }
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26:40Z
weaver/src/org/aspectj/weaver/internal/tools/PointcutExpressionImpl.java
/* ******************************************************************* * Copyright (c) 2004 IBM Corporation. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * ******************************************************************/ package org.aspectj.weaver.internal.tools; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Member; import java.lang.reflect.Method; import org.aspectj.lang.JoinPoint; import org.aspectj.weaver.patterns.AbstractPatternNodeVisitor; import org.aspectj.weaver.patterns.ArgsAnnotationPointcut; import org.aspectj.weaver.patterns.ArgsPointcut; import org.aspectj.weaver.patterns.CflowPointcut; import org.aspectj.weaver.patterns.IfPointcut; import org.aspectj.weaver.patterns.NotAnnotationTypePattern; import org.aspectj.weaver.patterns.NotPointcut; import org.aspectj.weaver.patterns.Pointcut; import org.aspectj.weaver.patterns.ThisOrTargetAnnotationPointcut; import org.aspectj.weaver.patterns.ThisOrTargetPointcut; import org.aspectj.weaver.tools.FuzzyBoolean; import org.aspectj.weaver.tools.PointcutExpression; /** * Map from weaver.tools interface to internal Pointcut implementation... */ public class PointcutExpressionImpl implements PointcutExpression { private Pointcut pointcut; private String expression; public PointcutExpressionImpl(Pointcut pointcut, String expression) { this.pointcut = pointcut; this.expression = expression; } public boolean couldMatchJoinPointsInType(Class aClass) { return pointcut.fastMatch(aClass).maybeTrue(); } public boolean mayNeedDynamicTest() { HasPossibleDynamicContentVisitor visitor = new HasPossibleDynamicContentVisitor(); pointcut.traverse(visitor, null); return visitor.hasDynamicContent(); } /* (non-Javadoc) * @see org.aspectj.weaver.tools.PointcutExpression#matchesMethodCall(java.lang.reflect.Method, java.lang.Class, java.lang.Class, java.lang.reflect.Member) */ public FuzzyBoolean matchesMethodCall(Method aMethod, Class thisClass, Class targetClass, Member withinCode) { return fuzzyMatch(pointcut.matchesStatically( JoinPoint.METHOD_CALL, aMethod, thisClass, targetClass, withinCode)); } /* (non-Javadoc) * @see org.aspectj.weaver.tools.PointcutExpression#matchesMethodExecution(java.lang.reflect.Method, java.lang.Class) */ public FuzzyBoolean matchesMethodExecution(Method aMethod, Class thisClass) { return fuzzyMatch(pointcut.matchesStatically( JoinPoint.METHOD_EXECUTION, aMethod, thisClass, thisClass, null)); } /* (non-Javadoc) * @see org.aspectj.weaver.tools.PointcutExpression#matchesConstructorCall(java.lang.reflect.Constructor, java.lang.Class, java.lang.reflect.Member) */ public FuzzyBoolean matchesConstructorCall(Constructor aConstructor, Class thisClass, Member withinCode) { return fuzzyMatch(pointcut.matchesStatically( JoinPoint.CONSTRUCTOR_CALL, aConstructor, thisClass, aConstructor.getDeclaringClass(), withinCode)); } /* (non-Javadoc) * @see org.aspectj.weaver.tools.PointcutExpression#matchesConstructorExecution(java.lang.reflect.Constructor) */ public FuzzyBoolean matchesConstructorExecution(Constructor aConstructor, Class thisClass) { return fuzzyMatch(pointcut.matchesStatically( JoinPoint.CONSTRUCTOR_EXECUTION, aConstructor, thisClass, thisClass, null)); } /* (non-Javadoc) * @see org.aspectj.weaver.tools.PointcutExpression#matchesAdviceExecution(java.lang.reflect.Method, java.lang.Class) */ public FuzzyBoolean matchesAdviceExecution(Method anAdviceMethod, Class thisClass) { return fuzzyMatch(pointcut.matchesStatically( JoinPoint.ADVICE_EXECUTION, anAdviceMethod, thisClass, thisClass, null)); } /* (non-Javadoc) * @see org.aspectj.weaver.tools.PointcutExpression#matchesHandler(java.lang.Class, java.lang.Class, java.lang.reflect.Member) */ public FuzzyBoolean matchesHandler(Class exceptionType, Class inClass, Member withinCode) { return fuzzyMatch(pointcut.matchesStatically( JoinPoint.EXCEPTION_HANDLER, new Handler(inClass,exceptionType), inClass, inClass, withinCode)); } /* (non-Javadoc) * @see org.aspectj.weaver.tools.PointcutExpression#matchesInitialization(java.lang.reflect.Constructor) */ public FuzzyBoolean matchesInitialization(Constructor aConstructor) { return fuzzyMatch(pointcut.matchesStatically( JoinPoint.INITIALIZATION, aConstructor, aConstructor.getDeclaringClass(), aConstructor.getDeclaringClass(), null)); } /* (non-Javadoc) * @see org.aspectj.weaver.tools.PointcutExpression#matchesPreInitialization(java.lang.reflect.Constructor) */ public FuzzyBoolean matchesPreInitialization(Constructor aConstructor) { return fuzzyMatch(pointcut.matchesStatically( JoinPoint.PREINTIALIZATION, aConstructor, aConstructor.getDeclaringClass(), aConstructor.getDeclaringClass(), null)); } /* (non-Javadoc) * @see org.aspectj.weaver.tools.PointcutExpression#matchesStaticInitialization(java.lang.Class) */ public FuzzyBoolean matchesStaticInitialization(Class aClass) { return fuzzyMatch(pointcut.matchesStatically( JoinPoint.STATICINITIALIZATION, null, aClass, aClass, null )); } /* (non-Javadoc) * @see org.aspectj.weaver.tools.PointcutExpression#matchesFieldSet(java.lang.reflect.Field, java.lang.Class, java.lang.Class, java.lang.reflect.Member) */ public FuzzyBoolean matchesFieldSet(Field aField, Class thisClass, Class targetClass, Member withinCode) { return fuzzyMatch(pointcut.matchesStatically( JoinPoint.FIELD_SET, aField, thisClass, targetClass, withinCode)); } /* (non-Javadoc) * @see org.aspectj.weaver.tools.PointcutExpression#matchesFieldGet(java.lang.reflect.Field, java.lang.Class, java.lang.Class, java.lang.reflect.Member) */ public FuzzyBoolean matchesFieldGet(Field aField, Class thisClass, Class targetClass, Member withinCode) { return fuzzyMatch(pointcut.matchesStatically( JoinPoint.FIELD_GET, aField, thisClass, targetClass, withinCode)); } /* (non-Javadoc) * @see org.aspectj.weaver.tools.PointcutExpression#matchesDynamically(java.lang.Object, java.lang.Object, java.lang.Object[]) */ public boolean matchesDynamically(Object thisObject, Object targetObject, Object[] args) { return pointcut.matchesDynamically(thisObject,targetObject,args); } /* (non-Javadoc) * @see org.aspectj.weaver.tools.PointcutExpression#getPointcutExpression() */ public String getPointcutExpression() { return expression; } private FuzzyBoolean fuzzyMatch(org.aspectj.util.FuzzyBoolean fb) { if (fb == org.aspectj.util.FuzzyBoolean.YES) return FuzzyBoolean.YES; if (fb == org.aspectj.util.FuzzyBoolean.NO) return FuzzyBoolean.NO; if (fb == org.aspectj.util.FuzzyBoolean.MAYBE) return FuzzyBoolean.MAYBE; throw new IllegalArgumentException("Cant match FuzzyBoolean " + fb); } private static class HasPossibleDynamicContentVisitor extends AbstractPatternNodeVisitor { private boolean hasDynamicContent = false; public boolean hasDynamicContent() { return hasDynamicContent; } public Object visit(ArgsAnnotationPointcut node, Object data) { hasDynamicContent = true; return null; } public Object visit(ArgsPointcut node, Object data) { hasDynamicContent = true; return null; } public Object visit(CflowPointcut node, Object data) { hasDynamicContent = true; return null; } public Object visit(IfPointcut node, Object data) { hasDynamicContent = true; return null; } public Object visit(NotAnnotationTypePattern node, Object data) { return node.getNegatedPattern().accept(this, data); } public Object visit(NotPointcut node, Object data) { return node.getNegatedPointcut().accept(this, data); } public Object visit(ThisOrTargetAnnotationPointcut node, Object data) { hasDynamicContent = true; return null; } public Object visit(ThisOrTargetPointcut node, Object data) { hasDynamicContent = true; return null; } } public static class Handler implements Member { private Class decClass; private Class exType; public Handler(Class decClass, Class exType) { this.decClass = decClass; this.exType = exType; } public int getModifiers() { return 0; } public Class getDeclaringClass() { return decClass; } public String getName() { return null; } public Class getHandledExceptionType() { return exType; } public boolean isSynthetic() { return false; } } }
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26:40Z
weaver/src/org/aspectj/weaver/patterns/AndPointcut.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataOutputStream; import java.io.IOException; import java.lang.reflect.Member; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.aspectj.lang.JoinPoint; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.ast.Test; public class AndPointcut extends Pointcut { Pointcut left, right; // exposed for testing private Set couldMatchKinds; public AndPointcut(Pointcut left, Pointcut right) { super(); this.left = left; this.right = right; this.pointcutKind = AND; setLocation(left.getSourceContext(), left.getStart(), right.getEnd()); couldMatchKinds = new HashSet(); couldMatchKinds.addAll(left.couldMatchKinds()); couldMatchKinds.retainAll(right.couldMatchKinds()); } public Set couldMatchKinds() { return couldMatchKinds; } public FuzzyBoolean fastMatch(FastMatchInfo type) { return left.fastMatch(type).and(right.fastMatch(type)); } public FuzzyBoolean fastMatch(Class targetType) { return left.fastMatch(targetType).and(right.fastMatch(targetType)); } protected FuzzyBoolean matchInternal(Shadow shadow) { FuzzyBoolean leftMatch = left.match(shadow); if (leftMatch.alwaysFalse()) return leftMatch; return leftMatch.and(right.match(shadow)); } public FuzzyBoolean match(JoinPoint jp, JoinPoint.StaticPart encJP) { return left.match(jp,encJP).and(right.match(jp,encJP)); } public FuzzyBoolean match(JoinPoint.StaticPart jpsp) { return left.match(jpsp).and(right.match(jpsp)); } /* (non-Javadoc) * @see org.aspectj.weaver.tools.PointcutExpression#matchesDynamically(java.lang.Object, java.lang.Object, java.lang.Object[]) */ public boolean matchesDynamically(Object thisObject, Object targetObject, Object[] args) { return left.matchesDynamically(thisObject,targetObject,args) && right.matchesDynamically(thisObject,targetObject,args); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#matchesStatically(java.lang.String, java.lang.reflect.Member, java.lang.Class, java.lang.Class, java.lang.reflect.Member) */ public FuzzyBoolean matchesStatically( String joinpointKind, Member member, Class thisClass, Class targetClass, Member withinCode) { return left.matchesStatically(joinpointKind,member,thisClass,targetClass,withinCode) .and( right.matchesStatically(joinpointKind,member,thisClass,targetClass,withinCode)); } public String toString() { return "(" + left.toString() + " && " + right.toString() + ")"; } public boolean equals(Object other) { if (!(other instanceof AndPointcut)) return false; AndPointcut o = (AndPointcut)other; return o.left.equals(left) && o.right.equals(right); } public int hashCode() { int result = 19; result = 37*result + left.hashCode(); result = 37*result + right.hashCode(); return result; } public void resolveBindings(IScope scope, Bindings bindings) { left.resolveBindings(scope, bindings); right.resolveBindings(scope, bindings); } public void resolveBindingsFromRTTI() { left.resolveBindingsFromRTTI(); right.resolveBindingsFromRTTI(); } public void write(DataOutputStream s) throws IOException { s.writeByte(Pointcut.AND); left.write(s); right.write(s); writeLocation(s); } public static Pointcut read(VersionedDataInputStream s, ISourceContext context) throws IOException { AndPointcut ret = new AndPointcut(Pointcut.read(s, context), Pointcut.read(s, context)); ret.readLocation(context, s); return ret; } protected Test findResidueInternal(Shadow shadow, ExposedState state) { return Test.makeAnd(left.findResidue(shadow, state), right.findResidue(shadow, state)); } public Pointcut concretize1(ResolvedType inAspect, ResolvedType declaringType, IntMap bindings) { AndPointcut ret = new AndPointcut(left.concretize(inAspect, declaringType, bindings), right.concretize(inAspect, declaringType, bindings)); ret.copyLocationFrom(this); return ret; } public Pointcut parameterizeWith(Map typeVariableMap) { AndPointcut ret = new AndPointcut(left.parameterizeWith(typeVariableMap), right.parameterizeWith(typeVariableMap)); ret.copyLocationFrom(this); return ret; } public Pointcut getLeft() { return left; } public Pointcut getRight() { return right; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } public Object traverse(PatternNodeVisitor visitor, Object data) { Object ret = accept(visitor,data); left.traverse(visitor,ret); right.traverse(visitor,ret); return ret; } }
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26:40Z
weaver/src/org/aspectj/weaver/patterns/AndTypePattern.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataOutputStream; import java.io.IOException; import java.util.Map; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.VersionedDataInputStream; /** * left && right * * <p>any binding to formals is explicitly forbidden for any composite by the language * * @author Erik Hilsdale * @author Jim Hugunin */ public class AndTypePattern extends TypePattern { private TypePattern left, right; public AndTypePattern(TypePattern left, TypePattern right) { super(false,false); //?? we override all methods that care about includeSubtypes this.left = left; this.right = right; setLocation(left.getSourceContext(), left.getStart(), right.getEnd()); } protected boolean couldEverMatchSameTypesAs(TypePattern other) { return true; // don't dive into ands yet.... } public FuzzyBoolean matchesInstanceof(ResolvedType type) { return left.matchesInstanceof(type).and(right.matchesInstanceof(type)); } protected boolean matchesExactly(ResolvedType type) { //??? if these had side-effects, this sort-circuit could be a mistake return left.matchesExactly(type) && right.matchesExactly(type); } protected boolean matchesExactly(ResolvedType type, ResolvedType annotatedType) { return left.matchesExactly(type,annotatedType) && right.matchesExactly(type,annotatedType); } public boolean matchesStatically(Class type) { return left.matchesStatically(type) && right.matchesStatically(type); } public FuzzyBoolean matchesInstanceof(Class type) { return left.matchesInstanceof(type).and(right.matchesInstanceof(type)); } protected boolean matchesExactly(Class type) { //??? if these had side-effects, this sort-circuit could be a mistake return left.matchesExactly(type) && right.matchesExactly(type); } public boolean matchesStatically(ResolvedType type) { return left.matchesStatically(type) && right.matchesStatically(type); } public void setIsVarArgs(boolean isVarArgs) { this.isVarArgs = isVarArgs; left.setIsVarArgs(isVarArgs); right.setIsVarArgs(isVarArgs); } public void setAnnotationTypePattern(AnnotationTypePattern annPatt) { if (annPatt == AnnotationTypePattern.ANY) return; if (left.annotationPattern == AnnotationTypePattern.ANY) { left.setAnnotationTypePattern(annPatt); } else { left.setAnnotationTypePattern( new AndAnnotationTypePattern(left.annotationPattern,annPatt)); } if (right.annotationPattern == AnnotationTypePattern.ANY) { right.setAnnotationTypePattern(annPatt); } else { right.setAnnotationTypePattern( new AndAnnotationTypePattern(right.annotationPattern,annPatt)); } } public void write(DataOutputStream s) throws IOException { s.writeByte(TypePattern.AND); left.write(s); right.write(s); writeLocation(s); } public static TypePattern read(VersionedDataInputStream s, ISourceContext context) throws IOException { AndTypePattern ret = new AndTypePattern(TypePattern.read(s, context), TypePattern.read(s, context)); ret.readLocation(context, s); if (ret.left.isVarArgs && ret.right.isVarArgs) ret.isVarArgs = true; return ret; } public TypePattern resolveBindings( IScope scope, Bindings bindings, boolean allowBinding, boolean requireExactType) { if (requireExactType) return notExactType(scope); left = left.resolveBindings(scope, bindings, false, false); right = right.resolveBindings(scope, bindings, false, false); return this; } public TypePattern parameterizeWith(Map typeVariableMap) { TypePattern newLeft = left.parameterizeWith(typeVariableMap); TypePattern newRight = right.parameterizeWith(typeVariableMap); AndTypePattern ret = new AndTypePattern(newLeft,newRight); ret.copyLocationFrom(this); return ret; } public TypePattern resolveBindingsFromRTTI(boolean allowBinding, boolean requireExactType) { if (requireExactType) return TypePattern.NO; left = left.resolveBindingsFromRTTI(allowBinding,requireExactType); right = right.resolveBindingsFromRTTI(allowBinding,requireExactType); return this; } public String toString() { StringBuffer buff = new StringBuffer(); if (annotationPattern != AnnotationTypePattern.ANY) { buff.append('('); buff.append(annotationPattern.toString()); buff.append(' '); } buff.append('('); buff.append(left.toString()); buff.append(" && "); buff.append(right.toString()); buff.append(')'); if (annotationPattern != AnnotationTypePattern.ANY) { buff.append(')'); } return buff.toString(); } public TypePattern getLeft() { return left; } public TypePattern getRight() { return right; } public boolean equals(Object obj) { if (! (obj instanceof AndTypePattern)) return false; AndTypePattern atp = (AndTypePattern) obj; return left.equals(atp.left) && right.equals(atp.right); } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ public int hashCode() { int ret = 17; ret = ret + 37 * left.hashCode(); ret = ret + 37 * right.hashCode(); return ret; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } public Object traverse(PatternNodeVisitor visitor, Object data) { Object ret = accept(visitor,data); left.traverse(visitor, ret); right.traverse(visitor, ret); return ret; } }
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26:40Z
weaver/src/org/aspectj/weaver/patterns/AnnotationPointcut.java
/* ******************************************************************* * Copyright (c) 2004 IBM Corporation. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Set; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.AnnotatedElement; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.Member; import org.aspectj.weaver.NameMangler; import org.aspectj.weaver.NewFieldTypeMunger; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.ast.Literal; import org.aspectj.weaver.ast.Test; import org.aspectj.weaver.ast.Var; import org.aspectj.weaver.bcel.BcelTypeMunger; /** * @annotation(@Foo) or @annotation(foo) * * Matches any join point where the subject of the join point has an * annotation matching the annotationTypePattern: * * Join Point Kind Subject * ================================ * method call the target method * method execution the method * constructor call the constructor * constructor execution the constructor * get the target field * set the target field * adviceexecution the advice * initialization the constructor * preinitialization the constructor * staticinitialization the type being initialized * handler the declared type of the handled exception */ public class AnnotationPointcut extends NameBindingPointcut { private ExactAnnotationTypePattern annotationTypePattern; private ShadowMunger munger = null; // only set after concretization public AnnotationPointcut(ExactAnnotationTypePattern type) { super(); this.annotationTypePattern = type; this.pointcutKind = Pointcut.ANNOTATION; } public AnnotationPointcut(ExactAnnotationTypePattern type, ShadowMunger munger) { this(type); this.munger = munger; } public ExactAnnotationTypePattern getAnnotationTypePattern() { return annotationTypePattern; } public Set couldMatchKinds() { return Shadow.ALL_SHADOW_KINDS; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#fastMatch(org.aspectj.weaver.patterns.FastMatchInfo) */ public FuzzyBoolean fastMatch(FastMatchInfo info) { if (info.getKind() == Shadow.StaticInitialization) { return annotationTypePattern.fastMatches(info.getType()); } else { return FuzzyBoolean.MAYBE; } } public FuzzyBoolean fastMatch(Class targetType) { // TODO AMC return FuzzyBoolean.MAYBE; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#match(org.aspectj.weaver.Shadow) */ protected FuzzyBoolean matchInternal(Shadow shadow) { AnnotatedElement toMatchAgainst = null; Member member = shadow.getSignature(); ResolvedMember rMember = member.resolve(shadow.getIWorld()); if (rMember == null) { if (member.getName().startsWith(NameMangler.PREFIX)) { return FuzzyBoolean.NO; } shadow.getIWorld().getLint().unresolvableMember.signal(member.toString(), getSourceLocation()); return FuzzyBoolean.NO; } Shadow.Kind kind = shadow.getKind(); if (kind == Shadow.StaticInitialization) { toMatchAgainst = rMember.getDeclaringType().resolve(shadow.getIWorld()); } else if ( (kind == Shadow.ExceptionHandler)) { toMatchAgainst = rMember.getParameterTypes()[0].resolve(shadow.getIWorld()); } else { toMatchAgainst = rMember; // FIXME asc I'd like to get rid of this bit of logic altogether, shame ITD fields don't have an effective sig attribute // FIXME asc perf cache the result of discovering the member that contains the real annotations if (rMember.isAnnotatedElsewhere()) { if (kind==Shadow.FieldGet || kind==Shadow.FieldSet) { List mungers = rMember.getDeclaringType().resolve(shadow.getIWorld()).getInterTypeMungers(); // FIXME asc should include supers with getInterTypeMungersIncludingSupers? for (Iterator iter = mungers.iterator(); iter.hasNext();) { BcelTypeMunger typeMunger = (BcelTypeMunger) iter.next(); if (typeMunger.getMunger() instanceof NewFieldTypeMunger) { ResolvedMember fakerm = typeMunger.getSignature(); if (fakerm.equals(member)) { ResolvedMember ajcMethod = AjcMemberMaker.interFieldInitializer(fakerm,typeMunger.getAspectType()); ResolvedMember rmm = findMethod(typeMunger.getAspectType(),ajcMethod); toMatchAgainst = rmm; } } } } } } annotationTypePattern.resolve(shadow.getIWorld()); return annotationTypePattern.matches(toMatchAgainst); } private ResolvedMember findMethod(ResolvedType aspectType, ResolvedMember ajcMethod) { ResolvedMember decMethods[] = aspectType.getDeclaredMethods(); for (int i = 0; i < decMethods.length; i++) { ResolvedMember member = decMethods[i]; if (member.equals(ajcMethod)) return member; } return null; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#resolveBindings(org.aspectj.weaver.patterns.IScope, org.aspectj.weaver.patterns.Bindings) */ protected void resolveBindings(IScope scope, Bindings bindings) { annotationTypePattern = (ExactAnnotationTypePattern) annotationTypePattern.resolveBindings(scope,bindings,true); // must be either a Var, or an annotation type pattern } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#resolveBindingsFromRTTI() */ protected void resolveBindingsFromRTTI() { // TODO Auto-generated method stub } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#concretize1(org.aspectj.weaver.ResolvedType, org.aspectj.weaver.IntMap) */ protected Pointcut concretize1(ResolvedType inAspect, ResolvedType declaringType, IntMap bindings) { ExactAnnotationTypePattern newType = (ExactAnnotationTypePattern) annotationTypePattern.remapAdviceFormals(bindings); Pointcut ret = new AnnotationPointcut(newType, bindings.getEnclosingAdvice()); ret.copyLocationFrom(this); return ret; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#findResidue(org.aspectj.weaver.Shadow, org.aspectj.weaver.patterns.ExposedState) */ protected Test findResidueInternal(Shadow shadow, ExposedState state) { if (annotationTypePattern instanceof BindingAnnotationTypePattern) { BindingAnnotationTypePattern btp = (BindingAnnotationTypePattern)annotationTypePattern; UnresolvedType annotationType = btp.getAnnotationType(); Var var = shadow.getKindedAnnotationVar(annotationType); // This should not happen, we shouldn't have gotten this far // if we weren't going to find the annotation if (var == null) throw new BCException("Impossible! annotation=["+annotationType+ "] shadow=["+shadow+" at "+shadow.getSourceLocation()+ "] pointcut is at ["+getSourceLocation()+"]");//return Literal.FALSE; // Check if we have already bound something to this formal if ((state.get(btp.getFormalIndex())!=null) &&(lastMatchedShadowId == shadow.shadowId)) { // ISourceLocation pcdSloc = getSourceLocation(); // ISourceLocation shadowSloc = shadow.getSourceLocation(); // Message errorMessage = new Message( // "Cannot use @pointcut to match at this location and bind a formal to type '"+var.getType()+ // "' - the formal is already bound to type '"+state.get(btp.getFormalIndex()).getType()+"'"+ // ". The secondary source location points to the problematic binding.", // shadowSloc,true,new ISourceLocation[]{pcdSloc}); // shadow.getIWorld().getMessageHandler().handleMessage(errorMessage); state.setErroneousVar(btp.getFormalIndex()); } state.set(btp.getFormalIndex(),var); } if (matchInternal(shadow).alwaysTrue()) return Literal.TRUE; else return Literal.FALSE; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.NameBindingPointcut#getBindingAnnotationTypePatterns() */ public List getBindingAnnotationTypePatterns() { if (annotationTypePattern instanceof BindingAnnotationTypePattern) { List l = new ArrayList(); l.add(annotationTypePattern); return l; } else return Collections.EMPTY_LIST; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.NameBindingPointcut#getBindingTypePatterns() */ public List getBindingTypePatterns() { return Collections.EMPTY_LIST; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.PatternNode#write(java.io.DataOutputStream) */ public void write(DataOutputStream s) throws IOException { s.writeByte(Pointcut.ANNOTATION); annotationTypePattern.write(s); writeLocation(s); } public static Pointcut read(VersionedDataInputStream s, ISourceContext context) throws IOException { AnnotationTypePattern type = AnnotationTypePattern.read(s, context); AnnotationPointcut ret = new AnnotationPointcut((ExactAnnotationTypePattern)type); ret.readLocation(context, s); return ret; } public boolean equals(Object other) { if (!(other instanceof AnnotationPointcut)) return false; AnnotationPointcut o = (AnnotationPointcut)other; return o.annotationTypePattern.equals(this.annotationTypePattern); } public int hashCode() { int result = 17; result = 37*result + annotationTypePattern.hashCode(); return result; } public String toString() { StringBuffer buf = new StringBuffer(); buf.append("@annotation("); String annPatt = annotationTypePattern.toString(); buf.append(annPatt.startsWith("@") ? annPatt.substring(1) : annPatt); buf.append(")"); return buf.toString(); } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } }
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26:40Z
weaver/src/org/aspectj/weaver/patterns/ArgsAnnotationPointcut.java
/* ******************************************************************* * Copyright (c) 2004 IBM Corporation. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Set; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.ast.Literal; import org.aspectj.weaver.ast.Test; import org.aspectj.weaver.ast.Var; /** * @author colyer * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class ArgsAnnotationPointcut extends NameBindingPointcut { private AnnotationPatternList arguments; /** * */ public ArgsAnnotationPointcut(AnnotationPatternList arguments) { super(); this.arguments = arguments; } public AnnotationPatternList getArguments() { return arguments; } public Set couldMatchKinds() { return Shadow.ALL_SHADOW_KINDS; // empty args() matches jps with no args } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#fastMatch(org.aspectj.weaver.patterns.FastMatchInfo) */ public FuzzyBoolean fastMatch(FastMatchInfo info) { return FuzzyBoolean.MAYBE; } public FuzzyBoolean fastMatch(Class targetType) { return FuzzyBoolean.MAYBE; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#match(org.aspectj.weaver.Shadow) */ protected FuzzyBoolean matchInternal(Shadow shadow) { arguments.resolve(shadow.getIWorld()); FuzzyBoolean ret = arguments.matches(shadow.getIWorld().resolve(shadow.getArgTypes())); return ret; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#resolveBindings(org.aspectj.weaver.patterns.IScope, org.aspectj.weaver.patterns.Bindings) */ protected void resolveBindings(IScope scope, Bindings bindings) { arguments.resolveBindings(scope, bindings, true); if (arguments.ellipsisCount > 1) { scope.message(IMessage.ERROR, this, "uses more than one .. in args (compiler limitation)"); } } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#resolveBindingsFromRTTI() */ protected void resolveBindingsFromRTTI() { // TODO Auto-generated method stub } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#concretize1(org.aspectj.weaver.ResolvedType, org.aspectj.weaver.IntMap) */ protected Pointcut concretize1(ResolvedType inAspect, ResolvedType declaringType, IntMap bindings) { if (isDeclare(bindings.getEnclosingAdvice())) { // Enforce rule about which designators are supported in declare inAspect.getWorld().showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ARGS_IN_DECLARE), bindings.getEnclosingAdvice().getSourceLocation(), null); return Pointcut.makeMatchesNothing(Pointcut.CONCRETE); } AnnotationPatternList list = arguments.resolveReferences(bindings); Pointcut ret = new ArgsAnnotationPointcut(list); ret.copyLocationFrom(this); return ret; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#findResidue(org.aspectj.weaver.Shadow, org.aspectj.weaver.patterns.ExposedState) */ protected Test findResidueInternal(Shadow shadow, ExposedState state) { int len = shadow.getArgCount(); // do some quick length tests first int numArgsMatchedByEllipsis = (len + arguments.ellipsisCount) - arguments.size(); if (numArgsMatchedByEllipsis < 0) return Literal.FALSE; // should never happen if ((numArgsMatchedByEllipsis > 0) && (arguments.ellipsisCount == 0)) { return Literal.FALSE; // should never happen } // now work through the args and the patterns, skipping at ellipsis Test ret = Literal.TRUE; int argsIndex = 0; for (int i = 0; i < arguments.size(); i++) { if (arguments.get(i) == AnnotationTypePattern.ELLIPSIS) { // match ellipsisMatchCount args argsIndex += numArgsMatchedByEllipsis; } else if (arguments.get(i) == AnnotationTypePattern.ANY) { argsIndex++; } else { // match the argument type at argsIndex with the ExactAnnotationTypePattern // we know it is exact because nothing else is allowed in args ExactAnnotationTypePattern ap = (ExactAnnotationTypePattern)arguments.get(i); UnresolvedType argType = shadow.getArgType(argsIndex); ResolvedType rArgType = argType.resolve(shadow.getIWorld()); if (rArgType == ResolvedType.MISSING) { IMessage msg = new Message( WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_ARG_TYPE,argType.getName()), "",IMessage.ERROR,shadow.getSourceLocation(),null,new ISourceLocation[]{getSourceLocation()}); } ResolvedType rAnnType = ap.getAnnotationType().resolve(shadow.getIWorld()); if (ap instanceof BindingAnnotationTypePattern) { BindingAnnotationTypePattern btp = (BindingAnnotationTypePattern)ap; Var annvar = shadow.getArgAnnotationVar(argsIndex,rAnnType); state.set(btp.getFormalIndex(),annvar); } if (!ap.matches(rArgType).alwaysTrue()) { // we need a test... ret = Test.makeAnd(ret,Test.makeHasAnnotation(shadow.getArgVar(argsIndex),rAnnType)); } argsIndex++; } } return ret; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.NameBindingPointcut#getBindingAnnotationTypePatterns() */ public List getBindingAnnotationTypePatterns() { List l = new ArrayList(); AnnotationTypePattern[] pats = arguments.getAnnotationPatterns(); for (int i = 0; i < pats.length; i++) { if (pats[i] instanceof BindingAnnotationTypePattern) { l.add(pats[i]); } } return l; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.NameBindingPointcut#getBindingTypePatterns() */ public List getBindingTypePatterns() { return Collections.EMPTY_LIST; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.PatternNode#write(java.io.DataOutputStream) */ public void write(DataOutputStream s) throws IOException { s.writeByte(Pointcut.ATARGS); arguments.write(s); writeLocation(s); } public static Pointcut read(VersionedDataInputStream s, ISourceContext context) throws IOException { AnnotationPatternList annotationPatternList = AnnotationPatternList.read(s,context); ArgsAnnotationPointcut ret = new ArgsAnnotationPointcut(annotationPatternList); ret.readLocation(context, s); return ret; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object obj) { if (!(obj instanceof ArgsAnnotationPointcut)) return false; ArgsAnnotationPointcut other = (ArgsAnnotationPointcut) obj; return other.arguments.equals(arguments); } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ public int hashCode() { return 17 + 37*arguments.hashCode(); } /* (non-Javadoc) * @see java.lang.Object#toString() */ public String toString() { StringBuffer buf = new StringBuffer("@args"); buf.append(arguments.toString()); return buf.toString(); } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } }