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