1 package com.puppycrawl.tools.checkstyle.checks.coding; 20 21 import com.puppycrawl.tools.checkstyle.api.DetailAST; 22 import com.puppycrawl.tools.checkstyle.api.TokenTypes; 23 24 import com.puppycrawl.tools.checkstyle.checks.AbstractFormatCheck; 25 26 import java.util.Stack ; 27 28 41 public final class ReturnCountCheck extends AbstractFormatCheck 42 { 43 44 private static final int DEFAULT_MAX = 2; 45 46 47 private final Stack mContextStack = new Stack (); 48 49 private int mMax; 50 51 private Context mContext; 52 53 54 public ReturnCountCheck() 55 { 56 super("^equals$"); 57 setMax(DEFAULT_MAX); 58 } 59 60 61 public int[] getDefaultTokens() 62 { 63 return new int[] { 64 TokenTypes.CTOR_DEF, 65 TokenTypes.METHOD_DEF, 66 TokenTypes.LITERAL_RETURN, 67 }; 68 } 69 70 71 public int[] getRequiredTokens() 72 { 73 return new int[]{ 74 TokenTypes.CTOR_DEF, 75 TokenTypes.METHOD_DEF, 76 }; 77 } 78 79 83 public int getMax() 84 { 85 return mMax; 86 } 87 88 92 public void setMax(int aMax) 93 { 94 mMax = aMax; 95 } 96 97 98 public void beginTree(DetailAST aRootAST) 99 { 100 mContext = null; 101 mContextStack.clear(); 102 } 103 104 105 public void visitToken(DetailAST aAST) 106 { 107 switch (aAST.getType()) { 108 case TokenTypes.CTOR_DEF: 109 case TokenTypes.METHOD_DEF: 110 visitMethodDef(aAST); 111 break; 112 case TokenTypes.LITERAL_RETURN: 113 mContext.visitLiteralReturn(); 114 break; 115 default: 116 throw new IllegalStateException (aAST.toString()); 117 } 118 } 119 120 121 public void leaveToken(DetailAST aAST) 122 { 123 switch (aAST.getType()) { 124 case TokenTypes.CTOR_DEF: 125 case TokenTypes.METHOD_DEF: 126 leaveMethodDef(aAST); 127 break; 128 case TokenTypes.LITERAL_RETURN: 129 break; 131 default: 132 throw new IllegalStateException (aAST.toString()); 133 } 134 } 135 136 140 private void visitMethodDef(DetailAST aAST) 141 { 142 mContextStack.push(mContext); 143 final DetailAST methodNameAST = aAST.findFirstToken(TokenTypes.IDENT); 144 mContext = 145 new Context(!getRegexp().matcher(methodNameAST.getText()).find()); 146 } 147 148 153 private void leaveMethodDef(DetailAST aAST) 154 { 155 mContext.checkCount(aAST); 156 mContext = (Context) mContextStack.pop(); 157 } 158 159 163 private class Context 164 { 165 166 private final boolean mChecking; 167 168 private int mCount; 169 170 174 public Context(boolean aChecking) 175 { 176 mChecking = aChecking; 177 mCount = 0; 178 } 179 180 181 public void visitLiteralReturn() 182 { 183 ++mCount; 184 } 185 186 191 public void checkCount(DetailAST aAST) 192 { 193 if (mChecking && (mCount > getMax())) { 194 log(aAST.getLineNo(), aAST.getColumnNo(), "return.count", 195 new Integer (mCount), new Integer (getMax())); 196 } 197 } 198 } 199 } 200 | Popular Tags |