Debian Codegraph @

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

raw
1 //------------------------------------------------------------------------------
2 // <copyright file="RegexNode.cs" company="Microsoft">
3 // Copyright (c) Microsoft Corporation. All rights reserved.
4 // </copyright>
5 //------------------------------------------------------------------------------
6
7 // This RegexNode class is internal to the Regex package.
8 // It is built into a parsed tree for a regular expression.
9
10 // Implementation notes:
11 //
12 // Since the node tree is a temporary data structure only used
13 // during compilation of the regexp to integer codes, it's
14 // designed for clarity and convenience rather than
15 // space efficiency.
16 //
17 // RegexNodes are built into a tree, linked by the _children list.
18 // Each node also has a _parent and _ichild member indicating
19 // its parent and which child # it is in its parent's list.
20 //
21 // RegexNodes come in as many types as there are constructs in
22 // a regular expression, for example, "concatenate", "alternate",
23 // "one", "rept", "group". There are also node types for basic
24 // peephole optimizations, e.g., "onerep", "notsetrep", etc.
25 //
26 // Because perl 5 allows "lookback" groups that scan backwards,
27 // each node also gets a "direction". Normally the value of
28 // boolean _backward = false.
29 //
30 // During parsing, top-level nodes are also stacked onto a parse
31 // stack (a stack of trees). For this purpose we have a _next
32 // pointer. [Note that to save a few bytes, we could overload the
33 // _parent pointer instead.]
34 //
35 // On the parse stack, each tree has a "role" - basically, the
36 // nonterminal in the grammar that the parser has currently
37 // assigned to the tree. That code is stored in _role.
38 //
39 // Finally, some of the different kinds of nodes have data.
40 // Two integers (for the looping constructs) are stored in
41 // _operands, an an object (either a string or a set)
42 // is stored in _data
43
44
45 namespace System.Text.RegularExpressions {
46
47 using System.Collections;
48 using System.Collections.Generic;
49 using System.Diagnostics;
50 using System.Globalization;
51
52 internal sealed class RegexNode {
53 /*
54 * RegexNode types
55 */
56
57 // the following are leaves, and correspond to primitive operations
58
59 // static final int Onerep = RegexCode.Onerep; // c,n a {n}
60 // static final int Notonerep = RegexCode.Notonerep; // c,n .{n}
61 // static final int Setrep = RegexCode.Setrep; // set,n \d {n}
62
63 internal const int Oneloop = RegexCode.Oneloop; // c,n a*
64 internal const int Notoneloop = RegexCode.Notoneloop; // c,n .*
65 internal const int Setloop = RegexCode.Setloop; // set,n \d*
66
67 internal const int Onelazy = RegexCode.Onelazy; // c,n a*?
68 internal const int Notonelazy = RegexCode.Notonelazy; // c,n .*?
69 internal const int Setlazy = RegexCode.Setlazy; // set,n \d*?
70
71 internal const int One = RegexCode.One; // char a
72 internal const int Notone = RegexCode.Notone; // char . [^a]
73 internal const int Set = RegexCode.Set; // set [a-z] \w \s \d
74
75 internal const int Multi = RegexCode.Multi; // string abcdef
76 internal const int Ref = RegexCode.Ref; // index \1
77
78 internal const int Bol = RegexCode.Bol; // ^
79 internal const int Eol = RegexCode.Eol; // $
80 internal const int Boundary = RegexCode.Boundary; // \b
81 internal const int Nonboundary= RegexCode.Nonboundary;// \B
82 internal const int ECMABoundary = RegexCode.ECMABoundary; // \b
83 internal const int NonECMABoundary= RegexCode.NonECMABoundary; // \B
84 internal const int Beginning = RegexCode.Beginning; // \A
85 internal const int Start = RegexCode.Start; // \G
86 internal const int EndZ = RegexCode.EndZ; // \Z
87 internal const int End = RegexCode.End; // \z
88
89 // (note: End = 21;)
90
91 // interior nodes do not correpond to primitive operations, but
92 // control structures compositing other operations
93
94 // concat and alternate take n children, and can run forward or backwards
95
96 internal const int Nothing = 22; // []
97 internal const int Empty = 23; // ()
98
99 internal const int Alternate = 24; // a|b
100 internal const int Concatenate= 25; // ab
101
102 internal const int Loop = 26; // m,x * + ? {,}
103 internal const int Lazyloop = 27; // m,x *? +? ?? {,}?
104
105 internal const int Capture = 28; // n ()
106 internal const int Group = 29; // (?:)
107 internal const int Require = 30; // (?=) (?<=)
108 internal const int Prevent = 31; // (?!) (?<!)
109 internal const int Greedy = 32; // (?>) (?<)
110 internal const int Testref = 33; // (?(n) | )
111 internal const int Testgroup = 34; // (?(...) | )
112
113 /*
114 * RegexNode data members
115 *
116 */
117
118 internal int _type;
119
120 internal List<RegexNode> _children;
121
122 internal String _str;
123 internal char _ch;
124 internal int _m;
125 internal int _n;
126 internal RegexOptions _options;
127
128 internal RegexNode _next;
129
130 internal RegexNode(int type, RegexOptions options) {
131 _type = type;
132 _options = options;
133 }
134
135 internal RegexNode(int type, RegexOptions options, char ch) {
136 _type = type;
137 _options = options;
138 _ch = ch;
139 }
140
141 internal RegexNode(int type, RegexOptions options, String str) {
142 _type = type;
143 _options = options;
144 _str = str;
145 }
146
147 internal RegexNode(int type, RegexOptions options, int m) {
148 _type = type;
149 _options = options;
150 _m = m;
151 }
152
153 internal RegexNode(int type, RegexOptions options, int m, int n) {
154 _type = type;
155 _options = options;
156 _m = m;
157 _n = n;
158 }
159
160 internal bool UseOptionR() {
161 return(_options & RegexOptions.RightToLeft) != 0;
162 }
163
164 internal RegexNode ReverseLeft() {
165 if (UseOptionR() && _type == Concatenate && _children != null) {
166 _children.Reverse(0, _children.Count);
167 }
168
169 return this;
170 }
171
172
173 // Pass type as OneLazy or OneLoop
174 internal void MakeRep(int type, int min, int max) {
175 _type += (type - One);
176 _m = min;
177 _n = max;
178 }
179
180 /*
181 * Reduce
182 *
183 * Removes redundant nodes from the subtree, and returns a reduced subtree.
184 */
185 internal RegexNode Reduce() {
186 RegexNode n;
187
188 switch (Type()) {
189 case Alternate:
190 n = ReduceAlternation();
191 break;
192
193 case Concatenate:
194 n = ReduceConcatenation();
195 break;
196
197 case Loop:
198 case Lazyloop:
199 n = ReduceRep();
200 break;
201
202 case Group:
203 n = ReduceGroup();
204 break;
205
206 case Set:
207 case Setloop:
208 n = ReduceSet();
209 break;
210
211 default:
212 n = this;
213 break;
214 }
215
216 return n;
217 }
218
219
220 /*
221 * StripEnation:
222 *
223 * Simple optimization. If a concatenation or alternation has only
224 * one child strip out the intermediate node. If it has zero children,
225 * turn it into an empty.
226 *
227 */
228
229 internal RegexNode StripEnation(int emptyType) {
230 switch (ChildCount()) {
231 case 0:
232 return new RegexNode(emptyType, _options);
233 case 1:
234 return Child(0);
235 default:
236 return this;
237 }
238 }
239
240 /*
241 * ReduceGroup:
242 *
243 * Simple optimization. Once parsed into a tree, noncapturing groups
244 * serve no function, so strip them out.
245 */
246
247 internal RegexNode ReduceGroup() {
248 RegexNode u;
249
250 for (u = this; u.Type() == Group; )
251 u = u.Child(0);
252
253 return u;
254 }
255
256 /*
257 * ReduceRep:
258 *
259 * Nested repeaters just get multiplied with each other if they're not
260 * too lumpy
261 */
262
263 internal RegexNode ReduceRep() {
264 RegexNode u;
265 RegexNode child;
266 int type;
267 int min;
268 int max;
269
270 u = this;
271 type = Type();
272 min = _m;
273 max = _n;
274
275 for (;;) {
276 if (u.ChildCount() == 0)
277 break;
278
279 child = u.Child(0);
280
281 // multiply reps of the same type only
282 if (child.Type() != type) {
283 int childType = child.Type();
284
285 if (!(childType >= Oneloop && childType <= Setloop && type == Loop ||
286 childType >= Onelazy && childType <= Setlazy && type == Lazyloop))
287 break;
288 }
289
290 // child can be too lumpy to blur, e.g., (a {100,105}) {3} or (a {2,})?
291 // [but things like (a {2,})+ are not too lumpy...]
292 if (u._m == 0 && child._m > 1 || child._n < child._m * 2)
293 break;
294
295 u = child;
296 if (u._m > 0)
297 u._m = min = ((Int32.MaxValue - 1) / u._m < min) ? Int32.MaxValue : u._m * min;
298 if (u._n > 0)
299 u._n = max = ((Int32.MaxValue - 1) / u._n < max) ? Int32.MaxValue : u._n * max;
300 }
301
302 return min == Int32.MaxValue ? new RegexNode(Nothing, _options) : u;
303 }
304
305 /*
306 * ReduceSet:
307 *
308 * Simple optimization. If a set is a singleton, an inverse singleton,
309 * or empty, it's transformed accordingly.
310 */
311
312 internal RegexNode ReduceSet() {
313 // Extract empty-set, one and not-one case as special
314
315 if (RegexCharClass.IsEmpty(_str)) {
316 _type = Nothing;
317 _str = null;
318 }
319 else if (RegexCharClass.IsSingleton(_str)) {
320 _ch = RegexCharClass.SingletonChar(_str);
321 _str = null;
322 _type += (One - Set);
323 }
324 else if (RegexCharClass.IsSingletonInverse(_str)) {
325 _ch = RegexCharClass.SingletonChar(_str);
326 _str = null;
327 _type += (Notone - Set);
328 }
329
330 return this;
331 }
332
333 /*
334 * ReduceAlternation:
335 *
336 * Basic optimization. Single-letter alternations can be replaced
337 * by faster set specifications, and nested alternations with no
338 * intervening operators can be flattened:
339 *
340 * a|b|c|def|g|h -> [a-c]|def|[gh]
341 * apple|(?:orange|pear)|grape -> apple|orange|pear|grape
342 *
343 * <
344 */
345
346 internal RegexNode ReduceAlternation() {
347 // Combine adjacent sets/chars
348
349 bool wasLastSet;
350 bool lastNodeCannotMerge;
351 RegexOptions optionsLast;
352 RegexOptions optionsAt;
353 int i;
354 int j;
355 RegexNode at;
356 RegexNode prev;
357
358 if (_children == null)
359 return new RegexNode(RegexNode.Nothing, _options);
360
361 wasLastSet = false;
362 lastNodeCannotMerge = false;
363 optionsLast = 0;
364
365 for (i = 0, j = 0; i < _children.Count; i++, j++) {
366 at = _children[i];
367
368 if (j < i)
369 _children[j] = at;
370
371 for (;;) {
372 if (at._type == Alternate) {
373 for (int k = 0; k < at._children.Count; k++)
374 at._children[k]._next = this;
375
376 _children.InsertRange(i + 1, at._children);
377 j--;
378 }
379 else if (at._type == Set || at._type == One) {
380 // Cannot merge sets if L or I options differ, or if either are negated.
381 optionsAt = at._options & (RegexOptions.RightToLeft | RegexOptions.IgnoreCase);
382
383
384 if (at._type == Set) {
385 if (!wasLastSet || optionsLast != optionsAt || lastNodeCannotMerge || !RegexCharClass.IsMergeable(at._str)) {
386 wasLastSet = true;
387 lastNodeCannotMerge = !RegexCharClass.IsMergeable(at._str);
388 optionsLast = optionsAt;
389 break;
390 }
391 }
392 else if (!wasLastSet || optionsLast != optionsAt || lastNodeCannotMerge) {
393 wasLastSet = true;
394 lastNodeCannotMerge = false;
395 optionsLast = optionsAt;
396 break;
397 }
398
399
400 // The last node was a Set or a One, we're a Set or One and our options are the same.
401 // Merge the two nodes.
402 j--;
403 prev = _children[j];
404
405 RegexCharClass prevCharClass;
406 if (prev._type == RegexNode.One) {
407 prevCharClass = new RegexCharClass();
408 prevCharClass.AddChar(prev._ch);
409 }
410 else {
411 prevCharClass = RegexCharClass.Parse(prev._str);
412 }
413
414 if (at._type == RegexNode.One) {
415 prevCharClass.AddChar(at._ch);
416 }
417 else {
418 RegexCharClass atCharClass = RegexCharClass.Parse(at._str);
419 prevCharClass.AddCharClass(atCharClass);
420 }
421
422 prev._type = RegexNode.Set;
423 prev._str = prevCharClass.ToStringClass();
424
425 }
426 else if (at._type == RegexNode.Nothing) {
427 j--;
428 }
429 else {
430 wasLastSet = false;
431 lastNodeCannotMerge = false;
432 }
433 break;
434 }
435 }
436
437 if (j < i)
438 _children.RemoveRange(j, i - j);
439
440 return StripEnation(RegexNode.Nothing);
441 }
442
443 /*
444 * ReduceConcatenation:
445 *
446 * Basic optimization. Adjacent strings can be concatenated.
447 *
448 * (?:abc)(?:def) -> abcdef
449 */
450
451 internal RegexNode ReduceConcatenation() {
452 // Eliminate empties and concat adjacent strings/chars
453
454 bool wasLastString;
455 RegexOptions optionsLast;
456 RegexOptions optionsAt;
457 int i;
458 int j;
459
460 if (_children == null)
461 return new RegexNode(RegexNode.Empty, _options);
462
463 wasLastString = false;
464 optionsLast = 0;
465
466 for (i = 0, j = 0; i < _children.Count; i++, j++) {
467 RegexNode at;
468 RegexNode prev;
469
470 at = _children[i];
471
472 if (j < i)
473 _children[j] = at;
474
475 if (at._type == RegexNode.Concatenate &&
476 ((at._options & RegexOptions.RightToLeft) == (_options & RegexOptions.RightToLeft))) {
477 for (int k = 0; k < at._children.Count; k++)
478 at._children[k]._next = this;
479
480 _children.InsertRange(i + 1, at._children);
481 j--;
482 }
483 else if (at._type == RegexNode.Multi ||
484 at._type == RegexNode.One) {
485 // Cannot merge strings if L or I options differ
486 optionsAt = at._options & (RegexOptions.RightToLeft | RegexOptions.IgnoreCase);
487
488 if (!wasLastString || optionsLast != optionsAt) {
489 wasLastString = true;
490 optionsLast = optionsAt;
491 continue;
492 }
493
494 prev = _children[--j];
495
496 if (prev._type == RegexNode.One) {
497 prev._type = RegexNode.Multi;
498 prev._str = Convert.ToString(prev._ch, CultureInfo.InvariantCulture);
499 }
500
501 if ((optionsAt & RegexOptions.RightToLeft) == 0) {
502 if (at._type == RegexNode.One)
503 prev._str += at._ch.ToString();
504 else
505 prev._str += at._str;
506 }
507 else {
508 if (at._type == RegexNode.One)
509 prev._str = at._ch.ToString() + prev._str;
510 else
511 prev._str = at._str + prev._str;
512 }
513
514 }
515 else if (at._type == RegexNode.Empty) {
516 j--;
517 }
518 else {
519 wasLastString = false;
520 }
521 }
522
523 if (j < i)
524 _children.RemoveRange(j, i - j);
525
526 return StripEnation(RegexNode.Empty);
527 }
528
529 internal RegexNode MakeQuantifier(bool lazy, int min, int max) {
530 RegexNode result;
531
532 if (min == 0 && max == 0)
533 return new RegexNode(RegexNode.Empty, _options);
534
535 if (min == 1 && max == 1)
536 return this;
537
538 switch (_type) {
539 case RegexNode.One:
540 case RegexNode.Notone:
541 case RegexNode.Set:
542
543 MakeRep(lazy ? RegexNode.Onelazy : RegexNode.Oneloop, min, max);
544 return this;
545
546 default:
547 result = new RegexNode(lazy ? RegexNode.Lazyloop : RegexNode.Loop, _options, min, max);
548 result.AddChild(this);
549 return result;
550 }
551 }
552
553 internal void AddChild(RegexNode newChild) {
554 RegexNode reducedChild;
555
556 if (_children == null)
557 _children = new List<RegexNode>(4);
558
559 reducedChild = newChild.Reduce();
560
561 _children.Add(reducedChild);
562 reducedChild._next = this;
563 }
564 internal RegexNode Child(int i) {
565 return _children[i];
566 }
567
568 internal int ChildCount() {
569 return _children == null ? 0 : _children.Count;
570 }
571
572 internal int Type() {
573 return _type;
574 }
575
576 #if DBG
577 internal static String[] TypeStr = new String[] {
578 "Onerep", "Notonerep", "Setrep",
579 "Oneloop", "Notoneloop", "Setloop",
580 "Onelazy", "Notonelazy", "Setlazy",
581 "One", "Notone", "Set",
582 "Multi", "Ref",
583 "Bol", "Eol", "Boundary", "Nonboundary",
584 "ECMABoundary", "NonECMABoundary",
585 "Beginning", "Start", "EndZ", "End",
586 "Nothing", "Empty",
587 "Alternate", "Concatenate",
588 "Loop", "Lazyloop",
589 "Capture", "Group", "Require", "Prevent", "Greedy",
590 "Testref", "Testgroup"};
591
592 internal String Description() {
593
594 StringBuilder ArgSb = new StringBuilder();
595
596 ArgSb.Append(TypeStr[_type]);
597
598 if ((_options & RegexOptions.ExplicitCapture) != 0)
599 ArgSb.Append("-C");
600 if ((_options & RegexOptions.IgnoreCase) != 0)
601 ArgSb.Append("-I");
602 if ((_options & RegexOptions.RightToLeft) != 0)
603 ArgSb.Append("-L");
604 if ((_options & RegexOptions.Multiline) != 0)
605 ArgSb.Append("-M");
606 if ((_options & RegexOptions.Singleline) != 0)
607 ArgSb.Append("-S");
608 if ((_options & RegexOptions.IgnorePatternWhitespace) != 0)
609 ArgSb.Append("-X");
610 if ((_options & RegexOptions.ECMAScript) != 0)
611 ArgSb.Append("-E");
612
613 switch (_type) {
614 case Oneloop:
615 case Notoneloop:
616 case Onelazy:
617 case Notonelazy:
618 case One:
619 case Notone:
620 ArgSb.Append("(Ch = " + RegexCharClass.CharDescription(_ch) + ")");
621 break;
622 case Capture:
623 ArgSb.Append("(index = " + _m.ToString(CultureInfo.InvariantCulture) + ", unindex = " + _n.ToString(CultureInfo.InvariantCulture) + ")");
624 break;
625 case Ref:
626 case Testref:
627 ArgSb.Append("(index = " + _m.ToString(CultureInfo.InvariantCulture) + ")");
628 break;
629 case Multi:
630 ArgSb.Append("(String = " + _str + ")");
631 break;
632 case Set:
633 case Setloop:
634 case Setlazy:
635 ArgSb.Append("(Set = " + RegexCharClass.SetDescription(_str) + ")");
636 break;
637 }
638
639 switch (_type) {
640 case Oneloop:
641 case Notoneloop:
642 case Onelazy:
643 case Notonelazy:
644 case Setloop:
645 case Setlazy:
646 case Loop:
647 case Lazyloop:
648 ArgSb.Append("(Min = " + _m.ToString(CultureInfo.InvariantCulture) + ", Max = " + (_n == Int32.MaxValue ? "inf" : Convert.ToString(_n, CultureInfo.InvariantCulture)) + ")");
649 break;
650 }
651
652 return ArgSb.ToString();
653 }
654
655 internal const String Space = " ";
656
657 internal void Dump() {
658 List<int> Stack = new List<int>();
659 RegexNode CurNode;
660 int CurChild;
661
662 CurNode = this;
663 CurChild = 0;
664
665 Debug.WriteLine(CurNode.Description());
666
667 for (;;) {
668 if (CurNode._children != null && CurChild < CurNode._children.Count) {
669 Stack.Add(CurChild + 1);
670 CurNode = CurNode._children[CurChild];
671 CurChild = 0;
672
673 int Depth = Stack.Count;
674 if (Depth > 32)
675 Depth = 32;
676
677 Debug.WriteLine(Space.Substring(0, Depth) + CurNode.Description());
678 }
679 else {
680 if (Stack.Count == 0)
681 break;
682
683 CurChild = Stack[Stack.Count - 1];
684 Stack.RemoveAt(Stack.Count - 1);
685 CurNode = CurNode._next;
686 }
687 }
688 }
689 #endif
690
691 }
692
693 }