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