Fix bugs for interfaces and a bug in the Class library
[IRC.git] / Robust / src / IR / TypeUtil.java
1 package IR;
2 import java.util.*;
3
4 import IR.Flat.FlatNode;
5 import IR.Tree.*;
6 import java.io.File;
7 import Main.Main;
8
9 public class TypeUtil {
10   public static final String StringClass="String";
11   public static final String ObjectClass="Object";
12   public static final String StartupClass="StartupObject";
13   public static final String TagClass="TagDescriptor";
14   public static final String ThreadClass="Thread";
15   public static final String TaskClass="Task";
16   State state;
17   Hashtable supertable;
18   Hashtable subclasstable;
19   BuildIR bir;
20   
21   // for interfaces
22   Hashtable superIFtbl;
23
24   public TypeUtil(State state, BuildIR bir) {
25     this.state=state;
26     this.bir=bir;
27     createTables();
28   }
29
30   public void addNewClass(String cl, Set todo) {
31     for(int i=0;i<state.classpath.size();i++) {
32       String path=(String)state.classpath.get(i);
33       File f=new File(path, cl+".java");
34       if (f.exists()) {
35         try {
36           ParseNode pn=Main.readSourceFile(state, f.getCanonicalPath());
37           bir.buildtree(pn, todo);
38           return;
39         } catch (Exception e) {
40           throw new Error(e);
41         }
42       }
43     }
44     throw new Error("Couldn't find class "+cl);
45   }
46
47
48
49   public ClassDescriptor getClass(String classname) {
50     ClassDescriptor cd=(ClassDescriptor)state.getClassSymbolTable().get(classname);
51     return cd;
52   }
53
54   public ClassDescriptor getClass(String classname, HashSet todo) {
55     ClassDescriptor cd=(ClassDescriptor)state.getClassSymbolTable().get(classname);
56     if (cd==null) {
57       //have to find class
58       addNewClass(classname, todo);
59       cd=(ClassDescriptor)state.getClassSymbolTable().get(classname);
60
61       System.out.println("Build class:"+cd);
62       todo.add(cd);
63     }
64     if (!supertable.containsKey(cd)) {
65       String superc=cd.getSuper();
66       if (superc!=null) {
67         ClassDescriptor cd_super=getClass(superc, todo);
68         supertable.put(cd,cd_super);
69       }
70     }
71     if (!this.superIFtbl.containsKey(cd)) {
72       // add inherited interfaces
73       superIFtbl.put(cd,new HashSet());
74       HashSet hs=(HashSet)superIFtbl.get(cd);
75       Vector<String> superifv = cd.getSuperInterface();
76       for(int i = 0; i < superifv.size(); i++) {
77         String superif = superifv.elementAt(i);
78         ClassDescriptor if_super = getClass(superif, todo);
79         hs.add(if_super);
80       }
81     }
82     return cd;
83   }
84
85   private void createTables() {
86     supertable=new Hashtable();
87     superIFtbl = new Hashtable();
88   }
89
90   public ClassDescriptor getMainClass() {
91     return getClass(state.main);
92   }
93
94   public MethodDescriptor getRun() {
95     ClassDescriptor cd=getClass(TypeUtil.ThreadClass);
96     for(Iterator methodit=cd.getMethodTable().getSet("run").iterator(); methodit.hasNext();) {
97       MethodDescriptor md=(MethodDescriptor) methodit.next();
98       if (md.numParameters()!=0||md.getModifiers().isStatic())
99         continue;
100       return md;
101     }
102     throw new Error("Can't find Thread.run");
103   }
104   
105   public MethodDescriptor getExecute() {
106     ClassDescriptor cd = getClass(TypeUtil.TaskClass);
107
108     if(cd == null && state.DSMTASK)
109       throw new Error("Task.java is not included");
110
111     for(Iterator methodit = cd.getMethodTable().getSet("execute").iterator(); methodit.hasNext();) {
112       MethodDescriptor md = (MethodDescriptor) methodit.next();
113       if (md.numParameters()!=0 || md.getModifiers().isStatic())
114         continue;
115       return md;
116     }
117     throw new Error("Can't find Task.execute");
118   }
119
120
121   public MethodDescriptor getMain() {
122     ClassDescriptor cd=getMainClass();
123     Set mainset=cd.getMethodTable().getSet("main");
124     for(Iterator mainit=mainset.iterator(); mainit.hasNext();) {
125       MethodDescriptor md=(MethodDescriptor)mainit.next();
126       if (md.numParameters()!=1)
127         continue;
128       Descriptor pd=md.getParameter(0);
129       TypeDescriptor tpd=(pd instanceof TagVarDescriptor) ? ((TagVarDescriptor)pd).getType() : ((VarDescriptor)pd)
130                           .getType();
131       if (tpd.getArrayCount()!=1)
132         continue;
133       if (!tpd.getSymbol().equals("String"))
134         continue;
135
136       if (!md.getModifiers().isStatic())
137         throw new Error("Error: Non static main");
138       return md;
139     }
140     throw new Error(cd+" has no main");
141   }
142
143   /** Check to see if md1 is more specific than md2...  Informally
144       if md2 could always be called given the arguments passed into
145       md1 */
146
147   public boolean isMoreSpecific(MethodDescriptor md1, MethodDescriptor md2) {
148     /* Checks if md1 is more specific than md2 */
149     if (md1.numParameters()!=md2.numParameters())
150       throw new Error();
151     for(int i=0; i<md1.numParameters(); i++) {
152       if (!this.isSuperorType(md2.getParamType(i), md1.getParamType(i))) {
153         if(((!md1.getParamType(i).isArray() && 
154             (md1.getParamType(i).isInt() || md1.getParamType(i).isLong() || md1.getParamType(i).isDouble() || md1.getParamType(i).isFloat()))
155             && md2.getParamType(i).isClass() && md2.getParamType(i).getClassDesc().getSymbol().equals("Object"))) {
156           // primitive parameters vs Object
157         } else {
158           return false;
159         }
160       }
161     }
162     if (md1.getReturnType()==null||md2.getReturnType()==null) {
163         if (md1.getReturnType()!=md2.getReturnType())
164             return false;
165     } else
166         if (!this.isSuperorType(md2.getReturnType(), md1.getReturnType()))
167             return false;
168
169     if (!this.isSuperorType(md2.getClassDesc(), md1.getClassDesc()))
170       return false;
171
172     return true;
173   }
174
175   public MethodDescriptor getMethod(ClassDescriptor cd, String name, TypeDescriptor[] types) {
176     Set methoddescriptorset=cd.getMethodTable().getSet(name);
177     MethodDescriptor bestmd=null;
178 NextMethod:
179     for(Iterator methodit=methoddescriptorset.iterator(); methodit.hasNext();) {
180       MethodDescriptor currmd=(MethodDescriptor)methodit.next();
181       /* Need correct number of parameters */
182       if (types.length!=currmd.numParameters())
183         continue;
184       for(int i=0; i<types.length; i++) {
185         if (!this.isSuperorType(currmd.getParamType(i),types[i]))
186           continue NextMethod;
187       }
188       /* Method okay so far */
189       if (bestmd==null)
190         bestmd=currmd;
191       else {
192         if (isMoreSpecific(currmd,bestmd)) {
193           bestmd=currmd;
194         } else if (!isMoreSpecific(bestmd, currmd))
195           throw new Error("No method is most specific");
196
197         /* Is this more specific than bestmd */
198       }
199     }
200     if (bestmd==null)
201       throw new Error("Could find: "+name + " in "+cd);
202
203     return bestmd;
204   }
205
206   public void createFullTable() {
207     subclasstable=new Hashtable();
208     HashSet tovisit=new HashSet();
209     HashSet visited=new HashSet();
210
211     Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
212     while(classit.hasNext()) {
213       tovisit.clear();
214       visited.clear();
215       ClassDescriptor cd=(ClassDescriptor)classit.next();
216       ClassDescriptor tmp=cd.getSuperDesc();
217       
218       // check cd's interface ancestors
219       {
220         Iterator it_sifs = cd.getSuperInterfaces();
221         while(it_sifs.hasNext()) {
222           ClassDescriptor cdt = (ClassDescriptor)it_sifs.next();
223           if(!tovisit.contains(cdt)){
224             tovisit.add(cdt);
225           }
226         }
227       }
228
229       while(tmp!=null) {
230         if (!subclasstable.containsKey(tmp))
231           subclasstable.put(tmp,new HashSet());
232         HashSet hs=(HashSet)subclasstable.get(tmp);
233         hs.add(cd);
234         // check tmp's interface ancestors
235         Iterator it_sifs = tmp.getSuperInterfaces();
236         while(it_sifs.hasNext()) {
237           ClassDescriptor cdt = (ClassDescriptor)it_sifs.next();
238           if(!tovisit.contains(cdt)){
239             tovisit.add(cdt);
240           }
241         }
242         
243         tmp=tmp.getSuperDesc();
244       }
245       
246       while(!tovisit.isEmpty()) {
247         ClassDescriptor sif = (ClassDescriptor)tovisit.iterator().next();
248         tovisit.remove(sif);
249         
250         if(!visited.contains(sif)) {
251           if(!this.subclasstable.containsKey(sif)) {
252             this.subclasstable.put(sif, new HashSet());
253           }
254           HashSet hs = (HashSet)this.subclasstable.get(sif);
255           hs.add(cd);
256           
257           Iterator it_sifs = sif.getSuperInterfaces();
258           while(it_sifs.hasNext()) {
259             ClassDescriptor siftmp = (ClassDescriptor)it_sifs.next();
260             if(!tovisit.contains(siftmp)){
261               tovisit.add(siftmp);
262             }
263           }
264           visited.add(sif);
265         }
266       }
267     }
268   }
269
270   public Set getSubClasses(ClassDescriptor cd) {
271     return (Set)subclasstable.get(cd);
272   }
273
274   public ClassDescriptor getSuper(ClassDescriptor cd) {
275     return (ClassDescriptor)supertable.get(cd);
276   }
277   
278   public Set getSuperIFs(ClassDescriptor cd) {
279     return (Set)this.superIFtbl.get(cd);
280   }
281
282   public boolean isCastable(TypeDescriptor original, TypeDescriptor casttype) {
283     if (original.isChar()&&
284         (casttype.isByte()||
285          casttype.isShort()))
286       return true;
287
288     if (casttype.isChar()&&
289         (original.isByte()||
290          original.isShort()||
291          original.isInt()||
292          original.isLong()||
293          original.isFloat()||
294          original.isDouble()))
295       return true;
296
297     return false;
298   }
299
300   public boolean isSuperorType(TypeDescriptor possiblesuper, TypeDescriptor cd2) {
301     if(possiblesuper.isClass() && possiblesuper.class_desc.isEnum() && cd2.isInt()) {
302       return true;
303     }
304
305     if (possiblesuper.isOffset() || cd2.isOffset()) return true;
306     //Matching type are always okay
307     if (possiblesuper.equals(cd2))
308       return true;
309
310     if ((possiblesuper.isTag() && !cd2.isTag())||
311         (!possiblesuper.isTag() && cd2.isTag()))
312       return false;
313
314     //Handle arrays
315     if (cd2.isArray()||possiblesuper.isArray()) {
316       // Object is super class of all arrays
317       if (possiblesuper.getSymbol().equals(ObjectClass)&&!possiblesuper.isArray())
318         return true;
319
320       // If we have the same dimensionality of arrays & both are classes, we can default to the normal test
321       if (cd2.isClass()&&possiblesuper.isClass()
322           &&(possiblesuper.getArrayCount()==cd2.getArrayCount())&&
323           isSuperorType(possiblesuper.getClassDesc(), cd2.getClassDesc()))
324         return true;
325
326       // Object is superclass of all array classes
327       if (possiblesuper.getSymbol().equals(ObjectClass)&&cd2.isClass()
328           &&(possiblesuper.getArrayCount()<cd2.getArrayCount()))
329         return true;
330
331       //Allow arraytype=null statements
332       if (possiblesuper.isArray()&&cd2.isNull())
333         return true;
334
335       return false;
336     }
337
338     if (possiblesuper.isClass()&&
339         cd2.isClass())
340       return isSuperorType(possiblesuper.getClassDesc(), cd2.getClassDesc());
341     else if (possiblesuper.isClass()&&
342              cd2.isNull())
343       return true;
344     else if (possiblesuper.isNull())
345       throw new Error();       //not sure when this case would occur
346     else if (possiblesuper.isPrimitive()&&
347              cd2.isPrimitive()) {
348       ///Primitive widenings from 5.1.2
349       if (cd2.isByte()&&(possiblesuper.isByte()||possiblesuper.isShort()||
350                          possiblesuper.isInt()||possiblesuper.isLong()||
351                          possiblesuper.isFloat()||possiblesuper.isDouble()))
352         return true;
353       if (cd2.isShort()&&(possiblesuper.isShort()||
354                           possiblesuper.isInt()||possiblesuper.isLong()||
355                           possiblesuper.isFloat()||possiblesuper.isDouble()))
356         return true;
357       if (cd2.isChar()&&(possiblesuper.isChar()||
358                          possiblesuper.isInt()||possiblesuper.isLong()||
359                          possiblesuper.isFloat()||possiblesuper.isDouble()))
360         return true;
361       if (cd2.isInt()&&(possiblesuper.isInt()||possiblesuper.isLong()||
362                         possiblesuper.isFloat()||possiblesuper.isDouble()))
363         return true;
364       if (cd2.isLong()&&(possiblesuper.isLong()||
365                          possiblesuper.isFloat()||possiblesuper.isDouble()))
366         return true;
367       if (cd2.isFloat()&&(possiblesuper.isFloat()||possiblesuper.isDouble()))
368         return true;
369       if (cd2.isDouble()&&possiblesuper.isDouble())
370
371         return true;
372       if (cd2.isBoolean()&&possiblesuper.isBoolean())
373         return true;
374
375       return false;
376     } else if (possiblesuper.isPrimitive()&&(!possiblesuper.isArray())&&
377                cd2.isPtr())
378       return false;
379     else if (cd2.isPrimitive()&&(!cd2.isArray())&&
380              possiblesuper.isPtr())
381       return false;
382     else
383       throw new Error("Case not handled:"+possiblesuper+" "+cd2);
384   }
385
386   public TypeDescriptor mostSpecific(TypeDescriptor td1, TypeDescriptor td2) {
387     if( isSuperorType( td1, td2 ) ) {
388       return td2;
389     }
390     if( isSuperorType( td2, td1 ) ) {
391       return td1;
392     }
393     throw new Error( td1+" and "+td2+" have no superclass relationship" );
394   }
395
396   public TypeDescriptor mostSpecific(TypeDescriptor td1, TypeDescriptor td2, TypeDescriptor td3) {
397     return mostSpecific( td1, mostSpecific( td2, td3 ) );
398   }
399
400   public boolean isSuperorType(ClassDescriptor possiblesuper, ClassDescriptor cd2) {
401     if (possiblesuper==cd2)
402       return true;
403     else
404       return isSuper(possiblesuper, cd2);
405   }
406
407   private boolean isSuper(ClassDescriptor possiblesuper, ClassDescriptor cd2) {
408     HashSet tovisit=new HashSet();
409     HashSet visited=new HashSet();
410     
411     {
412       // check cd2's interface ancestors
413       Iterator it_sifs = getSuperIFs(cd2).iterator();
414       while(it_sifs.hasNext()) {
415         ClassDescriptor cd = (ClassDescriptor)it_sifs.next();
416         if(cd == possiblesuper) {
417           return true;
418         } else if(!tovisit.contains(cd)){
419           tovisit.add(cd);
420         }
421       }
422     }
423
424     while(cd2!=null) {
425       cd2=getSuper(cd2);
426       if (cd2==possiblesuper)
427         return true;
428       
429       // check cd2's interface ancestors
430       if(cd2 != null) {
431         Iterator it_sifs = getSuperIFs(cd2).iterator();
432         while(it_sifs.hasNext()) {
433           ClassDescriptor cd = (ClassDescriptor)it_sifs.next();
434           if(cd == possiblesuper) {
435             return true;
436           } else if(!tovisit.contains(cd)){
437             tovisit.add(cd);
438           }
439         }
440       }
441     }
442     
443     while(!tovisit.isEmpty()) {
444       ClassDescriptor cd = (ClassDescriptor)tovisit.iterator().next();
445       tovisit.remove(cd);
446       
447       if(!visited.contains(cd)) {
448         Iterator it_sifs = getSuperIFs(cd).iterator();
449         while(it_sifs.hasNext()) {
450           ClassDescriptor cdt = (ClassDescriptor)it_sifs.next();
451           if(cdt == possiblesuper) {
452             return true;
453           } else if(!tovisit.contains(cdt)){
454             tovisit.add(cdt);
455           }
456         }
457         visited.add(cd);
458       }
459     }
460     return false;
461   }
462 }