-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
Copy pathRegexGenerator.Emitter.cs
3485 lines (3070 loc) · 171 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;
using System.Buffers.Binary;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp;
// NOTE: The logic in this file is largely a copy 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>Code for a [GeneratedCode] attribute to put on the top-level generated members.</summary>
private static readonly string s_generatedCodeAttribute = $"[global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"{typeof(RegexGenerator).Assembly.GetName().Name}\", \"{typeof(RegexGenerator).Assembly.GetName().Version}\")]";
/// <summary>Header comments and usings to include at the top of every generated file.</summary>
private static readonly string[] s_headers = new string[]
{
"// <auto-generated/>",
"#nullable enable",
"#pragma warning disable CS0162 // Unreachable code",
"#pragma warning disable CS0164 // Unreferenced label",
"#pragma warning disable CS0168 // Variable declared but never used",
"#pragma warning disable CS0219 // Variable assigned but never used",
"",
};
/// <summary>Generates the code for one regular expression class.</summary>
private static string EmitRegexType(RegexType regexClass)
{
var sb = new StringBuilder(1024);
var writer = new IndentedTextWriter(new StringWriter(sb));
// Emit the namespace
if (!string.IsNullOrWhiteSpace(regexClass.Namespace))
{
writer.WriteLine($"namespace {regexClass.Namespace}");
writer.WriteLine("{");
writer.Indent++;
}
// Emit containing types
RegexType? parent = regexClass.ParentClass;
var parentClasses = new Stack<string>();
while (parent is not null)
{
parentClasses.Push($"partial {parent.Keyword} {parent.Name} {parent.Constraints}");
parent = parent.ParentClass;
}
while (parentClasses.Count != 0)
{
writer.WriteLine($"{parentClasses.Pop()}");
writer.WriteLine("{");
writer.Indent++;
}
// Emit the direct parent type
writer.WriteLine($"partial {regexClass.Keyword} {regexClass.Name} {regexClass.Constraints}");
writer.WriteLine("{");
writer.Indent++;
// Generate a name to describe the regex instance. This includes the method name
// the user provided and a non-randomized (for determinism) hash of it to try to make
// the name that much harder to predict.
Debug.Assert(regexClass.Method is not null);
string generatedName = $"GeneratedRegex_{regexClass.Method.MethodName}_";
generatedName += ComputeStringHash(generatedName).ToString("X");
// Generate the regex type
EmitRegexMethod(writer, regexClass.Method, generatedName);
while (writer.Indent != 0)
{
writer.Indent--;
writer.WriteLine("}");
}
writer.Flush();
return sb.ToString();
// FNV-1a hash function. The actual algorithm used doesn't matter; just something simple
// to create a pseudo-random value based on input text.
static uint ComputeStringHash(string s)
{
uint hashCode = 2166136261;
foreach (char c in s)
{
hashCode = (c ^ hashCode) * 16777619;
}
return hashCode;
}
}
/// <summary>Gets whether a given regular expression method is supported by the code generator.</summary>
private static bool SupportsCustomCodeGeneration(RegexMethod rm) =>
// The generator doesn't currently know how to emit code for NonBacktracking.
(rm.Options & RegexOptions.NonBacktracking) == 0;
/// <summary>Generates the code for a regular expression method.</summary>
private static void EmitRegexMethod(IndentedTextWriter writer, RegexMethod rm, string id)
{
string patternExpression = Literal(rm.Pattern);
string optionsExpression = $"(global::System.Text.RegularExpressions.RegexOptions)({(int)rm.Options})";
string timeoutExpression = rm.MatchTimeout == Timeout.Infinite ?
"global::System.Threading.Timeout.InfiniteTimeSpan" :
$"global::System.TimeSpan.FromMilliseconds({rm.MatchTimeout.ToString(CultureInfo.InvariantCulture)})";
writer.WriteLine(s_generatedCodeAttribute);
writer.WriteLine($"{rm.Modifiers} global::System.Text.RegularExpressions.Regex {rm.MethodName}() => {id}.Instance;");
writer.WriteLine();
writer.WriteLine(s_generatedCodeAttribute);
writer.WriteLine("[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]");
writer.WriteLine($"{(writer.Indent != 0 ? "private" : "internal")} sealed class {id} : global::System.Text.RegularExpressions.Regex");
writer.WriteLine("{");
writer.Write(" public static global::System.Text.RegularExpressions.Regex Instance { get; } = ");
// If we can't support custom generation for this regex, spit out a Regex constructor call.
if (!SupportsCustomCodeGeneration(rm))
{
writer.WriteLine($"new global::System.Text.RegularExpressions.Regex({patternExpression}, {optionsExpression}, {timeoutExpression});");
writer.WriteLine("}");
return;
}
writer.WriteLine($"new {id}();");
writer.WriteLine();
writer.WriteLine($" private {id}()");
writer.WriteLine($" {{");
#if DEBUG
writer.WriteLine(" /*");
writer.WriteLine($"{rm.Code.Tree.ToString().Replace("*/", @"* /")}");
writer.WriteLine(" */");
#endif
writer.WriteLine($" base.pattern = {patternExpression};");
writer.WriteLine($" base.roptions = {optionsExpression};");
writer.WriteLine($" base.internalMatchTimeout = {timeoutExpression};");
writer.WriteLine($" base.factory = new RunnerFactory();");
if (rm.Code.Caps is not null)
{
writer.Write(" base.Caps = new global::System.Collections.Hashtable {");
AppendHashtableContents(writer, rm.Code.Caps);
writer.WriteLine(" };");
}
if (rm.Code.Tree.CapNames is not null)
{
writer.Write(" base.CapNames = new global::System.Collections.Hashtable {");
AppendHashtableContents(writer, rm.Code.Tree.CapNames);
writer.WriteLine(" };");
}
if (rm.Code.Tree.CapsList is not null)
{
writer.Write(" base.capslist = new string[] {");
string separator = "";
foreach (string s in rm.Code.Tree.CapsList)
{
writer.Write(separator);
writer.Write(Literal(s));
separator = ", ";
}
writer.WriteLine(" };");
}
writer.WriteLine($" base.capsize = {rm.Code.CapSize};");
writer.WriteLine($" base.InitializeReferences();");
writer.WriteLine($" }}");
writer.WriteLine(" ");
writer.WriteLine($" private sealed class RunnerFactory : global::System.Text.RegularExpressions.RegexRunnerFactory");
writer.WriteLine($" {{");
writer.WriteLine($" protected override global::System.Text.RegularExpressions.RegexRunner CreateInstance() => new Runner();");
writer.WriteLine();
writer.WriteLine($" private sealed class Runner : global::System.Text.RegularExpressions.RegexRunner");
writer.WriteLine($" {{");
// Main implementation methods
writer.WriteLine($" protected override void InitTrackCount() => base.runtrackcount = {rm.Code.TrackCount};");
writer.WriteLine();
writer.WriteLine($" protected override bool FindFirstChar()");
writer.WriteLine($" {{");
writer.Indent += 4;
EmitFindFirstChar(writer, rm, id);
writer.Indent -= 4;
writer.WriteLine($" }}");
writer.WriteLine();
writer.WriteLine($" protected override void Go()");
writer.WriteLine($" {{");
writer.Indent += 4;
EmitGo(writer, rm, id);
writer.Indent -= 4;
writer.WriteLine($" }}");
writer.WriteLine($" }}");
writer.WriteLine($" }}");
writer.WriteLine("}");
static void AppendHashtableContents(IndentedTextWriter writer, Hashtable ht)
{
IDictionaryEnumerator en = ht.GetEnumerator();
string separator = "";
while (en.MoveNext())
{
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 body of the FindFirstChar override.</summary>
private static void EmitFindFirstChar(IndentedTextWriter writer, RegexMethod rm, string id)
{
RegexOptions options = (RegexOptions)rm.Options;
RegexCode code = rm.Code;
(string CharClass, bool CaseInsensitive)[]? lcc = code.LeadingCharClasses;
bool rtl = code.RightToLeft;
bool hasTextInfo = false;
bool textInfoEmitted = false;
// Emit locals initialization
writer.WriteLine("string runtext = base.runtext!;");
writer.WriteLine("int runtextpos = base.runtextpos;");
writer.WriteLine("int runtextend = base.runtextend;");
if (rtl)
{
writer.WriteLine("int runtextbeg = base.runtextbeg;");
}
writer.WriteLine("int ch;");
writer.WriteLine();
// 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.Code.Tree.MinRequiredLength;
Debug.Assert(minRequiredLength >= 0);
string clause = !rtl ?
minRequiredLength switch
{
0 => "if (runtextpos <= runtextend)",
1 => "if (runtextpos < runtextend)",
_ => $"if (runtextpos < runtextend - {minRequiredLength - 1})"
} :
minRequiredLength switch
{
0 => "if (runtextpos >= runtextbeg)",
1 => "if (runtextpos > runtextbeg)",
_ => $"if (runtextpos - {minRequiredLength - 1} > runtextbeg)"
};
using (EmitBlock(writer, clause))
{
EmitAnchors();
if (code.BoyerMoorePrefix is RegexBoyerMoore { NegativeUnicode: null } rbm)
{
if (rbm.PatternSupportsIndexOf)
{
EmitIndexOf(rbm.Pattern);
}
else
{
EmitBoyerMoore(rbm);
}
}
else if (lcc is not null)
{
if (rtl)
{
EmitLeadingCharacter_RightToLeft();
}
else
{
EmitLeadingCharacter_LeftToRight();
}
}
else
{
writer.WriteLine("return true;");
}
}
writer.WriteLine();
writer.WriteLine("// No match");
writer.WriteLine("ReturnFalse:");
writer.WriteLine(!rm.Code.RightToLeft ? "base.runtextpos = runtextend;" : "base.runtextpos = runtextbeg;");
writer.WriteLine("return false;");
void EmitAnchors()
{
// Generate anchor checks.
if ((code.LeadingAnchor & (RegexPrefixAnalyzer.Beginning | RegexPrefixAnalyzer.Start | RegexPrefixAnalyzer.EndZ | RegexPrefixAnalyzer.End | RegexPrefixAnalyzer.Bol)) != 0)
{
// TODO: RegexInterpreter also factors in a Boyer-Moore prefix check in places Compiled just returns true.
// Determine if we should do so here and in Compiled as well, and potentially update RegexInterpreter.
// Interpreted and Compiled also differ in various places as to whether they update positions, as do LTR vs RTL. Determine why.
switch (code.LeadingAnchor)
{
case RegexPrefixAnalyzer.Beginning:
writer.WriteLine("// Beginning \\A anchor");
if (!rtl)
{
using (EmitBlock(writer, "if (runtextpos > runtextbeg)"))
{
writer.WriteLine("goto ReturnFalse;");
}
}
else
{
// TODO: RegexOptions.Compiled doesn't ever return false here. Instead it updates the position. Why?
using (EmitBlock(writer, "if (runtextpos > runtextbeg)"))
{
writer.WriteLine("base.runtextpos = runtextbeg;");
}
}
writer.WriteLine("return true;");
return;
case RegexPrefixAnalyzer.Start:
writer.WriteLine("// Start \\G anchor");
if (!rtl)
{
using (EmitBlock(writer, "if (runtextpos > runtextstart)"))
{
writer.WriteLine("goto ReturnFalse;");
}
}
else
{
// TODO: RegexOptions.Compiled doesn't ever return false here. Instead it updates the position. Why?
using (EmitBlock(writer, "if (runtextpos < runtextstart)"))
{
writer.WriteLine("goto ReturnFalse;");
}
}
writer.WriteLine("return true;");
return;
case RegexPrefixAnalyzer.EndZ:
// TODO: Why are the LTR and RTL cases inconsistent here with RegexOptions.Compiled?
writer.WriteLine("// End \\Z anchor");
if (!rtl)
{
using (EmitBlock(writer, "if (runtextpos < runtextend - 1)"))
{
writer.WriteLine("base.runtextpos = runtextend - 1;");
}
}
else
{
// TODO: This differs subtly between interpreted and compiled. Why?
using (EmitBlock(writer, "if (runtextpos < runtextend - 1 || (runtextpos == runtextend - 1 && runtext[runtextpos] != '\\n'))"))
{
writer.WriteLine("goto ReturnFalse;");
}
}
writer.WriteLine("return true;");
return;
case RegexPrefixAnalyzer.End when minRequiredLength == 0: // if it's > 0, we already output a more stringent check
writer.WriteLine("// End \\z anchor");
if (!rtl)
{
using (EmitBlock(writer, "if (runtextpos < runtextend)"))
{
writer.WriteLine("base.runtextpos = runtextend;");
}
}
else
{
using (EmitBlock(writer, "if (runtextpos < runtextend)"))
{
writer.WriteLine("goto ReturnFalse;");
}
}
writer.WriteLine("return true;");
return;
case RegexPrefixAnalyzer.Bol when !rtl: // Don't bother optimizing for the niche case of RegexOptions.RightToLeft | RegexOptions.Multiline
// 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 Boyer-Moore or
// leading char class searches.
writer.WriteLine("// Beginning-of-line anchor");
using (EmitBlock(writer, "if (runtextpos > runtextbeg && runtext[runtextpos - 1] != '\\n')"))
{
writer.WriteLine("int newlinePos = runtext.IndexOf('\\n', runtextpos);");
using (EmitBlock(writer, "if (newlinePos == -1 || newlinePos + 1 > runtextend)"))
{
writer.WriteLine("goto ReturnFalse;");
}
writer.WriteLine("runtextpos = newlinePos + 1;");
}
writer.WriteLine();
break;
}
}
}
void EmitBoyerMoore(RegexBoyerMoore rbm)
{
EmitTextInfoIfRequired(writer, ref textInfoEmitted, ref hasTextInfo, rm);
int beforefirst;
int last;
if (!rtl)
{
//limitLocal = "runtextend";
beforefirst = -1;
last = rbm.Pattern.Length - 1;
}
else
{
//limitLocal = "runtextbeg";
beforefirst = rbm.Pattern.Length;
last = 0;
}
int chLast = rbm.Pattern[last];
EmitAdd(writer, "runtextpos", !rtl ? rbm.Pattern.Length - 1 : -rbm.Pattern.Length);
using (EmitBlock(writer, $"while ({(!rtl ? "runtextpos < runtextend" : "runtextpos >= runtextbeg")})"))
{
writer.WriteLine($"ch = {ToLowerIfNeeded(hasTextInfo, options, "runtext[runtextpos]", rbm.CaseInsensitive)};");
using (EmitBlock(writer, $"if (ch != {Literal((char)chLast)})"))
{
writer.WriteLine($"ch -= {Literal((char)rbm.LowASCII)};");
using (EmitBlock(writer, $"if ((uint)ch > ({Literal((char)rbm.HighASCII)} - {Literal((char)rbm.LowASCII)}))"))
{
EmitAdd(writer, "runtextpos", (!rtl ? rbm.Pattern.Length : -rbm.Pattern.Length));
writer.WriteLine("continue;");
}
int negativeRange = rbm.HighASCII - rbm.LowASCII + 1;
if (negativeRange > 1) // High > Low
{
// Create a string to store the lookup table we use to find the offset.
// Store the offsets into the string. RightToLeft has negative offsets, so to support it with chars (unsigned), we negate
// the values to be stored in the string, and then at run time after looking up the offset in the string, negate it again.
Debug.Assert(rbm.Pattern.Length <= char.MaxValue, "RegexBoyerMoore should have limited the size allowed.");
Span<char> span = new char[negativeRange];
for (int i = 0; i < span.Length; i++)
{
int offset = rbm.NegativeASCII[i + rbm.LowASCII];
if (offset == beforefirst)
{
offset = rbm.Pattern.Length;
}
else if (rtl)
{
offset = -offset;
}
Debug.Assert(offset >= 0 && offset <= char.MaxValue);
span[i] = (char)offset;
}
writer.WriteLine($"runtextpos {(rtl ? "-=" : "+=")} {Literal(span.ToString())}[ch];");
}
else
{
Debug.Assert(negativeRange == 1); // High == Low
int offset = rbm.NegativeASCII[rbm.LowASCII];
if (offset == beforefirst)
{
offset = rtl ? -rbm.Pattern.Length : rbm.Pattern.Length;
}
EmitAdd(writer, "runtextpos", offset);
}
writer.WriteLine("continue;");
}
writer.WriteLine();
writer.WriteLine("int test = runtextpos;");
writer.WriteLine();
for (int i = rbm.Pattern.Length - 2; i >= 0; i--)
{
int charIndex = !rtl ? i : rbm.Pattern.Length - 1 - i;
bool sameAsPrev = i < rbm.Pattern.Length - 2 && rbm.Positive[charIndex] == rbm.Positive[!rtl ? i + 1 : rbm.Pattern.Length - 1 - (i + 1)];
bool sameAsNext = i > 0 && rbm.Positive[charIndex] == rbm.Positive[!rtl ? i - 1 : rbm.Pattern.Length - 1 - (i - 1)];
string condition = $"{ToLowerIfNeeded(hasTextInfo, options, (!rtl ? "runtext[--test]" : "runtext[++test]"), rbm.CaseInsensitive && RegexCharClass.ParticipatesInCaseConversion(rbm.Pattern[charIndex]))} != {Literal(rbm.Pattern[charIndex])}";
switch ((sameAsPrev, sameAsNext))
{
case (true, true):
writer.WriteLine($" {condition} ||");
break;
case (false, true):
writer.WriteLine($"if ({condition} ||");
break;
case (true, false):
writer.WriteLine($" {condition})");
using (EmitBlock(writer, null))
{
EmitAdd(writer, "runtextpos", rbm.Positive[charIndex]);
writer.WriteLine("continue;");
}
writer.WriteLine();
break;
case (false, false):
using (EmitBlock(writer, $"if ({condition})"))
{
EmitAdd(writer, "runtextpos", rbm.Positive[charIndex]);
writer.WriteLine("continue;");
}
writer.WriteLine();
break;
}
}
writer.WriteLine(!rtl ?
"base.runtextpos = test;" :
"base.runtextpos = test + 1;");
writer.WriteLine("return true;");
}
}
void EmitIndexOf(string prefix)
{
writer.WriteLine($"int i = global::System.MemoryExtensions.IndexOf(global::System.MemoryExtensions.AsSpan(runtext, runtextpos, runtextend - runtextpos), {Literal(prefix)});");
writer.WriteLine("if (i >= 0)");
writer.WriteLine("{");
writer.WriteLine(" base.runtextpos = runtextpos + i;");
writer.WriteLine(" return true;");
writer.WriteLine("}");
}
void EmitLeadingCharacter_RightToLeft()
{
EmitTextInfoIfRequired(writer, ref textInfoEmitted, ref hasTextInfo, rm);
Debug.Assert(lcc.Length == 1, "Only the FirstChars and not MultiFirstChars computation is supported for RightToLeft");
string set = lcc[0].CharClass;
if (RegexCharClass.IsSingleton(set))
{
char ch = RegexCharClass.SingletonChar(set);
using (EmitBlock(writer, "for (int i = runtextpos - 1; i >= runtextbeg; i--)"))
{
using (EmitBlock(writer, $"if (runtext[i] == {ToLowerIfNeeded(hasTextInfo, options, Literal(ch), lcc[0].CaseInsensitive)})"))
{
writer.WriteLine("base.runtextpos = i + 1;");
writer.WriteLine("return true;");
}
}
}
else
{
using (EmitBlock(writer, "for (int i = runtextpos - 1; i >= runtextbeg; i--)"))
{
using (EmitBlock(writer, $"if ({MatchCharacterClass(hasTextInfo, options, "runtext[i]", set, lcc[0].CaseInsensitive)})"))
{
writer.WriteLine("runtextpos = i + 1;");
writer.WriteLine("return true;");
}
}
}
}
void EmitLeadingCharacter_LeftToRight()
{
Debug.Assert(lcc is not null && lcc.Length > 0);
// If minRequiredLength > 0, we already output a more stringent check. In the rare case
// where we were unable to get an accurate enough min required length to ensure it's larger
// than the prefixes we calculated, we also need to ensure we have enough space for those,
// as they also represent a min required length.
if (minRequiredLength < lcc.Length)
{
writer.WriteLine($"// Validate at least {lcc.Length} characters are available to match");
string endExpr = lcc.Length > 1 ? $"runtextend - {lcc.Length - 1}" : "runtextend";
using (EmitBlock(writer, $"if (runtextpos >= {endExpr})"))
{
writer.WriteLine("goto ReturnFalse;");
}
writer.WriteLine();
}
writer.WriteLine("global::System.ReadOnlySpan<char> span = global::System.MemoryExtensions.AsSpan(runtext, runtextpos, runtextend - runtextpos);");
// 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.
Span<char> setChars = stackalloc char[3]; // up to 3 characters handled by IndexOf{Any} below
int setCharsCount = 0, charClassIndex = 0;
bool canUseIndexOf =
!lcc[0].CaseInsensitive &&
(setCharsCount = RegexCharClass.GetSetChars(lcc[0].CharClass, setChars)) > 0 &&
!RegexCharClass.IsNegated(lcc[0].CharClass);
bool needLoop = !canUseIndexOf || lcc.Length > 1;
FinishEmitScope loopBlock = default;
if (needLoop)
{
EmitTextInfoIfRequired(writer, ref textInfoEmitted, ref hasTextInfo, rm);
writer.WriteLine();
string upperBound = lcc.Length > 1 ? $"span.Length - {lcc.Length - 1}" : "span.Length";
loopBlock = EmitBlock(writer, $"for (int i = 0; i < {upperBound}; i++)");
}
if (canUseIndexOf)
{
charClassIndex = 1;
string span = needLoop ? "span.Slice(i)" : "span";
string indexOf = setCharsCount switch
{
1 => $"global::System.MemoryExtensions.IndexOf({span}, {Literal(setChars[0])})",
2 => $"global::System.MemoryExtensions.IndexOfAny({span}, {Literal(setChars[0])}, {Literal(setChars[1])})",
_ => $"global::System.MemoryExtensions.IndexOfAny({span}, {Literal(setChars[0])}, {Literal(setChars[1])}, {Literal(setChars[2])})",
};
if (needLoop)
{
writer.WriteLine($"int indexOfPos = {indexOf};");
using (EmitBlock(writer, "if (indexOfPos < 0)"))
{
writer.WriteLine("goto ReturnFalse;");
}
writer.WriteLine("i += indexOfPos;");
writer.WriteLine();
if (lcc.Length > 1)
{
using (EmitBlock(writer, $"if (i >= span.Length - {lcc.Length - 1})"))
{
writer.WriteLine("goto ReturnFalse;");
}
}
}
else
{
writer.WriteLine($"int i = {indexOf};");
using (EmitBlock(writer, "if (i < 0)"))
{
writer.WriteLine("goto ReturnFalse;");
}
}
writer.WriteLine();
}
Debug.Assert(charClassIndex == 0 || charClassIndex == 1);
bool hasCharClassConditions = false;
if (charClassIndex < lcc.Length)
{
// if (CharInClass(textSpan[i + charClassIndex], prefix[0], "...") &&
// ...)
Debug.Assert(needLoop);
int start = charClassIndex;
for (; charClassIndex < lcc.Length; charClassIndex++)
{
string spanIndex = charClassIndex > 0 ? $"span[i + {charClassIndex}]" : "span[i]";
string charInClassExpr = MatchCharacterClass(hasTextInfo, options, spanIndex, lcc[charClassIndex].CharClass, lcc[charClassIndex].CaseInsensitive);
if (charClassIndex == 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 = runtextpos + i;");
writer.WriteLine("return true;");
}
loopBlock.Dispose();
}
}
/// <summary>Emits the body of the Go override.</summary>
private static void EmitGo(IndentedTextWriter writer, RegexMethod rm, string id)
{
Debug.Assert(rm.Code.Tree.Root.Type == RegexNode.Capture);
if ((rm.Options & RegexOptions.NonBacktracking) != 0)
{
EmitNonBacktrackingGo(writer, rm, id);
return;
}
RegexNode root = rm.Code.Tree.Root;
if (!ExceedsMaxDepthForSimpleCodeGeneration(root) &&
root.Child(0).SupportsSimplifiedCodeGenerationImplementation() &&
(((RegexOptions)root.Options) & RegexOptions.RightToLeft) == 0)
{
EmitSimplifiedGo(writer, rm, id);
return;
}
EmitCompleteGo(writer, rm, id);
// Deep RegexNode trees used with the simplified code generator can result in
// emitting C# code that exceeds C# compiler limitations, leading to "CS8078: An
// expression is too long or complex to compile". Place an artificial limit on
// max tree depth in order to mitigate such issues.
static bool ExceedsMaxDepthForSimpleCodeGeneration(RegexNode node, int maxDepth = 30)
{
if (maxDepth <= 0)
{
return true;
}
int childCount = node.ChildCount();
for (int i = 0; i < childCount; i++)
{
if (ExceedsMaxDepthForSimpleCodeGeneration(node.Child(i), maxDepth - 1))
{
return true;
}
}
return false;
}
}
/// <summary>Emits the body of a Go method supporting RegexOptions.NonBacktracking.</summary>
private static void EmitNonBacktrackingGo(IndentedTextWriter writer, RegexMethod rm, string id)
{
// TODO: Implement this and remove SupportsCustomCodeGeneration.
}
/// <summary>Emits the body of a simplified Go implementation that's possible when there's minimal backtracking required by the expression.</summary>
private static void EmitSimplifiedGo(IndentedTextWriter writer, RegexMethod rm, string id)
{
RegexOptions options = (RegexOptions)rm.Options;
RegexCode code = rm.Code;
(string CharClass, bool CaseInsensitive)[]? lcc = code.LeadingCharClasses;
bool rtl = code.RightToLeft;
bool hasTimeout = false;
int localCounter = 0;
string NextLocalName(string prefix) => $"{prefix}{localCounter++}";
RegexNode node = rm.Code.Tree.Root;
Debug.Assert(node.Type == RegexNode.Capture, "Every generated tree should begin with a capture node");
Debug.Assert(node.ChildCount() == 1, "Capture nodes should have one child");
// Skip the Capture node. We handle the implicit root capture specially.
node = node.Child(0);
// If there's any backtracking in the expression, nodes may emit labels that their peers
// need to jump to. Scopes (which we emit for readability) get in the way of that. As such,
// for nodes that emit such labels, we emit faux, commented-out scopes instead.
HashSet<RegexNode> nodesWithCrossScopeLabels = NodesWithCrossScopeLabels(node);
// In some limited cases, FindFirstChar will only return true if it successfully matched the whole thing.
// This is the case, in particular, for strings. We can special case these to do essentially nothing
// in Go other than emit the capture.
if (!IsCaseInsensitive(node)) // FindFirstChar may not be 100% accurate on casing in all cultures
{
switch (node.Type)
{
case RegexNode.Multi:
case RegexNode.Notone:
case RegexNode.One:
case RegexNode.Set:
writer.WriteLine($"int start = base.runtextpos;");
writer.WriteLine($"int end = start + {(node.Type == RegexNode.Multi ? node.Str!.Length : 1)};");
writer.WriteLine("base.Capture(0, start, end);");
writer.WriteLine("base.runtextpos = end;");
return;
}
}
// Declare some locals.
string textSpanLocal = "textSpan";
writer.WriteLine("string runtext = base.runtext!;");
writer.WriteLine("int runtextpos = base.runtextpos;");
writer.WriteLine("int runtextend = base.runtextend;");
writer.WriteLine("int originalruntextpos = runtextpos;");
writer.WriteLine("global::System.ReadOnlySpan<byte> byteSpan;");
writer.WriteLine("char ch;");
hasTimeout = EmitLoopTimeoutCounterIfNeeded(writer, rm);
// TextInfo textInfo = CultureInfo.CurrentCulture.TextInfo; // only if the whole expression or any subportion is ignoring case, and we're not using invariant
bool hasTextInfo = EmitInitializeCultureForGoIfNecessary(writer, rm);
// The implementation tries to use const indexes into the span wherever possible, which we can do
// in all places except for variable-length loops. For everything else, we know at any point in
// the regex exactly how far into it we are, and we can use that to index into the span created
// at the beginning of the routine to begin at exactly where we're starting in the input. For
// variable-length loops, we index at this textSpanPos + i, and then after the loop we slice the input
// by i so that this position is still accurate for everything after it.
int textSpanPos = 0;
LoadTextSpanLocal(writer, defineLocal: true);
writer.WriteLine();
int labelCounter = 0;
string DefineLabel(string prefix = "L") => $"{prefix}{labelCounter++}";
void MarkLabel(string label) => writer.WriteLine($"{label}:");
void Goto(string label) => writer.WriteLine($"goto {label};");
string doneLabel = "NoMatch";
string originalDoneLabel = doneLabel;
// Emit the code for all nodes in the tree.
bool expressionHasCaptures = (node.Options & RegexNode.HasCapturesFlag) != 0;
EmitNode(node);
// Emit success
writer.WriteLine("// Match");
if (textSpanPos > 0)
{
EmitAdd(writer, "runtextpos", textSpanPos);
}
writer.WriteLine("base.runtextpos = runtextpos;");
writer.WriteLine("base.Capture(0, originalruntextpos, runtextpos);");
writer.WriteLine("return;");
writer.WriteLine();
// Emit failure
writer.WriteLine("// No match");
MarkLabel(originalDoneLabel);
if (expressionHasCaptures)
{
EmitUncaptureUntil("0");
}
else
{
// We can't have a label at the end of the method, so explicitly
// add a "return;" if the End label would otherwise be an issue.
writer.WriteLine("return;");
}
return;
static bool IsCaseInsensitive(RegexNode node) => (node.Options & RegexOptions.IgnoreCase) != 0;
// Creates a span for runtext starting at runtextpos until base.runtextend.
void LoadTextSpanLocal(IndentedTextWriter writer, bool defineLocal = false)
{
if (defineLocal)
{
writer.Write("global::System.ReadOnlySpan<char> ");
}
writer.WriteLine($"{textSpanLocal} = global::System.MemoryExtensions.AsSpan(runtext, runtextpos, runtextend - runtextpos);");
}
// Emits the sum of a constant and a value from a local.
string Sum(int constant, string? local = null) =>
local is null ? constant.ToString() :
constant == 0 ? local :
$"{constant} + {local}";
// Emits a check that the span is large enough at the currently known static position to handle the required additional length.
void EmitSpanLengthCheck(int requiredLength, string? dynamicRequiredLength = null)
{
Debug.Assert(requiredLength > 0);
using (EmitBlock(writer, $"if ({SpanLengthCheck(requiredLength, dynamicRequiredLength)})"))
{
writer.WriteLine($"goto {doneLabel};");
}
}
string SpanLengthCheck(int requiredLength, string? dynamicRequiredLength = null) =>
$"(uint){textSpanLocal}.Length < {Sum(textSpanPos + requiredLength, dynamicRequiredLength)}";
// Adds the value of textSpanPos into the runtextpos local, slices textspan by the corresponding amount,
// and zeros out textSpanPos.
void TransferTextSpanPosToRunTextPos()
{
if (textSpanPos > 0)
{
EmitAdd(writer, "runtextpos", textSpanPos);
writer.WriteLine($"{textSpanLocal} = {textSpanLocal}.Slice({textSpanPos});");
textSpanPos = 0;
}
}
string AddTextSpanPos() => textSpanPos > 0 ? $" + {textSpanPos}" : "";
// Emits the code for an atomic alternate, one that once a branch successfully matches is non-backtracking into it.
// This amounts to generating the code for each branch, with failures in a branch resetting state to what it was initially
// and then jumping to the next branch. We don't need to worry about uncapturing, because capturing is only allowed for the
// implicit capture that happens for the whole match at the end.
void EmitAtomicAlternate(RegexNode node)
{
int childCount = node.ChildCount();
Debug.Assert(childCount >= 2);
// If no child branch overlaps with another child branch, we can emit more streamlined code
// that avoids checking unnecessary branches, e.g. with abc|def|ghi if the next character in
// the input is 'a', we needn't try the def or ghi branches. A simple, relatively common case
// of this is if every branch begins with a specific, unique character, in which case
// the whole alternation can be treated as a simple switch, so we special-case that.
var seenChars = new HashSet<char>();
bool allBranchesStartUnique = true;
for (int i = 0; i < childCount; i++)
{
if (node.Child(i).FindBranchOneOrMultiStart() is not RegexNode oneOrMulti ||
!seenChars.Add(oneOrMulti.FirstCharOfOneOrMulti()))
{
allBranchesStartUnique = false;
break;
}
}
if (allBranchesStartUnique)
{
// Note: This optimization does not exist with RegexOptions.Compiled. Here we rely on the
// C# compiler to lower the C# switch statement with appropriate optimizations.
EmitSwitchedBranches();
}
else
{
EmitAllBranches();
}
void EmitSwitchedBranches()
{
EmitSpanLengthCheck(1);
writer.WriteLine();
using (EmitBlock(writer, $"switch ({ToLowerIfNeeded(hasTextInfo, options, $"{textSpanLocal}[{textSpanPos++}]", IsCaseInsensitive(node))})"))
{
int startingTextSpanPos = textSpanPos;
for (int i = 0; i < childCount; i++)
{
textSpanPos = startingTextSpanPos;
RegexNode child = node.Child(i);
Debug.Assert(child.Type is RegexNode.One or RegexNode.Multi or RegexNode.Concatenate, child.Description());
Debug.Assert(child.Type is not RegexNode.Concatenate || (child.ChildCount() >= 2 && child.Child(0).Type is RegexNode.One or RegexNode.Multi));
RegexNode? childStart = child.FindBranchOneOrMultiStart();
Debug.Assert(childStart is not null, child.Description());
writer.WriteLine($"case {Literal(childStart.FirstCharOfOneOrMulti())}:");
writer.Indent++;
// Emit the code for the branch, without the first character that was already matched in the switch.
switch (child.Type)
{
case RegexNode.Multi:
EmitNode(CloneMultiWithoutFirstChar(child));
break;
case RegexNode.Concatenate:
var newConcat = new RegexNode(RegexNode.Concatenate, child.Options);
if (childStart.Type == RegexNode.Multi)
{
newConcat.AddChild(CloneMultiWithoutFirstChar(childStart));
}
int concatChildCount = child.ChildCount();
for (int j = 1; j < concatChildCount; j++)
{
newConcat.AddChild(child.Child(j));
}
EmitNode(newConcat.Reduce());
break;
static RegexNode CloneMultiWithoutFirstChar(RegexNode node)
{
Debug.Assert(node.Type is RegexNode.Multi);
Debug.Assert(node.Str!.Length >= 2);
return node.Str!.Length == 2 ?
new RegexNode(RegexNode.One, node.Options, node.Str![1]) :
new RegexNode(RegexNode.Multi, node.Options, node.Str!.Substring(1));
}
}
// If we get here in the generated code, the branch completed successfully.
// Before jumping to the end, we need to zero out textSpanPos, so that no
// matter what the value is after the branch, whatever follows the alternate
// will see the same textSpanPos.
TransferTextSpanPosToRunTextPos();
writer.WriteLine($"break;");
writer.WriteLine();
writer.Indent--;
}
// Default branch if the character didn't match the start of any branches.
writer.WriteLine("default:");