-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
Copy pathRegexGenerator.Emitter.cs
5096 lines (4518 loc) · 282 KB
/
RegexGenerator.Emitter.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.CodeDom.Compiler;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
// NOTE: The logic in this file is largely a duplicate of logic in RegexCompiler, emitting C# instead of MSIL.
// Most changes made to this file should be kept in sync, so far as bug fixes and relevant optimizations
// are concerned.
namespace System.Text.RegularExpressions.Generator
{
public partial class RegexGenerator
{
/// <summary>Emits the definition of the partial method. This method just delegates to the property cache on the generated Regex-derived type.</summary>
private static void EmitRegexPartialMethod(RegexMethod regexMethod, IndentedTextWriter writer)
{
// Emit the namespace.
RegexType? parent = regexMethod.DeclaringType;
if (!string.IsNullOrWhiteSpace(parent.Namespace))
{
writer.WriteLine($"namespace {parent.Namespace}");
writer.WriteLine("{");
writer.Indent++;
}
// Emit containing types.
var parentClasses = new Stack<string>();
while (parent is not null)
{
parentClasses.Push($"partial {parent.Keyword} {parent.Name}");
parent = parent.Parent;
}
while (parentClasses.Count != 0)
{
writer.WriteLine($"{parentClasses.Pop()}");
writer.WriteLine("{");
writer.Indent++;
}
// Emit the partial method definition.
writer.WriteLine("/// <remarks>");
writer.WriteLine("/// Pattern explanation:<br/>");
writer.WriteLine("/// <code>");
DescribeExpressionAsXmlComment(writer, regexMethod.Tree.Root.Child(0), regexMethod); // skip implicit root capture
writer.WriteLine("/// </code>");
writer.WriteLine("/// </remarks>");
writer.WriteLine($"[global::System.CodeDom.Compiler.{s_generatedCodeAttribute}]");
writer.WriteLine($"{regexMethod.Modifiers} global::System.Text.RegularExpressions.Regex {regexMethod.MethodName}() => global::{GeneratedNamespace}.{regexMethod.GeneratedName}.Instance;");
// Unwind all scopes
while (writer.Indent != 0)
{
writer.Indent--;
writer.WriteLine("}");
}
}
/// <summary>Emits the Regex-derived type for a method where we're unable to generate custom code.</summary>
private static void EmitRegexLimitedBoilerplate(
IndentedTextWriter writer, RegexMethod rm, string reason)
{
writer.WriteLine($"/// <summary>Caches a <see cref=\"Regex\"/> instance for the {rm.MethodName} method.</summary>");
writer.WriteLine($"/// <remarks>A custom Regex-derived type could not be generated because {reason}.</remarks>");
writer.WriteLine($"[{s_generatedCodeAttribute}]");
writer.WriteLine($"file sealed class {rm.GeneratedName} : Regex");
writer.WriteLine($"{{");
writer.WriteLine($" /// <summary>Cached, thread-safe singleton instance.</summary>");
writer.Write($" internal static readonly Regex Instance = ");
writer.WriteLine(
rm.MatchTimeout is not null ? $"new({Literal(rm.Pattern)}, {Literal(rm.Options)}, {GetTimeoutExpression(rm.MatchTimeout.Value)});" :
rm.Options != 0 ? $"new({Literal(rm.Pattern)}, {Literal(rm.Options)});" :
$"new({Literal(rm.Pattern)});");
writer.WriteLine($"}}");
}
/// <summary>Name of the helper type field that indicates the process-wide default timeout.</summary>
private const string DefaultTimeoutFieldName = "s_defaultTimeout";
/// <summary>Name of the helper type field that indicates whether <see cref="DefaultTimeoutFieldName"/> is non-infinite.</summary>
private const string HasDefaultTimeoutFieldName = "s_hasTimeout";
/// <summary>Emits the Regex-derived type for a method whose RunnerFactory implementation was generated into <paramref name="runnerFactoryImplementation"/>.</summary>
private static void EmitRegexDerivedImplementation(
IndentedTextWriter writer, RegexMethod rm, string runnerFactoryImplementation, bool allowUnsafe)
{
writer.WriteLine($"/// <summary>Custom <see cref=\"Regex\"/>-derived type for the {rm.MethodName} method.</summary>");
writer.WriteLine($"[{s_generatedCodeAttribute}]");
if (allowUnsafe)
{
writer.WriteLine($"[SkipLocalsInit]");
}
writer.WriteLine($"file sealed class {rm.GeneratedName} : Regex");
writer.WriteLine($"{{");
writer.WriteLine($" /// <summary>Cached, thread-safe singleton instance.</summary>");
writer.WriteLine($" internal static readonly {rm.GeneratedName} Instance = new();");
writer.WriteLine($"");
writer.WriteLine($" /// <summary>Initializes the instance.</summary>");
writer.WriteLine($" private {rm.GeneratedName}()");
writer.WriteLine($" {{");
writer.WriteLine($" base.pattern = {Literal(rm.Pattern)};");
writer.WriteLine($" base.roptions = {Literal(rm.Options)};");
if (rm.MatchTimeout is not null)
{
writer.WriteLine($" base.internalMatchTimeout = {GetTimeoutExpression(rm.MatchTimeout.Value)};");
}
else
{
writer.WriteLine($" ValidateMatchTimeout({HelpersTypeName}.{DefaultTimeoutFieldName});");
writer.WriteLine($" base.internalMatchTimeout = {HelpersTypeName}.{DefaultTimeoutFieldName};");
}
writer.WriteLine($" base.factory = new RunnerFactory();");
if (rm.Tree.CaptureNumberSparseMapping is not null)
{
writer.Write(" base.Caps = new Hashtable {");
AppendHashtableContents(writer, rm.Tree.CaptureNumberSparseMapping.Cast<DictionaryEntry>().OrderBy(de => de.Key as int?));
writer.WriteLine($" }};");
}
if (rm.Tree.CaptureNameToNumberMapping is not null)
{
writer.Write(" base.CapNames = new Hashtable {");
AppendHashtableContents(writer, rm.Tree.CaptureNameToNumberMapping.Cast<DictionaryEntry>().OrderBy(de => de.Key as string, StringComparer.Ordinal));
writer.WriteLine($" }};");
}
if (rm.Tree.CaptureNames is not null)
{
writer.Write(" base.capslist = new string[] {");
string separator = "";
foreach (string s in rm.Tree.CaptureNames)
{
writer.Write(separator);
writer.Write(Literal(s));
separator = ", ";
}
writer.WriteLine($" }};");
}
writer.WriteLine($" base.capsize = {rm.Tree.CaptureCount};");
writer.WriteLine($" }}");
writer.WriteLine(runnerFactoryImplementation);
writer.WriteLine($"}}");
static void AppendHashtableContents(IndentedTextWriter writer, IEnumerable<DictionaryEntry> contents)
{
string separator = "";
foreach (DictionaryEntry en in contents)
{
writer.Write(separator);
separator = ", ";
writer.Write(" { ");
if (en.Key is int key)
{
writer.Write(key);
}
else
{
writer.Write($"\"{en.Key}\"");
}
writer.Write($", {en.Value} }} ");
}
}
}
/// <summary>Emits the code for the RunnerFactory. This is the actual logic for the regular expression.</summary>
private static void EmitRegexDerivedTypeRunnerFactory(IndentedTextWriter writer, RegexMethod rm, Dictionary<string, string[]> requiredHelpers, bool checkOverflow)
{
void EnterCheckOverflow()
{
if (checkOverflow)
{
writer.WriteLine($"unchecked");
writer.WriteLine($"{{");
writer.Indent++;
}
}
void ExitCheckOverflow()
{
if (checkOverflow)
{
writer.Indent--;
writer.WriteLine($"}}");
}
}
writer.WriteLine($"/// <summary>Provides a factory for creating <see cref=\"RegexRunner\"/> instances to be used by methods on <see cref=\"Regex\"/>.</summary>");
writer.WriteLine($"private sealed class RunnerFactory : RegexRunnerFactory");
writer.WriteLine($"{{");
writer.WriteLine($" /// <summary>Creates an instance of a <see cref=\"RegexRunner\"/> used by methods on <see cref=\"Regex\"/>.</summary>");
writer.WriteLine($" protected override RegexRunner CreateInstance() => new Runner();");
writer.WriteLine();
writer.WriteLine($" /// <summary>Provides the runner that contains the custom logic implementing the specified regular expression.</summary>");
writer.WriteLine($" private sealed class Runner : RegexRunner");
writer.WriteLine($" {{");
if (rm.MatchTimeout is null)
{
// We need to emit timeout checks for everything other than the developer explicitly setting Timeout.Infinite.
// In the common case where a timeout isn't specified, we need to at run-time check whether a process-wide
// default timeout has been specified, so we emit a static readonly TimeSpan to store the default value
// and a static readonly bool to store whether that value is non-infinite (the latter enables the JIT
// to remove all timeout checks as part of tiering if the default is infinite).
const string DefaultTimeoutHelpers = nameof(DefaultTimeoutHelpers);
if (!requiredHelpers.ContainsKey(DefaultTimeoutHelpers))
{
requiredHelpers.Add(DefaultTimeoutHelpers, new string[]
{
$"/// <summary>Default timeout value set in <see cref=\"AppContext\"/>, or <see cref=\"Regex.InfiniteMatchTimeout\"/> if none was set.</summary>",
$"internal static readonly TimeSpan {DefaultTimeoutFieldName} = AppContext.GetData(\"REGEX_DEFAULT_MATCH_TIMEOUT\") is TimeSpan timeout ? timeout : Regex.InfiniteMatchTimeout;",
$"",
$"/// <summary>Whether <see cref=\"{DefaultTimeoutFieldName}\"/> is non-infinite.</summary>",
$"internal static readonly bool {HasDefaultTimeoutFieldName} = {DefaultTimeoutFieldName} != Regex.InfiniteMatchTimeout;",
});
}
}
writer.WriteLine($" /// <summary>Scan the <paramref name=\"inputSpan\"/> starting from base.runtextstart for the next match.</summary>");
writer.WriteLine($" /// <param name=\"inputSpan\">The text being scanned by the regular expression.</param>");
writer.WriteLine($" protected override void Scan(ReadOnlySpan<char> inputSpan)");
writer.WriteLine($" {{");
writer.Indent += 3;
EnterCheckOverflow();
(bool needsTryFind, bool needsTryMatch) = EmitScan(writer, rm);
ExitCheckOverflow();
writer.Indent -= 3;
writer.WriteLine($" }}");
if (needsTryFind)
{
writer.WriteLine();
writer.WriteLine($" /// <summary>Search <paramref name=\"inputSpan\"/> starting from base.runtextpos for the next location a match could possibly start.</summary>");
writer.WriteLine($" /// <param name=\"inputSpan\">The text being scanned by the regular expression.</param>");
writer.WriteLine($" /// <returns>true if a possible match was found; false if no more matches are possible.</returns>");
writer.WriteLine($" private bool TryFindNextPossibleStartingPosition(ReadOnlySpan<char> inputSpan)");
writer.WriteLine($" {{");
writer.Indent += 3;
EnterCheckOverflow();
EmitTryFindNextPossibleStartingPosition(writer, rm, requiredHelpers);
ExitCheckOverflow();
writer.Indent -= 3;
writer.WriteLine($" }}");
}
if (needsTryMatch)
{
writer.WriteLine();
writer.WriteLine($" /// <summary>Determine whether <paramref name=\"inputSpan\"/> at base.runtextpos is a match for the regular expression.</summary>");
writer.WriteLine($" /// <param name=\"inputSpan\">The text being scanned by the regular expression.</param>");
writer.WriteLine($" /// <returns>true if the regular expression matches at the current position; otherwise, false.</returns>");
writer.WriteLine($" private bool TryMatchAtCurrentPosition(ReadOnlySpan<char> inputSpan)");
writer.WriteLine($" {{");
writer.Indent += 3;
EnterCheckOverflow();
EmitTryMatchAtCurrentPosition(writer, rm, requiredHelpers, checkOverflow);
ExitCheckOverflow();
writer.Indent -= 3;
writer.WriteLine($" }}");
}
writer.WriteLine($" }}");
writer.WriteLine($"}}");
}
/// <summary>Gets a C# expression representing the specified timeout value.</summary>
private static string GetTimeoutExpression(int matchTimeout) =>
matchTimeout == Timeout.Infinite ?
"Regex.InfiniteMatchTimeout" :
$"TimeSpan.FromMilliseconds({matchTimeout.ToString(CultureInfo.InvariantCulture)})";
/// <summary>Adds the IsWordChar helper to the required helpers collection.</summary>
private static void AddIsWordCharHelper(Dictionary<string, string[]> requiredHelpers)
{
const string IsWordChar = nameof(IsWordChar);
if (!requiredHelpers.ContainsKey(IsWordChar))
{
requiredHelpers.Add(IsWordChar, new string[]
{
"/// <summary>Determines whether the character is part of the [\\w] set.</summary>",
"[MethodImpl(MethodImplOptions.AggressiveInlining)]",
"internal static bool IsWordChar(char ch)",
"{",
" // Bitmap for whether each character 0 through 127 is in [\\w]",
" ReadOnlySpan<byte> ascii = new byte[]",
" {",
" 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x03,",
" 0xFE, 0xFF, 0xFF, 0x87, 0xFE, 0xFF, 0xFF, 0x07",
" };",
"",
" // If the char is ASCII, look it up in the bitmap. Otherwise, query its Unicode category.",
" int chDiv8 = ch >> 3;",
" return (uint)chDiv8 < (uint)ascii.Length ?",
" (ascii[chDiv8] & (1 << (ch & 0x7))) != 0 :",
" CharUnicodeInfo.GetUnicodeCategory(ch) switch",
" {",
" UnicodeCategory.UppercaseLetter or",
" UnicodeCategory.LowercaseLetter or",
" UnicodeCategory.TitlecaseLetter or",
" UnicodeCategory.ModifierLetter or",
" UnicodeCategory.OtherLetter or",
" UnicodeCategory.NonSpacingMark or",
" UnicodeCategory.DecimalDigitNumber or",
" UnicodeCategory.ConnectorPunctuation => true,",
" _ => false,",
" };",
"}",
});
}
}
/// <summary>Adds the IsBoundary helper to the required helpers collection.</summary>
private static void AddIsBoundaryHelper(Dictionary<string, string[]> requiredHelpers, bool checkOverflow)
{
const string IsBoundary = nameof(IsBoundary);
if (!requiredHelpers.ContainsKey(IsBoundary))
{
string uncheckedKeyword = checkOverflow ? "unchecked" : "";
requiredHelpers.Add(IsBoundary, new string[]
{
$"/// <summary>Determines whether the specified index is a boundary.</summary>",
$"[MethodImpl(MethodImplOptions.AggressiveInlining)]",
$"internal static bool IsBoundary(ReadOnlySpan<char> inputSpan, int index)",
$"{{",
$" int indexMinus1 = index - 1;",
$" return {uncheckedKeyword}((uint)indexMinus1 < (uint)inputSpan.Length && IsBoundaryWordChar(inputSpan[indexMinus1])) !=",
$" {uncheckedKeyword}((uint)index < (uint)inputSpan.Length && IsBoundaryWordChar(inputSpan[index]));",
$"",
$" static bool IsBoundaryWordChar(char ch) => IsWordChar(ch) || (ch == '\\u200C' | ch == '\\u200D');",
$"}}",
});
AddIsWordCharHelper(requiredHelpers);
}
}
/// <summary>Adds the IsECMABoundary helper to the required helpers collection.</summary>
private static void AddIsECMABoundaryHelper(Dictionary<string, string[]> requiredHelpers, bool checkOverflow)
{
const string IsECMABoundary = nameof(IsECMABoundary);
if (!requiredHelpers.ContainsKey(IsECMABoundary))
{
string uncheckedKeyword = checkOverflow ? "unchecked" : "";
requiredHelpers.Add(IsECMABoundary, new string[]
{
$"/// <summary>Determines whether the specified index is a boundary (ECMAScript).</summary>",
$"[MethodImpl(MethodImplOptions.AggressiveInlining)]",
$"internal static bool IsECMABoundary(ReadOnlySpan<char> inputSpan, int index)",
$"{{",
$" int indexMinus1 = index - 1;",
$" return {uncheckedKeyword}((uint)indexMinus1 < (uint)inputSpan.Length && IsECMAWordChar(inputSpan[indexMinus1])) !=",
$" {uncheckedKeyword}((uint)index < (uint)inputSpan.Length && IsECMAWordChar(inputSpan[index]));",
$"",
$" static bool IsECMAWordChar(char ch) =>",
$" char.IsAsciiLetterOrDigit(ch) ||",
$" ch == '_' ||",
$" ch == '\\u0130'; // latin capital letter I with dot above",
$"}}",
});
}
}
/// <summary>Emits the body of the Scan method override.</summary>
private static (bool NeedsTryFind, bool NeedsTryMatch) EmitScan(IndentedTextWriter writer, RegexMethod rm)
{
bool rtl = (rm.Options & RegexOptions.RightToLeft) != 0;
bool needsTryFind = false, needsTryMatch = false;
RegexNode root = rm.Tree.Root.Child(0);
// We can always emit our most general purpose scan loop, but there are common situations we can easily check
// for where we can emit simpler/better code instead.
if (root.Kind is RegexNodeKind.Empty)
{
// Emit a capture for the current position of length 0. This is rare to see with a real-world pattern,
// but it's very common as part of exploring the source generator, because it's what you get when you
// start out with an empty pattern.
writer.WriteLine("// The pattern matches the empty string.");
writer.WriteLine($"int pos = base.runtextpos;");
writer.WriteLine($"base.Capture(0, pos, pos);");
}
else if (root.Kind is RegexNodeKind.Nothing)
{
// Emit nothing. This is rare in production and not something to we need optimize for, but as with
// empty, it's helpful as a learning exposition tool.
writer.WriteLine("// The pattern never matches anything.");
}
else if (root.Kind is RegexNodeKind.Multi or RegexNodeKind.One or RegexNodeKind.Notone or RegexNodeKind.Set)
{
// If the whole expression is just one or more characters, we can rely on the FindOptimizations spitting out
// an IndexOf that will find the exact sequence or not, and we don't need to do additional checking beyond that.
needsTryFind = true;
using (EmitBlock(writer, "if (TryFindNextPossibleStartingPosition(inputSpan))"))
{
writer.WriteLine("// The search in TryFindNextPossibleStartingPosition performed the entire match.");
writer.WriteLine($"int start = base.runtextpos;");
writer.WriteLine($"int end = base.runtextpos = start {(!rtl ? "+" : "-")} {(root.Kind == RegexNodeKind.Multi ? root.Str!.Length : 1)};");
writer.WriteLine($"base.Capture(0, start, end);");
}
}
else if (rm.Tree.FindOptimizations.FindMode is
FindNextStartingPositionMode.LeadingAnchor_LeftToRight_Beginning or
FindNextStartingPositionMode.LeadingAnchor_LeftToRight_Start or
FindNextStartingPositionMode.LeadingAnchor_RightToLeft_Start or
FindNextStartingPositionMode.LeadingAnchor_RightToLeft_End)
{
// If the expression is anchored in such a way that there's one and only one possible position that can match,
// we don't need a scan loop, just a single check and match.
needsTryFind = needsTryMatch = true;
writer.WriteLine("// The pattern is anchored. Validate the current position and try to match at it only.");
using (EmitBlock(writer, "if (TryFindNextPossibleStartingPosition(inputSpan) && !TryMatchAtCurrentPosition(inputSpan))"))
{
writer.WriteLine($"base.runtextpos = {(!rtl ? "inputSpan.Length" : "0")};");
}
}
else
{
// Emit the general purpose scan loop. At this point, we always need TryMatchAtCurrentPosition. If we have any
// information that will enable TryFindNextPossibleStartingPosition to help narrow down the search, we need it,
// too, but otherwise it can be skipped.
needsTryMatch = true;
needsTryFind =
rm.Tree.FindOptimizations.FindMode != FindNextStartingPositionMode.NoSearch ||
rm.Tree.FindOptimizations.MinRequiredLength != 0 ||
rm.Tree.FindOptimizations.LeadingAnchor != RegexNodeKind.Unknown ||
rm.Tree.FindOptimizations.TrailingAnchor != RegexNodeKind.Unknown;
writer.WriteLine("// Search until we can't find a valid starting position, we find a match, or we reach the end of the input.");
writer.Write("while (");
if (needsTryFind)
{
writer.WriteLine("TryFindNextPossibleStartingPosition(inputSpan) &&");
writer.Write(" ");
}
writer.WriteLine("!TryMatchAtCurrentPosition(inputSpan) &&");
writer.WriteLine($" base.runtextpos != {(!rtl ? "inputSpan.Length" : "0")})");
using (EmitBlock(writer, null))
{
writer.WriteLine($"base.runtextpos{(!rtl ? "++" : "--")};");
// Check the timeout at least once per failed starting location, as finding the next location and
// attempting a match at that location could do work at least linear in the length of the input.
EmitTimeoutCheckIfNeeded(writer, rm, appendNewLineIfTimeoutEmitted: false);
}
}
return (needsTryFind, needsTryMatch);
}
/// <summary>Emits the body of the TryFindNextPossibleStartingPosition.</summary>
private static void EmitTryFindNextPossibleStartingPosition(IndentedTextWriter writer, RegexMethod rm, Dictionary<string, string[]> requiredHelpers)
{
RegexOptions options = rm.Options;
RegexTree regexTree = rm.Tree;
bool rtl = (options & RegexOptions.RightToLeft) != 0;
// In some cases, we need to emit declarations at the beginning of the method, but we only discover we need them later.
// To handle that, we build up a collection of all the declarations to include, track where they should be inserted,
// and then insert them at that position once everything else has been output.
var additionalDeclarations = new HashSet<string>();
// Emit locals initialization
writer.WriteLine("int pos = base.runtextpos;");
writer.Flush();
int additionalDeclarationsPosition = ((StringWriter)writer.InnerWriter).GetStringBuilder().Length;
int additionalDeclarationsIndent = writer.Indent;
writer.WriteLine();
const string NoMatchFound = "NoMatchFound";
bool findEndsInAlwaysReturningTrue = false;
bool noMatchFoundLabelNeeded = false;
// Generate length check. If the input isn't long enough to possibly match, fail quickly.
// It's rare for min required length to be 0, so we don't bother special-casing the check,
// especially since we want the "return false" code regardless.
int minRequiredLength = rm.Tree.FindOptimizations.MinRequiredLength;
Debug.Assert(minRequiredLength >= 0);
FinishEmitBlock clause = default;
if (minRequiredLength > 0)
{
writer.WriteLine(minRequiredLength == 1 ?
"// Empty matches aren't possible." :
$"// Any possible match is at least {minRequiredLength} characters.");
clause = EmitBlock(writer, (minRequiredLength, rtl) switch
{
(1, false) => "if ((uint)pos < (uint)inputSpan.Length)",
(_, false) => $"if (pos <= inputSpan.Length - {minRequiredLength})",
(1, true) => "if (pos > 0)",
(_, true) => $"if (pos >= {minRequiredLength})",
});
}
using (clause)
{
// Emit any anchors.
if (!EmitAnchors())
{
// Either anchors weren't specified, or they don't completely root all matches to a specific location.
// Emit the code for whatever find mode has been determined.
switch (regexTree.FindOptimizations.FindMode)
{
case FindNextStartingPositionMode.LeadingString_LeftToRight:
case FindNextStartingPositionMode.FixedDistanceString_LeftToRight:
EmitIndexOf_LeftToRight();
break;
case FindNextStartingPositionMode.LeadingString_RightToLeft:
EmitIndexOf_RightToLeft();
break;
case FindNextStartingPositionMode.LeadingSet_LeftToRight:
case FindNextStartingPositionMode.FixedDistanceSets_LeftToRight:
EmitFixedSet_LeftToRight();
break;
case FindNextStartingPositionMode.LeadingSet_RightToLeft:
EmitFixedSet_RightToLeft();
break;
case FindNextStartingPositionMode.LiteralAfterLoop_LeftToRight:
EmitLiteralAfterAtomicLoop();
break;
default:
Debug.Fail($"Unexpected mode: {regexTree.FindOptimizations.FindMode}");
goto case FindNextStartingPositionMode.NoSearch;
case FindNextStartingPositionMode.NoSearch:
writer.WriteLine("return true;");
findEndsInAlwaysReturningTrue = true;
break;
}
}
}
// If the main path is guaranteed to end in a "return true;" and nothing is going to
// jump past it, we don't need a "return false;" path.
if (minRequiredLength > 0 || !findEndsInAlwaysReturningTrue || noMatchFoundLabelNeeded)
{
writer.WriteLine();
writer.WriteLine("// No match found.");
if (noMatchFoundLabelNeeded)
{
writer.WriteLine($"{NoMatchFound}:");
}
writer.WriteLine($"base.runtextpos = {(!rtl ? "inputSpan.Length" : "0")};");
writer.WriteLine("return false;");
}
// We're done. Patch up any additional declarations.
ReplaceAdditionalDeclarations(writer, additionalDeclarations, additionalDeclarationsPosition, additionalDeclarationsIndent);
return;
// Emit a goto for the specified label.
void Goto(string label) => writer.WriteLine($"goto {label};");
// Emits any anchors. Returns true if the anchor roots any match to a specific location and thus no further
// searching is required; otherwise, false.
bool EmitAnchors()
{
// Anchors that fully implement TryFindNextPossibleStartingPosition, with a check that leads to immediate success or failure determination.
switch (regexTree.FindOptimizations.FindMode)
{
case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_Beginning:
writer.WriteLine("// The pattern leads with a beginning (\\A) anchor.");
using (EmitBlock(writer, "if (pos == 0)"))
{
// If we're at the beginning, we're at a possible match location. Otherwise,
// we'll never be, so fail immediately.
writer.WriteLine("return true;");
}
return true;
case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_Start:
case FindNextStartingPositionMode.LeadingAnchor_RightToLeft_Start:
writer.Write($"// The pattern leads with a start (\\G) anchor");
if (regexTree.FindOptimizations.FindMode == FindNextStartingPositionMode.LeadingAnchor_RightToLeft_Start)
{
writer.Write(" when processed right to left.");
}
writer.WriteLine(".");
using (EmitBlock(writer, "if (pos == base.runtextstart)"))
{
// For both left-to-right and right-to-left, if we're currently at the start,
// we're at a possible match location. Otherwise, because we've already moved
// beyond it, we'll never be, so fail immediately.
writer.WriteLine("return true;");
}
return true;
case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_EndZ:
writer.WriteLine("// The pattern leads with an end (\\Z) anchor.");
using (EmitBlock(writer, "if (pos < inputSpan.Length - 1)"))
{
// If we're not currently at the end (or a newline just before it), skip ahead
// since nothing until then can possibly match.
writer.WriteLine("base.runtextpos = inputSpan.Length - 1;");
}
writer.WriteLine("return true;");
findEndsInAlwaysReturningTrue = true;
return true;
case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_End:
writer.WriteLine("// The pattern leads with an end (\\z) anchor.");
using (EmitBlock(writer, "if (pos < inputSpan.Length)"))
{
// If we're not currently at the end (or a newline just before it), skip ahead
// since nothing until then can possibly match.
writer.WriteLine("base.runtextpos = inputSpan.Length;");
}
writer.WriteLine("return true;");
findEndsInAlwaysReturningTrue = true;
return true;
case FindNextStartingPositionMode.LeadingAnchor_RightToLeft_Beginning:
writer.WriteLine("// The pattern leads with a beginning (\\A) anchor when processed right to left.");
using (EmitBlock(writer, "if (pos != 0)"))
{
// If we're not currently at the beginning, skip ahead (or, rather, backwards)
// since nothing until then can possibly match. (We're iterating from the end
// to the beginning in RightToLeft mode.)
writer.WriteLine("base.runtextpos = 0;");
}
writer.WriteLine("return true;");
findEndsInAlwaysReturningTrue = true;
return true;
case FindNextStartingPositionMode.LeadingAnchor_RightToLeft_EndZ:
writer.WriteLine("// The pattern leads with an end (\\Z) anchor when processed right to left.");
using (EmitBlock(writer, "if (pos >= inputSpan.Length - 1 && ((uint)pos >= (uint)inputSpan.Length || inputSpan[pos] == '\\n'))"))
{
// If we're currently at the end, we're at a valid position to try. Otherwise,
// we'll never be (we're iterating from end to beginning), so fail immediately.
writer.WriteLine("return true;");
}
return true;
case FindNextStartingPositionMode.LeadingAnchor_RightToLeft_End:
writer.WriteLine("// The pattern leads with an end (\\z) anchor when processed right to left.");
using (EmitBlock(writer, "if (pos >= inputSpan.Length)"))
{
// If we're currently at the end, we're at a valid position to try. Otherwise,
// we'll never be (we're iterating from end to beginning), so fail immediately.
writer.WriteLine("return true;");
}
return true;
case FindNextStartingPositionMode.TrailingAnchor_FixedLength_LeftToRight_EndZ:
// Jump to the end, minus the min required length, which in this case is actually the fixed length, minus 1 (for a possible ending \n).
writer.WriteLine($"// The pattern has a trailing end (\\Z) anchor, and any possible match is exactly {regexTree.FindOptimizations.MinRequiredLength} characters.");
using (EmitBlock(writer, $"if (pos < inputSpan.Length - {regexTree.FindOptimizations.MinRequiredLength + 1})"))
{
writer.WriteLine($"base.runtextpos = inputSpan.Length - {regexTree.FindOptimizations.MinRequiredLength + 1};");
}
writer.WriteLine("return true;");
findEndsInAlwaysReturningTrue = true;
return true;
case FindNextStartingPositionMode.TrailingAnchor_FixedLength_LeftToRight_End:
// Jump to the end, minus the min required length, which in this case is actually the fixed length.
writer.WriteLine($"// The pattern has a trailing end (\\z) anchor, and any possible match is exactly {regexTree.FindOptimizations.MinRequiredLength} characters.");
using (EmitBlock(writer, $"if (pos < inputSpan.Length - {regexTree.FindOptimizations.MinRequiredLength})"))
{
writer.WriteLine($"base.runtextpos = inputSpan.Length - {regexTree.FindOptimizations.MinRequiredLength};");
}
writer.WriteLine("return true;");
findEndsInAlwaysReturningTrue = true;
return true;
}
// Now handle anchors that boost the position but may not determine immediate success or failure.
switch (regexTree.FindOptimizations.LeadingAnchor)
{
case RegexNodeKind.Bol:
// Optimize the handling of a Beginning-Of-Line (BOL) anchor. BOL is special, in that unlike
// other anchors like Beginning, there are potentially multiple places a BOL can match. So unlike
// the other anchors, which all skip all subsequent processing if found, with BOL we just use it
// to boost our position to the next line, and then continue normally with any searches.
writer.WriteLine($"// The pattern has a leading beginning-of-line anchor.");
using (EmitBlock(writer, "if (pos > 0 && inputSpan[pos - 1] != '\\n')"))
{
writer.WriteLine("int newlinePos = inputSpan.Slice(pos).IndexOf('\\n');");
using (EmitBlock(writer, "if ((uint)newlinePos > inputSpan.Length - pos - 1)"))
{
noMatchFoundLabelNeeded = true;
Goto(NoMatchFound);
}
writer.WriteLine("pos += newlinePos + 1;");
writer.WriteLine();
// We've updated the position. Make sure there's still enough room in the input for a possible match.
using (EmitBlock(writer, minRequiredLength switch
{
0 => "if (pos > inputSpan.Length)",
1 => "if (pos >= inputSpan.Length)",
_ => $"if (pos > inputSpan.Length - {minRequiredLength})"
}))
{
noMatchFoundLabelNeeded = true;
Goto(NoMatchFound);
}
}
writer.WriteLine();
break;
}
switch (regexTree.FindOptimizations.TrailingAnchor)
{
case RegexNodeKind.End when regexTree.FindOptimizations.MaxPossibleLength is int maxLength:
writer.WriteLine($"// The pattern has a trailing end (\\z) anchor, and any possible match is no more than {maxLength} characters.");
using (EmitBlock(writer, $"if (pos < inputSpan.Length - {maxLength})"))
{
writer.WriteLine($"pos = inputSpan.Length - {maxLength};");
}
writer.WriteLine();
break;
case RegexNodeKind.EndZ when regexTree.FindOptimizations.MaxPossibleLength is int maxLength:
writer.WriteLine($"// The pattern has a trailing end (\\Z) anchor, and any possible match is no more than {maxLength} characters.");
using (EmitBlock(writer, $"if (pos < inputSpan.Length - {maxLength + 1})"))
{
writer.WriteLine($"pos = inputSpan.Length - {maxLength + 1};");
}
writer.WriteLine();
break;
}
return false;
}
// Emits a case-sensitive left-to-right search for a substring.
void EmitIndexOf_LeftToRight()
{
RegexFindOptimizations opts = regexTree.FindOptimizations;
string substring = "";
string offset = "";
string offsetDescription = "at the beginning of the pattern";
switch (opts.FindMode)
{
case FindNextStartingPositionMode.LeadingString_LeftToRight:
substring = regexTree.FindOptimizations.LeadingPrefix;
Debug.Assert(!string.IsNullOrEmpty(substring));
break;
case FindNextStartingPositionMode.FixedDistanceString_LeftToRight:
Debug.Assert(!string.IsNullOrEmpty(regexTree.FindOptimizations.FixedDistanceLiteral.String));
substring = regexTree.FindOptimizations.FixedDistanceLiteral.String;
if (regexTree.FindOptimizations.FixedDistanceLiteral is { Distance: > 0 } literal)
{
offset = $" + {literal.Distance}";
offsetDescription = $" at index {literal.Distance} in the pattern";
}
break;
default:
Debug.Fail($"Unexpected mode: {opts.FindMode}");
break;
}
writer.WriteLine($"// The pattern has the literal {Literal(substring)} {offsetDescription}. Find the next occurrence.");
writer.WriteLine($"// If it can't be found, there's no match.");
writer.WriteLine($"int i = inputSpan.Slice(pos{offset}).IndexOf({Literal(substring)});");
using (EmitBlock(writer, "if (i >= 0)"))
{
writer.WriteLine("base.runtextpos = pos + i;");
writer.WriteLine("return true;");
}
}
// Emits a case-sensitive right-to-left search for a substring.
void EmitIndexOf_RightToLeft()
{
string prefix = regexTree.FindOptimizations.LeadingPrefix;
writer.WriteLine($"// The pattern begins with a literal {Literal(prefix)}. Find the next occurrence right-to-left.");
writer.WriteLine($"// If it can't be found, there's no match.");
writer.WriteLine($"pos = inputSpan.Slice(0, pos).LastIndexOf({Literal(prefix)});");
using (EmitBlock(writer, "if (pos >= 0)"))
{
writer.WriteLine($"base.runtextpos = pos + {prefix.Length};");
writer.WriteLine($"return true;");
}
}
// Emits a search for a set at a fixed position from the start of the pattern,
// and potentially other sets at other fixed positions in the pattern.
void EmitFixedSet_LeftToRight()
{
Debug.Assert(regexTree.FindOptimizations.FixedDistanceSets is { Count: > 0 });
List<RegexFindOptimizations.FixedDistanceSet>? sets = regexTree.FindOptimizations.FixedDistanceSets;
RegexFindOptimizations.FixedDistanceSet primarySet = sets![0];
const int MaxSets = 4;
int setsToUse = Math.Min(sets.Count, MaxSets);
writer.WriteLine(primarySet.Distance == 0 ?
$"// The pattern begins with {DescribeSet(primarySet.Set)}." :
$"// The pattern matches {DescribeSet(primarySet.Set)} at index {primarySet.Distance}.");
writer.WriteLine($"// Find the next occurrence. If it can't be found, there's no match.");
// If we can use IndexOf{Any}, try to accelerate the skip loop via vectorization to match the first prefix.
// We can use it if this is a case-sensitive class with a small number of characters in the class.
// We avoid using it for the relatively common case of the starting set being '.', aka anything other than
// a newline, as it's very rare to have long, uninterrupted sequences of newlines.
int setIndex = 0;
bool canUseIndexOf =
primarySet.Set != RegexCharClass.NotNewLineClass &&
(primarySet.Chars is not null || primarySet.Range is not null);
bool needLoop = !canUseIndexOf || setsToUse > 1;
FinishEmitBlock loopBlock = default;
if (needLoop)
{
writer.WriteLine("ReadOnlySpan<char> span = inputSpan.Slice(pos);");
string upperBound = "span.Length" + (setsToUse > 1 || primarySet.Distance != 0 ? $" - {minRequiredLength - 1}" : "");
loopBlock = EmitBlock(writer, $"for (int i = 0; i < {upperBound}; i++)");
}
if (canUseIndexOf)
{
string span = needLoop ?
"span" :
"inputSpan.Slice(pos)";
span = (needLoop, primarySet.Distance) switch
{
(false, 0) => span,
(true, 0) => $"{span}.Slice(i)",
(false, _) => $"{span}.Slice({primarySet.Distance})",
(true, _) => $"{span}.Slice(i + {primarySet.Distance})",
};
string indexOf =
primarySet.Chars is not null ? primarySet.Chars!.Length switch
{
1 => $"{span}.IndexOf({Literal(primarySet.Chars[0])})",
2 => $"{span}.IndexOfAny({Literal(primarySet.Chars[0])}, {Literal(primarySet.Chars[1])})",
3 => $"{span}.IndexOfAny({Literal(primarySet.Chars[0])}, {Literal(primarySet.Chars[1])}, {Literal(primarySet.Chars[2])})",
_ => $"{span}.IndexOfAny({Literal(new string(primarySet.Chars))})",
} :
(primarySet.Range.Value.LowInclusive == primarySet.Range.Value.HighInclusive, primarySet.Range.Value.Negated) switch
{
(false, false) => $"{span}.IndexOfAnyInRange({Literal(primarySet.Range.Value.LowInclusive)}, {Literal(primarySet.Range.Value.HighInclusive)})",
(true, false) => $"{span}.IndexOf({Literal(primarySet.Range.Value.LowInclusive)})",
(false, true) => $"{span}.IndexOfAnyExceptInRange({Literal(primarySet.Range.Value.LowInclusive)}, {Literal(primarySet.Range.Value.HighInclusive)})",
(true, true) => $"{span}.IndexOfAnyExcept({Literal(primarySet.Range.Value.LowInclusive)})",
};
if (needLoop)
{
writer.WriteLine($"int indexOfPos = {indexOf};");
using (EmitBlock(writer, "if (indexOfPos < 0)"))
{
noMatchFoundLabelNeeded = true;
Goto(NoMatchFound);
}
writer.WriteLine("i += indexOfPos;");
writer.WriteLine();
if (setsToUse > 1)
{
// Of the remaining sets we're going to check, find the maximum distance of any of them.
// If it's further than the primary set we checked, we need a bounds check.
int maxDistance = sets[1].Distance;
for (int i = 2; i < setsToUse; i++)
{
maxDistance = Math.Max(maxDistance, sets[i].Distance);
}
if (maxDistance > primarySet.Distance)
{
int numRemainingSets = setsToUse - 1;
writer.WriteLine($"// The primary set being searched for was found. {numRemainingSets} more set{(numRemainingSets > 1 ? "s" : "")} will be checked so as");
writer.WriteLine($"// to minimize the number of places TryMatchAtCurrentPosition is run unnecessarily.");
writer.WriteLine($"// Make sure {(numRemainingSets > 1 ? "they fit" : "it fits")} in the remainder of the input.");
using (EmitBlock(writer, $"if ((uint)(i + {maxDistance}) >= (uint)span.Length)"))
{
noMatchFoundLabelNeeded = true;
Goto(NoMatchFound);
}
writer.WriteLine();
}
}
}
else
{
writer.WriteLine($"int i = {indexOf};");
using (EmitBlock(writer, "if (i >= 0)"))
{
writer.WriteLine("base.runtextpos = pos + i;");
writer.WriteLine("return true;");
}
}
setIndex = 1;
}
if (needLoop)
{
Debug.Assert(setIndex == 0 || setIndex == 1);
bool hasCharClassConditions = false;
if (setIndex < setsToUse)
{
// if (CharInClass(textSpan[i + charClassIndex], prefix[0], "...") &&
// ...)
Debug.Assert(needLoop);
int start = setIndex;
for (; setIndex < setsToUse; setIndex++)
{
string spanIndex = $"span[i{(sets[setIndex].Distance > 0 ? $" + {sets[setIndex].Distance}" : "")}]";
string charInClassExpr = MatchCharacterClass(options, spanIndex, sets[setIndex].Set, negate: false, additionalDeclarations, requiredHelpers);
if (setIndex == start)
{
writer.Write($"if ({charInClassExpr}");
}
else
{
writer.WriteLine(" &&");
writer.Write($" {charInClassExpr}");
}
}
writer.WriteLine(")");
hasCharClassConditions = true;
}
using (hasCharClassConditions ? EmitBlock(writer, null) : default)
{
writer.WriteLine("base.runtextpos = pos + i;");
writer.WriteLine("return true;");
}
}
loopBlock.Dispose();
}
// Emits a right-to-left search for a set at a fixed position from the start of the pattern.
// (Currently that position will always be a distance of 0, meaning the start of the pattern itself.)
void EmitFixedSet_RightToLeft()
{
Debug.Assert(regexTree.FindOptimizations.FixedDistanceSets is { Count: > 0 });
RegexFindOptimizations.FixedDistanceSet set = regexTree.FindOptimizations.FixedDistanceSets![0];
Debug.Assert(set.Distance == 0);
writer.WriteLine($"// The pattern begins with {DescribeSet(set.Set)}.");
writer.WriteLine($"// Find the next occurrence. If it can't be found, there's no match.");
if (set.Chars is { Length: 1 })
{
writer.WriteLine($"pos = inputSpan.Slice(0, pos).LastIndexOf({Literal(set.Chars[0])});");
using (EmitBlock(writer, "if (pos >= 0)"))
{
writer.WriteLine("base.runtextpos = pos + 1;");
writer.WriteLine("return true;");
}
}
else
{
using (EmitBlock(writer, "while ((uint)--pos < (uint)inputSpan.Length)"))
{
using (EmitBlock(writer, $"if ({MatchCharacterClass(options, "inputSpan[pos]", set.Set, negate: false, additionalDeclarations, requiredHelpers)})"))
{
writer.WriteLine("base.runtextpos = pos + 1;");
writer.WriteLine("return true;");
}
}
}
}
// Emits a search for a literal following a leading atomic single-character loop.
void EmitLiteralAfterAtomicLoop()
{
Debug.Assert(regexTree.FindOptimizations.LiteralAfterLoop is not null);
(RegexNode LoopNode, (char Char, string? String, char[]? Chars) Literal) target = regexTree.FindOptimizations.LiteralAfterLoop.Value;
Debug.Assert(target.LoopNode.Kind is RegexNodeKind.Setloop or RegexNodeKind.Setlazy or RegexNodeKind.Setloopatomic);
Debug.Assert(target.LoopNode.N == int.MaxValue);
writer.Write($"// The pattern begins with an atomic loop for {DescribeSet(target.LoopNode.Str!)}, followed by ");
writer.WriteLine(
target.Literal.String is not null ? $"the string {Literal(target.Literal.String)}." :
target.Literal.Chars is not null ? $"one of the characters {Literal(new string(target.Literal.Chars))}" :
$"the character {Literal(target.Literal.Char)}.");
writer.WriteLine($"// Search for the literal, and then walk backwards to the beginning of the loop.");
FinishEmitBlock block = default;
if (target.LoopNode.M > 0)
{
// If there's no lower bound on the loop, then once we find the literal, we know we have a valid starting position to try.
// If there is a lower bound, then we need a loop, as we could find the literal but it might not be prefixed with enough
// appropriate characters to satisfy the minimum bound.
block = EmitBlock(writer, "while (true)");
}
using (block)
{