41439daac6f3976d774d59078f981f69d027be1e
[IRC.git] / Robust / src / Analysis / SSJava / FlowDownCheck.java
1 package Analysis.SSJava;
2
3 import java.util.ArrayList;
4 import java.util.HashSet;
5 import java.util.Hashtable;
6 import java.util.Iterator;
7 import java.util.List;
8 import java.util.Set;
9 import java.util.StringTokenizer;
10 import java.util.Vector;
11
12 import Analysis.SSJava.FlowDownCheck.ComparisonResult;
13 import Analysis.SSJava.FlowDownCheck.CompositeLattice;
14 import IR.AnnotationDescriptor;
15 import IR.ClassDescriptor;
16 import IR.Descriptor;
17 import IR.FieldDescriptor;
18 import IR.MethodDescriptor;
19 import IR.NameDescriptor;
20 import IR.Operation;
21 import IR.State;
22 import IR.SymbolTable;
23 import IR.TypeDescriptor;
24 import IR.VarDescriptor;
25 import IR.Tree.ArrayAccessNode;
26 import IR.Tree.AssignmentNode;
27 import IR.Tree.BlockExpressionNode;
28 import IR.Tree.BlockNode;
29 import IR.Tree.BlockStatementNode;
30 import IR.Tree.CastNode;
31 import IR.Tree.CreateObjectNode;
32 import IR.Tree.DeclarationNode;
33 import IR.Tree.ExpressionNode;
34 import IR.Tree.FieldAccessNode;
35 import IR.Tree.IfStatementNode;
36 import IR.Tree.Kind;
37 import IR.Tree.LiteralNode;
38 import IR.Tree.LoopNode;
39 import IR.Tree.MethodInvokeNode;
40 import IR.Tree.NameNode;
41 import IR.Tree.OpNode;
42 import IR.Tree.ReturnNode;
43 import IR.Tree.SubBlockNode;
44 import IR.Tree.SwitchBlockNode;
45 import IR.Tree.SwitchStatementNode;
46 import IR.Tree.TertiaryNode;
47 import IR.Tree.TreeNode;
48 import Util.Pair;
49
50 public class FlowDownCheck {
51
52   State state;
53   static SSJavaAnalysis ssjava;
54
55   HashSet toanalyze;
56
57   // mapping from 'descriptor' to 'composite location'
58   Hashtable<Descriptor, CompositeLocation> d2loc;
59
60   Hashtable<MethodDescriptor, CompositeLocation> md2ReturnLoc;
61   Hashtable<MethodDescriptor, ReturnLocGenerator> md2ReturnLocGen;
62
63   // mapping from 'locID' to 'class descriptor'
64   Hashtable<String, ClassDescriptor> fieldLocName2cd;
65
66   public FlowDownCheck(SSJavaAnalysis ssjava, State state) {
67     this.ssjava = ssjava;
68     this.state = state;
69     this.toanalyze = new HashSet();
70     this.d2loc = new Hashtable<Descriptor, CompositeLocation>();
71     this.fieldLocName2cd = new Hashtable<String, ClassDescriptor>();
72     this.md2ReturnLoc = new Hashtable<MethodDescriptor, CompositeLocation>();
73     this.md2ReturnLocGen = new Hashtable<MethodDescriptor, ReturnLocGenerator>();
74   }
75
76   public void init() {
77
78     // construct mapping from the location name to the class descriptor
79     // assume that the location name is unique through the whole program
80
81     Set<ClassDescriptor> cdSet = ssjava.getCd2lattice().keySet();
82     for (Iterator iterator = cdSet.iterator(); iterator.hasNext();) {
83       ClassDescriptor cd = (ClassDescriptor) iterator.next();
84       SSJavaLattice<String> lattice = ssjava.getCd2lattice().get(cd);
85       Set<String> fieldLocNameSet = lattice.getKeySet();
86
87       for (Iterator iterator2 = fieldLocNameSet.iterator(); iterator2.hasNext();) {
88         String fieldLocName = (String) iterator2.next();
89         fieldLocName2cd.put(fieldLocName, cd);
90       }
91
92     }
93
94   }
95
96   public void flowDownCheck() {
97     SymbolTable classtable = state.getClassSymbolTable();
98
99     // phase 1 : checking declaration node and creating mapping of 'type
100     // desciptor' & 'location'
101     toanalyze.addAll(classtable.getValueSet());
102     toanalyze.addAll(state.getTaskSymbolTable().getValueSet());
103
104     while (!toanalyze.isEmpty()) {
105       Object obj = toanalyze.iterator().next();
106       ClassDescriptor cd = (ClassDescriptor) obj;
107       toanalyze.remove(cd);
108
109       if (ssjava.needToBeAnnoated(cd)) {
110
111         ClassDescriptor superDesc = cd.getSuperDesc();
112
113         if (superDesc != null && (!superDesc.getSymbol().equals("Object"))) {
114           checkOrderingInheritance(superDesc, cd);
115         }
116
117         checkDeclarationInClass(cd);
118         for (Iterator method_it = cd.getMethods(); method_it.hasNext();) {
119           MethodDescriptor md = (MethodDescriptor) method_it.next();
120           if (ssjava.needTobeAnnotated(md)) {
121             checkDeclarationInMethodBody(cd, md);
122           }
123         }
124       }
125
126     }
127
128     // phase2 : checking assignments
129     toanalyze.addAll(classtable.getValueSet());
130     toanalyze.addAll(state.getTaskSymbolTable().getValueSet());
131     while (!toanalyze.isEmpty()) {
132       Object obj = toanalyze.iterator().next();
133       ClassDescriptor cd = (ClassDescriptor) obj;
134       toanalyze.remove(cd);
135
136       checkClass(cd);
137       for (Iterator method_it = cd.getMethods(); method_it.hasNext();) {
138         MethodDescriptor md = (MethodDescriptor) method_it.next();
139         if (ssjava.needTobeAnnotated(md)) {
140           checkMethodBody(cd, md);
141         }
142       }
143     }
144
145   }
146
147   private void checkOrderingInheritance(ClassDescriptor superCd, ClassDescriptor cd) {
148     // here, we're going to check that sub class keeps same relative orderings
149     // in respect to super class
150
151     SSJavaLattice<String> superLattice = ssjava.getClassLattice(superCd);
152     SSJavaLattice<String> subLattice = ssjava.getClassLattice(cd);
153
154     if (superLattice != null) {
155       // if super class doesn't define lattice, then we don't need to check its
156       // subclass
157       if (subLattice == null) {
158         throw new Error("If a parent class '" + superCd
159             + "' has a ordering lattice, its subclass '" + cd + "' should have one.");
160       }
161
162       Set<Pair<String, String>> superPairSet = superLattice.getOrderingPairSet();
163       Set<Pair<String, String>> subPairSet = subLattice.getOrderingPairSet();
164
165       for (Iterator iterator = superPairSet.iterator(); iterator.hasNext();) {
166         Pair<String, String> pair = (Pair<String, String>) iterator.next();
167
168         if (!subPairSet.contains(pair)) {
169           throw new Error("Subclass '" + cd + "' does not have the relative ordering '"
170               + pair.getSecond() + " < " + pair.getFirst()
171               + "' that is defined by its superclass '" + superCd + "'.");
172         }
173       }
174     }
175
176     MethodLattice<String> superMethodDefaultLattice = ssjava.getMethodDefaultLattice(superCd);
177     MethodLattice<String> subMethodDefaultLattice = ssjava.getMethodDefaultLattice(cd);
178
179     if (superMethodDefaultLattice != null) {
180       if (subMethodDefaultLattice == null) {
181         throw new Error("When a parent class '" + superCd
182             + "' defines a default method lattice, its subclass '" + cd + "' should define one.");
183       }
184
185       Set<Pair<String, String>> superPairSet = superMethodDefaultLattice.getOrderingPairSet();
186       Set<Pair<String, String>> subPairSet = subMethodDefaultLattice.getOrderingPairSet();
187
188       for (Iterator iterator = superPairSet.iterator(); iterator.hasNext();) {
189         Pair<String, String> pair = (Pair<String, String>) iterator.next();
190
191         if (!subPairSet.contains(pair)) {
192           throw new Error("Subclass '" + cd + "' does not have the relative ordering '"
193               + pair.getSecond() + " < " + pair.getFirst()
194               + "' that is defined by its superclass '" + superCd
195               + "' in the method default lattice.");
196         }
197       }
198
199     }
200
201   }
202
203   public Hashtable getMap() {
204     return d2loc;
205   }
206
207   private void checkDeclarationInMethodBody(ClassDescriptor cd, MethodDescriptor md) {
208     BlockNode bn = state.getMethodBody(md);
209
210     if (ssjava.needTobeAnnotated(md)) {
211
212       // parsing returnloc annotation
213       Vector<AnnotationDescriptor> methodAnnotations = md.getModifiers().getAnnotations();
214       if (methodAnnotations != null) {
215         for (int i = 0; i < methodAnnotations.size(); i++) {
216           AnnotationDescriptor an = methodAnnotations.elementAt(i);
217           if (an.getMarker().equals(ssjava.RETURNLOC)) {
218             // developer explicitly defines method lattice
219             String returnLocDeclaration = an.getValue();
220             CompositeLocation returnLocComp =
221                 parseLocationDeclaration(md, null, returnLocDeclaration);
222             md2ReturnLoc.put(md, returnLocComp);
223           }
224         }
225         if (!md.getReturnType().isVoid() && !md2ReturnLoc.containsKey(md)) {
226           throw new Error("Return location is not specified for the method " + md + " at "
227               + cd.getSourceFileName());
228         }
229       }
230
231       List<CompositeLocation> paramList = new ArrayList<CompositeLocation>();
232
233       boolean hasReturnValue = (!md.getReturnType().isVoid());
234       if (hasReturnValue) {
235         MethodLattice<String> methodLattice = ssjava.getMethodLattice(md);
236         String thisLocId = methodLattice.getThisLoc();
237         if (thisLocId == null) {
238           throw new Error("Method '" + md + "' does not have the definition of 'this' location at "
239               + md.getClassDesc().getSourceFileName());
240         }
241         CompositeLocation thisLoc = new CompositeLocation(new Location(md, thisLocId));
242         paramList.add(thisLoc);
243       }
244
245       for (int i = 0; i < md.numParameters(); i++) {
246         // process annotations on method parameters
247         VarDescriptor vd = (VarDescriptor) md.getParameter(i);
248         assignLocationOfVarDescriptor(vd, md, md.getParameterTable(), bn);
249         if (hasReturnValue) {
250           paramList.add(d2loc.get(vd));
251         }
252       }
253
254       if (hasReturnValue) {
255         md2ReturnLocGen.put(md, new ReturnLocGenerator(md2ReturnLoc.get(md), paramList,
256             generateErrorMessage(cd, null)));
257       }
258       checkDeclarationInBlockNode(md, md.getParameterTable(), bn);
259     }
260
261   }
262
263   private void checkDeclarationInBlockNode(MethodDescriptor md, SymbolTable nametable, BlockNode bn) {
264     bn.getVarTable().setParent(nametable);
265     for (int i = 0; i < bn.size(); i++) {
266       BlockStatementNode bsn = bn.get(i);
267       checkDeclarationInBlockStatementNode(md, bn.getVarTable(), bsn);
268     }
269   }
270
271   private void checkDeclarationInBlockStatementNode(MethodDescriptor md, SymbolTable nametable,
272       BlockStatementNode bsn) {
273
274     switch (bsn.kind()) {
275     case Kind.SubBlockNode:
276       checkDeclarationInSubBlockNode(md, nametable, (SubBlockNode) bsn);
277       return;
278
279     case Kind.DeclarationNode:
280       checkDeclarationNode(md, nametable, (DeclarationNode) bsn);
281       break;
282
283     case Kind.LoopNode:
284       checkDeclarationInLoopNode(md, nametable, (LoopNode) bsn);
285       break;
286     }
287   }
288
289   private void checkDeclarationInLoopNode(MethodDescriptor md, SymbolTable nametable, LoopNode ln) {
290
291     if (ln.getType() == LoopNode.FORLOOP) {
292       // check for loop case
293       ClassDescriptor cd = md.getClassDesc();
294       BlockNode bn = ln.getInitializer();
295       for (int i = 0; i < bn.size(); i++) {
296         BlockStatementNode bsn = bn.get(i);
297         checkDeclarationInBlockStatementNode(md, nametable, bsn);
298       }
299     }
300
301     // check loop body
302     checkDeclarationInBlockNode(md, nametable, ln.getBody());
303   }
304
305   private void checkMethodBody(ClassDescriptor cd, MethodDescriptor md) {
306     BlockNode bn = state.getMethodBody(md);
307     checkLocationFromBlockNode(md, md.getParameterTable(), bn);
308   }
309
310   private String generateErrorMessage(ClassDescriptor cd, TreeNode tn) {
311     if (tn != null) {
312       return cd.getSourceFileName() + "::" + tn.getNumLine();
313     } else {
314       return cd.getSourceFileName();
315     }
316
317   }
318
319   private CompositeLocation checkLocationFromBlockNode(MethodDescriptor md, SymbolTable nametable,
320       BlockNode bn) {
321
322     bn.getVarTable().setParent(nametable);
323     // it will return the lowest location in the block node
324     CompositeLocation lowestLoc = null;
325
326     for (int i = 0; i < bn.size(); i++) {
327       BlockStatementNode bsn = bn.get(i);
328       CompositeLocation bLoc = checkLocationFromBlockStatementNode(md, bn.getVarTable(), bsn);
329       if (!bLoc.isEmpty()) {
330         if (lowestLoc == null) {
331           lowestLoc = bLoc;
332         } else {
333           if (CompositeLattice.isGreaterThan(lowestLoc, bLoc,
334               generateErrorMessage(md.getClassDesc(), bn))) {
335             lowestLoc = bLoc;
336           }
337         }
338       }
339
340     }
341
342     if (lowestLoc == null) {
343       lowestLoc = new CompositeLocation(Location.createBottomLocation(md));
344     }
345
346     return lowestLoc;
347   }
348
349   private CompositeLocation checkLocationFromBlockStatementNode(MethodDescriptor md,
350       SymbolTable nametable, BlockStatementNode bsn) {
351
352     CompositeLocation compLoc = null;
353     switch (bsn.kind()) {
354     case Kind.BlockExpressionNode:
355       compLoc = checkLocationFromBlockExpressionNode(md, nametable, (BlockExpressionNode) bsn);
356       break;
357
358     case Kind.DeclarationNode:
359       compLoc = checkLocationFromDeclarationNode(md, nametable, (DeclarationNode) bsn);
360       break;
361
362     case Kind.IfStatementNode:
363       compLoc = checkLocationFromIfStatementNode(md, nametable, (IfStatementNode) bsn);
364       break;
365
366     case Kind.LoopNode:
367       compLoc = checkLocationFromLoopNode(md, nametable, (LoopNode) bsn);
368       break;
369
370     case Kind.ReturnNode:
371       compLoc = checkLocationFromReturnNode(md, nametable, (ReturnNode) bsn);
372       break;
373
374     case Kind.SubBlockNode:
375       compLoc = checkLocationFromSubBlockNode(md, nametable, (SubBlockNode) bsn);
376       break;
377
378     case Kind.ContinueBreakNode:
379       compLoc = new CompositeLocation();
380       break;
381
382     case Kind.SwitchStatementNode:
383       compLoc = checkLocationFromSwitchStatementNode(md, nametable, (SwitchStatementNode) bsn);
384
385     }
386     return compLoc;
387   }
388
389   private CompositeLocation checkLocationFromSwitchStatementNode(MethodDescriptor md,
390       SymbolTable nametable, SwitchStatementNode ssn) {
391
392     ClassDescriptor cd = md.getClassDesc();
393     CompositeLocation condLoc =
394         checkLocationFromExpressionNode(md, nametable, ssn.getCondition(), new CompositeLocation());
395     BlockNode sbn = ssn.getSwitchBody();
396
397     Set<CompositeLocation> blockLocSet = new HashSet<CompositeLocation>();
398     for (int i = 0; i < sbn.size(); i++) {
399       CompositeLocation blockLoc =
400           checkLocationFromSwitchBlockNode(md, nametable, (SwitchBlockNode) sbn.get(i));
401       if (!CompositeLattice.isGreaterThan(condLoc, blockLoc,
402           generateErrorMessage(cd, ssn.getCondition()))) {
403         throw new Error(
404             "The location of the switch-condition statement is lower than the conditional body at "
405                 + cd.getSourceFileName() + ":" + ssn.getCondition().getNumLine());
406       }
407
408       blockLocSet.add(blockLoc);
409     }
410     return CompositeLattice.calculateGLB(blockLocSet);
411   }
412
413   private CompositeLocation checkLocationFromSwitchBlockNode(MethodDescriptor md,
414       SymbolTable nametable, SwitchBlockNode sbn) {
415
416     CompositeLocation blockLoc =
417         checkLocationFromBlockNode(md, nametable, sbn.getSwitchBlockStatement());
418
419     return blockLoc;
420
421   }
422
423   private CompositeLocation checkLocationFromReturnNode(MethodDescriptor md, SymbolTable nametable,
424       ReturnNode rn) {
425
426     ExpressionNode returnExp = rn.getReturnExpression();
427
428     CompositeLocation returnValueLoc;
429     if (returnExp != null) {
430       returnValueLoc =
431           checkLocationFromExpressionNode(md, nametable, returnExp, new CompositeLocation());
432
433       // check if return value is equal or higher than RETRUNLOC of method
434       // declaration annotation
435       CompositeLocation declaredReturnLoc = md2ReturnLoc.get(md);
436
437       System.out.println("\nreturnLocAt=" + declaredReturnLoc);
438       System.out.println("returnValueLoc=" + returnValueLoc);
439       System.out.println("COMPARE RESULT="
440           + CompositeLattice.compare(declaredReturnLoc, returnValueLoc,
441               generateErrorMessage(md.getClassDesc(), rn)));
442
443       int compareResult =
444           CompositeLattice.compare(returnValueLoc, declaredReturnLoc,
445               generateErrorMessage(md.getClassDesc(), rn));
446
447       if (compareResult == ComparisonResult.LESS || compareResult == ComparisonResult.INCOMPARABLE) {
448         throw new Error(
449             "Return value location is not equal or higher than the declaraed return location at "
450                 + md.getClassDesc().getSourceFileName() + "::" + rn.getNumLine());
451       }
452     }
453
454     return new CompositeLocation();
455   }
456
457   private boolean hasOnlyLiteralValue(ExpressionNode en) {
458     if (en.kind() == Kind.LiteralNode) {
459       return true;
460     } else {
461       return false;
462     }
463   }
464
465   private CompositeLocation checkLocationFromLoopNode(MethodDescriptor md, SymbolTable nametable,
466       LoopNode ln) {
467
468     ClassDescriptor cd = md.getClassDesc();
469     if (ln.getType() == LoopNode.WHILELOOP || ln.getType() == LoopNode.DOWHILELOOP) {
470
471       CompositeLocation condLoc =
472           checkLocationFromExpressionNode(md, nametable, ln.getCondition(), new CompositeLocation());
473       addLocationType(ln.getCondition().getType(), (condLoc));
474
475       CompositeLocation bodyLoc = checkLocationFromBlockNode(md, nametable, ln.getBody());
476
477       if (!CompositeLattice.isGreaterThan(condLoc, bodyLoc, generateErrorMessage(cd, ln))) {
478         // loop condition should be higher than loop body
479         throw new Error(
480             "The location of the while-condition statement is lower than the loop body at "
481                 + cd.getSourceFileName() + ":" + ln.getCondition().getNumLine());
482       }
483
484       return bodyLoc;
485
486     } else {
487       // check for loop case
488       BlockNode bn = ln.getInitializer();
489       bn.getVarTable().setParent(nametable);
490
491       // calculate glb location of condition and update statements
492       CompositeLocation condLoc =
493           checkLocationFromExpressionNode(md, bn.getVarTable(), ln.getCondition(),
494               new CompositeLocation());
495       addLocationType(ln.getCondition().getType(), condLoc);
496
497       CompositeLocation updateLoc =
498           checkLocationFromBlockNode(md, bn.getVarTable(), ln.getUpdate());
499
500       Set<CompositeLocation> glbInputSet = new HashSet<CompositeLocation>();
501       glbInputSet.add(condLoc);
502       // glbInputSet.add(updateLoc);
503
504       CompositeLocation glbLocOfForLoopCond = CompositeLattice.calculateGLB(glbInputSet);
505
506       // check location of 'forloop' body
507       CompositeLocation blockLoc = checkLocationFromBlockNode(md, bn.getVarTable(), ln.getBody());
508
509       // compute glb of body including loop body and update statement
510       glbInputSet.clear();
511
512       if (blockLoc == null) {
513         // when there is no statement in the loop body
514
515         if (updateLoc == null) {
516           // also there is no update statement in the loop body
517           return glbLocOfForLoopCond;
518         }
519         glbInputSet.add(updateLoc);
520
521       } else {
522         glbInputSet.add(blockLoc);
523         glbInputSet.add(updateLoc);
524       }
525
526       CompositeLocation loopBodyLoc = CompositeLattice.calculateGLB(glbInputSet);
527
528       if (!CompositeLattice.isGreaterThan(glbLocOfForLoopCond, loopBodyLoc,
529           generateErrorMessage(cd, ln))) {
530         throw new Error(
531             "The location of the for-condition statement is lower than the for-loop body at "
532                 + cd.getSourceFileName() + ":" + ln.getCondition().getNumLine());
533       }
534       return blockLoc;
535     }
536
537   }
538
539   private CompositeLocation checkLocationFromSubBlockNode(MethodDescriptor md,
540       SymbolTable nametable, SubBlockNode sbn) {
541     CompositeLocation compLoc = checkLocationFromBlockNode(md, nametable, sbn.getBlockNode());
542     return compLoc;
543   }
544
545   private CompositeLocation checkLocationFromIfStatementNode(MethodDescriptor md,
546       SymbolTable nametable, IfStatementNode isn) {
547
548     ClassDescriptor localCD = md.getClassDesc();
549     Set<CompositeLocation> glbInputSet = new HashSet<CompositeLocation>();
550
551     CompositeLocation condLoc =
552         checkLocationFromExpressionNode(md, nametable, isn.getCondition(), new CompositeLocation());
553
554     addLocationType(isn.getCondition().getType(), condLoc);
555     glbInputSet.add(condLoc);
556
557     CompositeLocation locTrueBlock = checkLocationFromBlockNode(md, nametable, isn.getTrueBlock());
558     if (locTrueBlock != null) {
559       glbInputSet.add(locTrueBlock);
560       // here, the location of conditional block should be higher than the
561       // location of true/false blocks
562       if (locTrueBlock != null
563           && !CompositeLattice.isGreaterThan(condLoc, locTrueBlock,
564               generateErrorMessage(localCD, isn.getCondition()))) {
565         // error
566         throw new Error(
567             "The location of the if-condition statement is lower than the conditional block at "
568                 + localCD.getSourceFileName() + ":" + isn.getCondition().getNumLine());
569       }
570     }
571
572     if (isn.getFalseBlock() != null) {
573       CompositeLocation locFalseBlock =
574           checkLocationFromBlockNode(md, nametable, isn.getFalseBlock());
575
576       if (locFalseBlock != null) {
577         glbInputSet.add(locFalseBlock);
578
579         if (!CompositeLattice.isGreaterThan(condLoc, locFalseBlock,
580             generateErrorMessage(localCD, isn.getCondition()))) {
581           // error
582           throw new Error(
583               "The location of the if-condition statement is lower than the conditional block at "
584                   + localCD.getSourceFileName() + ":" + isn.getCondition().getNumLine());
585         }
586       }
587
588     }
589
590     // return GLB location of condition, true, and false block
591     CompositeLocation glbLoc = CompositeLattice.calculateGLB(glbInputSet);
592
593     return glbLoc;
594   }
595
596   private CompositeLocation checkLocationFromDeclarationNode(MethodDescriptor md,
597       SymbolTable nametable, DeclarationNode dn) {
598
599     System.out.println("##DeclarationNode=" + dn.printNode(0) + " "
600         + generateErrorMessage(md.getClassDesc(), dn));
601
602     VarDescriptor vd = dn.getVarDescriptor();
603
604     CompositeLocation destLoc = d2loc.get(vd);
605
606     System.out.println("##DeclarationNode destLoc=" + destLoc + " of vd=" + vd + " of md=" + md);
607
608     if (dn.getExpression() != null) {
609       CompositeLocation expressionLoc =
610           checkLocationFromExpressionNode(md, nametable, dn.getExpression(),
611               new CompositeLocation());
612       // addTypeLocation(dn.getExpression().getType(), expressionLoc);
613
614       if (expressionLoc != null) {
615         // checking location order
616         if (!CompositeLattice.isGreaterThan(expressionLoc, destLoc,
617             generateErrorMessage(md.getClassDesc(), dn))) {
618           throw new Error("The value flow from " + expressionLoc + " to " + destLoc
619               + " does not respect location hierarchy on the assignment " + dn.printNode(0)
620               + " at " + md.getClassDesc().getSourceFileName() + "::" + dn.getNumLine());
621         }
622       }
623       return expressionLoc;
624
625     } else {
626
627       return new CompositeLocation();
628
629     }
630
631   }
632
633   private void checkDeclarationInSubBlockNode(MethodDescriptor md, SymbolTable nametable,
634       SubBlockNode sbn) {
635     checkDeclarationInBlockNode(md, nametable.getParent(), sbn.getBlockNode());
636   }
637
638   private CompositeLocation checkLocationFromBlockExpressionNode(MethodDescriptor md,
639       SymbolTable nametable, BlockExpressionNode ben) {
640     CompositeLocation compLoc =
641         checkLocationFromExpressionNode(md, nametable, ben.getExpression(), null);
642     // addTypeLocation(ben.getExpression().getType(), compLoc);
643     return compLoc;
644   }
645
646   private CompositeLocation checkLocationFromExpressionNode(MethodDescriptor md,
647       SymbolTable nametable, ExpressionNode en, CompositeLocation loc) {
648
649     CompositeLocation compLoc = null;
650     switch (en.kind()) {
651
652     case Kind.AssignmentNode:
653       compLoc = checkLocationFromAssignmentNode(md, nametable, (AssignmentNode) en, loc);
654       break;
655
656     case Kind.FieldAccessNode:
657       compLoc = checkLocationFromFieldAccessNode(md, nametable, (FieldAccessNode) en, loc);
658       break;
659
660     case Kind.NameNode:
661       compLoc = checkLocationFromNameNode(md, nametable, (NameNode) en, loc);
662       break;
663
664     case Kind.OpNode:
665       compLoc = checkLocationFromOpNode(md, nametable, (OpNode) en);
666       break;
667
668     case Kind.CreateObjectNode:
669       compLoc = checkLocationFromCreateObjectNode(md, nametable, (CreateObjectNode) en);
670       break;
671
672     case Kind.ArrayAccessNode:
673       compLoc = checkLocationFromArrayAccessNode(md, nametable, (ArrayAccessNode) en);
674       break;
675
676     case Kind.LiteralNode:
677       compLoc = checkLocationFromLiteralNode(md, nametable, (LiteralNode) en, loc);
678       break;
679
680     case Kind.MethodInvokeNode:
681       compLoc = checkLocationFromMethodInvokeNode(md, nametable, (MethodInvokeNode) en, loc);
682       break;
683
684     case Kind.TertiaryNode:
685       compLoc = checkLocationFromTertiaryNode(md, nametable, (TertiaryNode) en);
686       break;
687
688     case Kind.CastNode:
689       compLoc = checkLocationFromCastNode(md, nametable, (CastNode) en);
690       break;
691
692     // case Kind.InstanceOfNode:
693     // checkInstanceOfNode(md, nametable, (InstanceOfNode) en, td);
694     // return null;
695
696     // case Kind.ArrayInitializerNode:
697     // checkArrayInitializerNode(md, nametable, (ArrayInitializerNode) en,
698     // td);
699     // return null;
700
701     // case Kind.ClassTypeNode:
702     // checkClassTypeNode(md, nametable, (ClassTypeNode) en, td);
703     // return null;
704
705     // case Kind.OffsetNode:
706     // checkOffsetNode(md, nametable, (OffsetNode)en, td);
707     // return null;
708
709     default:
710       return null;
711
712     }
713     // addTypeLocation(en.getType(), compLoc);
714     return compLoc;
715
716   }
717
718   private CompositeLocation checkLocationFromCastNode(MethodDescriptor md, SymbolTable nametable,
719       CastNode cn) {
720
721     ExpressionNode en = cn.getExpression();
722     return checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation());
723
724   }
725
726   private CompositeLocation checkLocationFromTertiaryNode(MethodDescriptor md,
727       SymbolTable nametable, TertiaryNode tn) {
728     ClassDescriptor cd = md.getClassDesc();
729
730     CompositeLocation condLoc =
731         checkLocationFromExpressionNode(md, nametable, tn.getCond(), new CompositeLocation());
732     addLocationType(tn.getCond().getType(), condLoc);
733     CompositeLocation trueLoc =
734         checkLocationFromExpressionNode(md, nametable, tn.getTrueExpr(), new CompositeLocation());
735     addLocationType(tn.getTrueExpr().getType(), trueLoc);
736     CompositeLocation falseLoc =
737         checkLocationFromExpressionNode(md, nametable, tn.getFalseExpr(), new CompositeLocation());
738     addLocationType(tn.getFalseExpr().getType(), falseLoc);
739
740     // locations from true/false branches can be TOP when there are only literal
741     // values
742     // in this case, we don't need to check flow down rule!
743
744     // check if condLoc is higher than trueLoc & falseLoc
745     if (!trueLoc.get(0).isTop()
746         && !CompositeLattice.isGreaterThan(condLoc, trueLoc, generateErrorMessage(cd, tn))) {
747       throw new Error(
748           "The location of the condition expression is lower than the true expression at "
749               + cd.getSourceFileName() + ":" + tn.getCond().getNumLine());
750     }
751
752     if (!falseLoc.get(0).isTop()
753         && !CompositeLattice.isGreaterThan(condLoc, falseLoc,
754             generateErrorMessage(cd, tn.getCond()))) {
755       throw new Error(
756           "The location of the condition expression is lower than the true expression at "
757               + cd.getSourceFileName() + ":" + tn.getCond().getNumLine());
758     }
759
760     // then, return glb of trueLoc & falseLoc
761     Set<CompositeLocation> glbInputSet = new HashSet<CompositeLocation>();
762     glbInputSet.add(trueLoc);
763     glbInputSet.add(falseLoc);
764
765     return CompositeLattice.calculateGLB(glbInputSet);
766   }
767
768   private CompositeLocation checkLocationFromMethodInvokeNode(MethodDescriptor md,
769       SymbolTable nametable, MethodInvokeNode min, CompositeLocation loc) {
770
771     checkCalleeConstraints(md, nametable, min);
772
773     CompositeLocation baseLocation = null;
774     if (min.getExpression() != null) {
775       baseLocation =
776           checkLocationFromExpressionNode(md, nametable, min.getExpression(),
777               new CompositeLocation());
778     } else {
779       String thisLocId = ssjava.getMethodLattice(md).getThisLoc();
780       baseLocation = new CompositeLocation(new Location(md, thisLocId));
781     }
782
783     if (!min.getMethod().getReturnType().isVoid()) {
784       // If method has a return value, compute the highest possible return
785       // location in the caller's perspective
786       CompositeLocation ceilingLoc =
787           computeCeilingLocationForCaller(md, nametable, min, baseLocation);
788       return ceilingLoc;
789     }
790
791     return new CompositeLocation();
792
793   }
794
795   private CompositeLocation computeCeilingLocationForCaller(MethodDescriptor md,
796       SymbolTable nametable, MethodInvokeNode min, CompositeLocation baseLocation) {
797     List<CompositeLocation> argList = new ArrayList<CompositeLocation>();
798
799     // by default, method has a THIS parameter
800     argList.add(baseLocation);
801
802     for (int i = 0; i < min.numArgs(); i++) {
803       ExpressionNode en = min.getArg(i);
804       CompositeLocation callerArg =
805           checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation());
806       argList.add(callerArg);
807     }
808
809     System.out.println("##");
810     System.out.println("min.getMethod()=" + min.getMethod() + " argList=" + argList);
811     System.out.println("computeReturnLocation="
812         + md2ReturnLocGen.get(min.getMethod()).computeReturnLocation(argList));
813
814     return md2ReturnLocGen.get(min.getMethod()).computeReturnLocation(argList);
815
816   }
817
818   private void checkCalleeConstraints(MethodDescriptor md, SymbolTable nametable,
819       MethodInvokeNode min) {
820
821     System.out.println("checkCalleeConstraints " + generateErrorMessage(md.getClassDesc(), min));
822
823     if (min.numArgs() > 1) {
824       // caller needs to guarantee that it passes arguments in regarding to
825       // callee's hierarchy
826       for (int i = 0; i < min.numArgs(); i++) {
827         ExpressionNode en = min.getArg(i);
828         CompositeLocation callerArg1 =
829             checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation());
830
831         ClassDescriptor calleecd = min.getMethod().getClassDesc();
832         VarDescriptor calleevd = (VarDescriptor) min.getMethod().getParameter(i);
833         CompositeLocation calleeLoc1 = d2loc.get(calleevd);
834
835         if (!callerArg1.get(0).isTop()) {
836           // here, check if ordering relations among caller's args respect
837           // ordering relations in-between callee's args
838           for (int currentIdx = 0; currentIdx < min.numArgs(); currentIdx++) {
839             if (currentIdx != i) { // skip itself
840               ExpressionNode argExp = min.getArg(currentIdx);
841
842               CompositeLocation callerArg2 =
843                   checkLocationFromExpressionNode(md, nametable, argExp, new CompositeLocation());
844
845               VarDescriptor calleevd2 = (VarDescriptor) min.getMethod().getParameter(currentIdx);
846               CompositeLocation calleeLoc2 = d2loc.get(calleevd2);
847
848               System.out.println("#callerResult=" + callerArg1 + " " + callerArg2);
849               System.out.println("#calleeResult=" + calleeLoc1 + " " + calleeLoc2);
850
851               int callerResult =
852                   CompositeLattice.compare(callerArg1, callerArg2,
853                       generateErrorMessage(md.getClassDesc(), min));
854               int calleeResult =
855                   CompositeLattice.compare(calleeLoc1, calleeLoc2,
856                       generateErrorMessage(md.getClassDesc(), min));
857
858               if (calleeResult == ComparisonResult.GREATER
859                   && callerResult != ComparisonResult.GREATER) {
860                 // If calleeLoc1 is higher than calleeLoc2
861                 // then, caller should have same ordering relation in-bet
862                 // callerLoc1 & callerLoc2
863
864                 throw new Error("Caller doesn't respect ordering relations among method arguments:"
865                     + md.getClassDesc().getSourceFileName() + ":" + min.getNumLine());
866               }
867
868             }
869           }
870         }
871
872       }
873
874     }
875
876   }
877
878   private CompositeLocation checkLocationFromArrayAccessNode(MethodDescriptor md,
879       SymbolTable nametable, ArrayAccessNode aan) {
880
881     // return glb location of array itself and index
882
883     ClassDescriptor cd = md.getClassDesc();
884
885     Set<CompositeLocation> glbInputSet = new HashSet<CompositeLocation>();
886
887     CompositeLocation arrayLoc =
888         checkLocationFromExpressionNode(md, nametable, aan.getExpression(), new CompositeLocation());
889     // addTypeLocation(aan.getExpression().getType(), arrayLoc);
890     glbInputSet.add(arrayLoc);
891     CompositeLocation indexLoc =
892         checkLocationFromExpressionNode(md, nametable, aan.getIndex(), new CompositeLocation());
893     glbInputSet.add(indexLoc);
894     // addTypeLocation(aan.getIndex().getType(), indexLoc);
895
896     CompositeLocation glbLoc = CompositeLattice.calculateGLB(glbInputSet);
897     return glbLoc;
898   }
899
900   private CompositeLocation checkLocationFromCreateObjectNode(MethodDescriptor md,
901       SymbolTable nametable, CreateObjectNode con) {
902
903     ClassDescriptor cd = md.getClassDesc();
904
905     // check arguments
906     Set<CompositeLocation> glbInputSet = new HashSet<CompositeLocation>();
907     for (int i = 0; i < con.numArgs(); i++) {
908       ExpressionNode en = con.getArg(i);
909       CompositeLocation argLoc =
910           checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation());
911       glbInputSet.add(argLoc);
912       addLocationType(en.getType(), argLoc);
913     }
914
915     // check array initializers
916     // if ((con.getArrayInitializer() != null)) {
917     // checkLocationFromArrayInitializerNode(md, nametable,
918     // con.getArrayInitializer());
919     // }
920
921     if (glbInputSet.size() > 0) {
922       return CompositeLattice.calculateGLB(glbInputSet);
923     }
924
925     CompositeLocation compLoc = new CompositeLocation();
926     compLoc.addLocation(Location.createTopLocation(md));
927     return compLoc;
928
929   }
930
931   private CompositeLocation checkLocationFromOpNode(MethodDescriptor md, SymbolTable nametable,
932       OpNode on) {
933
934     ClassDescriptor cd = md.getClassDesc();
935     CompositeLocation leftLoc = new CompositeLocation();
936     leftLoc = checkLocationFromExpressionNode(md, nametable, on.getLeft(), leftLoc);
937     // addTypeLocation(on.getLeft().getType(), leftLoc);
938
939     CompositeLocation rightLoc = new CompositeLocation();
940     if (on.getRight() != null) {
941       rightLoc = checkLocationFromExpressionNode(md, nametable, on.getRight(), rightLoc);
942       // addTypeLocation(on.getRight().getType(), rightLoc);
943     }
944
945     System.out.println("checking op node=" + on.printNode(0)
946         + generateErrorMessage(md.getClassDesc(), on));
947     System.out.println("left loc=" + leftLoc + " from " + on.getLeft().getClass());
948     if (on.getRight() != null) {
949       System.out.println("right loc=" + rightLoc + " from " + on.getRight().kind());
950     }
951
952     Operation op = on.getOp();
953
954     switch (op.getOp()) {
955
956     case Operation.UNARYPLUS:
957     case Operation.UNARYMINUS:
958     case Operation.LOGIC_NOT:
959       // single operand
960       return leftLoc;
961
962     case Operation.LOGIC_OR:
963     case Operation.LOGIC_AND:
964     case Operation.COMP:
965     case Operation.BIT_OR:
966     case Operation.BIT_XOR:
967     case Operation.BIT_AND:
968     case Operation.ISAVAILABLE:
969     case Operation.EQUAL:
970     case Operation.NOTEQUAL:
971     case Operation.LT:
972     case Operation.GT:
973     case Operation.LTE:
974     case Operation.GTE:
975     case Operation.ADD:
976     case Operation.SUB:
977     case Operation.MULT:
978     case Operation.DIV:
979     case Operation.MOD:
980     case Operation.LEFTSHIFT:
981     case Operation.RIGHTSHIFT:
982     case Operation.URIGHTSHIFT:
983
984       Set<CompositeLocation> inputSet = new HashSet<CompositeLocation>();
985       inputSet.add(leftLoc);
986       inputSet.add(rightLoc);
987       CompositeLocation glbCompLoc = CompositeLattice.calculateGLB(inputSet);
988       return glbCompLoc;
989
990     default:
991       throw new Error(op.toString());
992     }
993
994   }
995
996   private CompositeLocation checkLocationFromLiteralNode(MethodDescriptor md,
997       SymbolTable nametable, LiteralNode en, CompositeLocation loc) {
998
999     // literal value has the top location so that value can be flowed into any
1000     // location
1001     Location literalLoc = Location.createTopLocation(md);
1002     loc.addLocation(literalLoc);
1003     return loc;
1004
1005   }
1006
1007   private CompositeLocation checkLocationFromNameNode(MethodDescriptor md, SymbolTable nametable,
1008       NameNode nn, CompositeLocation loc) {
1009
1010     NameDescriptor nd = nn.getName();
1011     if (nd.getBase() != null) {
1012       loc = checkLocationFromExpressionNode(md, nametable, nn.getExpression(), loc);
1013     } else {
1014       String varname = nd.toString();
1015       if (varname.equals("this")) {
1016         // 'this' itself!
1017         MethodLattice<String> methodLattice = ssjava.getMethodLattice(md);
1018         String thisLocId = methodLattice.getThisLoc();
1019         if (thisLocId == null) {
1020           throw new Error("The location for 'this' is not defined at "
1021               + md.getClassDesc().getSourceFileName() + "::" + nn.getNumLine());
1022         }
1023         Location locElement = new Location(md, thisLocId);
1024         loc.addLocation(locElement);
1025         return loc;
1026       }
1027       Descriptor d = (Descriptor) nametable.get(varname);
1028
1029       // CompositeLocation localLoc = null;
1030       if (d instanceof VarDescriptor) {
1031         VarDescriptor vd = (VarDescriptor) d;
1032         // localLoc = d2loc.get(vd);
1033         // the type of var descriptor has a composite location!
1034         loc = ((CompositeLocation) vd.getType().getExtension()).clone();
1035       } else if (d instanceof FieldDescriptor) {
1036         // the type of field descriptor has a location!
1037         FieldDescriptor fd = (FieldDescriptor) d;
1038         if (fd.isStatic()) {
1039           if (fd.isFinal()) {
1040             // if it is 'static final', the location has TOP since no one can
1041             // change its value
1042             loc.addLocation(Location.createTopLocation(md));
1043           } else {
1044             // if 'static', the location has pre-assigned global loc
1045             MethodLattice<String> localLattice = ssjava.getMethodLattice(md);
1046             String globalLocId = localLattice.getGlobalLoc();
1047             if (globalLocId == null) {
1048               throw new Error("Global location element is not defined in the method " + md);
1049             }
1050             Location globalLoc = new Location(md, globalLocId);
1051
1052             loc.addLocation(globalLoc);
1053           }
1054         } else {
1055           // the location of field access starts from this, followed by field
1056           // location
1057           MethodLattice<String> localLattice = ssjava.getMethodLattice(md);
1058           Location thisLoc = new Location(md, localLattice.getThisLoc());
1059           loc.addLocation(thisLoc);
1060         }
1061
1062         Location fieldLoc = (Location) fd.getType().getExtension();
1063         loc.addLocation(fieldLoc);
1064       }
1065     }
1066     return loc;
1067   }
1068
1069   private CompositeLocation checkLocationFromFieldAccessNode(MethodDescriptor md,
1070       SymbolTable nametable, FieldAccessNode fan, CompositeLocation loc) {
1071
1072     ExpressionNode left = fan.getExpression();
1073     TypeDescriptor ltd = left.getType();
1074
1075     FieldDescriptor fd = fan.getField();
1076
1077     if (ltd.isClassNameRef()) {
1078       // using a class name directly
1079       if (fd.isStatic() && fd.isFinal()) {
1080         loc.addLocation(Location.createTopLocation(md));
1081         return loc;
1082       }
1083     }
1084
1085     loc = checkLocationFromExpressionNode(md, nametable, left, loc);
1086     if (!left.getType().isPrimitive()) {
1087       Location fieldLoc = getFieldLocation(fd);
1088       loc.addLocation(fieldLoc);
1089     }
1090
1091     return loc;
1092   }
1093
1094   private Location getFieldLocation(FieldDescriptor fd) {
1095
1096     Location fieldLoc = (Location) fd.getType().getExtension();
1097
1098     // handle the case that method annotation checking skips checking field
1099     // declaration
1100     if (fieldLoc == null) {
1101       fieldLoc = checkFieldDeclaration(fd.getClassDescriptor(), fd);
1102     }
1103
1104     return fieldLoc;
1105
1106   }
1107
1108   private CompositeLocation checkLocationFromAssignmentNode(MethodDescriptor md,
1109       SymbolTable nametable, AssignmentNode an, CompositeLocation loc) {
1110
1111     ClassDescriptor cd = md.getClassDesc();
1112
1113     boolean postinc = true;
1114     if (an.getOperation().getBaseOp() == null
1115         || (an.getOperation().getBaseOp().getOp() != Operation.POSTINC && an.getOperation()
1116             .getBaseOp().getOp() != Operation.POSTDEC))
1117       postinc = false;
1118
1119     CompositeLocation destLocation =
1120         checkLocationFromExpressionNode(md, nametable, an.getDest(), new CompositeLocation());
1121
1122     CompositeLocation srcLocation = new CompositeLocation();
1123
1124     if (!postinc) {
1125       if (hasOnlyLiteralValue(an.getSrc())) {
1126         // if source is literal value, src location is TOP. so do not need to
1127         // compare!
1128         return destLocation;
1129       }
1130       srcLocation = new CompositeLocation();
1131       srcLocation = checkLocationFromExpressionNode(md, nametable, an.getSrc(), srcLocation);
1132
1133       // System.out.println(" an= " + an.printNode(0) + " an.getSrc()=" +
1134       // an.getSrc().getClass()
1135       // + " at " + cd.getSourceFileName() + "::" + an.getNumLine());
1136       // System.out.println("srcLocation=" + srcLocation);
1137       // System.out.println("dstLocation=" + destLocation);
1138
1139       if (!CompositeLattice.isGreaterThan(srcLocation, destLocation, generateErrorMessage(cd, an))) {
1140         throw new Error("The value flow from " + srcLocation + " to " + destLocation
1141             + " does not respect location hierarchy on the assignment " + an.printNode(0) + " at "
1142             + cd.getSourceFileName() + "::" + an.getNumLine());
1143       }
1144     } else {
1145       destLocation =
1146           srcLocation = checkLocationFromExpressionNode(md, nametable, an.getDest(), srcLocation);
1147
1148       if (!CompositeLattice.isGreaterThan(srcLocation, destLocation, generateErrorMessage(cd, an))) {
1149         throw new Error("Location " + destLocation
1150             + " is not allowed to have the value flow that moves within the same location at "
1151             + cd.getSourceFileName() + "::" + an.getNumLine());
1152       }
1153
1154     }
1155
1156     return destLocation;
1157   }
1158
1159   private void assignLocationOfVarDescriptor(VarDescriptor vd, MethodDescriptor md,
1160       SymbolTable nametable, TreeNode n) {
1161
1162     ClassDescriptor cd = md.getClassDesc();
1163     Vector<AnnotationDescriptor> annotationVec = vd.getType().getAnnotationMarkers();
1164
1165     // currently enforce every variable to have corresponding location
1166     if (annotationVec.size() == 0) {
1167       throw new Error("Location is not assigned to variable " + vd.getSymbol() + " in the method "
1168           + md.getSymbol() + " of the class " + cd.getSymbol());
1169     }
1170
1171     if (annotationVec.size() > 1) { // variable can have at most one location
1172       throw new Error(vd.getSymbol() + " has more than one location.");
1173     }
1174
1175     AnnotationDescriptor ad = annotationVec.elementAt(0);
1176
1177     if (ad.getType() == AnnotationDescriptor.SINGLE_ANNOTATION) {
1178
1179       if (ad.getMarker().equals(SSJavaAnalysis.LOC)) {
1180         String locDec = ad.getValue(); // check if location is defined
1181
1182         if (locDec.startsWith(SSJavaAnalysis.DELTA)) {
1183           DeltaLocation deltaLoc = parseDeltaDeclaration(md, n, locDec);
1184           d2loc.put(vd, deltaLoc);
1185           addLocationType(vd.getType(), deltaLoc);
1186         } else {
1187           CompositeLocation compLoc = parseLocationDeclaration(md, n, locDec);
1188
1189           Location lastElement = compLoc.get(compLoc.getSize() - 1);
1190           if (ssjava.isSharedLocation(lastElement)) {
1191             ssjava.mapSharedLocation2Descriptor(lastElement, vd);
1192           }
1193
1194           d2loc.put(vd, compLoc);
1195           addLocationType(vd.getType(), compLoc);
1196         }
1197
1198       }
1199     }
1200
1201   }
1202
1203   private DeltaLocation parseDeltaDeclaration(MethodDescriptor md, TreeNode n, String locDec) {
1204
1205     int deltaCount = 0;
1206     int dIdx = locDec.indexOf(SSJavaAnalysis.DELTA);
1207     while (dIdx >= 0) {
1208       deltaCount++;
1209       int beginIdx = dIdx + 6;
1210       locDec = locDec.substring(beginIdx, locDec.length() - 1);
1211       dIdx = locDec.indexOf(SSJavaAnalysis.DELTA);
1212     }
1213
1214     CompositeLocation compLoc = parseLocationDeclaration(md, n, locDec);
1215     DeltaLocation deltaLoc = new DeltaLocation(compLoc, deltaCount);
1216
1217     return deltaLoc;
1218   }
1219
1220   private Location parseFieldLocDeclaraton(String decl, String msg) {
1221
1222     int idx = decl.indexOf(".");
1223     String className = decl.substring(0, idx);
1224     String fieldName = decl.substring(idx + 1);
1225
1226     className.replaceAll(" ", "");
1227     fieldName.replaceAll(" ", "");
1228
1229     Descriptor d = state.getClassSymbolTable().get(className);
1230
1231     if (d == null) {
1232       throw new Error("The class in the location declaration '" + decl + "' does not exist at "
1233           + msg);
1234     }
1235
1236     assert (d instanceof ClassDescriptor);
1237     SSJavaLattice<String> lattice = ssjava.getClassLattice((ClassDescriptor) d);
1238     if (!lattice.containsKey(fieldName)) {
1239       throw new Error("The location " + fieldName + " is not defined in the field lattice of '"
1240           + className + "' at " + msg);
1241     }
1242
1243     return new Location(d, fieldName);
1244   }
1245
1246   private CompositeLocation parseLocationDeclaration(MethodDescriptor md, TreeNode n, String locDec) {
1247
1248     CompositeLocation compLoc = new CompositeLocation();
1249
1250     StringTokenizer tokenizer = new StringTokenizer(locDec, ",");
1251     List<String> locIdList = new ArrayList<String>();
1252     while (tokenizer.hasMoreTokens()) {
1253       String locId = tokenizer.nextToken();
1254       locIdList.add(locId);
1255     }
1256
1257     // at least,one location element needs to be here!
1258     assert (locIdList.size() > 0);
1259
1260     // assume that loc with idx 0 comes from the local lattice
1261     // loc with idx 1 comes from the field lattice
1262
1263     String localLocId = locIdList.get(0);
1264     SSJavaLattice<String> localLattice = CompositeLattice.getLatticeByDescriptor(md);
1265     Location localLoc = new Location(md, localLocId);
1266     if (localLattice == null || (!localLattice.containsKey(localLocId))) {
1267       throw new Error("Location " + localLocId
1268           + " is not defined in the local variable lattice at "
1269           + md.getClassDesc().getSourceFileName() + "::" + (n != null ? n.getNumLine() : "") + ".");
1270     }
1271     compLoc.addLocation(localLoc);
1272
1273     for (int i = 1; i < locIdList.size(); i++) {
1274       String locName = locIdList.get(i);
1275
1276       Location fieldLoc =
1277           parseFieldLocDeclaraton(locName, generateErrorMessage(md.getClassDesc(), n));
1278       // ClassDescriptor cd = fieldLocName2cd.get(locName);
1279       // SSJavaLattice<String> fieldLattice =
1280       // CompositeLattice.getLatticeByDescriptor(cd);
1281       //
1282       // if (fieldLattice == null || (!fieldLattice.containsKey(locName))) {
1283       // throw new Error("Location " + locName +
1284       // " is not defined in the field lattice at "
1285       // + cd.getSourceFileName() + ".");
1286       // }
1287       // Location fieldLoc = new Location(cd, locName);
1288       compLoc.addLocation(fieldLoc);
1289     }
1290
1291     return compLoc;
1292
1293   }
1294
1295   private void checkDeclarationNode(MethodDescriptor md, SymbolTable nametable, DeclarationNode dn) {
1296     VarDescriptor vd = dn.getVarDescriptor();
1297     assignLocationOfVarDescriptor(vd, md, nametable, dn);
1298   }
1299
1300   private void checkClass(ClassDescriptor cd) {
1301     // Check to see that methods respects ss property
1302     for (Iterator method_it = cd.getMethods(); method_it.hasNext();) {
1303       MethodDescriptor md = (MethodDescriptor) method_it.next();
1304       checkMethodDeclaration(cd, md);
1305     }
1306   }
1307
1308   private void checkDeclarationInClass(ClassDescriptor cd) {
1309     // Check to see that fields are okay
1310     for (Iterator field_it = cd.getFields(); field_it.hasNext();) {
1311       FieldDescriptor fd = (FieldDescriptor) field_it.next();
1312
1313       if (!(fd.isFinal() && fd.isStatic())) {
1314         checkFieldDeclaration(cd, fd);
1315       } else {
1316         // for static final, assign top location by default
1317         Location loc = Location.createTopLocation(cd);
1318         addLocationType(fd.getType(), loc);
1319       }
1320     }
1321   }
1322
1323   private void checkMethodDeclaration(ClassDescriptor cd, MethodDescriptor md) {
1324     // TODO
1325   }
1326
1327   private Location checkFieldDeclaration(ClassDescriptor cd, FieldDescriptor fd) {
1328
1329     Vector<AnnotationDescriptor> annotationVec = fd.getType().getAnnotationMarkers();
1330
1331     // currently enforce every field to have corresponding location
1332     if (annotationVec.size() == 0) {
1333       throw new Error("Location is not assigned to the field '" + fd.getSymbol()
1334           + "' of the class " + cd.getSymbol() + " at " + cd.getSourceFileName());
1335     }
1336
1337     if (annotationVec.size() > 1) {
1338       // variable can have at most one location
1339       throw new Error("Field " + fd.getSymbol() + " of class " + cd
1340           + " has more than one location.");
1341     }
1342
1343     AnnotationDescriptor ad = annotationVec.elementAt(0);
1344     Location loc = null;
1345
1346     if (ad.getType() == AnnotationDescriptor.SINGLE_ANNOTATION) {
1347       if (ad.getMarker().equals(SSJavaAnalysis.LOC)) {
1348         String locationID = ad.getValue();
1349         // check if location is defined
1350         SSJavaLattice<String> lattice = ssjava.getClassLattice(cd);
1351         if (lattice == null || (!lattice.containsKey(locationID))) {
1352           throw new Error("Location " + locationID
1353               + " is not defined in the field lattice of class " + cd.getSymbol() + " at"
1354               + cd.getSourceFileName() + ".");
1355         }
1356         loc = new Location(cd, locationID);
1357
1358         if (ssjava.isSharedLocation(loc)) {
1359           ssjava.mapSharedLocation2Descriptor(loc, fd);
1360         }
1361
1362         addLocationType(fd.getType(), loc);
1363
1364       }
1365     }
1366
1367     return loc;
1368   }
1369
1370   private void addLocationType(TypeDescriptor type, CompositeLocation loc) {
1371     if (type != null) {
1372       type.setExtension(loc);
1373     }
1374   }
1375
1376   private void addLocationType(TypeDescriptor type, Location loc) {
1377     if (type != null) {
1378       type.setExtension(loc);
1379     }
1380   }
1381
1382   static class CompositeLattice {
1383
1384     public static boolean isGreaterThan(CompositeLocation loc1, CompositeLocation loc2, String msg) {
1385
1386       System.out.println("isGreaterThan=" + loc1 + " " + loc2 + " msg=" + msg);
1387       int baseCompareResult = compareBaseLocationSet(loc1, loc2, true, msg);
1388       if (baseCompareResult == ComparisonResult.EQUAL) {
1389         if (compareDelta(loc1, loc2) == ComparisonResult.GREATER) {
1390           return true;
1391         } else {
1392           return false;
1393         }
1394       } else if (baseCompareResult == ComparisonResult.GREATER) {
1395         return true;
1396       } else {
1397         return false;
1398       }
1399
1400     }
1401
1402     public static int compare(CompositeLocation loc1, CompositeLocation loc2, String msg) {
1403
1404       System.out.println("compare=" + loc1 + " " + loc2);
1405       int baseCompareResult = compareBaseLocationSet(loc1, loc2, false, msg);
1406
1407       if (baseCompareResult == ComparisonResult.EQUAL) {
1408         return compareDelta(loc1, loc2);
1409       } else {
1410         return baseCompareResult;
1411       }
1412
1413     }
1414
1415     private static int compareDelta(CompositeLocation dLoc1, CompositeLocation dLoc2) {
1416
1417       int deltaCount1 = 0;
1418       int deltaCount2 = 0;
1419       if (dLoc1 instanceof DeltaLocation) {
1420         deltaCount1 = ((DeltaLocation) dLoc1).getNumDelta();
1421       }
1422
1423       if (dLoc2 instanceof DeltaLocation) {
1424         deltaCount2 = ((DeltaLocation) dLoc2).getNumDelta();
1425       }
1426       if (deltaCount1 < deltaCount2) {
1427         return ComparisonResult.GREATER;
1428       } else if (deltaCount1 == deltaCount2) {
1429         return ComparisonResult.EQUAL;
1430       } else {
1431         return ComparisonResult.LESS;
1432       }
1433
1434     }
1435
1436     private static int compareBaseLocationSet(CompositeLocation compLoc1,
1437         CompositeLocation compLoc2, boolean awareSharedLoc, String msg) {
1438
1439       // if compLoc1 is greater than compLoc2, return true
1440       // else return false;
1441
1442       // compare one by one in according to the order of the tuple
1443       int numOfTie = 0;
1444       for (int i = 0; i < compLoc1.getSize(); i++) {
1445         Location loc1 = compLoc1.get(i);
1446         if (i >= compLoc2.getSize()) {
1447           throw new Error("Failed to compare two locations of " + compLoc1 + " and " + compLoc2
1448               + " because they are not comparable.");
1449         }
1450         Location loc2 = compLoc2.get(i);
1451
1452         if (!loc1.getDescriptor().equals(loc2.getDescriptor())) {
1453           throw new Error("Failed to compare two locations of " + compLoc1 + " and " + compLoc2
1454               + " because they are not comparable at " + msg);
1455         }
1456
1457         Descriptor d1 = loc1.getDescriptor();
1458         Descriptor d2 = loc2.getDescriptor();
1459
1460         SSJavaLattice<String> lattice1 = getLatticeByDescriptor(d1);
1461         SSJavaLattice<String> lattice2 = getLatticeByDescriptor(d2);
1462
1463         // check if the spin location is appeared only at the end of the
1464         // composite location
1465         if (lattice1.getSpinLocSet().contains(loc1.getLocIdentifier())) {
1466           if (i != (compLoc1.getSize() - 1)) {
1467             throw new Error("The spin location " + loc1.getLocIdentifier()
1468                 + " cannot be appeared in the middle of composite location at" + msg);
1469           }
1470         }
1471
1472         if (lattice2.getSpinLocSet().contains(loc2.getLocIdentifier())) {
1473           if (i != (compLoc2.getSize() - 1)) {
1474             throw new Error("The spin location " + loc2.getLocIdentifier()
1475                 + " cannot be appeared in the middle of composite location at " + msg);
1476           }
1477         }
1478
1479         if (!lattice1.equals(lattice2)) {
1480           throw new Error("Failed to compare two locations of " + compLoc1 + " and " + compLoc2
1481               + " because they are not comparable at " + msg);
1482         }
1483
1484         if (loc1.getLocIdentifier().equals(loc2.getLocIdentifier())) {
1485           numOfTie++;
1486           // check if the current location is the spinning location
1487           // note that the spinning location only can be appeared in the last
1488           // part of the composite location
1489           if (awareSharedLoc && numOfTie == compLoc1.getSize()
1490               && lattice1.getSpinLocSet().contains(loc1.getLocIdentifier())) {
1491             return ComparisonResult.GREATER;
1492           }
1493           continue;
1494         } else if (lattice1.isGreaterThan(loc1.getLocIdentifier(), loc2.getLocIdentifier())) {
1495           return ComparisonResult.GREATER;
1496         } else {
1497           return ComparisonResult.LESS;
1498         }
1499
1500       }
1501
1502       if (numOfTie == compLoc1.getSize()) {
1503
1504         if (numOfTie != compLoc2.getSize()) {
1505           throw new Error("Failed to compare two locations of " + compLoc1 + " and " + compLoc2
1506               + " because they are not comparable at " + msg);
1507         }
1508
1509         return ComparisonResult.EQUAL;
1510       }
1511
1512       return ComparisonResult.LESS;
1513
1514     }
1515
1516     public static CompositeLocation calculateGLB(Set<CompositeLocation> inputSet) {
1517
1518       // System.out.println("Calculating GLB=" + inputSet);
1519       CompositeLocation glbCompLoc = new CompositeLocation();
1520
1521       // calculate GLB of the first(priority) element
1522       Set<String> priorityLocIdentifierSet = new HashSet<String>();
1523       Descriptor priorityDescriptor = null;
1524
1525       Hashtable<String, Set<CompositeLocation>> locId2CompLocSet =
1526           new Hashtable<String, Set<CompositeLocation>>();
1527       // mapping from the priority loc ID to its full representation by the
1528       // composite location
1529
1530       int maxTupleSize = 0;
1531       CompositeLocation maxCompLoc = null;
1532
1533       for (Iterator iterator = inputSet.iterator(); iterator.hasNext();) {
1534         CompositeLocation compLoc = (CompositeLocation) iterator.next();
1535         if (compLoc.getSize() > maxTupleSize) {
1536           maxTupleSize = compLoc.getSize();
1537           maxCompLoc = compLoc;
1538         }
1539         Location priorityLoc = compLoc.get(0);
1540         String priorityLocId = priorityLoc.getLocIdentifier();
1541         priorityLocIdentifierSet.add(priorityLocId);
1542
1543         if (locId2CompLocSet.containsKey(priorityLocId)) {
1544           locId2CompLocSet.get(priorityLocId).add(compLoc);
1545         } else {
1546           Set<CompositeLocation> newSet = new HashSet<CompositeLocation>();
1547           newSet.add(compLoc);
1548           locId2CompLocSet.put(priorityLocId, newSet);
1549         }
1550
1551         // check if priority location are coming from the same lattice
1552         if (priorityDescriptor == null) {
1553           priorityDescriptor = priorityLoc.getDescriptor();
1554         } else if (!priorityDescriptor.equals(priorityLoc.getDescriptor())) {
1555           throw new Error("Failed to calculate GLB of " + inputSet
1556               + " because they are from different lattices.");
1557         }
1558       }
1559
1560       SSJavaLattice<String> locOrder = getLatticeByDescriptor(priorityDescriptor);
1561       String glbOfPriorityLoc = locOrder.getGLB(priorityLocIdentifierSet);
1562
1563       glbCompLoc.addLocation(new Location(priorityDescriptor, glbOfPriorityLoc));
1564       Set<CompositeLocation> compSet = locId2CompLocSet.get(glbOfPriorityLoc);
1565
1566       if (compSet == null) {
1567         // when GLB(x1,x2)!=x1 and !=x2 : GLB case 4
1568         // mean that the result is already lower than <x1,y1> and <x2,y2>
1569         // assign TOP to the rest of the location elements
1570
1571         // in this case, do not take care about delta
1572         // CompositeLocation inputComp = inputSet.iterator().next();
1573         for (int i = 1; i < maxTupleSize; i++) {
1574           glbCompLoc.addLocation(Location.createTopLocation(maxCompLoc.get(i).getDescriptor()));
1575         }
1576       } else {
1577
1578         // here find out composite location that has a maximum length tuple
1579         // if we have three input set: [A], [A,B], [A,B,C]
1580         // maximum length tuple will be [A,B,C]
1581         int max = 0;
1582         CompositeLocation maxFromCompSet = null;
1583         for (Iterator iterator = compSet.iterator(); iterator.hasNext();) {
1584           CompositeLocation c = (CompositeLocation) iterator.next();
1585           if (c.getSize() > max) {
1586             max = c.getSize();
1587             maxFromCompSet = c;
1588           }
1589         }
1590
1591         if (compSet.size() == 1) {
1592
1593           // if GLB(x1,x2)==x1 or x2 : GLB case 2,3
1594           CompositeLocation comp = compSet.iterator().next();
1595           for (int i = 1; i < comp.getSize(); i++) {
1596             glbCompLoc.addLocation(comp.get(i));
1597           }
1598
1599           // if input location corresponding to glb is a delta, need to apply
1600           // delta to glb result
1601           if (comp instanceof DeltaLocation) {
1602             glbCompLoc = new DeltaLocation(glbCompLoc, 1);
1603           }
1604
1605         } else {
1606           // when GLB(x1,x2)==x1 and x2 : GLB case 1
1607           // if more than one location shares the same priority GLB
1608           // need to calculate the rest of GLB loc
1609
1610           // int compositeLocSize = compSet.iterator().next().getSize();
1611           int compositeLocSize = maxFromCompSet.getSize();
1612
1613           Set<String> glbInputSet = new HashSet<String>();
1614           Descriptor currentD = null;
1615           for (int i = 1; i < compositeLocSize; i++) {
1616             for (Iterator iterator = compSet.iterator(); iterator.hasNext();) {
1617               CompositeLocation compositeLocation = (CompositeLocation) iterator.next();
1618               if (compositeLocation.getSize() > i) {
1619                 Location currentLoc = compositeLocation.get(i);
1620                 currentD = currentLoc.getDescriptor();
1621                 // making set of the current location sharing the same idx
1622                 glbInputSet.add(currentLoc.getLocIdentifier());
1623               }
1624             }
1625             // calculate glb for the current lattice
1626
1627             SSJavaLattice<String> currentLattice = getLatticeByDescriptor(currentD);
1628             String currentGLBLocId = currentLattice.getGLB(glbInputSet);
1629             glbCompLoc.addLocation(new Location(currentD, currentGLBLocId));
1630           }
1631
1632           // if input location corresponding to glb is a delta, need to apply
1633           // delta to glb result
1634
1635           for (Iterator iterator = compSet.iterator(); iterator.hasNext();) {
1636             CompositeLocation compLoc = (CompositeLocation) iterator.next();
1637             if (compLoc instanceof DeltaLocation) {
1638               if (glbCompLoc.equals(compLoc)) {
1639                 glbCompLoc = new DeltaLocation(glbCompLoc, 1);
1640                 break;
1641               }
1642             }
1643           }
1644
1645         }
1646       }
1647
1648       return glbCompLoc;
1649
1650     }
1651
1652     static SSJavaLattice<String> getLatticeByDescriptor(Descriptor d) {
1653
1654       SSJavaLattice<String> lattice = null;
1655
1656       if (d instanceof ClassDescriptor) {
1657         lattice = ssjava.getCd2lattice().get(d);
1658       } else if (d instanceof MethodDescriptor) {
1659         if (ssjava.getMd2lattice().containsKey(d)) {
1660           lattice = ssjava.getMd2lattice().get(d);
1661         } else {
1662           // use default lattice for the method
1663           lattice = ssjava.getCd2methodDefault().get(((MethodDescriptor) d).getClassDesc());
1664         }
1665       }
1666
1667       return lattice;
1668     }
1669
1670   }
1671
1672   class ComparisonResult {
1673
1674     public static final int GREATER = 0;
1675     public static final int EQUAL = 1;
1676     public static final int LESS = 2;
1677     public static final int INCOMPARABLE = 3;
1678     int result;
1679
1680   }
1681
1682 }
1683
1684 class ReturnLocGenerator {
1685
1686   public static final int PARAMISHIGHER = 0;
1687   public static final int PARAMISSAME = 1;
1688   public static final int IGNORE = 2;
1689
1690   Hashtable<Integer, Integer> paramIdx2paramType;
1691
1692   public ReturnLocGenerator(CompositeLocation returnLoc, List<CompositeLocation> params, String msg) {
1693     // creating mappings
1694     paramIdx2paramType = new Hashtable<Integer, Integer>();
1695     for (int i = 0; i < params.size(); i++) {
1696       CompositeLocation param = params.get(i);
1697       int compareResult = CompositeLattice.compare(param, returnLoc, msg);
1698
1699       int type;
1700       if (compareResult == ComparisonResult.GREATER) {
1701         type = 0;
1702       } else if (compareResult == ComparisonResult.EQUAL) {
1703         type = 1;
1704       } else {
1705         type = 2;
1706       }
1707       paramIdx2paramType.put(new Integer(i), new Integer(type));
1708     }
1709
1710   }
1711
1712   public CompositeLocation computeReturnLocation(List<CompositeLocation> args) {
1713
1714     // compute the highest possible location in caller's side
1715     assert paramIdx2paramType.keySet().size() == args.size();
1716
1717     Set<CompositeLocation> inputGLB = new HashSet<CompositeLocation>();
1718     for (int i = 0; i < args.size(); i++) {
1719       int type = (paramIdx2paramType.get(new Integer(i))).intValue();
1720       CompositeLocation argLoc = args.get(i);
1721       if (type == PARAMISHIGHER) {
1722         // return loc is lower than param
1723         DeltaLocation delta = new DeltaLocation(argLoc, 1);
1724         inputGLB.add(delta);
1725       } else if (type == PARAMISSAME) {
1726         // return loc is equal or lower than param
1727         inputGLB.add(argLoc);
1728       }
1729     }
1730
1731     // compute GLB of arguments subset that are same or higher than return
1732     // location
1733     CompositeLocation glb = CompositeLattice.calculateGLB(inputGLB);
1734
1735     System.out.println("### computeReturnLocation");
1736     System.out.println("### args=" + args);
1737     System.out.println("### calculateGLB=" + inputGLB);
1738     System.out.println("### glb=" + glb);
1739
1740     return glb;
1741   }
1742 }