-
Notifications
You must be signed in to change notification settings - Fork 4.6k
/
RegexParser.cs
2330 lines (1959 loc) · 85.2 KB
/
RegexParser.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
namespace System.Text.RegularExpressions
{
/// <summary>Builds a tree of RegexNodes from a regular expression.</summary>
internal ref struct RegexParser
{
// Implementation notes:
// It would be nice to get rid of the comment modes, since the
// ScanBlank() calls are just kind of duct-taped in.
private const int EscapeMaxBufferSize = 256;
private const int OptionStackDefaultSize = 32;
private const int MaxValueDiv10 = int.MaxValue / 10;
private const int MaxValueMod10 = int.MaxValue % 10;
private RegexNode? _stack;
private RegexNode? _group;
private RegexNode? _alternation;
private RegexNode? _concatenation;
private RegexNode? _unit;
private readonly string _pattern;
private int _currentPos;
private readonly CultureInfo _culture;
private RegexCaseBehavior _caseBehavior;
private bool _hasIgnoreCaseBackreferenceNodes;
private int _autocap;
private int _capcount;
private int _captop;
private readonly int _capsize;
private readonly Hashtable _caps;
private Hashtable? _capnames;
private int[]? _capnumlist;
private List<string>? _capnamelist;
private RegexOptions _options;
// NOTE: _optionsStack is ValueListBuilder<int> to ensure that
// ArrayPool<int>.Shared, not ArrayPool<RegexOptions>.Shared,
// will be created if the stackalloc'd capacity is ever exceeded.
private ValueListBuilder<int> _optionsStack;
private bool _ignoreNextParen; // flag to skip capturing a parentheses group
private RegexParser(string pattern, RegexOptions options, CultureInfo culture, Hashtable caps, int capsize, Hashtable? capnames, Span<int> optionSpan)
{
Debug.Assert(pattern != null, "Pattern must be set");
Debug.Assert(culture != null, "Culture must be set");
_pattern = pattern;
_options = options;
_culture = culture;
_caseBehavior = default;
_hasIgnoreCaseBackreferenceNodes = false;
_caps = caps;
_capsize = capsize;
_capnames = capnames;
_optionsStack = new ValueListBuilder<int>(optionSpan);
_stack = null;
_group = null;
_alternation = null;
_concatenation = null;
_unit = null;
_currentPos = 0;
_autocap = 0;
_capcount = 0;
_captop = 0;
_capnumlist = null;
_capnamelist = null;
_ignoreNextParen = false;
}
/// <summary>Gets the culture to use based on the specified options.</summary>
internal static CultureInfo GetTargetCulture(RegexOptions options) =>
(options & RegexOptions.CultureInvariant) != 0 ? CultureInfo.InvariantCulture : CultureInfo.CurrentCulture;
public static RegexTree Parse(string pattern, RegexOptions options, CultureInfo culture)
{
using var parser = new RegexParser(pattern, options, culture, new Hashtable(), 0, null, stackalloc int[OptionStackDefaultSize]);
parser.CountCaptures();
parser.Reset(options);
RegexNode root = parser.ScanRegex();
int[]? captureNumberList = parser._capnumlist;
Hashtable? sparseMapping = parser._caps;
int captop = parser._captop;
int captureCount;
if (captureNumberList == null || captop == captureNumberList.Length)
{
// The capture list isn't sparse. Null out the capture mapping as it's not necessary,
// and store the number of captures.
captureCount = captop;
sparseMapping = null;
}
else
{
// The capture list is sparse. Store the number of captures, and populate the number-to-names-list.
captureCount = captureNumberList.Length;
for (int i = 0; i < captureNumberList.Length; i++)
{
sparseMapping[captureNumberList[i]] = i;
}
}
return new RegexTree(root, captureCount, parser._capnamelist?.ToArray(), parser._capnames!, sparseMapping, options, parser._hasIgnoreCaseBackreferenceNodes ? culture : null);
}
/// <summary>
/// This static call constructs a flat concatenation node given a replacement pattern.
/// </summary>
public static RegexReplacement ParseReplacement(string pattern, RegexOptions options, Hashtable caps, int capsize, Hashtable capnames)
{
CultureInfo culture = (options & RegexOptions.CultureInvariant) != 0 ? CultureInfo.InvariantCulture : CultureInfo.CurrentCulture;
using var parser = new RegexParser(pattern, options, culture, caps, capsize, capnames, stackalloc int[OptionStackDefaultSize]);
RegexNode root = parser.ScanReplacement();
var regexReplacement = new RegexReplacement(pattern, root, caps);
return regexReplacement;
}
/// <summary>
/// Escapes all metacharacters (including |,(,),[,{,|,^,$,*,+,?,\, spaces and #)
/// </summary>
public static string Escape(string input)
{
for (int i = 0; i < input.Length; i++)
{
if (IsMetachar(input[i]))
{
return EscapeImpl(input, i);
}
}
return input;
}
private static string EscapeImpl(string input, int i)
{
// For small inputs we allocate on the stack. In most cases a buffer three
// times larger the original string should be sufficient as usually not all
// characters need to be encoded.
// For larger string we rent the input string's length plus a fixed
// conservative amount of chars from the ArrayPool.
ValueStringBuilder vsb = input.Length <= (EscapeMaxBufferSize / 3) ?
new ValueStringBuilder(stackalloc char[EscapeMaxBufferSize]) :
new ValueStringBuilder(input.Length + 200);
char ch = input[i];
vsb.Append(input.AsSpan(0, i));
do
{
vsb.Append('\\');
switch (ch)
{
case '\n':
ch = 'n';
break;
case '\r':
ch = 'r';
break;
case '\t':
ch = 't';
break;
case '\f':
ch = 'f';
break;
}
vsb.Append(ch);
i++;
int lastpos = i;
while (i < input.Length)
{
ch = input[i];
if (IsMetachar(ch))
{
break;
}
i++;
}
vsb.Append(input.AsSpan(lastpos, i - lastpos));
} while (i < input.Length);
return vsb.ToString();
}
/// <summary>
/// Unescapes all metacharacters (including (,),[,],{,},|,^,$,*,+,?,\, spaces and #)
/// </summary>
public static string Unescape(string input)
{
int i = input.IndexOf('\\');
return i >= 0 ?
UnescapeImpl(input, i) :
input;
}
private static string UnescapeImpl(string input, int i)
{
using var parser = new RegexParser(input, RegexOptions.None, CultureInfo.InvariantCulture, new Hashtable(), 0, null, stackalloc int[OptionStackDefaultSize]);
// In the worst case the escaped string has the same length.
// For small inputs we use stack allocation.
ValueStringBuilder vsb = input.Length <= EscapeMaxBufferSize ?
new ValueStringBuilder(stackalloc char[EscapeMaxBufferSize]) :
new ValueStringBuilder(input.Length);
vsb.Append(input.AsSpan(0, i));
do
{
i++;
parser.Textto(i);
if (i < input.Length)
{
vsb.Append(parser.ScanCharEscape());
}
i = parser.Textpos();
int lastpos = i;
while (i < input.Length && input[i] != '\\')
{
i++;
}
vsb.Append(input.AsSpan(lastpos, i - lastpos));
} while (i < input.Length);
return vsb.ToString();
}
/// <summary>
/// Resets parsing to the beginning of the pattern.
/// </summary>
private void Reset(RegexOptions options)
{
_currentPos = 0;
_autocap = 1;
_ignoreNextParen = false;
_optionsStack.Length = 0;
_options = options;
_stack = null;
}
public void Dispose() => _optionsStack.Dispose();
/*
* The main parsing function.
*/
private RegexNode ScanRegex()
{
char ch;
bool isQuantifier = false;
// For the main Capture object, strip out the IgnoreCase option. The rest of the nodes will strip it out depending on the content
// of each node.
StartGroup(new RegexNode(RegexNodeKind.Capture, (_options & ~RegexOptions.IgnoreCase), 0, -1));
while (CharsRight() > 0)
{
bool wasPrevQuantifier = isQuantifier;
isQuantifier = false;
ScanBlank();
int startpos = Textpos();
// move past all of the normal characters. We'll stop when we hit some kind of control character,
// or if IgnorePatternWhiteSpace is on, we'll stop when we see some whitespace.
if (UseOptionX())
{
while (CharsRight() > 0 && (!IsStopperX(ch = RightChar()) || (ch == '{' && !IsTrueQuantifier())))
MoveRight();
}
else
{
while (CharsRight() > 0 && (!IsSpecial(ch = RightChar()) || (ch == '{' && !IsTrueQuantifier())))
MoveRight();
}
int endpos = Textpos();
ScanBlank();
if (CharsRight() == 0)
{
ch = '!'; // nonspecial, means at end
}
else if (IsSpecial(ch = RightChar()))
{
isQuantifier = IsQuantifier(ch);
MoveRight();
}
else
{
ch = ' '; // nonspecial, means at ordinary char
}
if (startpos < endpos)
{
int cchUnquantified = endpos - startpos - (isQuantifier ? 1 : 0);
wasPrevQuantifier = false;
if (cchUnquantified > 0)
{
AddConcatenate(startpos, cchUnquantified, false);
}
if (isQuantifier)
{
AddUnitOne(CharAt(endpos - 1));
}
}
switch (ch)
{
case '!':
goto BreakOuterScan;
case ' ':
goto ContinueOuterScan;
case '[':
{
string setString = ScanCharClass(UseOptionI(), scanOnly: false)!.ToStringClass();
_unit = new RegexNode(RegexNodeKind.Set, _options & ~RegexOptions.IgnoreCase, setString);
}
break;
case '(':
{
RegexNode? grouper;
PushOptions();
if (null == (grouper = ScanGroupOpen()))
{
PopKeepOptions();
}
else
{
PushGroup();
StartGroup(grouper);
}
}
continue;
case '|':
AddAlternate();
goto ContinueOuterScan;
case ')':
if (EmptyStack())
{
throw MakeException(RegexParseError.InsufficientOpeningParentheses, SR.InsufficientOpeningParentheses);
}
AddGroup();
PopGroup();
PopOptions();
if (Unit() == null)
{
goto ContinueOuterScan;
}
break;
case '\\':
if (CharsRight() == 0)
{
throw MakeException(RegexParseError.UnescapedEndingBackslash, SR.UnescapedEndingBackslash);
}
AddUnitNode(ScanBackslash(scanOnly: false)!);
break;
case '^':
AddUnitType(UseOptionM() ? RegexNodeKind.Bol : RegexNodeKind.Beginning);
break;
case '$':
AddUnitType(UseOptionM() ? RegexNodeKind.Eol : RegexNodeKind.EndZ);
break;
case '.':
_unit = UseOptionS() ?
new RegexNode(RegexNodeKind.Set, _options & ~RegexOptions.IgnoreCase, RegexCharClass.AnyClass) :
new RegexNode(RegexNodeKind.Notone, _options & ~RegexOptions.IgnoreCase, '\n');
break;
case '{':
case '*':
case '+':
case '?':
if (Unit() == null)
{
throw wasPrevQuantifier ?
MakeException(RegexParseError.NestedQuantifiersNotParenthesized, SR.Format(SR.NestedQuantifiersNotParenthesized, ch)) :
MakeException(RegexParseError.QuantifierAfterNothing, SR.Format(SR.QuantifierAfterNothing, ch));
}
MoveLeft();
break;
default:
throw new InvalidOperationException(SR.InternalError_ScanRegex);
}
ScanBlank();
if (CharsRight() == 0 || !(isQuantifier = IsTrueQuantifier()))
{
AddConcatenate();
goto ContinueOuterScan;
}
ch = RightCharMoveRight();
// Handle quantifiers
while (Unit() != null)
{
int min;
int max;
switch (ch)
{
case '*':
min = 0;
max = int.MaxValue;
break;
case '?':
min = 0;
max = 1;
break;
case '+':
min = 1;
max = int.MaxValue;
break;
case '{':
{
startpos = Textpos();
max = min = ScanDecimal();
if (startpos < Textpos())
{
if (CharsRight() > 0 && RightChar() == ',')
{
MoveRight();
max = CharsRight() == 0 || RightChar() == '}' ? int.MaxValue : ScanDecimal();
}
}
if (startpos == Textpos() || CharsRight() == 0 || RightCharMoveRight() != '}')
{
AddConcatenate();
Textto(startpos - 1);
goto ContinueOuterScan;
}
}
break;
default:
throw new InvalidOperationException(SR.InternalError_ScanRegex);
}
ScanBlank();
bool lazy = false;
if (CharsRight() != 0 && RightChar() == '?')
{
MoveRight();
lazy = true;
}
if (min > max)
{
throw MakeException(RegexParseError.ReversedQuantifierRange, SR.ReversedQuantifierRange);
}
AddConcatenate(lazy, min, max);
}
ContinueOuterScan:
;
}
BreakOuterScan:
;
if (!EmptyStack())
{
throw MakeException(RegexParseError.InsufficientClosingParentheses, SR.InsufficientClosingParentheses);
}
AddGroup();
return Unit()!.FinalOptimize();
}
/*
* Simple parsing for replacement patterns
*/
private RegexNode ScanReplacement()
{
_concatenation = new RegexNode(RegexNodeKind.Concatenate, _options);
while (true)
{
int c = CharsRight();
if (c == 0)
{
break;
}
int startpos = Textpos();
while (c > 0 && RightChar() != '$')
{
MoveRight();
c--;
}
AddConcatenate(startpos, Textpos() - startpos, true);
if (c > 0)
{
if (RightCharMoveRight() == '$')
{
RegexNode node = ScanDollar();
AddUnitNode(node);
}
AddConcatenate();
}
}
return _concatenation;
}
/*
* Scans contents of [] (not including []'s), and converts to a
* RegexCharClass.
*/
private RegexCharClass? ScanCharClass(bool caseInsensitive, bool scanOnly)
{
char ch;
char chPrev = '\0';
bool inRange = false;
bool firstChar = true;
bool closed = false;
RegexCharClass? charClass = scanOnly ? null : new RegexCharClass();
if (CharsRight() > 0 && RightChar() == '^')
{
MoveRight();
if (!scanOnly)
{
charClass!.Negate = true;
}
if ((_options & RegexOptions.ECMAScript) != 0 && CharAt(_currentPos) == ']')
{
firstChar = false;
}
}
for (; CharsRight() > 0; firstChar = false)
{
bool translatedChar = false;
ch = RightCharMoveRight();
if (ch == ']')
{
if (!firstChar)
{
closed = true;
break;
}
}
else if (ch == '\\' && CharsRight() > 0)
{
switch (ch = RightCharMoveRight())
{
case 'D':
case 'd':
if (!scanOnly)
{
if (inRange)
{
throw MakeException(RegexParseError.ShorthandClassInCharacterRange, SR.Format(SR.ShorthandClassInCharacterRange, ch));
}
charClass!.AddDigit(UseOptionE(), ch == 'D', _pattern, _currentPos);
}
continue;
case 'S':
case 's':
if (!scanOnly)
{
if (inRange)
{
throw MakeException(RegexParseError.ShorthandClassInCharacterRange, SR.Format(SR.ShorthandClassInCharacterRange, ch));
}
charClass!.AddSpace(UseOptionE(), ch == 'S');
}
continue;
case 'W':
case 'w':
if (!scanOnly)
{
if (inRange)
{
throw MakeException(RegexParseError.ShorthandClassInCharacterRange, SR.Format(SR.ShorthandClassInCharacterRange, ch));
}
charClass!.AddWord(UseOptionE(), ch == 'W');
}
continue;
case 'p':
case 'P':
if (!scanOnly)
{
if (inRange)
{
throw MakeException(RegexParseError.ShorthandClassInCharacterRange, SR.Format(SR.ShorthandClassInCharacterRange, ch));
}
charClass!.AddCategoryFromName(ParseProperty(), ch != 'p', caseInsensitive, _pattern, _currentPos);
}
else
{
ParseProperty();
}
continue;
case '-':
if (!scanOnly)
{
if (inRange)
{
if (chPrev > ch)
{
throw MakeException(RegexParseError.ReversedCharacterRange, SR.ReversedCharacterRange);
}
charClass!.AddRange(chPrev, ch);
inRange = false;
chPrev = '\0';
}
else
{
charClass!.AddRange(ch, ch);
}
}
continue;
default:
MoveLeft();
ch = ScanCharEscape(); // non-literal character
translatedChar = true;
break; // this break will only break out of the switch
}
}
else if (ch == '[')
{
// This is code for Posix style properties - [:Ll:] or [:IsTibetan:].
// It currently doesn't do anything other than skip the whole thing!
if (CharsRight() > 0 && RightChar() == ':' && !inRange)
{
int savePos = Textpos();
MoveRight();
if (CharsRight() < 2 || RightCharMoveRight() != ':' || RightCharMoveRight() != ']')
{
Textto(savePos);
}
}
}
if (inRange)
{
inRange = false;
if (!scanOnly)
{
if (ch == '[' && !translatedChar && !firstChar)
{
// We thought we were in a range, but we're actually starting a subtraction.
// In that case, we'll add chPrev to our char class, skip the opening [, and
// scan the new character class recursively.
charClass!.AddChar(chPrev);
charClass.AddSubtraction(ScanCharClass(caseInsensitive, scanOnly)!);
if (CharsRight() > 0 && RightChar() != ']')
{
throw MakeException(RegexParseError.ExclusionGroupNotLast, SR.ExclusionGroupNotLast);
}
}
else
{
// a regular range, like a-z
if (chPrev > ch)
{
throw MakeException(RegexParseError.ReversedCharacterRange, SR.ReversedCharacterRange);
}
charClass!.AddRange(chPrev, ch);
}
}
}
else if (CharsRight() >= 2 && RightChar() == '-' && RightChar(1) != ']')
{
// this could be the start of a range
chPrev = ch;
inRange = true;
MoveRight();
}
else if (CharsRight() >= 1 && ch == '-' && !translatedChar && RightChar() == '[' && !firstChar)
{
// we aren't in a range, and now there is a subtraction. Usually this happens
// only when a subtraction follows a range, like [a-z-[b]]
MoveRight();
RegexCharClass? rcc = ScanCharClass(caseInsensitive, scanOnly);
if (!scanOnly)
{
charClass!.AddSubtraction(rcc!);
if (CharsRight() > 0 && RightChar() != ']')
{
throw MakeException(RegexParseError.ExclusionGroupNotLast, SR.ExclusionGroupNotLast);
}
}
}
else
{
if (!scanOnly)
{
charClass!.AddRange(ch, ch);
}
}
}
if (!closed)
{
throw MakeException(RegexParseError.UnterminatedBracket, SR.UnterminatedBracket);
}
if (!scanOnly && caseInsensitive)
{
charClass!.AddCaseEquivalences(_culture);
}
return charClass;
}
/*
* Scans chars following a '(' (not counting the '('), and returns
* a RegexNode for the type of group scanned, or null if the group
* simply changed options (?cimsx-cimsx) or was a comment (#...).
*/
private RegexNode? ScanGroupOpen()
{
// just return a RegexNode if we have:
// 1. "(" followed by nothing
// 2. "(x" where x != ?
// 3. "(?)"
if (CharsRight() == 0 || RightChar() != '?' || (RightChar() == '?' && CharsRight() > 1 && RightChar(1) == ')'))
{
if (UseOptionN() || _ignoreNextParen)
{
_ignoreNextParen = false;
return new RegexNode(RegexNodeKind.Group, _options);
}
else
{
return new RegexNode(RegexNodeKind.Capture, _options, _autocap++, -1);
}
}
MoveRight();
while (true)
{
if (CharsRight() == 0)
{
break;
}
RegexNodeKind nodeType;
char close = '>';
char ch = RightCharMoveRight();
switch (ch)
{
case ':':
// noncapturing group
nodeType = RegexNodeKind.Group;
break;
case '=':
// lookahead assertion
_options &= ~RegexOptions.RightToLeft;
nodeType = RegexNodeKind.PositiveLookaround;
break;
case '!':
// negative lookahead assertion
_options &= ~RegexOptions.RightToLeft;
nodeType = RegexNodeKind.NegativeLookaround;
break;
case '>':
// atomic subexpression
nodeType = RegexNodeKind.Atomic;
break;
case '\'':
close = '\'';
goto case '<'; // fallthrough
case '<':
if (CharsRight() == 0)
{
goto BreakRecognize;
}
switch (ch = RightCharMoveRight())
{
case '=':
if (close == '\'')
{
goto BreakRecognize;
}
// lookbehind assertion
_options |= RegexOptions.RightToLeft;
nodeType = RegexNodeKind.PositiveLookaround;
break;
case '!':
if (close == '\'')
{
goto BreakRecognize;
}
// negative lookbehind assertion
_options |= RegexOptions.RightToLeft;
nodeType = RegexNodeKind.NegativeLookaround;
break;
default:
MoveLeft();
int capnum = -1;
int uncapnum = -1;
bool proceed = false;
// grab part before -
if ((uint)(ch - '0') <= 9)
{
capnum = ScanDecimal();
if (!IsCaptureSlot(capnum))
{
capnum = -1;
}
// check if we have bogus characters after the number
if (CharsRight() > 0 && !(RightChar() == close || RightChar() == '-'))
{
throw MakeException(RegexParseError.CaptureGroupNameInvalid, SR.CaptureGroupNameInvalid);
}
if (capnum == 0)
{
throw MakeException(RegexParseError.CaptureGroupOfZero, SR.CaptureGroupOfZero);
}
}
else if (RegexCharClass.IsBoundaryWordChar(ch))
{
string capname = ScanCapname();
if (IsCaptureName(capname))
{
capnum = CaptureSlotFromName(capname);
}
// check if we have bogus character after the name
if (CharsRight() > 0 && !(RightChar() == close || RightChar() == '-'))
{
throw MakeException(RegexParseError.CaptureGroupNameInvalid, SR.CaptureGroupNameInvalid);
}
}
else if (ch == '-')
{
proceed = true;
}
else
{
// bad group name - starts with something other than a word character and isn't a number
throw MakeException(RegexParseError.CaptureGroupNameInvalid, SR.CaptureGroupNameInvalid);
}
// grab part after - if any
if ((capnum != -1 || proceed) && CharsRight() > 1 && RightChar() == '-')
{
MoveRight();
ch = RightChar();
if ((uint)(ch - '0') <= 9)
{
uncapnum = ScanDecimal();
if (!IsCaptureSlot(uncapnum))
{
throw MakeException(RegexParseError.UndefinedNumberedReference, SR.Format(SR.UndefinedNumberedReference, uncapnum));
}
// check if we have bogus characters after the number
if (CharsRight() > 0 && RightChar() != close)
{
throw MakeException(RegexParseError.CaptureGroupNameInvalid, SR.CaptureGroupNameInvalid);
}
}
else if (RegexCharClass.IsBoundaryWordChar(ch))
{
string uncapname = ScanCapname();
if (IsCaptureName(uncapname))
{
uncapnum = CaptureSlotFromName(uncapname);
}
else
{
throw MakeException(RegexParseError.UndefinedNamedReference, SR.Format(SR.UndefinedNamedReference, uncapname));
}
// check if we have bogus character after the name
if (CharsRight() > 0 && RightChar() != close)
{
throw MakeException(RegexParseError.CaptureGroupNameInvalid, SR.CaptureGroupNameInvalid);
}
}
else
{
// bad group name - starts with something other than a word character and isn't a number
throw MakeException(RegexParseError.CaptureGroupNameInvalid, SR.CaptureGroupNameInvalid);
}
}
// actually make the node
if ((capnum != -1 || uncapnum != -1) && CharsRight() > 0 && RightCharMoveRight() == close)
{
return new RegexNode(RegexNodeKind.Capture, _options, capnum, uncapnum);
}
goto BreakRecognize;
}
break;
case '(':
// conditional alternation construct (?(...) | )
int parenPos = Textpos();
if (CharsRight() > 0)
{
ch = RightChar();
// check if the alternation condition is a backref
if (ch >= '0' && ch <= '9')
{
int capnum = ScanDecimal();
if (CharsRight() > 0 && RightCharMoveRight() == ')')
{
if (IsCaptureSlot(capnum))
{
return new RegexNode(RegexNodeKind.BackreferenceConditional, _options, capnum);
}
throw MakeException(RegexParseError.AlternationHasUndefinedReference, SR.Format(SR.AlternationHasUndefinedReference, capnum.ToString()));
}