1 package com.puppycrawl.tools.checkstyle.checks; 20 21 import java.util.regex.Matcher ; 22 import java.util.regex.Pattern ; 23 24 import com.puppycrawl.tools.checkstyle.api.DetailAST; 25 26 49 public class GenericIllegalRegexpCheck extends AbstractFormatCheck 50 { 51 55 private String mMessage = ""; 56 57 58 private boolean mIgnoreComments; 59 60 65 66 public void setMessage(String aMessage) 67 { 68 if (aMessage == null) { 69 aMessage = ""; 70 } 71 mMessage = aMessage; 72 } 73 74 79 public String getMessage() 80 { 81 return mMessage; 82 } 83 84 88 public void setIgnoreCase(boolean aCaseInsensitive) 89 { 90 if (aCaseInsensitive) { 91 setCompileFlags(Pattern.CASE_INSENSITIVE); 92 } 93 } 94 95 99 public void setIgnoreComments(boolean aIgnoreComments) 100 { 101 mIgnoreComments = aIgnoreComments; 102 } 103 104 107 public GenericIllegalRegexpCheck() 108 { 109 super("$^"); } 111 112 113 public int[] getDefaultTokens() 114 { 115 return new int[0]; 116 } 117 118 119 public void beginTree(DetailAST aRootAST) 120 { 121 final String [] lines = getLines(); 122 123 for (int i = 0; i < lines.length; i++) { 124 125 final String line = lines[i]; 126 final boolean foundMatch; 127 if (mIgnoreComments) { 128 foundMatch = findNonCommentMatch(line, i + 1, 0); 129 } 130 else { 131 foundMatch = getRegexp().matcher(line).find(); 132 } 133 if (foundMatch) { 134 if ("".equals(mMessage)) { 135 log(i + 1, "illegal.regexp", getFormat()); 136 } 137 else { 138 log(i + 1, mMessage); 139 } 140 } 141 } 142 } 143 144 151 private boolean findNonCommentMatch( 152 String aLine, int aLineNumber, int aStartPosition) 153 { 154 final Pattern pattern = getRegexp(); 155 final Matcher matcher = pattern.matcher(aLine); 156 final boolean foundMatch = matcher.find(aStartPosition); 157 if (!foundMatch) { 158 return false; 159 } 160 final int startCol = matcher.start(0); 162 final int endCol = matcher.end(0); 163 final boolean intersectsWithComment = getFileContents() 168 .hasIntersectionWithComment(aLineNumber, startCol, 169 aLineNumber, endCol - 1); 170 if (intersectsWithComment) { 171 if (endCol < aLine.length()) { 172 return findNonCommentMatch(aLine, aLineNumber, endCol); 174 } 175 return false; 177 } 178 return true; 180 } 181 } 182 | Popular Tags |