file changes
[IRC.git] / Robust / src / IR / Tree / SemanticCheck.java
1 package IR.Tree;
2
3 import java.util.*;
4
5 import IR.*;
6
7 public class SemanticCheck {
8   State state;
9   TypeUtil typeutil;
10   Stack loopstack;
11   HashSet toanalyze;
12   HashMap<ClassDescriptor, Integer> completed;
13
14   public static final int NOCHECK=0;
15   public static final int REFERENCE=1;
16   public static final int INIT=2;
17
18   boolean checkAll;
19
20   public boolean hasLayout(ClassDescriptor cd) {
21     return completed.get(cd)!=null&&completed.get(cd)==INIT;
22   }
23
24   public SemanticCheck(State state, TypeUtil tu) {
25     this(state, tu, true);
26   }
27
28   public SemanticCheck(State state, TypeUtil tu, boolean checkAll) {
29     this.state=state;
30     this.typeutil=tu;
31     this.loopstack=new Stack();
32     this.toanalyze=new HashSet();
33     this.completed=new HashMap<ClassDescriptor, Integer>();
34     this.checkAll=checkAll;
35   }
36
37   public ClassDescriptor getClass(ClassDescriptor context, String classname) {
38     return getClass(context, classname, INIT);
39   }
40   public ClassDescriptor getClass(ClassDescriptor context, String classnameIn, int fullcheck) {
41     String classname = classnameIn;
42     if (context!=null) {
43       classname = context.getCannonicalImportMapName(classnameIn);
44     }
45     ClassDescriptor cd=typeutil.getClass(classname, toanalyze);
46     checkClass(cd, fullcheck);
47
48     return cd;
49   }
50
51   public void checkClass(ClassDescriptor cd) {
52     checkClass(cd, INIT);
53   }
54
55   public void checkClass(ClassDescriptor cd, int fullcheck) {
56     if (!completed.containsKey(cd)||completed.get(cd)<fullcheck) {
57       int oldstatus=completed.containsKey(cd)?completed.get(cd):0;
58       completed.put(cd, fullcheck);
59
60       if (fullcheck>=REFERENCE&&oldstatus<INIT) {
61         //Set superclass link up
62         if (cd.getSuper()!=null) {
63           cd.setSuper(getClass(cd, cd.getSuper(), fullcheck));
64           if(cd.getSuperDesc().isInterface()) {
65             throw new Error("Error! Class " + cd.getSymbol() + " extends interface " + cd.getSuper());
66           }
67           // Link together Field, Method, and Flag tables so classes
68           // inherit these from their superclasses
69           if (oldstatus<REFERENCE) {
70             cd.getFieldTable().setParent(cd.getSuperDesc().getFieldTable());
71             cd.getMethodTable().setParent(cd.getSuperDesc().getMethodTable());
72             cd.getFlagTable().setParent(cd.getSuperDesc().getFlagTable());
73           }
74         }
75         // Link together Field, Method tables do classes inherit these from
76         // their ancestor interfaces
77         Vector<String> sifv = cd.getSuperInterface();
78         for(int i = 0; i < sifv.size(); i++) {
79           ClassDescriptor superif = getClass(cd, sifv.elementAt(i), fullcheck);
80           if(!superif.isInterface()) {
81             throw new Error("Error! Class " + cd.getSymbol() + " implements non-interface " + superif.getSymbol());
82           }
83           if (oldstatus<REFERENCE) {
84             cd.addSuperInterfaces(superif);
85             cd.getFieldTable().addParentIF(superif.getFieldTable());
86             cd.getMethodTable().addParentIF(superif.getMethodTable());
87           }
88         }
89       }
90       if (oldstatus<INIT&&fullcheck>=INIT) {
91         /* Check to see that fields are well typed */
92         for(Iterator field_it=cd.getFields(); field_it.hasNext(); ) {
93           FieldDescriptor fd=(FieldDescriptor)field_it.next();
94           checkField(cd,fd);
95         }
96         for(Iterator method_it=cd.getMethods(); method_it.hasNext(); ) {
97           MethodDescriptor md=(MethodDescriptor)method_it.next();
98           checkMethod(cd,md);
99         }
100       }
101     }
102   }
103
104   public void semanticCheck() {
105     SymbolTable classtable = state.getClassSymbolTable();
106     toanalyze.addAll(classtable.getValueSet());
107     toanalyze.addAll(state.getTaskSymbolTable().getValueSet());
108
109     // Do methods next
110     while (!toanalyze.isEmpty()) {
111       Object obj = toanalyze.iterator().next();
112       if (obj instanceof TaskDescriptor) {
113         toanalyze.remove(obj);
114         TaskDescriptor td = (TaskDescriptor) obj;
115         try {
116           checkTask(td);
117         } catch (Error e) {
118           System.out.println("Error in " + td);
119           throw e;
120         }
121       } else {
122         ClassDescriptor cd = (ClassDescriptor) obj;
123         toanalyze.remove(cd);
124
125         // need to initialize typeutil object here...only place we can
126         // get class descriptors without first calling getclass
127         getClass(cd, cd.getSymbol());
128         for (Iterator method_it = cd.getMethods(); method_it.hasNext(); ) {
129           MethodDescriptor md = (MethodDescriptor) method_it.next();
130           try {
131             checkMethodBody(cd, md);
132           } catch (Error e) {
133             System.out.println("Error in " + md);
134             throw e;
135           }
136         }
137       }
138     }
139   }
140
141   private void checkTypeDescriptor(ClassDescriptor cd, TypeDescriptor td) {
142     if (td.isPrimitive())
143       return;       /* Done */
144     else if (td.isClass()) {
145       String name=td.toString();
146       ClassDescriptor field_cd=checkAll?getClass(cd, name):getClass(cd, name, REFERENCE);
147
148       if (field_cd==null)
149         throw new Error("Undefined class "+name);
150       td.setClassDescriptor(field_cd);
151       return;
152     } else if (td.isTag())
153       return;
154     else
155       throw new Error();
156   }
157
158   public void checkField(ClassDescriptor cd, FieldDescriptor fd) {
159     checkTypeDescriptor(cd, fd.getType());
160   }
161
162   public void checkConstraintCheck(TaskDescriptor td, SymbolTable nametable, Vector ccs) {
163     if (ccs==null)
164       return;       /* No constraint checks to check */
165     for(int i=0; i<ccs.size(); i++) {
166       ConstraintCheck cc=(ConstraintCheck) ccs.get(i);
167
168       for(int j=0; j<cc.numArgs(); j++) {
169         ExpressionNode en=cc.getArg(j);
170         checkExpressionNode(td,nametable,en,null);
171       }
172     }
173   }
174
175   public void checkFlagEffects(TaskDescriptor td, Vector vfe, SymbolTable nametable) {
176     if (vfe==null)
177       return;       /* No flag effects to check */
178     for(int i=0; i<vfe.size(); i++) {
179       FlagEffects fe=(FlagEffects) vfe.get(i);
180       String varname=fe.getName();
181       //Make sure the variable is declared as a parameter to the task
182       VarDescriptor vd=(VarDescriptor)td.getParameterTable().get(varname);
183       if (vd==null)
184         throw new Error("Parameter "+varname+" in Flag Effects not declared in "+td);
185       fe.setVar(vd);
186
187       //Make sure it correspods to a class
188       TypeDescriptor type_d=vd.getType();
189       if (!type_d.isClass())
190         throw new Error("Cannot have non-object argument for flag_effect");
191
192       ClassDescriptor cd=type_d.getClassDesc();
193       for(int j=0; j<fe.numEffects(); j++) {
194         FlagEffect flag=fe.getEffect(j);
195         String name=flag.getName();
196         FlagDescriptor flag_d=(FlagDescriptor)cd.getFlagTable().get(name);
197         //Make sure the flag is declared
198         if (flag_d==null)
199           throw new Error("Flag descriptor "+name+" undefined in class: "+cd.getSymbol());
200         if (flag_d.getExternal())
201           throw new Error("Attempting to modify external flag: "+name);
202         flag.setFlag(flag_d);
203       }
204       for(int j=0; j<fe.numTagEffects(); j++) {
205         TagEffect tag=fe.getTagEffect(j);
206         String name=tag.getName();
207
208         Descriptor d=(Descriptor)nametable.get(name);
209         if (d==null)
210           throw new Error("Tag descriptor "+name+" undeclared");
211         else if (!(d instanceof TagVarDescriptor))
212           throw new Error(name+" is not a tag descriptor");
213         tag.setTag((TagVarDescriptor)d);
214       }
215     }
216   }
217
218   public void checkTask(TaskDescriptor td) {
219     for(int i=0; i<td.numParameters(); i++) {
220       /* Check that parameter is well typed */
221       TypeDescriptor param_type=td.getParamType(i);
222       checkTypeDescriptor(null, param_type);
223
224       /* Check the parameter's flag expression is well formed */
225       FlagExpressionNode fen=td.getFlag(td.getParameter(i));
226       if (!param_type.isClass())
227         throw new Error("Cannot have non-object argument to a task");
228       ClassDescriptor cd=param_type.getClassDesc();
229       if (fen!=null)
230         checkFlagExpressionNode(cd, fen);
231     }
232
233     checkFlagEffects(td, td.getFlagEffects(),td.getParameterTable());
234     /* Check that the task code is valid */
235     BlockNode bn=state.getMethodBody(td);
236     checkBlockNode(td, td.getParameterTable(),bn);
237   }
238
239   public void checkFlagExpressionNode(ClassDescriptor cd, FlagExpressionNode fen) {
240     switch(fen.kind()) {
241     case Kind.FlagOpNode:
242     {
243       FlagOpNode fon=(FlagOpNode)fen;
244       checkFlagExpressionNode(cd, fon.getLeft());
245       if (fon.getRight()!=null)
246         checkFlagExpressionNode(cd, fon.getRight());
247       break;
248     }
249
250     case Kind.FlagNode:
251     {
252       FlagNode fn=(FlagNode)fen;
253       String name=fn.getFlagName();
254       FlagDescriptor fd=(FlagDescriptor)cd.getFlagTable().get(name);
255       if (fd==null)
256         throw new Error("Undeclared flag: "+name);
257       fn.setFlag(fd);
258       break;
259     }
260
261     default:
262       throw new Error("Unrecognized FlagExpressionNode");
263     }
264   }
265
266   public void checkMethod(ClassDescriptor cd, MethodDescriptor md) {
267     /* Check for abstract methods */
268     if(md.isAbstract()) {
269       if(!cd.isAbstract() && !cd.isInterface()) {
270         throw new Error("Error! The non-abstract Class " + cd.getSymbol() + " contains an abstract method " + md.getSymbol());
271       }
272     }
273
274     /* Check return type */
275     if (!md.isConstructor() && !md.isStaticBlock())
276       if (!md.getReturnType().isVoid()) {
277         checkTypeDescriptor(cd, md.getReturnType());
278       }
279     for(int i=0; i<md.numParameters(); i++) {
280       TypeDescriptor param_type=md.getParamType(i);
281       checkTypeDescriptor(cd, param_type);
282     }
283     /* Link the naming environments */
284     if (!md.isStatic())     /* Fields aren't accessible directly in a static method, so don't link in this table */
285       md.getParameterTable().setParent(cd.getFieldTable());
286     md.setClassDesc(cd);
287     if (!md.isStatic()) {
288       VarDescriptor thisvd=new VarDescriptor(new TypeDescriptor(cd),"this");
289       md.setThis(thisvd);
290     }
291     if(md.isDefaultConstructor() && (cd.getSuperDesc() != null)) {
292       // add the construction of it super class, can only be super()
293       NameDescriptor nd=new NameDescriptor("super");
294       MethodInvokeNode min=new MethodInvokeNode(nd);
295       BlockExpressionNode ben=new BlockExpressionNode(min);
296       BlockNode bn = state.getMethodBody(md);
297       bn.addFirstBlockStatement(ben);
298     }
299   }
300
301   public void checkMethodBody(ClassDescriptor cd, MethodDescriptor md) {
302     ClassDescriptor superdesc=cd.getSuperDesc();
303     if (superdesc!=null) {
304       Set possiblematches=superdesc.getMethodTable().getSet(md.getSymbol());
305       for(Iterator methodit=possiblematches.iterator(); methodit.hasNext(); ) {
306         MethodDescriptor matchmd=(MethodDescriptor)methodit.next();
307         if (md.matches(matchmd)) {
308           if (matchmd.getModifiers().isFinal()) {
309             throw new Error("Try to override final method in method:"+md+" declared in  "+cd);
310           }
311         }
312       }
313     }
314     BlockNode bn=state.getMethodBody(md);
315     checkBlockNode(md, md.getParameterTable(),bn);
316   }
317
318   public void checkBlockNode(Descriptor md, SymbolTable nametable, BlockNode bn) {
319     /* Link in the naming environment */
320     bn.getVarTable().setParent(nametable);
321     for(int i=0; i<bn.size(); i++) {
322       BlockStatementNode bsn=bn.get(i);
323       checkBlockStatementNode(md, bn.getVarTable(),bsn);
324     }
325   }
326
327   public void checkBlockStatementNode(Descriptor md, SymbolTable nametable, BlockStatementNode bsn) {
328     switch(bsn.kind()) {
329     case Kind.BlockExpressionNode:
330       checkBlockExpressionNode(md, nametable,(BlockExpressionNode)bsn);
331       return;
332
333     case Kind.DeclarationNode:
334       checkDeclarationNode(md, nametable, (DeclarationNode)bsn);
335       return;
336
337     case Kind.TagDeclarationNode:
338       checkTagDeclarationNode(md, nametable, (TagDeclarationNode)bsn);
339       return;
340
341     case Kind.IfStatementNode:
342       checkIfStatementNode(md, nametable, (IfStatementNode)bsn);
343       return;
344
345     case Kind.SwitchStatementNode:
346       checkSwitchStatementNode(md, nametable, (SwitchStatementNode)bsn);
347       return;
348
349     case Kind.LoopNode:
350       checkLoopNode(md, nametable, (LoopNode)bsn);
351       return;
352
353     case Kind.ReturnNode:
354       checkReturnNode(md, nametable, (ReturnNode)bsn);
355       return;
356
357     case Kind.TaskExitNode:
358       checkTaskExitNode(md, nametable, (TaskExitNode)bsn);
359       return;
360
361     case Kind.SubBlockNode:
362       checkSubBlockNode(md, nametable, (SubBlockNode)bsn);
363       return;
364
365     case Kind.AtomicNode:
366       checkAtomicNode(md, nametable, (AtomicNode)bsn);
367       return;
368
369     case Kind.SynchronizedNode:
370       checkSynchronizedNode(md, nametable, (SynchronizedNode)bsn);
371       return;
372
373     case Kind.ContinueBreakNode:
374       checkContinueBreakNode(md, nametable, (ContinueBreakNode) bsn);
375       return;
376
377     case Kind.SESENode:
378     case Kind.GenReachNode:
379       // do nothing, no semantic check for SESEs
380       return;
381     }
382
383     throw new Error();
384   }
385
386   void checkBlockExpressionNode(Descriptor md, SymbolTable nametable, BlockExpressionNode ben) {
387     checkExpressionNode(md, nametable, ben.getExpression(), null);
388   }
389
390   void checkDeclarationNode(Descriptor md, SymbolTable nametable,  DeclarationNode dn) {
391     VarDescriptor vd=dn.getVarDescriptor();
392     checkTypeDescriptor(((md instanceof MethodDescriptor)?((MethodDescriptor)md).getClassDesc():null), vd.getType());
393     Descriptor d=nametable.get(vd.getSymbol());
394     if ((d==null)||
395         (d instanceof FieldDescriptor)) {
396       nametable.add(vd);
397     } else
398       throw new Error(vd.getSymbol()+" in "+md+" defined a second time");
399     if (dn.getExpression()!=null)
400       checkExpressionNode(md, nametable, dn.getExpression(), vd.getType());
401   }
402
403   void checkTagDeclarationNode(Descriptor md, SymbolTable nametable,  TagDeclarationNode dn) {
404     TagVarDescriptor vd=dn.getTagVarDescriptor();
405     Descriptor d=nametable.get(vd.getSymbol());
406     if ((d==null)||
407         (d instanceof FieldDescriptor)) {
408       nametable.add(vd);
409     } else
410       throw new Error(vd.getSymbol()+" defined a second time");
411   }
412
413   void checkSubBlockNode(Descriptor md, SymbolTable nametable, SubBlockNode sbn) {
414     checkBlockNode(md, nametable, sbn.getBlockNode());
415   }
416
417   void checkAtomicNode(Descriptor md, SymbolTable nametable, AtomicNode sbn) {
418     checkBlockNode(md, nametable, sbn.getBlockNode());
419   }
420
421   void checkSynchronizedNode(Descriptor md, SymbolTable nametable, SynchronizedNode sbn) {
422     checkBlockNode(md, nametable, sbn.getBlockNode());
423     //todo this could be Object
424     checkExpressionNode(md, nametable, sbn.getExpr(), null);
425   }
426
427   void checkContinueBreakNode(Descriptor md, SymbolTable nametable, ContinueBreakNode cbn) {
428     if (loopstack.empty())
429       throw new Error("continue/break outside of loop");
430     Object o = loopstack.peek();
431     if(o instanceof LoopNode) {
432       LoopNode ln=(LoopNode)o;
433       cbn.setLoop(ln);
434     }
435   }
436
437   void checkReturnNode(Descriptor d, SymbolTable nametable, ReturnNode rn) {
438     if (d instanceof TaskDescriptor)
439       throw new Error("Illegal return appears in Task: "+d.getSymbol());
440     MethodDescriptor md=(MethodDescriptor)d;
441     if (rn.getReturnExpression()!=null)
442       if (md.getReturnType()==null)
443         throw new Error("Constructor can't return something.");
444       else if (md.getReturnType().isVoid())
445         throw new Error(md+" is void");
446       else
447         checkExpressionNode(md, nametable, rn.getReturnExpression(), md.getReturnType());
448     else
449     if (md.getReturnType()!=null&&!md.getReturnType().isVoid())
450       throw new Error("Need to return something for "+md);
451   }
452
453   void checkTaskExitNode(Descriptor md, SymbolTable nametable, TaskExitNode ten) {
454     if (md instanceof MethodDescriptor)
455       throw new Error("Illegal taskexit appears in Method: "+md.getSymbol());
456     checkFlagEffects((TaskDescriptor)md, ten.getFlagEffects(),nametable);
457     checkConstraintCheck((TaskDescriptor) md, nametable, ten.getChecks());
458   }
459
460   void checkIfStatementNode(Descriptor md, SymbolTable nametable, IfStatementNode isn) {
461     checkExpressionNode(md, nametable, isn.getCondition(), new TypeDescriptor(TypeDescriptor.BOOLEAN));
462     checkBlockNode(md, nametable, isn.getTrueBlock());
463     if (isn.getFalseBlock()!=null)
464       checkBlockNode(md, nametable, isn.getFalseBlock());
465   }
466
467   void checkSwitchStatementNode(Descriptor md, SymbolTable nametable, SwitchStatementNode ssn) {
468     checkExpressionNode(md, nametable, ssn.getCondition(), new TypeDescriptor(TypeDescriptor.INT));
469
470     BlockNode sbn = ssn.getSwitchBody();
471     boolean hasdefault = false;
472     for(int i = 0; i < sbn.size(); i++) {
473       boolean containdefault = checkSwitchBlockNode(md, nametable, (SwitchBlockNode)sbn.get(i));
474       if(hasdefault && containdefault) {
475         throw new Error("Error: duplicate default branch in switch-case statement in Method: " + md.getSymbol());
476       }
477       hasdefault = containdefault;
478     }
479   }
480
481   boolean checkSwitchBlockNode(Descriptor md, SymbolTable nametable, SwitchBlockNode sbn) {
482     Vector<SwitchLabelNode> slnv = sbn.getSwitchConditions();
483     int defaultb = 0;
484     for(int i = 0; i < slnv.size(); i++) {
485       if(slnv.elementAt(i).isdefault) {
486         defaultb++;
487       } else {
488         checkConstantExpressionNode(md, nametable, slnv.elementAt(i).getCondition(), new TypeDescriptor(TypeDescriptor.INT));
489       }
490     }
491     if(defaultb > 1) {
492       throw new Error("Error: duplicate default branch in switch-case statement in Method: " + md.getSymbol());
493     } else {
494       loopstack.push(sbn);
495       checkBlockNode(md, nametable, sbn.getSwitchBlockStatement());
496       loopstack.pop();
497       return (defaultb > 0);
498     }
499   }
500
501   void checkConstantExpressionNode(Descriptor md, SymbolTable nametable, ExpressionNode en, TypeDescriptor td) {
502     switch(en.kind()) {
503     case Kind.FieldAccessNode:
504       checkFieldAccessNode(md,nametable,(FieldAccessNode)en,td);
505       return;
506
507     case Kind.LiteralNode:
508       checkLiteralNode(md,nametable,(LiteralNode)en,td);
509       return;
510
511     case Kind.NameNode:
512       checkNameNode(md,nametable,(NameNode)en,td);
513       return;
514
515     case Kind.OpNode:
516       checkOpNode(md, nametable, (OpNode)en, td);
517       return;
518     }
519     throw new Error();
520   }
521
522   void checkExpressionNode(Descriptor md, SymbolTable nametable, ExpressionNode en, TypeDescriptor td) {
523     switch(en.kind()) {
524     case Kind.AssignmentNode:
525       checkAssignmentNode(md,nametable,(AssignmentNode)en,td);
526       return;
527
528     case Kind.CastNode:
529       checkCastNode(md,nametable,(CastNode)en,td);
530       return;
531
532     case Kind.CreateObjectNode:
533       checkCreateObjectNode(md,nametable,(CreateObjectNode)en,td);
534       return;
535
536     case Kind.FieldAccessNode:
537       checkFieldAccessNode(md,nametable,(FieldAccessNode)en,td);
538       return;
539
540     case Kind.ArrayAccessNode:
541       checkArrayAccessNode(md,nametable,(ArrayAccessNode)en,td);
542       return;
543
544     case Kind.LiteralNode:
545       checkLiteralNode(md,nametable,(LiteralNode)en,td);
546       return;
547
548     case Kind.MethodInvokeNode:
549       checkMethodInvokeNode(md,nametable,(MethodInvokeNode)en,td);
550       return;
551
552     case Kind.NameNode:
553       checkNameNode(md,nametable,(NameNode)en,td);
554       return;
555
556     case Kind.OpNode:
557       checkOpNode(md,nametable,(OpNode)en,td);
558       return;
559
560     case Kind.OffsetNode:
561       checkOffsetNode(md, nametable, (OffsetNode)en, td);
562       return;
563
564     case Kind.TertiaryNode:
565       checkTertiaryNode(md, nametable, (TertiaryNode)en, td);
566       return;
567
568     case Kind.InstanceOfNode:
569       checkInstanceOfNode(md, nametable, (InstanceOfNode) en, td);
570       return;
571
572     case Kind.ArrayInitializerNode:
573       checkArrayInitializerNode(md, nametable, (ArrayInitializerNode) en, td);
574       return;
575
576     case Kind.ClassTypeNode:
577       checkClassTypeNode(md, nametable, (ClassTypeNode) en, td);
578       return;
579     }
580     throw new Error();
581   }
582
583   void checkClassTypeNode(Descriptor md, SymbolTable nametable, ClassTypeNode tn, TypeDescriptor td) {
584     checkTypeDescriptor(((md instanceof MethodDescriptor)?((MethodDescriptor)md).getClassDesc():null), tn.getType());
585   }
586
587   void checkCastNode(Descriptor md, SymbolTable nametable, CastNode cn, TypeDescriptor td) {
588     /* Get type descriptor */
589     if (cn.getType()==null) {
590       NameDescriptor typenamed=cn.getTypeName().getName();
591       TypeDescriptor ntd=new TypeDescriptor(getClass(((md instanceof MethodDescriptor)?((MethodDescriptor)md).getClassDesc():null), typenamed.toString()));
592       cn.setType(ntd);
593     }
594
595     /* Check the type descriptor */
596     TypeDescriptor cast_type=cn.getType();
597     checkTypeDescriptor(((md instanceof MethodDescriptor)?((MethodDescriptor)md).getClassDesc():null),cast_type);
598
599     /* Type check */
600     if (td!=null) {
601       if (!typeutil.isSuperorType(td,cast_type))
602         throw new Error("Cast node returns "+cast_type+", but need "+td);
603     }
604
605     ExpressionNode en=cn.getExpression();
606     checkExpressionNode(md, nametable, en, null);
607     TypeDescriptor etd=en.getType();
608     if (typeutil.isSuperorType(cast_type,etd))     /* Cast trivially succeeds */
609       return;
610
611     if (typeutil.isSuperorType(etd,cast_type))     /* Cast may succeed */
612       return;
613     if (typeutil.isCastable(etd, cast_type))
614       return;
615
616     /* Different branches */
617     /* TODO: change if add interfaces */
618     throw new Error("Cast will always fail\n"+cn.printNode(0));
619   }
620
621   void checkFieldAccessNode(Descriptor md, SymbolTable nametable, FieldAccessNode fan, TypeDescriptor td) {
622     ExpressionNode left=fan.getExpression();
623     checkExpressionNode(md,nametable,left,null);
624     TypeDescriptor ltd=left.getType();
625     String fieldname=fan.getFieldName();
626
627     FieldDescriptor fd=null;
628     if (ltd.isArray()&&fieldname.equals("length"))
629       fd=FieldDescriptor.arrayLength;
630     else
631       fd=(FieldDescriptor) ltd.getClassDesc().getFieldTable().get(fieldname);
632
633     if(ltd.isClassNameRef()) {
634       // the field access is using a class name directly
635       if(ltd.getClassDesc().isEnum()) {
636         int value = ltd.getClassDesc().getEnumConstant(fieldname);
637         if(-1 == value) {
638           // check if this field is an enum constant
639           throw new Error(fieldname + " is not an enum constant in "+fan.printNode(0)+" in "+md);
640         }
641         fd = new FieldDescriptor(new Modifiers(Modifiers.PUBLIC|Modifiers.FINAL), new TypeDescriptor(TypeDescriptor.INT), fieldname, null, false);
642         fd.setAsEnum();
643         fd.setEnumValue(value);
644       } else if(fd == null) {
645         throw new Error("Could not find field "+ fieldname + " in "+fan.printNode(0)+" in "+md + " (Line: "+fan.getNumLine()+")");
646       } else if(fd.isStatic()) {
647         // check if this field is a static field
648         if(fd.getExpressionNode() != null) {
649           checkExpressionNode(md,nametable,fd.getExpressionNode(),null);
650         }
651       } else {
652         throw new Error("Dereference of the non-static field "+ fieldname + " in "+fan.printNode(0)+" in "+md);
653       }
654     }
655
656     if (fd==null)
657       throw new Error("Unknown field "+fieldname + " in "+fan.printNode(0)+" in "+md);
658
659     if (fd.getType().iswrapper()) {
660       FieldAccessNode fan2=new FieldAccessNode(left, fieldname);
661       fan2.setNumLine(left.getNumLine());
662       fan2.setField(fd);
663       fan.left=fan2;
664       fan.fieldname="value";
665
666       ExpressionNode leftwr=fan.getExpression();
667       TypeDescriptor ltdwr=leftwr.getType();
668       String fieldnamewr=fan.getFieldName();
669       FieldDescriptor fdwr=(FieldDescriptor) ltdwr.getClassDesc().getFieldTable().get(fieldnamewr);
670       fan.setField(fdwr);
671       if (fdwr==null)
672         throw new Error("Unknown field "+fieldnamewr + " in "+fan.printNode(0)+" in "+md);
673     } else {
674       fan.setField(fd);
675     }
676     if (td!=null) {
677       if (!typeutil.isSuperorType(td,fan.getType()))
678         throw new Error("Field node returns "+fan.getType()+", but need "+td);
679     }
680   }
681
682   void checkArrayAccessNode(Descriptor md, SymbolTable nametable, ArrayAccessNode aan, TypeDescriptor td) {
683     ExpressionNode left=aan.getExpression();
684     checkExpressionNode(md,nametable,left,null);
685
686     checkExpressionNode(md,nametable,aan.getIndex(),new TypeDescriptor(TypeDescriptor.INT));
687     TypeDescriptor ltd=left.getType();
688     if (ltd.dereference().iswrapper()) {
689       aan.wrappertype=((FieldDescriptor)ltd.dereference().getClassDesc().getFieldTable().get("value")).getType();
690     }
691
692     if (td!=null)
693       if (!typeutil.isSuperorType(td,aan.getType()))
694         throw new Error("Field node returns "+aan.getType()+", but need "+td);
695   }
696
697   void checkLiteralNode(Descriptor md, SymbolTable nametable, LiteralNode ln, TypeDescriptor td) {
698     /* Resolve the type */
699     Object o=ln.getValue();
700     if (ln.getTypeString().equals("null")) {
701       ln.setType(new TypeDescriptor(TypeDescriptor.NULL));
702     } else if (o instanceof Integer) {
703       ln.setType(new TypeDescriptor(TypeDescriptor.INT));
704     } else if (o instanceof Long) {
705       ln.setType(new TypeDescriptor(TypeDescriptor.LONG));
706     } else if (o instanceof Float) {
707       ln.setType(new TypeDescriptor(TypeDescriptor.FLOAT));
708     } else if (o instanceof Boolean) {
709       ln.setType(new TypeDescriptor(TypeDescriptor.BOOLEAN));
710     } else if (o instanceof Double) {
711       ln.setType(new TypeDescriptor(TypeDescriptor.DOUBLE));
712     } else if (o instanceof Character) {
713       ln.setType(new TypeDescriptor(TypeDescriptor.CHAR));
714     } else if (o instanceof String) {
715       ln.setType(new TypeDescriptor(getClass(null, TypeUtil.StringClass)));
716     }
717
718     if (td!=null)
719       if (!typeutil.isSuperorType(td,ln.getType())) {
720         Long l = ln.evaluate();
721         if((ln.getType().isByte() || ln.getType().isShort()
722             || ln.getType().isChar() || ln.getType().isInt())
723            && (l != null)
724            && (td.isByte() || td.isShort() || td.isChar()
725                || td.isInt() || td.isLong())) {
726           long lnvalue = l.longValue();
727           if((td.isByte() && ((lnvalue > 127) || (lnvalue < -128)))
728              || (td.isShort() && ((lnvalue > 32767) || (lnvalue < -32768)))
729              || (td.isChar() && ((lnvalue > 65535) || (lnvalue < 0)))
730              || (td.isInt() && ((lnvalue > 2147483647) || (lnvalue < -2147483648)))
731              || (td.isLong() && ((lnvalue > 9223372036854775807L) || (lnvalue < -9223372036854775808L)))) {
732             throw new Error("Field node returns "+ln.getType()+", but need "+td+" in "+md);
733           }
734         } else {
735           throw new Error("Field node returns "+ln.getType()+", but need "+td+" in "+md);
736         }
737       }
738   }
739
740   void checkNameNode(Descriptor md, SymbolTable nametable, NameNode nn, TypeDescriptor td) {
741     NameDescriptor nd=nn.getName();
742     if (nd.getBase()!=null) {
743       /* Big hack */
744       /* Rewrite NameNode */
745       ExpressionNode en=translateNameDescriptorintoExpression(nd,nn.getNumLine());
746       nn.setExpression(en);
747       checkExpressionNode(md,nametable,en,td);
748     } else {
749       String varname=nd.toString();
750       if(varname.equals("this")) {
751         // "this"
752         nn.setVar((VarDescriptor)nametable.get("this"));
753         return;
754       }
755       Descriptor d=(Descriptor)nametable.get(varname);
756       if (d==null) {
757         ClassDescriptor cd = null;
758         if((md instanceof MethodDescriptor) && ((MethodDescriptor)md).isStaticBlock()) {
759           // this is a static block, all the accessed fields should be static field
760           cd = ((MethodDescriptor)md).getClassDesc();
761           SymbolTable fieldtbl = cd.getFieldTable();
762           FieldDescriptor fd=(FieldDescriptor)fieldtbl.get(varname);
763           if((fd == null) || (!fd.isStatic())) {
764             // no such field in the class, check if this is a class
765             if(varname.equals("this")) {
766               throw new Error("Error: access this obj in a static block");
767             }
768             cd=getClass(((md instanceof MethodDescriptor)?((MethodDescriptor)md).getClassDesc():null), varname);
769             if(cd != null) {
770               // this is a class name
771               nn.setClassDesc(cd);
772               return;
773             } else {
774               throw new Error("Name "+varname+" should not be used in static block: "+md);
775             }
776           } else {
777             // this is a static field
778             nn.setField(fd);
779             nn.setClassDesc(cd);
780             return;
781           }
782         } else {
783           // check if the var is a static field of the class
784           if(md instanceof MethodDescriptor) {
785             cd = ((MethodDescriptor)md).getClassDesc();
786             FieldDescriptor fd = (FieldDescriptor)cd.getFieldTable().get(varname);
787             if((fd != null) && (fd.isStatic())) {
788               nn.setField(fd);
789               nn.setClassDesc(cd);
790               if (td!=null)
791                 if (!typeutil.isSuperorType(td,nn.getType()))
792                   throw new Error("Field node returns "+nn.getType()+", but need "+td);
793               return;
794             } else if(fd != null) {
795               throw new Error("Name "+varname+" should not be used in " + md);
796             }
797           }
798           cd=getClass(((md instanceof MethodDescriptor)?((MethodDescriptor)md).getClassDesc():null), varname);
799           if(cd != null) {
800             // this is a class name
801             nn.setClassDesc(cd);
802             return;
803           } else {
804             throw new Error("Name "+varname+" undefined in: "+md);
805           }
806         }
807       }
808       if (d instanceof VarDescriptor) {
809         nn.setVar(d);
810       } else if (d instanceof FieldDescriptor) {
811         FieldDescriptor fd=(FieldDescriptor)d;
812         if (fd.getType().iswrapper()) {
813           String id=nd.getIdentifier();
814           NameDescriptor base=nd.getBase();
815           NameNode n=new NameNode(nn.getName());
816           n.setNumLine(nn.getNumLine());
817           n.setField(fd);
818           n.setVar((VarDescriptor)nametable.get("this"));        /* Need a pointer to this */
819           FieldAccessNode fan=new FieldAccessNode(n,"value");
820           fan.setNumLine(n.getNumLine());
821           FieldDescriptor fdval=(FieldDescriptor) fd.getType().getClassDesc().getFieldTable().get("value");
822           fan.setField(fdval);
823           nn.setExpression(fan);
824         } else {
825           nn.setField(fd);
826           nn.setVar((VarDescriptor)nametable.get("this"));        /* Need a pointer to this */
827         }
828       } else if (d instanceof TagVarDescriptor) {
829         nn.setVar(d);
830       } else throw new Error("Wrong type of descriptor");
831       if (td!=null)
832         if (!typeutil.isSuperorType(td,nn.getType()))
833           throw new Error("Field node returns "+nn.getType()+", but need "+td);
834     }
835   }
836
837   void checkOffsetNode(Descriptor md, SymbolTable nameTable, OffsetNode ofn, TypeDescriptor td) {
838     TypeDescriptor ltd=ofn.td;
839     checkTypeDescriptor(((md instanceof MethodDescriptor)?((MethodDescriptor)md).getClassDesc():null),ltd);
840
841     String fieldname = ofn.fieldname;
842     FieldDescriptor fd=null;
843     if (ltd.isArray()&&fieldname.equals("length")) {
844       fd=FieldDescriptor.arrayLength;
845     } else {
846       fd=(FieldDescriptor) ltd.getClassDesc().getFieldTable().get(fieldname);
847     }
848
849     ofn.setField(fd);
850     checkField(ltd.getClassDesc(), fd);
851
852     if (fd==null)
853       throw new Error("Unknown field "+fieldname + " in "+ofn.printNode(1)+" in "+md);
854
855     if (td!=null) {
856       if (!typeutil.isSuperorType(td, ofn.getType())) {
857         System.out.println(td);
858         System.out.println(ofn.getType());
859         throw new Error("Type of rside not compatible with type of lside"+ofn.printNode(0));
860       }
861     }
862   }
863
864
865   void checkTertiaryNode(Descriptor md, SymbolTable nametable, TertiaryNode tn, TypeDescriptor td) {
866     checkExpressionNode(md, nametable, tn.getCond(), new TypeDescriptor(TypeDescriptor.BOOLEAN));
867     checkExpressionNode(md, nametable, tn.getTrueExpr(), td);
868     checkExpressionNode(md, nametable, tn.getFalseExpr(), td);
869   }
870
871   void checkInstanceOfNode(Descriptor md, SymbolTable nametable, InstanceOfNode tn, TypeDescriptor td) {
872     if (td!=null&&!td.isBoolean())
873       throw new Error("Expecting type "+td+"for instanceof expression");
874
875     checkTypeDescriptor(((md instanceof MethodDescriptor)?((MethodDescriptor)md).getClassDesc():null), tn.getExprType());
876     checkExpressionNode(md, nametable, tn.getExpr(), null);
877   }
878
879   void checkArrayInitializerNode(Descriptor md, SymbolTable nametable, ArrayInitializerNode ain, TypeDescriptor td) {
880     Vector<TypeDescriptor> vec_type = new Vector<TypeDescriptor>();
881     for( int i = 0; i < ain.numVarInitializers(); ++i ) {
882       checkExpressionNode(md, nametable, ain.getVarInitializer(i), td==null?td:td.dereference());
883       vec_type.add(ain.getVarInitializer(i).getType());
884     }
885     // descide the type of this variableInitializerNode
886     TypeDescriptor out_type = vec_type.elementAt(0);
887     for(int i = 1; i < vec_type.size(); i++) {
888       TypeDescriptor tmp_type = vec_type.elementAt(i);
889       if(out_type == null) {
890         if(tmp_type != null) {
891           out_type = tmp_type;
892         }
893       } else if(out_type.isNull()) {
894         if(!tmp_type.isNull() ) {
895           if(!tmp_type.isArray()) {
896             throw new Error("Error: mixed type in var initializer list");
897           } else {
898             out_type = tmp_type;
899           }
900         }
901       } else if(out_type.isArray()) {
902         if(tmp_type.isArray()) {
903           if(tmp_type.getArrayCount() > out_type.getArrayCount()) {
904             out_type = tmp_type;
905           }
906         } else if((tmp_type != null) && (!tmp_type.isNull())) {
907           throw new Error("Error: mixed type in var initializer list");
908         }
909       } else if(out_type.isInt()) {
910         if(!tmp_type.isInt()) {
911           throw new Error("Error: mixed type in var initializer list");
912         }
913       } else if(out_type.isString()) {
914         if(!tmp_type.isString()) {
915           throw new Error("Error: mixed type in var initializer list");
916         }
917       }
918     }
919     if(out_type != null) {
920       out_type = out_type.makeArray(state);
921       //out_type.setStatic();
922     }
923     ain.setType(out_type);
924   }
925
926   void checkAssignmentNode(Descriptor md, SymbolTable nametable, AssignmentNode an, TypeDescriptor td) {
927     boolean postinc=true;
928     if (an.getOperation().getBaseOp()==null||
929         (an.getOperation().getBaseOp().getOp()!=Operation.POSTINC&&
930          an.getOperation().getBaseOp().getOp()!=Operation.POSTDEC))
931       postinc=false;
932     if (!postinc)
933       checkExpressionNode(md, nametable, an.getSrc(),td);
934     //TODO: Need check on validity of operation here
935     if (!((an.getDest() instanceof FieldAccessNode)||
936           (an.getDest() instanceof ArrayAccessNode)||
937           (an.getDest() instanceof NameNode)))
938       throw new Error("Bad lside in "+an.printNode(0));
939     checkExpressionNode(md, nametable, an.getDest(), null);
940
941     /* We want parameter variables to tasks to be immutable */
942     if (md instanceof TaskDescriptor) {
943       if (an.getDest() instanceof NameNode) {
944         NameNode nn=(NameNode)an.getDest();
945         if (nn.getVar()!=null) {
946           if (((TaskDescriptor)md).getParameterTable().contains(nn.getVar().getSymbol()))
947             throw new Error("Can't modify parameter "+nn.getVar()+ " to task "+td.getSymbol());
948         }
949       }
950     }
951
952     if (an.getDest().getType().isString()&&an.getOperation().getOp()==AssignOperation.PLUSEQ) {
953       //String add
954       ClassDescriptor stringcl=getClass(null, TypeUtil.StringClass);
955       TypeDescriptor stringtd=new TypeDescriptor(stringcl);
956       NameDescriptor nd=new NameDescriptor("String");
957       NameDescriptor valuend=new NameDescriptor(nd, "valueOf");
958
959       if (!(an.getSrc().getType().isString()&&(an.getSrc() instanceof OpNode))) {
960         MethodInvokeNode rightmin=new MethodInvokeNode(valuend);
961         rightmin.setNumLine(an.getSrc().getNumLine());
962         rightmin.addArgument(an.getSrc());
963         an.right=rightmin;
964         checkExpressionNode(md, nametable, an.getSrc(), null);
965       }
966     }
967
968     if (!postinc&&!typeutil.isSuperorType(an.getDest().getType(),an.getSrc().getType())) {
969       TypeDescriptor dt = an.getDest().getType();
970       TypeDescriptor st = an.getSrc().getType();
971       if(an.getSrc().kind() == Kind.ArrayInitializerNode) {
972         if(dt.getArrayCount() != st.getArrayCount()) {
973           throw new Error("Type of rside ("+an.getSrc().getType().toPrettyString()+") not compatible with type of lside ("+an.getDest().getType().toPrettyString()+")"+an.printNode(0));
974         } else {
975           do {
976             dt = dt.dereference();
977             st = st.dereference();
978           } while(dt.isArray());
979           if((st.isByte() || st.isShort() || st.isChar() || st.isInt())
980              && (dt.isByte() || dt.isShort() || dt.isChar() || dt.isInt() || dt.isLong())) {
981             return;
982           } else {
983             throw new Error("Type of rside ("+an.getSrc().getType().toPrettyString()+") not compatible with type of lside ("+an.getDest().getType().toPrettyString()+")"+an.printNode(0));
984           }
985         }
986       } else {
987         Long l = an.getSrc().evaluate();
988         if((st.isByte() || st.isShort() || st.isChar() || st.isInt())
989            && (l != null)
990            && (dt.isByte() || dt.isShort() || dt.isChar() || dt.isInt() || dt.isLong())) {
991           long lnvalue = l.longValue();
992           if((dt.isByte() && ((lnvalue > 127) || (lnvalue < -128)))
993              || (dt.isShort() && ((lnvalue > 32767) || (lnvalue < -32768)))
994              || (dt.isChar() && ((lnvalue > 65535) || (lnvalue < 0)))
995              || (dt.isInt() && ((lnvalue > 2147483647) || (lnvalue < -2147483648)))
996              || (dt.isLong() && ((lnvalue > 9223372036854775807L) || (lnvalue < -9223372036854775808L)))) {
997             throw new Error("Type of rside ("+an.getSrc().getType().toPrettyString()+") not compatible with type of lside ("+an.getDest().getType().toPrettyString()+")"+an.printNode(0));
998           }
999         } else {
1000           throw new Error("Type of rside ("+an.getSrc().getType().toPrettyString()+") not compatible with type of lside ("+an.getDest().getType().toPrettyString()+")"+an.printNode(0));
1001         }
1002       }
1003     }
1004   }
1005
1006   void checkLoopNode(Descriptor md, SymbolTable nametable, LoopNode ln) {
1007     loopstack.push(ln);
1008     if (ln.getType()==LoopNode.WHILELOOP||ln.getType()==LoopNode.DOWHILELOOP) {
1009       checkExpressionNode(md, nametable, ln.getCondition(), new TypeDescriptor(TypeDescriptor.BOOLEAN));
1010       checkBlockNode(md, nametable, ln.getBody());
1011     } else {
1012       //For loop case
1013       /* Link in the initializer naming environment */
1014       BlockNode bn=ln.getInitializer();
1015       bn.getVarTable().setParent(nametable);
1016       for(int i=0; i<bn.size(); i++) {
1017         BlockStatementNode bsn=bn.get(i);
1018         checkBlockStatementNode(md, bn.getVarTable(),bsn);
1019       }
1020       //check the condition
1021       checkExpressionNode(md, bn.getVarTable(), ln.getCondition(), new TypeDescriptor(TypeDescriptor.BOOLEAN));
1022       checkBlockNode(md, bn.getVarTable(), ln.getBody());
1023       checkBlockNode(md, bn.getVarTable(), ln.getUpdate());
1024     }
1025     loopstack.pop();
1026   }
1027
1028
1029   void checkCreateObjectNode(Descriptor md, SymbolTable nametable, CreateObjectNode con,
1030                              TypeDescriptor td) {
1031     TypeDescriptor[] tdarray = new TypeDescriptor[con.numArgs()];
1032     for (int i = 0; i < con.numArgs(); i++) {
1033       ExpressionNode en = con.getArg(i);
1034       checkExpressionNode(md, nametable, en, null);
1035       tdarray[i] = en.getType();
1036     }
1037
1038     TypeDescriptor typetolookin = con.getType();
1039     checkTypeDescriptor(((md instanceof MethodDescriptor)?((MethodDescriptor)md).getClassDesc():null), typetolookin);
1040
1041     if (td != null && !typeutil.isSuperorType(td, typetolookin))
1042       throw new Error(typetolookin + " isn't a " + td);
1043
1044     /* Check Array Initializers */
1045     if ((con.getArrayInitializer() != null)) {
1046       checkArrayInitializerNode(md, nametable, con.getArrayInitializer(), td);
1047     }
1048
1049     /* Check flag effects */
1050     if (con.getFlagEffects() != null) {
1051       FlagEffects fe = con.getFlagEffects();
1052       ClassDescriptor cd = typetolookin.getClassDesc();
1053
1054       for (int j = 0; j < fe.numEffects(); j++) {
1055         FlagEffect flag = fe.getEffect(j);
1056         String name = flag.getName();
1057         FlagDescriptor flag_d = (FlagDescriptor) cd.getFlagTable().get(name);
1058         // Make sure the flag is declared
1059         if (flag_d == null)
1060           throw new Error("Flag descriptor " + name + " undefined in class: " + cd.getSymbol());
1061         if (flag_d.getExternal())
1062           throw new Error("Attempting to modify external flag: " + name);
1063         flag.setFlag(flag_d);
1064       }
1065       for (int j = 0; j < fe.numTagEffects(); j++) {
1066         TagEffect tag = fe.getTagEffect(j);
1067         String name = tag.getName();
1068
1069         Descriptor d = (Descriptor) nametable.get(name);
1070         if (d == null)
1071           throw new Error("Tag descriptor " + name + " undeclared");
1072         else if (!(d instanceof TagVarDescriptor))
1073           throw new Error(name + " is not a tag descriptor");
1074         tag.setTag((TagVarDescriptor) d);
1075       }
1076     }
1077
1078     if ((!typetolookin.isClass()) && (!typetolookin.isArray()))
1079       throw new Error("Can't allocate primitive type:" + con.printNode(0));
1080
1081     if (!typetolookin.isArray()) {
1082       // Array's don't need constructor calls
1083       ClassDescriptor classtolookin = typetolookin.getClassDesc();
1084       checkClass(classtolookin, INIT);
1085
1086       Set methoddescriptorset = classtolookin.getMethodTable().getSet(typetolookin.getSymbol());
1087       MethodDescriptor bestmd = null;
1088 NextMethod: for (Iterator methodit = methoddescriptorset.iterator(); methodit.hasNext(); ) {
1089         MethodDescriptor currmd = (MethodDescriptor) methodit.next();
1090         /* Need correct number of parameters */
1091         if (con.numArgs() != currmd.numParameters())
1092           continue;
1093         for (int i = 0; i < con.numArgs(); i++) {
1094           if (!typeutil.isSuperorType(currmd.getParamType(i), tdarray[i]))
1095             continue NextMethod;
1096         }
1097         /* Local allocations can't call global allocator */
1098         if (!con.isGlobal() && currmd.isGlobal())
1099           continue;
1100
1101         /* Method okay so far */
1102         if (bestmd == null)
1103           bestmd = currmd;
1104         else {
1105           if (typeutil.isMoreSpecific(currmd, bestmd)) {
1106             bestmd = currmd;
1107           } else if (con.isGlobal() && match(currmd, bestmd)) {
1108             if (currmd.isGlobal() && !bestmd.isGlobal())
1109               bestmd = currmd;
1110             else if (currmd.isGlobal() && bestmd.isGlobal())
1111               throw new Error();
1112           } else if (!typeutil.isMoreSpecific(bestmd, currmd)) {
1113             throw new Error("No method is most specific:" + bestmd + " and " + currmd);
1114           }
1115
1116           /* Is this more specific than bestmd */
1117         }
1118       }
1119       if (bestmd == null)
1120         throw new Error("No method found for " + con.printNode(0) + " in " + md);
1121       con.setConstructor(bestmd);
1122     }
1123   }
1124
1125
1126   /** Check to see if md1 is the same specificity as md2.*/
1127
1128   boolean match(MethodDescriptor md1, MethodDescriptor md2) {
1129     /* Checks if md1 is more specific than md2 */
1130     if (md1.numParameters()!=md2.numParameters())
1131       throw new Error();
1132     for(int i=0; i<md1.numParameters(); i++) {
1133       if (!md2.getParamType(i).equals(md1.getParamType(i)))
1134         return false;
1135     }
1136     if (!md2.getReturnType().equals(md1.getReturnType()))
1137       return false;
1138
1139     if (!md2.getClassDesc().equals(md1.getClassDesc()))
1140       return false;
1141
1142     return true;
1143   }
1144
1145
1146
1147   ExpressionNode translateNameDescriptorintoExpression(NameDescriptor nd, int numLine) {
1148     String id=nd.getIdentifier();
1149     NameDescriptor base=nd.getBase();
1150     if (base==null) {
1151       NameNode nn=new NameNode(nd);
1152       nn.setNumLine(numLine);
1153       return nn;
1154     } else {
1155       FieldAccessNode fan=new FieldAccessNode(translateNameDescriptorintoExpression(base,numLine),id);
1156       fan.setNumLine(numLine);
1157       return fan;
1158     }
1159   }
1160
1161
1162   void checkMethodInvokeNode(Descriptor md, SymbolTable nametable, MethodInvokeNode min, TypeDescriptor td) {
1163     /*Typecheck subexpressions
1164        and get types for expressions*/
1165
1166     boolean isstatic = false;
1167     if((md instanceof MethodDescriptor) && ((MethodDescriptor)md).isStatic()) {
1168       isstatic = true;
1169     }
1170     TypeDescriptor[] tdarray=new TypeDescriptor[min.numArgs()];
1171     for(int i=0; i<min.numArgs(); i++) {
1172       ExpressionNode en=min.getArg(i);
1173       checkExpressionNode(md,nametable,en,null);
1174       tdarray[i]=en.getType();
1175       if(en.getType().isClass() && en.getType().getClassDesc().isEnum()) {
1176         tdarray[i] = new TypeDescriptor(TypeDescriptor.INT);
1177       }
1178     }
1179     TypeDescriptor typetolookin=null;
1180     if (min.getExpression()!=null) {
1181       checkExpressionNode(md,nametable,min.getExpression(),null);
1182       typetolookin=min.getExpression().getType();
1183       //if (typetolookin==null)
1184       //throw new Error(md+" has null return type");
1185
1186     } else if (min.getBaseName()!=null) {
1187       String rootname=min.getBaseName().getRoot();
1188       if (rootname.equals("super")) {
1189         ClassDescriptor supercd=((MethodDescriptor)md).getClassDesc().getSuperDesc();
1190         typetolookin=new TypeDescriptor(supercd);
1191         min.setSuper();
1192       } else if (rootname.equals("this")) {
1193         if(isstatic) {
1194           throw new Error("use this object in static method md = "+ md.toString());
1195         }
1196         ClassDescriptor cd=((MethodDescriptor)md).getClassDesc();
1197         typetolookin=new TypeDescriptor(cd);
1198       } else if (nametable.get(rootname)!=null) {
1199         //we have an expression
1200         min.setExpression(translateNameDescriptorintoExpression(min.getBaseName(),min.getNumLine()));
1201         checkExpressionNode(md, nametable, min.getExpression(), null);
1202         typetolookin=min.getExpression().getType();
1203       } else {
1204         if(!min.getBaseName().getSymbol().equals("System.out")||state.JNI) {
1205           ExpressionNode nn = translateNameDescriptorintoExpression(min.getBaseName(),min.getNumLine());
1206           checkExpressionNode(md, nametable, nn, null);
1207           typetolookin = nn.getType();
1208           if(!((nn.kind()== Kind.NameNode) && (((NameNode)nn).getField() == null)
1209                && (((NameNode)nn).getVar() == null) && (((NameNode)nn).getExpression() == null))) {
1210             // this is not a pure class name, need to add to
1211             min.setExpression(nn);
1212           }
1213         } else {
1214           //we have a type
1215           ClassDescriptor cd = getClass(null, "System");
1216
1217           if (cd==null)
1218             throw new Error("md = "+ md.toString()+ "  "+min.getBaseName()+" undefined");
1219           typetolookin=new TypeDescriptor(cd);
1220         }
1221       }
1222     } else if ((md instanceof MethodDescriptor)&&min.getMethodName().equals("super")) {
1223       ClassDescriptor supercd=((MethodDescriptor)md).getClassDesc().getSuperDesc();
1224       min.methodid=supercd.getSymbol();
1225       typetolookin=new TypeDescriptor(supercd);
1226     } else if (md instanceof MethodDescriptor) {
1227       typetolookin=new TypeDescriptor(((MethodDescriptor)md).getClassDesc());
1228     } else {
1229       /* If this a task descriptor we throw an error at this point */
1230       throw new Error("Unknown method call to "+min.getMethodName()+"in task"+md.getSymbol());
1231     }
1232     if (!typetolookin.isClass())
1233       throw new Error("Error with method call to "+min.getMethodName());
1234     ClassDescriptor classtolookin=typetolookin.getClassDesc();
1235     checkClass(classtolookin, INIT);
1236     //System.out.println("Method name="+min.getMethodName());
1237
1238     Set methoddescriptorset=classtolookin.getMethodTable().getSet(min.getMethodName());
1239     MethodDescriptor bestmd=null;
1240 NextMethod:
1241     for(Iterator methodit=methoddescriptorset.iterator(); methodit.hasNext(); ) {
1242       MethodDescriptor currmd=(MethodDescriptor)methodit.next();
1243       /* Need correct number of parameters */
1244       if (min.numArgs()!=currmd.numParameters())
1245         continue;
1246       for(int i=0; i<min.numArgs(); i++) {
1247         if (!typeutil.isSuperorType(currmd.getParamType(i),tdarray[i]))
1248           if(((!tdarray[i].isArray() &&(tdarray[i].isInt() || tdarray[i].isLong()))
1249               && currmd.getParamType(i).isClass() && currmd.getParamType(i).getClassDesc().getSymbol().equals("Object"))) {
1250             // primitive parameters vs object
1251           } else {
1252             continue NextMethod;
1253           }
1254       }
1255       /* Method okay so far */
1256       if (bestmd==null)
1257         bestmd=currmd;
1258       else {
1259         if (typeutil.isMoreSpecific(currmd,bestmd)) {
1260           bestmd=currmd;
1261         } else if (!typeutil.isMoreSpecific(bestmd, currmd))
1262           throw new Error("No method is most specific:"+bestmd+" and "+currmd);
1263
1264         /* Is this more specific than bestmd */
1265       }
1266     }
1267     if (bestmd==null)
1268       throw new Error("No method found for :"+min.printNode(0)+" in class: " + classtolookin+" in "+md);
1269     min.setMethod(bestmd);
1270
1271     if ((td!=null)&&(min.getType()!=null)&&!typeutil.isSuperorType(td,  min.getType()))
1272       throw new Error(min.getType()+ " is not equal to or a subclass of "+td);
1273     /* Check whether we need to set this parameter to implied this */
1274     if (!isstatic && !bestmd.isStatic()) {
1275       if (min.getExpression()==null) {
1276         ExpressionNode en=new NameNode(new NameDescriptor("this"));
1277         min.setExpression(en);
1278         checkExpressionNode(md, nametable, min.getExpression(), null);
1279       }
1280     }
1281
1282     /* Check if we need to wrap primitive paratmeters to objects */
1283     for(int i=0; i<min.numArgs(); i++) {
1284       if(!tdarray[i].isArray() && (tdarray[i].isInt() || tdarray[i].isLong())
1285          && min.getMethod().getParamType(i).isClass() && min.getMethod().getParamType(i).getClassDesc().getSymbol().equals("Object")) {
1286         // Shall wrap this primitive parameter as a object
1287         ExpressionNode exp = min.getArg(i);
1288         TypeDescriptor ptd = null;
1289         NameDescriptor nd=null;
1290         if(exp.getType().isInt()) {
1291           nd = new NameDescriptor("Integer");
1292           ptd = state.getTypeDescriptor(nd);
1293         } else if(exp.getType().isLong()) {
1294           nd = new NameDescriptor("Long");
1295           ptd = state.getTypeDescriptor(nd);
1296         }
1297         boolean isglobal = false;
1298         String disjointId = null;
1299         CreateObjectNode con=new CreateObjectNode(ptd, isglobal, disjointId);
1300         con.addArgument(exp);
1301         checkExpressionNode(md, nametable, con, null);
1302         min.setArgument(con, i);
1303       }
1304     }
1305   }
1306
1307
1308   void checkOpNode(Descriptor md, SymbolTable nametable, OpNode on, TypeDescriptor td) {
1309     checkExpressionNode(md, nametable, on.getLeft(), null);
1310     if (on.getRight()!=null)
1311       checkExpressionNode(md, nametable, on.getRight(), null);
1312     TypeDescriptor ltd=on.getLeft().getType();
1313     TypeDescriptor rtd=on.getRight()!=null?on.getRight().getType():null;
1314     TypeDescriptor lefttype=null;
1315     TypeDescriptor righttype=null;
1316     Operation op=on.getOp();
1317
1318     switch(op.getOp()) {
1319     case Operation.LOGIC_OR:
1320     case Operation.LOGIC_AND:
1321       if (!(rtd.isBoolean()))
1322         throw new Error();
1323       on.setRightType(rtd);
1324
1325     case Operation.LOGIC_NOT:
1326       if (!(ltd.isBoolean()))
1327         throw new Error();
1328       //no promotion
1329       on.setLeftType(ltd);
1330
1331       on.setType(new TypeDescriptor(TypeDescriptor.BOOLEAN));
1332       break;
1333
1334     case Operation.COMP:
1335       // 5.6.2 Binary Numeric Promotion
1336       //TODO unboxing of reference objects
1337       if (ltd.isDouble())
1338         throw new Error();
1339       else if (ltd.isFloat())
1340         throw new Error();
1341       else if (ltd.isLong())
1342         lefttype=new TypeDescriptor(TypeDescriptor.LONG);
1343       else
1344         lefttype=new TypeDescriptor(TypeDescriptor.INT);
1345       on.setLeftType(lefttype);
1346       on.setType(lefttype);
1347       break;
1348
1349     case Operation.BIT_OR:
1350     case Operation.BIT_XOR:
1351     case Operation.BIT_AND:
1352       // 5.6.2 Binary Numeric Promotion
1353       //TODO unboxing of reference objects
1354       if (ltd.isDouble()||rtd.isDouble())
1355         throw new Error();
1356       else if (ltd.isFloat()||rtd.isFloat())
1357         throw new Error();
1358       else if (ltd.isLong()||rtd.isLong())
1359         lefttype=new TypeDescriptor(TypeDescriptor.LONG);
1360       // 090205 hack for boolean
1361       else if (ltd.isBoolean()||rtd.isBoolean())
1362         lefttype=new TypeDescriptor(TypeDescriptor.BOOLEAN);
1363       else
1364         lefttype=new TypeDescriptor(TypeDescriptor.INT);
1365       righttype=lefttype;
1366
1367       on.setLeftType(lefttype);
1368       on.setRightType(righttype);
1369       on.setType(lefttype);
1370       break;
1371
1372     case Operation.ISAVAILABLE:
1373       if (!(ltd.isPtr())) {
1374         throw new Error("Can't use isavailable on non-pointers/non-parameters.");
1375       }
1376       lefttype=ltd;
1377       on.setLeftType(lefttype);
1378       on.setType(new TypeDescriptor(TypeDescriptor.BOOLEAN));
1379       break;
1380
1381     case Operation.EQUAL:
1382     case Operation.NOTEQUAL:
1383       // 5.6.2 Binary Numeric Promotion
1384       //TODO unboxing of reference objects
1385       if (ltd.isBoolean()||rtd.isBoolean()) {
1386         if (!(ltd.isBoolean()&&rtd.isBoolean()))
1387           throw new Error();
1388         righttype=lefttype=new TypeDescriptor(TypeDescriptor.BOOLEAN);
1389       } else if (ltd.isPtr()||rtd.isPtr()) {
1390         if (!(ltd.isPtr()&&rtd.isPtr())) {
1391           if(!rtd.isEnum()) {
1392             throw new Error();
1393           }
1394         }
1395         righttype=rtd;
1396         lefttype=ltd;
1397       } else if (ltd.isDouble()||rtd.isDouble())
1398         righttype=lefttype=new TypeDescriptor(TypeDescriptor.DOUBLE);
1399       else if (ltd.isFloat()||rtd.isFloat())
1400         righttype=lefttype=new TypeDescriptor(TypeDescriptor.FLOAT);
1401       else if (ltd.isLong()||rtd.isLong())
1402         righttype=lefttype=new TypeDescriptor(TypeDescriptor.LONG);
1403       else
1404         righttype=lefttype=new TypeDescriptor(TypeDescriptor.INT);
1405
1406       on.setLeftType(lefttype);
1407       on.setRightType(righttype);
1408       on.setType(new TypeDescriptor(TypeDescriptor.BOOLEAN));
1409       break;
1410
1411
1412
1413     case Operation.LT:
1414     case Operation.GT:
1415     case Operation.LTE:
1416     case Operation.GTE:
1417       // 5.6.2 Binary Numeric Promotion
1418       //TODO unboxing of reference objects
1419       if (!ltd.isNumber()||!rtd.isNumber()) {
1420         if (!ltd.isNumber())
1421           throw new Error("Leftside is not number"+on.printNode(0)+"type="+ltd.toPrettyString());
1422         if (!rtd.isNumber())
1423           throw new Error("Rightside is not number"+on.printNode(0));
1424       }
1425
1426       if (ltd.isDouble()||rtd.isDouble())
1427         lefttype=new TypeDescriptor(TypeDescriptor.DOUBLE);
1428       else if (ltd.isFloat()||rtd.isFloat())
1429         lefttype=new TypeDescriptor(TypeDescriptor.FLOAT);
1430       else if (ltd.isLong()||rtd.isLong())
1431         lefttype=new TypeDescriptor(TypeDescriptor.LONG);
1432       else
1433         lefttype=new TypeDescriptor(TypeDescriptor.INT);
1434       righttype=lefttype;
1435       on.setLeftType(lefttype);
1436       on.setRightType(righttype);
1437       on.setType(new TypeDescriptor(TypeDescriptor.BOOLEAN));
1438       break;
1439
1440     case Operation.ADD:
1441       if (ltd.isString()||rtd.isString()) {
1442         ClassDescriptor stringcl=getClass(null, TypeUtil.StringClass);
1443         TypeDescriptor stringtd=new TypeDescriptor(stringcl);
1444         NameDescriptor nd=new NameDescriptor("String");
1445         NameDescriptor valuend=new NameDescriptor(nd, "valueOf");
1446         if (!(ltd.isString()&&(on.getLeft() instanceof OpNode))) {
1447           MethodInvokeNode leftmin=new MethodInvokeNode(valuend);
1448           leftmin.setNumLine(on.getLeft().getNumLine());
1449           leftmin.addArgument(on.getLeft());
1450           on.left=leftmin;
1451           checkExpressionNode(md, nametable, on.getLeft(), null);
1452         }
1453
1454         if (!(rtd.isString()&&(on.getRight() instanceof OpNode))) {
1455           MethodInvokeNode rightmin=new MethodInvokeNode(valuend);
1456           rightmin.setNumLine(on.getRight().getNumLine());
1457           rightmin.addArgument(on.getRight());
1458           on.right=rightmin;
1459           checkExpressionNode(md, nametable, on.getRight(), null);
1460         }
1461
1462         on.setLeftType(stringtd);
1463         on.setRightType(stringtd);
1464         on.setType(stringtd);
1465         break;
1466       }
1467
1468     case Operation.SUB:
1469     case Operation.MULT:
1470     case Operation.DIV:
1471     case Operation.MOD:
1472       // 5.6.2 Binary Numeric Promotion
1473       //TODO unboxing of reference objects
1474       if (ltd.isArray()||rtd.isArray()||!ltd.isNumber()||!rtd.isNumber())
1475         throw new Error("Error in "+on.printNode(0));
1476
1477       if (ltd.isDouble()||rtd.isDouble())
1478         lefttype=new TypeDescriptor(TypeDescriptor.DOUBLE);
1479       else if (ltd.isFloat()||rtd.isFloat())
1480         lefttype=new TypeDescriptor(TypeDescriptor.FLOAT);
1481       else if (ltd.isLong()||rtd.isLong())
1482         lefttype=new TypeDescriptor(TypeDescriptor.LONG);
1483       else
1484         lefttype=new TypeDescriptor(TypeDescriptor.INT);
1485       righttype=lefttype;
1486       on.setLeftType(lefttype);
1487       on.setRightType(righttype);
1488       on.setType(lefttype);
1489       break;
1490
1491     case Operation.LEFTSHIFT:
1492     case Operation.RIGHTSHIFT:
1493     case Operation.URIGHTSHIFT:
1494       if (!rtd.isIntegerType())
1495         throw new Error();
1496       //5.6.1 Unary Numeric Promotion
1497       if (rtd.isByte()||rtd.isShort()||rtd.isInt())
1498         righttype=new TypeDescriptor(TypeDescriptor.INT);
1499       else
1500         righttype=rtd;
1501
1502       on.setRightType(righttype);
1503       if (!ltd.isIntegerType())
1504         throw new Error();
1505
1506     case Operation.UNARYPLUS:
1507     case Operation.UNARYMINUS:
1508       /*        case Operation.POSTINC:
1509           case Operation.POSTDEC:
1510           case Operation.PREINC:
1511           case Operation.PREDEC:*/
1512       if (!ltd.isNumber())
1513         throw new Error();
1514       //5.6.1 Unary Numeric Promotion
1515       if (ltd.isByte()||ltd.isShort()||ltd.isInt())
1516         lefttype=new TypeDescriptor(TypeDescriptor.INT);
1517       else
1518         lefttype=ltd;
1519       on.setLeftType(lefttype);
1520       on.setType(lefttype);
1521       break;
1522
1523     default:
1524       throw new Error(op.toString());
1525     }
1526
1527     if (td!=null)
1528       if (!typeutil.isSuperorType(td, on.getType())) {
1529         System.out.println(td);
1530         System.out.println(on.getType());
1531         throw new Error("Type of rside not compatible with type of lside"+on.printNode(0));
1532       }
1533   }
1534
1535 }