1 cananian 1.1.2.1 // DefaultClassDepthMap.java, created Sat Jan 16 21:35:05 1999 by cananian
 2 cananian 1.1.2.2 // Copyright (C) 1998 C. Scott Ananian <cananian@alumni.princeton.edu>
 3 cananian 1.1.2.2 // Licensed under the terms of the GNU GPL; see COPYING for details.
 4 cananian 1.1.2.1 package harpoon.Backend.Maps;
 5 cananian 1.1.2.1 
 6 cananian 1.1.2.1 import harpoon.ClassFile.HClass;
 7 cananian 1.1.2.3 import harpoon.Analysis.ClassHierarchy;
 8 cananian 1.1.2.3 
 9 cananian 1.1.2.3 import java.util.HashMap;
10 cananian 1.1.2.3 import java.util.Iterator;
11 cananian 1.1.2.3 import java.util.Map;
12 cananian 1.1.2.1 
13 cananian 1.1.2.1 /**
14 cananian 1.1.2.1  * A <code>DefaultClassDepthMap</code> computes class depth simply and
15 cananian 1.1.2.3  * efficiently.  It uses a <code>ClassHierarchy</code> object to enable it
16 cananian 1.1.2.3  * to implement the <code>maxDepth()</code> method.  It also caches
17 cananian 1.1.2.3  * the depths it computes to avoid having to traverse the entire class
18 cananian 1.1.2.3  * inheritance tree repeatedly.
19 cananian 1.1.2.1  * 
20 cananian 1.1.2.1  * @author  C. Scott Ananian <cananian@alumni.princeton.edu>
21 cananian 1.2      * @version $Id: DefaultClassDepthMap.java,v 1.2 2002/02/25 21:01:55 cananian Exp $
22 cananian 1.1.2.1  */
23 cananian 1.1.2.3 public class DefaultClassDepthMap extends ClassDepthMap {
24 cananian 1.1.2.4     private final int maxDepth;
25 cananian 1.1.2.3     /** Creates a <code>DefaultClassDepthMap</code> using the given
26 cananian 1.1.2.3      *  <code>ClassHierarchy</code> to compute the maximum class depth. */
27 cananian 1.1.2.3     public DefaultClassDepthMap(ClassHierarchy ch) {
28 cananian 1.1.2.3         int max = 0;
29 cananian 1.1.2.3         for (Iterator it = ch.classes().iterator(); it.hasNext(); )
30 cananian 1.1.2.3             max = Math.max(max, classDepth((HClass)it.next()));
31 cananian 1.1.2.3         this.maxDepth = max;
32 cananian 1.1.2.1     }
33 cananian 1.1.2.1     public int classDepth(HClass hc) {
34 cananian 1.1.2.3         if (cache.containsKey(hc)) return ((Integer)cache.get(hc)).intValue();
35 cananian 1.1.2.3         int depth;
36 cananian 1.1.2.3         if (hc.isArray()) // array hierarchy is based on component type
37 cananian 1.1.2.3             depth = 1 + classDepth(hc.getComponentType());
38 cananian 1.1.2.3         else {
39 cananian 1.1.2.3             HClass sc = hc.getSuperclass();
40 cananian 1.1.2.3             depth = (sc==null) ? 0 : 1 + classDepth(sc);
41 cananian 1.1.2.3         }
42 cananian 1.1.2.3         cache.put(hc, new Integer(depth));
43 cananian 1.1.2.3         return depth;
44 cananian 1.1.2.1     }
45 cananian 1.1.2.3     private final Map cache = new HashMap();
46 cananian 1.1.2.3 
47 cananian 1.1.2.3     public int maxDepth() { return maxDepth; }
48 cananian 1.2     }