Debian Codegraph @

net/sf/saxon/regex/ARegexIterator.java

raw symbols SCIP
1 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2 // Copyright (c) 2018 Saxonica Limited.
3 // This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
4 // If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
5 // This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0.
6 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
7
8 package net.sf.saxon.regex;
9
10 import net.sf.saxon.expr.LastPositionFinder;
11 import net.sf.saxon.trans.SaxonErrorCode;
12 import net.sf.saxon.trans.XPathException;
13 import net.sf.saxon.tree.util.FastStringBuffer;
14 import net.sf.saxon.value.StringValue;
15 import net.sf.saxon.z.IntHashMap;
16 import net.sf.saxon.z.IntToIntHashMap;
17
18 import java.util.ArrayList;
19 import java.util.List;
20
21 /**
22 * Class ARegexIterator - provides an iterator over matched and unmatched substrings.
23 * This implementation of RegexIterator uses the modified Jakarta regular expression engine.
24 */
25
26 public class ARegexIterator implements RegexIterator, LastPositionFinder {
27
28 private UnicodeString theString; // the input string being matched
29 private UnicodeString regex;
30 private REMatcher matcher; // the Matcher object that does the matching, and holds the state
31 private UnicodeString current; // the string most recently returned by the iterator
32 private UnicodeString next; // if the last string was a matching string, null; otherwise the next substring
33 // matched by the regex
34 private int prevEnd = 0; // the position in the input string of the end of the last match or non-match
35 private IntToIntHashMap nestingTable = null;
36 // evaluated on demand: a table that indicates for each captured group,
37 // what its immediately-containing captured group is.
38 private boolean skip = false; // indicates the last match was zero length
39
40 /**
41 * Construct a RegexIterator. Note that the underlying matcher.find() method is called once
42 * to obtain each matching substring. But the iterator also returns non-matching substrings
43 * if these appear between the matching substrings.
44 *
45 * @param string the string to be analysed
46 * @param matcher a matcher for the regular expression
47 */
48
49 public ARegexIterator(UnicodeString string, UnicodeString regex, REMatcher matcher) {
50 theString = string;
51 this.regex = regex;
52 this.matcher = matcher;
53 next = null;
54 }
55
56 @Override
57 public int getLength() throws XPathException {
58 ARegexIterator another = new ARegexIterator(theString, regex, new REMatcher(matcher.getProgram()));
59 int n = 0;
60 while (another.next() != null) {
61 n++;
62 }
63 return n;
64 }
65
66 /**
67 * Get the next item in the sequence
68 *
69 * @return the next item in the sequence
70 */
71
72 public StringValue next() throws XPathException {
73 try {
74 if (next == null && prevEnd >= 0) {
75 // we've returned a match (or we're at the start), so find the next match
76 int searchStart = prevEnd;
77 if (skip) {
78 // previous match was zero-length
79 searchStart++;
80 if (searchStart >= theString.uLength()) {
81 if (prevEnd < theString.uLength()) {
82 current = theString.uSubstring(prevEnd, theString.uLength());
83 next = null;
84 } else {
85 current = null;
86 prevEnd = -1;
87 return null;
88 }
89 }
90 }
91 if (matcher.match(theString, searchStart)) {
92 int start = matcher.getParenStart(0);
93 int end = matcher.getParenEnd(0);
94 skip = start == end;
95 if (prevEnd == start) {
96 // there's no intervening non-matching string to return
97 next = null;
98 current = theString.uSubstring(start, end);
99 prevEnd = end;
100 } else {
101 // return the non-matching substring first
102 current = theString.uSubstring(prevEnd, start);
103 next = theString.uSubstring(start, end);
104 }
105 } else {
106 // there are no more regex matches, we must return the final non-matching text if any
107 if (prevEnd < theString.uLength()) {
108 current = theString.uSubstring(prevEnd, theString.uLength());
109 next = null;
110 } else {
111 // this really is the end...
112 current = null;
113 prevEnd = -1;
114 return null;
115 }
116 prevEnd = -1;
117 }
118 } else {
119 // we've returned a non-match, so now return the match that follows it, if there is one
120 if (prevEnd >= 0) {
121 current = next;
122 next = null;
123 prevEnd = matcher.getParenEnd(0);
124 } else {
125 current = null;
126 return null;
127 }
128 }
129 return currentStringValue();
130 } catch (StackOverflowError e) {
131 XPathException xe = new XPathException("Stack overflow (excessive recursion) during regular expression evaluation");
132 xe.setErrorCode(SaxonErrorCode.SXRE0001);
133 throw xe;
134 }
135 }
136
137 private StringValue currentStringValue() {
138 return StringValue.makeStringValue(current);
139 }
140
141
142 /**
143 * Get properties of this iterator, as a bit-significant integer.
144 *
145 * @return the properties of this iterator. This will be some combination of
146 * properties such as {@link #GROUNDED}, {@link #LAST_POSITION_FINDER},
147 * and {@link #LOOKAHEAD}. It is always
148 * acceptable to return the value zero, indicating that there are no known special properties.
149 * It is acceptable for the properties of the iterator to change depending on its state.
150 */
151
152 public int getProperties() {
153 return LAST_POSITION_FINDER;
154 }
155
156 /**
157 * Determine whether the current item is a matching item or a non-matching item
158 *
159 * @return true if the current item (the one most recently returned by next()) is
160 * an item that matches the regular expression, or false if it is an item that
161 * does not match
162 */
163
164 public boolean isMatching() {
165 return next == null && prevEnd >= 0;
166 }
167
168 /**
169 * Get a substring that matches a parenthesised group within the regular expression
170 *
171 * @param number the number of the group to be obtained
172 * @return the substring of the current item that matches the n'th parenthesized group
173 * within the regular expression
174 */
175
176 public String getRegexGroup(int number) {
177 if (!isMatching()) {
178 return null;
179 }
180 if (number >= matcher.getParenCount() || number < 0) return "";
181 UnicodeString us = matcher.getParen(number);
182 return (us == null ? "" : us.toString());
183 }
184
185 /**
186 * Get the number of captured groups
187 */
188 @Override
189 public int getNumberOfGroups() {
190 return matcher.getParenCount();
191 }
192
193 /**
194 * Process a matching substring, performing specified actions at the start and end of each captured
195 * subgroup. This method will always be called when operating in "push" mode; it writes its
196 * result to context.getReceiver(). The matching substring text is all written to the receiver,
197 * interspersed with calls to the {@link net.sf.saxon.regex.RegexIterator.MatchHandler} methods onGroupStart() and onGroupEnd().
198 *
199 * @param action defines the processing to be performed at the start and end of a group
200 */
201
202 public void processMatchingSubstring(MatchHandler action) throws XPathException {
203 int c = matcher.getParenCount() - 1;
204 if (c == 0) {
205 action.characters(current.toString());
206 } else {
207 // Create a map from positions in the string to lists of actions.
208 // The "actions" in each list are: +N: start group N; -N: end group N.
209 IntHashMap<List<Integer>> actions = new IntHashMap<List<Integer>>(c);
210 for (int i = 1; i <= c; i++) {
211 int start = matcher.getParenStart(i) - matcher.getParenStart(0);
212 if (start != -1) {
213 int end = matcher.getParenEnd(i) - matcher.getParenStart(0);
214 if (start < end) {
215 // Add the start action after all other actions on the list for the same position
216 List<Integer> s = actions.get(start);
217 if (s == null) {
218 s = new ArrayList<Integer>(4);
219 actions.put(start, s);
220 }
221 s.add(i);
222 // Add the end action before all other actions on the list for the same position
223 List<Integer> e = actions.get(end);
224 if (e == null) {
225 e = new ArrayList<Integer>(4);
226 actions.put(end, e);
227 }
228 e.add(0, -i);
229 } else {
230 // zero-length group (start==end). The problem here is that the information available
231 // from Java isn't sufficient to determine the nesting of groups: match("a", "(a(b?))")
232 // and match("a", "(a)(b?)") will both give the same result for group 2 (start=1, end=1).
233 // So we need to go back to the original regex to determine the group nesting
234 if (nestingTable == null) {
235 nestingTable = computeNestingTable(regex);
236 }
237 int parentGroup = nestingTable.get(i);
238 // insert the start and end events immediately before the end event for the parent group,
239 // if present; otherwise after all existing events for this position
240 List<Integer> s = actions.get(start);
241 if (s == null) {
242 s = new ArrayList<Integer>(4);
243 actions.put(start, s);
244 s.add(i);
245 s.add(-i);
246 } else {
247 int pos = s.size();
248 for (int e = 0; e < s.size(); e++) {
249 if (s.get(e) == -parentGroup) {
250 pos = e;
251 break;
252 }
253 }
254 s.add(pos, -i);
255 s.add(pos, i);
256 }
257
258 }
259 }
260
261 }
262 FastStringBuffer buff = new FastStringBuffer(current.uLength());
263 for (int i = 0; i < current.uLength() + 1; i++) {
264 List<Integer> events = actions.get(i);
265 if (events != null) {
266 if (buff.length() > 0) {
267 action.characters(buff);
268 buff.setLength(0);
269 }
270 for (Integer group : events) {
271 if (group > 0) {
272 action.onGroupStart(group);
273 } else {
274 action.onGroupEnd(-group);
275 }
276 }
277 }
278 if (i < current.uLength()) {
279 buff.appendWideChar(current.uCharAt(i));
280 }
281 }
282 if (buff.length() > 0) {
283 action.characters(buff);
284 }
285 }
286
287 }
288
289 /**
290 * Compute a table showing for each captured group number (opening paren in the regex),
291 * the number of its parent group. This is done by reparsing the source of the regular
292 * expression. This is needed when the result of a match includes an empty group, to determine
293 * its position relative to other groups finishing at the same character position.
294 */
295
296 public static IntToIntHashMap computeNestingTable(UnicodeString regex) {
297 // See bug 3211
298 IntToIntHashMap nestingTable = new IntToIntHashMap(16);
299 int[] stack = new int[regex.uLength()];
300 int tos = 0;
301 boolean[] captureStack = new boolean[regex.uLength()];
302 int captureTos = 0;
303 int group = 1;
304 int inBrackets = 0;
305 stack[tos++] = 0;
306 for (int i = 0; i < regex.uLength(); i++) {
307 int ch = regex.uCharAt(i);
308 if (ch == '\\') {
309 i++;
310 } else if (ch == '[') {
311 inBrackets++;
312 } else if (ch == ']') {
313 inBrackets--;
314 } else if (ch == '(' && inBrackets == 0) {
315 boolean capture = regex.uCharAt(i + 1) != '?';
316 captureStack[captureTos++] = capture;
317 if (capture) {
318 nestingTable.put(group, stack[tos - 1]);
319 stack[tos++] = group++;
320 }
321 } else if (ch == ')' && inBrackets == 0) {
322 boolean capture = captureStack[--captureTos];
323 if (capture) {
324 tos--;
325 }
326 }
327 }
328 return nestingTable;
329 }
330
331
332 }
333