825a7479383e19c9ebe455b07fd238c7277a0f58
[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() && !ssjava.getMethodContainingSSJavaLoop().equals(md)) {
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() && !ssjava.getMethodContainingSSJavaLoop().equals(md)) {
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 declaredReturnLoc = md2ReturnLoc.get(md);
551
552     CompositeLocation returnValueLoc;
553     if (returnExp != null) {
554       returnValueLoc =
555           checkLocationFromExpressionNode(md, nametable, returnExp, new CompositeLocation(),
556               constraint, false);
557
558       // System.out.println("# RETURN VALUE LOC=" + returnValueLoc +
559       // " with constraint=" + constraint);
560
561       // TODO: do we need to check here?
562       // if this return statement is inside branch, return value has an implicit
563       // flow from conditional location
564       // if (constraint != null) {
565       // Set<CompositeLocation> inputGLB = new HashSet<CompositeLocation>();
566       // inputGLB.add(returnValueLoc);
567       // inputGLB.add(constraint);
568       // returnValueLoc =
569       // CompositeLattice.calculateGLB(inputGLB,
570       // generateErrorMessage(md.getClassDesc(), rn));
571       // }
572
573       if (constraint != null) {
574
575         // Set<CompositeLocation> inputGLB = new HashSet<CompositeLocation>();
576         // inputGLB.add(returnValueLoc);
577         // inputGLB.add(constraint);
578         // returnValueLoc =
579         // CompositeLattice.calculateGLB(inputGLB,
580         // generateErrorMessage(md.getClassDesc(), rn));
581
582         // if (!returnValueLoc.get(returnValueLoc.getSize() - 1).isTop()) {
583         // if (!CompositeLattice.isGreaterThan(constraint, returnValueLoc,
584         // generateErrorMessage(md.getClassDesc(), rn))) {
585         // System.out.println("returnValueLoc.get(returnValueLoc.getSize() - 1).isTop()="
586         // + returnValueLoc.get(returnValueLoc.getSize() - 1).isTop());
587         // throw new Error("The value flow from " + constraint + " to " +
588         // returnValueLoc
589         // + " does not respect location hierarchy on the assignment " +
590         // rn.printNode(0)
591         // + " at " + md.getClassDesc().getSourceFileName() + "::" +
592         // rn.getNumLine());
593         // }
594         // }
595
596         if (!CompositeLattice.isGreaterThan(constraint, declaredReturnLoc,
597             generateErrorMessage(md.getClassDesc(), rn))) {
598           throw new Error("The value flow from " + constraint + " to " + declaredReturnLoc
599               + " does not respect location hierarchy on the assignment " + rn.printNode(0)
600               + " at " + md.getClassDesc().getSourceFileName() + "::" + rn.getNumLine());
601         }
602
603       }
604
605       // check if return value is equal or higher than RETRUNLOC of method
606       // declaration annotation
607
608       int compareResult =
609           CompositeLattice.compare(returnValueLoc, declaredReturnLoc, false,
610               generateErrorMessage(md.getClassDesc(), rn));
611
612       if (compareResult == ComparisonResult.LESS || compareResult == ComparisonResult.INCOMPARABLE) {
613         throw new Error(
614             "Return value location is not equal or higher than the declaraed return location at "
615                 + md.getClassDesc().getSourceFileName() + "::" + rn.getNumLine());
616       }
617     }
618
619     return new CompositeLocation();
620   }
621
622   private boolean hasOnlyLiteralValue(ExpressionNode en) {
623     if (en.kind() == Kind.LiteralNode) {
624       return true;
625     } else {
626       return false;
627     }
628   }
629
630   private CompositeLocation checkLocationFromLoopNode(MethodDescriptor md, SymbolTable nametable,
631       LoopNode ln, CompositeLocation constraint) {
632
633     ClassDescriptor cd = md.getClassDesc();
634     if (ln.getType() == LoopNode.WHILELOOP || ln.getType() == LoopNode.DOWHILELOOP) {
635
636       CompositeLocation condLoc =
637           checkLocationFromExpressionNode(md, nametable, ln.getCondition(),
638               new CompositeLocation(), constraint, false);
639       // addLocationType(ln.getCondition().getType(), (condLoc));
640
641       constraint = generateNewConstraint(constraint, condLoc);
642       checkLocationFromBlockNode(md, nametable, ln.getBody(), constraint);
643
644       return new CompositeLocation();
645
646     } else {
647       // check 'for loop' case
648       BlockNode bn = ln.getInitializer();
649       bn.getVarTable().setParent(nametable);
650       // need to check initialization node
651       // checkLocationFromBlockNode(md, bn.getVarTable(), bn, constraint);
652       for (int i = 0; i < bn.size(); i++) {
653         BlockStatementNode bsn = bn.get(i);
654         checkLocationFromBlockStatementNode(md, bn.getVarTable(), bsn, constraint);
655       }
656
657       // calculate glb location of condition and update statements
658       CompositeLocation condLoc =
659           checkLocationFromExpressionNode(md, bn.getVarTable(), ln.getCondition(),
660               new CompositeLocation(), constraint, false);
661       // addLocationType(ln.getCondition().getType(), condLoc);
662
663       constraint = generateNewConstraint(constraint, condLoc);
664
665       checkLocationFromBlockNode(md, bn.getVarTable(), ln.getUpdate(), constraint);
666       checkLocationFromBlockNode(md, bn.getVarTable(), ln.getBody(), constraint);
667
668       return new CompositeLocation();
669
670     }
671
672   }
673
674   private CompositeLocation checkLocationFromSubBlockNode(MethodDescriptor md,
675       SymbolTable nametable, SubBlockNode sbn, CompositeLocation constraint) {
676     CompositeLocation compLoc =
677         checkLocationFromBlockNode(md, nametable, sbn.getBlockNode(), constraint);
678     return compLoc;
679   }
680
681   private CompositeLocation generateNewConstraint(CompositeLocation currentCon,
682       CompositeLocation newCon) {
683
684     if (currentCon == null) {
685       return newCon;
686     } else {
687       // compute GLB of current constraint and new constraint
688       Set<CompositeLocation> inputSet = new HashSet<CompositeLocation>();
689       inputSet.add(currentCon);
690       inputSet.add(newCon);
691       return CompositeLattice.calculateGLB(inputSet, "");
692     }
693
694   }
695
696   private CompositeLocation checkLocationFromIfStatementNode(MethodDescriptor md,
697       SymbolTable nametable, IfStatementNode isn, CompositeLocation constraint) {
698
699     CompositeLocation condLoc =
700         checkLocationFromExpressionNode(md, nametable, isn.getCondition(), new CompositeLocation(),
701             constraint, false);
702
703     System.out.println("checkLocationFromIfStatementNode=" + isn.getCondition().printNode(0));
704     System.out.println("---old constraints=" + constraint);
705     // addLocationType(isn.getCondition().getType(), condLoc);
706     constraint = generateNewConstraint(constraint, condLoc);
707     System.out.println("---new constraints=" + constraint);
708     checkLocationFromBlockNode(md, nametable, isn.getTrueBlock(), constraint);
709
710     if (isn.getFalseBlock() != null) {
711       checkLocationFromBlockNode(md, nametable, isn.getFalseBlock(), constraint);
712     }
713
714     return new CompositeLocation();
715   }
716
717   private void checkOwnership(MethodDescriptor md, TreeNode tn, ExpressionNode srcExpNode) {
718
719     if (srcExpNode.kind() == Kind.NameNode || srcExpNode.kind() == Kind.FieldAccessNode) {
720       if (srcExpNode.getType().isPtr() && !srcExpNode.getType().isNull()) {
721         // first, check the linear type
722         // RHS reference should be owned by the current method
723         FieldDescriptor fd = getFieldDescriptorFromExpressionNode(srcExpNode);
724         boolean isOwned;
725         if (fd == null) {
726           // local var case
727           isOwned = ((SSJavaType) srcExpNode.getType().getExtension()).isOwned();
728         } else {
729           // field case
730           isOwned = ssjava.isOwnedByMethod(md, fd);
731         }
732         if (!isOwned) {
733           throw new Error(
734               "It is not allowed to create the reference alias from the reference not owned by the method at "
735                   + generateErrorMessage(md.getClassDesc(), tn));
736         }
737
738       }
739     }
740
741   }
742
743   private CompositeLocation checkLocationFromDeclarationNode(MethodDescriptor md,
744       SymbolTable nametable, DeclarationNode dn, CompositeLocation constraint) {
745
746     VarDescriptor vd = dn.getVarDescriptor();
747
748     CompositeLocation destLoc = d2loc.get(vd);
749
750     if (dn.getExpression() != null) {
751
752       checkOwnership(md, dn, dn.getExpression());
753
754       CompositeLocation expressionLoc =
755           checkLocationFromExpressionNode(md, nametable, dn.getExpression(),
756               new CompositeLocation(), constraint, false);
757       // addTypeLocation(dn.getExpression().getType(), expressionLoc);
758
759       if (expressionLoc != null) {
760
761         // checking location order
762         if (!CompositeLattice.isGreaterThan(expressionLoc, destLoc,
763             generateErrorMessage(md.getClassDesc(), dn))) {
764           throw new Error("The value flow from " + expressionLoc + " to " + destLoc
765               + " does not respect location hierarchy on the assignment " + dn.printNode(0)
766               + " at " + md.getClassDesc().getSourceFileName() + "::" + dn.getNumLine());
767         }
768       }
769       return expressionLoc;
770
771     } else {
772
773       return new CompositeLocation();
774
775     }
776
777   }
778
779   private void checkDeclarationInSubBlockNode(MethodDescriptor md, SymbolTable nametable,
780       SubBlockNode sbn) {
781     checkDeclarationInBlockNode(md, nametable, sbn.getBlockNode());
782   }
783
784   private CompositeLocation checkLocationFromBlockExpressionNode(MethodDescriptor md,
785       SymbolTable nametable, BlockExpressionNode ben, CompositeLocation constraint) {
786
787     CompositeLocation compLoc =
788         checkLocationFromExpressionNode(md, nametable, ben.getExpression(), null, constraint, false);
789     // addTypeLocation(ben.getExpression().getType(), compLoc);
790     return compLoc;
791   }
792
793   private CompositeLocation checkLocationFromExpressionNode(MethodDescriptor md,
794       SymbolTable nametable, ExpressionNode en, CompositeLocation loc,
795       CompositeLocation constraint, boolean isLHS) {
796
797     CompositeLocation compLoc = null;
798     switch (en.kind()) {
799
800     case Kind.AssignmentNode:
801       compLoc =
802           checkLocationFromAssignmentNode(md, nametable, (AssignmentNode) en, loc, constraint);
803       break;
804
805     case Kind.FieldAccessNode:
806       compLoc =
807           checkLocationFromFieldAccessNode(md, nametable, (FieldAccessNode) en, loc, constraint);
808       break;
809
810     case Kind.NameNode:
811       compLoc = checkLocationFromNameNode(md, nametable, (NameNode) en, loc, constraint);
812       break;
813
814     case Kind.OpNode:
815       compLoc = checkLocationFromOpNode(md, nametable, (OpNode) en, constraint);
816       break;
817
818     case Kind.CreateObjectNode:
819       compLoc = checkLocationFromCreateObjectNode(md, nametable, (CreateObjectNode) en);
820       break;
821
822     case Kind.ArrayAccessNode:
823       compLoc =
824           checkLocationFromArrayAccessNode(md, nametable, (ArrayAccessNode) en, constraint, isLHS);
825       break;
826
827     case Kind.LiteralNode:
828       compLoc = checkLocationFromLiteralNode(md, nametable, (LiteralNode) en, loc);
829       break;
830
831     case Kind.MethodInvokeNode:
832       compLoc =
833           checkLocationFromMethodInvokeNode(md, nametable, (MethodInvokeNode) en, loc, constraint);
834       break;
835
836     case Kind.TertiaryNode:
837       compLoc = checkLocationFromTertiaryNode(md, nametable, (TertiaryNode) en, constraint);
838       break;
839
840     case Kind.CastNode:
841       compLoc = checkLocationFromCastNode(md, nametable, (CastNode) en, constraint);
842       break;
843
844     // case Kind.InstanceOfNode:
845     // checkInstanceOfNode(md, nametable, (InstanceOfNode) en, td);
846     // return null;
847
848     // case Kind.ArrayInitializerNode:
849     // checkArrayInitializerNode(md, nametable, (ArrayInitializerNode) en,
850     // td);
851     // return null;
852
853     // case Kind.ClassTypeNode:
854     // checkClassTypeNode(md, nametable, (ClassTypeNode) en, td);
855     // return null;
856
857     // case Kind.OffsetNode:
858     // checkOffsetNode(md, nametable, (OffsetNode)en, td);
859     // return null;
860
861     default:
862       return null;
863
864     }
865     // addTypeLocation(en.getType(), compLoc);
866     return compLoc;
867
868   }
869
870   private CompositeLocation checkLocationFromCastNode(MethodDescriptor md, SymbolTable nametable,
871       CastNode cn, CompositeLocation constraint) {
872
873     ExpressionNode en = cn.getExpression();
874     return checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation(), constraint,
875         false);
876
877   }
878
879   private CompositeLocation checkLocationFromTertiaryNode(MethodDescriptor md,
880       SymbolTable nametable, TertiaryNode tn, CompositeLocation constraint) {
881     ClassDescriptor cd = md.getClassDesc();
882
883     CompositeLocation condLoc =
884         checkLocationFromExpressionNode(md, nametable, tn.getCond(), new CompositeLocation(),
885             constraint, false);
886     // addLocationType(tn.getCond().getType(), condLoc);
887     CompositeLocation trueLoc =
888         checkLocationFromExpressionNode(md, nametable, tn.getTrueExpr(), new CompositeLocation(),
889             constraint, false);
890     // addLocationType(tn.getTrueExpr().getType(), trueLoc);
891     CompositeLocation falseLoc =
892         checkLocationFromExpressionNode(md, nametable, tn.getFalseExpr(), new CompositeLocation(),
893             constraint, false);
894     // addLocationType(tn.getFalseExpr().getType(), falseLoc);
895
896     // locations from true/false branches can be TOP when there are only literal
897     // values
898     // in this case, we don't need to check flow down rule!
899
900     // System.out.println("\n#tertiary cond=" + tn.getCond().printNode(0) +
901     // " Loc=" + condLoc);
902     // System.out.println("# true=" + tn.getTrueExpr().printNode(0) + " Loc=" +
903     // trueLoc);
904     // System.out.println("# false=" + tn.getFalseExpr().printNode(0) + " Loc="
905     // + falseLoc);
906
907     // check if condLoc is higher than trueLoc & falseLoc
908     if (!trueLoc.get(0).isTop()
909         && !CompositeLattice.isGreaterThan(condLoc, trueLoc, generateErrorMessage(cd, tn))) {
910       throw new Error(
911           "The location of the condition expression is lower than the true expression at "
912               + cd.getSourceFileName() + ":" + tn.getCond().getNumLine());
913     }
914
915     if (!falseLoc.get(0).isTop()
916         && !CompositeLattice.isGreaterThan(condLoc, falseLoc,
917             generateErrorMessage(cd, tn.getCond()))) {
918       throw new Error(
919           "The location of the condition expression is lower than the false expression at "
920               + cd.getSourceFileName() + ":" + tn.getCond().getNumLine());
921     }
922
923     // then, return glb of trueLoc & falseLoc
924     Set<CompositeLocation> glbInputSet = new HashSet<CompositeLocation>();
925     glbInputSet.add(trueLoc);
926     glbInputSet.add(falseLoc);
927
928     if (glbInputSet.size() == 1) {
929       return trueLoc;
930     } else {
931       return CompositeLattice.calculateGLB(glbInputSet, generateErrorMessage(cd, tn));
932     }
933
934   }
935
936   private CompositeLocation checkLocationFromMethodInvokeNode(MethodDescriptor md,
937       SymbolTable nametable, MethodInvokeNode min, CompositeLocation loc,
938       CompositeLocation constraint) {
939
940     ClassDescriptor cd = md.getClassDesc();
941     MethodDescriptor calleeMethodDesc = min.getMethod();
942
943     NameDescriptor baseName = min.getBaseName();
944     boolean isSystemout = false;
945     if (baseName != null) {
946       isSystemout = baseName.getSymbol().equals("System.out");
947     }
948
949     if (!ssjava.isSSJavaUtil(calleeMethodDesc.getClassDesc())
950         && !ssjava.isTrustMethod(calleeMethodDesc) && !calleeMethodDesc.getModifiers().isNative()
951         && !isSystemout) {
952
953       CompositeLocation baseLocation = null;
954       if (min.getExpression() != null) {
955         baseLocation =
956             checkLocationFromExpressionNode(md, nametable, min.getExpression(),
957                 new CompositeLocation(), constraint, false);
958       } else {
959         if (min.getMethod().isStatic()) {
960           String globalLocId = ssjava.getMethodLattice(md).getGlobalLoc();
961           if (globalLocId == null) {
962             throw new Error("Method lattice does not define global variable location at "
963                 + generateErrorMessage(md.getClassDesc(), min));
964           }
965           baseLocation = new CompositeLocation(new Location(md, globalLocId));
966         } else {
967           String thisLocId = ssjava.getMethodLattice(md).getThisLoc();
968           baseLocation = new CompositeLocation(new Location(md, thisLocId));
969         }
970       }
971
972       // System.out.println("\n#checkLocationFromMethodInvokeNode=" +
973       // min.printNode(0)
974       // + " baseLocation=" + baseLocation + " constraint=" + constraint);
975
976       // setup the location list of caller's arguments
977       List<CompositeLocation> callerArgList = new ArrayList<CompositeLocation>();
978
979       // setup the location list of callee's parameters
980       MethodLattice<String> calleeLattice = ssjava.getMethodLattice(calleeMethodDesc);
981       List<CompositeLocation> calleeParamList = new ArrayList<CompositeLocation>();
982
983       if (min.numArgs() > 0) {
984         if (!calleeMethodDesc.isStatic()) {
985           callerArgList.add(baseLocation);
986         }
987         for (int i = 0; i < min.numArgs(); i++) {
988           ExpressionNode en = min.getArg(i);
989           CompositeLocation callerArgLoc =
990               checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation(),
991                   constraint, false);
992           callerArgList.add(callerArgLoc);
993         }
994
995         if (!calleeMethodDesc.isStatic()) {
996           CompositeLocation calleeThisLoc =
997               new CompositeLocation(new Location(calleeMethodDesc, calleeLattice.getThisLoc()));
998           calleeParamList.add(calleeThisLoc);
999         }
1000
1001         for (int i = 0; i < calleeMethodDesc.numParameters(); i++) {
1002           VarDescriptor calleevd = (VarDescriptor) calleeMethodDesc.getParameter(i);
1003           CompositeLocation calleeLoc = d2loc.get(calleevd);
1004           calleeParamList.add(calleeLoc);
1005         }
1006       }
1007
1008       if (constraint != null) {
1009         // check whether the PC location is lower than one of the
1010         // argument locations. If it is lower, the callee has to have @PCLOC
1011         // annotation that declares the program counter that is higher than
1012         // corresponding parameter
1013
1014         CompositeLocation calleePCLOC = ssjava.getPCLocation(calleeMethodDesc);
1015
1016         for (int idx = 0; idx < callerArgList.size(); idx++) {
1017           CompositeLocation argLocation = callerArgList.get(idx);
1018
1019           // need to check that param is higher than PCLOC
1020           if (!argLocation.get(0).isTop()
1021               && CompositeLattice.compare(argLocation, constraint, true,
1022                   generateErrorMessage(cd, min)) == ComparisonResult.GREATER) {
1023
1024             CompositeLocation paramLocation = calleeParamList.get(idx);
1025
1026             int paramCompareResult =
1027                 CompositeLattice.compare(calleePCLOC, paramLocation, true,
1028                     generateErrorMessage(cd, min));
1029
1030             if (paramCompareResult == ComparisonResult.GREATER) {
1031               throw new Error(
1032                   "The program counter location "
1033                       + constraint
1034                       + " is lower than the argument(idx="
1035                       + idx
1036                       + ") location "
1037                       + argLocation
1038                       + ". Need to specify that the initial PC location of the callee, which is currently set to "
1039                       + calleePCLOC + ", is lower than " + paramLocation + " in the method "
1040                       + calleeMethodDesc.getSymbol() + ":" + min.getNumLine());
1041             }
1042
1043           }
1044
1045         }
1046
1047       }
1048
1049       checkCalleeConstraints(md, nametable, min, baseLocation, constraint);
1050
1051       // checkCallerArgumentLocationConstraints(md, nametable, min,
1052       // baseLocation, constraint);
1053
1054       if (!min.getMethod().getReturnType().isVoid()) {
1055         // If method has a return value, compute the highest possible return
1056         // location in the caller's perspective
1057         CompositeLocation ceilingLoc =
1058             computeCeilingLocationForCaller(md, nametable, min, baseLocation, constraint);
1059
1060         if (ceilingLoc == null) {
1061           return new CompositeLocation(Location.createTopLocation(md));
1062         }
1063         return ceilingLoc;
1064       }
1065     }
1066
1067     return new CompositeLocation(Location.createTopLocation(md));
1068
1069   }
1070
1071   private CompositeLocation translateCallerLocToCalleeLoc(MethodDescriptor calleeMD,
1072       CompositeLocation calleeBaseLoc, CompositeLocation constraint) {
1073
1074     CompositeLocation calleeConstraint = new CompositeLocation();
1075
1076     // if (constraint.startsWith(calleeBaseLoc)) {
1077     // if the first part of constraint loc is matched with callee base loc
1078     Location thisLoc = new Location(calleeMD, ssjava.getMethodLattice(calleeMD).getThisLoc());
1079     calleeConstraint.addLocation(thisLoc);
1080     for (int i = calleeBaseLoc.getSize(); i < constraint.getSize(); i++) {
1081       calleeConstraint.addLocation(constraint.get(i));
1082     }
1083
1084     // }
1085
1086     return calleeConstraint;
1087   }
1088
1089   private void checkCallerArgumentLocationConstraints(MethodDescriptor md, SymbolTable nametable,
1090       MethodInvokeNode min, CompositeLocation callerBaseLoc, CompositeLocation constraint) {
1091     // if parameter location consists of THIS and FIELD location,
1092     // caller should pass an argument that is comparable to the declared
1093     // parameter location
1094     // and is not lower than the declared parameter location in the field
1095     // lattice.
1096
1097     MethodDescriptor calleemd = min.getMethod();
1098
1099     List<CompositeLocation> callerArgList = new ArrayList<CompositeLocation>();
1100     List<CompositeLocation> calleeParamList = new ArrayList<CompositeLocation>();
1101
1102     MethodLattice<String> calleeLattice = ssjava.getMethodLattice(calleemd);
1103     Location calleeThisLoc = new Location(calleemd, calleeLattice.getThisLoc());
1104
1105     for (int i = 0; i < min.numArgs(); i++) {
1106       ExpressionNode en = min.getArg(i);
1107       CompositeLocation callerArgLoc =
1108           checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation(), constraint,
1109               false);
1110       callerArgList.add(callerArgLoc);
1111     }
1112
1113     // setup callee params set
1114     for (int i = 0; i < calleemd.numParameters(); i++) {
1115       VarDescriptor calleevd = (VarDescriptor) calleemd.getParameter(i);
1116       CompositeLocation calleeLoc = d2loc.get(calleevd);
1117       calleeParamList.add(calleeLoc);
1118     }
1119
1120     String errorMsg = generateErrorMessage(md.getClassDesc(), min);
1121
1122     // System.out.println("checkCallerArgumentLocationConstraints=" +
1123     // min.printNode(0));
1124     // System.out.println("base location=" + callerBaseLoc + " constraint=" +
1125     // constraint);
1126
1127     for (int i = 0; i < calleeParamList.size(); i++) {
1128       CompositeLocation calleeParamLoc = calleeParamList.get(i);
1129       if (calleeParamLoc.get(0).equals(calleeThisLoc) && calleeParamLoc.getSize() > 1) {
1130
1131         // callee parameter location has field information
1132         CompositeLocation callerArgLoc = callerArgList.get(i);
1133
1134         CompositeLocation paramLocation =
1135             translateCalleeParamLocToCaller(md, calleeParamLoc, callerBaseLoc, errorMsg);
1136
1137         Set<CompositeLocation> inputGLBSet = new HashSet<CompositeLocation>();
1138         if (constraint != null) {
1139           inputGLBSet.add(callerArgLoc);
1140           inputGLBSet.add(constraint);
1141           callerArgLoc =
1142               CompositeLattice.calculateGLB(inputGLBSet,
1143                   generateErrorMessage(md.getClassDesc(), min));
1144         }
1145
1146         if (!CompositeLattice.isGreaterThan(callerArgLoc, paramLocation, errorMsg)) {
1147           throw new Error("Caller argument '" + min.getArg(i).printNode(0) + " : " + callerArgLoc
1148               + "' should be higher than corresponding callee's parameter : " + paramLocation
1149               + " at " + errorMsg);
1150         }
1151
1152       }
1153     }
1154
1155   }
1156
1157   private CompositeLocation translateCalleeParamLocToCaller(MethodDescriptor md,
1158       CompositeLocation calleeParamLoc, CompositeLocation callerBaseLocation, String errorMsg) {
1159
1160     CompositeLocation translate = new CompositeLocation();
1161
1162     for (int i = 0; i < callerBaseLocation.getSize(); i++) {
1163       translate.addLocation(callerBaseLocation.get(i));
1164     }
1165
1166     for (int i = 1; i < calleeParamLoc.getSize(); i++) {
1167       translate.addLocation(calleeParamLoc.get(i));
1168     }
1169
1170     // System.out.println("TRANSLATED=" + translate + " from calleeParamLoc=" +
1171     // calleeParamLoc);
1172
1173     return translate;
1174   }
1175
1176   private CompositeLocation computeCeilingLocationForCaller(MethodDescriptor md,
1177       SymbolTable nametable, MethodInvokeNode min, CompositeLocation baseLocation,
1178       CompositeLocation constraint) {
1179     List<CompositeLocation> argList = new ArrayList<CompositeLocation>();
1180
1181     // by default, method has a THIS parameter
1182     if (!min.getMethod().isStatic()) {
1183       argList.add(baseLocation);
1184     }
1185
1186     for (int i = 0; i < min.numArgs(); i++) {
1187       ExpressionNode en = min.getArg(i);
1188       CompositeLocation callerArg =
1189           checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation(), constraint,
1190               false);
1191       argList.add(callerArg);
1192     }
1193
1194     // System.out.println("\n## computeReturnLocation=" + min.getMethod() + " argList=" + argList);
1195     CompositeLocation ceilLoc = md2ReturnLocGen.get(min.getMethod()).computeReturnLocation(argList);
1196     // System.out.println("## ReturnLocation=" + ceilLoc);
1197
1198     return ceilLoc;
1199
1200   }
1201
1202   private void checkCalleeConstraints(MethodDescriptor md, SymbolTable nametable,
1203       MethodInvokeNode min, CompositeLocation callerBaseLoc, CompositeLocation constraint) {
1204
1205     MethodDescriptor calleemd = min.getMethod();
1206
1207     MethodLattice<String> calleeLattice = ssjava.getMethodLattice(calleemd);
1208
1209     // System.out.println("checkCalleeConstraints=" + calleemd + " calleeLattice.getThisLoc()="
1210     // + calleeLattice.getThisLoc());
1211
1212     CompositeLocation calleeThisLoc =
1213         new CompositeLocation(new Location(calleemd, calleeLattice.getThisLoc()));
1214
1215     List<CompositeLocation> callerArgList = new ArrayList<CompositeLocation>();
1216     List<CompositeLocation> calleeParamList = new ArrayList<CompositeLocation>();
1217
1218     if (min.numArgs() > 0) {
1219       // caller needs to guarantee that it passes arguments in regarding to
1220       // callee's hierarchy
1221
1222       // setup caller args set
1223       // first, add caller's base(this) location
1224       if (!calleemd.isStatic())
1225         callerArgList.add(callerBaseLoc);
1226       // second, add caller's arguments
1227       for (int i = 0; i < min.numArgs(); i++) {
1228         ExpressionNode en = min.getArg(i);
1229         CompositeLocation callerArgLoc =
1230             checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation(), constraint,
1231                 false);
1232         callerArgList.add(callerArgLoc);
1233       }
1234
1235       // setup callee params set
1236       // first, add callee's this location
1237       if (!calleemd.isStatic())
1238         calleeParamList.add(calleeThisLoc);
1239       // second, add callee's parameters
1240       for (int i = 0; i < calleemd.numParameters(); i++) {
1241         VarDescriptor calleevd = (VarDescriptor) calleemd.getParameter(i);
1242         CompositeLocation calleeLoc = d2loc.get(calleevd);
1243         // System.out.println("calleevd=" + calleevd + " loc=" + calleeLoc);
1244         calleeParamList.add(calleeLoc);
1245       }
1246
1247       // here, check if ordering relations among caller's args respect
1248       // ordering relations in-between callee's args
1249       CHECK: for (int i = 0; i < calleeParamList.size(); i++) {
1250         CompositeLocation calleeLoc1 = calleeParamList.get(i);
1251         CompositeLocation callerLoc1 = callerArgList.get(i);
1252
1253         for (int j = 0; j < calleeParamList.size(); j++) {
1254           if (i != j) {
1255             CompositeLocation calleeLoc2 = calleeParamList.get(j);
1256             CompositeLocation callerLoc2 = callerArgList.get(j);
1257
1258             if (callerLoc1.get(callerLoc1.getSize() - 1).isTop()
1259                 || callerLoc2.get(callerLoc2.getSize() - 1).isTop()) {
1260               continue CHECK;
1261             }
1262
1263             // System.out.println("calleeLoc1=" + calleeLoc1);
1264             // System.out.println("calleeLoc2=" + calleeLoc2 +
1265             // "calleeParamList=" + calleeParamList);
1266
1267             int callerResult =
1268                 CompositeLattice.compare(callerLoc1, callerLoc2, true,
1269                     generateErrorMessage(md.getClassDesc(), min));
1270             // System.out.println("callerResult=" + callerResult);
1271             int calleeResult =
1272                 CompositeLattice.compare(calleeLoc1, calleeLoc2, true,
1273                     generateErrorMessage(md.getClassDesc(), min));
1274             // System.out.println("calleeResult=" + calleeResult);
1275
1276             if (callerResult == ComparisonResult.EQUAL) {
1277               if (ssjava.isSharedLocation(callerLoc1.get(callerLoc1.getSize() - 1))
1278                   && ssjava.isSharedLocation(callerLoc2.get(callerLoc2.getSize() - 1))) {
1279                 // if both of them are shared locations, promote them to
1280                 // "GREATER relation"
1281                 callerResult = ComparisonResult.GREATER;
1282               }
1283             }
1284
1285             if (calleeResult == ComparisonResult.GREATER
1286                 && callerResult != ComparisonResult.GREATER) {
1287               // If calleeLoc1 is higher than calleeLoc2
1288               // then, caller should have same ordering relation in-bet
1289               // callerLoc1 & callerLoc2
1290
1291               String paramName1, paramName2;
1292
1293               if (i == 0) {
1294                 paramName1 = "'THIS'";
1295               } else {
1296                 paramName1 = "'parameter " + calleemd.getParamName(i - 1) + "'";
1297               }
1298
1299               if (j == 0) {
1300                 paramName2 = "'THIS'";
1301               } else {
1302                 paramName2 = "'parameter " + calleemd.getParamName(j - 1) + "'";
1303               }
1304
1305               throw new Error(
1306                   "Caller doesn't respect an ordering relation among method arguments: callee expects that "
1307                       + paramName1 + " should be higher than " + paramName2 + " in " + calleemd
1308                       + " at " + md.getClassDesc().getSourceFileName() + ":" + min.getNumLine());
1309             }
1310           }
1311
1312         }
1313       }
1314
1315     }
1316
1317   }
1318
1319   private CompositeLocation checkLocationFromArrayAccessNode(MethodDescriptor md,
1320       SymbolTable nametable, ArrayAccessNode aan, CompositeLocation constraint, boolean isLHS) {
1321     // System.out.println("aan=" + aan.printNode(0) + "  line#=" + aan.getNumLine());
1322     ClassDescriptor cd = md.getClassDesc();
1323
1324     CompositeLocation arrayLoc =
1325         checkLocationFromExpressionNode(md, nametable, aan.getExpression(),
1326             new CompositeLocation(), constraint, isLHS);
1327
1328     // addTypeLocation(aan.getExpression().getType(), arrayLoc);
1329     CompositeLocation indexLoc =
1330         checkLocationFromExpressionNode(md, nametable, aan.getIndex(), new CompositeLocation(),
1331             constraint, isLHS);
1332     // addTypeLocation(aan.getIndex().getType(), indexLoc);
1333
1334     if (isLHS) {
1335       if (!CompositeLattice.isGreaterThan(indexLoc, arrayLoc, generateErrorMessage(cd, aan))) {
1336         throw new Error("Array index value is not higher than array location at "
1337             + generateErrorMessage(cd, aan));
1338       }
1339       return arrayLoc;
1340     } else {
1341       Set<CompositeLocation> inputGLB = new HashSet<CompositeLocation>();
1342       inputGLB.add(arrayLoc);
1343       inputGLB.add(indexLoc);
1344       return CompositeLattice.calculateGLB(inputGLB, generateErrorMessage(cd, aan));
1345     }
1346
1347   }
1348
1349   private CompositeLocation checkLocationFromCreateObjectNode(MethodDescriptor md,
1350       SymbolTable nametable, CreateObjectNode con) {
1351
1352     ClassDescriptor cd = md.getClassDesc();
1353
1354     CompositeLocation compLoc = new CompositeLocation();
1355     compLoc.addLocation(Location.createTopLocation(md));
1356     return compLoc;
1357
1358   }
1359
1360   private CompositeLocation checkLocationFromOpNode(MethodDescriptor md, SymbolTable nametable,
1361       OpNode on, CompositeLocation constraint) {
1362
1363     ClassDescriptor cd = md.getClassDesc();
1364     CompositeLocation leftLoc = new CompositeLocation();
1365     leftLoc =
1366         checkLocationFromExpressionNode(md, nametable, on.getLeft(), leftLoc, constraint, false);
1367     // addTypeLocation(on.getLeft().getType(), leftLoc);
1368
1369     CompositeLocation rightLoc = new CompositeLocation();
1370     if (on.getRight() != null) {
1371       rightLoc =
1372           checkLocationFromExpressionNode(md, nametable, on.getRight(), rightLoc, constraint, false);
1373       // addTypeLocation(on.getRight().getType(), rightLoc);
1374     }
1375
1376     // System.out.println("\n# OP NODE=" + on.printNode(0));
1377     // System.out.println("# left loc=" + leftLoc + " from " +
1378     // on.getLeft().getClass());
1379     // if (on.getRight() != null) {
1380     // System.out.println("# right loc=" + rightLoc + " from " +
1381     // on.getRight().getClass());
1382     // }
1383
1384     Operation op = on.getOp();
1385
1386     switch (op.getOp()) {
1387
1388     case Operation.UNARYPLUS:
1389     case Operation.UNARYMINUS:
1390     case Operation.LOGIC_NOT:
1391       // single operand
1392       return leftLoc;
1393
1394     case Operation.LOGIC_OR:
1395     case Operation.LOGIC_AND:
1396     case Operation.COMP:
1397     case Operation.BIT_OR:
1398     case Operation.BIT_XOR:
1399     case Operation.BIT_AND:
1400     case Operation.ISAVAILABLE:
1401     case Operation.EQUAL:
1402     case Operation.NOTEQUAL:
1403     case Operation.LT:
1404     case Operation.GT:
1405     case Operation.LTE:
1406     case Operation.GTE:
1407     case Operation.ADD:
1408     case Operation.SUB:
1409     case Operation.MULT:
1410     case Operation.DIV:
1411     case Operation.MOD:
1412     case Operation.LEFTSHIFT:
1413     case Operation.RIGHTSHIFT:
1414     case Operation.URIGHTSHIFT:
1415
1416       Set<CompositeLocation> inputSet = new HashSet<CompositeLocation>();
1417       inputSet.add(leftLoc);
1418       inputSet.add(rightLoc);
1419       CompositeLocation glbCompLoc =
1420           CompositeLattice.calculateGLB(inputSet, generateErrorMessage(cd, on));
1421       return glbCompLoc;
1422
1423     default:
1424       throw new Error(op.toString());
1425     }
1426
1427   }
1428
1429   private CompositeLocation checkLocationFromLiteralNode(MethodDescriptor md,
1430       SymbolTable nametable, LiteralNode en, CompositeLocation loc) {
1431
1432     // literal value has the top location so that value can be flowed into any
1433     // location
1434     Location literalLoc = Location.createTopLocation(md);
1435     loc.addLocation(literalLoc);
1436     return loc;
1437
1438   }
1439
1440   private CompositeLocation checkLocationFromNameNode(MethodDescriptor md, SymbolTable nametable,
1441       NameNode nn, CompositeLocation loc, CompositeLocation constraint) {
1442
1443     NameDescriptor nd = nn.getName();
1444     if (nd.getBase() != null) {
1445       loc =
1446           checkLocationFromExpressionNode(md, nametable, nn.getExpression(), loc, constraint, false);
1447     } else {
1448       String varname = nd.toString();
1449       if (varname.equals("this")) {
1450         // 'this' itself!
1451         MethodLattice<String> methodLattice = ssjava.getMethodLattice(md);
1452         String thisLocId = methodLattice.getThisLoc();
1453         if (thisLocId == null) {
1454           throw new Error("The location for 'this' is not defined at "
1455               + md.getClassDesc().getSourceFileName() + "::" + nn.getNumLine());
1456         }
1457         Location locElement = new Location(md, thisLocId);
1458         loc.addLocation(locElement);
1459         return loc;
1460
1461       }
1462
1463       Descriptor d = (Descriptor) nametable.get(varname);
1464
1465       // CompositeLocation localLoc = null;
1466       if (d instanceof VarDescriptor) {
1467         VarDescriptor vd = (VarDescriptor) d;
1468         // localLoc = d2loc.get(vd);
1469         // the type of var descriptor has a composite location!
1470         loc = ((SSJavaType) vd.getType().getExtension()).getCompLoc().clone();
1471       } else if (d instanceof FieldDescriptor) {
1472         // the type of field descriptor has a location!
1473         FieldDescriptor fd = (FieldDescriptor) d;
1474         if (fd.isStatic()) {
1475           if (fd.isFinal()) {
1476             // if it is 'static final', the location has TOP since no one can
1477             // change its value
1478             loc.addLocation(Location.createTopLocation(md));
1479             return loc;
1480           } else {
1481             // if 'static', the location has pre-assigned global loc
1482             MethodLattice<String> localLattice = ssjava.getMethodLattice(md);
1483             String globalLocId = localLattice.getGlobalLoc();
1484             if (globalLocId == null) {
1485               throw new Error("Global location element is not defined in the method " + md);
1486             }
1487             Location globalLoc = new Location(md, globalLocId);
1488
1489             loc.addLocation(globalLoc);
1490           }
1491         } else {
1492           // the location of field access starts from this, followed by field
1493           // location
1494           MethodLattice<String> localLattice = ssjava.getMethodLattice(md);
1495           Location thisLoc = new Location(md, localLattice.getThisLoc());
1496           loc.addLocation(thisLoc);
1497         }
1498
1499         Location fieldLoc = (Location) fd.getType().getExtension();
1500         loc.addLocation(fieldLoc);
1501       } else if (d == null) {
1502         // access static field
1503         FieldDescriptor fd = nn.getField();
1504
1505         MethodLattice<String> localLattice = ssjava.getMethodLattice(md);
1506         String globalLocId = localLattice.getGlobalLoc();
1507         if (globalLocId == null) {
1508           throw new Error("Method lattice does not define global variable location at "
1509               + generateErrorMessage(md.getClassDesc(), nn));
1510         }
1511         loc.addLocation(new Location(md, globalLocId));
1512
1513         Location fieldLoc = (Location) fd.getType().getExtension();
1514         loc.addLocation(fieldLoc);
1515
1516         return loc;
1517
1518       }
1519     }
1520     return loc;
1521   }
1522
1523   private CompositeLocation checkLocationFromFieldAccessNode(MethodDescriptor md,
1524       SymbolTable nametable, FieldAccessNode fan, CompositeLocation loc,
1525       CompositeLocation constraint) {
1526
1527     ExpressionNode left = fan.getExpression();
1528     TypeDescriptor ltd = left.getType();
1529
1530     FieldDescriptor fd = fan.getField();
1531
1532     String varName = null;
1533     if (left.kind() == Kind.NameNode) {
1534       NameDescriptor nd = ((NameNode) left).getName();
1535       varName = nd.toString();
1536     }
1537
1538     if (ltd.isClassNameRef() || (varName != null && varName.equals("this"))) {
1539       // using a class name directly or access using this
1540       if (fd.isStatic() && fd.isFinal()) {
1541         loc.addLocation(Location.createTopLocation(md));
1542         return loc;
1543       }
1544     }
1545
1546     Set<CompositeLocation> inputGLB = new HashSet<CompositeLocation>();
1547     if (left instanceof ArrayAccessNode) {
1548       ArrayAccessNode aan = (ArrayAccessNode) left;
1549       CompositeLocation indexLoc =
1550           checkLocationFromExpressionNode(md, nametable, aan.getIndex(), loc, constraint, false);
1551       inputGLB.add(indexLoc);
1552     }
1553
1554     loc = checkLocationFromExpressionNode(md, nametable, left, loc, constraint, false);
1555
1556     if (!left.getType().isPrimitive()) {
1557
1558       if (!fd.getSymbol().equals("length")) {
1559         // array.length access, return the location of the array
1560         Location fieldLoc = getFieldLocation(fd);
1561         loc.addLocation(fieldLoc);
1562       }
1563
1564     }
1565
1566     inputGLB.add(loc);
1567     loc = CompositeLattice.calculateGLB(inputGLB, generateErrorMessage(md.getClassDesc(), fan));
1568     return loc;
1569   }
1570
1571   private Location getFieldLocation(FieldDescriptor fd) {
1572
1573     // System.out.println("### getFieldLocation=" + fd);
1574     // System.out.println("### fd.getType().getExtension()=" +
1575     // fd.getType().getExtension());
1576
1577     Location fieldLoc = (Location) fd.getType().getExtension();
1578
1579     // handle the case that method annotation checking skips checking field
1580     // declaration
1581     if (fieldLoc == null) {
1582       fieldLoc = checkFieldDeclaration(fd.getClassDescriptor(), fd);
1583     }
1584
1585     return fieldLoc;
1586
1587   }
1588
1589   private FieldDescriptor getFieldDescriptorFromExpressionNode(ExpressionNode en) {
1590
1591     if (en.kind() == Kind.NameNode) {
1592       NameNode nn = (NameNode) en;
1593       if (nn.getField() != null) {
1594         return nn.getField();
1595       }
1596
1597       if (nn.getName() != null && nn.getName().getBase() != null) {
1598         return getFieldDescriptorFromExpressionNode(nn.getExpression());
1599       }
1600
1601     } else if (en.kind() == Kind.FieldAccessNode) {
1602       FieldAccessNode fan = (FieldAccessNode) en;
1603       return fan.getField();
1604     }
1605
1606     return null;
1607   }
1608
1609   private CompositeLocation checkLocationFromAssignmentNode(MethodDescriptor md,
1610       SymbolTable nametable, AssignmentNode an, CompositeLocation loc, CompositeLocation constraint) {
1611     ClassDescriptor cd = md.getClassDesc();
1612
1613     Set<CompositeLocation> inputGLBSet = new HashSet<CompositeLocation>();
1614
1615     boolean postinc = true;
1616     if (an.getOperation().getBaseOp() == null
1617         || (an.getOperation().getBaseOp().getOp() != Operation.POSTINC && an.getOperation()
1618             .getBaseOp().getOp() != Operation.POSTDEC))
1619       postinc = false;
1620
1621     // if LHS is array access node, need to check if array index is higher
1622     // than array itself
1623     CompositeLocation destLocation =
1624         checkLocationFromExpressionNode(md, nametable, an.getDest(), new CompositeLocation(),
1625             constraint, true);
1626
1627     CompositeLocation rhsLocation;
1628     CompositeLocation srcLocation;
1629
1630     if (!postinc) {
1631
1632       checkOwnership(md, an, an.getSrc());
1633
1634       rhsLocation =
1635           checkLocationFromExpressionNode(md, nametable, an.getSrc(), new CompositeLocation(),
1636               constraint, false);
1637
1638       if (an.getOperation().getOp() >= 2 && an.getOperation().getOp() <= 12) {
1639         // if assignment contains OP+EQ operator, need to merge location types
1640         // of LHS & RHS into the RHS
1641         Set<CompositeLocation> srcGLBSet = new HashSet<CompositeLocation>();
1642         srcGLBSet.add(rhsLocation);
1643         srcGLBSet.add(destLocation);
1644         srcLocation = CompositeLattice.calculateGLB(srcGLBSet, generateErrorMessage(cd, an));
1645       } else {
1646         srcLocation = rhsLocation;
1647       }
1648
1649       if (constraint != null) {
1650
1651         if (!CompositeLattice.isGreaterThan(constraint, destLocation, generateErrorMessage(cd, an))) {
1652           throw new Error("The value flow from " + constraint + " to " + destLocation
1653               + " does not respect location hierarchy on the assignment " + an.printNode(0)
1654               + " at " + cd.getSourceFileName() + "::" + an.getNumLine());
1655         }
1656         // inputGLBSet.add(srcLocation);
1657         // inputGLBSet.add(constraint);
1658         // srcLocation = CompositeLattice.calculateGLB(inputGLBSet,
1659         // generateErrorMessage(cd, an));
1660       }
1661
1662       // System.out.println("src=" + srcLocation + "  dest=" + destLocation + "  const=" +
1663       // constraint);
1664
1665       if (!CompositeLattice.isGreaterThan(srcLocation, destLocation, generateErrorMessage(cd, an))) {
1666
1667         String context = "";
1668         if (constraint != null) {
1669           context = " and the current context constraint is " + constraint;
1670         }
1671
1672         throw new Error("The value flow from " + srcLocation + " to " + destLocation
1673             + " does not respect location hierarchy on the assignment " + an.printNode(0) + context
1674             + " at " + cd.getSourceFileName() + "::" + an.getNumLine());
1675       }
1676
1677       if (srcLocation.equals(destLocation)) {
1678         // keep it for definitely written analysis
1679         Set<FlatNode> flatNodeSet = ssjava.getBuildFlat().getFlatNodeSet(an);
1680         for (Iterator iterator = flatNodeSet.iterator(); iterator.hasNext();) {
1681           FlatNode fn = (FlatNode) iterator.next();
1682           ssjava.addSameHeightWriteFlatNode(fn);
1683         }
1684
1685       }
1686
1687     } else {
1688       destLocation =
1689           rhsLocation =
1690               checkLocationFromExpressionNode(md, nametable, an.getDest(), new CompositeLocation(),
1691                   constraint, false);
1692
1693       if (constraint != null) {
1694
1695         if (!CompositeLattice.isGreaterThan(constraint, destLocation, generateErrorMessage(cd, an))) {
1696           throw new Error("The value flow from " + constraint + " to " + destLocation
1697               + " does not respect location hierarchy on the assignment " + an.printNode(0)
1698               + " at " + cd.getSourceFileName() + "::" + an.getNumLine());
1699         }
1700         // inputGLBSet.add(rhsLocation);
1701         // inputGLBSet.add(constraint);
1702         // srcLocation = CompositeLattice.calculateGLB(inputGLBSet,
1703         // generateErrorMessage(cd, an));
1704         srcLocation = rhsLocation;
1705       } else {
1706         srcLocation = rhsLocation;
1707       }
1708
1709       if (!CompositeLattice.isGreaterThan(srcLocation, destLocation, generateErrorMessage(cd, an))) {
1710
1711         if (srcLocation.equals(destLocation)) {
1712           throw new Error("Location " + srcLocation
1713               + " is not allowed to have the value flow that moves within the same location at '"
1714               + an.printNode(0) + "' of " + cd.getSourceFileName() + "::" + an.getNumLine());
1715         } else {
1716           throw new Error("The value flow from " + srcLocation + " to " + destLocation
1717               + " does not respect location hierarchy on the assignment " + an.printNode(0)
1718               + " at " + cd.getSourceFileName() + "::" + an.getNumLine());
1719         }
1720
1721       }
1722
1723       if (srcLocation.equals(destLocation)) {
1724         // keep it for definitely written analysis
1725         Set<FlatNode> flatNodeSet = ssjava.getBuildFlat().getFlatNodeSet(an);
1726         for (Iterator iterator = flatNodeSet.iterator(); iterator.hasNext();) {
1727           FlatNode fn = (FlatNode) iterator.next();
1728           ssjava.addSameHeightWriteFlatNode(fn);
1729         }
1730       }
1731
1732     }
1733
1734     return destLocation;
1735   }
1736
1737   private void assignLocationOfVarDescriptor(VarDescriptor vd, MethodDescriptor md,
1738       SymbolTable nametable, TreeNode n) {
1739
1740     ClassDescriptor cd = md.getClassDesc();
1741     Vector<AnnotationDescriptor> annotationVec = vd.getType().getAnnotationMarkers();
1742
1743     // currently enforce every variable to have corresponding location
1744     if (annotationVec.size() == 0) {
1745       throw new Error("Location is not assigned to variable '" + vd.getSymbol()
1746           + "' in the method '" + md + "' of the class " + cd.getSymbol() + " at "
1747           + generateErrorMessage(cd, n));
1748     }
1749
1750     int locDecCount = 0;
1751     for (int i = 0; i < annotationVec.size(); i++) {
1752       AnnotationDescriptor ad = annotationVec.elementAt(i);
1753
1754       if (ad.getType() == AnnotationDescriptor.SINGLE_ANNOTATION) {
1755
1756         if (ad.getMarker().equals(SSJavaAnalysis.LOC)) {
1757           locDecCount++;
1758           if (locDecCount > 1) {// variable can have at most one location
1759             throw new Error(vd.getSymbol() + " has more than one location declaration.");
1760           }
1761           String locDec = ad.getValue(); // check if location is defined
1762
1763           if (locDec.startsWith(SSJavaAnalysis.DELTA)) {
1764             DeltaLocation deltaLoc = parseDeltaDeclaration(md, n, locDec);
1765             d2loc.put(vd, deltaLoc);
1766             addLocationType(vd.getType(), deltaLoc);
1767           } else {
1768             CompositeLocation compLoc = parseLocationDeclaration(md, n, locDec);
1769
1770             Location lastElement = compLoc.get(compLoc.getSize() - 1);
1771             if (ssjava.isSharedLocation(lastElement)) {
1772               ssjava.mapSharedLocation2Descriptor(lastElement, vd);
1773             }
1774
1775             d2loc.put(vd, compLoc);
1776             addLocationType(vd.getType(), compLoc);
1777           }
1778
1779         }
1780       }
1781     }
1782
1783   }
1784
1785   private DeltaLocation parseDeltaDeclaration(MethodDescriptor md, TreeNode n, String locDec) {
1786
1787     int deltaCount = 0;
1788     int dIdx = locDec.indexOf(SSJavaAnalysis.DELTA);
1789     while (dIdx >= 0) {
1790       deltaCount++;
1791       int beginIdx = dIdx + 6;
1792       locDec = locDec.substring(beginIdx, locDec.length() - 1);
1793       dIdx = locDec.indexOf(SSJavaAnalysis.DELTA);
1794     }
1795
1796     CompositeLocation compLoc = parseLocationDeclaration(md, n, locDec);
1797     DeltaLocation deltaLoc = new DeltaLocation(compLoc, deltaCount);
1798
1799     return deltaLoc;
1800   }
1801
1802   private Location parseFieldLocDeclaraton(String decl, String msg) throws Exception {
1803
1804     int idx = decl.indexOf(".");
1805
1806     String className = decl.substring(0, idx);
1807     String fieldName = decl.substring(idx + 1);
1808
1809     className.replaceAll(" ", "");
1810     fieldName.replaceAll(" ", "");
1811
1812     Descriptor d = state.getClassSymbolTable().get(className);
1813
1814     if (d == null) {
1815       // System.out.println("state.getClassSymbolTable()=" +
1816       // state.getClassSymbolTable());
1817       throw new Error("The class in the location declaration '" + decl + "' does not exist at "
1818           + msg);
1819     }
1820
1821     assert (d instanceof ClassDescriptor);
1822     SSJavaLattice<String> lattice = ssjava.getClassLattice((ClassDescriptor) d);
1823     if (!lattice.containsKey(fieldName)) {
1824       throw new Error("The location " + fieldName + " is not defined in the field lattice of '"
1825           + className + "' at " + msg);
1826     }
1827
1828     return new Location(d, fieldName);
1829   }
1830
1831   private CompositeLocation parseLocationDeclaration(MethodDescriptor md, TreeNode n, String locDec) {
1832
1833     CompositeLocation compLoc = new CompositeLocation();
1834
1835     StringTokenizer tokenizer = new StringTokenizer(locDec, ",");
1836     List<String> locIdList = new ArrayList<String>();
1837     while (tokenizer.hasMoreTokens()) {
1838       String locId = tokenizer.nextToken();
1839       locIdList.add(locId);
1840     }
1841
1842     // at least,one location element needs to be here!
1843     assert (locIdList.size() > 0);
1844
1845     // assume that loc with idx 0 comes from the local lattice
1846     // loc with idx 1 comes from the field lattice
1847
1848     String localLocId = locIdList.get(0);
1849     SSJavaLattice<String> localLattice = CompositeLattice.getLatticeByDescriptor(md);
1850     Location localLoc = new Location(md, localLocId);
1851     if (localLattice == null || (!localLattice.containsKey(localLocId))) {
1852       throw new Error("Location " + localLocId
1853           + " is not defined in the local variable lattice at "
1854           + md.getClassDesc().getSourceFileName() + "::" + (n != null ? n.getNumLine() : md) + ".");
1855     }
1856     compLoc.addLocation(localLoc);
1857
1858     for (int i = 1; i < locIdList.size(); i++) {
1859       String locName = locIdList.get(i);
1860       try {
1861         Location fieldLoc =
1862             parseFieldLocDeclaraton(locName, generateErrorMessage(md.getClassDesc(), n));
1863         compLoc.addLocation(fieldLoc);
1864       } catch (Exception e) {
1865         throw new Error("The location declaration '" + locName + "' is wrong  at "
1866             + generateErrorMessage(md.getClassDesc(), n));
1867       }
1868     }
1869
1870     return compLoc;
1871
1872   }
1873
1874   private void checkDeclarationNode(MethodDescriptor md, SymbolTable nametable, DeclarationNode dn) {
1875     VarDescriptor vd = dn.getVarDescriptor();
1876     assignLocationOfVarDescriptor(vd, md, nametable, dn);
1877   }
1878
1879   private void checkDeclarationInClass(ClassDescriptor cd) {
1880     // Check to see that fields are okay
1881     for (Iterator field_it = cd.getFields(); field_it.hasNext();) {
1882       FieldDescriptor fd = (FieldDescriptor) field_it.next();
1883
1884       if (!(fd.isFinal() && fd.isStatic())) {
1885         checkFieldDeclaration(cd, fd);
1886       } else {
1887         // for static final, assign top location by default
1888         Location loc = Location.createTopLocation(cd);
1889         addLocationType(fd.getType(), loc);
1890       }
1891     }
1892   }
1893
1894   private Location checkFieldDeclaration(ClassDescriptor cd, FieldDescriptor fd) {
1895
1896     Vector<AnnotationDescriptor> annotationVec = fd.getType().getAnnotationMarkers();
1897
1898     // currently enforce every field to have corresponding location
1899     if (annotationVec.size() == 0) {
1900       throw new Error("Location is not assigned to the field '" + fd.getSymbol()
1901           + "' of the class " + cd.getSymbol() + " at " + cd.getSourceFileName());
1902     }
1903
1904     if (annotationVec.size() > 1) {
1905       // variable can have at most one location
1906       throw new Error("Field " + fd.getSymbol() + " of class " + cd
1907           + " has more than one location.");
1908     }
1909
1910     AnnotationDescriptor ad = annotationVec.elementAt(0);
1911     Location loc = null;
1912
1913     if (ad.getType() == AnnotationDescriptor.SINGLE_ANNOTATION) {
1914       if (ad.getMarker().equals(SSJavaAnalysis.LOC)) {
1915         String locationID = ad.getValue();
1916         // check if location is defined
1917         SSJavaLattice<String> lattice = ssjava.getClassLattice(cd);
1918         if (lattice == null || (!lattice.containsKey(locationID))) {
1919           throw new Error("Location " + locationID
1920               + " is not defined in the field lattice of class " + cd.getSymbol() + " at"
1921               + cd.getSourceFileName() + ".");
1922         }
1923         loc = new Location(cd, locationID);
1924
1925         if (ssjava.isSharedLocation(loc)) {
1926           ssjava.mapSharedLocation2Descriptor(loc, fd);
1927         }
1928
1929         addLocationType(fd.getType(), loc);
1930
1931       }
1932     }
1933
1934     return loc;
1935   }
1936
1937   private void addLocationType(TypeDescriptor type, CompositeLocation loc) {
1938     if (type != null) {
1939       TypeExtension te = type.getExtension();
1940       SSJavaType ssType;
1941       if (te != null) {
1942         ssType = (SSJavaType) te;
1943         ssType.setCompLoc(loc);
1944       } else {
1945         ssType = new SSJavaType(loc);
1946         type.setExtension(ssType);
1947       }
1948     }
1949   }
1950
1951   private void addLocationType(TypeDescriptor type, Location loc) {
1952     if (type != null) {
1953       type.setExtension(loc);
1954     }
1955   }
1956
1957   static class CompositeLattice {
1958
1959     public static boolean isGreaterThan(CompositeLocation loc1, CompositeLocation loc2, String msg) {
1960
1961       // System.out.println("\nisGreaterThan=" + loc1 + " " + loc2 + " msg=" +
1962       // msg);
1963       int baseCompareResult = compareBaseLocationSet(loc1, loc2, true, false, msg);
1964       if (baseCompareResult == ComparisonResult.EQUAL) {
1965         if (compareDelta(loc1, loc2) == ComparisonResult.GREATER) {
1966           return true;
1967         } else {
1968           return false;
1969         }
1970       } else if (baseCompareResult == ComparisonResult.GREATER) {
1971         return true;
1972       } else {
1973         return false;
1974       }
1975
1976     }
1977
1978     public static int compare(CompositeLocation loc1, CompositeLocation loc2, boolean ignore,
1979         String msg) {
1980
1981       // System.out.println("compare=" + loc1 + " " + loc2);
1982       int baseCompareResult = compareBaseLocationSet(loc1, loc2, false, ignore, msg);
1983
1984       if (baseCompareResult == ComparisonResult.EQUAL) {
1985         return compareDelta(loc1, loc2);
1986       } else {
1987         return baseCompareResult;
1988       }
1989
1990     }
1991
1992     private static int compareDelta(CompositeLocation dLoc1, CompositeLocation dLoc2) {
1993
1994       int deltaCount1 = 0;
1995       int deltaCount2 = 0;
1996       if (dLoc1 instanceof DeltaLocation) {
1997         deltaCount1 = ((DeltaLocation) dLoc1).getNumDelta();
1998       }
1999
2000       if (dLoc2 instanceof DeltaLocation) {
2001         deltaCount2 = ((DeltaLocation) dLoc2).getNumDelta();
2002       }
2003       if (deltaCount1 < deltaCount2) {
2004         return ComparisonResult.GREATER;
2005       } else if (deltaCount1 == deltaCount2) {
2006         return ComparisonResult.EQUAL;
2007       } else {
2008         return ComparisonResult.LESS;
2009       }
2010
2011     }
2012
2013     private static int compareBaseLocationSet(CompositeLocation compLoc1,
2014         CompositeLocation compLoc2, boolean awareSharedLoc, boolean ignore, String msg) {
2015
2016       // if compLoc1 is greater than compLoc2, return true
2017       // else return false;
2018
2019       // compare one by one in according to the order of the tuple
2020       int numOfTie = 0;
2021       for (int i = 0; i < compLoc1.getSize(); i++) {
2022         Location loc1 = compLoc1.get(i);
2023         if (i >= compLoc2.getSize()) {
2024           if (ignore) {
2025             return ComparisonResult.INCOMPARABLE;
2026           } else {
2027             throw new Error("Failed to compare two locations of " + compLoc1 + " and " + compLoc2
2028                 + " because they are not comparable at " + msg);
2029           }
2030         }
2031         Location loc2 = compLoc2.get(i);
2032
2033         Descriptor descriptor = getCommonParentDescriptor(loc1, loc2, msg);
2034         SSJavaLattice<String> lattice = getLatticeByDescriptor(descriptor);
2035
2036         // check if the shared location is appeared only at the end of the
2037         // composite location
2038         if (lattice.getSharedLocSet().contains(loc1.getLocIdentifier())) {
2039           if (i != (compLoc1.getSize() - 1)) {
2040             throw new Error("The shared location " + loc1.getLocIdentifier()
2041                 + " cannot be appeared in the middle of composite location at" + msg);
2042           }
2043         }
2044
2045         if (lattice.getSharedLocSet().contains(loc2.getLocIdentifier())) {
2046           if (i != (compLoc2.getSize() - 1)) {
2047             throw new Error("The shared location " + loc2.getLocIdentifier()
2048                 + " cannot be appeared in the middle of composite location at " + msg);
2049           }
2050         }
2051
2052         // if (!lattice1.equals(lattice2)) {
2053         // throw new Error("Failed to compare two locations of " + compLoc1 +
2054         // " and " + compLoc2
2055         // + " because they are not comparable at " + msg);
2056         // }
2057
2058         if (loc1.getLocIdentifier().equals(loc2.getLocIdentifier())) {
2059           numOfTie++;
2060           // check if the current location is the spinning location
2061           // note that the spinning location only can be appeared in the last
2062           // part of the composite location
2063           if (awareSharedLoc && numOfTie == compLoc1.getSize()
2064               && lattice.getSharedLocSet().contains(loc1.getLocIdentifier())) {
2065             return ComparisonResult.GREATER;
2066           }
2067           continue;
2068         } else if (lattice.isGreaterThan(loc1.getLocIdentifier(), loc2.getLocIdentifier())) {
2069           return ComparisonResult.GREATER;
2070         } else {
2071           return ComparisonResult.LESS;
2072         }
2073
2074       }
2075
2076       if (numOfTie == compLoc1.getSize()) {
2077
2078         if (numOfTie != compLoc2.getSize()) {
2079
2080           if (ignore) {
2081             return ComparisonResult.INCOMPARABLE;
2082           } else {
2083             throw new Error("Failed to compare two locations of " + compLoc1 + " and " + compLoc2
2084                 + " because they are not comparable at " + msg);
2085           }
2086
2087         }
2088
2089         return ComparisonResult.EQUAL;
2090       }
2091
2092       return ComparisonResult.LESS;
2093
2094     }
2095
2096     public static CompositeLocation calculateGLB(Set<CompositeLocation> inputSet, String errMsg) {
2097
2098       System.out.println("Calculating GLB=" + inputSet);
2099       CompositeLocation glbCompLoc = new CompositeLocation();
2100
2101       // calculate GLB of the first(priority) element
2102       Set<String> priorityLocIdentifierSet = new HashSet<String>();
2103       Descriptor priorityDescriptor = null;
2104
2105       Hashtable<String, Set<CompositeLocation>> locId2CompLocSet =
2106           new Hashtable<String, Set<CompositeLocation>>();
2107       // mapping from the priority loc ID to its full representation by the
2108       // composite location
2109
2110       int maxTupleSize = 0;
2111       CompositeLocation maxCompLoc = null;
2112
2113       Location prevPriorityLoc = null;
2114       for (Iterator iterator = inputSet.iterator(); iterator.hasNext();) {
2115         CompositeLocation compLoc = (CompositeLocation) iterator.next();
2116         if (compLoc.getSize() > maxTupleSize) {
2117           maxTupleSize = compLoc.getSize();
2118           maxCompLoc = compLoc;
2119         }
2120         Location priorityLoc = compLoc.get(0);
2121         String priorityLocId = priorityLoc.getLocIdentifier();
2122         priorityLocIdentifierSet.add(priorityLocId);
2123
2124         if (locId2CompLocSet.containsKey(priorityLocId)) {
2125           locId2CompLocSet.get(priorityLocId).add(compLoc);
2126         } else {
2127           Set<CompositeLocation> newSet = new HashSet<CompositeLocation>();
2128           newSet.add(compLoc);
2129           locId2CompLocSet.put(priorityLocId, newSet);
2130         }
2131
2132         // check if priority location are coming from the same lattice
2133         if (priorityDescriptor == null) {
2134           priorityDescriptor = priorityLoc.getDescriptor();
2135         } else {
2136           priorityDescriptor = getCommonParentDescriptor(priorityLoc, prevPriorityLoc, errMsg);
2137         }
2138         prevPriorityLoc = priorityLoc;
2139         // else if (!priorityDescriptor.equals(priorityLoc.getDescriptor())) {
2140         // throw new Error("Failed to calculate GLB of " + inputSet
2141         // + " because they are from different lattices.");
2142         // }
2143       }
2144
2145       SSJavaLattice<String> locOrder = getLatticeByDescriptor(priorityDescriptor);
2146       String glbOfPriorityLoc = locOrder.getGLB(priorityLocIdentifierSet);
2147       glbCompLoc.addLocation(new Location(priorityDescriptor, glbOfPriorityLoc));
2148       Set<CompositeLocation> compSet = locId2CompLocSet.get(glbOfPriorityLoc);
2149
2150       if (compSet == null) {
2151         // when GLB(x1,x2)!=x1 and !=x2 : GLB case 4
2152         // mean that the result is already lower than <x1,y1> and <x2,y2>
2153         // assign TOP to the rest of the location elements
2154
2155         // in this case, do not take care about delta
2156         // CompositeLocation inputComp = inputSet.iterator().next();
2157         for (int i = 1; i < maxTupleSize; i++) {
2158           glbCompLoc.addLocation(Location.createTopLocation(maxCompLoc.get(i).getDescriptor()));
2159         }
2160       } else {
2161
2162         // here find out composite location that has a maximum length tuple
2163         // if we have three input set: [A], [A,B], [A,B,C]
2164         // maximum length tuple will be [A,B,C]
2165         int max = 0;
2166         CompositeLocation maxFromCompSet = null;
2167         for (Iterator iterator = compSet.iterator(); iterator.hasNext();) {
2168           CompositeLocation c = (CompositeLocation) iterator.next();
2169           if (c.getSize() > max) {
2170             max = c.getSize();
2171             maxFromCompSet = c;
2172           }
2173         }
2174
2175         if (compSet.size() == 1) {
2176           // if GLB(x1,x2)==x1 or x2 : GLB case 2,3
2177           CompositeLocation comp = compSet.iterator().next();
2178           for (int i = 1; i < comp.getSize(); i++) {
2179             glbCompLoc.addLocation(comp.get(i));
2180           }
2181
2182           // if input location corresponding to glb is a delta, need to apply
2183           // delta to glb result
2184           if (comp instanceof DeltaLocation) {
2185             glbCompLoc = new DeltaLocation(glbCompLoc, 1);
2186           }
2187
2188         } else {
2189           // when GLB(x1,x2)==x1 and x2 : GLB case 1
2190           // if more than one location shares the same priority GLB
2191           // need to calculate the rest of GLB loc
2192
2193           // setup input set starting from the second tuple item
2194           Set<CompositeLocation> innerGLBInput = new HashSet<CompositeLocation>();
2195           for (Iterator iterator = compSet.iterator(); iterator.hasNext();) {
2196             CompositeLocation compLoc = (CompositeLocation) iterator.next();
2197             CompositeLocation innerCompLoc = new CompositeLocation();
2198             for (int idx = 1; idx < compLoc.getSize(); idx++) {
2199               innerCompLoc.addLocation(compLoc.get(idx));
2200             }
2201             if (innerCompLoc.getSize() > 0) {
2202               innerGLBInput.add(innerCompLoc);
2203             }
2204           }
2205
2206           if (innerGLBInput.size() > 0) {
2207             CompositeLocation innerGLB = CompositeLattice.calculateGLB(innerGLBInput, errMsg);
2208             for (int idx = 0; idx < innerGLB.getSize(); idx++) {
2209               glbCompLoc.addLocation(innerGLB.get(idx));
2210             }
2211           }
2212
2213           // if input location corresponding to glb is a delta, need to apply
2214           // delta to glb result
2215
2216           for (Iterator iterator = compSet.iterator(); iterator.hasNext();) {
2217             CompositeLocation compLoc = (CompositeLocation) iterator.next();
2218             if (compLoc instanceof DeltaLocation) {
2219               if (glbCompLoc.equals(compLoc)) {
2220                 glbCompLoc = new DeltaLocation(glbCompLoc, 1);
2221                 break;
2222               }
2223             }
2224           }
2225
2226         }
2227       }
2228
2229       System.out.println("GLB=" + glbCompLoc + "\n");
2230       return glbCompLoc;
2231
2232     }
2233
2234     static SSJavaLattice<String> getLatticeByDescriptor(Descriptor d) {
2235
2236       SSJavaLattice<String> lattice = null;
2237
2238       if (d instanceof ClassDescriptor) {
2239         lattice = ssjava.getCd2lattice().get(d);
2240       } else if (d instanceof MethodDescriptor) {
2241         if (ssjava.getMd2lattice().containsKey(d)) {
2242           lattice = ssjava.getMd2lattice().get(d);
2243         } else {
2244           // use default lattice for the method
2245           lattice = ssjava.getCd2methodDefault().get(((MethodDescriptor) d).getClassDesc());
2246         }
2247       }
2248
2249       return lattice;
2250     }
2251
2252     static Descriptor getCommonParentDescriptor(Location loc1, Location loc2, String msg) {
2253
2254       Descriptor d1 = loc1.getDescriptor();
2255       Descriptor d2 = loc2.getDescriptor();
2256
2257       Descriptor descriptor;
2258
2259       if (d1 instanceof ClassDescriptor && d2 instanceof ClassDescriptor) {
2260
2261         if (d1.equals(d2)) {
2262           descriptor = d1;
2263         } else {
2264           // identifying which one is parent class
2265           Set<Descriptor> d1SubClassesSet = ssjava.tu.getSubClasses((ClassDescriptor) d1);
2266           Set<Descriptor> d2SubClassesSet = ssjava.tu.getSubClasses((ClassDescriptor) d2);
2267
2268           if (d1 == null && d2 == null) {
2269             throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
2270                 + " because they are not comparable at " + msg);
2271           } else if (d1SubClassesSet != null && d1SubClassesSet.contains(d2)) {
2272             descriptor = d1;
2273           } else if (d2SubClassesSet != null && d2SubClassesSet.contains(d1)) {
2274             descriptor = d2;
2275           } else {
2276             throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
2277                 + " because they are not comparable at " + msg);
2278           }
2279         }
2280
2281       } else if (d1 instanceof MethodDescriptor && d2 instanceof MethodDescriptor) {
2282
2283         if (d1.equals(d2)) {
2284           descriptor = d1;
2285         } else {
2286
2287           // identifying which one is parent class
2288           MethodDescriptor md1 = (MethodDescriptor) d1;
2289           MethodDescriptor md2 = (MethodDescriptor) d2;
2290
2291           if (!md1.matches(md2)) {
2292             throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
2293                 + " because they are not comparable at " + msg);
2294           }
2295
2296           Set<Descriptor> d1SubClassesSet =
2297               ssjava.tu.getSubClasses(((MethodDescriptor) d1).getClassDesc());
2298           Set<Descriptor> d2SubClassesSet =
2299               ssjava.tu.getSubClasses(((MethodDescriptor) d2).getClassDesc());
2300
2301           if (d1 == null && d2 == null) {
2302             throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
2303                 + " because they are not comparable at " + msg);
2304           } else if (d1 != null && d1SubClassesSet.contains(d2)) {
2305             descriptor = d1;
2306           } else if (d2 != null && d2SubClassesSet.contains(d1)) {
2307             descriptor = d2;
2308           } else {
2309             throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
2310                 + " because they are not comparable at " + msg);
2311           }
2312         }
2313
2314       } else {
2315         throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
2316             + " because they are not comparable at " + msg);
2317       }
2318
2319       return descriptor;
2320
2321     }
2322
2323   }
2324
2325   class ComparisonResult {
2326
2327     public static final int GREATER = 0;
2328     public static final int EQUAL = 1;
2329     public static final int LESS = 2;
2330     public static final int INCOMPARABLE = 3;
2331     int result;
2332
2333   }
2334
2335 }
2336
2337 class ReturnLocGenerator {
2338
2339   public static final int PARAMISHIGHER = 0;
2340   public static final int PARAMISSAME = 1;
2341   public static final int IGNORE = 2;
2342
2343   private Hashtable<Integer, Integer> paramIdx2paramType;
2344
2345   private CompositeLocation declaredReturnLoc = null;
2346
2347   public ReturnLocGenerator(CompositeLocation returnLoc, MethodDescriptor md,
2348       List<CompositeLocation> params, String msg) {
2349
2350     CompositeLocation thisLoc = params.get(0);
2351     if (returnLoc.get(0).equals(thisLoc.get(0)) && returnLoc.getSize() > 1) {
2352       // if the declared return location consists of THIS and field location,
2353       // return location for the caller's side has to have same field element
2354       this.declaredReturnLoc = returnLoc;
2355     } else {
2356       // creating mappings
2357       paramIdx2paramType = new Hashtable<Integer, Integer>();
2358       for (int i = 0; i < params.size(); i++) {
2359         CompositeLocation param = params.get(i);
2360         int compareResult = CompositeLattice.compare(param, returnLoc, true, msg);
2361
2362         int type;
2363         if (compareResult == ComparisonResult.GREATER) {
2364           type = 0;
2365         } else if (compareResult == ComparisonResult.EQUAL) {
2366           type = 1;
2367         } else {
2368           type = 2;
2369         }
2370         paramIdx2paramType.put(new Integer(i), new Integer(type));
2371       }
2372     }
2373
2374   }
2375
2376   public CompositeLocation computeReturnLocation(List<CompositeLocation> args) {
2377
2378     if (declaredReturnLoc != null) {
2379       // when developer specify that the return value is [THIS,field]
2380       // needs to translate to the caller's location
2381       CompositeLocation callerLoc = new CompositeLocation();
2382       CompositeLocation callerBaseLocation = args.get(0);
2383
2384       for (int i = 0; i < callerBaseLocation.getSize(); i++) {
2385         callerLoc.addLocation(callerBaseLocation.get(i));
2386       }
2387       for (int i = 1; i < declaredReturnLoc.getSize(); i++) {
2388         callerLoc.addLocation(declaredReturnLoc.get(i));
2389       }
2390       return callerLoc;
2391     } else {
2392       // compute the highest possible location in caller's side
2393       assert paramIdx2paramType.keySet().size() == args.size();
2394
2395       Set<CompositeLocation> inputGLB = new HashSet<CompositeLocation>();
2396       for (int i = 0; i < args.size(); i++) {
2397         int type = (paramIdx2paramType.get(new Integer(i))).intValue();
2398         CompositeLocation argLoc = args.get(i);
2399         if (type == PARAMISHIGHER || type == PARAMISSAME) {
2400           // return loc is equal to or lower than param
2401           inputGLB.add(argLoc);
2402         }
2403       }
2404
2405       // compute GLB of arguments subset that are same or higher than return
2406       // location
2407       if (inputGLB.isEmpty()) {
2408         if (args.size() == 0) {
2409           return null;
2410         }
2411         CompositeLocation rtr =
2412             new CompositeLocation(Location.createTopLocation(args.get(0).get(0).getDescriptor()));
2413         return rtr;
2414       } else {
2415         CompositeLocation glb = CompositeLattice.calculateGLB(inputGLB, "");
2416         return glb;
2417       }
2418     }
2419
2420   }
2421 }