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