7 public class SemanticCheck {
12 HashMap<ClassDescriptor, Integer> completed;
13 HashMap<ClassDescriptor, Vector<VarDescriptor>> inlineClass2LiveVars;
14 boolean trialcheck = false;
16 public static final int NOCHECK=0;
17 public static final int REFERENCE=1;
18 public static final int INIT=2;
22 public boolean hasLayout(ClassDescriptor cd) {
23 return completed.get(cd)!=null&&completed.get(cd)==INIT;
26 public SemanticCheck(State state, TypeUtil tu) {
27 this(state, tu, true);
30 public SemanticCheck(State state, TypeUtil tu, boolean checkAll) {
33 this.loopstack=new Stack();
34 this.toanalyze=new HashSet();
35 this.completed=new HashMap<ClassDescriptor, Integer>();
36 this.checkAll=checkAll;
37 this.inlineClass2LiveVars = new HashMap<ClassDescriptor, Vector<VarDescriptor>>();
40 public ClassDescriptor getClass(ClassDescriptor context, String classname) {
41 return getClass(context, classname, INIT);
43 public ClassDescriptor getClass(ClassDescriptor context, String classnameIn, int fullcheck) {
44 ClassDescriptor cd=typeutil.getClass(context, classnameIn, toanalyze);
45 checkClass(cd, fullcheck);
49 public void checkClass(ClassDescriptor cd) {
53 public void checkClass(ClassDescriptor cd, int fullcheck) {
54 if (!completed.containsKey(cd)||completed.get(cd)<fullcheck) {
55 int oldstatus=completed.containsKey(cd)?completed.get(cd):0;
56 completed.put(cd, fullcheck);
58 if (fullcheck>=REFERENCE&&oldstatus<INIT) {
59 //Set superclass link up
60 if (cd.getSuper()!=null) {
61 ClassDescriptor superdesc=getClass(cd, cd.getSuper(), fullcheck);
62 if (superdesc.isInnerClass()) {
65 if (superdesc.isInterface()) {
68 cd.getSuperInterface().add(superdesc.getSymbol());
70 throw new Error("Error! Class " + cd.getSymbol() + " extends interface " + cd.getSuper());
73 cd.setSuperDesc(superdesc);
75 // Link together Field, Method, and Flag tables so classes
76 // inherit these from their superclasses
77 if (oldstatus<REFERENCE) {
78 cd.getFieldTable().setParent(cd.getSuperDesc().getFieldTable());
79 cd.getMethodTable().setParent(cd.getSuperDesc().getMethodTable());
80 cd.getFlagTable().setParent(cd.getSuperDesc().getFlagTable());
84 // Link together Field, Method tables do classes inherit these from
85 // their ancestor interfaces
86 Vector<String> sifv = cd.getSuperInterface();
87 for(int i = 0; i < sifv.size(); i++) {
88 ClassDescriptor superif = getClass(cd, sifv.elementAt(i), fullcheck);
89 if(!superif.isInterface()) {
90 throw new Error("Error! Class " + cd.getSymbol() + " implements non-interface " + superif.getSymbol());
92 if (oldstatus<REFERENCE) {
93 cd.addSuperInterfaces(superif);
94 cd.getMethodTable().addParentIF(superif.getMethodTable());
95 cd.getFieldTable().addParentIF(superif.getFieldTable());
99 if (oldstatus<INIT&&fullcheck>=INIT) {
100 /* Check to see that fields are well typed */
101 for(Iterator field_it=cd.getFields(); field_it.hasNext(); ) {
102 FieldDescriptor fd=(FieldDescriptor)field_it.next();
106 System.out.println("Class/Field in "+cd+":"+fd);
110 for(Iterator method_it=cd.getMethods(); method_it.hasNext(); ) {
111 MethodDescriptor md=(MethodDescriptor)method_it.next();
115 System.out.println("Class/Method in "+cd+":"+md);
123 public void semanticCheckClass(ClassDescriptor cd) {
124 // need to initialize typeutil object here...only place we can
125 // get class descriptors without first calling getclass
126 getClass(cd, cd.getSymbol());
129 // for inline defined anonymous classes, we need to check its
130 // surrounding class first to get its surrounding context
131 ClassDescriptor surroundingcd = cd.getSurroundingDesc();
132 if(toanalyze.contains(surroundingcd)) {
133 toanalyze.remove(surroundingcd);
134 semanticCheckClass(surroundingcd);
138 for (Iterator method_it = cd.getMethods(); method_it.hasNext(); ) {
139 MethodDescriptor md = (MethodDescriptor) method_it.next();
141 checkMethodBody(cd, md);
143 System.out.println("Error in " + md);
149 public void semanticCheck() {
150 SymbolTable classtable = state.getClassSymbolTable();
151 toanalyze.addAll(classtable.getValueSet());
152 toanalyze.addAll(state.getTaskSymbolTable().getValueSet());
155 while (!toanalyze.isEmpty()) {
156 Object obj = toanalyze.iterator().next();
157 if (obj instanceof TaskDescriptor) {
158 toanalyze.remove(obj);
159 TaskDescriptor td = (TaskDescriptor) obj;
163 System.out.println("Error in " + td);
167 ClassDescriptor cd = (ClassDescriptor) obj;
168 toanalyze.remove(cd);
169 semanticCheckClass(cd);
174 private void checkTypeDescriptor(ClassDescriptor cd, TypeDescriptor td) {
175 if (td.isPrimitive())
177 else if (td.isClass()) {
178 String name=td.toString();
179 ClassDescriptor field_cd=checkAll?getClass(cd, name):getClass(cd, name, REFERENCE);
182 throw new Error("Undefined class "+name);
183 td.setClassDescriptor(field_cd);
185 } else if (td.isTag())
191 public void checkField(ClassDescriptor cd, FieldDescriptor fd) {
192 checkTypeDescriptor(cd, fd.getType());
195 public void checkConstraintCheck(TaskDescriptor td, SymbolTable nametable, Vector ccs) {
197 return; /* No constraint checks to check */
198 for(int i=0; i<ccs.size(); i++) {
199 ConstraintCheck cc=(ConstraintCheck) ccs.get(i);
201 for(int j=0; j<cc.numArgs(); j++) {
202 ExpressionNode en=cc.getArg(j);
203 checkExpressionNode(td,nametable,en,null);
208 public void checkFlagEffects(TaskDescriptor td, Vector vfe, SymbolTable nametable) {
210 return; /* No flag effects to check */
211 for(int i=0; i<vfe.size(); i++) {
212 FlagEffects fe=(FlagEffects) vfe.get(i);
213 String varname=fe.getName();
214 //Make sure the variable is declared as a parameter to the task
215 VarDescriptor vd=(VarDescriptor)td.getParameterTable().get(varname);
217 throw new Error("Parameter "+varname+" in Flag Effects not declared in "+td);
220 //Make sure it correspods to a class
221 TypeDescriptor type_d=vd.getType();
222 if (!type_d.isClass())
223 throw new Error("Cannot have non-object argument for flag_effect");
225 ClassDescriptor cd=type_d.getClassDesc();
226 for(int j=0; j<fe.numEffects(); j++) {
227 FlagEffect flag=fe.getEffect(j);
228 String name=flag.getName();
229 FlagDescriptor flag_d=(FlagDescriptor)cd.getFlagTable().get(name);
230 //Make sure the flag is declared
232 throw new Error("Flag descriptor "+name+" undefined in class: "+cd.getSymbol());
233 if (flag_d.getExternal())
234 throw new Error("Attempting to modify external flag: "+name);
235 flag.setFlag(flag_d);
237 for(int j=0; j<fe.numTagEffects(); j++) {
238 TagEffect tag=fe.getTagEffect(j);
239 String name=tag.getName();
241 Descriptor d=(Descriptor)nametable.get(name);
243 throw new Error("Tag descriptor "+name+" undeclared");
244 else if (!(d instanceof TagVarDescriptor))
245 throw new Error(name+" is not a tag descriptor");
246 tag.setTag((TagVarDescriptor)d);
251 public void checkTask(TaskDescriptor td) {
252 for(int i=0; i<td.numParameters(); i++) {
253 /* Check that parameter is well typed */
254 TypeDescriptor param_type=td.getParamType(i);
255 checkTypeDescriptor(null, param_type);
257 /* Check the parameter's flag expression is well formed */
258 FlagExpressionNode fen=td.getFlag(td.getParameter(i));
259 if (!param_type.isClass())
260 throw new Error("Cannot have non-object argument to a task");
261 ClassDescriptor cd=param_type.getClassDesc();
263 checkFlagExpressionNode(cd, fen);
266 checkFlagEffects(td, td.getFlagEffects(),td.getParameterTable());
267 /* Check that the task code is valid */
268 BlockNode bn=state.getMethodBody(td);
269 checkBlockNode(td, td.getParameterTable(),bn);
272 public void checkFlagExpressionNode(ClassDescriptor cd, FlagExpressionNode fen) {
274 case Kind.FlagOpNode:
276 FlagOpNode fon=(FlagOpNode)fen;
277 checkFlagExpressionNode(cd, fon.getLeft());
278 if (fon.getRight()!=null)
279 checkFlagExpressionNode(cd, fon.getRight());
285 FlagNode fn=(FlagNode)fen;
286 String name=fn.getFlagName();
287 FlagDescriptor fd=(FlagDescriptor)cd.getFlagTable().get(name);
289 throw new Error("Undeclared flag: "+name);
295 throw new Error("Unrecognized FlagExpressionNode");
299 public void checkMethod(ClassDescriptor cd, MethodDescriptor md) {
300 /* Check for abstract methods */
301 if(md.isAbstract()) {
302 if(!cd.isAbstract() && !cd.isInterface()) {
303 throw new Error("Error! The non-abstract Class " + cd.getSymbol() + " contains an abstract method " + md.getSymbol());
307 /* Check return type */
308 if (!md.isConstructor() && !md.isStaticBlock())
309 if (!md.getReturnType().isVoid()) {
310 checkTypeDescriptor(cd, md.getReturnType());
312 for(int i=0; i<md.numParameters(); i++) {
313 TypeDescriptor param_type=md.getParamType(i);
314 checkTypeDescriptor(cd, param_type);
316 /* Link the naming environments */
317 if (!md.isStatic()) /* Fields aren't accessible directly in a static method, so don't link in this table */
318 md.getParameterTable().setParent(cd.getFieldTable());
320 if (!md.isStatic()) {
321 VarDescriptor thisvd=new VarDescriptor(new TypeDescriptor(cd),"this");
324 if(md.isDefaultConstructor() && (cd.getSuperDesc() != null) && !cd.getInline()) {
325 // add the construction of it super class, can only be super()
326 // NOTE: inline class should be treated differently
327 NameDescriptor nd=new NameDescriptor("super");
328 MethodInvokeNode min=new MethodInvokeNode(nd);
329 BlockExpressionNode ben=new BlockExpressionNode(min);
330 BlockNode bn = state.getMethodBody(md);
331 bn.addFirstBlockStatement(ben);
335 public void checkMethodBody(ClassDescriptor cd, MethodDescriptor md) {
336 ClassDescriptor superdesc=cd.getSuperDesc();
337 // for inline classes, it has done this during trial check
338 if ((!cd.getInline() || this.trialcheck) && (superdesc!=null)) {
339 Set possiblematches=superdesc.getMethodTable().getSet(md.getSymbol());
340 for(Iterator methodit=possiblematches.iterator(); methodit.hasNext(); ) {
341 MethodDescriptor matchmd=(MethodDescriptor)methodit.next();
342 if (md.matches(matchmd)) {
343 if (matchmd.getModifiers().isFinal()) {
344 throw new Error("Try to override final method in method:"+md+" declared in "+cd);
349 BlockNode bn=state.getMethodBody(md);
350 checkBlockNode(md, md.getParameterTable(),bn);
353 public void checkBlockNode(Descriptor md, SymbolTable nametable, BlockNode bn) {
354 /* Link in the naming environment */
355 bn.getVarTable().setParent(nametable);
356 for(int i=0; i<bn.size(); i++) {
357 BlockStatementNode bsn=bn.get(i);
358 checkBlockStatementNode(md, bn.getVarTable(),bsn);
362 public void checkBlockStatementNode(Descriptor md, SymbolTable nametable, BlockStatementNode bsn) {
364 case Kind.BlockExpressionNode:
365 checkBlockExpressionNode(md, nametable,(BlockExpressionNode)bsn);
368 case Kind.DeclarationNode:
369 checkDeclarationNode(md, nametable, (DeclarationNode)bsn);
372 case Kind.TagDeclarationNode:
373 checkTagDeclarationNode(md, nametable, (TagDeclarationNode)bsn);
376 case Kind.IfStatementNode:
377 checkIfStatementNode(md, nametable, (IfStatementNode)bsn);
380 case Kind.SwitchStatementNode:
381 checkSwitchStatementNode(md, nametable, (SwitchStatementNode)bsn);
385 checkLoopNode(md, nametable, (LoopNode)bsn);
388 case Kind.ReturnNode:
389 checkReturnNode(md, nametable, (ReturnNode)bsn);
392 case Kind.TaskExitNode:
393 checkTaskExitNode(md, nametable, (TaskExitNode)bsn);
396 case Kind.SubBlockNode:
397 checkSubBlockNode(md, nametable, (SubBlockNode)bsn);
400 case Kind.AtomicNode:
401 checkAtomicNode(md, nametable, (AtomicNode)bsn);
404 case Kind.SynchronizedNode:
405 checkSynchronizedNode(md, nametable, (SynchronizedNode)bsn);
408 case Kind.ContinueBreakNode:
409 checkContinueBreakNode(md, nametable, (ContinueBreakNode) bsn);
413 case Kind.GenReachNode:
414 case Kind.GenDefReachNode:
415 // do nothing, no semantic check for SESEs
422 void checkBlockExpressionNode(Descriptor md, SymbolTable nametable, BlockExpressionNode ben) {
423 checkExpressionNode(md, nametable, ben.getExpression(), null);
426 void checkDeclarationNode(Descriptor md, SymbolTable nametable, DeclarationNode dn) {
427 VarDescriptor vd=dn.getVarDescriptor();
428 checkTypeDescriptor(((md instanceof MethodDescriptor)?((MethodDescriptor)md).getClassDesc():null), vd.getType());
429 Descriptor d=nametable.get(vd.getSymbol());
431 (d instanceof FieldDescriptor)) {
433 } else if((md instanceof MethodDescriptor) && (((MethodDescriptor)md).getClassDesc().getInline()) && !this.trialcheck) {
434 // for inline classes, the var has been checked during trial check and added into the nametable
436 throw new Error(vd.getSymbol()+" in "+md+" defined a second time");
437 if (dn.getExpression()!=null)
438 checkExpressionNode(md, nametable, dn.getExpression(), vd.getType());
441 void checkTagDeclarationNode(Descriptor md, SymbolTable nametable, TagDeclarationNode dn) {
442 TagVarDescriptor vd=dn.getTagVarDescriptor();
443 Descriptor d=nametable.get(vd.getSymbol());
445 (d instanceof FieldDescriptor)) {
447 } else if((md instanceof MethodDescriptor) && (((MethodDescriptor)md).getClassDesc().getInline()) && !this.trialcheck) {
448 // for inline classes, the var has been checked during trial check and added into the nametable
450 throw new Error(vd.getSymbol()+" defined a second time");
453 void checkSubBlockNode(Descriptor md, SymbolTable nametable, SubBlockNode sbn) {
454 checkBlockNode(md, nametable, sbn.getBlockNode());
457 void checkAtomicNode(Descriptor md, SymbolTable nametable, AtomicNode sbn) {
458 checkBlockNode(md, nametable, sbn.getBlockNode());
461 void checkSynchronizedNode(Descriptor md, SymbolTable nametable, SynchronizedNode sbn) {
462 checkBlockNode(md, nametable, sbn.getBlockNode());
463 //todo this could be Object
464 checkExpressionNode(md, nametable, sbn.getExpr(), null);
467 void checkContinueBreakNode(Descriptor md, SymbolTable nametable, ContinueBreakNode cbn) {
468 if (loopstack.empty())
469 throw new Error("continue/break outside of loop");
470 Object o = loopstack.peek();
471 if(o instanceof LoopNode) {
472 LoopNode ln=(LoopNode)o;
477 void checkReturnNode(Descriptor d, SymbolTable nametable, ReturnNode rn) {
478 if (d instanceof TaskDescriptor)
479 throw new Error("Illegal return appears in Task: "+d.getSymbol());
480 MethodDescriptor md=(MethodDescriptor)d;
481 if (rn.getReturnExpression()!=null)
482 if (md.getReturnType()==null)
483 throw new Error("Constructor can't return something.");
484 else if (md.getReturnType().isVoid())
485 throw new Error(md+" is void");
487 checkExpressionNode(md, nametable, rn.getReturnExpression(), md.getReturnType());
489 if (md.getReturnType()!=null&&!md.getReturnType().isVoid())
490 throw new Error("Need to return something for "+md);
493 void checkTaskExitNode(Descriptor md, SymbolTable nametable, TaskExitNode ten) {
494 if (md instanceof MethodDescriptor)
495 throw new Error("Illegal taskexit appears in Method: "+md.getSymbol());
496 checkFlagEffects((TaskDescriptor)md, ten.getFlagEffects(),nametable);
497 checkConstraintCheck((TaskDescriptor) md, nametable, ten.getChecks());
500 void checkIfStatementNode(Descriptor md, SymbolTable nametable, IfStatementNode isn) {
501 checkExpressionNode(md, nametable, isn.getCondition(), new TypeDescriptor(TypeDescriptor.BOOLEAN));
502 checkBlockNode(md, nametable, isn.getTrueBlock());
503 if (isn.getFalseBlock()!=null)
504 checkBlockNode(md, nametable, isn.getFalseBlock());
507 void checkSwitchStatementNode(Descriptor md, SymbolTable nametable, SwitchStatementNode ssn) {
508 checkExpressionNode(md, nametable, ssn.getCondition(), new TypeDescriptor(TypeDescriptor.INT));
510 BlockNode sbn = ssn.getSwitchBody();
511 boolean hasdefault = false;
512 for(int i = 0; i < sbn.size(); i++) {
513 boolean containdefault = checkSwitchBlockNode(md, nametable, (SwitchBlockNode)sbn.get(i));
514 if(hasdefault && containdefault) {
515 throw new Error("Error: duplicate default branch in switch-case statement in Method: " + md.getSymbol());
517 hasdefault = containdefault;
521 boolean checkSwitchBlockNode(Descriptor md, SymbolTable nametable, SwitchBlockNode sbn) {
522 Vector<SwitchLabelNode> slnv = sbn.getSwitchConditions();
524 for(int i = 0; i < slnv.size(); i++) {
525 if(slnv.elementAt(i).isdefault) {
528 checkConstantExpressionNode(md, nametable, slnv.elementAt(i).getCondition(), new TypeDescriptor(TypeDescriptor.INT));
532 throw new Error("Error: duplicate default branch in switch-case statement in Method: " + md.getSymbol());
535 checkBlockNode(md, nametable, sbn.getSwitchBlockStatement());
537 return (defaultb > 0);
541 void checkConstantExpressionNode(Descriptor md, SymbolTable nametable, ExpressionNode en, TypeDescriptor td) {
543 case Kind.FieldAccessNode:
544 checkFieldAccessNode(md,nametable,(FieldAccessNode)en,td);
547 case Kind.LiteralNode:
548 checkLiteralNode(md,nametable,(LiteralNode)en,td);
552 checkNameNode(md,nametable,(NameNode)en,td);
556 checkOpNode(md, nametable, (OpNode)en, td);
562 void checkExpressionNode(Descriptor md, SymbolTable nametable, ExpressionNode en, TypeDescriptor td) {
564 case Kind.AssignmentNode:
565 checkAssignmentNode(md,nametable,(AssignmentNode)en,td);
569 checkCastNode(md,nametable,(CastNode)en,td);
572 case Kind.CreateObjectNode:
573 checkCreateObjectNode(md,nametable,(CreateObjectNode)en,td);
576 case Kind.FieldAccessNode:
577 checkFieldAccessNode(md,nametable,(FieldAccessNode)en,td);
580 case Kind.ArrayAccessNode:
581 checkArrayAccessNode(md,nametable,(ArrayAccessNode)en,td);
584 case Kind.LiteralNode:
585 checkLiteralNode(md,nametable,(LiteralNode)en,td);
588 case Kind.MethodInvokeNode:
589 checkMethodInvokeNode(md,nametable,(MethodInvokeNode)en,td);
593 checkNameNode(md,nametable,(NameNode)en,td);
597 checkOpNode(md,nametable,(OpNode)en,td);
600 case Kind.OffsetNode:
601 checkOffsetNode(md, nametable, (OffsetNode)en, td);
604 case Kind.TertiaryNode:
605 checkTertiaryNode(md, nametable, (TertiaryNode)en, td);
608 case Kind.InstanceOfNode:
609 checkInstanceOfNode(md, nametable, (InstanceOfNode) en, td);
612 case Kind.ArrayInitializerNode:
613 checkArrayInitializerNode(md, nametable, (ArrayInitializerNode) en, td);
616 case Kind.ClassTypeNode:
617 checkClassTypeNode(md, nametable, (ClassTypeNode) en, td);
623 void checkClassTypeNode(Descriptor md, SymbolTable nametable, ClassTypeNode tn, TypeDescriptor td) {
624 checkTypeDescriptor(((md instanceof MethodDescriptor)?((MethodDescriptor)md).getClassDesc():null), tn.getType());
627 void checkCastNode(Descriptor md, SymbolTable nametable, CastNode cn, TypeDescriptor td) {
628 /* Get type descriptor */
629 if (cn.getType()==null) {
630 NameDescriptor typenamed=cn.getTypeName().getName();
631 TypeDescriptor ntd=new TypeDescriptor(getClass(((md instanceof MethodDescriptor)?((MethodDescriptor)md).getClassDesc():null), typenamed.toString()));
635 /* Check the type descriptor */
636 TypeDescriptor cast_type=cn.getType();
637 checkTypeDescriptor(((md instanceof MethodDescriptor)?((MethodDescriptor)md).getClassDesc():null),cast_type);
641 if (!typeutil.isSuperorType(td,cast_type))
642 throw new Error("Cast node returns "+cast_type+", but need "+td);
645 ExpressionNode en=cn.getExpression();
646 checkExpressionNode(md, nametable, en, null);
647 TypeDescriptor etd=en.getType();
648 if (typeutil.isSuperorType(cast_type,etd)) /* Cast trivially succeeds */
651 if (typeutil.isSuperorType(etd,cast_type)) /* Cast may succeed */
653 if (typeutil.isCastable(etd, cast_type))
656 //rough hack to handle interfaces...should clean up
657 if (etd.isClass()&&cast_type.isClass()) {
658 ClassDescriptor cdetd=etd.getClassDesc();
659 ClassDescriptor cdcast_type=cast_type.getClassDesc();
661 if (cdetd.isInterface()&&!cdcast_type.getModifier().isFinal())
664 if (cdcast_type.isInterface()&&!cdetd.getModifier().isFinal())
667 /* Different branches */
668 /* TODO: change if add interfaces */
669 throw new Error("Cast will always fail\n"+cn.printNode(0));
672 //FieldDescriptor checkFieldAccessNodeForParentNode( Descriptor md, SymbolTable na )
673 void checkFieldAccessNode(Descriptor md, SymbolTable nametable, FieldAccessNode fan, TypeDescriptor td) {
674 ExpressionNode left=fan.getExpression();
675 checkExpressionNode(md,nametable,left,null);
676 TypeDescriptor ltd=left.getType();
678 checkClass(ltd.getClassDesc(), INIT);
679 String fieldname=fan.getFieldName();
681 FieldDescriptor fd=null;
682 if (ltd.isArray()&&fieldname.equals("length"))
683 fd=FieldDescriptor.arrayLength;
684 else if(((left instanceof NameNode) && ((NameNode)left).isSuper())
685 ||((left instanceof FieldAccessNode) && ((FieldAccessNode)left).isSuper())){
686 fd = (FieldDescriptor) ltd.getClassDesc().getSuperDesc().getFieldTable().get(fieldname);
688 fd=(FieldDescriptor) ltd.getClassDesc().getFieldTable().get(fieldname);
690 if(ltd.isClassNameRef()) {
691 // the field access is using a class name directly
693 // check if it is to access a surrounding class in an inner class
694 if(fieldname.equals("this") || fieldname.equals("super")) {
695 ClassDescriptor icd = ((VarDescriptor)nametable.get("this")).getType().getClassDesc();
696 if(icd.isInnerClass()) {
697 NameNode nn = new NameNode(new NameDescriptor("this"));
698 nn.setVar((VarDescriptor)nametable.get("this"));
699 fan.setExpression(nn);
700 if(icd.getSurroundingDesc()==ltd.getClassDesc()) {
701 // this is a surrounding class access inside an inner class
702 fan.setExpression(nn);
703 fan.setFieldName("this$0");
704 fd = (FieldDescriptor)icd.getFieldTable().get("this$0");
705 } else if(icd==ltd.getClassDesc()) {
706 // this is an inner class this operation
707 fd = new FieldDescriptor(new Modifiers(),new TypeDescriptor(icd),"this",null,false);
709 if(fieldname.equals("super")) {
716 ClassDescriptor surroundingCls=ltd.getClassDesc().getSurroundingDesc();
718 while(surroundingCls!=null) {
719 fd=(FieldDescriptor) surroundingCls.getFieldTable().get(fieldname);
721 fan.left=new ClassTypeNode(new TypeDescriptor(surroundingCls));
724 surroundingCls=surroundingCls.getSurroundingDesc();
728 if(ltd.getClassDesc().isEnum()) {
729 int value = ltd.getClassDesc().getEnumConstant(fieldname);
731 // check if this field is an enum constant
732 throw new Error(fieldname + " is not an enum constant in "+fan.printNode(0)+" in "+md);
734 fd = new FieldDescriptor(new Modifiers(Modifiers.PUBLIC|Modifiers.FINAL), new TypeDescriptor(TypeDescriptor.INT), fieldname, null, false);
736 fd.setEnumValue(value);
737 } else if(fd == null) {
738 throw new Error("Could not find field "+ fieldname + " in "+fan.printNode(0)+" in "+md + " (Line: "+fan.getNumLine()+")");
739 } else if(fd.isStatic()) {
740 // check if this field is a static field
741 if(fd.getExpressionNode() != null) {
742 checkExpressionNode(md,nametable,fd.getExpressionNode(),null);
745 throw new Error("Dereference of the non-static field "+ fieldname + " in "+fan.printNode(0)+" in "+md);
750 if((md instanceof MethodDescriptor) && false == ((MethodDescriptor)md).isStaticBlock()) {
751 ClassDescriptor cd = ((MethodDescriptor)md).getClassDesc();
752 FieldAccessNode theFieldNode = fieldAccessExpression( cd, fieldname, fan.getNumLine() );
753 if( null != theFieldNode ) {
754 //fan = theFieldNode;
755 checkFieldAccessNode( md, nametable, theFieldNode, td );
756 fan.setField( theFieldNode.getField() );
757 fan.setExpression( theFieldNode.getExpression() );
758 //TypeDescriptor td1 = fan.getType();
763 throw new Error("Unknown field "+fieldname + " in "+fan.printNode(0)+" in "+md);
766 if (fd.getType().iswrapper()) {
767 FieldAccessNode fan2=new FieldAccessNode(left, fieldname);
768 fan2.setNumLine(left.getNumLine());
771 fan.fieldname="value";
773 ExpressionNode leftwr=fan.getExpression();
774 TypeDescriptor ltdwr=leftwr.getType();
775 String fieldnamewr=fan.getFieldName();
776 FieldDescriptor fdwr=(FieldDescriptor) ltdwr.getClassDesc().getFieldTable().get(fieldnamewr);
779 throw new Error("Unknown field "+fieldnamewr + " in "+fan.printNode(0)+" in "+md);
784 if (!typeutil.isSuperorType(td,fan.getType()))
785 throw new Error("Field node returns "+fan.getType()+", but need "+td);
789 void checkArrayAccessNode(Descriptor md, SymbolTable nametable, ArrayAccessNode aan, TypeDescriptor td) {
790 ExpressionNode left=aan.getExpression();
791 checkExpressionNode(md,nametable,left,null);
793 checkExpressionNode(md,nametable,aan.getIndex(),new TypeDescriptor(TypeDescriptor.INT));
794 TypeDescriptor ltd=left.getType();
795 if (ltd.dereference().iswrapper()) {
796 aan.wrappertype=((FieldDescriptor)ltd.dereference().getClassDesc().getFieldTable().get("value")).getType();
800 if (!typeutil.isSuperorType(td,aan.getType()))
801 throw new Error("Field node returns "+aan.getType()+", but need "+td);
804 void checkLiteralNode(Descriptor md, SymbolTable nametable, LiteralNode ln, TypeDescriptor td) {
805 /* Resolve the type */
806 Object o=ln.getValue();
807 if (ln.getTypeString().equals("null")) {
808 ln.setType(new TypeDescriptor(TypeDescriptor.NULL));
809 } else if (o instanceof Integer) {
810 ln.setType(new TypeDescriptor(TypeDescriptor.INT));
811 } else if (o instanceof Long) {
812 ln.setType(new TypeDescriptor(TypeDescriptor.LONG));
813 } else if (o instanceof Float) {
814 ln.setType(new TypeDescriptor(TypeDescriptor.FLOAT));
815 } else if (o instanceof Boolean) {
816 ln.setType(new TypeDescriptor(TypeDescriptor.BOOLEAN));
817 } else if (o instanceof Double) {
818 ln.setType(new TypeDescriptor(TypeDescriptor.DOUBLE));
819 } else if (o instanceof Character) {
820 ln.setType(new TypeDescriptor(TypeDescriptor.CHAR));
821 } else if (o instanceof String) {
822 ln.setType(new TypeDescriptor(getClass(null, TypeUtil.StringClass)));
826 if (!typeutil.isSuperorType(td,ln.getType())) {
827 Long l = ln.evaluate();
828 if((ln.getType().isByte() || ln.getType().isShort()
829 || ln.getType().isChar() || ln.getType().isInt())
831 && (td.isByte() || td.isShort() || td.isChar()
832 || td.isInt() || td.isLong())) {
833 long lnvalue = l.longValue();
834 if((td.isByte() && ((lnvalue > 127) || (lnvalue < -128)))
835 || (td.isShort() && ((lnvalue > 32767) || (lnvalue < -32768)))
836 || (td.isChar() && ((lnvalue > 65535) || (lnvalue < 0)))
837 || (td.isInt() && ((lnvalue > 2147483647) || (lnvalue < -2147483648)))
838 || (td.isLong() && ((lnvalue > 9223372036854775807L) || (lnvalue < -9223372036854775808L)))) {
839 throw new Error("Field node returns "+ln.getType()+", but need "+td+" in "+md);
842 throw new Error("Field node returns "+ln.getType()+", but need "+td+" in "+md);
847 FieldDescriptor recurseSurroundingClasses( ClassDescriptor icd, String varname ) {
848 if( null == icd || false == icd.isInnerClass() )
851 ClassDescriptor surroundingDesc = icd.getSurroundingDesc();
852 if( null == surroundingDesc )
855 SymbolTable fieldTable = surroundingDesc.getFieldTable();
856 FieldDescriptor fd = ( FieldDescriptor ) fieldTable.get( varname );
859 return recurseSurroundingClasses( surroundingDesc, varname );
862 FieldAccessNode fieldAccessExpression( ClassDescriptor icd, String varname, int linenum ) {
863 FieldDescriptor fd = recurseSurroundingClasses( icd, varname );
867 ClassDescriptor cd = fd.getClassDescriptor();
869 int startingDepth = icd.getInnerDepth();
871 if( true == cd.isInnerClass() )
872 depth = cd.getInnerDepth();
874 String composed = "this";
875 NameDescriptor runningDesc = new NameDescriptor( "this" );;
877 for ( int index = startingDepth; index > depth; --index ) {
878 composed = "this$" + String.valueOf( index - 1 );
879 runningDesc = new NameDescriptor( runningDesc, composed );
881 if( false == cd.isInnerClass() )
882 runningDesc = new NameDescriptor( runningDesc, "this$" + String.valueOf(0) ); //all the way up.
883 NameDescriptor idDesc = new NameDescriptor( runningDesc, varname );
886 FieldAccessNode theFieldNode = ( FieldAccessNode )translateNameDescriptorintoExpression( idDesc, linenum );
890 void checkNameNode(Descriptor md, SymbolTable nametable, NameNode nn, TypeDescriptor td) {
891 NameDescriptor nd=nn.getName();
892 if (nd.getBase()!=null) {
894 /* Rewrite NameNode */
895 ExpressionNode en=translateNameDescriptorintoExpression(nd,nn.getNumLine());
896 nn.setExpression(en);
897 checkExpressionNode(md,nametable,en,td);
899 String varname=nd.toString();
900 if(varname.equals("this") || varname.equals("super")) {
902 nn.setVar((VarDescriptor)nametable.get("this"));
903 if(varname.equals("super")) {
908 Descriptor d=(Descriptor)nametable.get(varname);
910 ClassDescriptor cd = null;
911 //check the inner class case first.
912 if((md instanceof MethodDescriptor) && false == ((MethodDescriptor)md).isStaticBlock()) {
913 cd = ((MethodDescriptor)md).getClassDesc();
914 FieldAccessNode theFieldNode = fieldAccessExpression( cd, varname, nn.getNumLine() );
915 if( null != theFieldNode ) {
916 nn.setExpression(( ExpressionNode )theFieldNode);
917 checkExpressionNode(md,nametable,( ExpressionNode )theFieldNode,td);
919 } else if(cd.getInline() && (this.trialcheck)) {
920 // for the trial check of an inline class, cache the unknown var
921 d = cd.getSurroundingNameTable().get(varname);
923 if(!this.inlineClass2LiveVars.containsKey(cd)) {
924 this.inlineClass2LiveVars.put(cd, new Vector<VarDescriptor>());
926 Vector<VarDescriptor> vars = this.inlineClass2LiveVars.get(cd);
927 if(!vars.contains((VarDescriptor)d)) {
928 vars.add((VarDescriptor)d);
934 if((md instanceof MethodDescriptor) && ((MethodDescriptor)md).isStaticBlock()) {
935 // this is a static block, all the accessed fields should be static field
936 cd = ((MethodDescriptor)md).getClassDesc();
937 SymbolTable fieldtbl = cd.getFieldTable();
938 FieldDescriptor fd=(FieldDescriptor)fieldtbl.get(varname);
939 if((fd == null) || (!fd.isStatic())) {
940 // no such field in the class, check if this is a class
941 if(varname.equals("this")) {
942 throw new Error("Error: access this obj in a static block");
944 cd=getClass(((md instanceof MethodDescriptor)?((MethodDescriptor)md).getClassDesc():null), varname);
946 // this is a class name
950 throw new Error("Name "+varname+" should not be used in static block: "+md);
953 // this is a static field
959 // check if the var is a static field of the class
960 if(md instanceof MethodDescriptor) {
961 cd = ((MethodDescriptor)md).getClassDesc();
962 FieldDescriptor fd = (FieldDescriptor)cd.getFieldTable().get(varname);
963 if((fd != null) && (fd.isStatic())) {
967 if (!typeutil.isSuperorType(td,nn.getType()))
968 throw new Error("Field node returns "+nn.getType()+", but need "+td);
970 } else if(fd != null) {
971 throw new Error("Name "+varname+" should not be used in " + md);
974 cd=getClass(((md instanceof MethodDescriptor)?((MethodDescriptor)md).getClassDesc():null), varname);
976 // this is a class name
980 throw new Error("Name "+varname+" undefined in: "+md);
986 if (d instanceof VarDescriptor) {
988 } else if (d instanceof FieldDescriptor) {
989 FieldDescriptor fd=(FieldDescriptor)d;
990 if (fd.getType().iswrapper()) {
991 String id=nd.getIdentifier();
992 NameDescriptor base=nd.getBase();
993 NameNode n=new NameNode(nn.getName());
994 n.setNumLine(nn.getNumLine());
996 n.setVar((VarDescriptor)nametable.get("this")); /* Need a pointer to this */
997 FieldAccessNode fan=new FieldAccessNode(n,"value");
998 fan.setNumLine(n.getNumLine());
999 FieldDescriptor fdval=(FieldDescriptor) fd.getType().getClassDesc().getFieldTable().get("value");
1000 fan.setField(fdval);
1001 nn.setExpression(fan);
1004 nn.setVar((VarDescriptor)nametable.get("this")); /* Need a pointer to this */
1006 } else if (d instanceof TagVarDescriptor) {
1008 } else throw new Error("Wrong type of descriptor");
1010 if (!typeutil.isSuperorType(td,nn.getType()))
1011 throw new Error("Field node returns "+nn.getType()+", but need "+td);
1015 void checkOffsetNode(Descriptor md, SymbolTable nameTable, OffsetNode ofn, TypeDescriptor td) {
1016 TypeDescriptor ltd=ofn.td;
1017 checkTypeDescriptor(((md instanceof MethodDescriptor)?((MethodDescriptor)md).getClassDesc():null),ltd);
1019 String fieldname = ofn.fieldname;
1020 FieldDescriptor fd=null;
1021 if (ltd.isArray()&&fieldname.equals("length")) {
1022 fd=FieldDescriptor.arrayLength;
1024 fd=(FieldDescriptor) ltd.getClassDesc().getFieldTable().get(fieldname);
1028 checkField(ltd.getClassDesc(), fd);
1031 throw new Error("Unknown field "+fieldname + " in "+ofn.printNode(1)+" in "+md);
1034 if (!typeutil.isSuperorType(td, ofn.getType())) {
1035 throw new Error("Type of rside not compatible with type of lside"+ofn.printNode(0));
1041 void checkTertiaryNode(Descriptor md, SymbolTable nametable, TertiaryNode tn, TypeDescriptor td) {
1042 checkExpressionNode(md, nametable, tn.getCond(), new TypeDescriptor(TypeDescriptor.BOOLEAN));
1043 checkExpressionNode(md, nametable, tn.getTrueExpr(), td);
1044 checkExpressionNode(md, nametable, tn.getFalseExpr(), td);
1047 void checkInstanceOfNode(Descriptor md, SymbolTable nametable, InstanceOfNode tn, TypeDescriptor td) {
1048 if (td!=null&&!td.isBoolean())
1049 throw new Error("Expecting type "+td+"for instanceof expression");
1051 checkTypeDescriptor(((md instanceof MethodDescriptor)?((MethodDescriptor)md).getClassDesc():null), tn.getExprType());
1052 checkExpressionNode(md, nametable, tn.getExpr(), null);
1055 void checkArrayInitializerNode(Descriptor md, SymbolTable nametable, ArrayInitializerNode ain, TypeDescriptor td) {
1056 Vector<TypeDescriptor> vec_type = new Vector<TypeDescriptor>();
1057 for( int i = 0; i < ain.numVarInitializers(); ++i ) {
1058 checkExpressionNode(md, nametable, ain.getVarInitializer(i), td.dereference());
1059 vec_type.add(ain.getVarInitializer(i).getType());
1067 void checkAssignmentNode(Descriptor md, SymbolTable nametable, AssignmentNode an, TypeDescriptor td) {
1068 boolean postinc=true;
1069 if (an.getOperation().getBaseOp()==null||
1070 (an.getOperation().getBaseOp().getOp()!=Operation.POSTINC&&
1071 an.getOperation().getBaseOp().getOp()!=Operation.POSTDEC))
1074 checkExpressionNode(md, nametable, an.getSrc(),td);
1075 //TODO: Need check on validity of operation here
1076 if (!((an.getDest() instanceof FieldAccessNode)||
1077 (an.getDest() instanceof ArrayAccessNode)||
1078 (an.getDest() instanceof NameNode)))
1079 throw new Error("Bad lside in "+an.printNode(0));
1080 checkExpressionNode(md, nametable, an.getDest(), null);
1082 /* We want parameter variables to tasks to be immutable */
1083 if (md instanceof TaskDescriptor) {
1084 if (an.getDest() instanceof NameNode) {
1085 NameNode nn=(NameNode)an.getDest();
1086 if (nn.getVar()!=null) {
1087 if (((TaskDescriptor)md).getParameterTable().contains(nn.getVar().getSymbol()))
1088 throw new Error("Can't modify parameter "+nn.getVar()+ " to task "+td.getSymbol());
1093 if (an.getDest().getType().isString()&&an.getOperation().getOp()==AssignOperation.PLUSEQ) {
1095 ClassDescriptor stringcl=getClass(null, TypeUtil.StringClass);
1096 TypeDescriptor stringtd=new TypeDescriptor(stringcl);
1097 NameDescriptor nd=new NameDescriptor("String");
1098 NameDescriptor valuend=new NameDescriptor(nd, "valueOf");
1100 if (!(an.getSrc().getType().isString()&&(an.getSrc() instanceof OpNode))) {
1101 MethodInvokeNode rightmin=new MethodInvokeNode(valuend);
1102 rightmin.setNumLine(an.getSrc().getNumLine());
1103 rightmin.addArgument(an.getSrc());
1105 checkExpressionNode(md, nametable, an.getSrc(), null);
1109 if (!postinc&&!typeutil.isSuperorType(an.getDest().getType(),an.getSrc().getType())) {
1110 TypeDescriptor dt = an.getDest().getType();
1111 TypeDescriptor st = an.getSrc().getType();
1112 if(an.getSrc().kind() == Kind.ArrayInitializerNode) {
1113 if(dt.getArrayCount() != st.getArrayCount()) {
1114 throw new Error("Type of rside ("+an.getSrc().getType().toPrettyString()+") not compatible with type of lside ("+an.getDest().getType().toPrettyString()+")"+an.printNode(0));
1117 dt = dt.dereference();
1118 st = st.dereference();
1119 } while(dt.isArray());
1120 if((st.isByte() || st.isShort() || st.isChar() || st.isInt())
1121 && (dt.isByte() || dt.isShort() || dt.isChar() || dt.isInt() || dt.isLong())) {
1124 throw new Error("Type of rside ("+an.getSrc().getType().toPrettyString()+") not compatible with type of lside ("+an.getDest().getType().toPrettyString()+")"+an.printNode(0));
1128 Long l = an.getSrc().evaluate();
1129 if((st.isByte() || st.isShort() || st.isChar() || st.isInt())
1131 && (dt.isByte() || dt.isShort() || dt.isChar() || dt.isInt() || dt.isLong())) {
1132 long lnvalue = l.longValue();
1133 if((dt.isByte() && ((lnvalue > 127) || (lnvalue < -128)))
1134 || (dt.isShort() && ((lnvalue > 32767) || (lnvalue < -32768)))
1135 || (dt.isChar() && ((lnvalue > 65535) || (lnvalue < 0)))
1136 || (dt.isInt() && ((lnvalue > 2147483647) || (lnvalue < -2147483648)))
1137 || (dt.isLong() && ((lnvalue > 9223372036854775807L) || (lnvalue < -9223372036854775808L)))) {
1138 throw new Error("Type of rside ("+an.getSrc().getType().toPrettyString()+") not compatible with type of lside ("+an.getDest().getType().toPrettyString()+")"+an.printNode(0));
1141 throw new Error("Type of rside ("+an.getSrc().getType().toPrettyString()+") not compatible with type of lside ("+an.getDest().getType().toPrettyString()+")"+an.printNode(0));
1147 void checkLoopNode(Descriptor md, SymbolTable nametable, LoopNode ln) {
1149 if (ln.getType()==LoopNode.WHILELOOP||ln.getType()==LoopNode.DOWHILELOOP) {
1150 checkExpressionNode(md, nametable, ln.getCondition(), new TypeDescriptor(TypeDescriptor.BOOLEAN));
1151 checkBlockNode(md, nametable, ln.getBody());
1154 /* Link in the initializer naming environment */
1155 BlockNode bn=ln.getInitializer();
1156 bn.getVarTable().setParent(nametable);
1157 for(int i=0; i<bn.size(); i++) {
1158 BlockStatementNode bsn=bn.get(i);
1159 checkBlockStatementNode(md, bn.getVarTable(),bsn);
1161 //check the condition
1162 checkExpressionNode(md, bn.getVarTable(), ln.getCondition(), new TypeDescriptor(TypeDescriptor.BOOLEAN));
1163 checkBlockNode(md, bn.getVarTable(), ln.getBody());
1164 checkBlockNode(md, bn.getVarTable(), ln.getUpdate());
1169 void InnerClassAddParamToCtor( MethodDescriptor md, ClassDescriptor cd, SymbolTable nametable,
1170 CreateObjectNode con, TypeDescriptor td ) {
1172 TypeDescriptor cdsType = new TypeDescriptor( cd );
1173 ExpressionNode conExp = con.getSurroundingClassExpression();
1174 //System.out.println( "The surrounding class expression si " + con );
1175 if( null == conExp ) {
1176 if( md.isStatic()) {
1177 throw new Error("trying to instantiate inner class: " + con.getType() + " in a static scope" );
1179 VarDescriptor thisVD = md.getThis();
1180 if( null == thisVD ) {
1181 throw new Error( "this pointer is not defined in a non static scope" );
1183 if( cdsType.equals( thisVD.getType() ) == false ) {
1184 throw new Error( "the type of this pointer is different than the type expected for inner class constructor. Initializing the inner class: " + con.getType() + " in the wrong scope" );
1186 //make this into an expression node.
1187 NameNode nThis=new NameNode( new NameDescriptor( "this" ) );
1188 con.addArgument( nThis );
1191 //REVISIT : here i am storing the expression as an expressionNode which does not implement type, there is no way for me to semantic check this argument.
1192 con.addArgument( conExp );
1194 //System.out.println( " the modified createObjectNode is " + con.printNode( 0 ) + "\n" );
1197 void trialSemanticCheck(ClassDescriptor cd) {
1198 if(!cd.getInline()) {
1199 throw new Error("Error! Try to do a trial check on a non-inline class " + cd.getSymbol());
1203 for (Iterator method_it = cd.getMethods(); method_it.hasNext(); ) {
1204 MethodDescriptor md = (MethodDescriptor) method_it.next();
1206 checkMethodBody(cd, md);
1208 System.out.println("Error in " + md);
1215 // add all the live vars that are referred by the inline class in the surrounding
1216 // context of the inline class into the inline class' field table and pass them to
1217 // the inline class' constructors
1218 // TODO: BUGFIX. These local vars should be final. But currently we've lost those
1219 // information, so we cannot have that checked.
1220 void InlineClassAddParamToCtor(MethodDescriptor md, ClassDescriptor cd , SymbolTable nametable, CreateObjectNode con, TypeDescriptor td, TypeDescriptor[] tdarray ) {
1221 // for an inline class, need to first add the original parameters of the CreatObjectNode
1222 // into its anonymous constructor and insert a super(...) into the anonymous constructor
1223 // if its super class is not null
1224 MethodDescriptor cd_construtor = null;
1225 for(Iterator it_methods = cd.getMethods(); it_methods.hasNext();) {
1226 MethodDescriptor imd = (MethodDescriptor)it_methods.next();
1227 if(imd.isConstructor()) {
1228 cd_construtor = imd; // an inline class should only have one anonymous constructor
1231 MethodInvokeNode min = null;
1232 if(cd.getSuper()!= null) {
1233 // add a super(...) into the anonymous constructor
1234 NameDescriptor nd=new NameDescriptor("super");
1235 min=new MethodInvokeNode(nd);
1236 BlockExpressionNode ben=new BlockExpressionNode(min);
1237 BlockNode bn = state.getMethodBody(cd_construtor);
1238 bn.addFirstBlockStatement(ben);
1240 for(int i = 0 ; i < tdarray.length; i++) {
1242 TypeDescriptor itd = tdarray[i];
1243 cd_construtor.addParameter(itd, itd.getSymbol()+"_from_con_node_"+i);
1244 min.addArgument(new NameNode(new NameDescriptor(itd.getSymbol()+"_from_con_node_"+i)));
1247 // Next add the live vars into the inline class' fields
1248 cd.setSurroundingNameTable(nametable);
1249 // do a round of semantic check trial to get all the live vars required by the inline class
1250 trialSemanticCheck(cd);
1251 Vector<VarDescriptor> vars = this.inlineClass2LiveVars.remove(cd);
1255 for(int i = 0; i < vars.size(); i++) {
1256 Descriptor d = vars.elementAt(i);
1257 if(d instanceof VarDescriptor && !d.getSymbol().equals("this")) {
1258 con.addArgument(new NameNode(new NameDescriptor(d.getSymbol())));
1259 cd.addField(new FieldDescriptor(new Modifiers(Modifiers.PUBLIC), ((VarDescriptor)d).getType(), d.getSymbol(), null, false));
1260 cd_construtor.addParameter(((VarDescriptor)d).getType(), d.getSymbol()+"_p");
1261 // add the initialize statement into this constructor
1262 BlockNode obn = state.getMethodBody(cd_construtor);
1263 NameNode nn=new NameNode(new NameDescriptor(d.getSymbol()));
1264 NameNode fn = new NameNode (new NameDescriptor(d.getSymbol()+"_p"));
1265 AssignmentNode an=new AssignmentNode(nn,fn,new AssignOperation(1));
1266 obn.addFirstBlockStatement(new BlockExpressionNode(an));
1267 state.addTreeCode(cd_construtor, obn);
1272 void checkCreateObjectNode(Descriptor md, SymbolTable nametable, CreateObjectNode con,
1273 TypeDescriptor td) {
1274 TypeDescriptor[] tdarray = new TypeDescriptor[con.numArgs()];
1275 for (int i = 0; i < con.numArgs(); i++) {
1276 ExpressionNode en = con.getArg(i);
1277 checkExpressionNode(md, nametable, en, null);
1278 tdarray[i] = en.getType();
1281 TypeDescriptor typetolookin = con.getType();
1282 checkTypeDescriptor(((md instanceof MethodDescriptor)?((MethodDescriptor)md).getClassDesc():null), typetolookin);
1284 if (td != null && !typeutil.isSuperorType(td, typetolookin))
1285 throw new Error(typetolookin + " isn't a " + td);
1287 /* Check Array Initializers */
1288 if ((con.getArrayInitializer() != null)) {
1289 checkArrayInitializerNode(md, nametable, con.getArrayInitializer(), typetolookin);
1292 if(this.trialcheck) {
1293 // for a trialcheck of an inline class, skip the rest process
1297 /* Check flag effects */
1298 if (con.getFlagEffects() != null) {
1299 FlagEffects fe = con.getFlagEffects();
1300 ClassDescriptor cd = typetolookin.getClassDesc();
1302 for (int j = 0; j < fe.numEffects(); j++) {
1303 FlagEffect flag = fe.getEffect(j);
1304 String name = flag.getName();
1305 FlagDescriptor flag_d = (FlagDescriptor) cd.getFlagTable().get(name);
1306 // Make sure the flag is declared
1308 throw new Error("Flag descriptor " + name + " undefined in class: " + cd.getSymbol());
1309 if (flag_d.getExternal())
1310 throw new Error("Attempting to modify external flag: " + name);
1311 flag.setFlag(flag_d);
1313 for (int j = 0; j < fe.numTagEffects(); j++) {
1314 TagEffect tag = fe.getTagEffect(j);
1315 String name = tag.getName();
1317 Descriptor d = (Descriptor) nametable.get(name);
1319 throw new Error("Tag descriptor " + name + " undeclared");
1320 else if (!(d instanceof TagVarDescriptor))
1321 throw new Error(name + " is not a tag descriptor");
1322 tag.setTag((TagVarDescriptor) d);
1326 if ((!typetolookin.isClass()) && (!typetolookin.isArray()))
1327 throw new Error("Can't allocate primitive type:" + con.printNode(0));
1329 if (!typetolookin.isArray()) {
1330 // Array's don't need constructor calls
1331 ClassDescriptor classtolookin = typetolookin.getClassDesc();
1332 checkClass(classtolookin, INIT);
1333 if( classtolookin.isInnerClass() ) {
1334 // for inner class that is declared in a static context, it does not have
1335 // lexically enclosing instances
1336 if(!classtolookin.getInStaticContext()) {
1337 InnerClassAddParamToCtor( (MethodDescriptor)md, ((MethodDescriptor)md).getClassDesc() , nametable, con, td );
1339 if(classtolookin.getInline()) {
1340 // for an inline anonymous inner class, the live local variables that are
1341 // referred to by the inline class are passed as parameters of the constructors
1342 // of the inline class
1343 InlineClassAddParamToCtor( (MethodDescriptor)md, classtolookin, nametable, con, td, tdarray );
1345 tdarray = new TypeDescriptor[con.numArgs()];
1346 for (int i = 0; i < con.numArgs(); i++) {
1347 ExpressionNode en = con.getArg(i);
1348 checkExpressionNode(md, nametable, en, null);
1349 tdarray[i] = en.getType();
1352 Set methoddescriptorset = classtolookin.getMethodTable().getSet(classtolookin.getSymbol());
1353 MethodDescriptor bestmd = null;
1354 NextMethod: for (Iterator methodit = methoddescriptorset.iterator(); methodit.hasNext(); ) {
1355 MethodDescriptor currmd = (MethodDescriptor) methodit.next();
1356 /* Need correct number of parameters */
1357 if (con.numArgs() != currmd.numParameters())
1359 for (int i = 0; i < con.numArgs(); i++) {
1360 if (!typeutil.isSuperorType(currmd.getParamType(i), tdarray[i]))
1361 continue NextMethod;
1363 /* Local allocations can't call global allocator */
1364 if (!con.isGlobal() && currmd.isGlobal())
1367 /* Method okay so far */
1371 if (typeutil.isMoreSpecific(currmd, bestmd, true)) {
1373 } else if (con.isGlobal() && match(currmd, bestmd)) {
1374 if (currmd.isGlobal() && !bestmd.isGlobal())
1376 else if (currmd.isGlobal() && bestmd.isGlobal())
1378 } else if (!typeutil.isMoreSpecific(bestmd, currmd, true)) {
1379 throw new Error("No method is most specific:" + bestmd + " and " + currmd);
1382 /* Is this more specific than bestmd */
1385 if (bestmd == null) {
1386 throw new Error("No method found for " + con.printNode(0) + " in " + md);
1388 con.setConstructor(bestmd);
1393 /** Check to see if md1 is the same specificity as md2.*/
1395 boolean match(MethodDescriptor md1, MethodDescriptor md2) {
1396 /* Checks if md1 is more specific than md2 */
1397 if (md1.numParameters()!=md2.numParameters())
1399 for(int i=0; i<md1.numParameters(); i++) {
1400 if (!md2.getParamType(i).equals(md1.getParamType(i)))
1403 if (!md2.getReturnType().equals(md1.getReturnType()))
1406 if (!md2.getClassDesc().equals(md1.getClassDesc()))
1414 ExpressionNode translateNameDescriptorintoExpression(NameDescriptor nd, int numLine) {
1415 String id=nd.getIdentifier();
1416 NameDescriptor base=nd.getBase();
1418 NameNode nn=new NameNode(nd);
1419 nn.setNumLine(numLine);
1422 FieldAccessNode fan=new FieldAccessNode(translateNameDescriptorintoExpression(base,numLine),id);
1423 fan.setNumLine(numLine);
1428 MethodDescriptor recurseSurroundingClassesM( ClassDescriptor icd, String varname ) {
1429 if( null == icd || false == icd.isInnerClass() )
1432 ClassDescriptor surroundingDesc = icd.getSurroundingDesc();
1433 if( null == surroundingDesc )
1436 SymbolTable methodTable = surroundingDesc.getMethodTable();
1437 MethodDescriptor md = ( MethodDescriptor ) methodTable.get( varname );
1440 return recurseSurroundingClassesM( surroundingDesc, varname );
1443 ExpressionNode methodInvocationExpression( ClassDescriptor icd, MethodDescriptor md, int linenum ) {
1444 ClassDescriptor cd = md.getClassDesc();
1446 int startingDepth = icd.getInnerDepth();
1448 if( true == cd.isInnerClass() )
1449 depth = cd.getInnerDepth();
1451 String composed = "this";
1452 NameDescriptor runningDesc = new NameDescriptor( "this" );;
1454 for ( int index = startingDepth; index > depth; --index ) {
1455 composed = "this$" + String.valueOf( index - 1 );
1456 runningDesc = new NameDescriptor( runningDesc, composed );
1458 if( false == cd.isInnerClass() )
1459 runningDesc = new NameDescriptor( runningDesc, "this$" + String.valueOf(0) ); //all the way up.
1461 return new NameNode(runningDesc);
1464 void checkMethodInvokeNode(Descriptor md, SymbolTable nametable, MethodInvokeNode min, TypeDescriptor td) {
1465 /*Typecheck subexpressions
1466 and get types for expressions*/
1468 boolean isstatic = false;
1469 if((md instanceof MethodDescriptor) && ((MethodDescriptor)md).isStatic()) {
1472 TypeDescriptor[] tdarray=new TypeDescriptor[min.numArgs()];
1473 for(int i=0; i<min.numArgs(); i++) {
1474 ExpressionNode en=min.getArg(i);
1475 checkExpressionNode(md,nametable,en,null);
1476 tdarray[i]=en.getType();
1478 if(en.getType().isClass() && en.getType().getClassDesc().isEnum()) {
1479 tdarray[i] = new TypeDescriptor(TypeDescriptor.INT);
1482 TypeDescriptor typetolookin=null;
1483 if (min.getExpression()!=null) {
1484 checkExpressionNode(md,nametable,min.getExpression(),null);
1485 typetolookin=min.getExpression().getType();
1486 } else if (min.getBaseName()!=null) {
1487 String rootname=min.getBaseName().getRoot();
1488 if (rootname.equals("super")) {
1489 ClassDescriptor supercd=((MethodDescriptor)md).getClassDesc().getSuperDesc();
1490 typetolookin=new TypeDescriptor(supercd);
1492 } else if (rootname.equals("this")) {
1494 throw new Error("use this object in static method md = "+ md.toString());
1496 ClassDescriptor cd=((MethodDescriptor)md).getClassDesc();
1497 typetolookin=new TypeDescriptor(cd);
1498 } else if (nametable.get(rootname)!=null) {
1499 //we have an expression
1500 min.setExpression(translateNameDescriptorintoExpression(min.getBaseName(),min.getNumLine()));
1501 checkExpressionNode(md, nametable, min.getExpression(), null);
1502 typetolookin=min.getExpression().getType();
1504 if(!min.getBaseName().getSymbol().equals("System.out")||state.JNI) {
1505 ExpressionNode nn = translateNameDescriptorintoExpression(min.getBaseName(),min.getNumLine());
1506 checkExpressionNode(md, nametable, nn, null);
1507 typetolookin = nn.getType();
1508 if(!((nn.kind()== Kind.NameNode) && (((NameNode)nn).getField() == null)
1509 && (((NameNode)nn).getVar() == null) && (((NameNode)nn).getExpression() == null))) {
1510 // this is not a pure class name, need to add to
1511 min.setExpression(nn);
1515 ClassDescriptor cd = getClass(null, "System");
1518 throw new Error("md = "+ md.toString()+ " "+min.getBaseName()+" undefined");
1519 typetolookin=new TypeDescriptor(cd);
1522 } else if ((md instanceof MethodDescriptor)&&min.getMethodName().equals("super")) {
1523 ClassDescriptor supercd=((MethodDescriptor)md).getClassDesc().getSuperDesc();
1524 min.methodid=supercd.getSymbol();
1525 typetolookin=new TypeDescriptor(supercd);
1526 } else if (md instanceof MethodDescriptor) {
1527 typetolookin=new TypeDescriptor(((MethodDescriptor)md).getClassDesc());
1529 /* If this a task descriptor we throw an error at this point */
1530 throw new Error("Unknown method call to "+min.getMethodName()+"in task"+md.getSymbol());
1532 if (!typetolookin.isClass())
1533 throw new Error("Error with method call to "+min.getMethodName()+" in class "+typetolookin);
1534 ClassDescriptor classtolookin=typetolookin.getClassDesc();
1535 checkClass(classtolookin, REFERENCE);
1536 Set methoddescriptorset=classtolookin.getMethodTable().getSet(min.getMethodName());
1537 MethodDescriptor bestmd=null;
1539 for(Iterator methodit=methoddescriptorset.iterator(); methodit.hasNext(); ) {
1540 MethodDescriptor currmd=(MethodDescriptor)methodit.next();
1541 /* Need correct number of parameters */
1542 if (min.numArgs()!=currmd.numParameters())
1544 for(int i=0; i<min.numArgs(); i++) {
1545 if (!typeutil.isSuperorType(currmd.getParamType(i),tdarray[i]))
1546 if(((!tdarray[i].isArray() &&(tdarray[i].isInt() || tdarray[i].isLong()))
1547 && currmd.getParamType(i).isClass() && currmd.getParamType(i).getClassDesc().getSymbol().equals("Object"))) {
1548 // primitive parameters vs object
1550 continue NextMethod;
1553 /* Method okay so far */
1557 if (typeutil.isMoreSpecific(currmd,bestmd, false)) {
1559 } else if (!typeutil.isMoreSpecific(bestmd, currmd, false))
1560 throw new Error("No method is most specific:"+bestmd+" and "+currmd);
1562 /* Is this more specific than bestmd */
1566 // if this is an inner class, need to check the method table for the surrounding class
1567 bestmd = recurseSurroundingClassesM(classtolookin, min.getMethodName());
1569 throw new Error("No method found for :"+min.printNode(0)+" in class: " + classtolookin+" in "+md);
1571 // set the correct "this" expression here
1572 ExpressionNode en=methodInvocationExpression(classtolookin, bestmd, min.getNumLine());
1573 min.setExpression(en);
1574 checkExpressionNode(md, nametable, min.getExpression(), null);
1577 min.setMethod(bestmd);
1579 if ((td!=null)&&(min.getType()!=null)&&!typeutil.isSuperorType(td, min.getType()))
1580 throw new Error(min.getType()+ " is not equal to or a subclass of "+td);
1581 /* Check whether we need to set this parameter to implied this */
1582 if (!isstatic && !bestmd.isStatic()) {
1583 if (min.getExpression()==null) {
1584 ExpressionNode en=new NameNode(new NameDescriptor("this"));
1585 min.setExpression(en);
1586 checkExpressionNode(md, nametable, min.getExpression(), null);
1590 /* Check if we need to wrap primitive paratmeters to objects */
1591 for(int i=0; i<min.numArgs(); i++) {
1592 if(!tdarray[i].isArray() && (tdarray[i].isInt() || tdarray[i].isLong())
1593 && min.getMethod().getParamType(i).isClass() && min.getMethod().getParamType(i).getClassDesc().getSymbol().equals("Object")) {
1594 // Shall wrap this primitive parameter as a object
1595 ExpressionNode exp = min.getArg(i);
1596 TypeDescriptor ptd = null;
1597 NameDescriptor nd=null;
1598 if(exp.getType().isInt()) {
1599 nd = new NameDescriptor("Integer");
1600 ptd = state.getTypeDescriptor(nd);
1601 } else if(exp.getType().isLong()) {
1602 nd = new NameDescriptor("Long");
1603 ptd = state.getTypeDescriptor(nd);
1605 boolean isglobal = false;
1606 String disjointId = null;
1607 CreateObjectNode con=new CreateObjectNode(ptd, isglobal, disjointId);
1608 con.addArgument(exp);
1609 checkExpressionNode(md, nametable, con, null);
1610 min.setArgument(con, i);
1616 void checkOpNode(Descriptor md, SymbolTable nametable, OpNode on, TypeDescriptor td) {
1617 checkExpressionNode(md, nametable, on.getLeft(), null);
1618 if (on.getRight()!=null)
1619 checkExpressionNode(md, nametable, on.getRight(), null);
1620 TypeDescriptor ltd=on.getLeft().getType();
1621 TypeDescriptor rtd=on.getRight()!=null?on.getRight().getType():null;
1622 TypeDescriptor lefttype=null;
1623 TypeDescriptor righttype=null;
1624 Operation op=on.getOp();
1626 switch(op.getOp()) {
1627 case Operation.LOGIC_OR:
1628 case Operation.LOGIC_AND:
1629 if (!(rtd.isBoolean()))
1631 on.setRightType(rtd);
1633 case Operation.LOGIC_NOT:
1634 if (!(ltd.isBoolean()))
1637 on.setLeftType(ltd);
1639 on.setType(new TypeDescriptor(TypeDescriptor.BOOLEAN));
1642 case Operation.COMP:
1643 // 5.6.2 Binary Numeric Promotion
1644 //TODO unboxing of reference objects
1647 else if (ltd.isFloat())
1649 else if (ltd.isLong())
1650 lefttype=new TypeDescriptor(TypeDescriptor.LONG);
1652 lefttype=new TypeDescriptor(TypeDescriptor.INT);
1653 on.setLeftType(lefttype);
1654 on.setType(lefttype);
1657 case Operation.BIT_OR:
1658 case Operation.BIT_XOR:
1659 case Operation.BIT_AND:
1660 // 5.6.2 Binary Numeric Promotion
1661 //TODO unboxing of reference objects
1662 if (ltd.isDouble()||rtd.isDouble())
1664 else if (ltd.isFloat()||rtd.isFloat())
1666 else if (ltd.isLong()||rtd.isLong())
1667 lefttype=new TypeDescriptor(TypeDescriptor.LONG);
1668 // 090205 hack for boolean
1669 else if (ltd.isBoolean()||rtd.isBoolean())
1670 lefttype=new TypeDescriptor(TypeDescriptor.BOOLEAN);
1672 lefttype=new TypeDescriptor(TypeDescriptor.INT);
1675 on.setLeftType(lefttype);
1676 on.setRightType(righttype);
1677 on.setType(lefttype);
1680 case Operation.ISAVAILABLE:
1681 if (!(ltd.isPtr())) {
1682 throw new Error("Can't use isavailable on non-pointers/non-parameters.");
1685 on.setLeftType(lefttype);
1686 on.setType(new TypeDescriptor(TypeDescriptor.BOOLEAN));
1689 case Operation.EQUAL:
1690 case Operation.NOTEQUAL:
1691 // 5.6.2 Binary Numeric Promotion
1692 //TODO unboxing of reference objects
1693 if (ltd.isBoolean()||rtd.isBoolean()) {
1694 if (!(ltd.isBoolean()&&rtd.isBoolean()))
1696 righttype=lefttype=new TypeDescriptor(TypeDescriptor.BOOLEAN);
1697 } else if (ltd.isPtr()||rtd.isPtr()) {
1698 if (!(ltd.isPtr()&&rtd.isPtr())) {
1705 } else if (ltd.isDouble()||rtd.isDouble())
1706 righttype=lefttype=new TypeDescriptor(TypeDescriptor.DOUBLE);
1707 else if (ltd.isFloat()||rtd.isFloat())
1708 righttype=lefttype=new TypeDescriptor(TypeDescriptor.FLOAT);
1709 else if (ltd.isLong()||rtd.isLong())
1710 righttype=lefttype=new TypeDescriptor(TypeDescriptor.LONG);
1712 righttype=lefttype=new TypeDescriptor(TypeDescriptor.INT);
1714 on.setLeftType(lefttype);
1715 on.setRightType(righttype);
1716 on.setType(new TypeDescriptor(TypeDescriptor.BOOLEAN));
1725 // 5.6.2 Binary Numeric Promotion
1726 //TODO unboxing of reference objects
1727 if (!ltd.isNumber()||!rtd.isNumber()) {
1728 if (!ltd.isNumber())
1729 throw new Error("Leftside is not number"+on.printNode(0)+"type="+ltd.toPrettyString());
1730 if (!rtd.isNumber())
1731 throw new Error("Rightside is not number"+on.printNode(0));
1734 if (ltd.isDouble()||rtd.isDouble())
1735 lefttype=new TypeDescriptor(TypeDescriptor.DOUBLE);
1736 else if (ltd.isFloat()||rtd.isFloat())
1737 lefttype=new TypeDescriptor(TypeDescriptor.FLOAT);
1738 else if (ltd.isLong()||rtd.isLong())
1739 lefttype=new TypeDescriptor(TypeDescriptor.LONG);
1741 lefttype=new TypeDescriptor(TypeDescriptor.INT);
1743 on.setLeftType(lefttype);
1744 on.setRightType(righttype);
1745 on.setType(new TypeDescriptor(TypeDescriptor.BOOLEAN));
1749 if (ltd.isString()||rtd.isString()) {
1750 ClassDescriptor stringcl=getClass(null, TypeUtil.StringClass);
1751 TypeDescriptor stringtd=new TypeDescriptor(stringcl);
1752 NameDescriptor nd=new NameDescriptor("String");
1753 NameDescriptor valuend=new NameDescriptor(nd, "valueOf");
1754 if (!(ltd.isString()&&(on.getLeft() instanceof OpNode))) {
1755 MethodInvokeNode leftmin=new MethodInvokeNode(valuend);
1756 leftmin.setNumLine(on.getLeft().getNumLine());
1757 leftmin.addArgument(on.getLeft());
1759 checkExpressionNode(md, nametable, on.getLeft(), null);
1762 if (!(rtd.isString()&&(on.getRight() instanceof OpNode))) {
1763 MethodInvokeNode rightmin=new MethodInvokeNode(valuend);
1764 rightmin.setNumLine(on.getRight().getNumLine());
1765 rightmin.addArgument(on.getRight());
1767 checkExpressionNode(md, nametable, on.getRight(), null);
1770 on.setLeftType(stringtd);
1771 on.setRightType(stringtd);
1772 on.setType(stringtd);
1777 case Operation.MULT:
1780 // 5.6.2 Binary Numeric Promotion
1781 //TODO unboxing of reference objects
1782 if (ltd.isArray()||rtd.isArray()||!ltd.isNumber()||!rtd.isNumber())
1783 throw new Error("Error in "+on.printNode(0));
1785 if (ltd.isDouble()||rtd.isDouble())
1786 lefttype=new TypeDescriptor(TypeDescriptor.DOUBLE);
1787 else if (ltd.isFloat()||rtd.isFloat())
1788 lefttype=new TypeDescriptor(TypeDescriptor.FLOAT);
1789 else if (ltd.isLong()||rtd.isLong())
1790 lefttype=new TypeDescriptor(TypeDescriptor.LONG);
1792 lefttype=new TypeDescriptor(TypeDescriptor.INT);
1794 on.setLeftType(lefttype);
1795 on.setRightType(righttype);
1796 on.setType(lefttype);
1799 case Operation.LEFTSHIFT:
1800 case Operation.RIGHTSHIFT:
1801 case Operation.URIGHTSHIFT:
1802 if (!rtd.isIntegerType())
1804 //5.6.1 Unary Numeric Promotion
1805 if (rtd.isByte()||rtd.isShort()||rtd.isInt())
1806 righttype=new TypeDescriptor(TypeDescriptor.INT);
1810 on.setRightType(righttype);
1811 if (!ltd.isIntegerType())
1814 case Operation.UNARYPLUS:
1815 case Operation.UNARYMINUS:
1816 /* case Operation.POSTINC:
1817 case Operation.POSTDEC:
1818 case Operation.PREINC:
1819 case Operation.PREDEC:*/
1820 if (!ltd.isNumber())
1822 //5.6.1 Unary Numeric Promotion
1823 if (ltd.isByte()||ltd.isShort()||ltd.isInt())
1824 lefttype=new TypeDescriptor(TypeDescriptor.INT);
1827 on.setLeftType(lefttype);
1828 on.setType(lefttype);
1832 throw new Error(op.toString());
1836 if (!typeutil.isSuperorType(td, on.getType())) {
1837 throw new Error("Type of rside not compatible with type of lside"+on.printNode(0));