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