-
-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
Copy pathAutodoc.zig
5135 lines (4626 loc) · 196 KB
/
Autodoc.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 build_options = @import("build_options");
const Ast = std.zig.Ast;
const Autodoc = @This();
const Compilation = @import("Compilation.zig");
const CompilationModule = @import("Module.zig");
const File = CompilationModule.File;
const Module = @import("Package.zig");
const Tokenizer = std.zig.Tokenizer;
const InternPool = @import("InternPool.zig");
const Zir = @import("Zir.zig");
const Ref = Zir.Inst.Ref;
const log = std.log.scoped(.autodoc);
const renderer = @import("autodoc/render_source.zig");
comp_module: *CompilationModule,
doc_location: Compilation.EmitLoc,
arena: std.mem.Allocator,
// The goal of autodoc is to fill up these arrays
// that will then be serialized as JSON and consumed
// by the JS frontend.
modules: std.AutoArrayHashMapUnmanaged(*Module, DocData.DocModule) = .{},
files: std.AutoArrayHashMapUnmanaged(*File, usize) = .{},
calls: std.ArrayListUnmanaged(DocData.Call) = .{},
types: std.ArrayListUnmanaged(DocData.Type) = .{},
decls: std.ArrayListUnmanaged(DocData.Decl) = .{},
exprs: std.ArrayListUnmanaged(DocData.Expr) = .{},
ast_nodes: std.ArrayListUnmanaged(DocData.AstNode) = .{},
comptime_exprs: std.ArrayListUnmanaged(DocData.ComptimeExpr) = .{},
guide_sections: std.ArrayListUnmanaged(Section) = .{},
// These fields hold temporary state of the analysis process
// and are mainly used by the decl path resolving algorithm.
pending_ref_paths: std.AutoHashMapUnmanaged(
*DocData.Expr, // pointer to declpath tail end (ie `&decl_path[decl_path.len - 1]`)
std.ArrayListUnmanaged(RefPathResumeInfo),
) = .{},
ref_paths_pending_on_decls: std.AutoHashMapUnmanaged(
*Scope.DeclStatus,
std.ArrayListUnmanaged(RefPathResumeInfo),
) = .{},
ref_paths_pending_on_types: std.AutoHashMapUnmanaged(
usize,
std.ArrayListUnmanaged(RefPathResumeInfo),
) = .{},
const RefPathResumeInfo = struct {
file: *File,
ref_path: []DocData.Expr,
};
/// Used to accumulate src_node offsets.
/// In ZIR, all ast node indices are relative to the parent decl.
/// More concretely, `union_decl`, `struct_decl`, `enum_decl` and `opaque_decl`
/// and the value of each of their decls participate in the relative offset
/// counting, and nothing else.
/// We keep track of the line and byte values for these instructions in order
/// to avoid tokenizing every file (on new lines) from the start every time.
const SrcLocInfo = struct {
bytes: u32 = 0,
line: usize = 0,
src_node: u32 = 0,
};
const Section = struct {
name: []const u8 = "", // empty string is the default section
guides: std.ArrayListUnmanaged(Guide) = .{},
const Guide = struct {
name: []const u8,
body: []const u8,
};
};
var arena_allocator: std.heap.ArenaAllocator = undefined;
pub fn init(m: *CompilationModule, doc_location: Compilation.EmitLoc) Autodoc {
arena_allocator = std.heap.ArenaAllocator.init(m.gpa);
return .{
.comp_module = m,
.doc_location = doc_location,
.arena = arena_allocator.allocator(),
};
}
pub fn deinit(_: *Autodoc) void {
arena_allocator.deinit();
}
/// The entry point of the Autodoc generation process.
pub fn generateZirData(self: *Autodoc) !void {
if (self.doc_location.directory) |dir| {
if (dir.path) |path| {
log.debug("path: {s}", .{path});
}
}
const root_src_dir = self.comp_module.main_pkg.root_src_directory;
const root_src_path = self.comp_module.main_pkg.root_src_path;
const joined_src_path = try root_src_dir.join(self.arena, &.{root_src_path});
defer self.arena.free(joined_src_path);
const abs_root_src_path = try std.fs.path.resolve(self.arena, &.{ ".", joined_src_path });
defer self.arena.free(abs_root_src_path);
const file = self.comp_module.import_table.get(abs_root_src_path).?; // file is expected to be present in the import table
// Append all the types in Zir.Inst.Ref.
{
comptime std.debug.assert(@intFromEnum(InternPool.Index.first_type) == 0);
var i: u32 = 0;
while (i <= @intFromEnum(InternPool.Index.last_type)) : (i += 1) {
const ip_index = @as(InternPool.Index, @enumFromInt(i));
var tmpbuf = std.ArrayList(u8).init(self.arena);
if (ip_index == .generic_poison_type) {
// Not a real type, doesn't have a normal name
try tmpbuf.writer().writeAll("(generic poison)");
} else {
try ip_index.toType().fmt(self.comp_module).format("", .{}, tmpbuf.writer());
}
try self.types.append(
self.arena,
switch (ip_index) {
.u0_type,
.i0_type,
.u1_type,
.u8_type,
.i8_type,
.u16_type,
.i16_type,
.u29_type,
.u32_type,
.i32_type,
.u64_type,
.i64_type,
.u80_type,
.u128_type,
.i128_type,
.usize_type,
.isize_type,
.c_char_type,
.c_short_type,
.c_ushort_type,
.c_int_type,
.c_uint_type,
.c_long_type,
.c_ulong_type,
.c_longlong_type,
.c_ulonglong_type,
=> .{
.Int = .{ .name = try tmpbuf.toOwnedSlice() },
},
.f16_type,
.f32_type,
.f64_type,
.f80_type,
.f128_type,
.c_longdouble_type,
=> .{
.Float = .{ .name = try tmpbuf.toOwnedSlice() },
},
.comptime_int_type => .{
.ComptimeInt = .{ .name = try tmpbuf.toOwnedSlice() },
},
.comptime_float_type => .{
.ComptimeFloat = .{ .name = try tmpbuf.toOwnedSlice() },
},
.anyopaque_type => .{
.ComptimeExpr = .{ .name = try tmpbuf.toOwnedSlice() },
},
.bool_type => .{
.Bool = .{ .name = try tmpbuf.toOwnedSlice() },
},
.noreturn_type => .{
.NoReturn = .{ .name = try tmpbuf.toOwnedSlice() },
},
.void_type => .{
.Void = .{ .name = try tmpbuf.toOwnedSlice() },
},
.type_info_type => .{
.ComptimeExpr = .{ .name = try tmpbuf.toOwnedSlice() },
},
.type_type => .{
.Type = .{ .name = try tmpbuf.toOwnedSlice() },
},
.anyerror_type => .{
.ErrorSet = .{ .name = try tmpbuf.toOwnedSlice() },
},
// should be different types but if we don't analyze std we don't get the ast nodes etc.
// since they're defined in std.builtin
.calling_convention_type,
.atomic_order_type,
.atomic_rmw_op_type,
.address_space_type,
.float_mode_type,
.reduce_op_type,
.call_modifier_type,
.prefetch_options_type,
.export_options_type,
.extern_options_type,
=> .{
.Type = .{ .name = try tmpbuf.toOwnedSlice() },
},
.manyptr_u8_type => .{
.Pointer = .{
.size = .Many,
.child = .{ .type = @intFromEnum(InternPool.Index.u8_type) },
.is_mutable = true,
},
},
.manyptr_const_u8_type => .{
.Pointer = .{
.size = .Many,
.child = .{ .type = @intFromEnum(InternPool.Index.u8_type) },
},
},
.manyptr_const_u8_sentinel_0_type => .{
.Pointer = .{
.size = .Many,
.child = .{ .type = @intFromEnum(InternPool.Index.u8_type) },
.sentinel = .{ .int = .{ .value = 0 } },
},
},
.single_const_pointer_to_comptime_int_type => .{
.Pointer = .{
.size = .One,
.child = .{ .type = @intFromEnum(InternPool.Index.comptime_int_type) },
},
},
.slice_const_u8_type => .{
.Pointer = .{
.size = .Slice,
.child = .{ .type = @intFromEnum(InternPool.Index.u8_type) },
},
},
.slice_const_u8_sentinel_0_type => .{
.Pointer = .{
.size = .Slice,
.child = .{ .type = @intFromEnum(InternPool.Index.u8_type) },
.sentinel = .{ .int = .{ .value = 0 } },
},
},
// Not fully correct
// since it actually has no src or line_number
.empty_struct_type => .{
.Struct = .{
.name = "",
.src = 0,
.is_tuple = false,
.line_number = 0,
.parent_container = null,
.layout = null,
},
},
.anyerror_void_error_union_type => .{
.ErrorUnion = .{
.lhs = .{ .type = @intFromEnum(InternPool.Index.anyerror_type) },
.rhs = .{ .type = @intFromEnum(InternPool.Index.void_type) },
},
},
.anyframe_type => .{
.AnyFrame = .{ .name = try tmpbuf.toOwnedSlice() },
},
.enum_literal_type => .{
.EnumLiteral = .{ .name = try tmpbuf.toOwnedSlice() },
},
.undefined_type => .{
.Undefined = .{ .name = try tmpbuf.toOwnedSlice() },
},
.null_type => .{
.Null = .{ .name = try tmpbuf.toOwnedSlice() },
},
.optional_noreturn_type => .{
.Optional = .{
.name = try tmpbuf.toOwnedSlice(),
.child = .{ .type = @intFromEnum(InternPool.Index.noreturn_type) },
},
},
// Poison and special tag
.generic_poison_type,
.var_args_param_type,
=> .{
.Type = .{ .name = try tmpbuf.toOwnedSlice() },
},
// We want to catch new types added to InternPool.Index
else => unreachable,
},
);
}
}
const rootName = blk: {
const rootName = std.fs.path.basename(self.comp_module.main_pkg.root_src_path);
break :blk rootName[0 .. rootName.len - 4];
};
const main_type_index = self.types.items.len;
{
try self.modules.put(self.arena, self.comp_module.main_pkg, .{
.name = rootName,
.main = main_type_index,
.table = .{},
});
try self.modules.entries.items(.value)[0].table.put(
self.arena,
self.comp_module.main_pkg,
.{
.name = rootName,
.value = 0,
},
);
}
var root_scope = Scope{
.parent = null,
.enclosing_type = null,
};
const tldoc_comment = try self.getTLDocComment(file);
const cleaned_tldoc_comment = try self.findGuidePaths(file, tldoc_comment);
defer self.arena.free(cleaned_tldoc_comment);
try self.ast_nodes.append(self.arena, .{
.name = "(root)",
.docs = cleaned_tldoc_comment,
});
try self.files.put(self.arena, file, main_type_index);
_ = try self.walkInstruction(file, &root_scope, .{}, Zir.main_struct_inst, false);
if (self.ref_paths_pending_on_decls.count() > 0) {
@panic("some decl paths were never fully analized (pending on decls)");
}
if (self.ref_paths_pending_on_types.count() > 0) {
@panic("some decl paths were never fully analized (pending on types)");
}
if (self.pending_ref_paths.count() > 0) {
@panic("some decl paths were never fully analized");
}
var data = DocData{
.params = .{},
.modules = self.modules,
.files = self.files,
.calls = self.calls.items,
.types = self.types.items,
.decls = self.decls.items,
.exprs = self.exprs.items,
.astNodes = self.ast_nodes.items,
.comptimeExprs = self.comptime_exprs.items,
.guide_sections = self.guide_sections,
};
const base_dir = self.doc_location.directory orelse
self.comp_module.zig_cache_artifact_directory;
base_dir.handle.makeDir(self.doc_location.basename) catch |e| switch (e) {
error.PathAlreadyExists => {},
else => |err| return err,
};
const output_dir = if (self.doc_location.directory) |d|
try d.handle.openDir(self.doc_location.basename, .{})
else
try self.comp_module.zig_cache_artifact_directory.handle.openDir(self.doc_location.basename, .{});
{
const data_js_f = try output_dir.createFile("data.js", .{});
defer data_js_f.close();
var buffer = std.io.bufferedWriter(data_js_f.writer());
const out = buffer.writer();
try out.print(
\\ /** @type {{DocData}} */
\\ var zigAnalysis=
, .{});
try std.json.stringify(
data,
.{
.whitespace = .{ .indent = .none, .separator = false },
.emit_null_optional_fields = true,
},
out,
);
try out.print(";", .{});
// last thing (that can fail) that we do is flush
try buffer.flush();
}
{
output_dir.makeDir("src") catch |e| switch (e) {
error.PathAlreadyExists => {},
else => |err| return err,
};
const html_dir = try output_dir.openDir("src", .{});
var files_iterator = self.files.iterator();
while (files_iterator.next()) |entry| {
const sub_file_path = entry.key_ptr.*.sub_file_path;
const file_module = entry.key_ptr.*.pkg;
const module_name = (self.modules.get(file_module) orelse continue).name;
const file_path = std.fs.path.dirname(sub_file_path) orelse "";
const file_name = if (file_path.len > 0) sub_file_path[file_path.len + 1 ..] else sub_file_path;
const html_file_name = try std.mem.concat(self.arena, u8, &.{ file_name, ".html" });
defer self.arena.free(html_file_name);
const dir_name = try std.fs.path.join(self.arena, &.{ module_name, file_path });
defer self.arena.free(dir_name);
var dir = try html_dir.makeOpenPath(dir_name, .{});
defer dir.close();
const html_file = dir.createFile(html_file_name, .{}) catch |err| switch (err) {
error.PathAlreadyExists => try dir.openFile(html_file_name, .{}),
else => return err,
};
defer html_file.close();
var buffer = std.io.bufferedWriter(html_file.writer());
const out = buffer.writer();
try renderer.genHtml(self.comp_module.gpa, entry.key_ptr.*, out);
try buffer.flush();
}
}
// copy main.js, index.html
var docs_dir = try self.comp_module.comp.zig_lib_directory.handle.openDir("docs", .{});
defer docs_dir.close();
try docs_dir.copyFile("main.js", output_dir, "main.js", .{});
try docs_dir.copyFile("ziglexer.js", output_dir, "ziglexer.js", .{});
try docs_dir.copyFile("commonmark.js", output_dir, "commonmark.js", .{});
try docs_dir.copyFile("index.html", output_dir, "index.html", .{});
}
/// Represents a chain of scopes, used to resolve decl references to the
/// corresponding entry in `self.decls`. It also keeps track of whether
/// a given decl has been analyzed or not.
const Scope = struct {
parent: ?*Scope,
map: std.AutoHashMapUnmanaged(
u32, // index into the current file's string table (decl name)
*DeclStatus,
) = .{},
enclosing_type: ?usize, // index into `types`, null = file top-level struct
pub const DeclStatus = union(enum) {
Analyzed: usize, // index into `decls`
Pending,
NotRequested: u32, // instr_index
};
/// Returns a pointer so that the caller has a chance to modify the value
/// in case they decide to start analyzing a previously not requested decl.
/// Another reason is that in some places we use the pointer to uniquely
/// refer to a decl, as we wait for it to be analyzed. This means that
/// those pointers must stay stable.
pub fn resolveDeclName(self: Scope, string_table_idx: u32, file: *File, inst_index: usize) *DeclStatus {
var cur: ?*const Scope = &self;
return while (cur) |s| : (cur = s.parent) {
break s.map.get(string_table_idx) orelse continue;
} else {
printWithContext(
file,
inst_index,
"Could not find `{s}`\n\n",
.{file.zir.nullTerminatedString(string_table_idx)},
);
unreachable;
};
}
pub fn insertDeclRef(
self: *Scope,
arena: std.mem.Allocator,
decl_name_index: u32, // index into the current file's string table
decl_status: DeclStatus,
) !void {
const decl_status_ptr = try arena.create(DeclStatus);
errdefer arena.destroy(decl_status_ptr);
decl_status_ptr.* = decl_status;
try self.map.put(arena, decl_name_index, decl_status_ptr);
}
};
/// The output of our analysis process.
const DocData = struct {
typeKinds: []const []const u8 = std.meta.fieldNames(DocTypeKinds),
rootMod: u32 = 0,
params: struct {
zigId: []const u8 = "arst",
zigVersion: []const u8 = build_options.version,
target: []const u8 = "arst",
builds: []const struct { target: []const u8 } = &.{
.{ .target = "arst" },
},
},
modules: std.AutoArrayHashMapUnmanaged(*Module, DocModule),
errors: []struct {} = &.{},
// non-hardcoded stuff
astNodes: []AstNode,
calls: []Call,
files: std.AutoArrayHashMapUnmanaged(*File, usize),
types: []Type,
decls: []Decl,
exprs: []Expr,
comptimeExprs: []ComptimeExpr,
guide_sections: std.ArrayListUnmanaged(Section),
const Call = struct {
func: Expr,
args: []Expr,
ret: Expr,
};
pub fn jsonStringify(
self: DocData,
opts: std.json.StringifyOptions,
w: anytype,
) !void {
var jsw = std.json.writeStream(w, 15);
jsw.whitespace = opts.whitespace;
try jsw.beginObject();
inline for (comptime std.meta.tags(std.meta.FieldEnum(DocData))) |f| {
const f_name = @tagName(f);
try jsw.objectField(f_name);
switch (f) {
.files => try writeFileTableToJson(self.files, self.modules, &jsw),
.guide_sections => try writeGuidesToJson(self.guide_sections, &jsw),
.modules => {
try std.json.stringify(self.modules.values(), opts, w);
jsw.state_index -= 1;
},
else => {
try std.json.stringify(@field(self, f_name), opts, w);
jsw.state_index -= 1;
},
}
}
try jsw.endObject();
}
/// All the type "families" as described by `std.builtin.TypeId`
/// plus a couple extra that are unique to our use case.
///
/// `Unanalyzed` is used so that we can refer to types that have started
/// analysis but that haven't been fully analyzed yet (in case we find
/// self-referential stuff, like `@This()`).
///
/// `ComptimeExpr` represents the result of a piece of comptime logic
/// that we weren't able to analyze fully. Examples of that are comptime
/// function calls and comptime if / switch / ... expressions.
const DocTypeKinds = @typeInfo(Type).Union.tag_type.?;
const ComptimeExpr = struct {
code: []const u8,
};
const DocModule = struct {
name: []const u8 = "(root)",
file: usize = 0, // index into `files`
main: usize = 0, // index into `types`
table: std.AutoHashMapUnmanaged(*Module, TableEntry),
pub const TableEntry = struct {
name: []const u8,
value: usize,
};
pub fn jsonStringify(
self: DocModule,
opts: std.json.StringifyOptions,
w: anytype,
) !void {
var jsw = std.json.writeStream(w, 15);
jsw.whitespace = opts.whitespace;
try jsw.beginObject();
inline for (comptime std.meta.tags(std.meta.FieldEnum(DocModule))) |f| {
const f_name = @tagName(f);
try jsw.objectField(f_name);
switch (f) {
.table => try writeModuleTableToJson(self.table, &jsw),
else => {
try std.json.stringify(@field(self, f_name), opts, w);
jsw.state_index -= 1;
},
}
}
try jsw.endObject();
}
};
const Decl = struct {
name: []const u8,
kind: []const u8,
src: usize, // index into astNodes
value: WalkResult,
// The index in astNodes of the `test declname { }` node
decltest: ?usize = null,
is_uns: bool = false, // usingnamespace
parent_container: ?usize, // index into `types`
pub fn jsonStringify(
self: Decl,
opts: std.json.StringifyOptions,
w: anytype,
) !void {
var jsw = std.json.writeStream(w, 15);
jsw.whitespace = opts.whitespace;
try jsw.beginArray();
inline for (comptime std.meta.fields(Decl)) |f| {
try jsw.arrayElem();
try std.json.stringify(@field(self, f.name), opts, w);
jsw.state_index -= 1;
}
try jsw.endArray();
}
};
const AstNode = struct {
file: usize = 0, // index into files
line: usize = 0,
col: usize = 0,
name: ?[]const u8 = null,
code: ?[]const u8 = null,
docs: ?[]const u8 = null,
fields: ?[]usize = null, // index into astNodes
@"comptime": bool = false,
pub fn jsonStringify(
self: AstNode,
opts: std.json.StringifyOptions,
w: anytype,
) !void {
var jsw = std.json.writeStream(w, 15);
jsw.whitespace = opts.whitespace;
try jsw.beginArray();
inline for (comptime std.meta.fields(AstNode)) |f| {
try jsw.arrayElem();
try std.json.stringify(@field(self, f.name), opts, w);
jsw.state_index -= 1;
}
try jsw.endArray();
}
};
const Type = union(enum) {
Unanalyzed: struct {},
Type: struct { name: []const u8 },
Void: struct { name: []const u8 },
Bool: struct { name: []const u8 },
NoReturn: struct { name: []const u8 },
Int: struct { name: []const u8 },
Float: struct { name: []const u8 },
Pointer: struct {
size: std.builtin.Type.Pointer.Size,
child: Expr,
sentinel: ?Expr = null,
@"align": ?Expr = null,
address_space: ?Expr = null,
bit_start: ?Expr = null,
host_size: ?Expr = null,
is_ref: bool = false,
is_allowzero: bool = false,
is_mutable: bool = false,
is_volatile: bool = false,
has_sentinel: bool = false,
has_align: bool = false,
has_addrspace: bool = false,
has_bit_range: bool = false,
},
Array: struct {
len: Expr,
child: Expr,
sentinel: ?Expr = null,
},
Struct: struct {
name: []const u8,
src: usize, // index into astNodes
privDecls: []usize = &.{}, // index into decls
pubDecls: []usize = &.{}, // index into decls
field_types: []Expr = &.{}, // (use src->fields to find names)
field_defaults: []?Expr = &.{}, // default values is specified
backing_int: ?Expr = null, // backing integer if specified
is_tuple: bool,
line_number: usize,
parent_container: ?usize, // index into `types`
layout: ?Expr, // if different than Auto
},
ComptimeExpr: struct { name: []const u8 },
ComptimeFloat: struct { name: []const u8 },
ComptimeInt: struct { name: []const u8 },
Undefined: struct { name: []const u8 },
Null: struct { name: []const u8 },
Optional: struct {
name: []const u8,
child: Expr,
},
ErrorUnion: struct { lhs: Expr, rhs: Expr },
InferredErrorUnion: struct { payload: Expr },
ErrorSet: struct {
name: []const u8,
fields: ?[]const Field = null,
// TODO: fn field for inferred error sets?
},
Enum: struct {
name: []const u8,
src: usize, // index into astNodes
privDecls: []usize = &.{}, // index into decls
pubDecls: []usize = &.{}, // index into decls
// (use src->fields to find field names)
tag: ?Expr = null, // tag type if specified
values: []?Expr = &.{}, // tag values if specified
nonexhaustive: bool,
parent_container: ?usize, // index into `types`
},
Union: struct {
name: []const u8,
src: usize, // index into astNodes
privDecls: []usize = &.{}, // index into decls
pubDecls: []usize = &.{}, // index into decls
fields: []Expr = &.{}, // (use src->fields to find names)
tag: ?Expr, // tag type if specified
auto_enum: bool, // tag is an auto enum
parent_container: ?usize, // index into `types`
layout: ?Expr, // if different than Auto
},
Fn: struct {
name: []const u8,
src: ?usize = null, // index into `astNodes`
ret: Expr,
generic_ret: ?Expr = null,
params: ?[]Expr = null, // (use src->fields to find names)
lib_name: []const u8 = "",
is_var_args: bool = false,
is_inferred_error: bool = false,
has_lib_name: bool = false,
has_cc: bool = false,
cc: ?usize = null,
@"align": ?usize = null,
has_align: bool = false,
is_test: bool = false,
is_extern: bool = false,
},
Opaque: struct {
name: []const u8,
src: usize, // index into astNodes
privDecls: []usize = &.{}, // index into decls
pubDecls: []usize = &.{}, // index into decls
parent_container: ?usize, // index into `types`
},
Frame: struct { name: []const u8 },
AnyFrame: struct { name: []const u8 },
Vector: struct { name: []const u8 },
EnumLiteral: struct { name: []const u8 },
const Field = struct {
name: []const u8,
docs: []const u8,
};
pub fn jsonStringify(
self: Type,
opts: std.json.StringifyOptions,
w: anytype,
) !void {
const active_tag = std.meta.activeTag(self);
var jsw = std.json.writeStream(w, 15);
jsw.whitespace = opts.whitespace;
try jsw.beginArray();
try jsw.arrayElem();
try jsw.emitNumber(@intFromEnum(active_tag));
inline for (comptime std.meta.fields(Type)) |case| {
if (@field(Type, case.name) == active_tag) {
const current_value = @field(self, case.name);
inline for (comptime std.meta.fields(case.type)) |f| {
try jsw.arrayElem();
if (f.type == std.builtin.Type.Pointer.Size) {
try jsw.emitNumber(@intFromEnum(@field(current_value, f.name)));
} else {
try std.json.stringify(@field(current_value, f.name), opts, w);
jsw.state_index -= 1;
}
}
}
}
try jsw.endArray();
}
};
/// An Expr represents the (untyped) result of analyzing instructions.
/// The data is normalized, which means that an Expr that results in a
/// type definition will hold an index into `self.types`.
pub const Expr = union(enum) {
comptimeExpr: usize, // index in `comptimeExprs`
void: struct {},
@"unreachable": struct {},
null: struct {},
undefined: struct {},
@"struct": []FieldVal,
bool: bool,
@"anytype": struct {},
@"&": usize, // index in `exprs`
type: usize, // index in `types`
this: usize, // index in `types`
declRef: *Scope.DeclStatus,
declIndex: usize, // index into `decls`, alternative repr for `declRef`
builtinField: enum { len, ptr },
fieldRef: FieldRef,
refPath: []Expr,
int: struct {
value: u64, // direct value
negated: bool = false,
},
int_big: struct {
value: []const u8, // string representation
negated: bool = false,
},
float: f64, // direct value
float128: f128, // direct value
array: []usize, // index in `exprs`
call: usize, // index in `calls`
enumLiteral: []const u8, // direct value
alignOf: usize, // index in `exprs`
typeOf: usize, // index in `exprs`
typeInfo: usize, // index in `exprs`
typeOf_peer: []usize,
errorUnion: usize, // index in `types`
as: As,
sizeOf: usize, // index in `exprs`
bitSizeOf: usize, // index in `exprs`
intFromEnum: usize, // index in `exprs`
compileError: usize, //index in `exprs`
errorSets: usize,
string: []const u8, // direct value
sliceIndex: usize,
slice: Slice,
sliceLength: SliceLength,
cmpxchgIndex: usize,
cmpxchg: Cmpxchg,
builtin: Builtin,
builtinIndex: usize,
builtinBin: BuiltinBin,
builtinBinIndex: usize,
switchIndex: usize, // index in `exprs`
switchOp: SwitchOp,
binOp: BinOp,
binOpIndex: usize,
const BinOp = struct {
lhs: usize, // index in `exprs`
rhs: usize, // index in `exprs`
name: []const u8 = "", // tag name
};
const SwitchOp = struct {
cond_index: usize,
file_name: []const u8,
src: usize,
outer_decl: usize, // index in `types`
};
const BuiltinBin = struct {
name: []const u8 = "", // fn name
lhs: usize, // index in `exprs`
rhs: usize, // index in `exprs`
};
const Builtin = struct {
name: []const u8 = "", // fn name
param: usize, // index in `exprs`
};
const Slice = struct {
lhs: usize, // index in `exprs`
start: usize,
end: ?usize = null,
sentinel: ?usize = null, // index in `exprs`
};
const SliceLength = struct {
lhs: usize,
start: usize,
len: usize,
sentinel: ?usize = null,
};
const Cmpxchg = struct {
name: []const u8,
type: usize,
ptr: usize,
expected_value: usize,
new_value: usize,
success_order: usize,
failure_order: usize,
};
const As = struct {
typeRefArg: ?usize, // index in `exprs`
exprArg: usize, // index in `exprs`
};
const FieldRef = struct {
type: usize, // index in `types`
index: usize, // index in type.fields
};
const FieldVal = struct {
name: []const u8,
val: WalkResult,
};
pub fn jsonStringify(
self: Expr,
opts: std.json.StringifyOptions,
w: anytype,
) @TypeOf(w).Error!void {
const active_tag = std.meta.activeTag(self);
var jsw = std.json.writeStream(w, 15);
jsw.whitespace = opts.whitespace;
try jsw.beginObject();
if (active_tag == .declIndex) {
try jsw.objectField("declRef");
} else {
try jsw.objectField(@tagName(active_tag));
}
switch (self) {
.int => {
if (self.int.negated) try w.writeAll("-");
try jsw.emitNumber(self.int.value);
},
.builtinField => {
try jsw.emitString(@tagName(self.builtinField));
},
.declRef => {
try jsw.emitNumber(self.declRef.Analyzed);
},
else => {
inline for (comptime std.meta.fields(Expr)) |case| {
// TODO: this is super ugly, fix once `inline else` is a thing
if (comptime std.mem.eql(u8, case.name, "builtinField"))
continue;
if (comptime std.mem.eql(u8, case.name, "declRef"))
continue;
if (@field(Expr, case.name) == active_tag) {
try std.json.stringify(@field(self, case.name), opts, w);
jsw.state_index -= 1;
// TODO: we should not reach into the state of the
// json writer, but alas, this is what's
// necessary with the current api.
// would be nice to have a proper integration
// between the json writer and the generic
// std.json.stringify implementation
}
}
},
}
try jsw.endObject();
}
};
/// A WalkResult represents the result of the analysis process done to a
/// a Zir instruction. Walk results carry type information either inferred
/// from the context (eg string literals are pointers to null-terminated
/// arrays), or because of @as() instructions.
/// Since the type information is only needed in certain contexts, the
/// underlying normalized data (Expr) is untyped.
const WalkResult = struct {
typeRef: ?Expr = null, // index in `exprs`
expr: Expr, // index in `exprs`
};
};
const AutodocErrors = error{
OutOfMemory,
CurrentWorkingDirectoryUnlinked,
UnexpectedEndOfFile,
} || std.fs.File.OpenError || std.fs.File.ReadError;
/// Called when we need to analyze a Zir instruction.
/// For example it gets called by `generateZirData` on instruction 0,
/// which represents the top-level struct corresponding to the root file.
/// Note that in some situations where we're analyzing code that only allows
/// for a limited subset of Zig syntax, we don't always resort to calling
/// `walkInstruction` and instead sometimes we handle Zir directly.
/// The best example of that are instructions corresponding to function
/// params, as those can only occur while analyzing a function definition.
fn walkInstruction(
self: *Autodoc,
file: *File,
parent_scope: *Scope,
parent_src: SrcLocInfo,
inst_index: usize,
need_type: bool, // true if the caller needs us to provide also a typeRef
) AutodocErrors!DocData.WalkResult {
const tags = file.zir.instructions.items(.tag);
const data = file.zir.instructions.items(.data);
// We assume that the topmost ast_node entry corresponds to our decl
const self_ast_node_index = self.ast_nodes.items.len - 1;