-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathProgram.cs
More file actions
973 lines (834 loc) · 29 KB
/
Copy pathProgram.cs
File metadata and controls
973 lines (834 loc) · 29 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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.Json;
using System.Text.Json.Serialization;
using Resharp;
using DotnetRegex = System.Text.RegularExpressions.Regex;
using DotnetRegexOptions = System.Text.RegularExpressions.RegexOptions;
using RegexMatchTimeoutException = System.Text.RegularExpressions.RegexMatchTimeoutException;
class Program
{
private const int DefaultInputSize = 100_000;
private const int DefaultRuns = 3;
private static readonly TimeSpan DefaultTimeout = TimeSpan.FromSeconds(2);
// Default input sizes (chars) swept per dataset case when --input-sweep is
// not given. Mirrors the Rust runner so all engines share the heatmap's
// input axis.
private static readonly int[] DefaultInputSweep =
{ 1000, 10000, 25000, 50000, 75000, 100000, 150000, 200000 };
static void Main(string[] args)
{
if (args.Length > 0 && args[0] == "--child")
{
RunChild(args);
return;
}
var inputSize = ParseIntArg(args, "--input-length", ParseIntArg(args, "--input-size", DefaultInputSize));
var numRuns = ParseIntArg(args, "--runs", DefaultRuns);
var timeoutSeconds = ParseDoubleArg(args, "--timeout", DefaultTimeout.TotalSeconds);
if (timeoutSeconds <= 0)
{
throw new ArgumentException($"Invalid value for --timeout: {timeoutSeconds.ToString(CultureInfo.InvariantCulture)}");
}
var timeout = TimeSpan.FromSeconds(timeoutSeconds);
var singleTestId = ParseNullableIntArg(args, "--single");
var showTests = HasFlag(args, "--show-tests");
var datasetDir = GetArgValue(args, "--dataset");
var inProcess = HasFlag(args, "--in-process");
var libraries = GetLibraries(timeout);
var tests = datasetDir != null
? GetDatasetCases(datasetDir)
: GetTestCases(inputSize);
if (datasetDir != null)
{
var sweep = ParseInputSweep(GetArgValue(args, "--input-sweep")) ?? DefaultInputSweep;
if (sweep.Length > 0)
{
Console.WriteLine($"Sweeping input sizes: {string.Join(",", sweep)}");
tests = ExpandWithSweep(tests, sweep);
}
}
if (singleTestId.HasValue)
{
var results = RunSingleTest(singleTestId.Value, libraries, tests, inProcess);
foreach (var result in results)
{
Console.WriteLine($"{result.Library}: {result.Result.Result}");
}
return;
}
var worstCaseSeconds = (double)tests.Count * libraries.Count * numRuns * timeoutSeconds;
Console.WriteLine($"Config: {tests.Count} tests x {libraries.Count} libraries x {numRuns} runs (timeout {timeoutSeconds}s each, mode {(inProcess ? "in-process" : "subprocess")})");
Console.WriteLine($"Worst-case duration: {FormatDuration(worstCaseSeconds)} (if every test times out)");
var overallStopwatch = Stopwatch.StartNew();
var allResults = RunAllTests(numRuns, libraries, tests, showTests, inProcess);
overallStopwatch.Stop();
Console.WriteLine($"Completed all runs in {FormatDuration(overallStopwatch.Elapsed.TotalSeconds)}");
var summaryStats = CalculateSummaryStats(allResults, libraries);
SaveResults(allResults, summaryStats, libraries, numRuns, tests.Count, timeoutSeconds, datasetDir != null, inProcess);
}
static void RunChild(string[] args)
{
if (args.Length < 4)
{
WriteChildResult(new ChildResult { Error = "Child invocation requires engine, pattern, and testId." });
return;
}
var engine = args[1];
var pattern = args[2];
var input = Console.In.ReadToEnd();
try
{
if (engine == "RE#")
{
var match = new Regex(pattern).IsMatch(input);
WriteChildResult(new ChildResult { Match = match });
return;
}
if (engine == "dotnet")
{
var match = new DotnetRegex(pattern).IsMatch(input);
WriteChildResult(new ChildResult { Match = match });
return;
}
WriteChildResult(new ChildResult { Error = $"Unknown engine: {engine}" });
}
catch (Exception ex)
{
WriteChildResult(new ChildResult { Error = $"{ex.GetType().Name}: {ex.Message}" });
}
}
static void WriteChildResult(ChildResult result)
{
var options = new JsonSerializerOptions
{
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
};
Console.WriteLine(JsonSerializer.Serialize(result, options));
}
static List<RegexLibrary> GetLibraries(TimeSpan timeout)
{
return new List<RegexLibrary>
{
new RegexLibrary { Name = "RE#", Engine = "RE#", Timeout = timeout },
new RegexLibrary { Name = "dotnet", Engine = "dotnet", Timeout = timeout },
};
}
static List<TestCaseRun> GetTestCases(int inputSize)
{
var testCasesPath = FindFilePath("test_cases.json");
if (string.IsNullOrWhiteSpace(testCasesPath))
{
throw new FileNotFoundException("Unable to locate test_cases.json.");
}
var raw = File.ReadAllText(testCasesPath);
var testCases = JsonSerializer.Deserialize<List<TestCase>>(
raw,
new JsonSerializerOptions { PropertyNameCaseInsensitive = true }
);
if (testCases == null)
{
throw new InvalidOperationException("Failed to parse test_cases.json.");
}
return testCases
.OrderBy(tc => tc.Id)
.Select(tc => new TestCaseRun
{
Id = tc.Id,
Pattern = tc.Regex,
Input = RepeatString(tc.Repeat, inputSize)
})
.ToList();
}
/// <summary>
/// Load every *.json file under [datasetDir] as a new-schema DatasetCase.
/// Files are sorted by filename so the run order matches the case id.
/// </summary>
static List<TestCaseRun> GetDatasetCases(string datasetDir)
{
if (!Directory.Exists(datasetDir))
{
throw new DirectoryNotFoundException($"Dataset directory not found: {datasetDir}");
}
var files = Directory.GetFiles(datasetDir, "*.json");
Array.Sort(files, StringComparer.Ordinal);
var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
var result = new List<TestCaseRun>(files.Length);
foreach (var path in files)
{
var raw = File.ReadAllText(path);
var c = JsonSerializer.Deserialize<DatasetCase>(raw, options);
if (c == null)
{
throw new InvalidOperationException($"Failed to parse {path}.");
}
result.Add(new TestCaseRun
{
Id = c.Id,
Pattern = c.Regex,
Input = c.Input,
Metadata = new CaseMetadata
{
Group = c.Group,
Size = c.Size,
AstSize = c.AstSize,
AstDepth = c.AstDepth,
RegexSize = c.RegexSize,
InputSize = c.InputSize,
},
});
}
return result;
}
static List<SingleTestResult> RunSingleTest(
int testId,
List<RegexLibrary> libraries,
List<TestCaseRun> tests,
bool inProcess = false
)
{
if (testId < 1 || testId > tests.Count)
{
throw new ArgumentOutOfRangeException(nameof(testId), $"Invalid test_id. Must be between 1 and {tests.Count}.");
}
var test = tests[testId - 1];
var results = new List<SingleTestResult>();
foreach (var library in libraries)
{
results.Add(inProcess
? RunTestInProcess(library, test.Id, test.Pattern, test.Input, test.Metadata)
: RunTestWithTimeout(library, test.Id, test.Pattern, test.Input, test.Metadata));
}
return results;
}
static List<SingleTestResult> RunAllTests(
int numRuns,
List<RegexLibrary> libraries,
List<TestCaseRun> tests,
bool showTests,
bool inProcess = false
)
{
var allResults = new List<SingleTestResult>();
for (var run = 0; run < numRuns; run++)
{
var runStopwatch = Stopwatch.StartNew();
Console.WriteLine($"Run {run + 1}/{numRuns}{(inProcess ? " (in-process)" : "")}");
for (var i = 0; i < tests.Count; i++)
{
var test = tests[i];
if (showTests)
{
Console.WriteLine($" Test {test.Id} ({i + 1}/{tests.Count})");
}
foreach (var library in libraries)
{
var result = inProcess
? RunTestInProcess(library, test.Id, test.Pattern, test.Input, test.Metadata)
: RunTestWithTimeout(library, test.Id, test.Pattern, test.Input, test.Metadata);
allResults.Add(result);
if (result.Result.TimedOut)
{
Console.WriteLine($" [{library.Name}] test {test.Id} TIMED OUT after {result.Result.Time:0.00}s");
}
}
}
runStopwatch.Stop();
Console.WriteLine($"Run {run + 1}/{numRuns} finished in {FormatDuration(runStopwatch.Elapsed.TotalSeconds)}");
}
return allResults;
}
/// <summary>
/// In-process timing: runs the regex in the host process and times only
/// the IsMatch() call. Uses .NET Regex's built-in MatchTimeout for the
/// `dotnet` engine; the RE# engine has no native timeout, so an extreme
/// pattern there can hang the run for up to library.Timeout via the
/// host-side stopwatch.
/// </summary>
static SingleTestResult RunTestInProcess(
RegexLibrary library,
int testId,
string pattern,
string input,
CaseMetadata? metadata
)
{
var sw = Stopwatch.StartNew();
try
{
bool match;
if (library.Engine == "dotnet")
{
var re = new DotnetRegex(pattern, DotnetRegexOptions.None, library.Timeout);
sw.Restart();
match = re.IsMatch(input);
}
else // "RE#"
{
var re = new Regex(pattern);
sw.Restart();
match = re.IsMatch(input);
}
sw.Stop();
return BuildResult(testId, pattern, input, library.Name, match,
sw.Elapsed.TotalSeconds, timedOut: false, metadata);
}
catch (RegexMatchTimeoutException)
{
sw.Stop();
return BuildResult(testId, pattern, input, library.Name, null,
library.Timeout.TotalSeconds, timedOut: true, metadata);
}
catch (Exception)
{
sw.Stop();
return BuildResult(testId, pattern, input, library.Name, null,
sw.Elapsed.TotalSeconds, timedOut: false, metadata);
}
}
static SingleTestResult RunTestWithTimeout(
RegexLibrary library,
int testId,
string pattern,
string input,
CaseMetadata? metadata
)
{
var startInfo = CreateChildProcessStartInfo(library.Engine, pattern, testId);
using var process = Process.Start(startInfo);
var stopwatch = Stopwatch.StartNew();
if (process == null)
{
stopwatch.Stop();
return BuildResult(testId, pattern, input, library.Name, null, stopwatch.Elapsed.TotalSeconds, timedOut: false, metadata);
}
var stdoutTask = process.StandardOutput.ReadToEndAsync();
var stderrTask = process.StandardError.ReadToEndAsync();
_ = WriteStdinAsync(process, input);
if (!process.WaitForExit((int)library.Timeout.TotalMilliseconds))
{
TryKillProcessTree(process);
stopwatch.Stop();
return BuildResult(testId, pattern, input, library.Name, null, stopwatch.Elapsed.TotalSeconds, timedOut: true, metadata);
}
stopwatch.Stop();
var stdout = stdoutTask.Result;
var stderr = stderrTask.Result;
var childResult = ParseChildResult(stdout, stderr);
return BuildResult(
testId,
pattern,
input,
library.Name,
childResult.Match,
stopwatch.Elapsed.TotalSeconds,
timedOut: false,
metadata
);
}
static ChildResult ParseChildResult(string stdout, string stderr)
{
if (!string.IsNullOrWhiteSpace(stderr))
{
return new ChildResult { Error = stderr.Trim() };
}
if (string.IsNullOrWhiteSpace(stdout))
{
return new ChildResult { Error = "Empty child output." };
}
try
{
var result = JsonSerializer.Deserialize<ChildResult>(
stdout,
new JsonSerializerOptions { PropertyNameCaseInsensitive = true }
);
return result ?? new ChildResult { Error = "Failed to parse child output." };
}
catch (Exception ex)
{
return new ChildResult { Error = $"Failed to parse child output: {ex.Message}" };
}
}
static SingleTestResult BuildResult(
int testId,
string pattern,
string input,
string libraryName,
bool? match,
double elapsedSeconds,
bool timedOut,
CaseMetadata? metadata
)
{
return new SingleTestResult
{
TestId = testId,
Pattern = pattern,
Input = input,
Library = libraryName,
Result = new LibraryResult
{
Library = libraryName,
Result = match,
Time = elapsedSeconds,
TimedOut = timedOut
},
Metadata = metadata,
};
}
static ProcessStartInfo CreateChildProcessStartInfo(
string engine,
string pattern,
int testId
)
{
var processPath = Environment.ProcessPath;
var assemblyPath = Assembly.GetExecutingAssembly().Location;
if (string.IsNullOrWhiteSpace(processPath))
{
throw new InvalidOperationException("Unable to determine current process path.");
}
var startInfo = new ProcessStartInfo
{
RedirectStandardInput = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
};
if (Path.GetFileName(processPath).Equals("dotnet", StringComparison.OrdinalIgnoreCase)
&& !string.IsNullOrWhiteSpace(assemblyPath))
{
startInfo.FileName = processPath;
startInfo.ArgumentList.Add(assemblyPath);
}
else
{
startInfo.FileName = processPath;
}
startInfo.ArgumentList.Add("--child");
startInfo.ArgumentList.Add(engine);
startInfo.ArgumentList.Add(pattern);
startInfo.ArgumentList.Add(testId.ToString(CultureInfo.InvariantCulture));
return startInfo;
}
static async System.Threading.Tasks.Task WriteStdinAsync(Process process, string input)
{
try
{
await process.StandardInput.WriteAsync(input);
await process.StandardInput.FlushAsync();
}
catch (Exception)
{
}
finally
{
try
{
process.StandardInput.Close();
}
catch (Exception)
{
}
}
}
static void TryKillProcessTree(Process process)
{
try
{
process.Kill(entireProcessTree: true);
}
catch (Exception)
{
}
}
static Dictionary<string, SummaryStat> CalculateSummaryStats(
List<SingleTestResult> allResults,
List<RegexLibrary> libraries
)
{
var summary = new Dictionary<string, SummaryStat>();
foreach (var library in libraries)
{
var results = allResults.Where(r => r.Library == library.Name).ToList();
var times = results
.Where(r => !r.Result.TimedOut)
.Select(r => r.Result.Time)
.OrderBy(t => t)
.ToList();
var totalCount = results.Count;
var timeoutCount = results.Count(r => r.Result.TimedOut);
double? mean = null;
double? median = null;
if (times.Count > 0)
{
mean = times.Sum() / times.Count;
median = times.Count % 2 == 0
? (times[times.Count / 2 - 1] + times[times.Count / 2]) / 2
: times[times.Count / 2];
}
summary[library.Name] = new SummaryStat
{
MeanTime = mean,
MedianTime = median,
MinTime = times.Count > 0 ? times.First() : null,
MaxTime = times.Count > 0 ? times.Last() : null,
TimeoutCount = timeoutCount,
TotalCount = totalCount
};
}
return summary;
}
static void SaveResults(
List<SingleTestResult> allResults,
Dictionary<string, SummaryStat> summaryStats,
List<RegexLibrary> libraries,
int numRuns,
int testsCount,
double timeoutSeconds,
bool fromDataset,
bool inProcess
)
{
var testCasesPath = FindFilePath("test_cases.json");
if (string.IsNullOrWhiteSpace(testCasesPath))
{
throw new FileNotFoundException("Unable to locate test_cases.json.");
}
var timeoutText = TimeoutLabel(timeoutSeconds);
var tag = (fromDataset ? "_dataset" : "") + (inProcess ? "_inproc" : "");
var outputPath = Path.Combine(
Path.GetDirectoryName(testCasesPath) ?? ".",
$"csharp_redos_test_results{tag}_timeout-{timeoutText}.json"
);
var outputData = new ResultsFile
{
Metadata = new Metadata
{
Timestamp = DateTimeOffset.UtcNow.ToString("o", CultureInfo.InvariantCulture),
TotalRuns = numRuns,
TotalTests = testsCount,
TotalLibraries = libraries.Count,
Libraries = libraries.Select(lib => lib.Name).ToList()
},
SummaryStats = summaryStats,
Results = allResults
};
var options = new JsonSerializerOptions
{
WriteIndented = true
};
File.WriteAllText(outputPath, JsonSerializer.Serialize(outputData, options));
Console.WriteLine($"Saved {allResults.Count} results to {outputPath}");
}
static string? FindFilePath(string fileName)
{
var candidates = new List<string?>
{
Directory.GetCurrentDirectory(),
AppContext.BaseDirectory
};
foreach (var start in candidates)
{
if (string.IsNullOrWhiteSpace(start))
{
continue;
}
var dir = new DirectoryInfo(start);
while (dir != null)
{
var candidate = Path.Combine(dir.FullName, fileName);
if (File.Exists(candidate))
{
return candidate;
}
dir = dir.Parent;
}
}
return null;
}
static int ParseIntArg(string[] args, string flag, int defaultValue)
{
var raw = GetArgValue(args, flag);
if (raw == null)
{
return defaultValue;
}
if (!int.TryParse(raw, NumberStyles.Integer, CultureInfo.InvariantCulture, out var value))
{
throw new ArgumentException($"Invalid value for {flag}: {raw}");
}
return value;
}
static double ParseDoubleArg(string[] args, string flag, double defaultValue)
{
var raw = GetArgValue(args, flag);
if (raw == null)
{
return defaultValue;
}
if (!double.TryParse(raw, NumberStyles.Float | NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out var value))
{
throw new ArgumentException($"Invalid value for {flag}: {raw}");
}
return value;
}
static int? ParseNullableIntArg(string[] args, string flag)
{
var raw = GetArgValue(args, flag);
if (raw == null)
{
return null;
}
if (!int.TryParse(raw, NumberStyles.Integer, CultureInfo.InvariantCulture, out var value))
{
throw new ArgumentException($"Invalid value for {flag}: {raw}");
}
return value;
}
static string? GetArgValue(string[] args, string flag)
{
var prefix = $"{flag}=";
foreach (var arg in args)
{
if (arg.StartsWith(prefix, StringComparison.Ordinal))
{
return arg[prefix.Length..];
}
}
return null;
}
static bool HasFlag(string[] args, string flag)
{
return args.Any(arg => string.Equals(arg, flag, StringComparison.Ordinal));
}
static string TimeoutLabel(double timeoutSeconds)
{
if (Math.Abs(timeoutSeconds - Math.Round(timeoutSeconds)) < 1e-9)
{
return ((int)Math.Round(timeoutSeconds)).ToString(CultureInfo.InvariantCulture);
}
return timeoutSeconds.ToString("0.###", CultureInfo.InvariantCulture).Replace(".", "_");
}
static string FormatDuration(double seconds)
{
if (seconds < 60)
{
return $"{seconds:0.0}s";
}
if (seconds < 3600)
{
return $"{seconds / 60:0.0}m ({seconds:0}s)";
}
return $"{seconds / 3600:0.00}h ({seconds:0}s)";
}
static string RepeatString(string value, int count)
{
if (count <= 0)
{
return string.Empty;
}
return string.Concat(Enumerable.Repeat(value, count));
}
/// <summary>
/// Rebuild an input of exactly <paramref name="target"/> chars from a case's
/// base string by repeating then truncating it (dataset inputs are runs of a
/// single repeat unit, so any prefix/extension is still a valid input).
/// </summary>
static string ResizeInput(string baseStr, int target)
{
if (target <= 0 || baseStr.Length == 0)
{
return string.Empty;
}
var reps = (target + baseStr.Length - 1) / baseStr.Length; // ceil
return string.Concat(Enumerable.Repeat(baseStr, reps)).Substring(0, target);
}
/// <summary>
/// One TestCaseRun per (case, swept input size), rebuilding the input and
/// overriding metadata.input_size.
/// </summary>
static List<TestCaseRun> ExpandWithSweep(List<TestCaseRun> cases, int[] sweep)
{
var expanded = new List<TestCaseRun>(cases.Count * sweep.Length);
foreach (var c in cases)
{
foreach (var target in sweep)
{
var input = ResizeInput(c.Input, target);
CaseMetadata? md = c.Metadata == null ? null : new CaseMetadata
{
Group = c.Metadata.Group,
Size = c.Metadata.Size,
AstSize = c.Metadata.AstSize,
AstDepth = c.Metadata.AstDepth,
RegexSize = c.Metadata.RegexSize,
InputSize = input.Length,
};
expanded.Add(new TestCaseRun
{
Id = c.Id,
Pattern = c.Pattern,
Input = input,
Metadata = md,
});
}
}
return expanded;
}
/// <summary>
/// Parse --input-sweep: a comma list of ints, or `none` to disable. Returns
/// null when the flag is absent (caller uses DefaultInputSweep).
/// </summary>
static int[]? ParseInputSweep(string? raw)
{
if (raw == null)
{
return null;
}
if (raw.Trim().Equals("none", StringComparison.OrdinalIgnoreCase))
{
return Array.Empty<int>();
}
return raw
.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
.Select(s => int.Parse(s, CultureInfo.InvariantCulture))
.ToArray();
}
}
class RegexLibrary
{
public string Name { get; set; } = "";
public string Engine { get; set; } = "";
public TimeSpan Timeout { get; set; }
}
class TestCase
{
[JsonPropertyName("id")]
public int Id { get; set; }
[JsonPropertyName("regex")]
public string Regex { get; set; } = "";
[JsonPropertyName("repeat")]
public string Repeat { get; set; } = "";
[JsonPropertyName("description")]
public string Description { get; set; } = "";
}
class TestCaseRun
{
public int Id { get; set; }
public string Pattern { get; set; } = "";
public string Input { get; set; } = "";
public CaseMetadata? Metadata { get; set; }
}
class DatasetCase
{
[JsonPropertyName("id")]
public int Id { get; set; }
[JsonPropertyName("regex")]
public string Regex { get; set; } = "";
[JsonPropertyName("input")]
public string Input { get; set; } = "";
[JsonPropertyName("regex_size")]
public int? RegexSize { get; set; }
[JsonPropertyName("input_size")]
public int? InputSize { get; set; }
[JsonPropertyName("ast_size")]
public long? AstSize { get; set; }
[JsonPropertyName("ast_depth")]
public long? AstDepth { get; set; }
[JsonPropertyName("group")]
public string? Group { get; set; }
[JsonPropertyName("size")]
public string? Size { get; set; }
}
class CaseMetadata
{
[JsonPropertyName("group")]
public string? Group { get; set; }
[JsonPropertyName("size")]
public string? Size { get; set; }
[JsonPropertyName("ast_size")]
public long? AstSize { get; set; }
[JsonPropertyName("ast_depth")]
public long? AstDepth { get; set; }
[JsonPropertyName("regex_size")]
public int? RegexSize { get; set; }
[JsonPropertyName("input_size")]
public int? InputSize { get; set; }
}
class ChildResult
{
[JsonPropertyName("match")]
public bool? Match { get; set; }
[JsonPropertyName("error")]
public string? Error { get; set; }
}
class LibraryResult
{
[JsonPropertyName("library")]
public string Library { get; set; } = "";
[JsonPropertyName("result")]
public bool? Result { get; set; }
[JsonPropertyName("time")]
public double Time { get; set; }
[JsonPropertyName("timed_out")]
public bool TimedOut { get; set; }
}
class SingleTestResult
{
[JsonPropertyName("test_id")]
public int TestId { get; set; }
[JsonPropertyName("pattern")]
public string Pattern { get; set; } = "";
[JsonPropertyName("input")]
public string Input { get; set; } = "";
[JsonPropertyName("library")]
public string Library { get; set; } = "";
[JsonPropertyName("result")]
public LibraryResult Result { get; set; } = new LibraryResult();
[JsonPropertyName("metadata")]
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public CaseMetadata? Metadata { get; set; }
}
class SummaryStat
{
[JsonPropertyName("mean_time")]
public double? MeanTime { get; set; }
[JsonPropertyName("median_time")]
public double? MedianTime { get; set; }
[JsonPropertyName("min_time")]
public double? MinTime { get; set; }
[JsonPropertyName("max_time")]
public double? MaxTime { get; set; }
[JsonPropertyName("timeout_count")]
public int TimeoutCount { get; set; }
[JsonPropertyName("total_count")]
public int TotalCount { get; set; }
}
class Metadata
{
[JsonPropertyName("timestamp")]
public string Timestamp { get; set; } = "";
[JsonPropertyName("total_runs")]
public int TotalRuns { get; set; }
[JsonPropertyName("total_tests")]
public int TotalTests { get; set; }
[JsonPropertyName("total_libraries")]
public int TotalLibraries { get; set; }
[JsonPropertyName("libraries")]
public List<string> Libraries { get; set; } = new List<string>();
}
class ResultsFile
{
[JsonPropertyName("metadata")]
public Metadata Metadata { get; set; } = new Metadata();
[JsonPropertyName("summary_stats")]
public Dictionary<string, SummaryStat> SummaryStats { get; set; } = new Dictionary<string, SummaryStat>();
[JsonPropertyName("results")]
public List<SingleTestResult> Results { get; set; } = new List<SingleTestResult>();
}