changes.
[IRC.git] / Robust / src / Analysis / SSJava / FlowDownCheck.java
1 package Analysis.SSJava;
2
3 import java.util.ArrayList;
4 import java.util.Collections;
5 import java.util.Comparator;
6 import java.util.HashSet;
7 import java.util.Hashtable;
8 import java.util.Iterator;
9 import java.util.List;
10 import java.util.Set;
11 import java.util.StringTokenizer;
12 import java.util.Vector;
13
14 import Analysis.SSJava.FlowDownCheck.ComparisonResult;
15 import Analysis.SSJava.FlowDownCheck.CompositeLattice;
16 import IR.AnnotationDescriptor;
17 import IR.ClassDescriptor;
18 import IR.Descriptor;
19 import IR.FieldDescriptor;
20 import IR.MethodDescriptor;
21 import IR.NameDescriptor;
22 import IR.Operation;
23 import IR.State;
24 import IR.SymbolTable;
25 import IR.TypeDescriptor;
26 import IR.TypeExtension;
27 import IR.VarDescriptor;
28 import IR.Flat.FlatNode;
29 import IR.Tree.ArrayAccessNode;
30 import IR.Tree.AssignmentNode;
31 import IR.Tree.BlockExpressionNode;
32 import IR.Tree.BlockNode;
33 import IR.Tree.BlockStatementNode;
34 import IR.Tree.CastNode;
35 import IR.Tree.CreateObjectNode;
36 import IR.Tree.DeclarationNode;
37 import IR.Tree.ExpressionNode;
38 import IR.Tree.FieldAccessNode;
39 import IR.Tree.IfStatementNode;
40 import IR.Tree.Kind;
41 import IR.Tree.LiteralNode;
42 import IR.Tree.LoopNode;
43 import IR.Tree.MethodInvokeNode;
44 import IR.Tree.NameNode;
45 import IR.Tree.OpNode;
46 import IR.Tree.ReturnNode;
47 import IR.Tree.SubBlockNode;
48 import IR.Tree.SwitchBlockNode;
49 import IR.Tree.SwitchStatementNode;
50 import IR.Tree.SynchronizedNode;
51 import IR.Tree.TertiaryNode;
52 import IR.Tree.TreeNode;
53 import Util.Pair;
54
55 public class FlowDownCheck {
56
57   State state;
58   static SSJavaAnalysis ssjava;
59
60   Set<ClassDescriptor> toanalyze;
61   List<ClassDescriptor> toanalyzeList;
62
63   Set<MethodDescriptor> toanalyzeMethod;
64   List<MethodDescriptor> toanalyzeMethodList;
65
66   // mapping from 'descriptor' to 'composite location'
67   Hashtable<Descriptor, CompositeLocation> d2loc;
68
69   Hashtable<MethodDescriptor, CompositeLocation> md2ReturnLoc;
70   Hashtable<MethodDescriptor, ReturnLocGenerator> md2ReturnLocGen;
71
72   // mapping from 'locID' to 'class descriptor'
73   Hashtable<String, ClassDescriptor> fieldLocName2cd;
74
75   boolean deterministic = true;
76
77   public FlowDownCheck(SSJavaAnalysis ssjava, State state) {
78     this.ssjava = ssjava;
79     this.state = state;
80     if (deterministic) {
81       this.toanalyzeList = new ArrayList<ClassDescriptor>();
82     } else {
83       this.toanalyze = new HashSet<ClassDescriptor>();
84     }
85     if (deterministic) {
86       this.toanalyzeMethodList = new ArrayList<MethodDescriptor>();
87     } else {
88       this.toanalyzeMethod = new HashSet<MethodDescriptor>();
89     }
90     this.d2loc = new Hashtable<Descriptor, CompositeLocation>();
91     this.fieldLocName2cd = new Hashtable<String, ClassDescriptor>();
92     this.md2ReturnLoc = new Hashtable<MethodDescriptor, CompositeLocation>();
93     this.md2ReturnLocGen = new Hashtable<MethodDescriptor, ReturnLocGenerator>();
94   }
95
96   public void init() {
97
98     // construct mapping from the location name to the class descriptor
99     // assume that the location name is unique through the whole program
100
101     Set<ClassDescriptor> cdSet = ssjava.getCd2lattice().keySet();
102     for (Iterator iterator = cdSet.iterator(); iterator.hasNext();) {
103       ClassDescriptor cd = (ClassDescriptor) iterator.next();
104       SSJavaLattice<String> lattice = ssjava.getCd2lattice().get(cd);
105       Set<String> fieldLocNameSet = lattice.getKeySet();
106
107       for (Iterator iterator2 = fieldLocNameSet.iterator(); iterator2.hasNext();) {
108         String fieldLocName = (String) iterator2.next();
109         fieldLocName2cd.put(fieldLocName, cd);
110       }
111
112     }
113
114   }
115
116   public boolean toAnalyzeIsEmpty() {
117     if (deterministic) {
118       return toanalyzeList.isEmpty();
119     } else {
120       return toanalyze.isEmpty();
121     }
122   }
123
124   public ClassDescriptor toAnalyzeNext() {
125     if (deterministic) {
126       return toanalyzeList.remove(0);
127     } else {
128       ClassDescriptor cd = toanalyze.iterator().next();
129       toanalyze.remove(cd);
130       return cd;
131     }
132   }
133
134   public void setupToAnalyze() {
135     SymbolTable classtable = state.getClassSymbolTable();
136     if (deterministic) {
137       toanalyzeList.clear();
138       toanalyzeList.addAll(classtable.getValueSet());
139       Collections.sort(toanalyzeList, new Comparator<ClassDescriptor>() {
140         public int compare(ClassDescriptor o1, ClassDescriptor o2) {
141           return o1.getClassName().compareToIgnoreCase(o2.getClassName());
142         }
143       });
144     } else {
145       toanalyze.clear();
146       toanalyze.addAll(classtable.getValueSet());
147     }
148   }
149
150   public void setupToAnalazeMethod(ClassDescriptor cd) {
151
152     SymbolTable methodtable = cd.getMethodTable();
153     if (deterministic) {
154       toanalyzeMethodList.clear();
155       toanalyzeMethodList.addAll(methodtable.getValueSet());
156       Collections.sort(toanalyzeMethodList, new Comparator<MethodDescriptor>() {
157         public int compare(MethodDescriptor o1, MethodDescriptor o2) {
158           return o1.getSymbol().compareToIgnoreCase(o2.getSymbol());
159         }
160       });
161     } else {
162       toanalyzeMethod.clear();
163       toanalyzeMethod.addAll(methodtable.getValueSet());
164     }
165   }
166
167   public boolean toAnalyzeMethodIsEmpty() {
168     if (deterministic) {
169       return toanalyzeMethodList.isEmpty();
170     } else {
171       return toanalyzeMethod.isEmpty();
172     }
173   }
174
175   public MethodDescriptor toAnalyzeMethodNext() {
176     if (deterministic) {
177       return toanalyzeMethodList.remove(0);
178     } else {
179       MethodDescriptor md = toanalyzeMethod.iterator().next();
180       toanalyzeMethod.remove(md);
181       return md;
182     }
183   }
184
185   public void flowDownCheck() {
186
187     // phase 1 : checking declaration node and creating mapping of 'type
188     // desciptor' & 'location'
189     setupToAnalyze();
190
191     while (!toAnalyzeIsEmpty()) {
192       ClassDescriptor cd = toAnalyzeNext();
193
194       if (ssjava.needToBeAnnoated(cd)) {
195
196         ClassDescriptor superDesc = cd.getSuperDesc();
197
198         if (superDesc != null && (!superDesc.getSymbol().equals("Object"))) {
199           checkOrderingInheritance(superDesc, cd);
200         }
201
202         checkDeclarationInClass(cd);
203
204         setupToAnalazeMethod(cd);
205         while (!toAnalyzeMethodIsEmpty()) {
206           MethodDescriptor md = toAnalyzeMethodNext();
207           if (ssjava.needTobeAnnotated(md)) {
208             checkDeclarationInMethodBody(cd, md);
209           }
210         }
211
212       }
213
214     }
215
216     // phase2 : checking assignments
217     setupToAnalyze();
218
219     while (!toAnalyzeIsEmpty()) {
220       ClassDescriptor cd = toAnalyzeNext();
221
222       setupToAnalazeMethod(cd);
223       while (!toAnalyzeMethodIsEmpty()) {
224         MethodDescriptor md = toAnalyzeMethodNext();
225         if (ssjava.needTobeAnnotated(md)) {
226           if (state.SSJAVADEBUG) {
227             System.out.println("SSJAVA: Checking Flow-down Rules: " + md);
228           }
229           CompositeLocation calleePCLOC = ssjava.getPCLocation(md);
230           checkMethodBody(cd, md, calleePCLOC);
231         }
232       }
233     }
234
235   }
236
237   private void checkOrderingInheritance(ClassDescriptor superCd, ClassDescriptor cd) {
238     // here, we're going to check that sub class keeps same relative orderings
239     // in respect to super class
240
241     SSJavaLattice<String> superLattice = ssjava.getClassLattice(superCd);
242     SSJavaLattice<String> subLattice = ssjava.getClassLattice(cd);
243
244     if (superLattice != null) {
245       // if super class doesn't define lattice, then we don't need to check its
246       // subclass
247       if (subLattice == null) {
248         throw new Error("If a parent class '" + superCd
249             + "' has a ordering lattice, its subclass '" + cd + "' should have one.");
250       }
251
252       Set<Pair<String, String>> superPairSet = superLattice.getOrderingPairSet();
253       Set<Pair<String, String>> subPairSet = subLattice.getOrderingPairSet();
254
255       for (Iterator iterator = superPairSet.iterator(); iterator.hasNext();) {
256         Pair<String, String> pair = (Pair<String, String>) iterator.next();
257
258         if (!subPairSet.contains(pair)) {
259           throw new Error("Subclass '" + cd + "' does not have the relative ordering '"
260               + pair.getSecond() + " < " + pair.getFirst()
261               + "' that is defined by its superclass '" + superCd + "'.");
262         }
263       }
264     }
265
266     MethodLattice<String> superMethodDefaultLattice = ssjava.getMethodDefaultLattice(superCd);
267     MethodLattice<String> subMethodDefaultLattice = ssjava.getMethodDefaultLattice(cd);
268
269     if (superMethodDefaultLattice != null) {
270       if (subMethodDefaultLattice == null) {
271         throw new Error("When a parent class '" + superCd
272             + "' defines a default method lattice, its subclass '" + cd + "' should define one.");
273       }
274
275       Set<Pair<String, String>> superPairSet = superMethodDefaultLattice.getOrderingPairSet();
276       Set<Pair<String, String>> subPairSet = subMethodDefaultLattice.getOrderingPairSet();
277
278       for (Iterator iterator = superPairSet.iterator(); iterator.hasNext();) {
279         Pair<String, String> pair = (Pair<String, String>) iterator.next();
280
281         if (!subPairSet.contains(pair)) {
282           throw new Error("Subclass '" + cd + "' does not have the relative ordering '"
283               + pair.getSecond() + " < " + pair.getFirst()
284               + "' that is defined by its superclass '" + superCd
285               + "' in the method default lattice.");
286         }
287       }
288
289     }
290
291   }
292
293   public Hashtable getMap() {
294     return d2loc;
295   }
296
297   private void checkDeclarationInMethodBody(ClassDescriptor cd, MethodDescriptor md) {
298     BlockNode bn = state.getMethodBody(md);
299
300     // first, check annotations on method parameters
301     List<CompositeLocation> paramList = new ArrayList<CompositeLocation>();
302     for (int i = 0; i < md.numParameters(); i++) {
303       // process annotations on method parameters
304       VarDescriptor vd = (VarDescriptor) md.getParameter(i);
305       assignLocationOfVarDescriptor(vd, md, md.getParameterTable(), null);
306       paramList.add(d2loc.get(vd));
307     }
308     Vector<AnnotationDescriptor> methodAnnotations = md.getModifiers().getAnnotations();
309
310     CompositeLocation returnLocComp = null;
311
312     boolean hasReturnLocDeclaration = false;
313     if (methodAnnotations != null) {
314       for (int i = 0; i < methodAnnotations.size(); i++) {
315         AnnotationDescriptor an = methodAnnotations.elementAt(i);
316         if (an.getMarker().equals(ssjava.RETURNLOC)) {
317           // this case, developer explicitly defines method lattice
318           String returnLocDeclaration = an.getValue();
319           returnLocComp = parseLocationDeclaration(md, null, returnLocDeclaration);
320           hasReturnLocDeclaration = true;
321         } else if (an.getMarker().equals(ssjava.THISLOC)) {
322           String thisLoc = an.getValue();
323           ssjava.getMethodLattice(md).setThisLoc(thisLoc);
324         } else if (an.getMarker().equals(ssjava.GLOBALLOC)) {
325           String globalLoc = an.getValue();
326           ssjava.getMethodLattice(md).setGlobalLoc(globalLoc);
327         } else if (an.getMarker().equals(ssjava.PCLOC)) {
328           String pcLocDeclaration = an.getValue();
329           ssjava.setPCLocation(md, parseLocationDeclaration(md, null, pcLocDeclaration));
330         }
331       }
332     }
333
334     // second, check return location annotation
335     if (!md.getReturnType().isVoid()) {
336       if (!hasReturnLocDeclaration) {
337         // if developer does not define method lattice
338         // search return location in the method default lattice
339         String rtrStr = ssjava.getMethodLattice(md).getReturnLoc();
340         if (rtrStr != null) {
341           returnLocComp = new CompositeLocation(new Location(md, rtrStr));
342         }
343       }
344
345       if (returnLocComp == null) {
346         throw new Error("Return location is not specified for the method " + md + " at "
347             + cd.getSourceFileName());
348       }
349
350       md2ReturnLoc.put(md, returnLocComp);
351
352     }
353
354     if (!md.getReturnType().isVoid()) {
355       MethodLattice<String> methodLattice = ssjava.getMethodLattice(md);
356       String thisLocId = methodLattice.getThisLoc();
357       if ((!md.isStatic()) && thisLocId == null) {
358         throw new Error("Method '" + md + "' does not have the definition of 'this' location at "
359             + md.getClassDesc().getSourceFileName());
360       }
361       CompositeLocation thisLoc = new CompositeLocation(new Location(md, thisLocId));
362       paramList.add(0, thisLoc);
363       md2ReturnLocGen.put(md, new ReturnLocGenerator(md2ReturnLoc.get(md), md, paramList, md
364           + " of " + cd.getSourceFileName()));
365     }
366
367     // fourth, check declarations inside of method
368
369     checkDeclarationInBlockNode(md, md.getParameterTable(), bn);
370
371   }
372
373   private void checkDeclarationInBlockNode(MethodDescriptor md, SymbolTable nametable, BlockNode bn) {
374     bn.getVarTable().setParent(nametable);
375     for (int i = 0; i < bn.size(); i++) {
376       BlockStatementNode bsn = bn.get(i);
377       checkDeclarationInBlockStatementNode(md, bn.getVarTable(), bsn);
378     }
379   }
380
381   private void checkDeclarationInBlockStatementNode(MethodDescriptor md, SymbolTable nametable,
382       BlockStatementNode bsn) {
383
384     switch (bsn.kind()) {
385     case Kind.SubBlockNode:
386       checkDeclarationInSubBlockNode(md, nametable, (SubBlockNode) bsn);
387       return;
388
389     case Kind.DeclarationNode:
390       checkDeclarationNode(md, nametable, (DeclarationNode) bsn);
391       break;
392
393     case Kind.LoopNode:
394       checkDeclarationInLoopNode(md, nametable, (LoopNode) bsn);
395       break;
396
397     case Kind.IfStatementNode:
398       checkDeclarationInIfStatementNode(md, nametable, (IfStatementNode) bsn);
399       return;
400
401     case Kind.SwitchStatementNode:
402       checkDeclarationInSwitchStatementNode(md, nametable, (SwitchStatementNode) bsn);
403       return;
404
405     case Kind.SynchronizedNode:
406       checkDeclarationInSynchronizedNode(md, nametable, (SynchronizedNode) bsn);
407       return;
408
409     }
410   }
411
412   private void checkDeclarationInSynchronizedNode(MethodDescriptor md, SymbolTable nametable,
413       SynchronizedNode sbn) {
414     checkDeclarationInBlockNode(md, nametable, sbn.getBlockNode());
415   }
416
417   private void checkDeclarationInSwitchStatementNode(MethodDescriptor md, SymbolTable nametable,
418       SwitchStatementNode ssn) {
419     BlockNode sbn = ssn.getSwitchBody();
420     for (int i = 0; i < sbn.size(); i++) {
421       SwitchBlockNode node = (SwitchBlockNode) sbn.get(i);
422       checkDeclarationInBlockNode(md, nametable, node.getSwitchBlockStatement());
423     }
424   }
425
426   private void checkDeclarationInIfStatementNode(MethodDescriptor md, SymbolTable nametable,
427       IfStatementNode isn) {
428     checkDeclarationInBlockNode(md, nametable, isn.getTrueBlock());
429     if (isn.getFalseBlock() != null)
430       checkDeclarationInBlockNode(md, nametable, isn.getFalseBlock());
431   }
432
433   private void checkDeclarationInLoopNode(MethodDescriptor md, SymbolTable nametable, LoopNode ln) {
434
435     if (ln.getType() == LoopNode.FORLOOP) {
436       // check for loop case
437       ClassDescriptor cd = md.getClassDesc();
438       BlockNode bn = ln.getInitializer();
439       for (int i = 0; i < bn.size(); i++) {
440         BlockStatementNode bsn = bn.get(i);
441         checkDeclarationInBlockStatementNode(md, nametable, bsn);
442       }
443     }
444
445     // check loop body
446     checkDeclarationInBlockNode(md, nametable, ln.getBody());
447   }
448
449   private void checkMethodBody(ClassDescriptor cd, MethodDescriptor md,
450       CompositeLocation constraints) {
451     BlockNode bn = state.getMethodBody(md);
452     checkLocationFromBlockNode(md, md.getParameterTable(), bn, constraints);
453   }
454
455   private String generateErrorMessage(ClassDescriptor cd, TreeNode tn) {
456     if (tn != null) {
457       return cd.getSourceFileName() + "::" + tn.getNumLine();
458     } else {
459       return cd.getSourceFileName();
460     }
461
462   }
463
464   private CompositeLocation checkLocationFromBlockNode(MethodDescriptor md, SymbolTable nametable,
465       BlockNode bn, CompositeLocation constraint) {
466
467     bn.getVarTable().setParent(nametable);
468     for (int i = 0; i < bn.size(); i++) {
469       BlockStatementNode bsn = bn.get(i);
470       checkLocationFromBlockStatementNode(md, bn.getVarTable(), bsn, constraint);
471     }
472     return new CompositeLocation();
473
474   }
475
476   private CompositeLocation checkLocationFromBlockStatementNode(MethodDescriptor md,
477       SymbolTable nametable, BlockStatementNode bsn, CompositeLocation constraint) {
478
479     CompositeLocation compLoc = null;
480     switch (bsn.kind()) {
481     case Kind.BlockExpressionNode:
482       compLoc =
483           checkLocationFromBlockExpressionNode(md, nametable, (BlockExpressionNode) bsn, constraint);
484       break;
485
486     case Kind.DeclarationNode:
487       compLoc = checkLocationFromDeclarationNode(md, nametable, (DeclarationNode) bsn, constraint);
488       break;
489
490     case Kind.IfStatementNode:
491       compLoc = checkLocationFromIfStatementNode(md, nametable, (IfStatementNode) bsn, constraint);
492       break;
493
494     case Kind.LoopNode:
495       compLoc = checkLocationFromLoopNode(md, nametable, (LoopNode) bsn, constraint);
496       break;
497
498     case Kind.ReturnNode:
499       compLoc = checkLocationFromReturnNode(md, nametable, (ReturnNode) bsn, constraint);
500       break;
501
502     case Kind.SubBlockNode:
503       compLoc = checkLocationFromSubBlockNode(md, nametable, (SubBlockNode) bsn, constraint);
504       break;
505
506     case Kind.ContinueBreakNode:
507       compLoc = new CompositeLocation();
508       break;
509
510     case Kind.SwitchStatementNode:
511       compLoc =
512           checkLocationFromSwitchStatementNode(md, nametable, (SwitchStatementNode) bsn, constraint);
513
514     }
515     return compLoc;
516   }
517
518   private CompositeLocation checkLocationFromSwitchStatementNode(MethodDescriptor md,
519       SymbolTable nametable, SwitchStatementNode ssn, CompositeLocation constraint) {
520
521     ClassDescriptor cd = md.getClassDesc();
522     CompositeLocation condLoc =
523         checkLocationFromExpressionNode(md, nametable, ssn.getCondition(), new CompositeLocation(),
524             constraint, false);
525     BlockNode sbn = ssn.getSwitchBody();
526
527     constraint = generateNewConstraint(constraint, condLoc);
528
529     for (int i = 0; i < sbn.size(); i++) {
530       checkLocationFromSwitchBlockNode(md, nametable, (SwitchBlockNode) sbn.get(i), constraint);
531     }
532     return new CompositeLocation();
533   }
534
535   private CompositeLocation checkLocationFromSwitchBlockNode(MethodDescriptor md,
536       SymbolTable nametable, SwitchBlockNode sbn, CompositeLocation constraint) {
537
538     CompositeLocation blockLoc =
539         checkLocationFromBlockNode(md, nametable, sbn.getSwitchBlockStatement(), constraint);
540
541     return blockLoc;
542
543   }
544
545   private CompositeLocation checkLocationFromReturnNode(MethodDescriptor md, SymbolTable nametable,
546       ReturnNode rn, CompositeLocation constraint) {
547
548     ExpressionNode returnExp = rn.getReturnExpression();
549
550     CompositeLocation returnValueLoc;
551     if (returnExp != null) {
552       returnValueLoc =
553           checkLocationFromExpressionNode(md, nametable, returnExp, new CompositeLocation(),
554               constraint, false);
555
556       // System.out.println("# RETURN VALUE LOC=" + returnValueLoc +
557       // " with constraint=" + constraint);
558
559       // TODO: do we need to check here?
560       // if this return statement is inside branch, return value has an implicit
561       // flow from conditional location
562       // if (constraint != null) {
563       // Set<CompositeLocation> inputGLB = new HashSet<CompositeLocation>();
564       // inputGLB.add(returnValueLoc);
565       // inputGLB.add(constraint);
566       // returnValueLoc =
567       // CompositeLattice.calculateGLB(inputGLB,
568       // generateErrorMessage(md.getClassDesc(), rn));
569       // }
570
571       // check if return value is equal or higher than RETRUNLOC of method
572       // declaration annotation
573       CompositeLocation declaredReturnLoc = md2ReturnLoc.get(md);
574
575       int compareResult =
576           CompositeLattice.compare(returnValueLoc, declaredReturnLoc, false,
577               generateErrorMessage(md.getClassDesc(), rn));
578
579       if (compareResult == ComparisonResult.LESS || compareResult == ComparisonResult.INCOMPARABLE) {
580         throw new Error(
581             "Return value location is not equal or higher than the declaraed return location at "
582                 + md.getClassDesc().getSourceFileName() + "::" + rn.getNumLine());
583       }
584     }
585
586     return new CompositeLocation();
587   }
588
589   private boolean hasOnlyLiteralValue(ExpressionNode en) {
590     if (en.kind() == Kind.LiteralNode) {
591       return true;
592     } else {
593       return false;
594     }
595   }
596
597   private CompositeLocation checkLocationFromLoopNode(MethodDescriptor md, SymbolTable nametable,
598       LoopNode ln, CompositeLocation constraint) {
599
600     ClassDescriptor cd = md.getClassDesc();
601     if (ln.getType() == LoopNode.WHILELOOP || ln.getType() == LoopNode.DOWHILELOOP) {
602
603       CompositeLocation condLoc =
604           checkLocationFromExpressionNode(md, nametable, ln.getCondition(),
605               new CompositeLocation(), constraint, false);
606       // addLocationType(ln.getCondition().getType(), (condLoc));
607
608       constraint = generateNewConstraint(constraint, condLoc);
609       checkLocationFromBlockNode(md, nametable, ln.getBody(), constraint);
610
611       return new CompositeLocation();
612
613     } else {
614       // check 'for loop' case
615       BlockNode bn = ln.getInitializer();
616       bn.getVarTable().setParent(nametable);
617       // need to check initialization node
618       // checkLocationFromBlockNode(md, bn.getVarTable(), bn, constraint);
619       for (int i = 0; i < bn.size(); i++) {
620         BlockStatementNode bsn = bn.get(i);
621         checkLocationFromBlockStatementNode(md, bn.getVarTable(), bsn, constraint);
622       }
623
624       // calculate glb location of condition and update statements
625       CompositeLocation condLoc =
626           checkLocationFromExpressionNode(md, bn.getVarTable(), ln.getCondition(),
627               new CompositeLocation(), constraint, false);
628       // addLocationType(ln.getCondition().getType(), condLoc);
629
630       constraint = generateNewConstraint(constraint, condLoc);
631
632       checkLocationFromBlockNode(md, bn.getVarTable(), ln.getUpdate(), constraint);
633       checkLocationFromBlockNode(md, bn.getVarTable(), ln.getBody(), constraint);
634
635       return new CompositeLocation();
636
637     }
638
639   }
640
641   private CompositeLocation checkLocationFromSubBlockNode(MethodDescriptor md,
642       SymbolTable nametable, SubBlockNode sbn, CompositeLocation constraint) {
643     CompositeLocation compLoc =
644         checkLocationFromBlockNode(md, nametable, sbn.getBlockNode(), constraint);
645     return compLoc;
646   }
647
648   private CompositeLocation generateNewConstraint(CompositeLocation currentCon,
649       CompositeLocation newCon) {
650
651     if (currentCon == null) {
652       return newCon;
653     } else {
654       // compute GLB of current constraint and new constraint
655       Set<CompositeLocation> inputSet = new HashSet<CompositeLocation>();
656       inputSet.add(currentCon);
657       inputSet.add(newCon);
658       return CompositeLattice.calculateGLB(inputSet, "");
659     }
660
661   }
662
663   private CompositeLocation checkLocationFromIfStatementNode(MethodDescriptor md,
664       SymbolTable nametable, IfStatementNode isn, CompositeLocation constraint) {
665
666     CompositeLocation condLoc =
667         checkLocationFromExpressionNode(md, nametable, isn.getCondition(), new CompositeLocation(),
668             constraint, false);
669
670     // addLocationType(isn.getCondition().getType(), condLoc);
671
672     constraint = generateNewConstraint(constraint, condLoc);
673     checkLocationFromBlockNode(md, nametable, isn.getTrueBlock(), constraint);
674
675     if (isn.getFalseBlock() != null) {
676       checkLocationFromBlockNode(md, nametable, isn.getFalseBlock(), constraint);
677     }
678
679     return new CompositeLocation();
680   }
681
682   private void checkOwnership(MethodDescriptor md, TreeNode tn, ExpressionNode srcExpNode) {
683
684     if (srcExpNode.kind() == Kind.NameNode || srcExpNode.kind() == Kind.FieldAccessNode) {
685       if (srcExpNode.getType().isPtr() && !srcExpNode.getType().isNull()) {
686         // first, check the linear type
687         // RHS reference should be owned by the current method
688         FieldDescriptor fd = getFieldDescriptorFromExpressionNode(srcExpNode);
689         boolean isOwned;
690         if (fd == null) {
691           // local var case
692           isOwned = ((SSJavaType) srcExpNode.getType().getExtension()).isOwned();
693         } else {
694           // field case
695           isOwned = ssjava.isOwnedByMethod(md, fd);
696         }
697         if (!isOwned) {
698           throw new Error(
699               "It is not allowed to create the reference alias from the reference not owned by the method at "
700                   + generateErrorMessage(md.getClassDesc(), tn));
701         }
702
703       }
704     }
705
706   }
707
708   private CompositeLocation checkLocationFromDeclarationNode(MethodDescriptor md,
709       SymbolTable nametable, DeclarationNode dn, CompositeLocation constraint) {
710
711     VarDescriptor vd = dn.getVarDescriptor();
712
713     CompositeLocation destLoc = d2loc.get(vd);
714
715     if (dn.getExpression() != null) {
716
717       checkOwnership(md, dn, dn.getExpression());
718
719       CompositeLocation expressionLoc =
720           checkLocationFromExpressionNode(md, nametable, dn.getExpression(),
721               new CompositeLocation(), constraint, false);
722       // addTypeLocation(dn.getExpression().getType(), expressionLoc);
723
724       if (expressionLoc != null) {
725
726         // checking location order
727         if (!CompositeLattice.isGreaterThan(expressionLoc, destLoc,
728             generateErrorMessage(md.getClassDesc(), dn))) {
729           throw new Error("The value flow from " + expressionLoc + " to " + destLoc
730               + " does not respect location hierarchy on the assignment " + dn.printNode(0)
731               + " at " + md.getClassDesc().getSourceFileName() + "::" + dn.getNumLine());
732         }
733       }
734       return expressionLoc;
735
736     } else {
737
738       return new CompositeLocation();
739
740     }
741
742   }
743
744   private void checkDeclarationInSubBlockNode(MethodDescriptor md, SymbolTable nametable,
745       SubBlockNode sbn) {
746     checkDeclarationInBlockNode(md, nametable, sbn.getBlockNode());
747   }
748
749   private CompositeLocation checkLocationFromBlockExpressionNode(MethodDescriptor md,
750       SymbolTable nametable, BlockExpressionNode ben, CompositeLocation constraint) {
751
752     CompositeLocation compLoc =
753         checkLocationFromExpressionNode(md, nametable, ben.getExpression(), null, constraint, false);
754     // addTypeLocation(ben.getExpression().getType(), compLoc);
755     return compLoc;
756   }
757
758   private CompositeLocation checkLocationFromExpressionNode(MethodDescriptor md,
759       SymbolTable nametable, ExpressionNode en, CompositeLocation loc,
760       CompositeLocation constraint, boolean isLHS) {
761
762     CompositeLocation compLoc = null;
763     switch (en.kind()) {
764
765     case Kind.AssignmentNode:
766       compLoc =
767           checkLocationFromAssignmentNode(md, nametable, (AssignmentNode) en, loc, constraint);
768       break;
769
770     case Kind.FieldAccessNode:
771       compLoc =
772           checkLocationFromFieldAccessNode(md, nametable, (FieldAccessNode) en, loc, constraint);
773       break;
774
775     case Kind.NameNode:
776       compLoc = checkLocationFromNameNode(md, nametable, (NameNode) en, loc, constraint);
777       break;
778
779     case Kind.OpNode:
780       compLoc = checkLocationFromOpNode(md, nametable, (OpNode) en, constraint);
781       break;
782
783     case Kind.CreateObjectNode:
784       compLoc = checkLocationFromCreateObjectNode(md, nametable, (CreateObjectNode) en);
785       break;
786
787     case Kind.ArrayAccessNode:
788       compLoc =
789           checkLocationFromArrayAccessNode(md, nametable, (ArrayAccessNode) en, constraint, isLHS);
790       break;
791
792     case Kind.LiteralNode:
793       compLoc = checkLocationFromLiteralNode(md, nametable, (LiteralNode) en, loc);
794       break;
795
796     case Kind.MethodInvokeNode:
797       compLoc =
798           checkLocationFromMethodInvokeNode(md, nametable, (MethodInvokeNode) en, loc, constraint);
799       break;
800
801     case Kind.TertiaryNode:
802       compLoc = checkLocationFromTertiaryNode(md, nametable, (TertiaryNode) en, constraint);
803       break;
804
805     case Kind.CastNode:
806       compLoc = checkLocationFromCastNode(md, nametable, (CastNode) en, constraint);
807       break;
808
809     // case Kind.InstanceOfNode:
810     // checkInstanceOfNode(md, nametable, (InstanceOfNode) en, td);
811     // return null;
812
813     // case Kind.ArrayInitializerNode:
814     // checkArrayInitializerNode(md, nametable, (ArrayInitializerNode) en,
815     // td);
816     // return null;
817
818     // case Kind.ClassTypeNode:
819     // checkClassTypeNode(md, nametable, (ClassTypeNode) en, td);
820     // return null;
821
822     // case Kind.OffsetNode:
823     // checkOffsetNode(md, nametable, (OffsetNode)en, td);
824     // return null;
825
826     default:
827       return null;
828
829     }
830     // addTypeLocation(en.getType(), compLoc);
831     return compLoc;
832
833   }
834
835   private CompositeLocation checkLocationFromCastNode(MethodDescriptor md, SymbolTable nametable,
836       CastNode cn, CompositeLocation constraint) {
837
838     ExpressionNode en = cn.getExpression();
839     return checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation(), constraint,
840         false);
841
842   }
843
844   private CompositeLocation checkLocationFromTertiaryNode(MethodDescriptor md,
845       SymbolTable nametable, TertiaryNode tn, CompositeLocation constraint) {
846     ClassDescriptor cd = md.getClassDesc();
847
848     CompositeLocation condLoc =
849         checkLocationFromExpressionNode(md, nametable, tn.getCond(), new CompositeLocation(),
850             constraint, false);
851     // addLocationType(tn.getCond().getType(), condLoc);
852     CompositeLocation trueLoc =
853         checkLocationFromExpressionNode(md, nametable, tn.getTrueExpr(), new CompositeLocation(),
854             constraint, false);
855     // addLocationType(tn.getTrueExpr().getType(), trueLoc);
856     CompositeLocation falseLoc =
857         checkLocationFromExpressionNode(md, nametable, tn.getFalseExpr(), new CompositeLocation(),
858             constraint, false);
859     // addLocationType(tn.getFalseExpr().getType(), falseLoc);
860
861     // locations from true/false branches can be TOP when there are only literal
862     // values
863     // in this case, we don't need to check flow down rule!
864
865     // System.out.println("\n#tertiary cond=" + tn.getCond().printNode(0) +
866     // " Loc=" + condLoc);
867     // System.out.println("# true=" + tn.getTrueExpr().printNode(0) + " Loc=" +
868     // trueLoc);
869     // System.out.println("# false=" + tn.getFalseExpr().printNode(0) + " Loc="
870     // + falseLoc);
871
872     // check if condLoc is higher than trueLoc & falseLoc
873     if (!trueLoc.get(0).isTop()
874         && !CompositeLattice.isGreaterThan(condLoc, trueLoc, generateErrorMessage(cd, tn))) {
875       throw new Error(
876           "The location of the condition expression is lower than the true expression at "
877               + cd.getSourceFileName() + ":" + tn.getCond().getNumLine());
878     }
879
880     if (!falseLoc.get(0).isTop()
881         && !CompositeLattice.isGreaterThan(condLoc, falseLoc,
882             generateErrorMessage(cd, tn.getCond()))) {
883       throw new Error(
884           "The location of the condition expression is lower than the false expression at "
885               + cd.getSourceFileName() + ":" + tn.getCond().getNumLine());
886     }
887
888     // then, return glb of trueLoc & falseLoc
889     Set<CompositeLocation> glbInputSet = new HashSet<CompositeLocation>();
890     glbInputSet.add(trueLoc);
891     glbInputSet.add(falseLoc);
892
893     if (glbInputSet.size() == 1) {
894       return trueLoc;
895     } else {
896       return CompositeLattice.calculateGLB(glbInputSet, generateErrorMessage(cd, tn));
897     }
898
899   }
900
901   private CompositeLocation checkLocationFromMethodInvokeNode(MethodDescriptor md,
902       SymbolTable nametable, MethodInvokeNode min, CompositeLocation loc,
903       CompositeLocation constraint) {
904
905     ClassDescriptor cd = md.getClassDesc();
906     MethodDescriptor calleeMethodDesc = min.getMethod();
907
908     NameDescriptor baseName = min.getBaseName();
909     boolean isSystemout = false;
910     if (baseName != null) {
911       isSystemout = baseName.getSymbol().equals("System.out");
912     }
913
914     if (!ssjava.isSSJavaUtil(calleeMethodDesc.getClassDesc())
915         && !ssjava.isTrustMethod(calleeMethodDesc) && !calleeMethodDesc.getModifiers().isNative()
916         && !isSystemout) {
917
918       CompositeLocation baseLocation = null;
919       if (min.getExpression() != null) {
920         baseLocation =
921             checkLocationFromExpressionNode(md, nametable, min.getExpression(),
922                 new CompositeLocation(), constraint, false);
923       } else {
924         if (min.getMethod().isStatic()) {
925           String globalLocId = ssjava.getMethodLattice(md).getGlobalLoc();
926           if (globalLocId == null) {
927             throw new Error("Method lattice does not define global variable location at "
928                 + generateErrorMessage(md.getClassDesc(), min));
929           }
930           baseLocation = new CompositeLocation(new Location(md, globalLocId));
931         } else {
932           String thisLocId = ssjava.getMethodLattice(md).getThisLoc();
933           baseLocation = new CompositeLocation(new Location(md, thisLocId));
934         }
935       }
936
937       // System.out.println("\n#checkLocationFromMethodInvokeNode=" +
938       // min.printNode(0)
939       // + " baseLocation=" + baseLocation + " constraint=" + constraint);
940
941       // setup the location list of caller's arguments
942       List<CompositeLocation> callerArgList = new ArrayList<CompositeLocation>();
943
944       // setup the location list of callee's parameters
945       MethodLattice<String> calleeLattice = ssjava.getMethodLattice(calleeMethodDesc);
946       List<CompositeLocation> calleeParamList = new ArrayList<CompositeLocation>();
947
948       if (min.numArgs() > 0) {
949         if (!calleeMethodDesc.isStatic()) {
950           callerArgList.add(baseLocation);
951         }
952         for (int i = 0; i < min.numArgs(); i++) {
953           ExpressionNode en = min.getArg(i);
954           CompositeLocation callerArgLoc =
955               checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation(),
956                   constraint, false);
957           callerArgList.add(callerArgLoc);
958         }
959
960         if (!calleeMethodDesc.isStatic()) {
961           CompositeLocation calleeThisLoc =
962               new CompositeLocation(new Location(calleeMethodDesc, calleeLattice.getThisLoc()));
963           calleeParamList.add(calleeThisLoc);
964         }
965
966         for (int i = 0; i < calleeMethodDesc.numParameters(); i++) {
967           VarDescriptor calleevd = (VarDescriptor) calleeMethodDesc.getParameter(i);
968           CompositeLocation calleeLoc = d2loc.get(calleevd);
969           calleeParamList.add(calleeLoc);
970         }
971       }
972
973       if (constraint != null) {
974         // check whether the PC location is lower than one of the
975         // argument locations. If it is lower, the callee has to have @PCLOC
976         // annotation that declares the program counter that is higher than
977         // corresponding parameter
978
979         CompositeLocation calleePCLOC = ssjava.getPCLocation(calleeMethodDesc);
980
981         for (int idx = 0; idx < callerArgList.size(); idx++) {
982           CompositeLocation argLocation = callerArgList.get(idx);
983
984           // need to check that param is higher than PCLOC
985           if (!argLocation.get(0).isTop()
986               && CompositeLattice.compare(argLocation, constraint, true,
987                   generateErrorMessage(cd, min)) == ComparisonResult.GREATER) {
988
989             CompositeLocation paramLocation = calleeParamList.get(idx);
990
991             int paramCompareResult =
992                 CompositeLattice.compare(calleePCLOC, paramLocation, true,
993                     generateErrorMessage(cd, min));
994
995             if (paramCompareResult == ComparisonResult.GREATER) {
996               throw new Error(
997                   "The program counter location "
998                       + constraint
999                       + " is lower than the argument(idx="
1000                       + idx
1001                       + ") location "
1002                       + argLocation
1003                       + ". Need to specify that the initial PC location of the callee, which is currently set to "
1004                       + calleePCLOC + ", is lower than " + paramLocation + " in the method "
1005                       + calleeMethodDesc.getSymbol() + ":" + min.getNumLine());
1006             }
1007
1008           }
1009
1010         }
1011
1012       }
1013
1014       checkCalleeConstraints(md, nametable, min, baseLocation, constraint);
1015
1016       // checkCallerArgumentLocationConstraints(md, nametable, min,
1017       // baseLocation, constraint);
1018
1019       if (!min.getMethod().getReturnType().isVoid()) {
1020         // If method has a return value, compute the highest possible return
1021         // location in the caller's perspective
1022         CompositeLocation ceilingLoc =
1023             computeCeilingLocationForCaller(md, nametable, min, baseLocation, constraint);
1024         return ceilingLoc;
1025       }
1026     }
1027
1028     return new CompositeLocation(Location.createTopLocation(md));
1029
1030   }
1031
1032   private CompositeLocation translateCallerLocToCalleeLoc(MethodDescriptor calleeMD,
1033       CompositeLocation calleeBaseLoc, CompositeLocation constraint) {
1034
1035     CompositeLocation calleeConstraint = new CompositeLocation();
1036
1037     // if (constraint.startsWith(calleeBaseLoc)) {
1038     // if the first part of constraint loc is matched with callee base loc
1039     Location thisLoc = new Location(calleeMD, ssjava.getMethodLattice(calleeMD).getThisLoc());
1040     calleeConstraint.addLocation(thisLoc);
1041     for (int i = calleeBaseLoc.getSize(); i < constraint.getSize(); i++) {
1042       calleeConstraint.addLocation(constraint.get(i));
1043     }
1044
1045     // }
1046
1047     return calleeConstraint;
1048   }
1049
1050   private void checkCallerArgumentLocationConstraints(MethodDescriptor md, SymbolTable nametable,
1051       MethodInvokeNode min, CompositeLocation callerBaseLoc, CompositeLocation constraint) {
1052     // if parameter location consists of THIS and FIELD location,
1053     // caller should pass an argument that is comparable to the declared
1054     // parameter location
1055     // and is not lower than the declared parameter location in the field
1056     // lattice.
1057
1058     MethodDescriptor calleemd = min.getMethod();
1059
1060     List<CompositeLocation> callerArgList = new ArrayList<CompositeLocation>();
1061     List<CompositeLocation> calleeParamList = new ArrayList<CompositeLocation>();
1062
1063     MethodLattice<String> calleeLattice = ssjava.getMethodLattice(calleemd);
1064     Location calleeThisLoc = new Location(calleemd, calleeLattice.getThisLoc());
1065
1066     for (int i = 0; i < min.numArgs(); i++) {
1067       ExpressionNode en = min.getArg(i);
1068       CompositeLocation callerArgLoc =
1069           checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation(), constraint,
1070               false);
1071       callerArgList.add(callerArgLoc);
1072     }
1073
1074     // setup callee params set
1075     for (int i = 0; i < calleemd.numParameters(); i++) {
1076       VarDescriptor calleevd = (VarDescriptor) calleemd.getParameter(i);
1077       CompositeLocation calleeLoc = d2loc.get(calleevd);
1078       calleeParamList.add(calleeLoc);
1079     }
1080
1081     String errorMsg = generateErrorMessage(md.getClassDesc(), min);
1082
1083     // System.out.println("checkCallerArgumentLocationConstraints=" +
1084     // min.printNode(0));
1085     // System.out.println("base location=" + callerBaseLoc + " constraint=" +
1086     // constraint);
1087
1088     for (int i = 0; i < calleeParamList.size(); i++) {
1089       CompositeLocation calleeParamLoc = calleeParamList.get(i);
1090       if (calleeParamLoc.get(0).equals(calleeThisLoc) && calleeParamLoc.getSize() > 1) {
1091
1092         // callee parameter location has field information
1093         CompositeLocation callerArgLoc = callerArgList.get(i);
1094
1095         CompositeLocation paramLocation =
1096             translateCalleeParamLocToCaller(md, calleeParamLoc, callerBaseLoc, errorMsg);
1097
1098         Set<CompositeLocation> inputGLBSet = new HashSet<CompositeLocation>();
1099         if (constraint != null) {
1100           inputGLBSet.add(callerArgLoc);
1101           inputGLBSet.add(constraint);
1102           callerArgLoc =
1103               CompositeLattice.calculateGLB(inputGLBSet,
1104                   generateErrorMessage(md.getClassDesc(), min));
1105         }
1106
1107         if (!CompositeLattice.isGreaterThan(callerArgLoc, paramLocation, errorMsg)) {
1108           throw new Error("Caller argument '" + min.getArg(i).printNode(0) + " : " + callerArgLoc
1109               + "' should be higher than corresponding callee's parameter : " + paramLocation
1110               + " at " + errorMsg);
1111         }
1112
1113       }
1114     }
1115
1116   }
1117
1118   private CompositeLocation translateCalleeParamLocToCaller(MethodDescriptor md,
1119       CompositeLocation calleeParamLoc, CompositeLocation callerBaseLocation, String errorMsg) {
1120
1121     CompositeLocation translate = new CompositeLocation();
1122
1123     for (int i = 0; i < callerBaseLocation.getSize(); i++) {
1124       translate.addLocation(callerBaseLocation.get(i));
1125     }
1126
1127     for (int i = 1; i < calleeParamLoc.getSize(); i++) {
1128       translate.addLocation(calleeParamLoc.get(i));
1129     }
1130
1131     // System.out.println("TRANSLATED=" + translate + " from calleeParamLoc=" +
1132     // calleeParamLoc);
1133
1134     return translate;
1135   }
1136
1137   private CompositeLocation computeCeilingLocationForCaller(MethodDescriptor md,
1138       SymbolTable nametable, MethodInvokeNode min, CompositeLocation baseLocation,
1139       CompositeLocation constraint) {
1140     List<CompositeLocation> argList = new ArrayList<CompositeLocation>();
1141
1142     // by default, method has a THIS parameter
1143     argList.add(baseLocation);
1144
1145     for (int i = 0; i < min.numArgs(); i++) {
1146       ExpressionNode en = min.getArg(i);
1147       CompositeLocation callerArg =
1148           checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation(), constraint,
1149               false);
1150       argList.add(callerArg);
1151     }
1152
1153     // System.out.println("\n## computeReturnLocation=" + min.getMethod() +
1154     // " argList=" + argList);
1155     CompositeLocation ceilLoc = md2ReturnLocGen.get(min.getMethod()).computeReturnLocation(argList);
1156     // System.out.println("## ReturnLocation=" + ceilLoc);
1157
1158     return ceilLoc;
1159
1160   }
1161
1162   private void checkCalleeConstraints(MethodDescriptor md, SymbolTable nametable,
1163       MethodInvokeNode min, CompositeLocation callerBaseLoc, CompositeLocation constraint) {
1164
1165     MethodDescriptor calleemd = min.getMethod();
1166
1167     MethodLattice<String> calleeLattice = ssjava.getMethodLattice(calleemd);
1168
1169     CompositeLocation calleeThisLoc =
1170         new CompositeLocation(new Location(calleemd, calleeLattice.getThisLoc()));
1171
1172     List<CompositeLocation> callerArgList = new ArrayList<CompositeLocation>();
1173     List<CompositeLocation> calleeParamList = new ArrayList<CompositeLocation>();
1174
1175     if (min.numArgs() > 0) {
1176       // caller needs to guarantee that it passes arguments in regarding to
1177       // callee's hierarchy
1178
1179       // setup caller args set
1180       // first, add caller's base(this) location
1181       if (!calleemd.isStatic())
1182         callerArgList.add(callerBaseLoc);
1183       // second, add caller's arguments
1184       for (int i = 0; i < min.numArgs(); i++) {
1185         ExpressionNode en = min.getArg(i);
1186         CompositeLocation callerArgLoc =
1187             checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation(), constraint,
1188                 false);
1189         callerArgList.add(callerArgLoc);
1190       }
1191
1192       // setup callee params set
1193       // first, add callee's this location
1194       if (!calleemd.isStatic())
1195         calleeParamList.add(calleeThisLoc);
1196       // second, add callee's parameters
1197       for (int i = 0; i < calleemd.numParameters(); i++) {
1198         VarDescriptor calleevd = (VarDescriptor) calleemd.getParameter(i);
1199         CompositeLocation calleeLoc = d2loc.get(calleevd);
1200         // System.out.println("calleevd=" + calleevd + " loc=" + calleeLoc);
1201         calleeParamList.add(calleeLoc);
1202       }
1203
1204       // here, check if ordering relations among caller's args respect
1205       // ordering relations in-between callee's args
1206       CHECK: for (int i = 0; i < calleeParamList.size(); i++) {
1207         CompositeLocation calleeLoc1 = calleeParamList.get(i);
1208         CompositeLocation callerLoc1 = callerArgList.get(i);
1209
1210         for (int j = 0; j < calleeParamList.size(); j++) {
1211           if (i != j) {
1212             CompositeLocation calleeLoc2 = calleeParamList.get(j);
1213             CompositeLocation callerLoc2 = callerArgList.get(j);
1214
1215             if (callerLoc1.get(callerLoc1.getSize() - 1).isTop()
1216                 || callerLoc2.get(callerLoc2.getSize() - 1).isTop()) {
1217               continue CHECK;
1218             }
1219
1220             // System.out.println("calleeLoc1=" + calleeLoc1);
1221             // System.out.println("calleeLoc2=" + calleeLoc2 +
1222             // "calleeParamList=" + calleeParamList);
1223
1224             int callerResult =
1225                 CompositeLattice.compare(callerLoc1, callerLoc2, true,
1226                     generateErrorMessage(md.getClassDesc(), min));
1227             // System.out.println("callerResult=" + callerResult);
1228             int calleeResult =
1229                 CompositeLattice.compare(calleeLoc1, calleeLoc2, true,
1230                     generateErrorMessage(md.getClassDesc(), min));
1231             // System.out.println("calleeResult=" + calleeResult);
1232
1233             if (callerResult == ComparisonResult.EQUAL) {
1234               if (ssjava.isSharedLocation(callerLoc1.get(callerLoc1.getSize() - 1))
1235                   && ssjava.isSharedLocation(callerLoc2.get(callerLoc2.getSize() - 1))) {
1236                 // if both of them are shared locations, promote them to
1237                 // "GREATER relation"
1238                 callerResult = ComparisonResult.GREATER;
1239               }
1240             }
1241
1242             if (calleeResult == ComparisonResult.GREATER
1243                 && callerResult != ComparisonResult.GREATER) {
1244               // If calleeLoc1 is higher than calleeLoc2
1245               // then, caller should have same ordering relation in-bet
1246               // callerLoc1 & callerLoc2
1247
1248               String paramName1, paramName2;
1249
1250               if (i == 0) {
1251                 paramName1 = "'THIS'";
1252               } else {
1253                 paramName1 = "'parameter " + calleemd.getParamName(i - 1) + "'";
1254               }
1255
1256               if (j == 0) {
1257                 paramName2 = "'THIS'";
1258               } else {
1259                 paramName2 = "'parameter " + calleemd.getParamName(j - 1) + "'";
1260               }
1261
1262               throw new Error(
1263                   "Caller doesn't respect an ordering relation among method arguments: callee expects that "
1264                       + paramName1 + " should be higher than " + paramName2 + " in " + calleemd
1265                       + " at " + md.getClassDesc().getSourceFileName() + ":" + min.getNumLine());
1266             }
1267           }
1268
1269         }
1270       }
1271
1272     }
1273
1274   }
1275
1276   private CompositeLocation checkLocationFromArrayAccessNode(MethodDescriptor md,
1277       SymbolTable nametable, ArrayAccessNode aan, CompositeLocation constraint, boolean isLHS) {
1278
1279     ClassDescriptor cd = md.getClassDesc();
1280
1281     CompositeLocation arrayLoc =
1282         checkLocationFromExpressionNode(md, nametable, aan.getExpression(),
1283             new CompositeLocation(), constraint, isLHS);
1284
1285     // addTypeLocation(aan.getExpression().getType(), arrayLoc);
1286     CompositeLocation indexLoc =
1287         checkLocationFromExpressionNode(md, nametable, aan.getIndex(), new CompositeLocation(),
1288             constraint, isLHS);
1289     // addTypeLocation(aan.getIndex().getType(), indexLoc);
1290
1291     if (isLHS) {
1292       if (!CompositeLattice.isGreaterThan(indexLoc, arrayLoc, generateErrorMessage(cd, aan))) {
1293         throw new Error("Array index value is not higher than array location at "
1294             + generateErrorMessage(cd, aan));
1295       }
1296       return arrayLoc;
1297     } else {
1298       Set<CompositeLocation> inputGLB = new HashSet<CompositeLocation>();
1299       inputGLB.add(arrayLoc);
1300       inputGLB.add(indexLoc);
1301       return CompositeLattice.calculateGLB(inputGLB, generateErrorMessage(cd, aan));
1302     }
1303
1304   }
1305
1306   private CompositeLocation checkLocationFromCreateObjectNode(MethodDescriptor md,
1307       SymbolTable nametable, CreateObjectNode con) {
1308
1309     ClassDescriptor cd = md.getClassDesc();
1310
1311     CompositeLocation compLoc = new CompositeLocation();
1312     compLoc.addLocation(Location.createTopLocation(md));
1313     return compLoc;
1314
1315   }
1316
1317   private CompositeLocation checkLocationFromOpNode(MethodDescriptor md, SymbolTable nametable,
1318       OpNode on, CompositeLocation constraint) {
1319
1320     ClassDescriptor cd = md.getClassDesc();
1321     CompositeLocation leftLoc = new CompositeLocation();
1322     leftLoc =
1323         checkLocationFromExpressionNode(md, nametable, on.getLeft(), leftLoc, constraint, false);
1324     // addTypeLocation(on.getLeft().getType(), leftLoc);
1325
1326     CompositeLocation rightLoc = new CompositeLocation();
1327     if (on.getRight() != null) {
1328       rightLoc =
1329           checkLocationFromExpressionNode(md, nametable, on.getRight(), rightLoc, constraint, false);
1330       // addTypeLocation(on.getRight().getType(), rightLoc);
1331     }
1332
1333     // System.out.println("\n# OP NODE=" + on.printNode(0));
1334     // System.out.println("# left loc=" + leftLoc + " from " +
1335     // on.getLeft().getClass());
1336     // if (on.getRight() != null) {
1337     // System.out.println("# right loc=" + rightLoc + " from " +
1338     // on.getRight().getClass());
1339     // }
1340
1341     Operation op = on.getOp();
1342
1343     switch (op.getOp()) {
1344
1345     case Operation.UNARYPLUS:
1346     case Operation.UNARYMINUS:
1347     case Operation.LOGIC_NOT:
1348       // single operand
1349       return leftLoc;
1350
1351     case Operation.LOGIC_OR:
1352     case Operation.LOGIC_AND:
1353     case Operation.COMP:
1354     case Operation.BIT_OR:
1355     case Operation.BIT_XOR:
1356     case Operation.BIT_AND:
1357     case Operation.ISAVAILABLE:
1358     case Operation.EQUAL:
1359     case Operation.NOTEQUAL:
1360     case Operation.LT:
1361     case Operation.GT:
1362     case Operation.LTE:
1363     case Operation.GTE:
1364     case Operation.ADD:
1365     case Operation.SUB:
1366     case Operation.MULT:
1367     case Operation.DIV:
1368     case Operation.MOD:
1369     case Operation.LEFTSHIFT:
1370     case Operation.RIGHTSHIFT:
1371     case Operation.URIGHTSHIFT:
1372
1373       Set<CompositeLocation> inputSet = new HashSet<CompositeLocation>();
1374       inputSet.add(leftLoc);
1375       inputSet.add(rightLoc);
1376       CompositeLocation glbCompLoc =
1377           CompositeLattice.calculateGLB(inputSet, generateErrorMessage(cd, on));
1378       return glbCompLoc;
1379
1380     default:
1381       throw new Error(op.toString());
1382     }
1383
1384   }
1385
1386   private CompositeLocation checkLocationFromLiteralNode(MethodDescriptor md,
1387       SymbolTable nametable, LiteralNode en, CompositeLocation loc) {
1388
1389     // literal value has the top location so that value can be flowed into any
1390     // location
1391     Location literalLoc = Location.createTopLocation(md);
1392     loc.addLocation(literalLoc);
1393     return loc;
1394
1395   }
1396
1397   private CompositeLocation checkLocationFromNameNode(MethodDescriptor md, SymbolTable nametable,
1398       NameNode nn, CompositeLocation loc, CompositeLocation constraint) {
1399
1400     NameDescriptor nd = nn.getName();
1401     if (nd.getBase() != null) {
1402       loc =
1403           checkLocationFromExpressionNode(md, nametable, nn.getExpression(), loc, constraint, false);
1404     } else {
1405       String varname = nd.toString();
1406       if (varname.equals("this")) {
1407         // 'this' itself!
1408         MethodLattice<String> methodLattice = ssjava.getMethodLattice(md);
1409         String thisLocId = methodLattice.getThisLoc();
1410         if (thisLocId == null) {
1411           throw new Error("The location for 'this' is not defined at "
1412               + md.getClassDesc().getSourceFileName() + "::" + nn.getNumLine());
1413         }
1414         Location locElement = new Location(md, thisLocId);
1415         loc.addLocation(locElement);
1416         return loc;
1417
1418       }
1419
1420       Descriptor d = (Descriptor) nametable.get(varname);
1421
1422       // CompositeLocation localLoc = null;
1423       if (d instanceof VarDescriptor) {
1424         VarDescriptor vd = (VarDescriptor) d;
1425         // localLoc = d2loc.get(vd);
1426         // the type of var descriptor has a composite location!
1427         loc = ((SSJavaType) vd.getType().getExtension()).getCompLoc().clone();
1428       } else if (d instanceof FieldDescriptor) {
1429         // the type of field descriptor has a location!
1430         FieldDescriptor fd = (FieldDescriptor) d;
1431         if (fd.isStatic()) {
1432           if (fd.isFinal()) {
1433             // if it is 'static final', the location has TOP since no one can
1434             // change its value
1435             loc.addLocation(Location.createTopLocation(md));
1436             return loc;
1437           } else {
1438             // if 'static', the location has pre-assigned global loc
1439             MethodLattice<String> localLattice = ssjava.getMethodLattice(md);
1440             String globalLocId = localLattice.getGlobalLoc();
1441             if (globalLocId == null) {
1442               throw new Error("Global location element is not defined in the method " + md);
1443             }
1444             Location globalLoc = new Location(md, globalLocId);
1445
1446             loc.addLocation(globalLoc);
1447           }
1448         } else {
1449           // the location of field access starts from this, followed by field
1450           // location
1451           MethodLattice<String> localLattice = ssjava.getMethodLattice(md);
1452           Location thisLoc = new Location(md, localLattice.getThisLoc());
1453           loc.addLocation(thisLoc);
1454         }
1455
1456         Location fieldLoc = (Location) fd.getType().getExtension();
1457         loc.addLocation(fieldLoc);
1458       } else if (d == null) {
1459         // access static field
1460         FieldDescriptor fd = nn.getField();
1461
1462         MethodLattice<String> localLattice = ssjava.getMethodLattice(md);
1463         String globalLocId = localLattice.getGlobalLoc();
1464         if (globalLocId == null) {
1465           throw new Error("Method lattice does not define global variable location at "
1466               + generateErrorMessage(md.getClassDesc(), nn));
1467         }
1468         loc.addLocation(new Location(md, globalLocId));
1469
1470         Location fieldLoc = (Location) fd.getType().getExtension();
1471         loc.addLocation(fieldLoc);
1472
1473         return loc;
1474
1475       }
1476     }
1477     return loc;
1478   }
1479
1480   private CompositeLocation checkLocationFromFieldAccessNode(MethodDescriptor md,
1481       SymbolTable nametable, FieldAccessNode fan, CompositeLocation loc,
1482       CompositeLocation constraint) {
1483
1484     ExpressionNode left = fan.getExpression();
1485     TypeDescriptor ltd = left.getType();
1486
1487     FieldDescriptor fd = fan.getField();
1488
1489     String varName = null;
1490     if (left.kind() == Kind.NameNode) {
1491       NameDescriptor nd = ((NameNode) left).getName();
1492       varName = nd.toString();
1493     }
1494
1495     if (ltd.isClassNameRef() || (varName != null && varName.equals("this"))) {
1496       // using a class name directly or access using this
1497       if (fd.isStatic() && fd.isFinal()) {
1498         loc.addLocation(Location.createTopLocation(md));
1499         return loc;
1500       }
1501     }
1502
1503     Set<CompositeLocation> inputGLB = new HashSet<CompositeLocation>();
1504     if (left instanceof ArrayAccessNode) {
1505       ArrayAccessNode aan = (ArrayAccessNode) left;
1506       CompositeLocation indexLoc =
1507           checkLocationFromExpressionNode(md, nametable, aan.getIndex(), loc, constraint, false);
1508       inputGLB.add(indexLoc);
1509     }
1510
1511     loc = checkLocationFromExpressionNode(md, nametable, left, loc, constraint, false);
1512
1513     if (!left.getType().isPrimitive()) {
1514
1515       if (!fd.getSymbol().equals("length")) {
1516         // array.length access, return the location of the array
1517         Location fieldLoc = getFieldLocation(fd);
1518         loc.addLocation(fieldLoc);
1519       }
1520
1521     }
1522
1523     inputGLB.add(loc);
1524     loc = CompositeLattice.calculateGLB(inputGLB, generateErrorMessage(md.getClassDesc(), fan));
1525     return loc;
1526   }
1527
1528   private Location getFieldLocation(FieldDescriptor fd) {
1529
1530     // System.out.println("### getFieldLocation=" + fd);
1531     // System.out.println("### fd.getType().getExtension()=" +
1532     // fd.getType().getExtension());
1533
1534     Location fieldLoc = (Location) fd.getType().getExtension();
1535
1536     // handle the case that method annotation checking skips checking field
1537     // declaration
1538     if (fieldLoc == null) {
1539       fieldLoc = checkFieldDeclaration(fd.getClassDescriptor(), fd);
1540     }
1541
1542     return fieldLoc;
1543
1544   }
1545
1546   private FieldDescriptor getFieldDescriptorFromExpressionNode(ExpressionNode en) {
1547
1548     if (en.kind() == Kind.NameNode) {
1549       NameNode nn = (NameNode) en;
1550       if (nn.getField() != null) {
1551         return nn.getField();
1552       }
1553
1554       if (nn.getName() != null && nn.getName().getBase() != null) {
1555         return getFieldDescriptorFromExpressionNode(nn.getExpression());
1556       }
1557
1558     } else if (en.kind() == Kind.FieldAccessNode) {
1559       FieldAccessNode fan = (FieldAccessNode) en;
1560       return fan.getField();
1561     }
1562
1563     return null;
1564   }
1565
1566   private CompositeLocation checkLocationFromAssignmentNode(MethodDescriptor md,
1567       SymbolTable nametable, AssignmentNode an, CompositeLocation loc, CompositeLocation constraint) {
1568
1569     ClassDescriptor cd = md.getClassDesc();
1570
1571     Set<CompositeLocation> inputGLBSet = new HashSet<CompositeLocation>();
1572
1573     boolean postinc = true;
1574     if (an.getOperation().getBaseOp() == null
1575         || (an.getOperation().getBaseOp().getOp() != Operation.POSTINC && an.getOperation()
1576             .getBaseOp().getOp() != Operation.POSTDEC))
1577       postinc = false;
1578
1579     // if LHS is array access node, need to check if array index is higher
1580     // than array itself
1581     CompositeLocation destLocation =
1582         checkLocationFromExpressionNode(md, nametable, an.getDest(), new CompositeLocation(),
1583             constraint, true);
1584
1585     CompositeLocation rhsLocation;
1586     CompositeLocation srcLocation;
1587
1588     if (!postinc) {
1589
1590       checkOwnership(md, an, an.getSrc());
1591
1592       rhsLocation =
1593           checkLocationFromExpressionNode(md, nametable, an.getSrc(), new CompositeLocation(),
1594               constraint, false);
1595
1596       if (an.getOperation().getOp() >= 2 && an.getOperation().getOp() <= 12) {
1597         // if assignment contains OP+EQ operator, need to merge location types
1598         // of LHS & RHS into the RHS
1599         Set<CompositeLocation> srcGLBSet = new HashSet<CompositeLocation>();
1600         srcGLBSet.add(rhsLocation);
1601         srcGLBSet.add(destLocation);
1602         srcLocation = CompositeLattice.calculateGLB(srcGLBSet, generateErrorMessage(cd, an));
1603       } else {
1604         srcLocation = rhsLocation;
1605       }
1606
1607       if (constraint != null) {
1608         inputGLBSet.add(srcLocation);
1609         inputGLBSet.add(constraint);
1610         srcLocation = CompositeLattice.calculateGLB(inputGLBSet, generateErrorMessage(cd, an));
1611       }
1612
1613       if (!CompositeLattice.isGreaterThan(srcLocation, destLocation, generateErrorMessage(cd, an))) {
1614
1615         String context = "";
1616         if (constraint != null) {
1617           context = " and the current context constraint is " + constraint;
1618         }
1619
1620         throw new Error("The value flow from " + srcLocation + " to " + destLocation
1621             + " does not respect location hierarchy on the assignment " + an.printNode(0) + context
1622             + " at " + cd.getSourceFileName() + "::" + an.getNumLine());
1623       }
1624
1625       if (srcLocation.equals(destLocation)) {
1626         // keep it for definitely written analysis
1627         Set<FlatNode> flatNodeSet = ssjava.getBuildFlat().getFlatNodeSet(an);
1628         for (Iterator iterator = flatNodeSet.iterator(); iterator.hasNext();) {
1629           FlatNode fn = (FlatNode) iterator.next();
1630           ssjava.addSameHeightWriteFlatNode(fn);
1631         }
1632
1633       }
1634
1635     } else {
1636       destLocation =
1637           rhsLocation =
1638               checkLocationFromExpressionNode(md, nametable, an.getDest(), new CompositeLocation(),
1639                   constraint, false);
1640
1641       if (constraint != null) {
1642         inputGLBSet.add(rhsLocation);
1643         inputGLBSet.add(constraint);
1644         srcLocation = CompositeLattice.calculateGLB(inputGLBSet, generateErrorMessage(cd, an));
1645       } else {
1646         srcLocation = rhsLocation;
1647       }
1648
1649       if (!CompositeLattice.isGreaterThan(srcLocation, destLocation, generateErrorMessage(cd, an))) {
1650
1651         if (srcLocation.equals(destLocation)) {
1652           throw new Error("Location " + srcLocation
1653               + " is not allowed to have the value flow that moves within the same location at '"
1654               + an.printNode(0) + "' of " + cd.getSourceFileName() + "::" + an.getNumLine());
1655         } else {
1656           throw new Error("The value flow from " + srcLocation + " to " + destLocation
1657               + " does not respect location hierarchy on the assignment " + an.printNode(0)
1658               + " at " + cd.getSourceFileName() + "::" + an.getNumLine());
1659         }
1660
1661       }
1662
1663       if (srcLocation.equals(destLocation)) {
1664         // keep it for definitely written analysis
1665         Set<FlatNode> flatNodeSet = ssjava.getBuildFlat().getFlatNodeSet(an);
1666         for (Iterator iterator = flatNodeSet.iterator(); iterator.hasNext();) {
1667           FlatNode fn = (FlatNode) iterator.next();
1668           ssjava.addSameHeightWriteFlatNode(fn);
1669         }
1670       }
1671
1672     }
1673
1674     return destLocation;
1675   }
1676
1677   private void assignLocationOfVarDescriptor(VarDescriptor vd, MethodDescriptor md,
1678       SymbolTable nametable, TreeNode n) {
1679
1680     ClassDescriptor cd = md.getClassDesc();
1681     Vector<AnnotationDescriptor> annotationVec = vd.getType().getAnnotationMarkers();
1682
1683     // currently enforce every variable to have corresponding location
1684     if (annotationVec.size() == 0) {
1685       throw new Error("Location is not assigned to variable '" + vd.getSymbol()
1686           + "' in the method '" + md + "' of the class " + cd.getSymbol() + " at "
1687           + generateErrorMessage(cd, n));
1688     }
1689
1690     int locDecCount = 0;
1691     for (int i = 0; i < annotationVec.size(); i++) {
1692       AnnotationDescriptor ad = annotationVec.elementAt(i);
1693
1694       if (ad.getType() == AnnotationDescriptor.SINGLE_ANNOTATION) {
1695
1696         if (ad.getMarker().equals(SSJavaAnalysis.LOC)) {
1697           locDecCount++;
1698           if (locDecCount > 1) {// variable can have at most one location
1699             throw new Error(vd.getSymbol() + " has more than one location declaration.");
1700           }
1701           String locDec = ad.getValue(); // check if location is defined
1702
1703           if (locDec.startsWith(SSJavaAnalysis.DELTA)) {
1704             DeltaLocation deltaLoc = parseDeltaDeclaration(md, n, locDec);
1705             d2loc.put(vd, deltaLoc);
1706             addLocationType(vd.getType(), deltaLoc);
1707           } else {
1708             CompositeLocation compLoc = parseLocationDeclaration(md, n, locDec);
1709
1710             Location lastElement = compLoc.get(compLoc.getSize() - 1);
1711             if (ssjava.isSharedLocation(lastElement)) {
1712               ssjava.mapSharedLocation2Descriptor(lastElement, vd);
1713             }
1714
1715             d2loc.put(vd, compLoc);
1716             addLocationType(vd.getType(), compLoc);
1717           }
1718
1719         }
1720       }
1721     }
1722
1723   }
1724
1725   private DeltaLocation parseDeltaDeclaration(MethodDescriptor md, TreeNode n, String locDec) {
1726
1727     int deltaCount = 0;
1728     int dIdx = locDec.indexOf(SSJavaAnalysis.DELTA);
1729     while (dIdx >= 0) {
1730       deltaCount++;
1731       int beginIdx = dIdx + 6;
1732       locDec = locDec.substring(beginIdx, locDec.length() - 1);
1733       dIdx = locDec.indexOf(SSJavaAnalysis.DELTA);
1734     }
1735
1736     CompositeLocation compLoc = parseLocationDeclaration(md, n, locDec);
1737     DeltaLocation deltaLoc = new DeltaLocation(compLoc, deltaCount);
1738
1739     return deltaLoc;
1740   }
1741
1742   private Location parseFieldLocDeclaraton(String decl, String msg) throws Exception {
1743
1744     int idx = decl.indexOf(".");
1745
1746     String className = decl.substring(0, idx);
1747     String fieldName = decl.substring(idx + 1);
1748
1749     className.replaceAll(" ", "");
1750     fieldName.replaceAll(" ", "");
1751
1752     Descriptor d = state.getClassSymbolTable().get(className);
1753
1754     if (d == null) {
1755       // System.out.println("state.getClassSymbolTable()=" +
1756       // state.getClassSymbolTable());
1757       throw new Error("The class in the location declaration '" + decl + "' does not exist at "
1758           + msg);
1759     }
1760
1761     assert (d instanceof ClassDescriptor);
1762     SSJavaLattice<String> lattice = ssjava.getClassLattice((ClassDescriptor) d);
1763     if (!lattice.containsKey(fieldName)) {
1764       throw new Error("The location " + fieldName + " is not defined in the field lattice of '"
1765           + className + "' at " + msg);
1766     }
1767
1768     return new Location(d, fieldName);
1769   }
1770
1771   private CompositeLocation parseLocationDeclaration(MethodDescriptor md, TreeNode n, String locDec) {
1772
1773     CompositeLocation compLoc = new CompositeLocation();
1774
1775     StringTokenizer tokenizer = new StringTokenizer(locDec, ",");
1776     List<String> locIdList = new ArrayList<String>();
1777     while (tokenizer.hasMoreTokens()) {
1778       String locId = tokenizer.nextToken();
1779       locIdList.add(locId);
1780     }
1781
1782     // at least,one location element needs to be here!
1783     assert (locIdList.size() > 0);
1784
1785     // assume that loc with idx 0 comes from the local lattice
1786     // loc with idx 1 comes from the field lattice
1787
1788     String localLocId = locIdList.get(0);
1789     SSJavaLattice<String> localLattice = CompositeLattice.getLatticeByDescriptor(md);
1790     Location localLoc = new Location(md, localLocId);
1791     if (localLattice == null || (!localLattice.containsKey(localLocId))) {
1792       throw new Error("Location " + localLocId
1793           + " is not defined in the local variable lattice at "
1794           + md.getClassDesc().getSourceFileName() + "::" + (n != null ? n.getNumLine() : md) + ".");
1795     }
1796     compLoc.addLocation(localLoc);
1797
1798     for (int i = 1; i < locIdList.size(); i++) {
1799       String locName = locIdList.get(i);
1800       try {
1801         Location fieldLoc =
1802             parseFieldLocDeclaraton(locName, generateErrorMessage(md.getClassDesc(), n));
1803         compLoc.addLocation(fieldLoc);
1804       } catch (Exception e) {
1805         throw new Error("The location declaration '" + locName + "' is wrong  at "
1806             + generateErrorMessage(md.getClassDesc(), n));
1807       }
1808     }
1809
1810     return compLoc;
1811
1812   }
1813
1814   private void checkDeclarationNode(MethodDescriptor md, SymbolTable nametable, DeclarationNode dn) {
1815     VarDescriptor vd = dn.getVarDescriptor();
1816     assignLocationOfVarDescriptor(vd, md, nametable, dn);
1817   }
1818
1819   private void checkDeclarationInClass(ClassDescriptor cd) {
1820     // Check to see that fields are okay
1821     for (Iterator field_it = cd.getFields(); field_it.hasNext();) {
1822       FieldDescriptor fd = (FieldDescriptor) field_it.next();
1823
1824       if (!(fd.isFinal() && fd.isStatic())) {
1825         checkFieldDeclaration(cd, fd);
1826       } else {
1827         // for static final, assign top location by default
1828         Location loc = Location.createTopLocation(cd);
1829         addLocationType(fd.getType(), loc);
1830       }
1831     }
1832   }
1833
1834   private Location checkFieldDeclaration(ClassDescriptor cd, FieldDescriptor fd) {
1835
1836     Vector<AnnotationDescriptor> annotationVec = fd.getType().getAnnotationMarkers();
1837
1838     // currently enforce every field to have corresponding location
1839     if (annotationVec.size() == 0) {
1840       throw new Error("Location is not assigned to the field '" + fd.getSymbol()
1841           + "' of the class " + cd.getSymbol() + " at " + cd.getSourceFileName());
1842     }
1843
1844     if (annotationVec.size() > 1) {
1845       // variable can have at most one location
1846       throw new Error("Field " + fd.getSymbol() + " of class " + cd
1847           + " has more than one location.");
1848     }
1849
1850     AnnotationDescriptor ad = annotationVec.elementAt(0);
1851     Location loc = null;
1852
1853     if (ad.getType() == AnnotationDescriptor.SINGLE_ANNOTATION) {
1854       if (ad.getMarker().equals(SSJavaAnalysis.LOC)) {
1855         String locationID = ad.getValue();
1856         // check if location is defined
1857         SSJavaLattice<String> lattice = ssjava.getClassLattice(cd);
1858         if (lattice == null || (!lattice.containsKey(locationID))) {
1859           throw new Error("Location " + locationID
1860               + " is not defined in the field lattice of class " + cd.getSymbol() + " at"
1861               + cd.getSourceFileName() + ".");
1862         }
1863         loc = new Location(cd, locationID);
1864
1865         if (ssjava.isSharedLocation(loc)) {
1866           ssjava.mapSharedLocation2Descriptor(loc, fd);
1867         }
1868
1869         addLocationType(fd.getType(), loc);
1870
1871       }
1872     }
1873
1874     return loc;
1875   }
1876
1877   private void addLocationType(TypeDescriptor type, CompositeLocation loc) {
1878     if (type != null) {
1879       TypeExtension te = type.getExtension();
1880       SSJavaType ssType;
1881       if (te != null) {
1882         ssType = (SSJavaType) te;
1883         ssType.setCompLoc(loc);
1884       } else {
1885         ssType = new SSJavaType(loc);
1886         type.setExtension(ssType);
1887       }
1888     }
1889   }
1890
1891   private void addLocationType(TypeDescriptor type, Location loc) {
1892     if (type != null) {
1893       type.setExtension(loc);
1894     }
1895   }
1896
1897   static class CompositeLattice {
1898
1899     public static boolean isGreaterThan(CompositeLocation loc1, CompositeLocation loc2, String msg) {
1900
1901       // System.out.println("\nisGreaterThan=" + loc1 + " " + loc2 + " msg=" +
1902       // msg);
1903       int baseCompareResult = compareBaseLocationSet(loc1, loc2, true, false, msg);
1904       if (baseCompareResult == ComparisonResult.EQUAL) {
1905         if (compareDelta(loc1, loc2) == ComparisonResult.GREATER) {
1906           return true;
1907         } else {
1908           return false;
1909         }
1910       } else if (baseCompareResult == ComparisonResult.GREATER) {
1911         return true;
1912       } else {
1913         return false;
1914       }
1915
1916     }
1917
1918     public static int compare(CompositeLocation loc1, CompositeLocation loc2, boolean ignore,
1919         String msg) {
1920
1921       // System.out.println("compare=" + loc1 + " " + loc2);
1922       int baseCompareResult = compareBaseLocationSet(loc1, loc2, false, ignore, msg);
1923
1924       if (baseCompareResult == ComparisonResult.EQUAL) {
1925         return compareDelta(loc1, loc2);
1926       } else {
1927         return baseCompareResult;
1928       }
1929
1930     }
1931
1932     private static int compareDelta(CompositeLocation dLoc1, CompositeLocation dLoc2) {
1933
1934       int deltaCount1 = 0;
1935       int deltaCount2 = 0;
1936       if (dLoc1 instanceof DeltaLocation) {
1937         deltaCount1 = ((DeltaLocation) dLoc1).getNumDelta();
1938       }
1939
1940       if (dLoc2 instanceof DeltaLocation) {
1941         deltaCount2 = ((DeltaLocation) dLoc2).getNumDelta();
1942       }
1943       if (deltaCount1 < deltaCount2) {
1944         return ComparisonResult.GREATER;
1945       } else if (deltaCount1 == deltaCount2) {
1946         return ComparisonResult.EQUAL;
1947       } else {
1948         return ComparisonResult.LESS;
1949       }
1950
1951     }
1952
1953     private static int compareBaseLocationSet(CompositeLocation compLoc1,
1954         CompositeLocation compLoc2, boolean awareSharedLoc, boolean ignore, String msg) {
1955
1956       // if compLoc1 is greater than compLoc2, return true
1957       // else return false;
1958
1959       // compare one by one in according to the order of the tuple
1960       int numOfTie = 0;
1961       for (int i = 0; i < compLoc1.getSize(); i++) {
1962         Location loc1 = compLoc1.get(i);
1963         if (i >= compLoc2.getSize()) {
1964           if (ignore) {
1965             return ComparisonResult.INCOMPARABLE;
1966           } else {
1967             throw new Error("Failed to compare two locations of " + compLoc1 + " and " + compLoc2
1968                 + " because they are not comparable at " + msg);
1969           }
1970         }
1971         Location loc2 = compLoc2.get(i);
1972
1973         Descriptor descriptor = getCommonParentDescriptor(loc1, loc2, msg);
1974         SSJavaLattice<String> lattice = getLatticeByDescriptor(descriptor);
1975
1976         // check if the shared location is appeared only at the end of the
1977         // composite location
1978         if (lattice.getSharedLocSet().contains(loc1.getLocIdentifier())) {
1979           if (i != (compLoc1.getSize() - 1)) {
1980             throw new Error("The shared location " + loc1.getLocIdentifier()
1981                 + " cannot be appeared in the middle of composite location at" + msg);
1982           }
1983         }
1984
1985         if (lattice.getSharedLocSet().contains(loc2.getLocIdentifier())) {
1986           if (i != (compLoc2.getSize() - 1)) {
1987             throw new Error("The shared location " + loc2.getLocIdentifier()
1988                 + " cannot be appeared in the middle of composite location at " + msg);
1989           }
1990         }
1991
1992         // if (!lattice1.equals(lattice2)) {
1993         // throw new Error("Failed to compare two locations of " + compLoc1 +
1994         // " and " + compLoc2
1995         // + " because they are not comparable at " + msg);
1996         // }
1997
1998         if (loc1.getLocIdentifier().equals(loc2.getLocIdentifier())) {
1999           numOfTie++;
2000           // check if the current location is the spinning location
2001           // note that the spinning location only can be appeared in the last
2002           // part of the composite location
2003           if (awareSharedLoc && numOfTie == compLoc1.getSize()
2004               && lattice.getSharedLocSet().contains(loc1.getLocIdentifier())) {
2005             return ComparisonResult.GREATER;
2006           }
2007           continue;
2008         } else if (lattice.isGreaterThan(loc1.getLocIdentifier(), loc2.getLocIdentifier())) {
2009           return ComparisonResult.GREATER;
2010         } else {
2011           return ComparisonResult.LESS;
2012         }
2013
2014       }
2015
2016       if (numOfTie == compLoc1.getSize()) {
2017
2018         if (numOfTie != compLoc2.getSize()) {
2019
2020           if (ignore) {
2021             return ComparisonResult.INCOMPARABLE;
2022           } else {
2023             throw new Error("Failed to compare two locations of " + compLoc1 + " and " + compLoc2
2024                 + " because they are not comparable at " + msg);
2025           }
2026
2027         }
2028
2029         return ComparisonResult.EQUAL;
2030       }
2031
2032       return ComparisonResult.LESS;
2033
2034     }
2035
2036     public static CompositeLocation calculateGLB(Set<CompositeLocation> inputSet, String errMsg) {
2037
2038       // System.out.println("Calculating GLB=" + inputSet);
2039       CompositeLocation glbCompLoc = new CompositeLocation();
2040
2041       // calculate GLB of the first(priority) element
2042       Set<String> priorityLocIdentifierSet = new HashSet<String>();
2043       Descriptor priorityDescriptor = null;
2044
2045       Hashtable<String, Set<CompositeLocation>> locId2CompLocSet =
2046           new Hashtable<String, Set<CompositeLocation>>();
2047       // mapping from the priority loc ID to its full representation by the
2048       // composite location
2049
2050       int maxTupleSize = 0;
2051       CompositeLocation maxCompLoc = null;
2052
2053       Location prevPriorityLoc = null;
2054       for (Iterator iterator = inputSet.iterator(); iterator.hasNext();) {
2055         CompositeLocation compLoc = (CompositeLocation) iterator.next();
2056         if (compLoc.getSize() > maxTupleSize) {
2057           maxTupleSize = compLoc.getSize();
2058           maxCompLoc = compLoc;
2059         }
2060         Location priorityLoc = compLoc.get(0);
2061         String priorityLocId = priorityLoc.getLocIdentifier();
2062         priorityLocIdentifierSet.add(priorityLocId);
2063
2064         if (locId2CompLocSet.containsKey(priorityLocId)) {
2065           locId2CompLocSet.get(priorityLocId).add(compLoc);
2066         } else {
2067           Set<CompositeLocation> newSet = new HashSet<CompositeLocation>();
2068           newSet.add(compLoc);
2069           locId2CompLocSet.put(priorityLocId, newSet);
2070         }
2071
2072         // check if priority location are coming from the same lattice
2073         if (priorityDescriptor == null) {
2074           priorityDescriptor = priorityLoc.getDescriptor();
2075         } else {
2076           priorityDescriptor = getCommonParentDescriptor(priorityLoc, prevPriorityLoc, errMsg);
2077         }
2078         prevPriorityLoc = priorityLoc;
2079         // else if (!priorityDescriptor.equals(priorityLoc.getDescriptor())) {
2080         // throw new Error("Failed to calculate GLB of " + inputSet
2081         // + " because they are from different lattices.");
2082         // }
2083       }
2084
2085       SSJavaLattice<String> locOrder = getLatticeByDescriptor(priorityDescriptor);
2086       String glbOfPriorityLoc = locOrder.getGLB(priorityLocIdentifierSet);
2087
2088       glbCompLoc.addLocation(new Location(priorityDescriptor, glbOfPriorityLoc));
2089       Set<CompositeLocation> compSet = locId2CompLocSet.get(glbOfPriorityLoc);
2090
2091       if (compSet == null) {
2092         // when GLB(x1,x2)!=x1 and !=x2 : GLB case 4
2093         // mean that the result is already lower than <x1,y1> and <x2,y2>
2094         // assign TOP to the rest of the location elements
2095
2096         // in this case, do not take care about delta
2097         // CompositeLocation inputComp = inputSet.iterator().next();
2098         for (int i = 1; i < maxTupleSize; i++) {
2099           glbCompLoc.addLocation(Location.createTopLocation(maxCompLoc.get(i).getDescriptor()));
2100         }
2101       } else {
2102
2103         // here find out composite location that has a maximum length tuple
2104         // if we have three input set: [A], [A,B], [A,B,C]
2105         // maximum length tuple will be [A,B,C]
2106         int max = 0;
2107         CompositeLocation maxFromCompSet = null;
2108         for (Iterator iterator = compSet.iterator(); iterator.hasNext();) {
2109           CompositeLocation c = (CompositeLocation) iterator.next();
2110           if (c.getSize() > max) {
2111             max = c.getSize();
2112             maxFromCompSet = c;
2113           }
2114         }
2115
2116         if (compSet.size() == 1) {
2117           // if GLB(x1,x2)==x1 or x2 : GLB case 2,3
2118           CompositeLocation comp = compSet.iterator().next();
2119           for (int i = 1; i < comp.getSize(); i++) {
2120             glbCompLoc.addLocation(comp.get(i));
2121           }
2122
2123           // if input location corresponding to glb is a delta, need to apply
2124           // delta to glb result
2125           if (comp instanceof DeltaLocation) {
2126             glbCompLoc = new DeltaLocation(glbCompLoc, 1);
2127           }
2128
2129         } else {
2130           // when GLB(x1,x2)==x1 and x2 : GLB case 1
2131           // if more than one location shares the same priority GLB
2132           // need to calculate the rest of GLB loc
2133
2134           // setup input set starting from the second tuple item
2135           Set<CompositeLocation> innerGLBInput = new HashSet<CompositeLocation>();
2136           for (Iterator iterator = compSet.iterator(); iterator.hasNext();) {
2137             CompositeLocation compLoc = (CompositeLocation) iterator.next();
2138             CompositeLocation innerCompLoc = new CompositeLocation();
2139             for (int idx = 1; idx < compLoc.getSize(); idx++) {
2140               innerCompLoc.addLocation(compLoc.get(idx));
2141             }
2142             if (innerCompLoc.getSize() > 0) {
2143               innerGLBInput.add(innerCompLoc);
2144             }
2145           }
2146
2147           if (innerGLBInput.size() > 0) {
2148             CompositeLocation innerGLB = CompositeLattice.calculateGLB(innerGLBInput, errMsg);
2149             for (int idx = 0; idx < innerGLB.getSize(); idx++) {
2150               glbCompLoc.addLocation(innerGLB.get(idx));
2151             }
2152           }
2153
2154           // if input location corresponding to glb is a delta, need to apply
2155           // delta to glb result
2156
2157           for (Iterator iterator = compSet.iterator(); iterator.hasNext();) {
2158             CompositeLocation compLoc = (CompositeLocation) iterator.next();
2159             if (compLoc instanceof DeltaLocation) {
2160               if (glbCompLoc.equals(compLoc)) {
2161                 glbCompLoc = new DeltaLocation(glbCompLoc, 1);
2162                 break;
2163               }
2164             }
2165           }
2166
2167         }
2168       }
2169
2170       // System.out.println("GLB=" + glbCompLoc);
2171       return glbCompLoc;
2172
2173     }
2174
2175     static SSJavaLattice<String> getLatticeByDescriptor(Descriptor d) {
2176
2177       SSJavaLattice<String> lattice = null;
2178
2179       if (d instanceof ClassDescriptor) {
2180         lattice = ssjava.getCd2lattice().get(d);
2181       } else if (d instanceof MethodDescriptor) {
2182         if (ssjava.getMd2lattice().containsKey(d)) {
2183           lattice = ssjava.getMd2lattice().get(d);
2184         } else {
2185           // use default lattice for the method
2186           lattice = ssjava.getCd2methodDefault().get(((MethodDescriptor) d).getClassDesc());
2187         }
2188       }
2189
2190       return lattice;
2191     }
2192
2193     static Descriptor getCommonParentDescriptor(Location loc1, Location loc2, String msg) {
2194
2195       Descriptor d1 = loc1.getDescriptor();
2196       Descriptor d2 = loc2.getDescriptor();
2197
2198       Descriptor descriptor;
2199
2200       if (d1 instanceof ClassDescriptor && d2 instanceof ClassDescriptor) {
2201
2202         if (d1.equals(d2)) {
2203           descriptor = d1;
2204         } else {
2205           // identifying which one is parent class
2206           Set<Descriptor> d1SubClassesSet = ssjava.tu.getSubClasses((ClassDescriptor) d1);
2207           Set<Descriptor> d2SubClassesSet = ssjava.tu.getSubClasses((ClassDescriptor) d2);
2208
2209           if (d1 == null && d2 == null) {
2210             throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
2211                 + " because they are not comparable at " + msg);
2212           } else if (d1SubClassesSet != null && d1SubClassesSet.contains(d2)) {
2213             descriptor = d1;
2214           } else if (d2SubClassesSet != null && d2SubClassesSet.contains(d1)) {
2215             descriptor = d2;
2216           } else {
2217             throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
2218                 + " because they are not comparable at " + msg);
2219           }
2220         }
2221
2222       } else if (d1 instanceof MethodDescriptor && d2 instanceof MethodDescriptor) {
2223
2224         if (d1.equals(d2)) {
2225           descriptor = d1;
2226         } else {
2227
2228           // identifying which one is parent class
2229           MethodDescriptor md1 = (MethodDescriptor) d1;
2230           MethodDescriptor md2 = (MethodDescriptor) d2;
2231
2232           if (!md1.matches(md2)) {
2233             throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
2234                 + " because they are not comparable at " + msg);
2235           }
2236
2237           Set<Descriptor> d1SubClassesSet =
2238               ssjava.tu.getSubClasses(((MethodDescriptor) d1).getClassDesc());
2239           Set<Descriptor> d2SubClassesSet =
2240               ssjava.tu.getSubClasses(((MethodDescriptor) d2).getClassDesc());
2241
2242           if (d1 == null && d2 == null) {
2243             throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
2244                 + " because they are not comparable at " + msg);
2245           } else if (d1 != null && d1SubClassesSet.contains(d2)) {
2246             descriptor = d1;
2247           } else if (d2 != null && d2SubClassesSet.contains(d1)) {
2248             descriptor = d2;
2249           } else {
2250             throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
2251                 + " because they are not comparable at " + msg);
2252           }
2253         }
2254
2255       } else {
2256         throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
2257             + " because they are not comparable at " + msg);
2258       }
2259
2260       return descriptor;
2261
2262     }
2263
2264   }
2265
2266   class ComparisonResult {
2267
2268     public static final int GREATER = 0;
2269     public static final int EQUAL = 1;
2270     public static final int LESS = 2;
2271     public static final int INCOMPARABLE = 3;
2272     int result;
2273
2274   }
2275
2276 }
2277
2278 class ReturnLocGenerator {
2279
2280   public static final int PARAMISHIGHER = 0;
2281   public static final int PARAMISSAME = 1;
2282   public static final int IGNORE = 2;
2283
2284   private Hashtable<Integer, Integer> paramIdx2paramType;
2285
2286   private CompositeLocation declaredReturnLoc = null;
2287
2288   public ReturnLocGenerator(CompositeLocation returnLoc, MethodDescriptor md,
2289       List<CompositeLocation> params, String msg) {
2290
2291     CompositeLocation thisLoc = params.get(0);
2292     if (returnLoc.get(0).equals(thisLoc.get(0)) && returnLoc.getSize() > 1) {
2293       // if the declared return location consists of THIS and field location,
2294       // return location for the caller's side has to have same field element
2295       this.declaredReturnLoc = returnLoc;
2296     } else {
2297       // creating mappings
2298       paramIdx2paramType = new Hashtable<Integer, Integer>();
2299       for (int i = 0; i < params.size(); i++) {
2300         CompositeLocation param = params.get(i);
2301         int compareResult = CompositeLattice.compare(param, returnLoc, true, msg);
2302
2303         int type;
2304         if (compareResult == ComparisonResult.GREATER) {
2305           type = 0;
2306         } else if (compareResult == ComparisonResult.EQUAL) {
2307           type = 1;
2308         } else {
2309           type = 2;
2310         }
2311         paramIdx2paramType.put(new Integer(i), new Integer(type));
2312       }
2313     }
2314
2315   }
2316
2317   public CompositeLocation computeReturnLocation(List<CompositeLocation> args) {
2318
2319     if (declaredReturnLoc != null) {
2320       // when developer specify that the return value is [THIS,field]
2321       // needs to translate to the caller's location
2322       CompositeLocation callerLoc = new CompositeLocation();
2323       CompositeLocation callerBaseLocation = args.get(0);
2324
2325       for (int i = 0; i < callerBaseLocation.getSize(); i++) {
2326         callerLoc.addLocation(callerBaseLocation.get(i));
2327       }
2328       for (int i = 1; i < declaredReturnLoc.getSize(); i++) {
2329         callerLoc.addLocation(declaredReturnLoc.get(i));
2330       }
2331       return callerLoc;
2332     } else {
2333       // compute the highest possible location in caller's side
2334       assert paramIdx2paramType.keySet().size() == args.size();
2335
2336       Set<CompositeLocation> inputGLB = new HashSet<CompositeLocation>();
2337       for (int i = 0; i < args.size(); i++) {
2338         int type = (paramIdx2paramType.get(new Integer(i))).intValue();
2339         CompositeLocation argLoc = args.get(i);
2340         if (type == PARAMISHIGHER || type == PARAMISSAME) {
2341           // return loc is equal to or lower than param
2342           inputGLB.add(argLoc);
2343         }
2344       }
2345
2346       // compute GLB of arguments subset that are same or higher than return
2347       // location
2348       if (inputGLB.isEmpty()) {
2349         CompositeLocation rtr =
2350             new CompositeLocation(Location.createTopLocation(args.get(0).get(0).getDescriptor()));
2351         return rtr;
2352       } else {
2353         CompositeLocation glb = CompositeLattice.calculateGLB(inputGLB, "");
2354         return glb;
2355       }
2356     }
2357
2358   }
2359 }