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