1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package com.puppycrawl.tools.checkstyle.checks.regexp;
21
22 import java.util.regex.Matcher;
23
24 import com.puppycrawl.tools.checkstyle.api.FileText;
25 import com.puppycrawl.tools.checkstyle.api.LineColumn;
26
27
28
29
30 class MultilineDetector {
31
32
33
34
35
36 public static final String MSG_REGEXP_EXCEEDED = "regexp.exceeded";
37
38
39
40
41
42 public static final String MSG_REGEXP_MINIMUM = "regexp.minimum";
43
44
45
46
47
48 public static final String MSG_EMPTY = "regexp.empty";
49
50
51
52
53 public static final String MSG_STACKOVERFLOW = "regexp.StackOverflowError";
54
55
56 private final DetectorOptions options;
57
58 private int currentMatches;
59
60 private Matcher matcher;
61
62 private FileText text;
63
64
65
66
67
68
69 MultilineDetector(DetectorOptions options) {
70 this.options = options;
71 }
72
73
74
75
76
77
78 public void processLines(FileText fileText) {
79 text = new FileText(fileText);
80 resetState();
81
82 final String format = options.getFormat();
83 if (format == null || format.isEmpty()) {
84 options.getReporter().log(1, MSG_EMPTY);
85 }
86 else {
87 matcher = options.getPattern().matcher(fileText.getFullText());
88 findMatch();
89 finish();
90 }
91 }
92
93
94 private void findMatch() {
95 try {
96 boolean foundMatch = matcher.find();
97
98 while (foundMatch) {
99 currentMatches++;
100 if (currentMatches > options.getMaximum()) {
101 final LineColumn start = text.lineColumn(matcher.start());
102 if (options.getMessage().isEmpty()) {
103 options.getReporter().log(start.getLine(),
104 MSG_REGEXP_EXCEEDED, matcher.pattern().toString());
105 }
106 else {
107 options.getReporter()
108 .log(start.getLine(), options.getMessage());
109 }
110 }
111 foundMatch = matcher.find();
112 }
113 }
114
115 catch (StackOverflowError ignored) {
116
117
118
119 options.getReporter().log(1, MSG_STACKOVERFLOW, matcher.pattern().toString());
120 }
121 }
122
123
124 private void finish() {
125 if (currentMatches < options.getMinimum()) {
126 if (options.getMessage().isEmpty()) {
127 options.getReporter().log(1, MSG_REGEXP_MINIMUM,
128 options.getMinimum(), options.getFormat());
129 }
130 else {
131 options.getReporter().log(1, options.getMessage());
132 }
133 }
134 }
135
136
137
138
139 private void resetState() {
140 currentMatches = 0;
141 }
142
143 }