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();
727 // check if it is to access an enum field
728 Iterator it_enum = ltd.getClassDesc().getEnum();
729 while(it_enum.hasNext()) {
730 ClassDescriptor ecd = (ClassDescriptor)it_enum.next();
731 if(ecd.getSymbol().equals(ltd.getClassDesc().getSymbol()+"$"+fieldname)) {
732 // this is an enum field access
733 if(!ecd.isStatic() && !ecd.getModifier().isStatic() && !ecd.getModifier().isPublic()) {
734 throw new Error(fieldname + " is not a public/static enum field in "+fan.printNode(0)+" in "+md);
736 TypeDescriptor tp = new TypeDescriptor(ecd);
737 tp.setClassNameRef();
738 fd=new FieldDescriptor(ecd.getModifier(), tp, ltd.getClassDesc().getSymbol()+"$"+fieldname, null, false);;
745 if(ltd.getClassDesc().isEnum()) {
746 int value = ltd.getClassDesc().getEnumConstant(fieldname);
748 // check if this field is an enum constant
749 throw new Error(fieldname + " is not an enum constant in "+fan.printNode(0)+" in "+md);
751 fd = new FieldDescriptor(new Modifiers(Modifiers.PUBLIC|Modifiers.FINAL), new TypeDescriptor(TypeDescriptor.INT), fieldname, null, false);
753 fd.setEnumValue(value);
754 } else if(fd == null) {
755 throw new Error("Could not find field "+ fieldname + " in "+fan.printNode(0)+" in "+md + " (Line: "+fan.getNumLine()+")");
756 } else if(fd.isStatic()) {
757 // check if this field is a static field
758 if(fd.getExpressionNode() != null) {
759 checkExpressionNode(md,nametable,fd.getExpressionNode(),null);
762 throw new Error("Dereference of the non-static field "+ fieldname + " in "+fan.printNode(0)+" in "+md);
767 if((md instanceof MethodDescriptor) && false == ((MethodDescriptor)md).isStaticBlock()) {
768 ClassDescriptor cd = ((MethodDescriptor)md).getClassDesc();
769 FieldAccessNode theFieldNode = fieldAccessExpression( cd, fieldname, fan.getNumLine() );
770 if( null != theFieldNode ) {
771 //fan = theFieldNode;
772 checkFieldAccessNode( md, nametable, theFieldNode, td );
773 fan.setField( theFieldNode.getField() );
774 fan.setExpression( theFieldNode.getExpression() );
775 //TypeDescriptor td1 = fan.getType();
780 throw new Error("Unknown field "+fieldname + " in "+fan.printNode(0)+" in "+md);
783 if (fd.getType().iswrapper()) {
784 FieldAccessNode fan2=new FieldAccessNode(left, fieldname);
785 fan2.setNumLine(left.getNumLine());
788 fan.fieldname="value";
790 ExpressionNode leftwr=fan.getExpression();
791 TypeDescriptor ltdwr=leftwr.getType();
792 String fieldnamewr=fan.getFieldName();
793 FieldDescriptor fdwr=(FieldDescriptor) ltdwr.getClassDesc().getFieldTable().get(fieldnamewr);
796 throw new Error("Unknown field "+fieldnamewr + " in "+fan.printNode(0)+" in "+md);
801 if (!typeutil.isSuperorType(td,fan.getType()))
802 throw new Error("Field node returns "+fan.getType()+", but need "+td);
806 void checkArrayAccessNode(Descriptor md, SymbolTable nametable, ArrayAccessNode aan, TypeDescriptor td) {
807 ExpressionNode left=aan.getExpression();
808 checkExpressionNode(md,nametable,left,null);
810 checkExpressionNode(md,nametable,aan.getIndex(),new TypeDescriptor(TypeDescriptor.INT));
811 TypeDescriptor ltd=left.getType();
812 if (ltd.dereference().iswrapper()) {
813 aan.wrappertype=((FieldDescriptor)ltd.dereference().getClassDesc().getFieldTable().get("value")).getType();
817 if (!typeutil.isSuperorType(td,aan.getType()))
818 throw new Error("Field node returns "+aan.getType()+", but need "+td);
821 void checkLiteralNode(Descriptor md, SymbolTable nametable, LiteralNode ln, TypeDescriptor td) {
822 /* Resolve the type */
823 Object o=ln.getValue();
824 if (ln.getTypeString().equals("null")) {
825 ln.setType(new TypeDescriptor(TypeDescriptor.NULL));
826 } else if (o instanceof Integer) {
827 ln.setType(new TypeDescriptor(TypeDescriptor.INT));
828 } else if (o instanceof Long) {
829 ln.setType(new TypeDescriptor(TypeDescriptor.LONG));
830 } else if (o instanceof Float) {
831 ln.setType(new TypeDescriptor(TypeDescriptor.FLOAT));
832 } else if (o instanceof Boolean) {
833 ln.setType(new TypeDescriptor(TypeDescriptor.BOOLEAN));
834 } else if (o instanceof Double) {
835 ln.setType(new TypeDescriptor(TypeDescriptor.DOUBLE));
836 } else if (o instanceof Character) {
837 ln.setType(new TypeDescriptor(TypeDescriptor.CHAR));
838 } else if (o instanceof String) {
839 ln.setType(new TypeDescriptor(getClass(null, TypeUtil.StringClass)));
843 if (!typeutil.isSuperorType(td,ln.getType())) {
844 Long l = ln.evaluate();
845 if((ln.getType().isByte() || ln.getType().isShort()
846 || ln.getType().isChar() || ln.getType().isInt())
848 && (td.isByte() || td.isShort() || td.isChar()
849 || td.isInt() || td.isLong())) {
850 long lnvalue = l.longValue();
851 if((td.isByte() && ((lnvalue > 127) || (lnvalue < -128)))
852 || (td.isShort() && ((lnvalue > 32767) || (lnvalue < -32768)))
853 || (td.isChar() && ((lnvalue > 65535) || (lnvalue < 0)))
854 || (td.isInt() && ((lnvalue > 2147483647) || (lnvalue < -2147483648)))
855 || (td.isLong() && ((lnvalue > 9223372036854775807L) || (lnvalue < -9223372036854775808L)))) {
856 throw new Error("Field node returns "+ln.getType()+", but need "+td+" in "+md);
859 throw new Error("Field node returns "+ln.getType()+", but need "+td+" in "+md);
864 FieldDescriptor recurseSurroundingClasses( ClassDescriptor icd, String varname ) {
865 if( null == icd || false == icd.isInnerClass() )
868 ClassDescriptor surroundingDesc = icd.getSurroundingDesc();
869 if( null == surroundingDesc )
872 SymbolTable fieldTable = surroundingDesc.getFieldTable();
873 FieldDescriptor fd = ( FieldDescriptor ) fieldTable.get( varname );
876 return recurseSurroundingClasses( surroundingDesc, varname );
879 FieldAccessNode fieldAccessExpression( ClassDescriptor icd, String varname, int linenum ) {
880 FieldDescriptor fd = recurseSurroundingClasses( icd, varname );
884 ClassDescriptor cd = fd.getClassDescriptor();
885 if(icd.getInStaticContext()) {
886 // if the inner class is in a static context, it does not have the this$0
887 // pointer to its surrounding class. Instead, it might have reference to
888 // its static surrounding method/block is there is any and it can refer
889 // to static fields in its surrounding class too.
891 NameNode nn = new NameNode(new NameDescriptor(cd.getSymbol()));
892 nn.setNumLine(linenum);
893 FieldAccessNode theFieldNode = new FieldAccessNode(nn,varname);
894 theFieldNode.setNumLine(linenum);
897 throw new Error("Error: access non-static field " + cd.getSymbol() + "." + fd.getSymbol() + " in an inner class " + icd.getSymbol() + " that is declared in a static context");
901 int startingDepth = icd.getInnerDepth();
903 if( true == cd.isInnerClass() )
904 depth = cd.getInnerDepth();
906 String composed = "this";
907 NameDescriptor runningDesc = new NameDescriptor( "this" );;
909 for ( int index = startingDepth; index > depth; --index ) {
910 composed = "this$" + String.valueOf( index - 1 );
911 runningDesc = new NameDescriptor( runningDesc, composed );
913 if( false == cd.isInnerClass() )
914 runningDesc = new NameDescriptor( runningDesc, "this$" + String.valueOf(0) ); //all the way up.
915 NameDescriptor idDesc = new NameDescriptor( runningDesc, varname );
918 FieldAccessNode theFieldNode = ( FieldAccessNode )translateNameDescriptorintoExpression( idDesc, linenum );
922 void checkNameNode(Descriptor md, SymbolTable nametable, NameNode nn, TypeDescriptor td) {
923 NameDescriptor nd=nn.getName();
924 if (nd.getBase()!=null) {
926 /* Rewrite NameNode */
927 ExpressionNode en=translateNameDescriptorintoExpression(nd,nn.getNumLine());
928 nn.setExpression(en);
929 checkExpressionNode(md,nametable,en,td);
931 String varname=nd.toString();
932 if(varname.equals("this") || varname.equals("super")) {
934 nn.setVar((VarDescriptor)nametable.get("this"));
935 if(varname.equals("super")) {
940 Descriptor d=(Descriptor)nametable.get(varname);
942 ClassDescriptor cd = null;
943 //check the inner class case first.
944 if((md instanceof MethodDescriptor) && false == ((MethodDescriptor)md).isStaticBlock()) {
945 cd = ((MethodDescriptor)md).getClassDesc();
946 FieldAccessNode theFieldNode = fieldAccessExpression( cd, varname, nn.getNumLine() );
947 if( null != theFieldNode ) {
948 nn.setExpression(( ExpressionNode )theFieldNode);
949 checkExpressionNode(md,nametable,( ExpressionNode )theFieldNode,td);
951 } else if(cd.getInline() && (this.trialcheck)) {
952 // for the trial check of an inline class, cache the unknown var
953 d = cd.getSurroundingNameTable().get(varname);
955 if(!this.inlineClass2LiveVars.containsKey(cd)) {
956 this.inlineClass2LiveVars.put(cd, new Vector<VarDescriptor>());
958 Vector<VarDescriptor> vars = this.inlineClass2LiveVars.get(cd);
959 if(!vars.contains((VarDescriptor)d)) {
960 vars.add((VarDescriptor)d);
966 if((md instanceof MethodDescriptor) && ((MethodDescriptor)md).isStaticBlock()) {
967 // this is a static block, all the accessed fields should be static field
968 cd = ((MethodDescriptor)md).getClassDesc();
969 SymbolTable fieldtbl = cd.getFieldTable();
970 FieldDescriptor fd=(FieldDescriptor)fieldtbl.get(varname);
971 if((fd == null) || (!fd.isStatic())) {
972 // no such field in the class, check if this is a class
973 if(varname.equals("this")) {
974 throw new Error("Error: access this obj in a static block");
976 cd=getClass(((md instanceof MethodDescriptor)?((MethodDescriptor)md).getClassDesc():null), varname);
978 // this is a class name
982 throw new Error("Name "+varname+" should not be used in static block: "+md);
985 // this is a static field
991 // check if the var is a static field of the class
992 if(md instanceof MethodDescriptor) {
993 cd = ((MethodDescriptor)md).getClassDesc();
994 FieldDescriptor fd = (FieldDescriptor)cd.getFieldTable().get(varname);
995 if((fd != null) && (fd.isStatic())) {
999 if (!typeutil.isSuperorType(td,nn.getType()))
1000 throw new Error("Field node returns "+nn.getType()+", but need "+td);
1002 } else if(fd != null) {
1003 throw new Error("Name "+varname+" should not be used in " + md);
1006 cd=getClass(((md instanceof MethodDescriptor)?((MethodDescriptor)md).getClassDesc():null), varname);
1008 // this is a class name
1009 nn.setClassDesc(cd);
1012 throw new Error("Name "+varname+" undefined in: "+md);
1018 if (d instanceof VarDescriptor) {
1020 } else if (d instanceof FieldDescriptor) {
1021 FieldDescriptor fd=(FieldDescriptor)d;
1022 if (fd.getType().iswrapper()) {
1023 String id=nd.getIdentifier();
1024 NameDescriptor base=nd.getBase();
1025 NameNode n=new NameNode(nn.getName());
1026 n.setNumLine(nn.getNumLine());
1028 n.setVar((VarDescriptor)nametable.get("this")); /* Need a pointer to this */
1029 FieldAccessNode fan=new FieldAccessNode(n,"value");
1030 fan.setNumLine(n.getNumLine());
1031 FieldDescriptor fdval=(FieldDescriptor) fd.getType().getClassDesc().getFieldTable().get("value");
1032 fan.setField(fdval);
1033 nn.setExpression(fan);
1036 nn.setVar((VarDescriptor)nametable.get("this")); /* Need a pointer to this */
1038 } else if (d instanceof TagVarDescriptor) {
1040 } else throw new Error("Wrong type of descriptor");
1042 if (!typeutil.isSuperorType(td,nn.getType()))
1043 throw new Error("Field node returns "+nn.getType()+", but need "+td);
1047 void checkOffsetNode(Descriptor md, SymbolTable nameTable, OffsetNode ofn, TypeDescriptor td) {
1048 TypeDescriptor ltd=ofn.td;
1049 checkTypeDescriptor(((md instanceof MethodDescriptor)?((MethodDescriptor)md).getClassDesc():null),ltd);
1051 String fieldname = ofn.fieldname;
1052 FieldDescriptor fd=null;
1053 if (ltd.isArray()&&fieldname.equals("length")) {
1054 fd=FieldDescriptor.arrayLength;
1056 fd=(FieldDescriptor) ltd.getClassDesc().getFieldTable().get(fieldname);
1060 checkField(ltd.getClassDesc(), fd);
1063 throw new Error("Unknown field "+fieldname + " in "+ofn.printNode(1)+" in "+md);
1066 if (!typeutil.isSuperorType(td, ofn.getType())) {
1067 throw new Error("Type of rside not compatible with type of lside"+ofn.printNode(0));
1073 void checkTertiaryNode(Descriptor md, SymbolTable nametable, TertiaryNode tn, TypeDescriptor td) {
1074 checkExpressionNode(md, nametable, tn.getCond(), new TypeDescriptor(TypeDescriptor.BOOLEAN));
1075 checkExpressionNode(md, nametable, tn.getTrueExpr(), td);
1076 checkExpressionNode(md, nametable, tn.getFalseExpr(), td);
1079 void checkInstanceOfNode(Descriptor md, SymbolTable nametable, InstanceOfNode tn, TypeDescriptor td) {
1080 if (td!=null&&!td.isBoolean())
1081 throw new Error("Expecting type "+td+"for instanceof expression");
1083 checkTypeDescriptor(((md instanceof MethodDescriptor)?((MethodDescriptor)md).getClassDesc():null), tn.getExprType());
1084 checkExpressionNode(md, nametable, tn.getExpr(), null);
1087 void checkArrayInitializerNode(Descriptor md, SymbolTable nametable, ArrayInitializerNode ain, TypeDescriptor td) {
1088 for( int i = 0; i < ain.numVarInitializers(); ++i ) {
1089 checkExpressionNode(md, nametable, ain.getVarInitializer(i), td.dereference());
1097 void checkAssignmentNode(Descriptor md, SymbolTable nametable, AssignmentNode an, TypeDescriptor td) {
1098 // Need to first check the lside to decide the correct type of the rside
1099 // TODO: Need check on validity of operation here
1100 if (!((an.getDest() instanceof FieldAccessNode)||
1101 (an.getDest() instanceof ArrayAccessNode)||
1102 (an.getDest() instanceof NameNode)))
1103 throw new Error("Bad lside in "+an.printNode(0));
1104 checkExpressionNode(md, nametable, an.getDest(), null);
1105 boolean postinc=true;
1106 if (an.getOperation().getBaseOp()==null||
1107 (an.getOperation().getBaseOp().getOp()!=Operation.POSTINC&&
1108 an.getOperation().getBaseOp().getOp()!=Operation.POSTDEC))
1111 if(an.getSrc() instanceof ArrayInitializerNode) {
1112 checkExpressionNode(md, nametable, an.getSrc(), an.getDest().getType());
1114 checkExpressionNode(md, nametable, an.getSrc(),td);
1118 /* We want parameter variables to tasks to be immutable */
1119 if (md instanceof TaskDescriptor) {
1120 if (an.getDest() instanceof NameNode) {
1121 NameNode nn=(NameNode)an.getDest();
1122 if (nn.getVar()!=null) {
1123 if (((TaskDescriptor)md).getParameterTable().contains(nn.getVar().getSymbol()))
1124 throw new Error("Can't modify parameter "+nn.getVar()+ " to task "+td.getSymbol());
1129 if (an.getDest().getType().isString()&&an.getOperation().getOp()==AssignOperation.PLUSEQ) {
1131 ClassDescriptor stringcl=getClass(null, TypeUtil.StringClass);
1132 TypeDescriptor stringtd=new TypeDescriptor(stringcl);
1133 NameDescriptor nd=new NameDescriptor("String");
1134 NameDescriptor valuend=new NameDescriptor(nd, "valueOf");
1136 if (!(an.getSrc().getType().isString()&&(an.getSrc() instanceof OpNode))) {
1137 MethodInvokeNode rightmin=new MethodInvokeNode(valuend);
1138 rightmin.setNumLine(an.getSrc().getNumLine());
1139 rightmin.addArgument(an.getSrc());
1141 checkExpressionNode(md, nametable, an.getSrc(), null);
1145 if (!postinc&&!typeutil.isSuperorType(an.getDest().getType(),an.getSrc().getType())) {
1146 TypeDescriptor dt = an.getDest().getType();
1147 TypeDescriptor st = an.getSrc().getType();
1148 if(an.getSrc().kind() == Kind.ArrayInitializerNode) {
1149 if(dt.getArrayCount() != st.getArrayCount()) {
1150 throw new Error("Type of rside ("+an.getSrc().getType().toPrettyString()+") not compatible with type of lside ("+an.getDest().getType().toPrettyString()+")"+an.printNode(0));
1153 dt = dt.dereference();
1154 st = st.dereference();
1155 } while(dt.isArray());
1156 if((st.isByte() || st.isShort() || st.isChar() || st.isInt())
1157 && (dt.isByte() || dt.isShort() || dt.isChar() || dt.isInt() || dt.isLong())) {
1160 throw new Error("Type of rside ("+an.getSrc().getType().toPrettyString()+") not compatible with type of lside ("+an.getDest().getType().toPrettyString()+")"+an.printNode(0));
1164 Long l = an.getSrc().evaluate();
1165 if((st.isByte() || st.isShort() || st.isChar() || st.isInt())
1167 && (dt.isByte() || dt.isShort() || dt.isChar() || dt.isInt() || dt.isLong())) {
1168 long lnvalue = l.longValue();
1169 if((dt.isByte() && ((lnvalue > 127) || (lnvalue < -128)))
1170 || (dt.isShort() && ((lnvalue > 32767) || (lnvalue < -32768)))
1171 || (dt.isChar() && ((lnvalue > 65535) || (lnvalue < 0)))
1172 || (dt.isInt() && ((lnvalue > 2147483647) || (lnvalue < -2147483648)))
1173 || (dt.isLong() && ((lnvalue > 9223372036854775807L) || (lnvalue < -9223372036854775808L)))) {
1174 throw new Error("Type of rside ("+an.getSrc().getType().toPrettyString()+") not compatible with type of lside ("+an.getDest().getType().toPrettyString()+")"+an.printNode(0));
1177 throw new Error("Type of rside ("+an.getSrc().getType().toPrettyString()+") not compatible with type of lside ("+an.getDest().getType().toPrettyString()+")"+an.printNode(0));
1183 void checkLoopNode(Descriptor md, SymbolTable nametable, LoopNode ln) {
1185 if (ln.getType()==LoopNode.WHILELOOP||ln.getType()==LoopNode.DOWHILELOOP) {
1186 checkExpressionNode(md, nametable, ln.getCondition(), new TypeDescriptor(TypeDescriptor.BOOLEAN));
1187 checkBlockNode(md, nametable, ln.getBody());
1190 /* Link in the initializer naming environment */
1191 BlockNode bn=ln.getInitializer();
1192 bn.getVarTable().setParent(nametable);
1193 for(int i=0; i<bn.size(); i++) {
1194 BlockStatementNode bsn=bn.get(i);
1195 checkBlockStatementNode(md, bn.getVarTable(),bsn);
1197 //check the condition
1198 checkExpressionNode(md, bn.getVarTable(), ln.getCondition(), new TypeDescriptor(TypeDescriptor.BOOLEAN));
1199 checkBlockNode(md, bn.getVarTable(), ln.getBody());
1200 checkBlockNode(md, bn.getVarTable(), ln.getUpdate());
1205 void InnerClassAddParamToCtor( MethodDescriptor md, ClassDescriptor cd, SymbolTable nametable,
1206 CreateObjectNode con, TypeDescriptor td ) {
1208 TypeDescriptor cdsType = new TypeDescriptor( cd );
1209 ExpressionNode conExp = con.getSurroundingClassExpression();
1210 //System.out.println( "The surrounding class expression si " + con );
1211 if( null == conExp ) {
1212 if( md.isStatic()) {
1213 throw new Error("trying to instantiate inner class: " + con.getType() + " in a static scope" );
1215 VarDescriptor thisVD = md.getThis();
1216 if( null == thisVD ) {
1217 throw new Error( "this pointer is not defined in a non static scope" );
1219 if( cdsType.equals( thisVD.getType() ) == false ) {
1220 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" );
1222 //make this into an expression node.
1223 NameNode nThis=new NameNode( new NameDescriptor( "this" ) );
1224 con.addArgument( nThis );
1227 //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.
1228 con.addArgument( conExp );
1230 //System.out.println( " the modified createObjectNode is " + con.printNode( 0 ) + "\n" );
1233 void trialSemanticCheck(ClassDescriptor cd) {
1234 if(!cd.getInline()) {
1235 throw new Error("Error! Try to do a trial check on a non-inline class " + cd.getSymbol());
1239 for (Iterator method_it = cd.getMethods(); method_it.hasNext(); ) {
1240 MethodDescriptor md = (MethodDescriptor) method_it.next();
1242 checkMethodBody(cd, md);
1244 System.out.println("Error in " + md);
1251 // add all the live vars that are referred by the inline class in the surrounding
1252 // context of the inline class into the inline class' field table and pass them to
1253 // the inline class' constructors
1254 // TODO: BUGFIX. These local vars should be final. But currently we've lost those
1255 // information, so we cannot have that checked.
1256 void InlineClassAddParamToCtor(MethodDescriptor md, ClassDescriptor cd , SymbolTable nametable, CreateObjectNode con, TypeDescriptor td, TypeDescriptor[] tdarray ) {
1257 // for an inline class, need to first add the original parameters of the CreatObjectNode
1258 // into its anonymous constructor and insert a super(...) into the anonymous constructor
1259 // if its super class is not null
1260 MethodDescriptor cd_construtor = null;
1261 for(Iterator it_methods = cd.getMethods(); it_methods.hasNext();) {
1262 MethodDescriptor imd = (MethodDescriptor)it_methods.next();
1263 if(imd.isConstructor()) {
1264 cd_construtor = imd; // an inline class should only have one anonymous constructor
1267 MethodInvokeNode min = null;
1268 if(cd.getSuper()!= null) {
1269 // add a super(...) into the anonymous constructor
1270 NameDescriptor nd=new NameDescriptor("super");
1271 min=new MethodInvokeNode(nd);
1272 BlockExpressionNode ben=new BlockExpressionNode(min);
1273 BlockNode bn = state.getMethodBody(cd_construtor);
1274 bn.addFirstBlockStatement(ben);
1276 for(int i = 0 ; i < tdarray.length; i++) {
1278 TypeDescriptor itd = tdarray[i];
1279 cd_construtor.addParameter(itd, itd.getSymbol()+"_from_con_node_"+i);
1280 min.addArgument(new NameNode(new NameDescriptor(itd.getSymbol()+"_from_con_node_"+i)));
1283 // Next add the live vars into the inline class' fields
1284 cd.setSurroundingNameTable(nametable);
1285 // do a round of semantic check trial to get all the live vars required by the inline class
1286 trialSemanticCheck(cd);
1287 Vector<VarDescriptor> vars = this.inlineClass2LiveVars.remove(cd);
1291 for(int i = 0; i < vars.size(); i++) {
1292 Descriptor d = vars.elementAt(i);
1293 if(d instanceof VarDescriptor && !d.getSymbol().equals("this")) {
1294 con.addArgument(new NameNode(new NameDescriptor(d.getSymbol())));
1295 cd.addField(new FieldDescriptor(new Modifiers(Modifiers.PUBLIC), ((VarDescriptor)d).getType(), d.getSymbol(), null, false));
1296 cd_construtor.addParameter(((VarDescriptor)d).getType(), d.getSymbol()+"_p");
1297 // add the initialize statement into this constructor
1298 BlockNode obn = state.getMethodBody(cd_construtor);
1299 NameNode nn=new NameNode(new NameDescriptor(d.getSymbol()));
1300 NameNode fn = new NameNode (new NameDescriptor(d.getSymbol()+"_p"));
1301 AssignmentNode an=new AssignmentNode(nn,fn,new AssignOperation(1));
1302 obn.addFirstBlockStatement(new BlockExpressionNode(an));
1303 state.addTreeCode(cd_construtor, obn);
1308 void checkCreateObjectNode(Descriptor md, SymbolTable nametable, CreateObjectNode con,
1309 TypeDescriptor td) {
1310 TypeDescriptor[] tdarray = new TypeDescriptor[con.numArgs()];
1311 for (int i = 0; i < con.numArgs(); i++) {
1312 ExpressionNode en = con.getArg(i);
1313 checkExpressionNode(md, nametable, en, null);
1314 tdarray[i] = en.getType();
1317 TypeDescriptor typetolookin = con.getType();
1318 checkTypeDescriptor(((md instanceof MethodDescriptor)?((MethodDescriptor)md).getClassDesc():null), typetolookin);
1320 if (td != null && !typeutil.isSuperorType(td, typetolookin))
1321 throw new Error(typetolookin + " isn't a " + td);
1323 /* Check Array Initializers */
1324 if ((con.getArrayInitializer() != null)) {
1325 checkArrayInitializerNode(md, nametable, con.getArrayInitializer(), typetolookin);
1328 if(this.trialcheck) {
1329 // for a trialcheck of an inline class, skip the rest process
1333 /* Check flag effects */
1334 if (con.getFlagEffects() != null) {
1335 FlagEffects fe = con.getFlagEffects();
1336 ClassDescriptor cd = typetolookin.getClassDesc();
1338 for (int j = 0; j < fe.numEffects(); j++) {
1339 FlagEffect flag = fe.getEffect(j);
1340 String name = flag.getName();
1341 FlagDescriptor flag_d = (FlagDescriptor) cd.getFlagTable().get(name);
1342 // Make sure the flag is declared
1344 throw new Error("Flag descriptor " + name + " undefined in class: " + cd.getSymbol());
1345 if (flag_d.getExternal())
1346 throw new Error("Attempting to modify external flag: " + name);
1347 flag.setFlag(flag_d);
1349 for (int j = 0; j < fe.numTagEffects(); j++) {
1350 TagEffect tag = fe.getTagEffect(j);
1351 String name = tag.getName();
1353 Descriptor d = (Descriptor) nametable.get(name);
1355 throw new Error("Tag descriptor " + name + " undeclared");
1356 else if (!(d instanceof TagVarDescriptor))
1357 throw new Error(name + " is not a tag descriptor");
1358 tag.setTag((TagVarDescriptor) d);
1362 if ((!typetolookin.isClass()) && (!typetolookin.isArray()))
1363 throw new Error("Can't allocate primitive type:" + con.printNode(0));
1365 if (!typetolookin.isArray()) {
1366 // Array's don't need constructor calls
1367 ClassDescriptor classtolookin = typetolookin.getClassDesc();
1368 checkClass(classtolookin, INIT);
1369 if( classtolookin.isInnerClass() ) {
1370 // for inner class that is declared in a static context, it does not have
1371 // lexically enclosing instances
1372 if(!classtolookin.getInStaticContext()) {
1373 InnerClassAddParamToCtor( (MethodDescriptor)md, ((MethodDescriptor)md).getClassDesc() , nametable, con, td );
1375 if(classtolookin.getInline()) {
1376 // for an inline anonymous inner class, the live local variables that are
1377 // referred to by the inline class are passed as parameters of the constructors
1378 // of the inline class
1379 InlineClassAddParamToCtor( (MethodDescriptor)md, classtolookin, nametable, con, td, tdarray );
1381 tdarray = new TypeDescriptor[con.numArgs()];
1382 for (int i = 0; i < con.numArgs(); i++) {
1383 ExpressionNode en = con.getArg(i);
1384 checkExpressionNode(md, nametable, en, null);
1385 tdarray[i] = en.getType();
1388 Set methoddescriptorset = classtolookin.getMethodTable().getSet(classtolookin.getSymbol());
1389 MethodDescriptor bestmd = null;
1390 NextMethod: for (Iterator methodit = methoddescriptorset.iterator(); methodit.hasNext(); ) {
1391 MethodDescriptor currmd = (MethodDescriptor) methodit.next();
1392 /* Need correct number of parameters */
1393 if (con.numArgs() != currmd.numParameters())
1395 for (int i = 0; i < con.numArgs(); i++) {
1396 if (!typeutil.isSuperorType(currmd.getParamType(i), tdarray[i]))
1397 continue NextMethod;
1399 /* Local allocations can't call global allocator */
1400 if (!con.isGlobal() && currmd.isGlobal())
1403 /* Method okay so far */
1407 if (typeutil.isMoreSpecific(currmd, bestmd, true)) {
1409 } else if (con.isGlobal() && match(currmd, bestmd)) {
1410 if (currmd.isGlobal() && !bestmd.isGlobal())
1412 else if (currmd.isGlobal() && bestmd.isGlobal())
1414 } else if (!typeutil.isMoreSpecific(bestmd, currmd, true)) {
1415 throw new Error("No method is most specific:" + bestmd + " and " + currmd);
1418 /* Is this more specific than bestmd */
1421 if (bestmd == null) {
1422 throw new Error("No method found for " + con.printNode(0) + " in " + md);
1424 con.setConstructor(bestmd);
1429 /** Check to see if md1 is the same specificity as md2.*/
1431 boolean match(MethodDescriptor md1, MethodDescriptor md2) {
1432 /* Checks if md1 is more specific than md2 */
1433 if (md1.numParameters()!=md2.numParameters())
1435 for(int i=0; i<md1.numParameters(); i++) {
1436 if (!md2.getParamType(i).equals(md1.getParamType(i)))
1439 if (!md2.getReturnType().equals(md1.getReturnType()))
1442 if (!md2.getClassDesc().equals(md1.getClassDesc()))
1450 ExpressionNode translateNameDescriptorintoExpression(NameDescriptor nd, int numLine) {
1451 String id=nd.getIdentifier();
1452 NameDescriptor base=nd.getBase();
1454 NameNode nn=new NameNode(nd);
1455 nn.setNumLine(numLine);
1458 FieldAccessNode fan=new FieldAccessNode(translateNameDescriptorintoExpression(base,numLine),id);
1459 fan.setNumLine(numLine);
1464 MethodDescriptor recurseSurroundingClassesM( ClassDescriptor icd, String varname ) {
1465 if( null == icd || false == icd.isInnerClass() )
1468 ClassDescriptor surroundingDesc = icd.getSurroundingDesc();
1469 if( null == surroundingDesc )
1472 SymbolTable methodTable = surroundingDesc.getMethodTable();
1473 MethodDescriptor md = ( MethodDescriptor ) methodTable.get( varname );
1476 return recurseSurroundingClassesM( surroundingDesc, varname );
1479 ExpressionNode methodInvocationExpression( ClassDescriptor icd, MethodDescriptor md, int linenum ) {
1480 ClassDescriptor cd = md.getClassDesc();
1482 int startingDepth = icd.getInnerDepth();
1484 if( true == cd.isInnerClass() )
1485 depth = cd.getInnerDepth();
1487 String composed = "this";
1488 NameDescriptor runningDesc = new NameDescriptor( "this" );;
1490 for ( int index = startingDepth; index > depth; --index ) {
1491 composed = "this$" + String.valueOf( index - 1 );
1492 runningDesc = new NameDescriptor( runningDesc, composed );
1494 if( false == cd.isInnerClass() )
1495 runningDesc = new NameDescriptor( runningDesc, "this$" + String.valueOf(0) ); //all the way up.
1497 return new NameNode(runningDesc);
1500 void checkMethodInvokeNode(Descriptor md, SymbolTable nametable, MethodInvokeNode min, TypeDescriptor td) {
1501 /*Typecheck subexpressions
1502 and get types for expressions*/
1504 boolean isstatic = false;
1505 if((md instanceof MethodDescriptor) && ((MethodDescriptor)md).isStatic()) {
1508 TypeDescriptor[] tdarray=new TypeDescriptor[min.numArgs()];
1509 for(int i=0; i<min.numArgs(); i++) {
1510 ExpressionNode en=min.getArg(i);
1511 checkExpressionNode(md,nametable,en,null);
1512 tdarray[i]=en.getType();
1514 if(en.getType().isClass() && en.getType().getClassDesc().isEnum()) {
1515 tdarray[i] = new TypeDescriptor(TypeDescriptor.INT);
1518 TypeDescriptor typetolookin=null;
1519 if (min.getExpression()!=null) {
1520 checkExpressionNode(md,nametable,min.getExpression(),null);
1521 typetolookin=min.getExpression().getType();
1522 } else if (min.getBaseName()!=null) {
1523 String rootname=min.getBaseName().getRoot();
1524 if (rootname.equals("super")) {
1525 ClassDescriptor supercd=((MethodDescriptor)md).getClassDesc().getSuperDesc();
1526 typetolookin=new TypeDescriptor(supercd);
1528 } else if (rootname.equals("this")) {
1530 throw new Error("use this object in static method md = "+ md.toString());
1532 ClassDescriptor cd=((MethodDescriptor)md).getClassDesc();
1533 typetolookin=new TypeDescriptor(cd);
1534 } else if (nametable.get(rootname)!=null) {
1535 //we have an expression
1536 min.setExpression(translateNameDescriptorintoExpression(min.getBaseName(),min.getNumLine()));
1537 checkExpressionNode(md, nametable, min.getExpression(), null);
1538 typetolookin=min.getExpression().getType();
1540 if(!min.getBaseName().getSymbol().equals("System.out")||state.JNI) {
1541 ExpressionNode nn = translateNameDescriptorintoExpression(min.getBaseName(),min.getNumLine());
1542 checkExpressionNode(md, nametable, nn, null);
1543 typetolookin = nn.getType();
1544 if(!((nn.kind()== Kind.NameNode) && (((NameNode)nn).getField() == null)
1545 && (((NameNode)nn).getVar() == null) && (((NameNode)nn).getExpression() == null))) {
1546 // this is not a pure class name, need to add to
1547 min.setExpression(nn);
1551 ClassDescriptor cd = getClass(null, "System");
1554 throw new Error("md = "+ md.toString()+ " "+min.getBaseName()+" undefined");
1555 typetolookin=new TypeDescriptor(cd);
1558 } else if ((md instanceof MethodDescriptor)&&min.getMethodName().equals("super")) {
1559 ClassDescriptor supercd=((MethodDescriptor)md).getClassDesc().getSuperDesc();
1560 min.methodid=supercd.getSymbol();
1561 typetolookin=new TypeDescriptor(supercd);
1562 } else if (md instanceof MethodDescriptor) {
1563 typetolookin=new TypeDescriptor(((MethodDescriptor)md).getClassDesc());
1565 /* If this a task descriptor we throw an error at this point */
1566 throw new Error("Unknown method call to "+min.getMethodName()+"in task"+md.getSymbol());
1568 if (!typetolookin.isClass())
1569 throw new Error("Error with method call to "+min.getMethodName()+" in class "+typetolookin);
1570 ClassDescriptor classtolookin=typetolookin.getClassDesc();
1571 checkClass(classtolookin, REFERENCE);
1572 Set methoddescriptorset=classtolookin.getMethodTable().getSet(min.getMethodName());
1573 MethodDescriptor bestmd=null;
1575 for(Iterator methodit=methoddescriptorset.iterator(); methodit.hasNext(); ) {
1576 MethodDescriptor currmd=(MethodDescriptor)methodit.next();
1577 /* Need correct number of parameters */
1578 if (min.numArgs()!=currmd.numParameters())
1580 for(int i=0; i<min.numArgs(); i++) {
1581 if (!typeutil.isSuperorType(currmd.getParamType(i),tdarray[i]))
1582 if(((!tdarray[i].isArray() &&(tdarray[i].isInt() || tdarray[i].isLong()))
1583 && currmd.getParamType(i).isClass() && currmd.getParamType(i).getClassDesc().getSymbol().equals("Object"))) {
1584 // primitive parameters vs object
1586 continue NextMethod;
1589 /* Method okay so far */
1593 if (typeutil.isMoreSpecific(currmd,bestmd, false)) {
1595 } else if (!typeutil.isMoreSpecific(bestmd, currmd, false))
1596 throw new Error("No method is most specific:"+bestmd+" and "+currmd);
1598 /* Is this more specific than bestmd */
1602 // if this is an inner class, need to check the method table for the surrounding class
1603 bestmd = recurseSurroundingClassesM(classtolookin, min.getMethodName());
1605 throw new Error("No method found for :"+min.printNode(0)+" in class: " + classtolookin+" in "+md);
1607 // set the correct "this" expression here
1608 ExpressionNode en=methodInvocationExpression(classtolookin, bestmd, min.getNumLine());
1609 min.setExpression(en);
1610 checkExpressionNode(md, nametable, min.getExpression(), null);
1613 min.setMethod(bestmd);
1615 if ((td!=null)&&(min.getType()!=null)&&!typeutil.isSuperorType(td, min.getType()))
1616 throw new Error(min.getType()+ " is not equal to or a subclass of "+td);
1617 /* Check whether we need to set this parameter to implied this */
1618 if (!isstatic && !bestmd.isStatic()) {
1619 if (min.getExpression()==null) {
1620 ExpressionNode en=new NameNode(new NameDescriptor("this"));
1621 min.setExpression(en);
1622 checkExpressionNode(md, nametable, min.getExpression(), null);
1626 /* Check if we need to wrap primitive paratmeters to objects */
1627 for(int i=0; i<min.numArgs(); i++) {
1628 if(!tdarray[i].isArray() && (tdarray[i].isInt() || tdarray[i].isLong())
1629 && min.getMethod().getParamType(i).isClass() && min.getMethod().getParamType(i).getClassDesc().getSymbol().equals("Object")) {
1630 // Shall wrap this primitive parameter as a object
1631 ExpressionNode exp = min.getArg(i);
1632 TypeDescriptor ptd = null;
1633 NameDescriptor nd=null;
1634 if(exp.getType().isInt()) {
1635 nd = new NameDescriptor("Integer");
1636 ptd = state.getTypeDescriptor(nd);
1637 } else if(exp.getType().isLong()) {
1638 nd = new NameDescriptor("Long");
1639 ptd = state.getTypeDescriptor(nd);
1641 boolean isglobal = false;
1642 String disjointId = null;
1643 CreateObjectNode con=new CreateObjectNode(ptd, isglobal, disjointId);
1644 con.addArgument(exp);
1645 checkExpressionNode(md, nametable, con, null);
1646 min.setArgument(con, i);
1652 void checkOpNode(Descriptor md, SymbolTable nametable, OpNode on, TypeDescriptor td) {
1653 checkExpressionNode(md, nametable, on.getLeft(), null);
1654 if (on.getRight()!=null)
1655 checkExpressionNode(md, nametable, on.getRight(), null);
1656 TypeDescriptor ltd=on.getLeft().getType();
1657 TypeDescriptor rtd=on.getRight()!=null?on.getRight().getType():null;
1658 TypeDescriptor lefttype=null;
1659 TypeDescriptor righttype=null;
1660 Operation op=on.getOp();
1662 switch(op.getOp()) {
1663 case Operation.LOGIC_OR:
1664 case Operation.LOGIC_AND:
1665 if (!(rtd.isBoolean()))
1667 on.setRightType(rtd);
1669 case Operation.LOGIC_NOT:
1670 if (!(ltd.isBoolean()))
1673 on.setLeftType(ltd);
1675 on.setType(new TypeDescriptor(TypeDescriptor.BOOLEAN));
1678 case Operation.COMP:
1679 // 5.6.2 Binary Numeric Promotion
1680 //TODO unboxing of reference objects
1683 else if (ltd.isFloat())
1685 else if (ltd.isLong())
1686 lefttype=new TypeDescriptor(TypeDescriptor.LONG);
1688 lefttype=new TypeDescriptor(TypeDescriptor.INT);
1689 on.setLeftType(lefttype);
1690 on.setType(lefttype);
1693 case Operation.BIT_OR:
1694 case Operation.BIT_XOR:
1695 case Operation.BIT_AND:
1696 // 5.6.2 Binary Numeric Promotion
1697 //TODO unboxing of reference objects
1698 if (ltd.isDouble()||rtd.isDouble())
1700 else if (ltd.isFloat()||rtd.isFloat())
1702 else if (ltd.isLong()||rtd.isLong())
1703 lefttype=new TypeDescriptor(TypeDescriptor.LONG);
1704 // 090205 hack for boolean
1705 else if (ltd.isBoolean()||rtd.isBoolean())
1706 lefttype=new TypeDescriptor(TypeDescriptor.BOOLEAN);
1708 lefttype=new TypeDescriptor(TypeDescriptor.INT);
1711 on.setLeftType(lefttype);
1712 on.setRightType(righttype);
1713 on.setType(lefttype);
1716 case Operation.ISAVAILABLE:
1717 if (!(ltd.isPtr())) {
1718 throw new Error("Can't use isavailable on non-pointers/non-parameters.");
1721 on.setLeftType(lefttype);
1722 on.setType(new TypeDescriptor(TypeDescriptor.BOOLEAN));
1725 case Operation.EQUAL:
1726 case Operation.NOTEQUAL:
1727 // 5.6.2 Binary Numeric Promotion
1728 //TODO unboxing of reference objects
1729 if (ltd.isBoolean()||rtd.isBoolean()) {
1730 if (!(ltd.isBoolean()&&rtd.isBoolean()))
1732 righttype=lefttype=new TypeDescriptor(TypeDescriptor.BOOLEAN);
1733 } else if (ltd.isPtr()||rtd.isPtr()) {
1734 if (!(ltd.isPtr()&&rtd.isPtr())) {
1741 } else if (ltd.isDouble()||rtd.isDouble())
1742 righttype=lefttype=new TypeDescriptor(TypeDescriptor.DOUBLE);
1743 else if (ltd.isFloat()||rtd.isFloat())
1744 righttype=lefttype=new TypeDescriptor(TypeDescriptor.FLOAT);
1745 else if (ltd.isLong()||rtd.isLong())
1746 righttype=lefttype=new TypeDescriptor(TypeDescriptor.LONG);
1748 righttype=lefttype=new TypeDescriptor(TypeDescriptor.INT);
1750 on.setLeftType(lefttype);
1751 on.setRightType(righttype);
1752 on.setType(new TypeDescriptor(TypeDescriptor.BOOLEAN));
1761 // 5.6.2 Binary Numeric Promotion
1762 //TODO unboxing of reference objects
1763 if (!ltd.isNumber()||!rtd.isNumber()) {
1764 if (!ltd.isNumber())
1765 throw new Error("Leftside is not number"+on.printNode(0)+"type="+ltd.toPrettyString());
1766 if (!rtd.isNumber())
1767 throw new Error("Rightside is not number"+on.printNode(0));
1770 if (ltd.isDouble()||rtd.isDouble())
1771 lefttype=new TypeDescriptor(TypeDescriptor.DOUBLE);
1772 else if (ltd.isFloat()||rtd.isFloat())
1773 lefttype=new TypeDescriptor(TypeDescriptor.FLOAT);
1774 else if (ltd.isLong()||rtd.isLong())
1775 lefttype=new TypeDescriptor(TypeDescriptor.LONG);
1777 lefttype=new TypeDescriptor(TypeDescriptor.INT);
1779 on.setLeftType(lefttype);
1780 on.setRightType(righttype);
1781 on.setType(new TypeDescriptor(TypeDescriptor.BOOLEAN));
1785 if (ltd.isString()||rtd.isString()) {
1786 ClassDescriptor stringcl=getClass(null, TypeUtil.StringClass);
1787 TypeDescriptor stringtd=new TypeDescriptor(stringcl);
1788 NameDescriptor nd=new NameDescriptor("String");
1789 NameDescriptor valuend=new NameDescriptor(nd, "valueOf");
1790 if (!(ltd.isString()&&(on.getLeft() instanceof OpNode))) {
1791 MethodInvokeNode leftmin=new MethodInvokeNode(valuend);
1792 leftmin.setNumLine(on.getLeft().getNumLine());
1793 leftmin.addArgument(on.getLeft());
1795 checkExpressionNode(md, nametable, on.getLeft(), null);
1798 if (!(rtd.isString()&&(on.getRight() instanceof OpNode))) {
1799 MethodInvokeNode rightmin=new MethodInvokeNode(valuend);
1800 rightmin.setNumLine(on.getRight().getNumLine());
1801 rightmin.addArgument(on.getRight());
1803 checkExpressionNode(md, nametable, on.getRight(), null);
1806 on.setLeftType(stringtd);
1807 on.setRightType(stringtd);
1808 on.setType(stringtd);
1813 case Operation.MULT:
1816 // 5.6.2 Binary Numeric Promotion
1817 //TODO unboxing of reference objects
1818 if (ltd.isArray()||rtd.isArray()||!ltd.isNumber()||!rtd.isNumber())
1819 throw new Error("Error in "+on.printNode(0));
1821 if (ltd.isDouble()||rtd.isDouble())
1822 lefttype=new TypeDescriptor(TypeDescriptor.DOUBLE);
1823 else if (ltd.isFloat()||rtd.isFloat())
1824 lefttype=new TypeDescriptor(TypeDescriptor.FLOAT);
1825 else if (ltd.isLong()||rtd.isLong())
1826 lefttype=new TypeDescriptor(TypeDescriptor.LONG);
1828 lefttype=new TypeDescriptor(TypeDescriptor.INT);
1830 on.setLeftType(lefttype);
1831 on.setRightType(righttype);
1832 on.setType(lefttype);
1835 case Operation.LEFTSHIFT:
1836 case Operation.RIGHTSHIFT:
1837 case Operation.URIGHTSHIFT:
1838 if (!rtd.isIntegerType())
1840 //5.6.1 Unary Numeric Promotion
1841 if (rtd.isByte()||rtd.isShort()||rtd.isInt())
1842 righttype=new TypeDescriptor(TypeDescriptor.INT);
1846 on.setRightType(righttype);
1847 if (!ltd.isIntegerType())
1850 case Operation.UNARYPLUS:
1851 case Operation.UNARYMINUS:
1852 /* case Operation.POSTINC:
1853 case Operation.POSTDEC:
1854 case Operation.PREINC:
1855 case Operation.PREDEC:*/
1856 if (!ltd.isNumber())
1858 //5.6.1 Unary Numeric Promotion
1859 if (ltd.isByte()||ltd.isShort()||ltd.isInt())
1860 lefttype=new TypeDescriptor(TypeDescriptor.INT);
1863 on.setLeftType(lefttype);
1864 on.setType(lefttype);
1868 throw new Error(op.toString());
1872 if (!typeutil.isSuperorType(td, on.getType())) {
1873 throw new Error("Type of rside not compatible with type of lside"+on.printNode(0));