1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package com.puppycrawl.tools.checkstyle.checks.metrics;
20
21 import com.puppycrawl.tools.checkstyle.api.Check;
22 import com.puppycrawl.tools.checkstyle.api.DetailAST;
23 import com.puppycrawl.tools.checkstyle.api.FastStack;
24 import com.puppycrawl.tools.checkstyle.api.TokenTypes;
25 import java.math.BigInteger;
26
27
28
29
30
31
32
33 public abstract class AbstractComplexityCheck
34 extends Check
35 {
36
37 private static final BigInteger INITIAL_VALUE = BigInteger.ONE;
38
39
40 private final FastStack<BigInteger> valueStack = FastStack.newInstance();
41
42
43 private BigInteger currentValue = BigInteger.ZERO;
44
45
46 private int max;
47
48
49
50
51
52 public AbstractComplexityCheck(int max)
53 {
54 this.max = max;
55 }
56
57
58
59
60 protected abstract String getMessageID();
61
62
63
64
65
66
67
68 protected void visitTokenHook(DetailAST ast)
69 {
70 }
71
72
73
74
75
76
77
78 protected void leaveTokenHook(DetailAST ast)
79 {
80 }
81
82 @Override
83 public final int[] getRequiredTokens()
84 {
85 return new int[] {
86 TokenTypes.CTOR_DEF,
87 TokenTypes.METHOD_DEF,
88 TokenTypes.INSTANCE_INIT,
89 TokenTypes.STATIC_INIT,
90 };
91 }
92
93
94 public final int getMax()
95 {
96 return max;
97 }
98
99
100
101
102
103
104 public final void setMax(int max)
105 {
106 this.max = max;
107 }
108
109 @Override
110 public void visitToken(DetailAST ast)
111 {
112 switch (ast.getType()) {
113 case TokenTypes.CTOR_DEF:
114 case TokenTypes.METHOD_DEF:
115 case TokenTypes.INSTANCE_INIT:
116 case TokenTypes.STATIC_INIT:
117 visitMethodDef();
118 break;
119 default:
120 visitTokenHook(ast);
121 }
122 }
123
124 @Override
125 public void leaveToken(DetailAST ast)
126 {
127 switch (ast.getType()) {
128 case TokenTypes.CTOR_DEF:
129 case TokenTypes.METHOD_DEF:
130 case TokenTypes.INSTANCE_INIT:
131 case TokenTypes.STATIC_INIT:
132 leaveMethodDef(ast);
133 break;
134 default:
135 leaveTokenHook(ast);
136 }
137 }
138
139
140
141
142 protected final BigInteger getCurrentValue()
143 {
144 return currentValue;
145 }
146
147
148
149
150
151 protected final void setCurrentValue(BigInteger value)
152 {
153 currentValue = value;
154 }
155
156
157
158
159
160
161 protected final void incrementCurrentValue(BigInteger by)
162 {
163 setCurrentValue(getCurrentValue().add(by));
164 }
165
166
167 protected final void pushValue()
168 {
169 valueStack.push(currentValue);
170 currentValue = INITIAL_VALUE;
171 }
172
173
174
175
176 protected final BigInteger popValue()
177 {
178 currentValue = valueStack.pop();
179 return currentValue;
180 }
181
182
183 private void visitMethodDef()
184 {
185 pushValue();
186 }
187
188
189
190
191
192
193 private void leaveMethodDef(DetailAST ast)
194 {
195 final BigInteger bigIntegerMax = BigInteger.valueOf(max);
196 if (currentValue.compareTo(bigIntegerMax) > 0) {
197 log(ast, getMessageID(), currentValue, bigIntegerMax);
198 }
199 popValue();
200 }
201 }