-
Notifications
You must be signed in to change notification settings - Fork 5.4k
Expand file tree
/
Copy pathRegexGenerator.Emitter.cs
More file actions
5896 lines (5229 loc) · 327 KB
/
RegexGenerator.Emitter.cs
File metadata and controls
5896 lines (5229 loc) · 327 KB
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.Runtime.CompilerServices;
using System.Security.Cryptography;
using System.Threading;
using System.Text;
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.
#pragma warning disable CA1861 // Avoid constant arrays as arguments.
namespace System.Text.RegularExpressions.Generator
{
public partial class RegexGenerator
{
/// <summary>Escapes characters that are invalid in XML comments.</summary>
private static string EscapeXmlComment(string text)
{
if (!string.IsNullOrEmpty(text))
{
StringBuilder sb = new(text.Length);
foreach (char c in text)
{
switch ((int)c)
{
// Escape XML entities.
case '&': sb.Append("&"); break;
case '<': sb.Append("<"); break;
case '>': sb.Append(">"); break;
// Propagate all other valid XML characters as-is. Control chars are considered invalid.
// U+2028 and U+2029 are valid XML but are C# line terminators, so they'd break /// comments.
case (>= 0x20 and <= 0x7F) or (>= 0xA0 and <= 0xD7FF and not 0x2028 and not 0x2029) or (>= 0xE000 and <= 0xFFFD): sb.Append(c); break;
// Use Unicode escape sequences for everything else.
default: sb.Append($"\\u{(int)c:X4}"); break;
}
}
text = sb.ToString();
}
return text;
}
/// <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:<br/>");
writer.WriteLine($"/// <code>{EscapeXmlComment(regexMethod.Pattern)}</code><br/>");
if (regexMethod.Options != RegexOptions.None)
{
writer.WriteLine($"/// Options:<br/>");
writer.WriteLine($"/// <code>{Literal(regexMethod.Options)}</code><br/>");
}
writer.WriteLine($"/// 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.Write($"{regexMethod.Modifiers} global::System.Text.RegularExpressions.Regex{(regexMethod.NullableRegex ? "?" : "")} {regexMethod.MemberName}");
if (!regexMethod.IsProperty)
{
writer.Write("()");
}
writer.WriteLine($" => 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, LanguageVersion langVer)
{
string visibility;
if (langVer >= LanguageVersion.CSharp11)
{
visibility = "file";
writer.WriteLine($"/// <summary>Caches a <see cref=\"Regex\"/> instance for the {rm.MemberName} method.</summary>");
}
else
{
visibility = "internal";
writer.WriteLine($"/// <summary>This class supports generated regexes and should not be used by other code directly.</summary>");
}
writer.WriteLine($"/// <remarks>A custom Regex-derived type could not be generated because {reason}.</remarks>");
writer.WriteLine($"[{s_generatedCodeAttribute}]");
writer.WriteLine($"{visibility} 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.MemberName} 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,
[
$"/// <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, checkOverflow);
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)})";
private const string IsBoundary = nameof(IsBoundary);
private const string IsECMABoundary = nameof(IsECMABoundary);
private const string IsWordChar = nameof(IsWordChar);
private const string IsBoundaryWordChar = nameof(IsBoundaryWordChar);
private const string IsPostWordCharBoundary = nameof(IsPostWordCharBoundary);
private const string IsPreWordCharBoundary = nameof(IsPreWordCharBoundary);
private const string IsECMABoundaryWordChar = nameof(IsECMABoundaryWordChar);
private const string WordCategoriesMask = nameof(WordCategoriesMask);
private const string WordCharBitmap = nameof(WordCharBitmap);
private static void AddWordCharHelpersSupport(Dictionary<string, string[]> requiredHelpers)
{
const string WordCharHelpersSupport = nameof(WordCharHelpersSupport);
if (!requiredHelpers.ContainsKey(WordCharHelpersSupport))
{
requiredHelpers.Add(WordCharHelpersSupport,
[
"/// <summary>Provides a mask of Unicode categories that combine to form [\\w].</summary>",
$"private const int {WordCategoriesMask} =",
" 1 << (int)UnicodeCategory.UppercaseLetter |",
" 1 << (int)UnicodeCategory.LowercaseLetter |",
" 1 << (int)UnicodeCategory.TitlecaseLetter |",
" 1 << (int)UnicodeCategory.ModifierLetter |",
" 1 << (int)UnicodeCategory.OtherLetter |",
" 1 << (int)UnicodeCategory.NonSpacingMark |",
" 1 << (int)UnicodeCategory.DecimalDigitNumber |",
" 1 << (int)UnicodeCategory.ConnectorPunctuation;",
"",
"/// <summary>Gets a bitmap for whether each character 0 through 127 is in [\\w]</summary>",
$"private static ReadOnlySpan<byte> {WordCharBitmap} => new byte[]",
"{",
" 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x03,",
" 0xFE, 0xFF, 0xFF, 0x87, 0xFE, 0xFF, 0xFF, 0x07",
"};",
]);
}
}
/// <summary>Adds the IsWordChar helper to the required helpers collection.</summary>
private static void AddIsWordCharHelper(Dictionary<string, string[]> requiredHelpers)
{
if (!requiredHelpers.ContainsKey(IsWordChar))
{
requiredHelpers.Add(IsWordChar,
[
$"/// <summary>Determines whether the character is part of the [\\w] set.</summary>",
$"[MethodImpl(MethodImplOptions.AggressiveInlining)]",
$"internal static bool {IsWordChar}(char ch)",
$"{{",
$" // If the char is ASCII, look it up in the bitmap. Otherwise, query its Unicode category.",
$" ReadOnlySpan<byte> ascii = {WordCharBitmap};",
$" int chDiv8 = ch >> 3;",
$" return (uint)chDiv8 < (uint)ascii.Length ?",
$" (ascii[chDiv8] & (1 << (ch & 0x7))) != 0 :",
$" ({WordCategoriesMask} & (1 << (int)CharUnicodeInfo.GetUnicodeCategory(ch))) != 0;",
$"}}",
]);
AddWordCharHelpersSupport(requiredHelpers);
}
}
/// <summary>Adds the IsBoundary helper to the required helpers collection.</summary>
private static void AddIsBoundaryWordCharHelper(Dictionary<string, string[]> requiredHelpers)
{
if (!requiredHelpers.ContainsKey(IsBoundaryWordChar))
{
requiredHelpers.Add(IsBoundaryWordChar,
[
$"/// <summary>Determines whether the specified index is a boundary word character.</summary>",
$"/// <remarks>This is the same as \\w plus U+200C ZERO WIDTH NON-JOINER and U+200D ZERO WIDTH JOINER.</remarks>",
$"[MethodImpl(MethodImplOptions.AggressiveInlining)]",
$"internal static bool {IsBoundaryWordChar}(char ch)",
$"{{",
$" ReadOnlySpan<byte> ascii = {WordCharBitmap};",
$" int chDiv8 = ch >> 3;",
$" return (uint)chDiv8 < (uint)ascii.Length ?",
$" (ascii[chDiv8] & (1 << (ch & 0x7))) != 0 :",
$" (({WordCategoriesMask} & (1 << (int)CharUnicodeInfo.GetUnicodeCategory(ch))) != 0) || (ch is '\u200C' or '\u200D');",
$"}}",
]);
AddWordCharHelpersSupport(requiredHelpers);
}
}
/// <summary>Adds the IsECMABoundary helper to the required helpers collection.</summary>
private static void AddIsECMABoundaryWordCharHelper(Dictionary<string, string[]> requiredHelpers)
{
if (!requiredHelpers.ContainsKey(IsECMABoundaryWordChar))
{
requiredHelpers.Add(IsECMABoundaryWordChar,
[
$"/// <summary>Determines whether the specified index is a boundary (ECMAScript) word character.</summary>",
$"[MethodImpl(MethodImplOptions.AggressiveInlining)]",
$"internal static bool {IsECMABoundaryWordChar}(char ch) =>",
$" char.IsAsciiLetterOrDigit(ch) ||",
$" ch is '_' or '\\u0130'; // latin capital letter I with dot above",
]);
}
}
/// <summary>Adds the IsBoundary helper to the required helpers collection.</summary>
private static void AddIsBoundaryHelper(Dictionary<string, string[]> requiredHelpers, bool checkOverflow)
{
if (!requiredHelpers.ContainsKey(IsBoundary))
{
string uncheckedKeyword = checkOverflow ? "unchecked" : "";
requiredHelpers.Add(IsBoundary,
[
$"/// <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]));",
$"}}",
]);
AddIsBoundaryWordCharHelper(requiredHelpers);
}
}
/// <summary>Adds the IsPreWordCharBoundary helper to the required helpers collection.</summary>
private static void AddIsPreWordCharBoundaryHelper(Dictionary<string, string[]> requiredHelpers, bool checkOverflow)
{
if (!requiredHelpers.ContainsKey(IsPreWordCharBoundary))
{
string uncheckedKeyword = checkOverflow ? "unchecked" : "";
requiredHelpers.Add(IsPreWordCharBoundary,
[
$"/// <summary>Determines whether the specified index is a boundary.</summary>",
$"/// <remarks>This variant is only employed when the subsequent character will separately be validated as a word character.</remarks>",
$"[MethodImpl(MethodImplOptions.AggressiveInlining)]",
$"internal static bool {IsPreWordCharBoundary}(ReadOnlySpan<char> inputSpan, int index)",
$"{{",
$" int indexMinus1 = index - 1;",
$" return {uncheckedKeyword}((uint)indexMinus1 >= (uint)inputSpan.Length || !{IsBoundaryWordChar}(inputSpan[indexMinus1]));",
$"}}",
]);
AddIsBoundaryWordCharHelper(requiredHelpers);
}
}
/// <summary>Adds the IsPostWordCharBoundary helper to the required helpers collection.</summary>
private static void AddIsPostWordCharBoundaryHelper(Dictionary<string, string[]> requiredHelpers, bool checkOverflow)
{
if (!requiredHelpers.ContainsKey(IsPostWordCharBoundary))
{
string uncheckedKeyword = checkOverflow ? "unchecked" : "";
requiredHelpers.Add(IsPostWordCharBoundary,
[
$"/// <summary>Determines whether the specified index is a boundary.</summary>",
$"/// <remarks>This variant is only employed when the previous character has already been validated as a word character.</remarks>",
$"[MethodImpl(MethodImplOptions.AggressiveInlining)]",
$"internal static bool {IsPostWordCharBoundary}(ReadOnlySpan<char> inputSpan, int index) =>",
$" {uncheckedKeyword}((uint)index >= (uint)inputSpan.Length || !{IsBoundaryWordChar}(inputSpan[index]));",
]);
AddIsBoundaryWordCharHelper(requiredHelpers);
}
}
/// <summary>Adds the IsECMABoundary helper to the required helpers collection.</summary>
private static void AddIsECMABoundaryHelper(Dictionary<string, string[]> requiredHelpers, bool checkOverflow)
{
if (!requiredHelpers.ContainsKey(IsECMABoundary))
{
string uncheckedKeyword = checkOverflow ? "unchecked" : "";
requiredHelpers.Add(IsECMABoundary,
[
$"/// <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 && {IsECMABoundaryWordChar}(inputSpan[indexMinus1])) !=",
$" {uncheckedKeyword}((uint)index < (uint)inputSpan.Length && {IsECMABoundaryWordChar}(inputSpan[index]));",
$"}}",
]);
AddIsECMABoundaryWordCharHelper(requiredHelpers);
}
}
/// <summary>Adds a SearchValues instance declaration to the required helpers collection if the chars are ASCII.</summary>
private static string EmitSearchValuesOrLiteral(ReadOnlySpan<char> chars, Dictionary<string, string[]> requiredHelpers)
{
Debug.Assert(chars.Length > 3);
// IndexOfAny(SearchValues) is faster than a regular IndexOfAny("abcd") if:
// - There are more than 5 characters in the needle, or
// - There are only 4 or 5 characters in the needle and they're all ASCII.
return chars.Length > 5 || Ascii.IsValid(chars)
? EmitSearchValues(chars, requiredHelpers)
: Literal(chars.ToString());
}
/// <summary>Adds a SearchValues instance declaration to the required helpers collection.</summary>
private static string EmitSearchValues(ReadOnlySpan<char> charsSpan, Dictionary<string, string[]> requiredHelpers, string? fieldName = null)
{
char[] chars = charsSpan.ToArray();
Array.Sort(chars);
if (fieldName is null)
{
if (Ascii.IsValid(chars))
{
// The set of ASCII characters can be represented as a 128-bit bitmap. Use the 16-byte hex string as the key.
var bitmap = new byte[16];
foreach (char c in chars)
{
bitmap[c >> 3] |= (byte)(1 << (c & 7));
}
string hexBitmap = ToHexStringNoDashes(bitmap);
fieldName = hexBitmap switch
{
"FFFFFFFF000000000000000000000080" => "s_asciiControl",
"000000000000FF030000000000000000" => "s_asciiDigits",
"0000000000000000FEFFFF07FEFFFF07" => "s_asciiLetters",
"000000000000FF03FEFFFF07FEFFFF07" => "s_asciiLettersAndDigits",
"000000000000FF037E0000007E000000" => "s_asciiHexDigits",
"000000000000FF03000000007E000000" => "s_asciiHexDigitsLower",
"000000000000FF037E00000000000000" => "s_asciiHexDigitsUpper",
"00000000EEF7008C010000B800000028" => "s_asciiPunctuation",
"00000000010000000000000000000000" => "s_asciiSeparators",
"00000000100800700000004001000050" => "s_asciiSymbols",
"003E0000010000000000000000000000" => "s_asciiWhiteSpace",
"000000000000FF03FEFFFF87FEFFFF07" => "s_asciiWordChars",
"00000000FFFFFFFFFFFFFFFFFFFFFF7F" => "s_asciiExceptControl",
"FFFFFFFFFFFF00FCFFFFFFFFFFFFFFFF" => "s_asciiExceptDigits",
"FFFFFFFFFFFFFFFF010000F8010000F8" => "s_asciiExceptLetters",
"FFFFFFFFFFFF00FC010000F8010000F8" => "s_asciiExceptLettersAndDigits",
"FFFFFFFFFFFFFFFFFFFFFFFF010000F8" => "s_asciiExceptLower",
"FFFFFFFF1108FF73FEFFFF47FFFFFFD7" => "s_asciiExceptPunctuation",
"FFFFFFFFFEFFFFFFFFFFFFFFFFFFFFFF" => "s_asciiExceptSeparators",
"FFFFFFFFEFF7FF8FFFFFFFBFFEFFFFAF" => "s_asciiExceptSymbols",
"FFFFFFFFFFFFFFFF010000F8FFFFFFFF" => "s_asciiExceptUpper",
"FFC1FFFFFEFFFFFFFFFFFFFFFFFFFFFF" => "s_asciiExceptWhiteSpace",
"FFFFFFFFFFFF00FC01000078010000F8" => "s_asciiExceptWordChars",
"FFFFFFFFFFDF00FCFFFFFFFFFFFFFFFF" => "s_asciiExceptDigitsAndDash",
"000000000040FF03FEFFFF07FEFFFF07" => "s_asciiLettersAndDigitsAndDot",
"000000000020FF03FEFFFF07FEFFFF07" => "s_asciiLettersAndDigitsAndDash",
"000000000060FF03FEFFFF07FEFFFF07" => "s_asciiLettersAndDigitsAndDashDot",
"000000000040FF03FEFFFF87FEFFFF07" => "s_asciiLettersAndDigitsAndDotUnderscore",
"000000000020FF03FEFFFF87FEFFFF07" => "s_asciiLettersAndDigitsAndDashUnderscore",
"000000000060FF03FEFFFF87FEFFFF07" => "s_asciiLettersAndDigitsAndDashDotUnderscore",
"000000000040FF030000000000000000" => "s_asciiDigitsAndDot",
"000000000020FF030000000000000000" => "s_asciiDigitsAndDash",
"0000000000200000FEFFFF07FEFFFF07" => "s_asciiLettersAndDash",
"0000000000000000FEFFFF87FEFFFF07" => "s_asciiLettersAndUnderscore",
"000000000000FF0300000000FEFFFF07" => "s_asciiLettersLowerAndDigits",
"000000000000FF03FEFFFF0700000000" => "s_asciiLettersUpperAndDigits",
"000000000020FF0300000000FEFFFF07" => "s_asciiLettersLowerAndDigitsAndDash",
_ => $"s_ascii_{hexBitmap.TrimStart('0')}"
};
}
else
{
fieldName = GetSHA256FieldName("s_nonAscii_", new string(chars));
fieldName = fieldName switch
{
"s_nonAscii_326E1FD0AD567A84CAD13F2BE521A57789829F59D59ABE37F9E111D0182B6601" => "s_asciiLettersAndKelvinSign",
"s_nonAscii_46E3FAA2E94950B9D41E9AB1B570CAB55D04A30009110072B4BC074D57272527" => "s_asciiLettersAndDigitsAndKelvinSign",
"s_nonAscii_2D5586687DC37F0329E3CA4127326E68B5A3A090B13B7834AEA7BFC4EDDE220F" => "s_asciiLettersAndDigitsAndDashKelvinSign",
"s_nonAscii_83AFA3CC45CC4C2D8C316947CFC319199813C7F90226BDF348E2B3236D6237C1" => "s_asciiLettersAndDigitsAndDashDotKelvinSign",
"s_nonAscii_9FA52D3BAECB644578472387D5284CC6F36F408FEB88A04BA674CE14F24D2386" => "s_asciiLettersAndDigitsAndUnderscoreKelvinSign",
"s_nonAscii_D41BEF0BEAFBA32A45D2356E3F1579596F35B7C67CAA9CF7C4B3F2A5422DCA51" => "s_asciiLettersAndDigitsAndDashUnderscoreKelvinSign",
"s_nonAscii_0D7E5600013B3F0349C00277028B6DEA566BB9BAF991CCB7AC92DEC54C4544C1" => "s_asciiLettersAndDigitsAndDashDotUnderscoreKelvinSign",
_ => fieldName
};
}
}
if (!requiredHelpers.ContainsKey(fieldName))
{
string setLiteral = Literal(new string(chars));
requiredHelpers.Add(fieldName,
[
$"/// <summary>Supports searching for characters in or not in {EscapeXmlComment(setLiteral)}.</summary>",
$"internal static readonly SearchValues<char> {fieldName} = SearchValues.Create({setLiteral});",
]);
}
return $"{HelpersTypeName}.{fieldName}";
}
private static string EmitIndexOfAnyCustomHelper(string set, Dictionary<string, string[]> requiredHelpers, bool checkOverflow)
{
// In order to optimize the search for ASCII characters, we use SearchValues to vectorize a search
// for those characters plus anything non-ASCII (if we find something non-ASCII, we'll fall back to
// a sequential walk). In order to do that search, we actually build up a set for all of the ASCII
// characters _not_ contained in the set, and then do a search for the inverse of that, which will be
// all of the target ASCII characters and all of non-ASCII.
var excludedAsciiChars = new List<char>();
for (int i = 0; i < 128; i++)
{
if (!RegexCharClass.CharInClass((char)i, set))
{
excludedAsciiChars.Add((char)i);
}
}
// If this is a known set, use a predetermined simple name for the helper.
string? helperName = set switch
{
RegexCharClass.DigitClass => "IndexOfAnyDigit",
RegexCharClass.ControlClass => "IndexOfAnyControl",
RegexCharClass.LetterClass => "IndexOfAnyLetter",
RegexCharClass.LetterOrDigitClass => "IndexOfAnyLetterOrDigit",
RegexCharClass.LowerClass => "IndexOfAnyLower",
RegexCharClass.NumberClass => "IndexOfAnyNumber",
RegexCharClass.PunctuationClass => "IndexOfAnyPunctuation",
RegexCharClass.SeparatorClass => "IndexOfAnySeparator",
RegexCharClass.SpaceClass => "IndexOfAnyWhiteSpace",
RegexCharClass.SymbolClass => "IndexOfAnySymbol",
RegexCharClass.UpperClass => "IndexOfAnyUpper",
RegexCharClass.WordClass => "IndexOfAnyWordChar",
RegexCharClass.NotDigitClass => "IndexOfAnyExceptDigit",
RegexCharClass.NotControlClass => "IndexOfAnyExceptControl",
RegexCharClass.NotLetterClass => "IndexOfAnyExceptLetter",
RegexCharClass.NotLetterOrDigitClass => "IndexOfAnyExceptLetterOrDigit",
RegexCharClass.NotLowerClass => "IndexOfAnyExceptLower",
RegexCharClass.NotNumberClass => "IndexOfAnyExceptNumber",
RegexCharClass.NotPunctuationClass => "IndexOfAnyExceptPunctuation",
RegexCharClass.NotSeparatorClass => "IndexOfAnyExceptSeparator",
RegexCharClass.NotSpaceClass => "IndexOfAnyExceptWhiteSpace",
RegexCharClass.NotSymbolClass => "IndexOfAnyExceptSymbol",
RegexCharClass.NotUpperClass => "IndexOfAnyExceptUpper",
RegexCharClass.NotWordClass => "IndexOfAnyExceptWordChar",
_ => null,
};
// If this set is just from a few Unicode categories, derive a name from the categories.
if (helperName is null)
{
Span<UnicodeCategory> categories = stackalloc UnicodeCategory[5]; // arbitrary limit to keep names from being too unwieldy
if (RegexCharClass.TryGetOnlyCategories(set, categories, out int numCategories, out bool negatedCategory))
{
helperName = $"IndexOfAny{(negatedCategory ? "Except" : "")}{string.Concat(categories.Slice(0, numCategories).ToArray().Select(c => c.ToString()))}";
}
}
// As a final fallback, manufacture a name unique to the full set description.
helperName ??= GetSHA256FieldName("IndexOfNonAsciiOrAny_", set);
if (!requiredHelpers.ContainsKey(helperName))
{
var additionalDeclarations = new HashSet<string>();
string matchExpr = MatchCharacterClass("span[i]", set, negate: false, additionalDeclarations, requiredHelpers);
var lines = new List<string>();
lines.Add($"/// <summary>Finds the next index of any character that matches {EscapeXmlComment(DescribeSet(set))}.</summary>");
lines.Add($"[MethodImpl(MethodImplOptions.AggressiveInlining)]");
lines.Add($"internal static int {helperName}(this ReadOnlySpan<char> span)");
lines.Add($"{{");
int uncheckedStart = lines.Count;
lines.Add(excludedAsciiChars.Count == 128 ? $" int i = span.IndexOfAnyExceptInRange('\\0', '\\u007f');" : // no ASCII is in the set
excludedAsciiChars.Count == 0 ? $" int i = 0;" : // all ASCII is in the set
$" int i = span.IndexOfAnyExcept({EmitSearchValues(excludedAsciiChars.ToArray(), requiredHelpers)});");
lines.Add($" if ((uint)i < (uint)span.Length)");
lines.Add($" {{");
if (excludedAsciiChars.Count is not (0 or 128))
{
lines.Add($" if (char.IsAscii(span[i]))");
lines.Add($" {{");
lines.Add($" return i;");
lines.Add($" }}");
lines.Add($"");
}
if (additionalDeclarations.Count > 0)
{
lines.AddRange(additionalDeclarations.Select(s => $" {s}"));
}
lines.Add($" do");
lines.Add($" {{");
lines.Add($" if ({matchExpr})");
lines.Add($" {{");
lines.Add($" return i;");
lines.Add($" }}");
lines.Add($" i++;");
lines.Add($" }}");
lines.Add($" while ((uint)i < (uint)span.Length);");
lines.Add($" }}");
lines.Add($"");
lines.Add($" return -1;");
lines.Add($"}}");
if (checkOverflow)
{
lines.Insert(uncheckedStart, " unchecked");
lines.Insert(uncheckedStart + 1, " {");
for (int i = uncheckedStart + 2; i < lines.Count - 1; i++)
{
lines[i] = $" {lines[i]}";
}
lines.Insert(lines.Count - 1, " }");
}
requiredHelpers.Add(helperName, lines.ToArray());
}
return helperName;
}
/// <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, bool checkOverflow)
{
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.LeadingString_OrdinalIgnoreCase_LeftToRight:
case FindNextStartingPositionMode.FixedDistanceString_LeftToRight:
EmitIndexOfString_LeftToRight();
break;
case FindNextStartingPositionMode.LeadingString_RightToLeft:
EmitIndexOfString_RightToLeft();
break;
case FindNextStartingPositionMode.LeadingStrings_LeftToRight:
case FindNextStartingPositionMode.LeadingStrings_OrdinalIgnoreCase_LeftToRight:
EmitIndexOfStrings_LeftToRight();
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.
InsertAdditionalDeclarations(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:
// If we also have a trailing End anchor with fixed length, we can check for exact length match.
// Compute this lazily to avoid overhead in the interpreter.
if (RegexPrefixAnalyzer.FindTrailingAnchor(regexTree.Root) == RegexNodeKind.End &&
regexTree.Root.ComputeMaxLength() == regexTree.FindOptimizations.MinRequiredLength)
{
int minRequiredLength = regexTree.FindOptimizations.MinRequiredLength;
writer.WriteLine($"// The pattern leads with a beginning (\\A) anchor and has a trailing end (\\z) anchor, and any possible match is exactly {minRequiredLength} characters.");
using (EmitBlock(writer, $"if (pos == 0 && inputSpan.Length == {minRequiredLength})"))
{
writer.WriteLine("return true;");
}
return true;
}
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)"))