-
-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
Copy pathdoctest.zig
1543 lines (1406 loc) · 62.4 KB
/
doctest.zig
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
const builtin = @import("builtin");
const std = @import("std");
const fatal = std.zig.fatal;
const mem = std.mem;
const fs = std.fs;
const process = std.process;
const Allocator = std.mem.Allocator;
const testing = std.testing;
const getExternalExecutor = std.zig.system.getExternalExecutor;
const max_doc_file_size = 10 * 1024 * 1024;
const usage =
\\Usage: doctest [options] -i input -o output
\\
\\ Compiles and possibly runs a code example, capturing output and rendering
\\ it to HTML documentation.
\\
\\Options:
\\ -h, --help Print this help and exit
\\ -i input Source code file path
\\ -o output Where to write output HTML docs to
\\ --zig zig Path to the zig compiler
\\ --zig-lib-dir dir Override the zig compiler library path
\\ --cache-root dir Path to local .zig-cache/
\\
;
pub fn main() !void {
var arena_instance = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena_instance.deinit();
const arena = arena_instance.allocator();
var args_it = try process.argsWithAllocator(arena);
if (!args_it.skip()) fatal("missing argv[0]", .{});
var opt_input: ?[]const u8 = null;
var opt_output: ?[]const u8 = null;
var opt_zig: ?[]const u8 = null;
var opt_zig_lib_dir: ?[]const u8 = null;
var opt_cache_root: ?[]const u8 = null;
while (args_it.next()) |arg| {
if (mem.startsWith(u8, arg, "-")) {
if (mem.eql(u8, arg, "-h") or mem.eql(u8, arg, "--help")) {
try std.io.getStdOut().writeAll(usage);
process.exit(0);
} else if (mem.eql(u8, arg, "-i")) {
opt_input = args_it.next() orelse fatal("expected parameter after -i", .{});
} else if (mem.eql(u8, arg, "-o")) {
opt_output = args_it.next() orelse fatal("expected parameter after -o", .{});
} else if (mem.eql(u8, arg, "--zig")) {
opt_zig = args_it.next() orelse fatal("expected parameter after --zig", .{});
} else if (mem.eql(u8, arg, "--zig-lib-dir")) {
opt_zig_lib_dir = args_it.next() orelse fatal("expected parameter after --zig-lib-dir", .{});
} else if (mem.eql(u8, arg, "--cache-root")) {
opt_cache_root = args_it.next() orelse fatal("expected parameter after --cache-root", .{});
} else {
fatal("unrecognized option: '{s}'", .{arg});
}
} else {
fatal("unexpected positional argument: '{s}'", .{arg});
}
}
const input_path = opt_input orelse fatal("missing input file (-i)", .{});
const output_path = opt_output orelse fatal("missing output file (-o)", .{});
const zig_path = opt_zig orelse fatal("missing zig compiler path (--zig)", .{});
const cache_root = opt_cache_root orelse fatal("missing cache root path (--cache-root)", .{});
const source_bytes = try fs.cwd().readFileAlloc(arena, input_path, std.math.maxInt(u32));
const code = try parseManifest(arena, source_bytes);
const source = stripManifest(source_bytes);
const tmp_dir_path = try std.fmt.allocPrint(arena, "{s}/tmp/{x}", .{
cache_root, std.crypto.random.int(u64),
});
fs.cwd().makePath(tmp_dir_path) catch |err|
fatal("unable to create tmp dir '{s}': {s}", .{ tmp_dir_path, @errorName(err) });
defer fs.cwd().deleteTree(tmp_dir_path) catch |err| std.log.err("unable to delete '{s}': {s}", .{
tmp_dir_path, @errorName(err),
});
var out_file = try fs.cwd().createFile(output_path, .{});
defer out_file.close();
var bw = std.io.bufferedWriter(out_file.writer());
const out = bw.writer();
try printSourceBlock(arena, out, source, fs.path.basename(input_path));
try printOutput(arena, out, code, input_path, zig_path, opt_zig_lib_dir, tmp_dir_path);
try bw.flush();
}
fn printOutput(
arena: Allocator,
out: anytype,
code: Code,
input_path: []const u8,
zig_exe: []const u8,
opt_zig_lib_dir: ?[]const u8,
tmp_dir_path: []const u8,
) !void {
var env_map = try process.getEnvMap(arena);
try env_map.put("CLICOLOR_FORCE", "1");
const host = try std.zig.system.resolveTargetQuery(.{});
const obj_ext = builtin.object_format.fileExt(builtin.cpu.arch);
const print = std.debug.print;
var shell_buffer = std.ArrayList(u8).init(arena);
defer shell_buffer.deinit();
var shell_out = shell_buffer.writer();
const code_name = std.fs.path.stem(input_path);
switch (code.id) {
.exe => |expected_outcome| code_block: {
var build_args = std.ArrayList([]const u8).init(arena);
defer build_args.deinit();
try build_args.appendSlice(&[_][]const u8{
zig_exe, "build-exe",
"--name", code_name,
"--color", "on",
input_path,
});
if (opt_zig_lib_dir) |zig_lib_dir| {
try build_args.appendSlice(&.{ "--zig-lib-dir", zig_lib_dir });
}
try shell_out.print("$ zig build-exe {s}.zig ", .{code_name});
switch (code.mode) {
.Debug => {},
else => {
try build_args.appendSlice(&[_][]const u8{ "-O", @tagName(code.mode) });
try shell_out.print("-O {s} ", .{@tagName(code.mode)});
},
}
for (code.link_objects) |link_object| {
const name_with_ext = try std.fmt.allocPrint(arena, "{s}{s}", .{ link_object, obj_ext });
try build_args.append(name_with_ext);
try shell_out.print("{s} ", .{name_with_ext});
}
if (code.link_libc) {
try build_args.append("-lc");
try shell_out.print("-lc ", .{});
}
if (code.target_str) |triple| {
try build_args.appendSlice(&[_][]const u8{ "-target", triple });
try shell_out.print("-target {s} ", .{triple});
}
if (code.verbose_cimport) {
try build_args.append("--verbose-cimport");
try shell_out.print("--verbose-cimport ", .{});
}
for (code.additional_options) |option| {
try build_args.append(option);
try shell_out.print("{s} ", .{option});
}
try shell_out.print("\n", .{});
if (expected_outcome == .build_fail) {
const result = try process.Child.run(.{
.allocator = arena,
.argv = build_args.items,
.cwd = tmp_dir_path,
.env_map = &env_map,
.max_output_bytes = max_doc_file_size,
});
switch (result.term) {
.Exited => |exit_code| {
if (exit_code == 0) {
print("{s}\nThe following command incorrectly succeeded:\n", .{result.stderr});
dumpArgs(build_args.items);
fatal("example incorrectly compiled", .{});
}
},
else => {
print("{s}\nThe following command crashed:\n", .{result.stderr});
dumpArgs(build_args.items);
fatal("example compile crashed", .{});
},
}
const escaped_stderr = try escapeHtml(arena, result.stderr);
const colored_stderr = try termColor(arena, escaped_stderr);
try shell_out.writeAll(colored_stderr);
break :code_block;
}
const exec_result = run(arena, &env_map, tmp_dir_path, build_args.items) catch
fatal("example failed to compile", .{});
if (code.verbose_cimport) {
const escaped_build_stderr = try escapeHtml(arena, exec_result.stderr);
try shell_out.writeAll(escaped_build_stderr);
}
if (code.target_str) |triple| {
if (mem.startsWith(u8, triple, "wasm32") or
mem.startsWith(u8, triple, "riscv64-linux") or
(mem.startsWith(u8, triple, "x86_64-linux") and
builtin.os.tag != .linux or builtin.cpu.arch != .x86_64))
{
// skip execution
break :code_block;
}
}
const target_query = try std.Target.Query.parse(.{
.arch_os_abi = code.target_str orelse "native",
});
const target = try std.zig.system.resolveTargetQuery(target_query);
const path_to_exe = try std.fmt.allocPrint(arena, "./{s}{s}", .{
code_name, target.exeFileExt(),
});
const run_args = &[_][]const u8{path_to_exe};
var exited_with_signal = false;
const result = if (expected_outcome == .fail) blk: {
const result = try process.Child.run(.{
.allocator = arena,
.argv = run_args,
.env_map = &env_map,
.cwd = tmp_dir_path,
.max_output_bytes = max_doc_file_size,
});
switch (result.term) {
.Exited => |exit_code| {
if (exit_code == 0) {
print("{s}\nThe following command incorrectly succeeded:\n", .{result.stderr});
dumpArgs(run_args);
fatal("example incorrectly compiled", .{});
}
},
.Signal => exited_with_signal = true,
else => {},
}
break :blk result;
} else blk: {
break :blk run(arena, &env_map, tmp_dir_path, run_args) catch
fatal("example crashed", .{});
};
const escaped_stderr = try escapeHtml(arena, result.stderr);
const escaped_stdout = try escapeHtml(arena, result.stdout);
const colored_stderr = try termColor(arena, escaped_stderr);
const colored_stdout = try termColor(arena, escaped_stdout);
try shell_out.print("$ ./{s}\n{s}{s}", .{ code_name, colored_stdout, colored_stderr });
if (exited_with_signal) {
try shell_out.print("(process terminated by signal)", .{});
}
try shell_out.writeAll("\n");
},
.@"test" => {
var test_args = std.ArrayList([]const u8).init(arena);
defer test_args.deinit();
try test_args.appendSlice(&[_][]const u8{
zig_exe, "test", input_path,
});
if (opt_zig_lib_dir) |zig_lib_dir| {
try test_args.appendSlice(&.{ "--zig-lib-dir", zig_lib_dir });
}
try shell_out.print("$ zig test {s}.zig ", .{code_name});
switch (code.mode) {
.Debug => {},
else => {
try test_args.appendSlice(&[_][]const u8{
"-O", @tagName(code.mode),
});
try shell_out.print("-O {s} ", .{@tagName(code.mode)});
},
}
if (code.link_libc) {
try test_args.append("-lc");
try shell_out.print("-lc ", .{});
}
if (code.target_str) |triple| {
try test_args.appendSlice(&[_][]const u8{ "-target", triple });
try shell_out.print("-target {s} ", .{triple});
const target_query = try std.Target.Query.parse(.{
.arch_os_abi = triple,
});
const target = try std.zig.system.resolveTargetQuery(
target_query,
);
switch (getExternalExecutor(host, &target, .{
.link_libc = code.link_libc,
})) {
.native => {},
else => {
try test_args.appendSlice(&[_][]const u8{"--test-no-exec"});
try shell_out.writeAll("--test-no-exec");
},
}
}
const result = run(arena, &env_map, null, test_args.items) catch
fatal("test failed", .{});
const escaped_stderr = try escapeHtml(arena, result.stderr);
const escaped_stdout = try escapeHtml(arena, result.stdout);
try shell_out.print("\n{s}{s}\n", .{ escaped_stderr, escaped_stdout });
},
.test_error => |error_match| {
var test_args = std.ArrayList([]const u8).init(arena);
defer test_args.deinit();
try test_args.appendSlice(&[_][]const u8{
zig_exe, "test",
"--color", "on",
input_path,
});
if (opt_zig_lib_dir) |zig_lib_dir| {
try test_args.appendSlice(&.{ "--zig-lib-dir", zig_lib_dir });
}
try shell_out.print("$ zig test {s}.zig ", .{code_name});
switch (code.mode) {
.Debug => {},
else => {
try test_args.appendSlice(&[_][]const u8{ "-O", @tagName(code.mode) });
try shell_out.print("-O {s} ", .{@tagName(code.mode)});
},
}
if (code.link_libc) {
try test_args.append("-lc");
try shell_out.print("-lc ", .{});
}
const result = try process.Child.run(.{
.allocator = arena,
.argv = test_args.items,
.env_map = &env_map,
.max_output_bytes = max_doc_file_size,
});
switch (result.term) {
.Exited => |exit_code| {
if (exit_code == 0) {
print("{s}\nThe following command incorrectly succeeded:\n", .{result.stderr});
dumpArgs(test_args.items);
fatal("example incorrectly compiled", .{});
}
},
else => {
print("{s}\nThe following command crashed:\n", .{result.stderr});
dumpArgs(test_args.items);
fatal("example compile crashed", .{});
},
}
if (mem.indexOf(u8, result.stderr, error_match) == null) {
print("{s}\nExpected to find '{s}' in stderr\n", .{ result.stderr, error_match });
fatal("example did not have expected compile error", .{});
}
const escaped_stderr = try escapeHtml(arena, result.stderr);
const colored_stderr = try termColor(arena, escaped_stderr);
try shell_out.print("\n{s}\n", .{colored_stderr});
},
.test_safety => |error_match| {
var test_args = std.ArrayList([]const u8).init(arena);
defer test_args.deinit();
try test_args.appendSlice(&[_][]const u8{
zig_exe, "test",
input_path,
});
if (opt_zig_lib_dir) |zig_lib_dir| {
try test_args.appendSlice(&.{ "--zig-lib-dir", zig_lib_dir });
}
var mode_arg: []const u8 = "";
switch (code.mode) {
.Debug => {},
.ReleaseSafe => {
try test_args.append("-OReleaseSafe");
mode_arg = "-OReleaseSafe";
},
.ReleaseFast => {
try test_args.append("-OReleaseFast");
mode_arg = "-OReleaseFast";
},
.ReleaseSmall => {
try test_args.append("-OReleaseSmall");
mode_arg = "-OReleaseSmall";
},
}
const result = try process.Child.run(.{
.allocator = arena,
.argv = test_args.items,
.env_map = &env_map,
.max_output_bytes = max_doc_file_size,
});
switch (result.term) {
.Exited => |exit_code| {
if (exit_code == 0) {
print("{s}\nThe following command incorrectly succeeded:\n", .{result.stderr});
dumpArgs(test_args.items);
fatal("example test incorrectly succeeded", .{});
}
},
else => {
print("{s}\nThe following command crashed:\n", .{result.stderr});
dumpArgs(test_args.items);
fatal("example compile crashed", .{});
},
}
if (mem.indexOf(u8, result.stderr, error_match) == null) {
print("{s}\nExpected to find '{s}' in stderr\n", .{ result.stderr, error_match });
fatal("example did not have expected runtime safety error message", .{});
}
const escaped_stderr = try escapeHtml(arena, result.stderr);
const colored_stderr = try termColor(arena, escaped_stderr);
try shell_out.print("$ zig test {s}.zig {s}\n{s}\n", .{
code_name,
mode_arg,
colored_stderr,
});
},
.obj => |maybe_error_match| {
const name_plus_obj_ext = try std.fmt.allocPrint(arena, "{s}{s}", .{ code_name, obj_ext });
var build_args = std.ArrayList([]const u8).init(arena);
defer build_args.deinit();
try build_args.appendSlice(&[_][]const u8{
zig_exe, "build-obj",
"--color", "on",
"--name", code_name,
input_path,
try std.fmt.allocPrint(arena, "-femit-bin={s}{c}{s}", .{
tmp_dir_path, fs.path.sep, name_plus_obj_ext,
}),
});
if (opt_zig_lib_dir) |zig_lib_dir| {
try build_args.appendSlice(&.{ "--zig-lib-dir", zig_lib_dir });
}
try shell_out.print("$ zig build-obj {s}.zig ", .{code_name});
switch (code.mode) {
.Debug => {},
else => {
try build_args.appendSlice(&[_][]const u8{ "-O", @tagName(code.mode) });
try shell_out.print("-O {s} ", .{@tagName(code.mode)});
},
}
if (code.target_str) |triple| {
try build_args.appendSlice(&[_][]const u8{ "-target", triple });
try shell_out.print("-target {s} ", .{triple});
}
for (code.additional_options) |option| {
try build_args.append(option);
try shell_out.print("{s} ", .{option});
}
if (maybe_error_match) |error_match| {
const result = try process.Child.run(.{
.allocator = arena,
.argv = build_args.items,
.env_map = &env_map,
.max_output_bytes = max_doc_file_size,
});
switch (result.term) {
.Exited => |exit_code| {
if (exit_code == 0) {
print("{s}\nThe following command incorrectly succeeded:\n", .{result.stderr});
dumpArgs(build_args.items);
fatal("example build incorrectly succeeded", .{});
}
},
else => {
print("{s}\nThe following command crashed:\n", .{result.stderr});
dumpArgs(build_args.items);
fatal("example compile crashed", .{});
},
}
if (mem.indexOf(u8, result.stderr, error_match) == null) {
print("{s}\nExpected to find '{s}' in stderr\n", .{ result.stderr, error_match });
fatal("example did not have expected compile error message", .{});
}
const escaped_stderr = try escapeHtml(arena, result.stderr);
const colored_stderr = try termColor(arena, escaped_stderr);
try shell_out.print("\n{s} ", .{colored_stderr});
} else {
_ = run(arena, &env_map, null, build_args.items) catch fatal("example failed to compile", .{});
}
try shell_out.writeAll("\n");
},
.lib => {
const bin_basename = try std.zig.binNameAlloc(arena, .{
.root_name = code_name,
.target = builtin.target,
.output_mode = .Lib,
});
var test_args = std.ArrayList([]const u8).init(arena);
defer test_args.deinit();
try test_args.appendSlice(&[_][]const u8{
zig_exe, "build-lib",
input_path,
try std.fmt.allocPrint(arena, "-femit-bin={s}{s}{s}", .{
tmp_dir_path, fs.path.sep_str, bin_basename,
}),
});
if (opt_zig_lib_dir) |zig_lib_dir| {
try test_args.appendSlice(&.{ "--zig-lib-dir", zig_lib_dir });
}
try shell_out.print("$ zig build-lib {s}.zig ", .{code_name});
switch (code.mode) {
.Debug => {},
else => {
try test_args.appendSlice(&[_][]const u8{ "-O", @tagName(code.mode) });
try shell_out.print("-O {s} ", .{@tagName(code.mode)});
},
}
if (code.target_str) |triple| {
try test_args.appendSlice(&[_][]const u8{ "-target", triple });
try shell_out.print("-target {s} ", .{triple});
}
if (code.link_mode) |link_mode| {
switch (link_mode) {
.static => {
try test_args.append("-static");
try shell_out.print("-static ", .{});
},
.dynamic => {
try test_args.append("-dynamic");
try shell_out.print("-dynamic ", .{});
},
}
}
for (code.additional_options) |option| {
try test_args.append(option);
try shell_out.print("{s} ", .{option});
}
const result = run(arena, &env_map, null, test_args.items) catch fatal("test failed", .{});
const escaped_stderr = try escapeHtml(arena, result.stderr);
const escaped_stdout = try escapeHtml(arena, result.stdout);
try shell_out.print("\n{s}{s}\n", .{ escaped_stderr, escaped_stdout });
},
}
if (!code.just_check_syntax) {
try printShell(out, shell_buffer.items, false);
}
}
fn dumpArgs(args: []const []const u8) void {
for (args) |arg|
std.debug.print("{s} ", .{arg})
else
std.debug.print("\n", .{});
}
fn printSourceBlock(arena: Allocator, out: anytype, source_bytes: []const u8, name: []const u8) !void {
try out.print("<figure><figcaption class=\"{s}-cap\"><cite class=\"file\">{s}</cite></figcaption><pre>", .{
"zig", name,
});
try tokenizeAndPrint(arena, out, source_bytes);
try out.writeAll("</pre></figure>");
}
fn tokenizeAndPrint(arena: Allocator, out: anytype, raw_src: []const u8) !void {
const src_non_terminated = mem.trim(u8, raw_src, " \r\n");
const src = try arena.dupeZ(u8, src_non_terminated);
try out.writeAll("<code>");
var tokenizer = std.zig.Tokenizer.init(src);
var index: usize = 0;
var next_tok_is_fn = false;
while (true) {
const prev_tok_was_fn = next_tok_is_fn;
next_tok_is_fn = false;
const token = tokenizer.next();
if (mem.indexOf(u8, src[index..token.loc.start], "//")) |comment_start_off| {
// render one comment
const comment_start = index + comment_start_off;
const comment_end_off = mem.indexOf(u8, src[comment_start..token.loc.start], "\n");
const comment_end = if (comment_end_off) |o| comment_start + o else token.loc.start;
try writeEscapedLines(out, src[index..comment_start]);
try out.writeAll("<span class=\"tok-comment\">");
try writeEscaped(out, src[comment_start..comment_end]);
try out.writeAll("</span>");
index = comment_end;
tokenizer.index = index;
continue;
}
try writeEscapedLines(out, src[index..token.loc.start]);
switch (token.tag) {
.eof => break,
.keyword_addrspace,
.keyword_align,
.keyword_and,
.keyword_asm,
.keyword_async,
.keyword_await,
.keyword_break,
.keyword_catch,
.keyword_comptime,
.keyword_const,
.keyword_continue,
.keyword_defer,
.keyword_else,
.keyword_enum,
.keyword_errdefer,
.keyword_error,
.keyword_export,
.keyword_extern,
.keyword_for,
.keyword_if,
.keyword_inline,
.keyword_noalias,
.keyword_noinline,
.keyword_nosuspend,
.keyword_opaque,
.keyword_or,
.keyword_orelse,
.keyword_packed,
.keyword_anyframe,
.keyword_pub,
.keyword_resume,
.keyword_return,
.keyword_linksection,
.keyword_callconv,
.keyword_struct,
.keyword_suspend,
.keyword_switch,
.keyword_test,
.keyword_threadlocal,
.keyword_try,
.keyword_union,
.keyword_unreachable,
.keyword_usingnamespace,
.keyword_var,
.keyword_volatile,
.keyword_allowzero,
.keyword_while,
.keyword_anytype,
=> {
try out.writeAll("<span class=\"tok-kw\">");
try writeEscaped(out, src[token.loc.start..token.loc.end]);
try out.writeAll("</span>");
},
.keyword_fn => {
try out.writeAll("<span class=\"tok-kw\">");
try writeEscaped(out, src[token.loc.start..token.loc.end]);
try out.writeAll("</span>");
next_tok_is_fn = true;
},
.string_literal,
.multiline_string_literal_line,
.char_literal,
=> {
try out.writeAll("<span class=\"tok-str\">");
try writeEscaped(out, src[token.loc.start..token.loc.end]);
try out.writeAll("</span>");
},
.builtin => {
try out.writeAll("<span class=\"tok-builtin\">");
try writeEscaped(out, src[token.loc.start..token.loc.end]);
try out.writeAll("</span>");
},
.doc_comment,
.container_doc_comment,
=> {
try out.writeAll("<span class=\"tok-comment\">");
try writeEscaped(out, src[token.loc.start..token.loc.end]);
try out.writeAll("</span>");
},
.identifier => {
const tok_bytes = src[token.loc.start..token.loc.end];
if (mem.eql(u8, tok_bytes, "undefined") or
mem.eql(u8, tok_bytes, "null") or
mem.eql(u8, tok_bytes, "true") or
mem.eql(u8, tok_bytes, "false"))
{
try out.writeAll("<span class=\"tok-null\">");
try writeEscaped(out, tok_bytes);
try out.writeAll("</span>");
} else if (prev_tok_was_fn) {
try out.writeAll("<span class=\"tok-fn\">");
try writeEscaped(out, tok_bytes);
try out.writeAll("</span>");
} else {
const is_int = blk: {
if (src[token.loc.start] != 'i' and src[token.loc.start] != 'u')
break :blk false;
var i = token.loc.start + 1;
if (i == token.loc.end)
break :blk false;
while (i != token.loc.end) : (i += 1) {
if (src[i] < '0' or src[i] > '9')
break :blk false;
}
break :blk true;
};
const isType = std.zig.isPrimitive;
if (is_int or isType(tok_bytes)) {
try out.writeAll("<span class=\"tok-type\">");
try writeEscaped(out, tok_bytes);
try out.writeAll("</span>");
} else {
try writeEscaped(out, tok_bytes);
}
}
},
.number_literal => {
try out.writeAll("<span class=\"tok-number\">");
try writeEscaped(out, src[token.loc.start..token.loc.end]);
try out.writeAll("</span>");
},
.bang,
.pipe,
.pipe_pipe,
.pipe_equal,
.equal,
.equal_equal,
.equal_angle_bracket_right,
.bang_equal,
.l_paren,
.r_paren,
.semicolon,
.percent,
.percent_equal,
.l_brace,
.r_brace,
.l_bracket,
.r_bracket,
.period,
.period_asterisk,
.ellipsis2,
.ellipsis3,
.caret,
.caret_equal,
.plus,
.plus_plus,
.plus_equal,
.plus_percent,
.plus_percent_equal,
.plus_pipe,
.plus_pipe_equal,
.minus,
.minus_equal,
.minus_percent,
.minus_percent_equal,
.minus_pipe,
.minus_pipe_equal,
.asterisk,
.asterisk_equal,
.asterisk_asterisk,
.asterisk_percent,
.asterisk_percent_equal,
.asterisk_pipe,
.asterisk_pipe_equal,
.arrow,
.colon,
.slash,
.slash_equal,
.comma,
.ampersand,
.ampersand_equal,
.question_mark,
.angle_bracket_left,
.angle_bracket_left_equal,
.angle_bracket_angle_bracket_left,
.angle_bracket_angle_bracket_left_equal,
.angle_bracket_angle_bracket_left_pipe,
.angle_bracket_angle_bracket_left_pipe_equal,
.angle_bracket_right,
.angle_bracket_right_equal,
.angle_bracket_angle_bracket_right,
.angle_bracket_angle_bracket_right_equal,
.tilde,
=> try writeEscaped(out, src[token.loc.start..token.loc.end]),
.invalid, .invalid_periodasterisks => fatal("syntax error", .{}),
}
index = token.loc.end;
}
try out.writeAll("</code>");
}
fn writeEscapedLines(out: anytype, text: []const u8) !void {
return writeEscaped(out, text);
}
const Code = struct {
id: Id,
mode: std.builtin.OptimizeMode,
link_objects: []const []const u8,
target_str: ?[]const u8,
link_libc: bool,
link_mode: ?std.builtin.LinkMode,
disable_cache: bool,
verbose_cimport: bool,
just_check_syntax: bool,
additional_options: []const []const u8,
const Id = union(enum) {
@"test",
test_error: []const u8,
test_safety: []const u8,
exe: ExpectedOutcome,
obj: ?[]const u8,
lib,
};
const ExpectedOutcome = enum {
succeed,
fail,
build_fail,
};
};
fn stripManifest(source_bytes: []const u8) []const u8 {
const manifest_start = mem.lastIndexOf(u8, source_bytes, "\n\n// ") orelse
fatal("missing manifest comment", .{});
return source_bytes[0 .. manifest_start + 1];
}
fn parseManifest(arena: Allocator, source_bytes: []const u8) !Code {
const manifest_start = mem.lastIndexOf(u8, source_bytes, "\n\n// ") orelse
fatal("missing manifest comment", .{});
var it = mem.tokenizeScalar(u8, source_bytes[manifest_start..], '\n');
const first_line = skipPrefix(it.next().?);
var just_check_syntax = false;
const id: Code.Id = if (mem.eql(u8, first_line, "syntax")) blk: {
just_check_syntax = true;
break :blk .{ .obj = null };
} else if (mem.eql(u8, first_line, "test"))
.@"test"
else if (mem.eql(u8, first_line, "lib"))
.lib
else if (mem.eql(u8, first_line, "obj"))
.{ .obj = null }
else if (mem.startsWith(u8, first_line, "test_error="))
.{ .test_error = first_line["test_error=".len..] }
else if (mem.startsWith(u8, first_line, "test_safety="))
.{ .test_safety = first_line["test_safety=".len..] }
else if (mem.startsWith(u8, first_line, "exe="))
.{ .exe = std.meta.stringToEnum(Code.ExpectedOutcome, first_line["exe=".len..]) orelse
fatal("bad exe expected outcome in line '{s}'", .{first_line}) }
else if (mem.startsWith(u8, first_line, "obj="))
.{ .obj = first_line["obj=".len..] }
else
fatal("unrecognized manifest id: '{s}'", .{first_line});
var mode: std.builtin.OptimizeMode = .Debug;
var link_mode: ?std.builtin.LinkMode = null;
var link_objects: std.ArrayListUnmanaged([]const u8) = .empty;
var additional_options: std.ArrayListUnmanaged([]const u8) = .empty;
var target_str: ?[]const u8 = null;
var link_libc = false;
var disable_cache = false;
var verbose_cimport = false;
while (it.next()) |prefixed_line| {
const line = skipPrefix(prefixed_line);
if (mem.startsWith(u8, line, "optimize=")) {
mode = std.meta.stringToEnum(std.builtin.OptimizeMode, line["optimize=".len..]) orelse
fatal("bad optimization mode line: '{s}'", .{line});
} else if (mem.startsWith(u8, line, "link_mode=")) {
link_mode = std.meta.stringToEnum(std.builtin.LinkMode, line["link_mode=".len..]) orelse
fatal("bad link mode line: '{s}'", .{line});
} else if (mem.startsWith(u8, line, "link_object=")) {
try link_objects.append(arena, line["link_object=".len..]);
} else if (mem.startsWith(u8, line, "additional_option=")) {
try additional_options.append(arena, line["additional_option=".len..]);
} else if (mem.startsWith(u8, line, "target=")) {
target_str = line["target=".len..];
} else if (mem.eql(u8, line, "link_libc")) {
link_libc = true;
} else if (mem.eql(u8, line, "disable_cache")) {
disable_cache = true;
} else if (mem.eql(u8, line, "verbose_cimport")) {
verbose_cimport = true;
} else {
fatal("unrecognized manifest line: {s}", .{line});
}
}
return .{
.id = id,
.mode = mode,
.additional_options = try additional_options.toOwnedSlice(arena),
.link_objects = try link_objects.toOwnedSlice(arena),
.target_str = target_str,
.link_libc = link_libc,
.link_mode = link_mode,
.disable_cache = disable_cache,
.verbose_cimport = verbose_cimport,
.just_check_syntax = just_check_syntax,
};
}
fn skipPrefix(line: []const u8) []const u8 {
if (!mem.startsWith(u8, line, "// ")) {
fatal("line does not start with '// ': '{s}", .{line});
}
return line[3..];
}
fn escapeHtml(allocator: Allocator, input: []const u8) ![]u8 {
var buf = std.ArrayList(u8).init(allocator);
defer buf.deinit();
const out = buf.writer();
try writeEscaped(out, input);
return try buf.toOwnedSlice();
}
fn writeEscaped(out: anytype, input: []const u8) !void {
for (input) |c| {
try switch (c) {
'&' => out.writeAll("&"),
'<' => out.writeAll("<"),
'>' => out.writeAll(">"),
'"' => out.writeAll("""),
else => out.writeByte(c),
};
}
}
fn termColor(allocator: Allocator, input: []const u8) ![]u8 {
// The SRG sequences generates by the Zig compiler are in the format:
// ESC [ <foreground-color> ; <n> m
// or
// ESC [ <n> m
//
// where
// foreground-color is 31 (red), 32 (green), 36 (cyan)
// n is 0 (reset), 1 (bold), 2 (dim)
//
// Note that 37 (white) is currently not used by the compiler.
//
// See std.debug.TTY.Color.
const supported_sgr_colors = [_]u8{ 31, 32, 36 };
const supported_sgr_numbers = [_]u8{ 0, 1, 2 };
var buf = std.ArrayList(u8).init(allocator);
defer buf.deinit();
var out = buf.writer();
var sgr_param_start_index: usize = undefined;
var sgr_num: u8 = undefined;
var sgr_color: u8 = undefined;
var i: usize = 0;
var state: enum {
start,
escape,
lbracket,
number,
after_number,
arg,
arg_number,
expect_end,
} = .start;
var last_new_line: usize = 0;
var open_span_count: usize = 0;
while (i < input.len) : (i += 1) {
const c = input[i];
switch (state) {
.start => switch (c) {
'\x1b' => state = .escape,
'\n' => {
try out.writeByte(c);
last_new_line = buf.items.len;
},
else => try out.writeByte(c),
},
.escape => switch (c) {
'[' => state = .lbracket,
else => return error.UnsupportedEscape,
},
.lbracket => switch (c) {
'0'...'9' => {
sgr_param_start_index = i;
state = .number;
},