-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
Module.zig
3388 lines (3028 loc) · 129 KB
/
Module.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 Module = @This();
const std = @import("std");
const Compilation = @import("Compilation.zig");
const mem = std.mem;
const Allocator = std.mem.Allocator;
const ArrayListUnmanaged = std.ArrayListUnmanaged;
const Value = @import("value.zig").Value;
const Type = @import("type.zig").Type;
const TypedValue = @import("TypedValue.zig");
const assert = std.debug.assert;
const log = std.log.scoped(.module);
const BigIntConst = std.math.big.int.Const;
const BigIntMutable = std.math.big.int.Mutable;
const Target = std.Target;
const Package = @import("Package.zig");
const link = @import("link.zig");
const ir = @import("ir.zig");
const zir = @import("zir.zig");
const Inst = ir.Inst;
const Body = ir.Body;
const ast = std.zig.ast;
const trace = @import("tracy.zig").trace;
const astgen = @import("astgen.zig");
const zir_sema = @import("zir_sema.zig");
/// General-purpose allocator. Used for both temporary and long-term storage.
gpa: *Allocator,
comp: *Compilation,
/// Where our incremental compilation metadata serialization will go.
zig_cache_artifact_directory: Compilation.Directory,
/// Pointer to externally managed resource. `null` if there is no zig file being compiled.
root_pkg: *Package,
/// Module owns this resource.
/// The `Scope` is either a `Scope.ZIRModule` or `Scope.File`.
root_scope: *Scope,
/// It's rare for a decl to be exported, so we save memory by having a sparse map of
/// Decl pointers to details about them being exported.
/// The Export memory is owned by the `export_owners` table; the slice itself is owned by this table.
decl_exports: std.AutoArrayHashMapUnmanaged(*Decl, []*Export) = .{},
/// We track which export is associated with the given symbol name for quick
/// detection of symbol collisions.
symbol_exports: std.StringArrayHashMapUnmanaged(*Export) = .{},
/// This models the Decls that perform exports, so that `decl_exports` can be updated when a Decl
/// is modified. Note that the key of this table is not the Decl being exported, but the Decl that
/// is performing the export of another Decl.
/// This table owns the Export memory.
export_owners: std.AutoArrayHashMapUnmanaged(*Decl, []*Export) = .{},
/// Maps fully qualified namespaced names to the Decl struct for them.
decl_table: std.ArrayHashMapUnmanaged(Scope.NameHash, *Decl, Scope.name_hash_hash, Scope.name_hash_eql, false) = .{},
/// We optimize memory usage for a compilation with no compile errors by storing the
/// error messages and mapping outside of `Decl`.
/// The ErrorMsg memory is owned by the decl, using Module's general purpose allocator.
/// Note that a Decl can succeed but the Fn it represents can fail. In this case,
/// a Decl can have a failed_decls entry but have analysis status of success.
failed_decls: std.AutoArrayHashMapUnmanaged(*Decl, *Compilation.ErrorMsg) = .{},
/// Using a map here for consistency with the other fields here.
/// The ErrorMsg memory is owned by the `Scope`, using Module's general purpose allocator.
failed_files: std.AutoArrayHashMapUnmanaged(*Scope, *Compilation.ErrorMsg) = .{},
/// Using a map here for consistency with the other fields here.
/// The ErrorMsg memory is owned by the `Export`, using Module's general purpose allocator.
failed_exports: std.AutoArrayHashMapUnmanaged(*Export, *Compilation.ErrorMsg) = .{},
next_anon_name_index: usize = 0,
/// Candidates for deletion. After a semantic analysis update completes, this list
/// contains Decls that need to be deleted if they end up having no references to them.
deletion_set: ArrayListUnmanaged(*Decl) = .{},
/// Error tags and their values, tag names are duped with mod.gpa.
global_error_set: std.StringHashMapUnmanaged(u16) = .{},
/// Keys are fully qualified paths
import_table: std.StringArrayHashMapUnmanaged(*Scope.File) = .{},
/// Incrementing integer used to compare against the corresponding Decl
/// field to determine whether a Decl's status applies to an ongoing update, or a
/// previous analysis.
generation: u32 = 0,
/// When populated it means there was an error opening/reading the root source file.
failed_root_src_file: ?anyerror = null,
stage1_flags: packed struct {
have_winmain: bool = false,
have_wwinmain: bool = false,
have_winmain_crt_startup: bool = false,
have_wwinmain_crt_startup: bool = false,
have_dllmain_crt_startup: bool = false,
have_c_main: bool = false,
reserved: u2 = 0,
} = .{},
pub const Export = struct {
options: std.builtin.ExportOptions,
/// Byte offset into the file that contains the export directive.
src: usize,
/// Represents the position of the export, if any, in the output file.
link: link.File.Export,
/// The Decl that performs the export. Note that this is *not* the Decl being exported.
owner_decl: *Decl,
/// The Decl being exported. Note this is *not* the Decl performing the export.
exported_decl: *Decl,
status: enum {
in_progress,
failed,
/// Indicates that the failure was due to a temporary issue, such as an I/O error
/// when writing to the output file. Retrying the export may succeed.
failed_retryable,
complete,
},
};
pub const Decl = struct {
/// This name is relative to the containing namespace of the decl. It uses a null-termination
/// to save bytes, since there can be a lot of decls in a compilation. The null byte is not allowed
/// in symbol names, because executable file formats use null-terminated strings for symbol names.
/// All Decls have names, even values that are not bound to a zig namespace. This is necessary for
/// mapping them to an address in the output file.
/// Memory owned by this decl, using Module's allocator.
name: [*:0]const u8,
/// The direct parent container of the Decl. This is either a `Scope.Container` or `Scope.ZIRModule`.
/// Reference to externally owned memory.
scope: *Scope,
/// The AST Node decl index or ZIR Inst index that contains this declaration.
/// Must be recomputed when the corresponding source file is modified.
src_index: usize,
/// The most recent value of the Decl after a successful semantic analysis.
typed_value: union(enum) {
never_succeeded: void,
most_recent: TypedValue.Managed,
},
/// Represents the "shallow" analysis status. For example, for decls that are functions,
/// the function type is analyzed with this set to `in_progress`, however, the semantic
/// analysis of the function body is performed with this value set to `success`. Functions
/// have their own analysis status field.
analysis: enum {
/// This Decl corresponds to an AST Node that has not been referenced yet, and therefore
/// because of Zig's lazy declaration analysis, it will remain unanalyzed until referenced.
unreferenced,
/// Semantic analysis for this Decl is running right now. This state detects dependency loops.
in_progress,
/// This Decl might be OK but it depends on another one which did not successfully complete
/// semantic analysis.
dependency_failure,
/// Semantic analysis failure.
/// There will be a corresponding ErrorMsg in Module.failed_decls.
sema_failure,
/// There will be a corresponding ErrorMsg in Module.failed_decls.
/// This indicates the failure was something like running out of disk space,
/// and attempting semantic analysis again may succeed.
sema_failure_retryable,
/// There will be a corresponding ErrorMsg in Module.failed_decls.
codegen_failure,
/// There will be a corresponding ErrorMsg in Module.failed_decls.
/// This indicates the failure was something like running out of disk space,
/// and attempting codegen again may succeed.
codegen_failure_retryable,
/// Everything is done. During an update, this Decl may be out of date, depending
/// on its dependencies. The `generation` field can be used to determine if this
/// completion status occurred before or after a given update.
complete,
/// A Module update is in progress, and this Decl has been flagged as being known
/// to require re-analysis.
outdated,
},
/// This flag is set when this Decl is added to a check_for_deletion set, and cleared
/// when removed.
deletion_flag: bool,
/// Whether the corresponding AST decl has a `pub` keyword.
is_pub: bool,
/// An integer that can be checked against the corresponding incrementing
/// generation field of Module. This is used to determine whether `complete` status
/// represents pre- or post- re-analysis.
generation: u32,
/// Represents the position of the code in the output file.
/// This is populated regardless of semantic analysis and code generation.
link: link.File.LinkBlock,
/// Represents the function in the linked output file, if the `Decl` is a function.
/// This is stored here and not in `Fn` because `Decl` survives across updates but
/// `Fn` does not.
/// TODO Look into making `Fn` a longer lived structure and moving this field there
/// to save on memory usage.
fn_link: link.File.LinkFn,
contents_hash: std.zig.SrcHash,
/// The shallow set of other decls whose typed_value could possibly change if this Decl's
/// typed_value is modified.
dependants: DepsTable = .{},
/// The shallow set of other decls whose typed_value changing indicates that this Decl's
/// typed_value may need to be regenerated.
dependencies: DepsTable = .{},
/// The reason this is not `std.AutoArrayHashMapUnmanaged` is a workaround for
/// stage1 compiler giving me: `error: struct 'Module.Decl' depends on itself`
pub const DepsTable = std.ArrayHashMapUnmanaged(*Decl, void, std.array_hash_map.getAutoHashFn(*Decl), std.array_hash_map.getAutoEqlFn(*Decl), false);
pub fn destroy(self: *Decl, gpa: *Allocator) void {
gpa.free(mem.spanZ(self.name));
if (self.typedValueManaged()) |tvm| {
tvm.deinit(gpa);
}
self.dependants.deinit(gpa);
self.dependencies.deinit(gpa);
gpa.destroy(self);
}
pub fn src(self: Decl) usize {
switch (self.scope.tag) {
.container => {
const container = @fieldParentPtr(Scope.Container, "base", self.scope);
const tree = container.file_scope.contents.tree;
// TODO Container should have its own decls()
const decl_node = tree.root_node.decls()[self.src_index];
return tree.token_locs[decl_node.firstToken()].start;
},
.zir_module => {
const zir_module = @fieldParentPtr(Scope.ZIRModule, "base", self.scope);
const module = zir_module.contents.module;
const src_decl = module.decls[self.src_index];
return src_decl.inst.src;
},
.file, .block => unreachable,
.gen_zir => unreachable,
.local_val => unreachable,
.local_ptr => unreachable,
.decl => unreachable,
}
}
pub fn fullyQualifiedNameHash(self: Decl) Scope.NameHash {
return self.scope.fullyQualifiedNameHash(mem.spanZ(self.name));
}
pub fn typedValue(self: *Decl) error{AnalysisFail}!TypedValue {
const tvm = self.typedValueManaged() orelse return error.AnalysisFail;
return tvm.typed_value;
}
pub fn value(self: *Decl) error{AnalysisFail}!Value {
return (try self.typedValue()).val;
}
pub fn dump(self: *Decl) void {
const loc = std.zig.findLineColumn(self.scope.source.bytes, self.src);
std.debug.print("{}:{}:{} name={} status={}", .{
self.scope.sub_file_path,
loc.line + 1,
loc.column + 1,
mem.spanZ(self.name),
@tagName(self.analysis),
});
if (self.typedValueManaged()) |tvm| {
std.debug.print(" ty={} val={}", .{ tvm.typed_value.ty, tvm.typed_value.val });
}
std.debug.print("\n", .{});
}
pub fn typedValueManaged(self: *Decl) ?*TypedValue.Managed {
switch (self.typed_value) {
.most_recent => |*x| return x,
.never_succeeded => return null,
}
}
fn removeDependant(self: *Decl, other: *Decl) void {
self.dependants.removeAssertDiscard(other);
}
fn removeDependency(self: *Decl, other: *Decl) void {
self.dependencies.removeAssertDiscard(other);
}
};
/// Fn struct memory is owned by the Decl's TypedValue.Managed arena allocator.
pub const Fn = struct {
/// This memory owned by the Decl's TypedValue.Managed arena allocator.
analysis: union(enum) {
queued: *ZIR,
in_progress,
/// There will be a corresponding ErrorMsg in Module.failed_decls
sema_failure,
/// This Fn might be OK but it depends on another Decl which did not successfully complete
/// semantic analysis.
dependency_failure,
success: Body,
},
owner_decl: *Decl,
/// This memory is temporary and points to stack memory for the duration
/// of Fn analysis.
pub const Analysis = struct {
inner_block: Scope.Block,
};
/// Contains un-analyzed ZIR instructions generated from Zig source AST.
pub const ZIR = struct {
body: zir.Module.Body,
arena: std.heap.ArenaAllocator.State,
};
/// For debugging purposes.
pub fn dump(self: *Fn, mod: Module) void {
std.debug.print("Module.Function(name={}) ", .{self.owner_decl.name});
switch (self.analysis) {
.queued => {
std.debug.print("queued\n", .{});
},
.in_progress => {
std.debug.print("in_progress\n", .{});
},
else => {
std.debug.print("\n", .{});
zir.dumpFn(mod, self);
},
}
}
};
pub const Var = struct {
/// if is_extern == true this is undefined
init: Value,
owner_decl: *Decl,
is_extern: bool,
is_mutable: bool,
is_threadlocal: bool,
};
pub const Scope = struct {
tag: Tag,
pub const NameHash = [16]u8;
pub fn cast(base: *Scope, comptime T: type) ?*T {
if (base.tag != T.base_tag)
return null;
return @fieldParentPtr(T, "base", base);
}
/// Asserts the scope has a parent which is a DeclAnalysis and
/// returns the arena Allocator.
pub fn arena(self: *Scope) *Allocator {
switch (self.tag) {
.block => return self.cast(Block).?.arena,
.decl => return &self.cast(DeclAnalysis).?.arena.allocator,
.gen_zir => return self.cast(GenZIR).?.arena,
.local_val => return self.cast(LocalVal).?.gen_zir.arena,
.local_ptr => return self.cast(LocalPtr).?.gen_zir.arena,
.zir_module => return &self.cast(ZIRModule).?.contents.module.arena.allocator,
.file => unreachable,
.container => unreachable,
}
}
/// If the scope has a parent which is a `DeclAnalysis`,
/// returns the `Decl`, otherwise returns `null`.
pub fn decl(self: *Scope) ?*Decl {
return switch (self.tag) {
.block => self.cast(Block).?.decl,
.gen_zir => self.cast(GenZIR).?.decl,
.local_val => self.cast(LocalVal).?.gen_zir.decl,
.local_ptr => self.cast(LocalPtr).?.gen_zir.decl,
.decl => self.cast(DeclAnalysis).?.decl,
.zir_module => null,
.file => null,
.container => null,
};
}
/// Asserts the scope has a parent which is a ZIRModule or Container and
/// returns it.
pub fn namespace(self: *Scope) *Scope {
switch (self.tag) {
.block => return self.cast(Block).?.decl.scope,
.gen_zir => return self.cast(GenZIR).?.decl.scope,
.local_val => return self.cast(LocalVal).?.gen_zir.decl.scope,
.local_ptr => return self.cast(LocalPtr).?.gen_zir.decl.scope,
.decl => return self.cast(DeclAnalysis).?.decl.scope,
.file => return &self.cast(File).?.root_container.base,
.zir_module, .container => return self,
}
}
/// Must generate unique bytes with no collisions with other decls.
/// The point of hashing here is only to limit the number of bytes of
/// the unique identifier to a fixed size (16 bytes).
pub fn fullyQualifiedNameHash(self: *Scope, name: []const u8) NameHash {
switch (self.tag) {
.block => unreachable,
.gen_zir => unreachable,
.local_val => unreachable,
.local_ptr => unreachable,
.decl => unreachable,
.file => unreachable,
.zir_module => return self.cast(ZIRModule).?.fullyQualifiedNameHash(name),
.container => return self.cast(Container).?.fullyQualifiedNameHash(name),
}
}
/// Asserts the scope is a child of a File and has an AST tree and returns the tree.
pub fn tree(self: *Scope) *ast.Tree {
switch (self.tag) {
.file => return self.cast(File).?.contents.tree,
.zir_module => unreachable,
.decl => return self.cast(DeclAnalysis).?.decl.scope.cast(Container).?.file_scope.contents.tree,
.block => return self.cast(Block).?.decl.scope.cast(Container).?.file_scope.contents.tree,
.gen_zir => return self.cast(GenZIR).?.decl.scope.cast(Container).?.file_scope.contents.tree,
.local_val => return self.cast(LocalVal).?.gen_zir.decl.scope.cast(Container).?.file_scope.contents.tree,
.local_ptr => return self.cast(LocalPtr).?.gen_zir.decl.scope.cast(Container).?.file_scope.contents.tree,
.container => return self.cast(Container).?.file_scope.contents.tree,
}
}
/// Asserts the scope is a child of a `GenZIR` and returns it.
pub fn getGenZIR(self: *Scope) *GenZIR {
return switch (self.tag) {
.block => unreachable,
.gen_zir => self.cast(GenZIR).?,
.local_val => return self.cast(LocalVal).?.gen_zir,
.local_ptr => return self.cast(LocalPtr).?.gen_zir,
.decl => unreachable,
.zir_module => unreachable,
.file => unreachable,
.container => unreachable,
};
}
/// Asserts the scope has a parent which is a ZIRModule, Contaienr or File and
/// returns the sub_file_path field.
pub fn subFilePath(base: *Scope) []const u8 {
switch (base.tag) {
.container => return @fieldParentPtr(Container, "base", base).file_scope.sub_file_path,
.file => return @fieldParentPtr(File, "base", base).sub_file_path,
.zir_module => return @fieldParentPtr(ZIRModule, "base", base).sub_file_path,
.block => unreachable,
.gen_zir => unreachable,
.local_val => unreachable,
.local_ptr => unreachable,
.decl => unreachable,
}
}
pub fn unload(base: *Scope, gpa: *Allocator) void {
switch (base.tag) {
.file => return @fieldParentPtr(File, "base", base).unload(gpa),
.zir_module => return @fieldParentPtr(ZIRModule, "base", base).unload(gpa),
.block => unreachable,
.gen_zir => unreachable,
.local_val => unreachable,
.local_ptr => unreachable,
.decl => unreachable,
.container => unreachable,
}
}
pub fn getSource(base: *Scope, module: *Module) ![:0]const u8 {
switch (base.tag) {
.container => return @fieldParentPtr(Container, "base", base).file_scope.getSource(module),
.file => return @fieldParentPtr(File, "base", base).getSource(module),
.zir_module => return @fieldParentPtr(ZIRModule, "base", base).getSource(module),
.gen_zir => unreachable,
.local_val => unreachable,
.local_ptr => unreachable,
.block => unreachable,
.decl => unreachable,
}
}
pub fn getOwnerPkg(base: *Scope) *Package {
var cur = base;
while (true) {
cur = switch (cur.tag) {
.container => return @fieldParentPtr(Container, "base", cur).file_scope.pkg,
.file => return @fieldParentPtr(File, "base", cur).pkg,
.zir_module => unreachable, // TODO are zir modules allowed to import packages?
.gen_zir => @fieldParentPtr(GenZIR, "base", cur).parent,
.local_val => @fieldParentPtr(LocalVal, "base", cur).parent,
.local_ptr => @fieldParentPtr(LocalPtr, "base", cur).parent,
.block => @fieldParentPtr(Block, "base", cur).decl.scope,
.decl => @fieldParentPtr(DeclAnalysis, "base", cur).decl.scope,
};
}
}
/// Asserts the scope is a namespace Scope and removes the Decl from the namespace.
pub fn removeDecl(base: *Scope, child: *Decl) void {
switch (base.tag) {
.container => return @fieldParentPtr(Container, "base", base).removeDecl(child),
.zir_module => return @fieldParentPtr(ZIRModule, "base", base).removeDecl(child),
.file => unreachable,
.block => unreachable,
.gen_zir => unreachable,
.local_val => unreachable,
.local_ptr => unreachable,
.decl => unreachable,
}
}
/// Asserts the scope is a File or ZIRModule and deinitializes it, then deallocates it.
pub fn destroy(base: *Scope, gpa: *Allocator) void {
switch (base.tag) {
.file => {
const scope_file = @fieldParentPtr(File, "base", base);
scope_file.deinit(gpa);
gpa.destroy(scope_file);
},
.zir_module => {
const scope_zir_module = @fieldParentPtr(ZIRModule, "base", base);
scope_zir_module.deinit(gpa);
gpa.destroy(scope_zir_module);
},
.block => unreachable,
.gen_zir => unreachable,
.local_val => unreachable,
.local_ptr => unreachable,
.decl => unreachable,
.container => unreachable,
}
}
fn name_hash_hash(x: NameHash) u32 {
return @truncate(u32, @bitCast(u128, x));
}
fn name_hash_eql(a: NameHash, b: NameHash) bool {
return @bitCast(u128, a) == @bitCast(u128, b);
}
pub const Tag = enum {
/// .zir source code.
zir_module,
/// .zig source code.
file,
/// struct, enum or union, every .file contains one of these.
container,
block,
decl,
gen_zir,
local_val,
local_ptr,
};
pub const Container = struct {
pub const base_tag: Tag = .container;
base: Scope = Scope{ .tag = base_tag },
file_scope: *Scope.File,
/// Direct children of the file.
decls: std.AutoArrayHashMapUnmanaged(*Decl, void),
ty: Type,
pub fn deinit(self: *Container, gpa: *Allocator) void {
self.decls.deinit(gpa);
// TODO either Container of File should have an arena for sub_file_path and ty
gpa.destroy(self.ty.cast(Type.Payload.EmptyStruct).?);
gpa.free(self.file_scope.sub_file_path);
self.* = undefined;
}
pub fn removeDecl(self: *Container, child: *Decl) void {
_ = self.decls.remove(child);
}
pub fn fullyQualifiedNameHash(self: *Container, name: []const u8) NameHash {
// TODO container scope qualified names.
return std.zig.hashSrc(name);
}
};
pub const File = struct {
pub const base_tag: Tag = .file;
base: Scope = Scope{ .tag = base_tag },
/// Relative to the owning package's root_src_dir.
/// Reference to external memory, not owned by File.
sub_file_path: []const u8,
source: union(enum) {
unloaded: void,
bytes: [:0]const u8,
},
contents: union {
not_available: void,
tree: *ast.Tree,
},
status: enum {
never_loaded,
unloaded_success,
unloaded_parse_failure,
loaded_success,
},
/// Package that this file is a part of, managed externally.
pkg: *Package,
root_container: Container,
pub fn unload(self: *File, gpa: *Allocator) void {
switch (self.status) {
.never_loaded,
.unloaded_parse_failure,
.unloaded_success,
=> {},
.loaded_success => {
self.contents.tree.deinit();
self.status = .unloaded_success;
},
}
switch (self.source) {
.bytes => |bytes| {
gpa.free(bytes);
self.source = .{ .unloaded = {} };
},
.unloaded => {},
}
}
pub fn deinit(self: *File, gpa: *Allocator) void {
self.root_container.deinit(gpa);
self.unload(gpa);
self.* = undefined;
}
pub fn dumpSrc(self: *File, src: usize) void {
const loc = std.zig.findLineColumn(self.source.bytes, src);
std.debug.print("{}:{}:{}\n", .{ self.sub_file_path, loc.line + 1, loc.column + 1 });
}
pub fn getSource(self: *File, module: *Module) ![:0]const u8 {
switch (self.source) {
.unloaded => {
const source = try self.pkg.root_src_directory.handle.readFileAllocOptions(
module.gpa,
self.sub_file_path,
std.math.maxInt(u32),
null,
1,
0,
);
self.source = .{ .bytes = source };
return source;
},
.bytes => |bytes| return bytes,
}
}
};
pub const ZIRModule = struct {
pub const base_tag: Tag = .zir_module;
base: Scope = Scope{ .tag = base_tag },
/// Relative to the owning package's root_src_dir.
/// Reference to external memory, not owned by ZIRModule.
sub_file_path: []const u8,
source: union(enum) {
unloaded: void,
bytes: [:0]const u8,
},
contents: union {
not_available: void,
module: *zir.Module,
},
status: enum {
never_loaded,
unloaded_success,
unloaded_parse_failure,
unloaded_sema_failure,
loaded_sema_failure,
loaded_success,
},
/// Even though .zir files only have 1 module, this set is still needed
/// because of anonymous Decls, which can exist in the global set, but
/// not this one.
decls: ArrayListUnmanaged(*Decl),
pub fn unload(self: *ZIRModule, gpa: *Allocator) void {
switch (self.status) {
.never_loaded,
.unloaded_parse_failure,
.unloaded_sema_failure,
.unloaded_success,
=> {},
.loaded_success => {
self.contents.module.deinit(gpa);
gpa.destroy(self.contents.module);
self.contents = .{ .not_available = {} };
self.status = .unloaded_success;
},
.loaded_sema_failure => {
self.contents.module.deinit(gpa);
gpa.destroy(self.contents.module);
self.contents = .{ .not_available = {} };
self.status = .unloaded_sema_failure;
},
}
switch (self.source) {
.bytes => |bytes| {
gpa.free(bytes);
self.source = .{ .unloaded = {} };
},
.unloaded => {},
}
}
pub fn deinit(self: *ZIRModule, gpa: *Allocator) void {
self.decls.deinit(gpa);
self.unload(gpa);
self.* = undefined;
}
pub fn removeDecl(self: *ZIRModule, child: *Decl) void {
for (self.decls.items) |item, i| {
if (item == child) {
_ = self.decls.swapRemove(i);
return;
}
}
}
pub fn dumpSrc(self: *ZIRModule, src: usize) void {
const loc = std.zig.findLineColumn(self.source.bytes, src);
std.debug.print("{}:{}:{}\n", .{ self.sub_file_path, loc.line + 1, loc.column + 1 });
}
pub fn getSource(self: *ZIRModule, module: *Module) ![:0]const u8 {
switch (self.source) {
.unloaded => {
const source = try module.root_pkg.root_src_directory.handle.readFileAllocOptions(
module.gpa,
self.sub_file_path,
std.math.maxInt(u32),
null,
1,
0,
);
self.source = .{ .bytes = source };
return source;
},
.bytes => |bytes| return bytes,
}
}
pub fn fullyQualifiedNameHash(self: *ZIRModule, name: []const u8) NameHash {
// ZIR modules only have 1 file with all decls global in the same namespace.
return std.zig.hashSrc(name);
}
};
/// This is a temporary structure, references to it are valid only
/// during semantic analysis of the block.
pub const Block = struct {
pub const base_tag: Tag = .block;
base: Scope = Scope{ .tag = base_tag },
parent: ?*Block,
func: ?*Fn,
decl: *Decl,
instructions: ArrayListUnmanaged(*Inst),
/// Points to the arena allocator of DeclAnalysis
arena: *Allocator,
label: ?Label = null,
is_comptime: bool,
pub const Label = struct {
zir_block: *zir.Inst.Block,
results: ArrayListUnmanaged(*Inst),
block_inst: *Inst.Block,
};
};
/// This is a temporary structure, references to it are valid only
/// during semantic analysis of the decl.
pub const DeclAnalysis = struct {
pub const base_tag: Tag = .decl;
base: Scope = Scope{ .tag = base_tag },
decl: *Decl,
arena: std.heap.ArenaAllocator,
};
/// This is a temporary structure, references to it are valid only
/// during semantic analysis of the decl.
pub const GenZIR = struct {
pub const base_tag: Tag = .gen_zir;
base: Scope = Scope{ .tag = base_tag },
/// Parents can be: `GenZIR`, `ZIRModule`, `File`
parent: *Scope,
decl: *Decl,
arena: *Allocator,
/// The first N instructions in a function body ZIR are arg instructions.
instructions: std.ArrayListUnmanaged(*zir.Inst) = .{},
label: ?Label = null,
pub const Label = struct {
token: ast.TokenIndex,
block_inst: *zir.Inst.Block,
result_loc: astgen.ResultLoc,
};
};
/// This is always a `const` local and importantly the `inst` is a value type, not a pointer.
/// This structure lives as long as the AST generation of the Block
/// node that contains the variable.
pub const LocalVal = struct {
pub const base_tag: Tag = .local_val;
base: Scope = Scope{ .tag = base_tag },
/// Parents can be: `LocalVal`, `LocalPtr`, `GenZIR`.
parent: *Scope,
gen_zir: *GenZIR,
name: []const u8,
inst: *zir.Inst,
};
/// This could be a `const` or `var` local. It has a pointer instead of a value.
/// This structure lives as long as the AST generation of the Block
/// node that contains the variable.
pub const LocalPtr = struct {
pub const base_tag: Tag = .local_ptr;
base: Scope = Scope{ .tag = base_tag },
/// Parents can be: `LocalVal`, `LocalPtr`, `GenZIR`.
parent: *Scope,
gen_zir: *GenZIR,
name: []const u8,
ptr: *zir.Inst,
};
};
pub const InnerError = error{ OutOfMemory, AnalysisFail };
pub fn deinit(self: *Module) void {
const gpa = self.gpa;
self.zig_cache_artifact_directory.handle.close();
self.deletion_set.deinit(gpa);
for (self.decl_table.items()) |entry| {
entry.value.destroy(gpa);
}
self.decl_table.deinit(gpa);
for (self.failed_decls.items()) |entry| {
entry.value.destroy(gpa);
}
self.failed_decls.deinit(gpa);
for (self.failed_files.items()) |entry| {
entry.value.destroy(gpa);
}
self.failed_files.deinit(gpa);
for (self.failed_exports.items()) |entry| {
entry.value.destroy(gpa);
}
self.failed_exports.deinit(gpa);
for (self.decl_exports.items()) |entry| {
const export_list = entry.value;
gpa.free(export_list);
}
self.decl_exports.deinit(gpa);
for (self.export_owners.items()) |entry| {
freeExportList(gpa, entry.value);
}
self.export_owners.deinit(gpa);
self.symbol_exports.deinit(gpa);
self.root_scope.destroy(gpa);
var it = self.global_error_set.iterator();
while (it.next()) |entry| {
gpa.free(entry.key);
}
self.global_error_set.deinit(gpa);
for (self.import_table.items()) |entry| {
entry.value.base.destroy(gpa);
}
self.import_table.deinit(gpa);
}
fn freeExportList(gpa: *Allocator, export_list: []*Export) void {
for (export_list) |exp| {
gpa.free(exp.options.name);
gpa.destroy(exp);
}
gpa.free(export_list);
}
pub fn ensureDeclAnalyzed(self: *Module, decl: *Decl) InnerError!void {
const tracy = trace(@src());
defer tracy.end();
const subsequent_analysis = switch (decl.analysis) {
.in_progress => unreachable,
.sema_failure,
.sema_failure_retryable,
.codegen_failure,
.dependency_failure,
.codegen_failure_retryable,
=> return error.AnalysisFail,
.complete => return,
.outdated => blk: {
log.debug("re-analyzing {}\n", .{decl.name});
// The exports this Decl performs will be re-discovered, so we remove them here
// prior to re-analysis.
self.deleteDeclExports(decl);
// Dependencies will be re-discovered, so we remove them here prior to re-analysis.
for (decl.dependencies.items()) |entry| {
const dep = entry.key;
dep.removeDependant(decl);
if (dep.dependants.items().len == 0 and !dep.deletion_flag) {
// We don't perform a deletion here, because this Decl or another one
// may end up referencing it before the update is complete.
dep.deletion_flag = true;
try self.deletion_set.append(self.gpa, dep);
}
}
decl.dependencies.clearRetainingCapacity();
break :blk true;
},
.unreferenced => false,
};
const type_changed = if (self.root_scope.cast(Scope.ZIRModule)) |zir_module|
try zir_sema.analyzeZirDecl(self, decl, zir_module.contents.module.decls[decl.src_index])
else
self.astGenAndAnalyzeDecl(decl) catch |err| switch (err) {
error.OutOfMemory => return error.OutOfMemory,
error.AnalysisFail => return error.AnalysisFail,
else => {
try self.failed_decls.ensureCapacity(self.gpa, self.failed_decls.items().len + 1);
self.failed_decls.putAssumeCapacityNoClobber(decl, try Compilation.ErrorMsg.create(
self.gpa,
decl.src(),
"unable to analyze: {}",
.{@errorName(err)},
));
decl.analysis = .sema_failure_retryable;
return error.AnalysisFail;
},
};
if (subsequent_analysis) {
// We may need to chase the dependants and re-analyze them.
// However, if the decl is a function, and the type is the same, we do not need to.
if (type_changed or decl.typed_value.most_recent.typed_value.val.tag() != .function) {
for (decl.dependants.items()) |entry| {
const dep = entry.key;
switch (dep.analysis) {
.unreferenced => unreachable,
.in_progress => unreachable,
.outdated => continue, // already queued for update
.dependency_failure,
.sema_failure,
.sema_failure_retryable,
.codegen_failure,
.codegen_failure_retryable,
.complete,
=> if (dep.generation != self.generation) {
try self.markOutdatedDecl(dep);
},
}
}
}
}
}
fn astGenAndAnalyzeDecl(self: *Module, decl: *Decl) !bool {
const tracy = trace(@src());
defer tracy.end();
const container_scope = decl.scope.cast(Scope.Container).?;
const tree = try self.getAstTree(container_scope);
const ast_node = tree.root_node.decls()[decl.src_index];
switch (ast_node.tag) {
.FnProto => {
const fn_proto = @fieldParentPtr(ast.Node.FnProto, "base", ast_node);
decl.analysis = .in_progress;
// This arena allocator's memory is discarded at the end of this function. It is used
// to determine the type of the function, and hence the type of the decl, which is needed
// to complete the Decl analysis.
var fn_type_scope_arena = std.heap.ArenaAllocator.init(self.gpa);
defer fn_type_scope_arena.deinit();