KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > soot > toolkits > astmetrics > ConditionComplexityMetric


1 package soot.toolkits.astmetrics;
2
3 import polyglot.ast.Binary;
4 import polyglot.ast.Expr;
5 import polyglot.ast.If;
6 import polyglot.ast.Loop;
7 import polyglot.ast.Node;
8 import polyglot.ast.Unary;
9 import polyglot.visit.NodeVisitor;
10
11 /*
12  * A unary boolean condition should have the complexity (BooleanLit) 1
13  * A noted condition (!) +0.5
14  * A binary relational operation ( < > <= >= == ) +0.5
15  * A boolean logical operator ( AND and OR) +1.0
16  */

17 public class ConditionComplexityMetric extends ASTMetric {
18     int loopComplexity;
19     int ifComplexity;
20     
21     public ConditionComplexityMetric(polyglot.ast.Node node){
22         super(node);
23     }
24     
25     
26     public void reset() {
27         loopComplexity=ifComplexity=0;
28     }
29
30     public void addMetrics(ClassData data) {
31         data.addMetric(new MetricData("Loop-Cond-Complexity",new Integer JavaDoc(loopComplexity)));
32         data.addMetric(new MetricData("If-Cond-Complexity",new Integer JavaDoc(ifComplexity)));
33         data.addMetric(new MetricData("Total-Cond-Complexity",new Integer JavaDoc(loopComplexity+ifComplexity)));
34     }
35
36     public NodeVisitor enter(Node parent, Node n){
37         if(n instanceof Loop){
38             Expr expr = ((Loop)n).cond();
39             loopComplexity += condComplexity(expr);
40         }
41         else if (n instanceof If){
42             Expr expr = ((If)n).cond();
43             ifComplexity += condComplexity(expr);
44         }
45         
46         return enter(n);
47     }
48     
49     private double condComplexity(Expr expr){
50
51         //boolean literal
52
//binary check for AND and OR ... else its relational!!
53
//unary (Check for NOT)
54

55         if(expr instanceof Binary){
56             Binary b = (Binary)expr;
57             if( b.operator() == Binary.COND_AND || b.operator() == Binary.COND_OR){
58                 //System.out.println(">>>>>>>> Binary (AND or OR) "+expr);
59
return 1.0 + condComplexity(b.left()) + condComplexity(b.right());
60             }
61             else{
62                 //System.out.println(">>>>>>>> Binary (relatinal) "+expr);
63
return 0.5 + condComplexity(b.left()) + condComplexity(b.right());
64             }
65         }
66         else if(expr instanceof Unary){
67             if(((Unary)expr).operator() == Unary.NOT){
68                 //System.out.println(">>>>>>>>>>>>>>Unary: !"+expr);
69
return 0.5 + condComplexity(((Unary)expr).expr());
70             }
71             else{
72                 //System.out.println(">>>>>>>>>>>>>>unary but Not ! "+expr);
73
return condComplexity(((Unary)expr).expr());
74             }
75         }
76         else
77             return 1;//should return something as it is a condition after all
78
}
79
80 }
81
Popular Tags