-
Notifications
You must be signed in to change notification settings - Fork 3
/
Tokenizer.RegExpParser.cs
1348 lines (1136 loc) · 57.3 KB
/
Tokenizer.RegExpParser.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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.RegularExpressions;
using Acornima.Helpers;
using Acornima.Properties;
namespace Acornima;
public partial class Tokenizer
{
[Flags]
internal enum RegExpFlags : byte
{
None = 0,
Global = 1 << 0,
IgnoreCase = 1 << 1,
Multiline = 1 << 2,
Unicode = 1 << 3,
Sticky = 1 << 4,
DotAll = 1 << 5,
Indices = 1 << 6,
UnicodeSets = 1 << 7
}
internal partial struct RegExpParser
{
private const string MatchAnyRegex = @"[\s\S]"; // .NET equivalent of /[^]/
private const string MatchNoneRegex = @"[^\s\S]"; // .NET equivalent of /[]/
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/dotAll#description
private const string MatchNewLineRegex = "[\n\r\u2028\u2029]";
private const string MatchAnyButNewLineRegex = "[^\n\r\u2028\u2029]";
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Character_classes#types
// https://learn.microsoft.com/en-us/dotnet/standard/base-types/character-classes-in-regular-expressions#whitespace-character-s
private const string AdditionalWhiteSpacePattern = "\u00A0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000\uFEFF";
private const int SetRangeNotStarted = int.MaxValue;
private const int SetRangeStartedWithCharClass = int.MaxValue - 1;
internal static RegExpFlags ParseFlags(string value, int startIndex, Tokenizer tokenizer)
{
var flags = RegExpFlags.None;
var ecmaVersion = tokenizer._options._ecmaVersion;
for (var i = 0; i < value.Length; i++)
{
var flag = value[i] switch
{
'g' => RegExpFlags.Global,
'i' => RegExpFlags.IgnoreCase,
'm' => RegExpFlags.Multiline,
'u' when ecmaVersion >= EcmaVersion.ES6 => RegExpFlags.Unicode,
'y' when ecmaVersion >= EcmaVersion.ES6 => RegExpFlags.Sticky,
's' when ecmaVersion >= EcmaVersion.ES9 => RegExpFlags.DotAll,
'd' when ecmaVersion >= EcmaVersion.ES13 => RegExpFlags.Indices,
'v' when ecmaVersion == EcmaVersion.Experimental => RegExpFlags.UnicodeSets,
_ => RegExpFlags.None
};
if (flag == RegExpFlags.None || (flags & flag) != 0)
{
// unknown or already set
tokenizer.Raise(startIndex, SyntaxErrorMessages.InvalidRegExpFlags);
}
flags |= flag;
}
if ((flags & RegExpFlags.UnicodeSets) != 0 && (flags & RegExpFlags.Unicode) != 0)
{
// cannot have them both
tokenizer.Raise(startIndex, SyntaxErrorMessages.InvalidRegExpFlags);
}
return flags;
}
private static RegexOptions FlagsToOptions(RegExpFlags flags, bool compiled)
{
// https://learn.microsoft.com/en-us/dotnet/standard/base-types/regular-expression-options#ecmascript-matching-behavior
// https://learn.microsoft.com/en-us/dotnet/standard/base-types/regular-expression-options#compare-using-the-invariant-culture
var options = RegexOptions.ECMAScript | RegexOptions.CultureInvariant;
if (compiled)
{
options |= RegexOptions.Compiled;
}
// Flags 's' and 'm' need special care as the equivalent RegexOptions flags have different behavior.
if ((flags & RegExpFlags.IgnoreCase) != 0)
{
// There are subtle differences between the case-insensitive matching behaviors of the JS and .NET regex engines.
// As a matter of fact, JS uses different algorithms in non-unicode and unicode mode (see https://tc39.es/ecma262/#sec-runtime-semantics-canonicalize-ch)
// and, unfortunately, .NET matches neither of them. By specifying RegexOptions.CultureInvariant we can approximate the non-unicode behavior to some extent
// (as it's based on the language-neutral Unicode Default Case Conversion; though it canonicalizes to upper case as opposed to .NET's lower case approach).
// However, there will still be differences: e. g. "\u2126" (Ω) isn't matched by /[ω]/i while it is by the same pattern in .NET.
// As for unicode mode, supposedly we have even more differences in behavior (e.g. "ſ" vs. "s").
// Maybe we could improve the situation by implementing a CultureInfo with a custom TextInfo but that wouldn't be an easy task and
// probably we would hit a wall anyway as the .NET regex engine seems to do a lot of internal shenanigans around case insensitive matching...
// https://learn.microsoft.com/en-us/dotnet/standard/base-types/regular-expression-options#case-insensitive-matching
options |= RegexOptions.IgnoreCase;
}
return options;
}
private readonly string _pattern;
private readonly int _patternStartIndex;
private readonly RegExpFlags _flags;
private readonly string _flagsOriginal;
private readonly Tokenizer _tokenizer;
private StringBuilder? _auxiliaryStringBuilder;
public RegExpParser(string pattern, int patternStartIndex, string flags, int flagsStartIndex, Tokenizer tokenizer)
{
_pattern = pattern;
_patternStartIndex = patternStartIndex;
_flags = ParseFlags(flags, flagsStartIndex, tokenizer);
_flagsOriginal = flags;
_tokenizer = tokenizer;
}
public RegExpParser(string pattern, string flags, TokenizerOptions tokenizerOptions)
: this(pattern, patternStartIndex: 0, flags, flagsStartIndex: 0, new Tokenizer(flags, tokenizerOptions))
{
_tokenizer.Reset(pattern);
}
private readonly ParseError ReportConversionFailure(int index, string reason)
{
return _tokenizer.RaiseRecoverable(_patternStartIndex + index,
$"Cannot convert regular expression to an equivalent {typeof(Regex).ToString()}: /{_pattern}/{_flagsOriginal}: {reason}",
ParseError.s_factory); // TODO: introduce dedicated Exception class?
}
[DoesNotReturn]
private readonly void ReportSyntaxError(int index, string messageFormat)
{
_tokenizer.Raise(_patternStartIndex + index, string.Format(CultureInfo.InvariantCulture, messageFormat, _pattern, _flagsOriginal));
}
public RegExpParseResult Parse()
{
ParseError? conversionError;
if ((_flags & RegExpFlags.UnicodeSets) != 0)
{
const string unicodeSetsModeNotSupported = "Unicode sets mode (flag v) is not supported currently";
if (_tokenizer._options._regExpParseMode == RegExpParseMode.Validate)
{
_tokenizer.Raise(_patternStartIndex, unicodeSetsModeNotSupported, ParseError.s_factory);
}
else
{
conversionError = ReportConversionFailure(0, unicodeSetsModeNotSupported);
return new RegExpParseResult(conversionError);
}
}
var adaptedPattern = ParseCore(out var capturingGroups, out conversionError);
if (adaptedPattern is null)
{
// NOTE: ParseCore should return null
// * in validation-only mode (RegExpParseMode.Validation) or
// * in conversion mode (RegExpParseMode.AdaptTo*), when it fails to construct an equivalent Regex.
Debug.Assert(conversionError is not null ^ _tokenizer._options.RegExpParseMode == RegExpParseMode.Validate);
return new RegExpParseResult(conversionError);
}
Debug.Assert(conversionError is null);
capturingGroups.TrimExcess();
var options = FlagsToOptions(_flags, compiled: _tokenizer._options._regExpParseMode == RegExpParseMode.AdaptToCompiled);
var matchTimeout = _tokenizer._options._regexTimeout;
try
{
return new RegExpParseResult(new Regex(adaptedPattern, options, matchTimeout), capturingGroups);
}
catch
{
conversionError = ReportConversionFailure(0, "Failed to adapt regular expression");
return new RegExpParseResult(conversionError);
}
}
internal string? ParseCore(out ArrayList<RegExpCapturingGroup> capturingGroups, out ParseError? conversionError)
{
_tokenizer.AcquireStringBuilder(out var sb);
try
{
StringBuilder? adaptedPatternBuilder;
if (_tokenizer._options._regExpParseMode == RegExpParseMode.Validate)
{
_auxiliaryStringBuilder = sb;
adaptedPatternBuilder = null;
}
else
{
if (sb.Capacity < _pattern.Length)
{
sb.Capacity = _pattern.Length;
}
adaptedPatternBuilder = sb;
}
CheckBracesBalance(out capturingGroups, out var capturingGroupNames);
var context = new ParsePatternContext(adaptedPatternBuilder, capturingGroups.AsReadOnlySpan(), capturingGroupNames)
{
CapturingGroupCounter = 0,
GroupStack = capturingGroupNames is not null
? new ArrayList<RegExpGroup>(new[] { new RegExpGroup(default, parent: null) })
: default,
SetStartIndex = -1,
FollowingQuantifierError = SyntaxErrorMessages.RegExpNothingToRepeat,
};
return (_flags & RegExpFlags.Unicode) != 0
? ParsePattern(UnicodeMode.Instance, ref context, out conversionError)
: ParsePattern(LegacyMode.Instance, ref context, out conversionError);
}
finally
{
_tokenizer.ReleaseStringBuilder(ref sb);
_auxiliaryStringBuilder = null;
}
}
/// <summary>
/// Ensures the braces are balanced in the regular expression pattern.
/// </summary>
private void CheckBracesBalance(out ArrayList<RegExpCapturingGroup> capturingGroups, out Dictionary<string, string?>? capturingGroupNames)
{
capturingGroups = default;
capturingGroupNames = null;
var isUnicode = (_flags & RegExpFlags.Unicode) != 0;
var inGroup = 0;
var inQuantifier = false;
var inSet = false;
// Potential problematic constructs:
// * Escaped opening/closing brackets (\(, \), \[, \], \{, \}, \<, \>) --> These are handled (see below).
// * ?<Name> and \k<Name> --> Shouldn't be an actual problem as opening/closing brackets are not allowed to occur in capturing group names.
// * \p{...} --> Might be problematic as, in theory, property values can contain special chars (see https://unicode.org/reports/tr18/#property_syntax),
// however it seems that currently no such value is defined (see https://unicode.org/Public/UCD/latest/ucd/PropertyValueAliases.txt),
// so we can ignore this for now.
for (var i = 0; i < _pattern.Length; i++)
{
var ch = _pattern[i];
if (ch == '\\')
{
// Skip escape
i++;
continue;
}
switch (ch)
{
case '(':
if (inSet)
{
break;
}
inGroup++;
var groupType = DetermineGroupType(i);
if (groupType == RegExpGroupType.Capturing)
{
capturingGroups.Add(new RegExpCapturingGroup(i, name: null));
}
else if (groupType == RegExpGroupType.NamedCapturing)
{
var groupStartIndex = i++;
var groupName = ReadNormalizedCapturingGroupName(ref i)!;
var isDuplicate = !(capturingGroupNames ??= new Dictionary<string, string?>()).TryAdd(groupName, null);
if (isDuplicate && _tokenizer._options._ecmaVersion != EcmaVersion.Experimental)
{
ReportSyntaxError(groupStartIndex + 3, SyntaxErrorMessages.RegExpDuplicateCaptureGroupName);
}
capturingGroups.Add(new RegExpCapturingGroup(i, groupName));
}
else if (groupType == RegExpGroupType.Unknown)
{
ReportSyntaxError(i, SyntaxErrorMessages.RegExpInvalidGroup);
}
break;
case ')':
if (inSet)
{
break;
}
if (inGroup == 0)
{
ReportSyntaxError(i, SyntaxErrorMessages.RegExpUnmatchedOpenParen);
}
inGroup--;
break;
case '{':
if (inSet)
{
break;
}
if (!inQuantifier)
{
inQuantifier = true;
}
else if (isUnicode)
{
ReportSyntaxError(i, SyntaxErrorMessages.RegExpIncompleteQuantifier);
}
break;
case '}':
if (inSet)
{
break;
}
if (inQuantifier)
{
inQuantifier = false;
}
else if (isUnicode)
{
ReportSyntaxError(i, SyntaxErrorMessages.RegExpLoneQuantifierBrackets);
}
break;
case '[':
if (inSet)
{
break;
}
inSet = true;
break;
case ']':
if (inSet)
{
inSet = false;
}
else if (isUnicode)
{
ReportSyntaxError(i, SyntaxErrorMessages.RegExpLoneQuantifierBrackets);
}
break;
default:
break;
}
}
if (inGroup > 0)
{
ReportSyntaxError(_pattern.Length, SyntaxErrorMessages.RegExpUnterminatedGroup);
}
if (inSet)
{
ReportSyntaxError(_pattern.Length, SyntaxErrorMessages.RegExpUnterminatedCharacterClass);
}
if (isUnicode)
{
if (inQuantifier)
{
ReportSyntaxError(_pattern.Length, SyntaxErrorMessages.RegExpLoneQuantifierBrackets);
}
}
}
/// <summary>
/// Check the regular expression pattern for additional syntax errors and optionally build an adjusted pattern which
/// implements the equivalent behavior in .NET, on top of the <see cref="RegexOptions.ECMAScript"/> compatibility mode.
/// </summary>
/// <returns>
/// <see langword="null"/> if the tokenizer is configured to validate the regular expression pattern but not adapt it to .NET.
/// Otherwise, the adapted pattern or <see langword="null"/> if the pattern is syntactically correct but a .NET equivalent could not be constructed
/// and the tokenizer is configured to tolerant mode.
/// </returns>
private string? ParsePattern<TMode>(TMode mode, ref ParsePatternContext context, out ParseError? conversionError)
where TMode : IMode
{
ref readonly var sb = ref context.StringBuilder;
ref var i = ref context.Index;
for (i = 0; i < _pattern.Length; i++)
{
var ch = _pattern[i];
switch (ch)
{
case '[' when !context.WithinSet:
context.SetStartIndex = i;
context.SetRangeStart = SetRangeNotStarted;
mode.ProcessSetSpecialChar(ref context, ch);
if ((ch = (char)_pattern.CharCodeAt(i + 1)) == '^')
{
mode.ProcessSetSpecialChar(ref context, ch);
i++;
}
break;
case '-' when context.WithinSet:
if (context.SetRangeStart is >= 0 and not SetRangeNotStarted)
{
// We use bitwise complement to indicate that '-' was encountered after a character (or character class like \d or \p{...}).
context.SetRangeStart = ~context.SetRangeStart;
mode.ProcessSetSpecialChar(ref context, ch);
}
else
{
// We encountered a case like /[-]/, /[0-9-]/, /[0-/d-]/, /[/d-0-]/ or /[\0--]/
mode.ProcessSetChar(ref context, ch, context.AppendCharSafe, ref this, startIndex: i);
}
break;
case ']':
if (!context.WithinSet)
{
Debug.Assert(mode is LegacyMode, SyntaxErrorMessages.RegExpLoneQuantifierBrackets); // CheckBracesBalance should ensure this.
goto default;
}
if (!mode.RewriteSet(ref context, ref this))
{
mode.ProcessSetSpecialChar(ref context, ch);
}
context.SetStartIndex = -1;
context.FollowingQuantifierError = null;
break;
case '(' when !context.WithinSet:
var currentGroupAlternate = context.CapturingGroupNames is not null
? context.GroupStack.PeekRef().LastAlternate
: null;
var groupType = DetermineGroupType(i);
if (groupType == RegExpGroupType.Capturing)
{
context.CapturingGroupCounter++;
}
else if (groupType == RegExpGroupType.NamedCapturing)
{
var groupName = context.CapturingGroups[context.CapturingGroupCounter++].Name;
Debug.Assert(groupName is not null);
if (!currentGroupAlternate!.TryAddGroupName(groupName!))
{
ReportSyntaxError(i + 3, SyntaxErrorMessages.RegExpDuplicateCaptureGroupName);
}
if (sb is not null)
{
groupName = AdjustCapturingGroupName(groupName!, context.CapturingGroupNames!);
if (groupName is null)
{
conversionError = ReportConversionFailure(i + 3, $"Cannot map group name '{groupName}' to a unique group name in the adapted regex.");
return null;
}
// The JS regex engine assigns numbers to capturing groups sequentially (regardless of the group being named or not named)
// but .NET uses a different, weird approach:
// "[...] Captures that use parentheses are numbered automatically from left to right
// based on the order of the opening parentheses in the regular expression, starting from 1.
// However, named capture groups are always ordered last, after non-named capture groups. [...]"
// (See also: https://learn.microsoft.com/en-us/dotnet/standard/base-types/grouping-constructs-in-regular-expressions#grouping-constructs-and-regular-expression-objects)
// This could totally mess up numbered backreferences and replace pattern references. So, as a workaround, we wrap all named capturing groups
// in a plain (numbered) capturing group to force .NET to include all capturing groups in the resulting match in the expected order.
// (Named groups will also be listed after these but we can't do anything about that.)
sb.Append('(').Append(_pattern, i, 3).Append(groupName);
}
i = _pattern.IndexOf('>', i + 3);
Debug.Assert(i >= 0);
sb?.Append(_pattern[i]);
context.GroupStack.Push(new RegExpGroup(groupType, currentGroupAlternate));
context.FollowingQuantifierError = SyntaxErrorMessages.RegExpNothingToRepeat;
break;
}
sb?.Append(_pattern, i, 1 + ((int)groupType >> 2));
i += (int)groupType >> 2;
context.GroupStack.Push(currentGroupAlternate is not null
? new RegExpGroup(groupType, currentGroupAlternate)
: new RegExpGroup(groupType));
context.FollowingQuantifierError = SyntaxErrorMessages.RegExpNothingToRepeat;
break;
case '|' when !context.WithinSet:
sb?.Append(ch);
if (context.CapturingGroupNames is not null)
{
context.GroupStack.PeekRef().AddAlternate();
}
context.FollowingQuantifierError = SyntaxErrorMessages.RegExpNothingToRepeat;
break;
case ')' when !context.WithinSet:
Debug.Assert(context.GroupStack.Count > (context.CapturingGroupNames is not null ? 1 : 0), SyntaxErrorMessages.RegExpUnmatchedOpenParen); // CheckBracesBalance should ensure this.
if (context.CapturingGroupNames is not null)
{
context.GroupStack.PeekRef().HoistGroupNamesToParent();
}
groupType = context.GroupStack.Pop().Type;
if (sb is not null)
{
sb.Append(ch);
if (groupType == RegExpGroupType.NamedCapturing)
{
sb.Append(')');
}
}
context.FollowingQuantifierError = mode.AllowsQuantifierAfterGroup(groupType) ? null : SyntaxErrorMessages.RegExpInvalidQuantifier;
break;
// RegexOptions.Multiline matches only '\n' and has other behavioral differences (e.g. "a\r\n\b".match(/^$/m) matches,
// while Regex.Matches("a\r\n\b", @"^$", RegexOptions.ECMAScript | RegexOptions.Multiline) doesn't!)
// We can simulate this using RegexOptions.ECMAScript (without RegexOptions.Multiline) + positive lookbehind/lookahead.
case '^' when !context.WithinSet:
if (sb is not null)
{
_ = (_flags & RegExpFlags.Multiline) != 0
? sb.Append("(?<=").Append(MatchNewLineRegex).Append('|').Append(ch).Append(')')
: sb.Append(ch);
}
context.FollowingQuantifierError = SyntaxErrorMessages.RegExpNothingToRepeat;
break;
case '$' when !context.WithinSet:
if (sb is not null)
{
_ = (_flags & RegExpFlags.Multiline) != 0
? sb.Append("(?=").Append(MatchNewLineRegex).Append('|').Append(ch).Append(')')
: sb.Append(ch);
}
context.FollowingQuantifierError = SyntaxErrorMessages.RegExpNothingToRepeat;
break;
case '.' when !context.WithinSet:
// The behavior of /./ depends on multiple flags:
// * Flag 's' determines whether to match new line characters or not (see https://github.com/tc39/proposal-regexp-dotall-flag).
// We need to rewrite dots even in the latter case because RegexOptions.ECMAScript doesn't handle them correctly as
// it only treats '\n' as new line while JS treats a few other characters like that as well.
// * Flag 'u' also changes the behavior (it must match code points instead of characters).
mode.RewriteDot(ref context, (_flags & RegExpFlags.DotAll) != 0);
context.FollowingQuantifierError = null;
break;
case '*' or '+' or '?' when !context.WithinSet:
if (context.FollowingQuantifierError is not null)
{
ReportSyntaxError(i, context.FollowingQuantifierError);
}
sb?.Append(ch);
if ((ch = (char)_pattern.CharCodeAt(i + 1)) == '?')
{
sb?.Append(ch);
i++;
}
context.FollowingQuantifierError = SyntaxErrorMessages.RegExpNothingToRepeat;
break;
case '{' when !context.WithinSet:
if (!TryAdjustRangeQuantifier(ref context, out conversionError))
{
mode.HandleInvalidRangeQuantifier(ref context, ref this, i);
break;
}
else if (conversionError is not null)
{
return null;
}
if ((ch = (char)_pattern.CharCodeAt(i + 1)) == '?')
{
sb?.Append(ch);
i++;
}
context.FollowingQuantifierError = SyntaxErrorMessages.RegExpNothingToRepeat;
break;
case '\\':
Debug.Assert(i + 1 < _pattern.Length, "Unexpected end of escape sequence in regular expression.");
if (!mode.AdjustEscapeSequence(ref context, ref this, out conversionError))
{
return null;
}
break;
default:
if (!context.WithinSet)
{
mode.ProcessChar(ref context, ch, context.AppendChar, ref this);
context.FollowingQuantifierError = null;
}
else
{
mode.ProcessSetChar(ref context, ch,
!(ch == '[' && context.SetRangeStart < 0) ? context.AppendChar : context.AppendCharSafe,
ref this, startIndex: i);
}
break;
}
}
conversionError = null;
return sb?.ToString();
}
private static readonly Action<StringBuilder, char> s_appendChar = static (sb, ch) => sb.Append(ch);
private static readonly Action<StringBuilder, char> s_appendCharSafe = AppendCharSafe;
private static void AppendCharSafe(StringBuilder sb, char ch)
{
// We don't unescape character code sequences in the printable ASCII character range (U+0020..U+007E) to
// prevent problems which could arise in the case of special regex characters.
// (This could be further optimized though by unescaping + escaping the problematic characters with '\'.)
_ = ch.IsInRange(0x20, 0x7E)
? sb.Append('\\').Append('x').Append(((byte)ch).ToString("X2", CultureInfo.InvariantCulture))
: sb.Append(ch);
}
private static bool TryReadHexEscape(string pattern, ref int i, int endIndex, int charCodeLength, out ushort charCode)
{
if (i + charCodeLength < endIndex)
{
if (ushort.TryParse(pattern.AsSpan(i + 1, charCodeLength).ToParsable(), NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out charCode))
{
i += charCodeLength;
return true;
}
}
charCode = default;
return false;
}
private static bool TryReadCodePoint(string pattern, ref int i, int endIndex, out int cp)
{
var escapeEndIndex = pattern.IndexOf('}', i + 2, endIndex - (i + 2));
if (escapeEndIndex < 0)
{
cp = default;
return false;
}
var slice = pattern.AsSpan(i + 2, escapeEndIndex - (i + 2));
if (!int.TryParse(slice.ToParsable(), NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out cp)
// NOTE: int.TryParse with NumberStyles.AllowHexSpecifier may return a negative number (e.g. '80000000' -> -2147483648)!
|| (uint)cp > UnicodeHelper.LastCodePoint)
{
cp = default;
return false;
}
i = escapeEndIndex;
return true;
}
private static bool TryGetSimpleEscapeCharCode(char ch, bool withinSet, out ushort charCode)
{
switch (ch)
{
// Assertion (word boundary) / Backspace
case 'b':
// NOTE: For the sake of simplicity, we also use this logic for validation in unicode mode,
// so we return an unused dummy value for word boundary escapes outside character sets.
charCode = withinSet ? '\b' : char.MaxValue;
return true;
case 'B':
charCode = char.MaxValue;
return !withinSet;
// CharacterEscape -> ControlEscape
case 'f': charCode = '\f'; return true;
case 'n': charCode = '\n'; return true;
case 't': charCode = '\t'; return true;
case 'r': charCode = '\r'; return true;
case 'v': charCode = '\v'; return true;
// CharacterEscape -> IdentityEscape -> '/'
case '/':
// CharacterEscape -> IdentityEscape -> SyntaxCharacter
case '^' or '$' or '\\' or '.' or '*' or '+' or '?' or '(' or ')' or '[' or ']' or '{' or '}' or '|':
charCode = ch;
return true;
// '-' is not a SyntaxCharacter by definition but must be escaped in character sets.
// (However, outside the class it is not allowed to be escaped in unicode mode!)
case '-':
charCode = ch;
return withinSet;
}
charCode = default;
return false;
}
private readonly bool TryAdjustRangeQuantifier(ref ParsePatternContext context, out ParseError? conversionError)
{
conversionError = null;
ref readonly var sb = ref context.StringBuilder;
ref var i = ref context.Index;
var endIndex = _pattern.IndexOf('}', i + 1);
if (endIndex < 0 || endIndex == i + 1)
{
return false;
}
var index = _pattern.IndexOf(',', i + 1, endIndex - (i + 1));
if (index < 0)
{
index = endIndex;
}
int min, max;
var slice = _pattern.AsSpan(i + 1, index - (i + 1));
if (!int.TryParse(slice.ToParsable(), NumberStyles.None, CultureInfo.InvariantCulture, out min))
{
if (slice.Length == 0 || slice.FindIndex(ch => !ch.IsDecimalDigit()) >= 0)
{
return false;
}
min = -1;
}
if (index == endIndex)
{
max = min;
}
else if (index == endIndex - 1)
{
max = int.MaxValue;
}
else
{
slice = _pattern.AsSpan(index + 1, endIndex - (index + 1));
if (!int.TryParse(slice.ToParsable(), NumberStyles.None, CultureInfo.InvariantCulture, out max))
{
if (slice.FindIndex(ch => !ch.IsDecimalDigit()) >= 0)
{
min = max = default;
return false;
}
max = -1;
}
}
if (min >= 0 && max >= 0)
{
if (min > max)
{
ReportSyntaxError(i, SyntaxErrorMessages.RegExpNumbersOutOfOrderInQuantifier);
}
if (context.FollowingQuantifierError is not null)
{
ReportSyntaxError(i, context.FollowingQuantifierError);
}
sb?.Append(_pattern, i, endIndex + 1 - i);
}
else if (sb is not null)
{
// According to the spec (https://tc39.es/ecma262/#sec-patterns-static-semantics-early-errors),
// number of occurrences can be an arbitrarily big number, however implementations (incl. V8) seems to ignore numbers greater than int.MaxValue.
// (e.g. /x{2147483647,2147483646}/ is syntax error while /x{2147483648,2147483647}/ is not!)
// We report failure in this case because .NET regex engine doesn't allow numbers greater than int.MaxValue.
conversionError = ReportConversionFailure(i, "Inconvertible {} quantifier");
return true;
}
i = endIndex;
return true;
}
private readonly RegExpGroupType DetermineGroupType(int i)
{
if (++i >= _pattern.Length || _pattern[i] != '?')
{
return RegExpGroupType.Capturing;
}
if (++i >= _pattern.Length)
{
return RegExpGroupType.Unknown;
}
return _pattern[i] switch
{
':' => RegExpGroupType.NonCapturing,
'=' => RegExpGroupType.LookaheadAssertion,
'!' => RegExpGroupType.NegativeLookaheadAssertion,
'<' when _tokenizer._options._ecmaVersion >= EcmaVersion.ES9 => (++i < _pattern.Length ? _pattern[i] : char.MinValue) switch
{
'=' => RegExpGroupType.LookbehindAssertion,
'!' => RegExpGroupType.NegativeLookbehindAssertion,
_ => RegExpGroupType.NamedCapturing,
},
_ => RegExpGroupType.Unknown
};
}
private string? ReadNormalizedCapturingGroupName(ref int i)
{
if (_pattern.CharCodeAt(i + 1) == '<')
{
var startIndex = i + 2;
var endIndex = _pattern.IndexOf('>', startIndex);
if (endIndex >= 0)
{
var cp = _pattern.CodePointAt(i += 2, endIndex);
var allowAstral = (_flags & RegExpFlags.Unicode) != 0 || _tokenizer._options.EcmaVersion >= EcmaVersion.ES11;
if (IsIdentifierStart(cp, allowAstral) || cp == '\\')
{
var groupName = ReadIdentifier(ref i, endIndex, allowAstral);
if (i == endIndex)
{
return DeduplicateString(groupName, ref _tokenizer._stringPool);
}
}
}
ReportSyntaxError(startIndex, SyntaxErrorMessages.RegExpInvalidCaptureGroupName);
}
return null;
}
private ReadOnlySpan<char> ReadIdentifier(ref int i, int endIndex, bool allowAstral)
{
var containsEscape = false;
var sb = _auxiliaryStringBuilder is not null ? _auxiliaryStringBuilder.Clear() : _auxiliaryStringBuilder = new StringBuilder();
var first = true;
var chunkStart = i;
for (int cp; (cp = _pattern.CodePointAt(i, endIndex)) >= 0;)
{
if (IsIdentifierChar(cp, allowAstral))
{
i += UnicodeHelper.GetCodePointLength((uint)cp);
}
else if (cp == '\\')
{
containsEscape = true;
sb.Append(_pattern, chunkStart, i - chunkStart);
var escStart = i++;
if (_pattern.CharCodeAt(i, endIndex) != 'u')
{
i = -1;
return default;
}
if (_pattern.CharCodeAt(i + 1, endIndex) == '{')
{
if (!allowAstral)
{
i = -1;
return default;
}
else if (!TryReadCodePoint(_pattern, ref i, endIndex, out cp))
{
ReportSyntaxError(escStart, SyntaxErrorMessages.RegExpInvalidUnicodeEscape);
}
++i;
}
else
{
if (!TryReadHexEscape(_pattern, ref i, endIndex, charCodeLength: 4, out var ch))
{
ReportSyntaxError(escStart, SyntaxErrorMessages.RegExpInvalidUnicodeEscape);
}
cp = ch;
++i;
if (allowAstral && ((char)ch).IsHighSurrogate() && i + 1 < endIndex && _pattern[i] == '\\' && _pattern[i + 1] == 'u')
{
escStart = i++;
if (TryReadHexEscape(_pattern, ref i, endIndex, charCodeLength: 4, out var ch2) && ((char)ch2).IsLowSurrogate())
{
++i;
cp = (int)UnicodeHelper.GetCodePoint((char)ch, (char)ch2);
}
else
{
i = escStart;
}
}
}
if (first
? !IsIdentifierStart(cp, allowAstral)
: !IsIdentifierChar(cp, allowAstral))
{
i = -1;
return default;
}
sb.AppendCodePoint(cp);
chunkStart = i;
}
else
{
break;
}
first = false;
}
return !containsEscape
? _pattern.SliceBetween(chunkStart, i)
: sb.Append(_pattern, chunkStart, i - chunkStart).ToString().AsSpan();
}
private static string? AdjustCapturingGroupName(string groupName, Dictionary<string, string?> capturingGroupNames)
{
// 0. Check that the adjusted name is already available.
var adjustedGroupName = capturingGroupNames[groupName];
if (adjustedGroupName is not null)
{
return adjustedGroupName;
}
// .NET capture group names can't start with a decimal digit (luckily, JS capture names can't either) and
// can only contain characters defined by the IsWordChar method
// (see also https://github.com/dotnet/runtime/blob/v6.0.16/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexParser.cs#L868)
// 1. When the group name contains invalid characters, rewrite it to a string which is a valid group name in .NET and can be reversed
if (groupName.AsSpan().FindIndex(ch => !IsWordChar(ch)) < 0)
{
capturingGroupNames[groupName] = groupName;
return groupName;
}
adjustedGroupName = EncodeGroupName(groupName);
// 2. Check that the adjusted group name is unique.
if (!capturingGroupNames.ContainsKey(adjustedGroupName))
{
capturingGroupNames[groupName] = adjustedGroupName;
return adjustedGroupName;
}
return null;
static bool IsWordChar(char ch)
{
// Source: https://github.com/dotnet/runtime/blob/v6.0.16/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexCharClass.cs#L918
// According to UTS#18 Unicode Regular Expressions (http://www.unicode.org/reports/tr18/)