Debian Codegraph @

mcs/class/referencesource/System/regex/system/text/regularexpressions/RegexRunner.cs

raw
1 //------------------------------------------------------------------------------
2 // <copyright file="RegexRunner.cs" company="Microsoft">
3 // Copyright (c) Microsoft Corporation. All rights reserved.
4 // </copyright>
5 //------------------------------------------------------------------------------
6
7 // This RegexRunner class is a base class for compiled regex code.
8
9 // Implementation notes:
10 //
11 // RegexRunner provides a common calling convention and a common
12 // runtime environment for the interpreter and the compiled code.
13 //
14 // It provides the driver code that call's the subclass's Go()
15 // method for either scanning or direct execution.
16 //
17 // It also maintains memory allocation for the backtracking stack,
18 // the grouping stack and the longjump crawlstack, and provides
19 // methods to push new subpattern match results into (or remove
20 // backtracked results from) the Match instance.
21
22
23 namespace System.Text.RegularExpressions {
24
25 using System.Collections;
26 using System.Diagnostics;
27 using System.ComponentModel;
28 using System.Globalization;
29
30 /// <internalonly/>
31
32 //
33
34
35
36
37 #if !SILVERLIGHT
38 [EditorBrowsable(EditorBrowsableState.Never)]
39 #endif
40 #if !SILVERLIGHT
41 abstract public class RegexRunner {
42 #else
43 abstract internal class RegexRunner {
44 #endif
45 protected internal int runtextbeg; // beginning of text to search
46 protected internal int runtextend; // end of text to search
47 protected internal int runtextstart; // starting point for search
48
49 protected internal String runtext; // text to search
50 protected internal int runtextpos; // current position in text
51
52 protected internal int [] runtrack; // The backtracking stack. Opcodes use this to store data regarding
53 protected internal int runtrackpos; // what they have matched and where to backtrack to. Each "frame" on
54 // the stack takes the form of [CodePosition Data1 Data2...], where
55 // CodePosition is the position of the current opcode and
56 // the data values are all optional. The CodePosition can be negative, and
57 // these values (also called "back2") are used by the BranchMark family of opcodes
58 // to indicate whether they are backtracking after a successful or failed
59 // match.
60 // When we backtrack, we pop the CodePosition off the stack, set the current
61 // instruction pointer to that code position, and mark the opcode
62 // with a backtracking flag ("Back"). Each opcode then knows how to
63 // handle its own data.
64
65 protected internal int [] runstack; // This stack is used to track text positions across different opcodes.
66 protected internal int runstackpos; // For example, in /(a*b)+/, the parentheses result in a SetMark/CaptureMark
67 // pair. SetMark records the text position before we match a*b. Then
68 // CaptureMark uses that position to figure out where the capture starts.
69 // Opcodes which push onto this stack are always paired with other opcodes
70 // which will pop the value from it later. A successful match should mean
71 // that this stack is empty.
72
73 protected internal int [] runcrawl; // The crawl stack is used to keep track of captures. Every time a group
74 protected internal int runcrawlpos; // has a capture, we push its group number onto the runcrawl stack. In
75 // the case of a balanced match, we push BOTH groups onto the stack.
76
77 protected internal int runtrackcount; // count of states that may do backtracking
78
79 protected internal Match runmatch; // result object
80 protected internal Regex runregex; // regex object
81
82 private Int32 timeout; // timeout in millisecs (needed for actual)
83 private bool ignoreTimeout;
84 private Int32 timeoutOccursAt;
85
86
87 // GPaperin: We have determined this value in a series of experiments where x86 retail
88 // builds (ono-lab-optimised) were run on different pattern/input pairs. Larger values
89 // of TimeoutCheckFrequency did not tend to increase performance; smaller values
90 // of TimeoutCheckFrequency tended to slow down the execution.
91 private const int TimeoutCheckFrequency = 1000;
92 private int timeoutChecksToSkip;
93
94 protected internal RegexRunner() { }
95
96 /*
97 * Scans the string to find the first match. Uses the Match object
98 * both to feed text in and as a place to store matches that come out.
99 *
100 * All the action is in the abstract Go() method defined by subclasses. Our
101 * responsibility is to load up the class members (as done here) before
102 * calling Go.
103 *
104 * <
105
106
107
108
109 */
110 protected internal Match Scan(Regex regex, String text, int textbeg, int textend, int textstart, int prevlen, bool quick) {
111 return Scan(regex, text, textbeg, textend, textstart, prevlen, quick, regex.MatchTimeout);
112 }
113
114 #if !SILVERLIGHT
115 protected internal
116 #else
117 internal
118 #endif
119 Match Scan(Regex regex, String text, int textbeg, int textend, int textstart, int prevlen, bool quick, TimeSpan timeout) {
120
121 int bump;
122 int stoppos;
123 bool initted = false;
124
125 // We need to re-validate timeout here because Scan is historically protected and
126 // thus there is a possibility it is called from user code:
127 Regex.ValidateMatchTimeout(timeout);
128
129 this.ignoreTimeout = (Regex.InfiniteMatchTimeout == timeout);
130 this.timeout = this.ignoreTimeout
131 ? (Int32) Regex.InfiniteMatchTimeout.TotalMilliseconds
132 : (Int32) (timeout.TotalMilliseconds + 0.5); // Round
133
134 runregex = regex;
135 runtext = text;
136 runtextbeg = textbeg;
137 runtextend = textend;
138 runtextstart = textstart;
139
140 bump = runregex.RightToLeft ? -1 : 1;
141 stoppos = runregex.RightToLeft ? runtextbeg : runtextend;
142
143 runtextpos = textstart;
144
145 // If previous match was empty or failed, advance by one before matching
146
147 if (prevlen == 0) {
148 if (runtextpos == stoppos)
149 return Match.Empty;
150
151 runtextpos += bump;
152 }
153
154 StartTimeoutWatch();
155
156 for (; ; ) {
157
158 #if DBG
159 if (runregex.Debug) {
160 Debug.WriteLine("");
161 Debug.WriteLine("Search range: from " + runtextbeg.ToString(CultureInfo.InvariantCulture) + " to " + runtextend.ToString(CultureInfo.InvariantCulture));
162 Debug.WriteLine("Firstchar search starting at " + runtextpos.ToString(CultureInfo.InvariantCulture) + " stopping at " + stoppos.ToString(CultureInfo.InvariantCulture));
163 }
164 #endif
165 if (FindFirstChar()) {
166
167 CheckTimeout();
168
169 if (!initted) {
170 InitMatch();
171 initted = true;
172 }
173 #if DBG
174 if (runregex.Debug) {
175 Debug.WriteLine("Executing engine starting at " + runtextpos.ToString(CultureInfo.InvariantCulture));
176 Debug.WriteLine("");
177 }
178 #endif
179 Go();
180
181 if (runmatch._matchcount [0] > 0) {
182 // <
183 return TidyMatch(quick);
184 }
185
186 // reset state for another go
187 runtrackpos = runtrack.Length;
188 runstackpos = runstack.Length;
189 runcrawlpos = runcrawl.Length;
190 }
191
192 // failure!
193
194 if (runtextpos == stoppos) {
195 TidyMatch(true);
196 return Match.Empty;
197 }
198
199 // <
200
201 // Bump by one and start again
202
203 runtextpos += bump;
204 }
205
206 // We never get here
207 }
208
209 private void StartTimeoutWatch() {
210
211 if (ignoreTimeout)
212 return;
213
214 timeoutChecksToSkip = TimeoutCheckFrequency;
215
216 // We are using Environment.TickCount and not Timewatch for performance reasons.
217 // Environment.TickCount is an int that cycles. We intentionally let timeoutOccursAt
218 // overflow it will still stay ahead of Environment.TickCount for comparisons made
219 // in DoCheckTimeout():
220 unchecked {
221 timeoutOccursAt = Environment.TickCount + timeout;
222 }
223 }
224
225 #if !SILVERLIGHT
226 protected
227 #else
228 internal
229 #endif
230 void CheckTimeout() {
231
232 if (ignoreTimeout)
233 return;
234
235 if (--timeoutChecksToSkip != 0)
236 return;
237
238 timeoutChecksToSkip = TimeoutCheckFrequency;
239 DoCheckTimeout();
240 }
241
242 private void DoCheckTimeout() {
243
244 // Note that both, Environment.TickCount and timeoutOccursAt are ints and can overflow and become negative.
245 // See the comment in StartTimeoutWatch().
246
247 int currentMillis = Environment.TickCount;
248
249 if (currentMillis < timeoutOccursAt)
250 return;
251
252 if (0 > timeoutOccursAt && 0 < currentMillis)
253 return;
254
255 #if DBG
256 if (runregex.Debug) {
257 Debug.WriteLine("");
258 Debug.WriteLine("RegEx match timeout occurred!");
259 Debug.WriteLine("Specified timeout: " + TimeSpan.FromMilliseconds(timeout).ToString());
260 Debug.WriteLine("Timeout check frequency: " + TimeoutCheckFrequency);
261 Debug.WriteLine("Search pattern: " + runregex.pattern);
262 Debug.WriteLine("Input: " + runtext);
263 Debug.WriteLine("About to throw RegexMatchTimeoutException.");
264 }
265 #endif
266
267 throw new RegexMatchTimeoutException(runtext, runregex.pattern, TimeSpan.FromMilliseconds(timeout));
268 }
269
270 /*
271 * The responsibility of Go() is to run the regular expression at
272 * runtextpos and call Capture() on all the captured subexpressions,
273 * then to leave runtextpos at the ending position. It should leave
274 * runtextpos where it started if there was no match.
275 */
276 protected abstract void Go();
277
278 /*
279 * The responsibility of FindFirstChar() is to advance runtextpos
280 * until it is at the next position which is a candidate for the
281 * beginning of a successful match.
282 */
283 protected abstract bool FindFirstChar();
284
285 /*
286 * InitTrackCount must initialize the runtrackcount field; this is
287 * used to know how large the initial runtrack and runstack arrays
288 * must be.
289 */
290 protected abstract void InitTrackCount();
291
292 /*
293 * Initializes all the data members that are used by Go()
294 */
295 private void InitMatch() {
296 // Use a hashtable'ed Match object if the capture numbers are sparse
297
298 if (runmatch == null) {
299 if (runregex.caps != null)
300 runmatch = new MatchSparse(runregex, runregex.caps, runregex.capsize, runtext, runtextbeg, runtextend - runtextbeg, runtextstart);
301 else
302 runmatch = new Match (runregex, runregex.capsize, runtext, runtextbeg, runtextend - runtextbeg, runtextstart);
303 } else {
304 runmatch.Reset(runregex, runtext, runtextbeg, runtextend, runtextstart);
305 }
306
307 // note we test runcrawl, because it is the last one to be allocated
308 // If there is an alloc failure in the middle of the three allocations,
309 // we may still return to reuse this instance, and we want to behave
310 // as if the allocations didn't occur. (we used to test _trackcount != 0)
311
312 if (runcrawl != null) {
313 runtrackpos = runtrack.Length;
314 runstackpos = runstack.Length;
315 runcrawlpos = runcrawl.Length;
316 return;
317 }
318
319 InitTrackCount();
320
321 int tracksize = runtrackcount * 8;
322 int stacksize = runtrackcount * 8;
323
324 if (tracksize < 32)
325 tracksize = 32;
326 if (stacksize < 16)
327 stacksize = 16;
328
329 runtrack = new int [tracksize];
330 runtrackpos = tracksize;
331
332 runstack = new int [stacksize];
333 runstackpos = stacksize;
334
335 runcrawl = new int [32];
336 runcrawlpos = 32;
337 }
338
339 /*
340 * Put match in its canonical form before returning it.
341 */
342 private Match TidyMatch(bool quick) {
343 if (!quick) {
344 Match match = runmatch;
345
346 runmatch = null;
347
348 match.Tidy(runtextpos);
349 return match;
350 } else {
351 // in quick mode, a successful match returns null, and
352 // the allocated match object is left in the cache
353
354 return null;
355 }
356 }
357
358 /*
359 * Called by the implemenation of Go() to increase the size of storage
360 */
361 protected void EnsureStorage() {
362 if (runstackpos < runtrackcount * 4)
363 DoubleStack();
364 if (runtrackpos < runtrackcount * 4)
365 DoubleTrack();
366 }
367
368 /*
369 * Called by the implemenation of Go() to decide whether the pos
370 * at the specified index is a boundary or not. It's just not worth
371 * emitting inline code for this logic.
372 */
373 protected bool IsBoundary(int index, int startpos, int endpos) {
374 return (index > startpos && RegexCharClass.IsWordChar(runtext [index - 1])) !=
375 (index < endpos && RegexCharClass.IsWordChar(runtext [index]));
376 }
377
378 protected bool IsECMABoundary(int index, int startpos, int endpos) {
379 return (index > startpos && RegexCharClass.IsECMAWordChar(runtext [index - 1])) !=
380 (index < endpos && RegexCharClass.IsECMAWordChar(runtext [index]));
381 }
382
383 protected static bool CharInSet(char ch, String set, String category) {
384 string charClass = RegexCharClass.ConvertOldStringsToClass(set, category);
385 return RegexCharClass.CharInClass(ch, charClass);
386 }
387
388 protected static bool CharInClass(char ch, String charClass) {
389 return RegexCharClass.CharInClass(ch, charClass);
390 }
391
392 /*
393 * Called by the implemenation of Go() to increase the size of the
394 * backtracking stack.
395 */
396 protected void DoubleTrack() {
397 int [] newtrack;
398
399 newtrack = new int [runtrack.Length * 2];
400
401 System.Array.Copy(runtrack, 0, newtrack, runtrack.Length, runtrack.Length);
402 runtrackpos += runtrack.Length;
403 runtrack = newtrack;
404 }
405
406 /*
407 * Called by the implemenation of Go() to increase the size of the
408 * grouping stack.
409 */
410 protected void DoubleStack() {
411 int [] newstack;
412
413 newstack = new int [runstack.Length * 2];
414
415 System.Array.Copy(runstack, 0, newstack, runstack.Length, runstack.Length);
416 runstackpos += runstack.Length;
417 runstack = newstack;
418 }
419
420 /*
421 * Increases the size of the longjump unrolling stack.
422 */
423 protected void DoubleCrawl() {
424 int [] newcrawl;
425
426 newcrawl = new int [runcrawl.Length * 2];
427
428 System.Array.Copy(runcrawl, 0, newcrawl, runcrawl.Length, runcrawl.Length);
429 runcrawlpos += runcrawl.Length;
430 runcrawl = newcrawl;
431 }
432
433 /*
434 * Save a number on the longjump unrolling stack
435 */
436 protected void Crawl(int i) {
437 if (runcrawlpos == 0)
438 DoubleCrawl();
439
440 runcrawl [--runcrawlpos] = i;
441 }
442
443 /*
444 * Remove a number from the longjump unrolling stack
445 */
446 protected int Popcrawl() {
447 return runcrawl [runcrawlpos++];
448 }
449
450 /*
451 * Get the height of the stack
452 */
453 protected int Crawlpos() {
454 return runcrawl.Length - runcrawlpos;
455 }
456
457 /*
458 * Called by Go() to capture a subexpression. Note that the
459 * capnum used here has already been mapped to a non-sparse
460 * index (by the code generator RegexWriter).
461 */
462 protected void Capture(int capnum, int start, int end) {
463 if (end < start) {
464 int T;
465
466 T = end;
467 end = start;
468 start = T;
469 }
470
471 Crawl(capnum);
472 runmatch.AddMatch(capnum, start, end - start);
473 }
474
475 /*
476 * Called by Go() to capture a subexpression. Note that the
477 * capnum used here has already been mapped to a non-sparse
478 * index (by the code generator RegexWriter).
479 */
480 protected void TransferCapture(int capnum, int uncapnum, int start, int end) {
481 int start2;
482 int end2;
483
484 // these are the two intervals that are cancelling each other
485
486 if (end < start) {
487 int T;
488
489 T = end;
490 end = start;
491 start = T;
492 }
493
494 start2 = MatchIndex(uncapnum);
495 end2 = start2 + MatchLength(uncapnum);
496
497 // The new capture gets the innermost defined interval
498
499 if (start >= end2) {
500 end = start;
501 start = end2;
502 } else if (end <= start2) {
503 start = start2;
504 } else {
505 if (end > end2)
506 end = end2;
507 if (start2 > start)
508 start = start2;
509 }
510
511 Crawl(uncapnum);
512 runmatch.BalanceMatch(uncapnum);
513
514 if (capnum != -1) {
515 Crawl(capnum);
516 runmatch.AddMatch(capnum, start, end - start);
517 }
518 }
519
520 /*
521 * Called by Go() to revert the last capture
522 */
523 protected void Uncapture() {
524 int capnum = Popcrawl();
525 runmatch.RemoveMatch(capnum);
526 }
527
528 /*
529 * Call out to runmatch to get around visibility issues
530 */
531 protected bool IsMatched(int cap) {
532 return runmatch.IsMatched(cap);
533 }
534
535 /*
536 * Call out to runmatch to get around visibility issues
537 */
538 protected int MatchIndex(int cap) {
539 return runmatch.MatchIndex(cap);
540 }
541
542 /*
543 * Call out to runmatch to get around visibility issues
544 */
545 protected int MatchLength(int cap) {
546 return runmatch.MatchLength(cap);
547 }
548
549 #if DBG
550 /*
551 * Dump the current state
552 */
553 internal virtual void DumpState() {
554 Debug.WriteLine("Text: " + TextposDescription());
555 Debug.WriteLine("Track: " + StackDescription(runtrack, runtrackpos));
556 Debug.WriteLine("Stack: " + StackDescription(runstack, runstackpos));
557 }
558
559 internal static String StackDescription(int [] A, int Index) {
560 StringBuilder Sb = new StringBuilder();
561
562 Sb.Append(A.Length - Index);
563 Sb.Append('/');
564 Sb.Append(A.Length);
565
566 if (Sb.Length < 8)
567 Sb.Append(' ', 8 - Sb.Length);
568
569 Sb.Append("(");
570
571 for (int i = Index; i < A.Length; i++) {
572 if (i > Index)
573 Sb.Append(' ');
574 Sb.Append(A [i]);
575 }
576
577 Sb.Append(')');
578
579 return Sb.ToString();
580 }
581
582 internal virtual String TextposDescription() {
583 StringBuilder Sb = new StringBuilder();
584 int remaining;
585
586 Sb.Append(runtextpos);
587
588 if (Sb.Length < 8)
589 Sb.Append(' ', 8 - Sb.Length);
590
591 if (runtextpos > runtextbeg)
592 Sb.Append(RegexCharClass.CharDescription(runtext [runtextpos - 1]));
593 else
594 Sb.Append('^');
595
596 Sb.Append('>');
597
598 remaining = runtextend - runtextpos;
599
600 for (int i = runtextpos; i < runtextend; i++) {
601 Sb.Append(RegexCharClass.CharDescription(runtext [i]));
602 }
603 if (Sb.Length >= 64) {
604 Sb.Length = 61;
605 Sb.Append("...");
606 } else {
607 Sb.Append('$');
608 }
609
610 return Sb.ToString();
611 }
612 #endif
613 }
614
615
616
617 }