-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbench.zig
More file actions
739 lines (637 loc) · 21.8 KB
/
bench.zig
File metadata and controls
739 lines (637 loc) · 21.8 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
const std = @import("std");
const zpars = @import("zpars");
const bench_io = std.Io.Threaded.global_single_threaded.io();
const Timer = struct {
start_ns: i96,
fn start() Timer {
return .{ .start_ns = std.Io.Clock.awake.now(bench_io).nanoseconds };
}
fn read(self: Timer) u64 {
const now_ns = std.Io.Clock.awake.now(bench_io).nanoseconds;
return @intCast(now_ns - self.start_ns);
}
};
const Abnf = zpars.abnf.Compiler;
const Matcher = zpars.Matcher;
const StatsMatcher = zpars.MatcherWith(.{ .enable_stats = true });
const Scanner = zpars.abnf.Scanner;
const Parser = zpars.abnf.Parser;
const Validator = zpars.Validator;
const Ast = zpars.Ast;
const VmCompiler = zpars.vm.Compiler;
const Vm = zpars.vm.Vm;
const Jit = zpars.vm.Jit;
const Aot = zpars.vm.Aot;
const AotRuntime = zpars.vm.AotRuntime;
const EreScanner = zpars.ere.Scanner;
const EreParser = zpars.ere.Parser;
const PegScanner = zpars.peg.Scanner;
const PegParser = zpars.peg.Parser;
const iterations = 1_000_000;
const Case = struct {
name: []const u8,
grammar: []const u8,
rule: []const u8,
input: []const u8,
};
const cases = [_]Case{
.{
.name = "literal",
.grammar = "greeting = \"hello\"",
.rule = "greeting",
.input = "Hello world",
},
.{
.name = "alternation",
.grammar = "bit = \"0\" / \"1\"",
.rule = "bit",
.input = "1",
},
.{
.name = "repetition",
.grammar = "digits = 1*DIGIT",
.rule = "digits",
.input = "1234567890abcdef",
},
.{
.name = "multi-rule",
.grammar =
\\number = 1*DIGIT
\\pair = number "," number
,
.rule = "pair",
.input = "42,7!",
},
.{
.name = "HTTP version",
.grammar =
\\version = "HTTP/" 1*DIGIT "." 1*DIGIT
,
.rule = "version",
.input = "HTTP/1.1 OK",
},
};
fn ComptimeParser(comptime idx: usize) type {
return Abnf.Compile(cases[idx].grammar, cases[idx].rule);
}
fn benchComptime(comptime idx: usize) u64 {
const P = ComptimeParser(idx);
var input: []const u8 = cases[idx].input;
std.mem.doNotOptimizeAway(&input);
var timer = Timer.start();
for (0..iterations) |_| {
const r = P.parse(input);
std.mem.doNotOptimizeAway(&r);
}
return timer.read();
}
fn benchRuntime(comptime idx: usize, matcher: *Matcher) u64 {
var input: []const u8 = cases[idx].input;
std.mem.doNotOptimizeAway(&input);
var timer = Timer.start();
for (0..iterations) |_| {
const r = matcher.match(cases[idx].rule, input);
std.mem.doNotOptimizeAway(&r);
}
return timer.read();
}
// VM benchmark cases using ERE patterns.
// These exercise all three optimization passes:
// - string fusion (consecutive chars)
// - optional char fusion (e?)
// - charset-to-char (single-char class)
const VmCase = struct {
name: []const u8,
pattern: []const u8,
input: []const u8,
};
const vm_cases = [_]VmCase{
.{
// string fusion: "hello" -> 5 chars fused into 1 string instruction
.name = "string fusion",
.pattern = "hello",
.input = "hello",
},
.{
// optional char: a?b -> optional_char + char
.name = "optional char",
.pattern = "a?b",
.input = "ab",
},
.{
// charset to char: [a] treated as char
.name = "charset->char",
.pattern = "[a]+",
.input = "aaaaaaaaaa",
},
.{
// combined: literal prefix + optional + class
.name = "combined opts",
.pattern = "HTTP/[0-9].[0-9]",
.input = "HTTP/1.1",
},
.{
// alternation with string fusion on both branches
.name = "alt + strings",
.pattern = "hello|world",
.input = "world",
},
.{
// longer string match to amplify fusion benefit
.name = "long literal",
.pattern = "abcdefghijklmnop",
.input = "abcdefghijklmnop",
},
.{
// common prefix factoring: "https|http" shares "http" prefix
.name = "prefix factor",
.pattern = "https|http",
.input = "https",
},
.{
// common prefix with both suffixes non-empty
.name = "prefix both",
.pattern = "httpAB|httpCD",
.input = "httpCD",
},
.{
// repetition over charset (no fusion, baseline)
.name = "charset repeat",
.pattern = "[a-z]+",
.input = "thequickbrownfox",
},
};
fn compileEre(source: []const u8, optimize: bool) VmCompiler {
var scanner = EreScanner.init(source);
const tokens = scanner.scanTokens();
var parser = EreParser.init(tokens, source);
const rules = parser.parse() catch return VmCompiler{};
return VmCompiler.compileOpts(rules, .{ .optimize = optimize });
}
fn benchVm(compiler: *const VmCompiler, input: []const u8) u64 {
var inp: []const u8 = input;
std.mem.doNotOptimizeAway(&inp);
var timer = Timer.start();
for (0..iterations) |_| {
var vm = Vm.init(compiler.getCode(), compiler.getCharsets(), compiler.getStringData(), inp);
const r = vm.execute() catch unreachable;
std.mem.doNotOptimizeAway(&r);
}
return timer.read();
}
fn benchJit(compiler: *const VmCompiler, input: []const u8) u64 {
var inp: []const u8 = input;
std.mem.doNotOptimizeAway(&inp);
var jit = Jit.init(compiler.getCode(), compiler.getCharsets(), compiler.getStringData(), inp) catch unreachable;
defer jit.deinit();
var timer = Timer.start();
for (0..iterations) |_| {
const r = jit.execute();
std.mem.doNotOptimizeAway(&r);
}
return timer.read();
}
fn benchAot(allocator: std.mem.Allocator, compiler: *const VmCompiler, input: []const u8) u64 {
var inp: []const u8 = input;
std.mem.doNotOptimizeAway(&inp);
var blob = Aot.compileToBlob(
allocator,
compiler.getCode(),
compiler.getCharsets(),
compiler.getStringData(),
compiler.getCaptureCount(),
) catch unreachable;
defer Aot.freeBlob(allocator, &blob);
// Serialize and deserialize to simulate loading from file.
const data = Aot.serializeBlob(allocator, blob) catch unreachable;
defer allocator.free(data);
var blob2 = Aot.deserializeBlob(allocator, data) catch unreachable;
defer Aot.freeBlob(allocator, &blob2);
var engine = AotRuntime.Engine.init(blob2) catch unreachable;
defer engine.deinit();
var timer = Timer.start();
for (0..iterations) |_| {
const r = engine.execute(inp);
std.mem.doNotOptimizeAway(&r);
}
return timer.read();
}
pub fn main(init: std.process.Init) !void {
const io = init.io;
const gpa_allocator = init.gpa;
var stdout_buffer: [4096]u8 = undefined;
var stdout_writer = std.Io.File.stdout().writer(io, &stdout_buffer);
const stdout = &stdout_writer.interface;
try stdout.print("\n Comptime vs Runtime (tree-walker)\n", .{});
try stdout.print(" {s:<16} {s:>14} {s:>14} {s:>10}\n", .{
"case", "comptime", "runtime", "ratio",
});
try stdout.print(" {s:-<16} {s:->14} {s:->14} {s:->10}\n", .{
"", "", "", "",
});
inline for (0..cases.len) |idx| {
// Build the runtime matcher once (not timed).
var arena = std.heap.ArenaAllocator.init(gpa_allocator);
defer arena.deinit();
var matcher = try buildMatcher(arena.allocator(), idx);
const ct_ns = benchComptime(idx);
const rt_ns = benchRuntime(idx, &matcher);
const ct_per_op = ct_ns / iterations;
const rt_per_op = rt_ns / iterations;
const ratio: f64 = if (ct_per_op > 0)
@as(f64, @floatFromInt(rt_per_op)) / @as(f64, @floatFromInt(ct_per_op))
else
0;
try stdout.print(" {s:<16} {d:>11} ns {d:>11} ns {d:>9.1}x\n", .{
cases[idx].name,
ct_per_op,
rt_per_op,
ratio,
});
}
try stdout.print("\n ({d} iterations per case)\n", .{iterations});
try stdout.print("\n VM optimized vs unoptimized\n", .{});
try stdout.print(" {s:<16} {s:>14} {s:>14} {s:>10} {s:>8} {s:>8}\n", .{
"case", "optimized", "unoptimized", "speedup", "opt #", "unopt #",
});
try stdout.print(" {s:-<16} {s:->14} {s:->14} {s:->10} {s:->8} {s:->8}\n", .{
"", "", "", "", "", "",
});
for (vm_cases) |case| {
const opt = compileEre(case.pattern, true);
const unopt = compileEre(case.pattern, false);
const opt_ns = benchVm(&opt, case.input);
const unopt_ns = benchVm(&unopt, case.input);
const opt_per_op = opt_ns / iterations;
const unopt_per_op = unopt_ns / iterations;
const speedup: f64 = if (opt_per_op > 0)
@as(f64, @floatFromInt(unopt_per_op)) / @as(f64, @floatFromInt(opt_per_op))
else
0;
try stdout.print(" {s:<16} {d:>11} ns {d:>11} ns {d:>9.2}x {d:>8} {d:>8}\n", .{
case.name,
opt_per_op,
unopt_per_op,
speedup,
opt.code_len,
unopt.code_len,
});
}
try stdout.print("\n VM interpreter vs JIT\n", .{});
try stdout.print(" {s:<16} {s:>14} {s:>14} {s:>10}\n", .{
"case", "interpreter", "jit", "speedup",
});
try stdout.print(" {s:-<16} {s:->14} {s:->14} {s:->10}\n", .{
"", "", "", "",
});
for (vm_cases) |case| {
const comp = compileEre(case.pattern, true);
const vm_ns = benchVm(&comp, case.input);
const jit_ns = benchJit(&comp, case.input);
const vm_per_op = vm_ns / iterations;
const jit_per_op = jit_ns / iterations;
const speedup: f64 = if (jit_per_op > 0)
@as(f64, @floatFromInt(vm_per_op)) / @as(f64, @floatFromInt(jit_per_op))
else
0;
try stdout.print(" {s:<16} {d:>11} ns {d:>11} ns {d:>9.2}x\n", .{
case.name,
vm_per_op,
jit_per_op,
speedup,
});
}
try stdout.print("\n JIT vs AOT (pre-compiled blob)\n", .{});
try stdout.print(" {s:<16} {s:>14} {s:>14} {s:>10}\n", .{
"case", "jit", "aot", "ratio",
});
try stdout.print(" {s:-<16} {s:->14} {s:->14} {s:->10}\n", .{
"", "", "", "",
});
for (vm_cases) |case| {
const comp = compileEre(case.pattern, true);
const jit_ns = benchJit(&comp, case.input);
const aot_ns = benchAot(gpa_allocator, &comp, case.input);
const jit_per_op = jit_ns / iterations;
const aot_per_op = aot_ns / iterations;
const ratio: f64 = if (jit_per_op > 0)
@as(f64, @floatFromInt(aot_per_op)) / @as(f64, @floatFromInt(jit_per_op))
else
0;
try stdout.print(" {s:<16} {d:>11} ns {d:>11} ns {d:>9.2}x\n", .{
case.name,
jit_per_op,
aot_per_op,
ratio,
});
}
try stdout.print("\n ({d} iterations per case)\n\n", .{iterations});
try stdout.print(" Packrat VM (plain vs memoized)\n", .{});
try stdout.print(" {s:<20} {s:>14} {s:>14} {s:>10}\n", .{
"case", "plain", "packrat", "speedup",
});
try stdout.print(" {s:-<20} {s:->14} {s:->14} {s:->10}\n", .{
"", "", "", "",
});
for (packrat_cases) |case| {
const memo_comp = compilePeg(case.grammar, .{ .memoize = true });
const memo_ns = benchVmPackrat(gpa_allocator, &memo_comp, case.input);
const memo_per = memo_ns / iterations;
if (case.left_recursive) {
try stdout.print(" {s:<20} {s:>14} {d:>11} ns {s:>10}\n", .{
case.name,
"(LR: n/a)",
memo_per,
"-",
});
continue;
}
const plain_comp = compilePeg(case.grammar, .{ .memoize = false });
const plain_ns = benchVmPlain(&plain_comp, case.input);
const plain_per = plain_ns / iterations;
const speedup: f64 = if (memo_per > 0)
@as(f64, @floatFromInt(plain_per)) / @as(f64, @floatFromInt(memo_per))
else
0;
try stdout.print(" {s:<20} {d:>11} ns {d:>11} ns {d:>9.2}x\n", .{
case.name,
plain_per,
memo_per,
speedup,
});
}
try stdout.print("\n ({d} iterations per case)\n\n", .{iterations});
try stdout.print(" Matcher: plain vs packrat (with stats)\n", .{});
try printStatsHeader(stdout);
for (matcher_packrat_cases) |case| {
var m_arena = std.heap.ArenaAllocator.init(gpa_allocator);
defer m_arena.deinit();
var sm = buildStatsMatcher(m_arena.allocator(), case.grammar) catch continue;
const memo_ns = benchMatcherPackrat(gpa_allocator, &sm, case.rule, case.input);
const memo_per = memo_ns / iterations;
// Run one more packrat to capture stats (bench loop overwrites each iteration).
_ = sm.matchPackrat(m_arena.allocator(), case.rule, case.input) catch {};
const stats = sm.getStats();
if (case.left_recursive) {
try printStatsRow(stdout, case.name, null, memo_per, stats);
continue;
}
const plain_ns = benchMatcherPlain(&sm, case.rule, case.input);
const plain_per = plain_ns / iterations;
// Re-run packrat once more to get stats (plain match resets them).
_ = sm.matchPackrat(m_arena.allocator(), case.rule, case.input) catch {};
const final_stats = sm.getStats();
try printStatsRow(stdout, case.name, plain_per, memo_per, final_stats);
}
try stdout.print("\n ({d} iterations per case)\n\n", .{iterations});
try stdout.flush();
}
const PackratCase = struct {
name: []const u8,
grammar: []const u8,
input: []const u8,
/// Plain-VM cannot run left-recursive grammars (call-stack blows
/// up), so benchmark packrat in isolation.
left_recursive: bool = false,
};
const packrat_cases = [_]PackratCase{
.{
// Redundant E descent: backtracks from alt 1 to alt 2 but E
// has already been evaluated once at position 0.
.name = "redundant E",
.grammar = "S <- E \"!\" / E \"?\"\nE <- \"a\" \"b\" \"c\" \"d\"",
.input = "abcd?",
},
.{
// Same pattern, failure path: both branches must consult E.
.name = "failure memo",
.grammar = "S <- E \"x\" / E \"y\"\nE <- \"a\" \"b\" \"c\"",
.input = "abqy",
},
.{
// Direct left recursion via Warth's seed-growing.
.name = "left-rec arith",
.grammar = "E <- E \"+\" N / N\nN <- [0-9]+",
.input = "1+2+3+4+5+6+7+8+9+0",
.left_recursive = true,
},
.{
// Indirect LR through two rules (A -> B -> A "x" / "y").
.name = "indirect LR",
.grammar = "A <- B\nB <- A \"x\" / \"y\"",
.input = "yxxxxxxxxx",
.left_recursive = true,
},
.{
// A baseline non-pathological grammar where packrat should
// add pure overhead (no redundant re-entries).
.name = "baseline (no LR)",
.grammar = "E <- T (\"+\" T)*\nT <- F (\"*\" F)*\nF <- \"(\" E \")\" / [0-9]+",
.input = "1+2*3+4*5+6",
},
};
fn compilePeg(source: []const u8, opts: VmCompiler.Options) VmCompiler {
var scanner = PegScanner.init(source);
const tokens = scanner.scanTokens();
var parser = PegParser.init(tokens, source);
const rules = parser.parse() catch return VmCompiler{};
return VmCompiler.compileOpts(rules, opts);
}
fn benchVmPlain(compiler: *const VmCompiler, input: []const u8) u64 {
var inp: []const u8 = input;
std.mem.doNotOptimizeAway(&inp);
var timer = Timer.start();
for (0..iterations) |_| {
var vm = Vm.init(compiler.getCode(), compiler.getCharsets(), compiler.getStringData(), inp);
const r = vm.execute() catch unreachable;
std.mem.doNotOptimizeAway(&r);
}
return timer.read();
}
fn benchVmPackrat(base_allocator: std.mem.Allocator, compiler: *const VmCompiler, input: []const u8) u64 {
var inp: []const u8 = input;
std.mem.doNotOptimizeAway(&inp);
var arena = std.heap.ArenaAllocator.init(base_allocator);
defer arena.deinit();
const arena_allocator = arena.allocator();
var timer = Timer.start();
for (0..iterations) |_| {
var vm = Vm.initPackrat(
arena_allocator,
compiler.getCode(),
compiler.getCharsets(),
compiler.getStringData(),
compiler.getMemoRuleCount(),
inp,
) catch unreachable;
const r = vm.execute() catch unreachable;
std.mem.doNotOptimizeAway(&r);
_ = arena.reset(.retain_capacity);
}
return timer.read();
}
const MatcherPackratCase = struct {
name: []const u8,
grammar: []const u8,
rule: []const u8,
input: []const u8,
left_recursive: bool = false,
};
const matcher_packrat_cases = [_]MatcherPackratCase{
.{
.name = "redundant E",
.grammar =
\\s = (e "!") / (e "?")
\\e = "a" "b" "c" "d"
,
.rule = "s",
.input = "abcd?",
},
.{
.name = "failure memo",
.grammar =
\\s = (e "x") / (e "y")
\\e = "a" "b" "c"
,
.rule = "s",
.input = "abqy",
},
.{
.name = "left-rec arith",
.grammar =
\\expr = expr "+" 1*DIGIT / 1*DIGIT
,
.rule = "expr",
.input = "1+2+3+4+5+6+7+8+9+0",
.left_recursive = true,
},
.{
.name = "indirect LR",
.grammar =
\\a = b
\\b = a "x" / "y"
,
.rule = "a",
.input = "yxxxxxxxxx",
.left_recursive = true,
},
.{
.name = "multi-rule",
.grammar =
\\number = 1*DIGIT
\\pair = number "," number
,
.rule = "pair",
.input = "42,7!",
},
.{
// Deep backtracking: `s` tries N alternatives that all start
// with `w` but differ in suffix. Each failed alternative
// re-enters `w` at position 0 -- packrat caches after the
// first evaluation so the remaining attempts are table hits.
.name = "deep backtrack",
.grammar =
\\s = (w "A") / (w "B") / (w "C") / (w "D") / (w "E") / (w "F") / (w "G") / (w "!")
\\w = 1*ALPHA
,
.rule = "s",
.input = "hello!",
},
.{
// Cascading alternatives: three rules each with two branches.
// Failing the first branch of `a` backtracks through `b` and
// `c`, then the second branch of `a` re-uses them at the
// same positions.
.name = "cascade alt",
.grammar =
\\a = (b "X") / (b "?")
\\b = (c "Y") / (c 1*ALPHA)
\\c = 1*DIGIT "-" 1*DIGIT
,
.rule = "a",
.input = "12-34hello?",
},
};
fn benchMatcherPlain(matcher: *StatsMatcher, rule: []const u8, input: []const u8) u64 {
var inp: []const u8 = input;
std.mem.doNotOptimizeAway(&inp);
var timer = Timer.start();
for (0..iterations) |_| {
const r = matcher.match(rule, inp);
std.mem.doNotOptimizeAway(&r);
}
return timer.read();
}
fn benchMatcherPackrat(
base_allocator: std.mem.Allocator,
matcher: *StatsMatcher,
rule: []const u8,
input: []const u8,
) u64 {
var inp: []const u8 = input;
std.mem.doNotOptimizeAway(&inp);
var arena = std.heap.ArenaAllocator.init(base_allocator);
defer arena.deinit();
const arena_alloc = arena.allocator();
var timer = Timer.start();
for (0..iterations) |_| {
const r = matcher.matchPackrat(arena_alloc, rule, inp) catch unreachable;
std.mem.doNotOptimizeAway(&r);
_ = arena.reset(.retain_capacity);
}
return timer.read();
}
fn buildStatsMatcher(allocator: std.mem.Allocator, grammar: []const u8) !StatsMatcher {
var scanner = Scanner.init(grammar);
const tokens = scanner.scanTokens();
var parser = Parser.init(tokens, grammar);
const rules = try parser.parse();
var validator = Validator.init(allocator, rules);
const merged = try validator.validate();
return try StatsMatcher.init(allocator, merged);
}
fn printStatsHeader(stdout: anytype) !void {
try stdout.print(" {s:<16} {s:>11} {s:>11} {s:>8} {s:>8} {s:>8} {s:>5} {s:>8}\n", .{
"case", "plain", "packrat", "speedup", "hits", "misses", "h/m%", "depth",
});
try stdout.print(" {s:-<16} {s:->11} {s:->11} {s:->8} {s:->8} {s:->8} {s:->5} {s:->8}\n", .{
"", "", "", "", "", "", "", "",
});
}
fn printStatsRow(
stdout: anytype,
name: []const u8,
plain_per: ?u64,
memo_per: u64,
stats: StatsMatcher.Stats,
) !void {
const total = stats.memo_hits + stats.memo_misses;
const hit_pct: f64 = if (total > 0)
@as(f64, @floatFromInt(stats.memo_hits)) / @as(f64, @floatFromInt(total)) * 100
else
0;
if (plain_per) |pp| {
const speedup: f64 = if (memo_per > 0)
@as(f64, @floatFromInt(pp)) / @as(f64, @floatFromInt(memo_per))
else
0;
try stdout.print(" {s:<16} {d:>8} ns {d:>8} ns {d:>7.2}x {d:>8} {d:>8} {d:>4.0}% {d:>8}\n", .{
name, pp, memo_per, speedup,
stats.memo_hits, stats.memo_misses, hit_pct, stats.max_depth_reached,
});
} else {
try stdout.print(" {s:<16} {s:>11} {d:>8} ns {s:>8} {d:>8} {d:>8} {d:>4.0}% {d:>8}\n", .{
name, "(LR: n/a)", memo_per, "-",
stats.memo_hits, stats.memo_misses, hit_pct, stats.max_depth_reached,
});
}
}
fn buildMatcher(allocator: std.mem.Allocator, comptime idx: usize) !Matcher {
var scanner = Scanner.init(cases[idx].grammar);
const tokens = scanner.scanTokens();
var parser = Parser.init(tokens, cases[idx].grammar);
const rules = try parser.parse();
var validator = Validator.init(allocator, rules);
const merged = try validator.validate();
return try Matcher.init(allocator, merged);
}