authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2020-06-08 18:29:12-04:00
committergravatar for noreply@github.comGitHub <noreply@github.com> 2020-06-08 18:29:12-04:00
logd2278f21560014c635afe4bc247a9096ecb845de
treee8bca82dcc8d09f6f287054b4c2ba171c190bf37
parent0ff5d7b24e2017199566d1bab75254fa5ef68611
parent05d284c842a5ba21cd836c2b212daa24227a9177
signaturebadge-question-mark Signed by PGP key 4AEE18F83AFDEB23

Merge pull request #5566 from ziglang/stage2-garbage-collect-decls

Stage2 garbage collect decls

12 files changed, 1043 insertions(+), 445 deletions(-)

lib/std/comptime_string_map.zig+24-24
......@@ -17,18 +17,18 @@ pub fn ComptimeStringMap(comptime V: type, comptime kvs: var) type {
1717 };
1818 var sorted_kvs: [kvs.len]KV = undefined;
1919 const lenAsc = (struct {
20 fn lenAsc(a: KV, b: KV) bool {
20 fn lenAsc(context: void, a: KV, b: KV) bool {
2121 return a.key.len < b.key.len;
2222 }
2323 }).lenAsc;
2424 for (kvs) |kv, i| {
2525 if (V != void) {
26 sorted_kvs[i] = .{.key = kv.@"0", .value = kv.@"1"};
26 sorted_kvs[i] = .{ .key = kv.@"0", .value = kv.@"1" };
2727 } else {
28 sorted_kvs[i] = .{.key = kv.@"0", .value = {}};
28 sorted_kvs[i] = .{ .key = kv.@"0", .value = {} };
2929 }
3030 }
31 std.sort.sort(KV, &sorted_kvs, lenAsc);
31 std.sort.sort(KV, &sorted_kvs, {}, lenAsc);
3232 const min_len = sorted_kvs[0].key.len;
3333 const max_len = sorted_kvs[sorted_kvs.len - 1].key.len;
3434 var len_indexes: [max_len + 1]usize = undefined;
......@@ -83,11 +83,11 @@ const TestEnum = enum {
8383
8484test "ComptimeStringMap list literal of list literals" {
8585 const map = ComptimeStringMap(TestEnum, .{
86 .{"these", .D},
87 .{"have", .A},
88 .{"nothing", .B},
89 .{"incommon", .C},
90 .{"samelen", .E},
86 .{ "these", .D },
87 .{ "have", .A },
88 .{ "nothing", .B },
89 .{ "incommon", .C },
90 .{ "samelen", .E },
9191 });
9292
9393 testMap(map);
......@@ -99,11 +99,11 @@ test "ComptimeStringMap array of structs" {
9999 @"1": TestEnum,
100100 };
101101 const map = ComptimeStringMap(TestEnum, [_]KV{
102 .{.@"0" = "these", .@"1" = .D},
103 .{.@"0" = "have", .@"1" = .A},
104 .{.@"0" = "nothing", .@"1" = .B},
105 .{.@"0" = "incommon", .@"1" = .C},
106 .{.@"0" = "samelen", .@"1" = .E},
102 .{ .@"0" = "these", .@"1" = .D },
103 .{ .@"0" = "have", .@"1" = .A },
104 .{ .@"0" = "nothing", .@"1" = .B },
105 .{ .@"0" = "incommon", .@"1" = .C },
106 .{ .@"0" = "samelen", .@"1" = .E },
107107 });
108108
109109 testMap(map);
......@@ -115,11 +115,11 @@ test "ComptimeStringMap slice of structs" {
115115 @"1": TestEnum,
116116 };
117117 const slice: []const KV = &[_]KV{
118 .{.@"0" = "these", .@"1" = .D},
119 .{.@"0" = "have", .@"1" = .A},
120 .{.@"0" = "nothing", .@"1" = .B},
121 .{.@"0" = "incommon", .@"1" = .C},
122 .{.@"0" = "samelen", .@"1" = .E},
118 .{ .@"0" = "these", .@"1" = .D },
119 .{ .@"0" = "have", .@"1" = .A },
120 .{ .@"0" = "nothing", .@"1" = .B },
121 .{ .@"0" = "incommon", .@"1" = .C },
122 .{ .@"0" = "samelen", .@"1" = .E },
123123 };
124124 const map = ComptimeStringMap(TestEnum, slice);
125125
......@@ -142,11 +142,11 @@ test "ComptimeStringMap void value type, slice of structs" {
142142 @"0": []const u8,
143143 };
144144 const slice: []const KV = &[_]KV{
145 .{.@"0" = "these"},
146 .{.@"0" = "have"},
147 .{.@"0" = "nothing"},
148 .{.@"0" = "incommon"},
149 .{.@"0" = "samelen"},
145 .{ .@"0" = "these" },
146 .{ .@"0" = "have" },
147 .{ .@"0" = "nothing" },
148 .{ .@"0" = "incommon" },
149 .{ .@"0" = "samelen" },
150150 };
151151 const map = ComptimeStringMap(void, slice);
152152
lib/std/debug.zig+3-3
......@@ -1003,7 +1003,7 @@ fn readMachODebugInfo(allocator: *mem.Allocator, macho_file: File) !ModuleDebugI
10031003 // Even though lld emits symbols in ascending order, this debug code
10041004 // should work for programs linked in any valid way.
10051005 // This sort is so that we can binary search later.
1006 std.sort.sort(MachoSymbol, symbols, MachoSymbol.addressLessThan);
1006 std.sort.sort(MachoSymbol, symbols, {}, MachoSymbol.addressLessThan);
10071007
10081008 return ModuleDebugInfo{
10091009 .base_address = undefined,
......@@ -1058,7 +1058,7 @@ const MachoSymbol = struct {
10581058 return self.nlist.n_value;
10591059 }
10601060
1061 fn addressLessThan(lhs: MachoSymbol, rhs: MachoSymbol) bool {
1061 fn addressLessThan(context: void, lhs: MachoSymbol, rhs: MachoSymbol) bool {
10621062 return lhs.address() < rhs.address();
10631063 }
10641064};
......@@ -1300,7 +1300,7 @@ pub const DebugInfo = struct {
13001300 fs.cwd().openFile(ctx.name, .{ .intended_io_mode = .blocking })
13011301 else
13021302 fs.openSelfExe(.{ .intended_io_mode = .blocking });
1303
1303
13041304 const elf_file = copy catch |err| switch (err) {
13051305 error.FileNotFound => return error.MissingDebugInfo,
13061306 else => return err,
lib/std/http/headers.zig+2-2
......@@ -58,7 +58,7 @@ const HeaderEntry = struct {
5858 self.never_index = never_index orelse never_index_default(self.name);
5959 }
6060
61 fn compare(a: HeaderEntry, b: HeaderEntry) bool {
61 fn compare(context: void, a: HeaderEntry, b: HeaderEntry) bool {
6262 if (a.name.ptr != b.name.ptr and a.name.len != b.name.len) {
6363 // Things beginning with a colon *must* be before others
6464 const a_is_colon = a.name[0] == ':';
......@@ -342,7 +342,7 @@ pub const Headers = struct {
342342 }
343343
344344 pub fn sort(self: *Self) void {
345 std.sort.sort(HeaderEntry, self.data.items, HeaderEntry.compare);
345 std.sort.sort(HeaderEntry, self.data.items, {}, HeaderEntry.compare);
346346 self.rebuild_index();
347347 }
348348
lib/std/net.zig+2-2
......@@ -836,7 +836,7 @@ fn linuxLookupName(
836836 key |= (MAXADDRS - @intCast(i32, i)) << DAS_ORDER_SHIFT;
837837 addr.sortkey = key;
838838 }
839 std.sort.sort(LookupAddr, addrs.span(), addrCmpLessThan);
839 std.sort.sort(LookupAddr, addrs.span(), {}, addrCmpLessThan);
840840}
841841
842842const Policy = struct {
......@@ -953,7 +953,7 @@ fn IN6_IS_ADDR_SITELOCAL(a: [16]u8) bool {
953953}
954954
955955// Parameters `b` and `a` swapped to make this descending.
956fn addrCmpLessThan(b: LookupAddr, a: LookupAddr) bool {
956fn addrCmpLessThan(context: void, b: LookupAddr, a: LookupAddr) bool {
957957 return a.sortkey < b.sortkey;
958958}
959959
lib/std/sort.zig+351-219
......@@ -5,7 +5,13 @@ const mem = std.mem;
55const math = std.math;
66const builtin = @import("builtin");
77
8pub fn binarySearch(comptime T: type, key: T, items: []const T, comptime compareFn: fn (lhs: T, rhs: T) math.Order) ?usize {
8pub fn binarySearch(
9 comptime T: type,
10 key: T,
11 items: []const T,
12 context: var,
13 comptime compareFn: fn (context: @TypeOf(context), lhs: T, rhs: T) math.Order,
14) ?usize {
915 var left: usize = 0;
1016 var right: usize = items.len;
1117
......@@ -13,7 +19,7 @@ pub fn binarySearch(comptime T: type, key: T, items: []const T, comptime compare
1319 // Avoid overflowing in the midpoint calculation
1420 const mid = left + (right - left) / 2;
1521 // Compare the key with the midpoint element
16 switch (compareFn(key, items[mid])) {
22 switch (compareFn(context, key, items[mid])) {
1723 .eq => return mid,
1824 .gt => left = mid + 1,
1925 .lt => right = mid,
......@@ -23,56 +29,61 @@ pub fn binarySearch(comptime T: type, key: T, items: []const T, comptime compare
2329 return null;
2430}
2531
26test "std.sort.binarySearch" {
32test "binarySearch" {
2733 const S = struct {
28 fn order_u32(lhs: u32, rhs: u32) math.Order {
34 fn order_u32(context: void, lhs: u32, rhs: u32) math.Order {
2935 return math.order(lhs, rhs);
3036 }
31 fn order_i32(lhs: i32, rhs: i32) math.Order {
37 fn order_i32(context: void, lhs: i32, rhs: i32) math.Order {
3238 return math.order(lhs, rhs);
3339 }
3440 };
3541 testing.expectEqual(
3642 @as(?usize, null),
37 binarySearch(u32, 1, &[_]u32{}, S.order_u32),
43 binarySearch(u32, 1, &[_]u32{}, {}, S.order_u32),
3844 );
3945 testing.expectEqual(
4046 @as(?usize, 0),
41 binarySearch(u32, 1, &[_]u32{1}, S.order_u32),
47 binarySearch(u32, 1, &[_]u32{1}, {}, S.order_u32),
4248 );
4349 testing.expectEqual(
4450 @as(?usize, null),
45 binarySearch(u32, 1, &[_]u32{0}, S.order_u32),
51 binarySearch(u32, 1, &[_]u32{0}, {}, S.order_u32),
4652 );
4753 testing.expectEqual(
4854 @as(?usize, null),
49 binarySearch(u32, 0, &[_]u32{1}, S.order_u32),
55 binarySearch(u32, 0, &[_]u32{1}, {}, S.order_u32),
5056 );
5157 testing.expectEqual(
5258 @as(?usize, 4),
53 binarySearch(u32, 5, &[_]u32{ 1, 2, 3, 4, 5 }, S.order_u32),
59 binarySearch(u32, 5, &[_]u32{ 1, 2, 3, 4, 5 }, {}, S.order_u32),
5460 );
5561 testing.expectEqual(
5662 @as(?usize, 0),
57 binarySearch(u32, 2, &[_]u32{ 2, 4, 8, 16, 32, 64 }, S.order_u32),
63 binarySearch(u32, 2, &[_]u32{ 2, 4, 8, 16, 32, 64 }, {}, S.order_u32),
5864 );
5965 testing.expectEqual(
6066 @as(?usize, 1),
61 binarySearch(i32, -4, &[_]i32{ -7, -4, 0, 9, 10 }, S.order_i32),
67 binarySearch(i32, -4, &[_]i32{ -7, -4, 0, 9, 10 }, {}, S.order_i32),
6268 );
6369 testing.expectEqual(
6470 @as(?usize, 3),
65 binarySearch(i32, 98, &[_]i32{ -100, -25, 2, 98, 99, 100 }, S.order_i32),
71 binarySearch(i32, 98, &[_]i32{ -100, -25, 2, 98, 99, 100 }, {}, S.order_i32),
6672 );
6773}
6874
6975/// Stable in-place sort. O(n) best case, O(pow(n, 2)) worst case. O(1) memory (no allocator required).
70pub fn insertionSort(comptime T: type, items: []T, lessThan: fn (lhs: T, rhs: T) bool) void {
76pub fn insertionSort(
77 comptime T: type,
78 items: []T,
79 context: var,
80 comptime lessThan: fn (context: @TypeOf(context), lhs: T, rhs: T) bool,
81) void {
7182 var i: usize = 1;
7283 while (i < items.len) : (i += 1) {
7384 const x = items[i];
7485 var j: usize = i;
75 while (j > 0 and lessThan(x, items[j - 1])) : (j -= 1) {
86 while (j > 0 and lessThan(context, x, items[j - 1])) : (j -= 1) {
7687 items[j] = items[j - 1];
7788 }
7889 items[j] = x;
......@@ -168,20 +179,25 @@ const Pull = struct {
168179
169180/// Stable in-place sort. O(n) best case, O(n*log(n)) worst case and average case. O(1) memory (no allocator required).
170181/// Currently implemented as block sort.
171pub fn sort(comptime T: type, items: []T, lessThan: fn (lhs: T, rhs: T) bool) void {
182pub fn sort(
183 comptime T: type,
184 items: []T,
185 context: var,
186 comptime lessThan: fn (context: @TypeOf(context), lhs: T, rhs: T) bool,
187) void {
172188 // Implementation ported from https://github.com/BonzaiThePenguin/WikiSort/blob/master/WikiSort.c
173189 var cache: [512]T = undefined;
174190
175191 if (items.len < 4) {
176192 if (items.len == 3) {
177193 // hard coded insertion sort
178 if (lessThan(items[1], items[0])) mem.swap(T, &items[0], &items[1]);
179 if (lessThan(items[2], items[1])) {
194 if (lessThan(context, items[1], items[0])) mem.swap(T, &items[0], &items[1]);
195 if (lessThan(context, items[2], items[1])) {
180196 mem.swap(T, &items[1], &items[2]);
181 if (lessThan(items[1], items[0])) mem.swap(T, &items[0], &items[1]);
197 if (lessThan(context, items[1], items[0])) mem.swap(T, &items[0], &items[1]);
182198 }
183199 } else if (items.len == 2) {
184 if (lessThan(items[1], items[0])) mem.swap(T, &items[0], &items[1]);
200 if (lessThan(context, items[1], items[0])) mem.swap(T, &items[0], &items[1]);
185201 }
186202 return;
187203 }
......@@ -197,75 +213,75 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn (lhs: T, rhs: T) bool) vo
197213 const sliced_items = items[range.start..];
198214 switch (range.length()) {
199215 8 => {
200 swap(T, sliced_items, lessThan, &order, 0, 1);
201 swap(T, sliced_items, lessThan, &order, 2, 3);
202 swap(T, sliced_items, lessThan, &order, 4, 5);
203 swap(T, sliced_items, lessThan, &order, 6, 7);
204 swap(T, sliced_items, lessThan, &order, 0, 2);
205 swap(T, sliced_items, lessThan, &order, 1, 3);
206 swap(T, sliced_items, lessThan, &order, 4, 6);
207 swap(T, sliced_items, lessThan, &order, 5, 7);
208 swap(T, sliced_items, lessThan, &order, 1, 2);
209 swap(T, sliced_items, lessThan, &order, 5, 6);
210 swap(T, sliced_items, lessThan, &order, 0, 4);
211 swap(T, sliced_items, lessThan, &order, 3, 7);
212 swap(T, sliced_items, lessThan, &order, 1, 5);
213 swap(T, sliced_items, lessThan, &order, 2, 6);
214 swap(T, sliced_items, lessThan, &order, 1, 4);
215 swap(T, sliced_items, lessThan, &order, 3, 6);
216 swap(T, sliced_items, lessThan, &order, 2, 4);
217 swap(T, sliced_items, lessThan, &order, 3, 5);
218 swap(T, sliced_items, lessThan, &order, 3, 4);
216 swap(T, sliced_items, context, lessThan, &order, 0, 1);
217 swap(T, sliced_items, context, lessThan, &order, 2, 3);
218 swap(T, sliced_items, context, lessThan, &order, 4, 5);
219 swap(T, sliced_items, context, lessThan, &order, 6, 7);
220 swap(T, sliced_items, context, lessThan, &order, 0, 2);
221 swap(T, sliced_items, context, lessThan, &order, 1, 3);
222 swap(T, sliced_items, context, lessThan, &order, 4, 6);
223 swap(T, sliced_items, context, lessThan, &order, 5, 7);
224 swap(T, sliced_items, context, lessThan, &order, 1, 2);
225 swap(T, sliced_items, context, lessThan, &order, 5, 6);
226 swap(T, sliced_items, context, lessThan, &order, 0, 4);
227 swap(T, sliced_items, context, lessThan, &order, 3, 7);
228 swap(T, sliced_items, context, lessThan, &order, 1, 5);
229 swap(T, sliced_items, context, lessThan, &order, 2, 6);
230 swap(T, sliced_items, context, lessThan, &order, 1, 4);
231 swap(T, sliced_items, context, lessThan, &order, 3, 6);
232 swap(T, sliced_items, context, lessThan, &order, 2, 4);
233 swap(T, sliced_items, context, lessThan, &order, 3, 5);
234 swap(T, sliced_items, context, lessThan, &order, 3, 4);
219235 },
220236 7 => {
221 swap(T, sliced_items, lessThan, &order, 1, 2);
222 swap(T, sliced_items, lessThan, &order, 3, 4);
223 swap(T, sliced_items, lessThan, &order, 5, 6);
224 swap(T, sliced_items, lessThan, &order, 0, 2);
225 swap(T, sliced_items, lessThan, &order, 3, 5);
226 swap(T, sliced_items, lessThan, &order, 4, 6);
227 swap(T, sliced_items, lessThan, &order, 0, 1);
228 swap(T, sliced_items, lessThan, &order, 4, 5);
229 swap(T, sliced_items, lessThan, &order, 2, 6);
230 swap(T, sliced_items, lessThan, &order, 0, 4);
231 swap(T, sliced_items, lessThan, &order, 1, 5);
232 swap(T, sliced_items, lessThan, &order, 0, 3);
233 swap(T, sliced_items, lessThan, &order, 2, 5);
234 swap(T, sliced_items, lessThan, &order, 1, 3);
235 swap(T, sliced_items, lessThan, &order, 2, 4);
236 swap(T, sliced_items, lessThan, &order, 2, 3);
237 swap(T, sliced_items, context, lessThan, &order, 1, 2);
238 swap(T, sliced_items, context, lessThan, &order, 3, 4);
239 swap(T, sliced_items, context, lessThan, &order, 5, 6);
240 swap(T, sliced_items, context, lessThan, &order, 0, 2);
241 swap(T, sliced_items, context, lessThan, &order, 3, 5);
242 swap(T, sliced_items, context, lessThan, &order, 4, 6);
243 swap(T, sliced_items, context, lessThan, &order, 0, 1);
244 swap(T, sliced_items, context, lessThan, &order, 4, 5);
245 swap(T, sliced_items, context, lessThan, &order, 2, 6);
246 swap(T, sliced_items, context, lessThan, &order, 0, 4);
247 swap(T, sliced_items, context, lessThan, &order, 1, 5);
248 swap(T, sliced_items, context, lessThan, &order, 0, 3);
249 swap(T, sliced_items, context, lessThan, &order, 2, 5);
250 swap(T, sliced_items, context, lessThan, &order, 1, 3);
251 swap(T, sliced_items, context, lessThan, &order, 2, 4);
252 swap(T, sliced_items, context, lessThan, &order, 2, 3);
237253 },
238254 6 => {
239 swap(T, sliced_items, lessThan, &order, 1, 2);
240 swap(T, sliced_items, lessThan, &order, 4, 5);
241 swap(T, sliced_items, lessThan, &order, 0, 2);
242 swap(T, sliced_items, lessThan, &order, 3, 5);
243 swap(T, sliced_items, lessThan, &order, 0, 1);
244 swap(T, sliced_items, lessThan, &order, 3, 4);
245 swap(T, sliced_items, lessThan, &order, 2, 5);
246 swap(T, sliced_items, lessThan, &order, 0, 3);
247 swap(T, sliced_items, lessThan, &order, 1, 4);
248 swap(T, sliced_items, lessThan, &order, 2, 4);
249 swap(T, sliced_items, lessThan, &order, 1, 3);
250 swap(T, sliced_items, lessThan, &order, 2, 3);
255 swap(T, sliced_items, context, lessThan, &order, 1, 2);
256 swap(T, sliced_items, context, lessThan, &order, 4, 5);
257 swap(T, sliced_items, context, lessThan, &order, 0, 2);
258 swap(T, sliced_items, context, lessThan, &order, 3, 5);
259 swap(T, sliced_items, context, lessThan, &order, 0, 1);
260 swap(T, sliced_items, context, lessThan, &order, 3, 4);
261 swap(T, sliced_items, context, lessThan, &order, 2, 5);
262 swap(T, sliced_items, context, lessThan, &order, 0, 3);
263 swap(T, sliced_items, context, lessThan, &order, 1, 4);
264 swap(T, sliced_items, context, lessThan, &order, 2, 4);
265 swap(T, sliced_items, context, lessThan, &order, 1, 3);
266 swap(T, sliced_items, context, lessThan, &order, 2, 3);
251267 },
252268 5 => {
253 swap(T, sliced_items, lessThan, &order, 0, 1);
254 swap(T, sliced_items, lessThan, &order, 3, 4);
255 swap(T, sliced_items, lessThan, &order, 2, 4);
256 swap(T, sliced_items, lessThan, &order, 2, 3);
257 swap(T, sliced_items, lessThan, &order, 1, 4);
258 swap(T, sliced_items, lessThan, &order, 0, 3);
259 swap(T, sliced_items, lessThan, &order, 0, 2);
260 swap(T, sliced_items, lessThan, &order, 1, 3);
261 swap(T, sliced_items, lessThan, &order, 1, 2);
269 swap(T, sliced_items, context, lessThan, &order, 0, 1);
270 swap(T, sliced_items, context, lessThan, &order, 3, 4);
271 swap(T, sliced_items, context, lessThan, &order, 2, 4);
272 swap(T, sliced_items, context, lessThan, &order, 2, 3);
273 swap(T, sliced_items, context, lessThan, &order, 1, 4);
274 swap(T, sliced_items, context, lessThan, &order, 0, 3);
275 swap(T, sliced_items, context, lessThan, &order, 0, 2);
276 swap(T, sliced_items, context, lessThan, &order, 1, 3);
277 swap(T, sliced_items, context, lessThan, &order, 1, 2);
262278 },
263279 4 => {
264 swap(T, sliced_items, lessThan, &order, 0, 1);
265 swap(T, sliced_items, lessThan, &order, 2, 3);
266 swap(T, sliced_items, lessThan, &order, 0, 2);
267 swap(T, sliced_items, lessThan, &order, 1, 3);
268 swap(T, sliced_items, lessThan, &order, 1, 2);
280 swap(T, sliced_items, context, lessThan, &order, 0, 1);
281 swap(T, sliced_items, context, lessThan, &order, 2, 3);
282 swap(T, sliced_items, context, lessThan, &order, 0, 2);
283 swap(T, sliced_items, context, lessThan, &order, 1, 3);
284 swap(T, sliced_items, context, lessThan, &order, 1, 2);
269285 },
270286 else => {},
271287 }
......@@ -288,16 +304,16 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn (lhs: T, rhs: T) bool) vo
288304 var A2 = iterator.nextRange();
289305 var B2 = iterator.nextRange();
290306
291 if (lessThan(items[B1.end - 1], items[A1.start])) {
307 if (lessThan(context, items[B1.end - 1], items[A1.start])) {
292308 // the two ranges are in reverse order, so copy them in reverse order into the cache
293309 mem.copy(T, cache[B1.length()..], items[A1.start..A1.end]);
294310 mem.copy(T, cache[0..], items[B1.start..B1.end]);
295 } else if (lessThan(items[B1.start], items[A1.end - 1])) {
311 } else if (lessThan(context, items[B1.start], items[A1.end - 1])) {
296312 // these two ranges weren't already in order, so merge them into the cache
297 mergeInto(T, items, A1, B1, lessThan, cache[0..]);
313 mergeInto(T, items, A1, B1, context, lessThan, cache[0..]);
298314 } else {
299315 // if A1, B1, A2, and B2 are all in order, skip doing anything else
300 if (!lessThan(items[B2.start], items[A2.end - 1]) and !lessThan(items[A2.start], items[B1.end - 1])) continue;
316 if (!lessThan(context, items[B2.start], items[A2.end - 1]) and !lessThan(context, items[A2.start], items[B1.end - 1])) continue;
301317
302318 // copy A1 and B1 into the cache in the same order
303319 mem.copy(T, cache[0..], items[A1.start..A1.end]);
......@@ -306,13 +322,13 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn (lhs: T, rhs: T) bool) vo
306322 A1 = Range.init(A1.start, B1.end);
307323
308324 // merge A2 and B2 into the cache
309 if (lessThan(items[B2.end - 1], items[A2.start])) {
325 if (lessThan(context, items[B2.end - 1], items[A2.start])) {
310326 // the two ranges are in reverse order, so copy them in reverse order into the cache
311327 mem.copy(T, cache[A1.length() + B2.length() ..], items[A2.start..A2.end]);
312328 mem.copy(T, cache[A1.length()..], items[B2.start..B2.end]);
313 } else if (lessThan(items[B2.start], items[A2.end - 1])) {
329 } else if (lessThan(context, items[B2.start], items[A2.end - 1])) {
314330 // these two ranges weren't already in order, so merge them into the cache
315 mergeInto(T, items, A2, B2, lessThan, cache[A1.length()..]);
331 mergeInto(T, items, A2, B2, context, lessThan, cache[A1.length()..]);
316332 } else {
317333 // copy A2 and B2 into the cache in the same order
318334 mem.copy(T, cache[A1.length()..], items[A2.start..A2.end]);
......@@ -324,13 +340,13 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn (lhs: T, rhs: T) bool) vo
324340 const A3 = Range.init(0, A1.length());
325341 const B3 = Range.init(A1.length(), A1.length() + A2.length());
326342
327 if (lessThan(cache[B3.end - 1], cache[A3.start])) {
343 if (lessThan(context, cache[B3.end - 1], cache[A3.start])) {
328344 // the two ranges are in reverse order, so copy them in reverse order into the items
329345 mem.copy(T, items[A1.start + A2.length() ..], cache[A3.start..A3.end]);
330346 mem.copy(T, items[A1.start..], cache[B3.start..B3.end]);
331 } else if (lessThan(cache[B3.start], cache[A3.end - 1])) {
347 } else if (lessThan(context, cache[B3.start], cache[A3.end - 1])) {
332348 // these two ranges weren't already in order, so merge them back into the items
333 mergeInto(T, cache[0..], A3, B3, lessThan, items[A1.start..]);
349 mergeInto(T, cache[0..], A3, B3, context, lessThan, items[A1.start..]);
334350 } else {
335351 // copy A3 and B3 into the items in the same order
336352 mem.copy(T, items[A1.start..], cache[A3.start..A3.end]);
......@@ -347,13 +363,13 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn (lhs: T, rhs: T) bool) vo
347363 var A = iterator.nextRange();
348364 var B = iterator.nextRange();
349365
350 if (lessThan(items[B.end - 1], items[A.start])) {
366 if (lessThan(context, items[B.end - 1], items[A.start])) {
351367 // the two ranges are in reverse order, so a simple rotation should fix it
352368 mem.rotate(T, items[A.start..B.end], A.length());
353 } else if (lessThan(items[B.start], items[A.end - 1])) {
369 } else if (lessThan(context, items[B.start], items[A.end - 1])) {
354370 // these two ranges weren't already in order, so we'll need to merge them!
355371 mem.copy(T, cache[0..], items[A.start..A.end]);
356 mergeExternal(T, items, A, B, lessThan, cache[0..]);
372 mergeExternal(T, items, A, B, context, lessThan, cache[0..]);
357373 }
358374 }
359375 }
......@@ -435,7 +451,7 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn (lhs: T, rhs: T) bool) vo
435451 last = index;
436452 count += 1;
437453 }) {
438 index = findLastForward(T, items, items[last], Range.init(last + 1, A.end), lessThan, find - count);
454 index = findLastForward(T, items, items[last], Range.init(last + 1, A.end), context, lessThan, find - count);
439455 if (index == A.end) break;
440456 }
441457 index = last;
......@@ -493,7 +509,7 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn (lhs: T, rhs: T) bool) vo
493509 last = index - 1;
494510 count += 1;
495511 }) {
496 index = findFirstBackward(T, items, items[last], Range.init(B.start, last), lessThan, find - count);
512 index = findFirstBackward(T, items, items[last], Range.init(B.start, last), context, lessThan, find - count);
497513 if (index == B.start) break;
498514 }
499515 index = last;
......@@ -558,7 +574,7 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn (lhs: T, rhs: T) bool) vo
558574 index = pull[pull_index].from;
559575 count = 1;
560576 while (count < length) : (count += 1) {
561 index = findFirstBackward(T, items, items[index - 1], Range.init(pull[pull_index].to, pull[pull_index].from - (count - 1)), lessThan, length - count);
577 index = findFirstBackward(T, items, items[index - 1], Range.init(pull[pull_index].to, pull[pull_index].from - (count - 1)), context, lessThan, length - count);
562578 const range = Range.init(index + 1, pull[pull_index].from + 1);
563579 mem.rotate(T, items[range.start..range.end], range.length() - count);
564580 pull[pull_index].from = index + count;
......@@ -568,7 +584,7 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn (lhs: T, rhs: T) bool) vo
568584 index = pull[pull_index].from + 1;
569585 count = 1;
570586 while (count < length) : (count += 1) {
571 index = findLastForward(T, items, items[index], Range.init(index, pull[pull_index].to), lessThan, length - count);
587 index = findLastForward(T, items, items[index], Range.init(index, pull[pull_index].to), context, lessThan, length - count);
572588 const range = Range.init(pull[pull_index].from, index - 1);
573589 mem.rotate(T, items[range.start..range.end], count);
574590 pull[pull_index].from = index - 1 - count;
......@@ -615,10 +631,10 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn (lhs: T, rhs: T) bool) vo
615631 }
616632 }
617633
618 if (lessThan(items[B.end - 1], items[A.start])) {
634 if (lessThan(context, items[B.end - 1], items[A.start])) {
619635 // the two ranges are in reverse order, so a simple rotation should fix it
620636 mem.rotate(T, items[A.start..B.end], A.length());
621 } else if (lessThan(items[A.end], items[A.end - 1])) {
637 } else if (lessThan(context, items[A.end], items[A.end - 1])) {
622638 // these two ranges weren't already in order, so we'll need to merge them!
623639 var findA: usize = undefined;
624640
......@@ -656,16 +672,16 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn (lhs: T, rhs: T) bool) vo
656672 while (true) {
657673 // if there's a previous B block and the first value of the minimum A block is <= the last value of the previous B block,
658674 // then drop that minimum A block behind. or if there are no B blocks left then keep dropping the remaining A blocks.
659 if ((lastB.length() > 0 and !lessThan(items[lastB.end - 1], items[indexA])) or blockB.length() == 0) {
675 if ((lastB.length() > 0 and !lessThan(context, items[lastB.end - 1], items[indexA])) or blockB.length() == 0) {
660676 // figure out where to split the previous B block, and rotate it at the split
661 const B_split = binaryFirst(T, items, items[indexA], lastB, lessThan);
677 const B_split = binaryFirst(T, items, items[indexA], lastB, context, lessThan);
662678 const B_remaining = lastB.end - B_split;
663679
664680 // swap the minimum A block to the beginning of the rolling A blocks
665681 var minA = blockA.start;
666682 findA = minA + block_size;
667683 while (findA < blockA.end) : (findA += block_size) {
668 if (lessThan(items[findA], items[minA])) {
684 if (lessThan(context, items[findA], items[minA])) {
669685 minA = findA;
670686 }
671687 }
......@@ -681,11 +697,11 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn (lhs: T, rhs: T) bool) vo
681697 // or failing that we'll use a strictly in-place merge algorithm (MergeInPlace)
682698
683699 if (lastA.length() <= cache.len) {
684 mergeExternal(T, items, lastA, Range.init(lastA.end, B_split), lessThan, cache[0..]);
700 mergeExternal(T, items, lastA, Range.init(lastA.end, B_split), context, lessThan, cache[0..]);
685701 } else if (buffer2.length() > 0) {
686 mergeInternal(T, items, lastA, Range.init(lastA.end, B_split), lessThan, buffer2);
702 mergeInternal(T, items, lastA, Range.init(lastA.end, B_split), context, lessThan, buffer2);
687703 } else {
688 mergeInPlace(T, items, lastA, Range.init(lastA.end, B_split), lessThan);
704 mergeInPlace(T, items, lastA, Range.init(lastA.end, B_split), context, lessThan);
689705 }
690706
691707 if (buffer2.length() > 0 or block_size <= cache.len) {
......@@ -741,11 +757,11 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn (lhs: T, rhs: T) bool) vo
741757
742758 // merge the last A block with the remaining B values
743759 if (lastA.length() <= cache.len) {
744 mergeExternal(T, items, lastA, Range.init(lastA.end, B.end), lessThan, cache[0..]);
760 mergeExternal(T, items, lastA, Range.init(lastA.end, B.end), context, lessThan, cache[0..]);
745761 } else if (buffer2.length() > 0) {
746 mergeInternal(T, items, lastA, Range.init(lastA.end, B.end), lessThan, buffer2);
762 mergeInternal(T, items, lastA, Range.init(lastA.end, B.end), context, lessThan, buffer2);
747763 } else {
748 mergeInPlace(T, items, lastA, Range.init(lastA.end, B.end), lessThan);
764 mergeInPlace(T, items, lastA, Range.init(lastA.end, B.end), context, lessThan);
749765 }
750766 }
751767 }
......@@ -755,7 +771,7 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn (lhs: T, rhs: T) bool) vo
755771
756772 // while an unstable sort like quicksort could be applied here, in benchmarks it was consistently slightly slower than a simple insertion sort,
757773 // even for tens of millions of items. this may be because insertion sort is quite fast when the data is already somewhat sorted, like it is here
758 insertionSort(T, items[buffer2.start..buffer2.end], lessThan);
774 insertionSort(T, items[buffer2.start..buffer2.end], context, lessThan);
759775
760776 pull_index = 0;
761777 while (pull_index < 2) : (pull_index += 1) {
......@@ -764,7 +780,7 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn (lhs: T, rhs: T) bool) vo
764780 // the values were pulled out to the left, so redistribute them back to the right
765781 var buffer = Range.init(pull[pull_index].range.start, pull[pull_index].range.start + pull[pull_index].count);
766782 while (buffer.length() > 0) {
767 index = findFirstForward(T, items, items[buffer.start], Range.init(buffer.end, pull[pull_index].range.end), lessThan, unique);
783 index = findFirstForward(T, items, items[buffer.start], Range.init(buffer.end, pull[pull_index].range.end), context, lessThan, unique);
768784 const amount = index - buffer.end;
769785 mem.rotate(T, items[buffer.start..index], buffer.length());
770786 buffer.start += (amount + 1);
......@@ -775,7 +791,7 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn (lhs: T, rhs: T) bool) vo
775791 // the values were pulled out to the right, so redistribute them back to the left
776792 var buffer = Range.init(pull[pull_index].range.end - pull[pull_index].count, pull[pull_index].range.end);
777793 while (buffer.length() > 0) {
778 index = findLastBackward(T, items, items[buffer.end - 1], Range.init(pull[pull_index].range.start, buffer.start), lessThan, unique);
794 index = findLastBackward(T, items, items[buffer.end - 1], Range.init(pull[pull_index].range.start, buffer.start), context, lessThan, unique);
779795 const amount = buffer.start - index;
780796 mem.rotate(T, items[index..buffer.end], amount);
781797 buffer.start -= amount;
......@@ -792,7 +808,14 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn (lhs: T, rhs: T) bool) vo
792808}
793809
794810// merge operation without a buffer
795fn mergeInPlace(comptime T: type, items: []T, A_arg: Range, B_arg: Range, lessThan: fn (T, T) bool) void {
811fn mergeInPlace(
812 comptime T: type,
813 items: []T,
814 A_arg: Range,
815 B_arg: Range,
816 context: var,
817 comptime lessThan: fn (@TypeOf(context), T, T) bool,
818) void {
796819 if (A_arg.length() == 0 or B_arg.length() == 0) return;
797820
798821 // this just repeatedly binary searches into B and rotates A into position.
......@@ -818,7 +841,7 @@ fn mergeInPlace(comptime T: type, items: []T, A_arg: Range, B_arg: Range, lessTh
818841
819842 while (true) {
820843 // find the first place in B where the first item in A needs to be inserted
821 const mid = binaryFirst(T, items, items[A.start], B, lessThan);
844 const mid = binaryFirst(T, items, items[A.start], B, context, lessThan);
822845
823846 // rotate A into place
824847 const amount = mid - A.end;
......@@ -828,13 +851,21 @@ fn mergeInPlace(comptime T: type, items: []T, A_arg: Range, B_arg: Range, lessTh
828851 // calculate the new A and B ranges
829852 B.start = mid;
830853 A = Range.init(A.start + amount, B.start);
831 A.start = binaryLast(T, items, items[A.start], A, lessThan);
854 A.start = binaryLast(T, items, items[A.start], A, context, lessThan);
832855 if (A.length() == 0) break;
833856 }
834857}
835858
836859// merge operation using an internal buffer
837fn mergeInternal(comptime T: type, items: []T, A: Range, B: Range, lessThan: fn (T, T) bool, buffer: Range) void {
860fn mergeInternal(
861 comptime T: type,
862 items: []T,
863 A: Range,
864 B: Range,
865 context: var,
866 comptime lessThan: fn (@TypeOf(context), T, T) bool,
867 buffer: Range,
868) void {
838869 // whenever we find a value to add to the final array, swap it with the value that's already in that spot
839870 // when this algorithm is finished, 'buffer' will contain its original contents, but in a different order
840871 var A_count: usize = 0;
......@@ -843,7 +874,7 @@ fn mergeInternal(comptime T: type, items: []T, A: Range, B: Range, lessThan: fn
843874
844875 if (B.length() > 0 and A.length() > 0) {
845876 while (true) {
846 if (!lessThan(items[B.start + B_count], items[buffer.start + A_count])) {
877 if (!lessThan(context, items[B.start + B_count], items[buffer.start + A_count])) {
847878 mem.swap(T, &items[A.start + insert], &items[buffer.start + A_count]);
848879 A_count += 1;
849880 insert += 1;
......@@ -870,63 +901,102 @@ fn blockSwap(comptime T: type, items: []T, start1: usize, start2: usize, block_s
870901
871902// combine a linear search with a binary search to reduce the number of comparisons in situations
872903// where have some idea as to how many unique values there are and where the next value might be
873fn findFirstForward(comptime T: type, items: []T, value: T, range: Range, lessThan: fn (T, T) bool, unique: usize) usize {
904fn findFirstForward(
905 comptime T: type,
906 items: []T,
907 value: T,
908 range: Range,
909 context: var,
910 comptime lessThan: fn (@TypeOf(context), T, T) bool,
911 unique: usize,
912) usize {
874913 if (range.length() == 0) return range.start;
875914 const skip = math.max(range.length() / unique, @as(usize, 1));
876915
877916 var index = range.start + skip;
878 while (lessThan(items[index - 1], value)) : (index += skip) {
917 while (lessThan(context, items[index - 1], value)) : (index += skip) {
879918 if (index >= range.end - skip) {
880 return binaryFirst(T, items, value, Range.init(index, range.end), lessThan);
919 return binaryFirst(T, items, value, Range.init(index, range.end), context, lessThan);
881920 }
882921 }
883922
884 return binaryFirst(T, items, value, Range.init(index - skip, index), lessThan);
923 return binaryFirst(T, items, value, Range.init(index - skip, index), context, lessThan);
885924}
886925
887fn findFirstBackward(comptime T: type, items: []T, value: T, range: Range, lessThan: fn (T, T) bool, unique: usize) usize {
926fn findFirstBackward(
927 comptime T: type,
928 items: []T,
929 value: T,
930 range: Range,
931 context: var,
932 comptime lessThan: fn (@TypeOf(context), T, T) bool,
933 unique: usize,
934) usize {
888935 if (range.length() == 0) return range.start;
889936 const skip = math.max(range.length() / unique, @as(usize, 1));
890937
891938 var index = range.end - skip;
892 while (index > range.start and !lessThan(items[index - 1], value)) : (index -= skip) {
939 while (index > range.start and !lessThan(context, items[index - 1], value)) : (index -= skip) {
893940 if (index < range.start + skip) {
894 return binaryFirst(T, items, value, Range.init(range.start, index), lessThan);
941 return binaryFirst(T, items, value, Range.init(range.start, index), context, lessThan);
895942 }
896943 }
897944
898 return binaryFirst(T, items, value, Range.init(index, index + skip), lessThan);
945 return binaryFirst(T, items, value, Range.init(index, index + skip), context, lessThan);
899946}
900947
901fn findLastForward(comptime T: type, items: []T, value: T, range: Range, lessThan: fn (T, T) bool, unique: usize) usize {
948fn findLastForward(
949 comptime T: type,
950 items: []T,
951 value: T,
952 range: Range,
953 context: var,
954 comptime lessThan: fn (@TypeOf(context), T, T) bool,
955 unique: usize,
956) usize {
902957 if (range.length() == 0) return range.start;
903958 const skip = math.max(range.length() / unique, @as(usize, 1));
904959
905960 var index = range.start + skip;
906 while (!lessThan(value, items[index - 1])) : (index += skip) {
961 while (!lessThan(context, value, items[index - 1])) : (index += skip) {
907962 if (index >= range.end - skip) {
908 return binaryLast(T, items, value, Range.init(index, range.end), lessThan);
963 return binaryLast(T, items, value, Range.init(index, range.end), context, lessThan);
909964 }
910965 }
911966
912 return binaryLast(T, items, value, Range.init(index - skip, index), lessThan);
967 return binaryLast(T, items, value, Range.init(index - skip, index), context, lessThan);
913968}
914969
915fn findLastBackward(comptime T: type, items: []T, value: T, range: Range, lessThan: fn (T, T) bool, unique: usize) usize {
970fn findLastBackward(
971 comptime T: type,
972 items: []T,
973 value: T,
974 range: Range,
975 context: var,
976 comptime lessThan: fn (@TypeOf(context), T, T) bool,
977 unique: usize,
978) usize {
916979 if (range.length() == 0) return range.start;
917980 const skip = math.max(range.length() / unique, @as(usize, 1));
918981
919982 var index = range.end - skip;
920 while (index > range.start and lessThan(value, items[index - 1])) : (index -= skip) {
983 while (index > range.start and lessThan(context, value, items[index - 1])) : (index -= skip) {
921984 if (index < range.start + skip) {
922 return binaryLast(T, items, value, Range.init(range.start, index), lessThan);
985 return binaryLast(T, items, value, Range.init(range.start, index), context, lessThan);
923986 }
924987 }
925988
926 return binaryLast(T, items, value, Range.init(index, index + skip), lessThan);
989 return binaryLast(T, items, value, Range.init(index, index + skip), context, lessThan);
927990}
928991
929fn binaryFirst(comptime T: type, items: []T, value: T, range: Range, lessThan: fn (T, T) bool) usize {
992fn binaryFirst(
993 comptime T: type,
994 items: []T,
995 value: T,
996 range: Range,
997 context: var,
998 comptime lessThan: fn (@TypeOf(context), T, T) bool,
999) usize {
9301000 var curr = range.start;
9311001 var size = range.length();
9321002 if (range.start >= range.end) return range.end;
......@@ -935,14 +1005,21 @@ fn binaryFirst(comptime T: type, items: []T, value: T, range: Range, lessThan: f
9351005
9361006 size /= 2;
9371007 const mid = items[curr + size];
938 if (lessThan(mid, value)) {
1008 if (lessThan(context, mid, value)) {
9391009 curr += size + offset;
9401010 }
9411011 }
9421012 return curr;
9431013}
9441014
945fn binaryLast(comptime T: type, items: []T, value: T, range: Range, lessThan: fn (T, T) bool) usize {
1015fn binaryLast(
1016 comptime T: type,
1017 items: []T,
1018 value: T,
1019 range: Range,
1020 context: var,
1021 comptime lessThan: fn (@TypeOf(context), T, T) bool,
1022) usize {
9461023 var curr = range.start;
9471024 var size = range.length();
9481025 if (range.start >= range.end) return range.end;
......@@ -951,14 +1028,22 @@ fn binaryLast(comptime T: type, items: []T, value: T, range: Range, lessThan: fn
9511028
9521029 size /= 2;
9531030 const mid = items[curr + size];
954 if (!lessThan(value, mid)) {
1031 if (!lessThan(context, value, mid)) {
9551032 curr += size + offset;
9561033 }
9571034 }
9581035 return curr;
9591036}
9601037
961fn mergeInto(comptime T: type, from: []T, A: Range, B: Range, lessThan: fn (T, T) bool, into: []T) void {
1038fn mergeInto(
1039 comptime T: type,
1040 from: []T,
1041 A: Range,
1042 B: Range,
1043 context: var,
1044 comptime lessThan: fn (@TypeOf(context), T, T) bool,
1045 into: []T,
1046) void {
9621047 var A_index: usize = A.start;
9631048 var B_index: usize = B.start;
9641049 const A_last = A.end;
......@@ -966,7 +1051,7 @@ fn mergeInto(comptime T: type, from: []T, A: Range, B: Range, lessThan: fn (T, T
9661051 var insert_index: usize = 0;
9671052
9681053 while (true) {
969 if (!lessThan(from[B_index], from[A_index])) {
1054 if (!lessThan(context, from[B_index], from[A_index])) {
9701055 into[insert_index] = from[A_index];
9711056 A_index += 1;
9721057 insert_index += 1;
......@@ -988,7 +1073,15 @@ fn mergeInto(comptime T: type, from: []T, A: Range, B: Range, lessThan: fn (T, T
9881073 }
9891074}
9901075
991fn mergeExternal(comptime T: type, items: []T, A: Range, B: Range, lessThan: fn (T, T) bool, cache: []T) void {
1076fn mergeExternal(
1077 comptime T: type,
1078 items: []T,
1079 A: Range,
1080 B: Range,
1081 context: var,
1082 comptime lessThan: fn (@TypeOf(context), T, T) bool,
1083 cache: []T,
1084) void {
9921085 // A fits into the cache, so use that instead of the internal buffer
9931086 var A_index: usize = 0;
9941087 var B_index: usize = B.start;
......@@ -998,7 +1091,7 @@ fn mergeExternal(comptime T: type, items: []T, A: Range, B: Range, lessThan: fn
9981091
9991092 if (B.length() > 0 and A.length() > 0) {
10001093 while (true) {
1001 if (!lessThan(items[B_index], cache[A_index])) {
1094 if (!lessThan(context, items[B_index], cache[A_index])) {
10021095 items[insert_index] = cache[A_index];
10031096 A_index += 1;
10041097 insert_index += 1;
......@@ -1016,17 +1109,25 @@ fn mergeExternal(comptime T: type, items: []T, A: Range, B: Range, lessThan: fn
10161109 mem.copy(T, items[insert_index..], cache[A_index..A_last]);
10171110}
10181111
1019fn swap(comptime T: type, items: []T, lessThan: fn (lhs: T, rhs: T) bool, order: *[8]u8, x: usize, y: usize) void {
1020 if (lessThan(items[y], items[x]) or ((order.*)[x] > (order.*)[y] and !lessThan(items[x], items[y]))) {
1112fn swap(
1113 comptime T: type,
1114 items: []T,
1115 context: var,
1116 comptime lessThan: fn (@TypeOf(context), lhs: T, rhs: T) bool,
1117 order: *[8]u8,
1118 x: usize,
1119 y: usize,
1120) void {
1121 if (lessThan(context, items[y], items[x]) or ((order.*)[x] > (order.*)[y] and !lessThan(context, items[x], items[y]))) {
10211122 mem.swap(T, &items[x], &items[y]);
10221123 mem.swap(u8, &(order.*)[x], &(order.*)[y]);
10231124 }
10241125}
10251126
1026// Use these to generate a comparator function for a given type. e.g. `sort(u8, slice, asc(u8))`.
1027pub fn asc(comptime T: type) fn (T, T) bool {
1127/// Use to generate a comparator function for a given type. e.g. `sort(u8, slice, asc(u8))`.
1128pub fn asc(comptime T: type) fn (void, T, T) bool {
10281129 const impl = struct {
1029 fn inner(a: T, b: T) bool {
1130 fn inner(context: void, a: T, b: T) bool {
10301131 return a < b;
10311132 }
10321133 };
......@@ -1034,9 +1135,10 @@ pub fn asc(comptime T: type) fn (T, T) bool {
10341135 return impl.inner;
10351136}
10361137
1037pub fn desc(comptime T: type) fn (T, T) bool {
1138/// Use to generate a comparator function for a given type. e.g. `sort(u8, slice, asc(u8))`.
1139pub fn desc(comptime T: type) fn (void, T, T) bool {
10381140 const impl = struct {
1039 fn inner(a: T, b: T) bool {
1141 fn inner(context: void, a: T, b: T) bool {
10401142 return a > b;
10411143 }
10421144 };
......@@ -1085,7 +1187,7 @@ fn testStableSort() void {
10851187 },
10861188 };
10871189 for (cases) |*case| {
1088 insertionSort(IdAndValue, (case.*)[0..], cmpByValue);
1190 insertionSort(IdAndValue, (case.*)[0..], {}, cmpByValue);
10891191 for (case.*) |item, i| {
10901192 testing.expect(item.id == expected[i].id);
10911193 testing.expect(item.value == expected[i].value);
......@@ -1096,11 +1198,16 @@ const IdAndValue = struct {
10961198 id: usize,
10971199 value: i32,
10981200};
1099fn cmpByValue(a: IdAndValue, b: IdAndValue) bool {
1100 return asc(i32)(a.value, b.value);
1201fn cmpByValue(context: void, a: IdAndValue, b: IdAndValue) bool {
1202 return asc_i32(context, a.value, b.value);
11011203}
11021204
1103test "std.sort" {
1205const asc_u8 = asc(u8);
1206const asc_i32 = asc(i32);
1207const desc_u8 = desc(u8);
1208const desc_i32 = desc(i32);
1209
1210test "sort" {
11041211 const u8cases = [_][]const []const u8{
11051212 &[_][]const u8{
11061213 "",
......@@ -1132,7 +1239,7 @@ test "std.sort" {
11321239 var buf: [8]u8 = undefined;
11331240 const slice = buf[0..case[0].len];
11341241 mem.copy(u8, slice, case[0]);
1135 sort(u8, slice, asc(u8));
1242 sort(u8, slice, {}, asc_u8);
11361243 testing.expect(mem.eql(u8, slice, case[1]));
11371244 }
11381245
......@@ -1167,12 +1274,12 @@ test "std.sort" {
11671274 var buf: [8]i32 = undefined;
11681275 const slice = buf[0..case[0].len];
11691276 mem.copy(i32, slice, case[0]);
1170 sort(i32, slice, asc(i32));
1277 sort(i32, slice, {}, asc_i32);
11711278 testing.expect(mem.eql(i32, slice, case[1]));
11721279 }
11731280}
11741281
1175test "std.sort descending" {
1282test "sort descending" {
11761283 const rev_cases = [_][]const []const i32{
11771284 &[_][]const i32{
11781285 &[_]i32{},
......@@ -1204,14 +1311,14 @@ test "std.sort descending" {
12041311 var buf: [8]i32 = undefined;
12051312 const slice = buf[0..case[0].len];
12061313 mem.copy(i32, slice, case[0]);
1207 sort(i32, slice, desc(i32));
1314 sort(i32, slice, {}, desc_i32);
12081315 testing.expect(mem.eql(i32, slice, case[1]));
12091316 }
12101317}
12111318
12121319test "another sort case" {
12131320 var arr = [_]i32{ 5, 3, 1, 2, 4 };
1214 sort(i32, arr[0..], asc(i32));
1321 sort(i32, arr[0..], {}, asc_i32);
12151322
12161323 testing.expect(mem.eql(i32, &arr, &[_]i32{ 1, 2, 3, 4, 5 }));
12171324}
......@@ -1236,7 +1343,7 @@ fn fuzzTest(rng: *std.rand.Random) !void {
12361343 item.id = index;
12371344 item.value = rng.intRangeLessThan(i32, 0, 100);
12381345 }
1239 sort(IdAndValue, array, cmpByValue);
1346 sort(IdAndValue, array, {}, cmpByValue);
12401347
12411348 var index: usize = 1;
12421349 while (index < array.len) : (index += 1) {
......@@ -1248,7 +1355,12 @@ fn fuzzTest(rng: *std.rand.Random) !void {
12481355 }
12491356}
12501357
1251pub fn argMin(comptime T: type, items: []const T, lessThan: fn (lhs: T, rhs: T) bool) ?usize {
1358pub fn argMin(
1359 comptime T: type,
1360 items: []const T,
1361 context: var,
1362 comptime lessThan: fn (@TypeOf(context), lhs: T, rhs: T) bool,
1363) ?usize {
12521364 if (items.len == 0) {
12531365 return null;
12541366 }
......@@ -1256,7 +1368,7 @@ pub fn argMin(comptime T: type, items: []const T, lessThan: fn (lhs: T, rhs: T)
12561368 var smallest = items[0];
12571369 var smallest_index: usize = 0;
12581370 for (items[1..]) |item, i| {
1259 if (lessThan(item, smallest)) {
1371 if (lessThan(context, item, smallest)) {
12601372 smallest = item;
12611373 smallest_index = i + 1;
12621374 }
......@@ -1265,32 +1377,42 @@ pub fn argMin(comptime T: type, items: []const T, lessThan: fn (lhs: T, rhs: T)
12651377 return smallest_index;
12661378}
12671379
1268test "std.sort.argMin" {
1269 testing.expectEqual(@as(?usize, null), argMin(i32, &[_]i32{}, asc(i32)));
1270 testing.expectEqual(@as(?usize, 0), argMin(i32, &[_]i32{1}, asc(i32)));
1271 testing.expectEqual(@as(?usize, 0), argMin(i32, &[_]i32{ 1, 2, 3, 4, 5 }, asc(i32)));
1272 testing.expectEqual(@as(?usize, 3), argMin(i32, &[_]i32{ 9, 3, 8, 2, 5 }, asc(i32)));
1273 testing.expectEqual(@as(?usize, 0), argMin(i32, &[_]i32{ 1, 1, 1, 1, 1 }, asc(i32)));
1274 testing.expectEqual(@as(?usize, 0), argMin(i32, &[_]i32{ -10, 1, 10 }, asc(i32)));
1275 testing.expectEqual(@as(?usize, 3), argMin(i32, &[_]i32{ 6, 3, 5, 7, 6 }, desc(i32)));
1380test "argMin" {
1381 testing.expectEqual(@as(?usize, null), argMin(i32, &[_]i32{}, {}, asc_i32));
1382 testing.expectEqual(@as(?usize, 0), argMin(i32, &[_]i32{1}, {}, asc_i32));
1383 testing.expectEqual(@as(?usize, 0), argMin(i32, &[_]i32{ 1, 2, 3, 4, 5 }, {}, asc_i32));
1384 testing.expectEqual(@as(?usize, 3), argMin(i32, &[_]i32{ 9, 3, 8, 2, 5 }, {}, asc_i32));
1385 testing.expectEqual(@as(?usize, 0), argMin(i32, &[_]i32{ 1, 1, 1, 1, 1 }, {}, asc_i32));
1386 testing.expectEqual(@as(?usize, 0), argMin(i32, &[_]i32{ -10, 1, 10 }, {}, asc_i32));
1387 testing.expectEqual(@as(?usize, 3), argMin(i32, &[_]i32{ 6, 3, 5, 7, 6 }, {}, desc_i32));
12761388}
12771389
1278pub fn min(comptime T: type, items: []const T, lessThan: fn (lhs: T, rhs: T) bool) ?T {
1279 const i = argMin(T, items, lessThan) orelse return null;
1390pub fn min(
1391 comptime T: type,
1392 items: []const T,
1393 context: var,
1394 comptime lessThan: fn (context: @TypeOf(context), lhs: T, rhs: T) bool,
1395) ?T {
1396 const i = argMin(T, items, context, lessThan) orelse return null;
12801397 return items[i];
12811398}
12821399
1283test "std.sort.min" {
1284 testing.expectEqual(@as(?i32, null), min(i32, &[_]i32{}, asc(i32)));
1285 testing.expectEqual(@as(?i32, 1), min(i32, &[_]i32{1}, asc(i32)));
1286 testing.expectEqual(@as(?i32, 1), min(i32, &[_]i32{ 1, 2, 3, 4, 5 }, asc(i32)));
1287 testing.expectEqual(@as(?i32, 2), min(i32, &[_]i32{ 9, 3, 8, 2, 5 }, asc(i32)));
1288 testing.expectEqual(@as(?i32, 1), min(i32, &[_]i32{ 1, 1, 1, 1, 1 }, asc(i32)));
1289 testing.expectEqual(@as(?i32, -10), min(i32, &[_]i32{ -10, 1, 10 }, asc(i32)));
1290 testing.expectEqual(@as(?i32, 7), min(i32, &[_]i32{ 6, 3, 5, 7, 6 }, desc(i32)));
1400test "min" {
1401 testing.expectEqual(@as(?i32, null), min(i32, &[_]i32{}, {}, asc_i32));
1402 testing.expectEqual(@as(?i32, 1), min(i32, &[_]i32{1}, {}, asc_i32));
1403 testing.expectEqual(@as(?i32, 1), min(i32, &[_]i32{ 1, 2, 3, 4, 5 }, {}, asc_i32));
1404 testing.expectEqual(@as(?i32, 2), min(i32, &[_]i32{ 9, 3, 8, 2, 5 }, {}, asc_i32));
1405 testing.expectEqual(@as(?i32, 1), min(i32, &[_]i32{ 1, 1, 1, 1, 1 }, {}, asc_i32));
1406 testing.expectEqual(@as(?i32, -10), min(i32, &[_]i32{ -10, 1, 10 }, {}, asc_i32));
1407 testing.expectEqual(@as(?i32, 7), min(i32, &[_]i32{ 6, 3, 5, 7, 6 }, {}, desc_i32));
12911408}
12921409
1293pub fn argMax(comptime T: type, items: []const T, lessThan: fn (lhs: T, rhs: T) bool) ?usize {
1410pub fn argMax(
1411 comptime T: type,
1412 items: []const T,
1413 context: var,
1414 comptime lessThan: fn (context: @TypeOf(context), lhs: T, rhs: T) bool,
1415) ?usize {
12941416 if (items.len == 0) {
12951417 return null;
12961418 }
......@@ -1298,7 +1420,7 @@ pub fn argMax(comptime T: type, items: []const T, lessThan: fn (lhs: T, rhs: T)
12981420 var biggest = items[0];
12991421 var biggest_index: usize = 0;
13001422 for (items[1..]) |item, i| {
1301 if (lessThan(biggest, item)) {
1423 if (lessThan(context, biggest, item)) {
13021424 biggest = item;
13031425 biggest_index = i + 1;
13041426 }
......@@ -1307,35 +1429,45 @@ pub fn argMax(comptime T: type, items: []const T, lessThan: fn (lhs: T, rhs: T)
13071429 return biggest_index;
13081430}
13091431
1310test "std.sort.argMax" {
1311 testing.expectEqual(@as(?usize, null), argMax(i32, &[_]i32{}, asc(i32)));
1312 testing.expectEqual(@as(?usize, 0), argMax(i32, &[_]i32{1}, asc(i32)));
1313 testing.expectEqual(@as(?usize, 4), argMax(i32, &[_]i32{ 1, 2, 3, 4, 5 }, asc(i32)));
1314 testing.expectEqual(@as(?usize, 0), argMax(i32, &[_]i32{ 9, 3, 8, 2, 5 }, asc(i32)));
1315 testing.expectEqual(@as(?usize, 0), argMax(i32, &[_]i32{ 1, 1, 1, 1, 1 }, asc(i32)));
1316 testing.expectEqual(@as(?usize, 2), argMax(i32, &[_]i32{ -10, 1, 10 }, asc(i32)));
1317 testing.expectEqual(@as(?usize, 1), argMax(i32, &[_]i32{ 6, 3, 5, 7, 6 }, desc(i32)));
1432test "argMax" {
1433 testing.expectEqual(@as(?usize, null), argMax(i32, &[_]i32{}, {}, asc_i32));
1434 testing.expectEqual(@as(?usize, 0), argMax(i32, &[_]i32{1}, {}, asc_i32));
1435 testing.expectEqual(@as(?usize, 4), argMax(i32, &[_]i32{ 1, 2, 3, 4, 5 }, {}, asc_i32));
1436 testing.expectEqual(@as(?usize, 0), argMax(i32, &[_]i32{ 9, 3, 8, 2, 5 }, {}, asc_i32));
1437 testing.expectEqual(@as(?usize, 0), argMax(i32, &[_]i32{ 1, 1, 1, 1, 1 }, {}, asc_i32));
1438 testing.expectEqual(@as(?usize, 2), argMax(i32, &[_]i32{ -10, 1, 10 }, {}, asc_i32));
1439 testing.expectEqual(@as(?usize, 1), argMax(i32, &[_]i32{ 6, 3, 5, 7, 6 }, {}, desc_i32));
13181440}
13191441
1320pub fn max(comptime T: type, items: []const T, lessThan: fn (lhs: T, rhs: T) bool) ?T {
1321 const i = argMax(T, items, lessThan) orelse return null;
1442pub fn max(
1443 comptime T: type,
1444 items: []const T,
1445 context: var,
1446 comptime lessThan: fn (context: @TypeOf(context), lhs: T, rhs: T) bool,
1447) ?T {
1448 const i = argMax(T, items, context, lessThan) orelse return null;
13221449 return items[i];
13231450}
13241451
1325test "std.sort.max" {
1326 testing.expectEqual(@as(?i32, null), max(i32, &[_]i32{}, asc(i32)));
1327 testing.expectEqual(@as(?i32, 1), max(i32, &[_]i32{1}, asc(i32)));
1328 testing.expectEqual(@as(?i32, 5), max(i32, &[_]i32{ 1, 2, 3, 4, 5 }, asc(i32)));
1329 testing.expectEqual(@as(?i32, 9), max(i32, &[_]i32{ 9, 3, 8, 2, 5 }, asc(i32)));
1330 testing.expectEqual(@as(?i32, 1), max(i32, &[_]i32{ 1, 1, 1, 1, 1 }, asc(i32)));
1331 testing.expectEqual(@as(?i32, 10), max(i32, &[_]i32{ -10, 1, 10 }, asc(i32)));
1332 testing.expectEqual(@as(?i32, 3), max(i32, &[_]i32{ 6, 3, 5, 7, 6 }, desc(i32)));
1452test "max" {
1453 testing.expectEqual(@as(?i32, null), max(i32, &[_]i32{}, {}, asc_i32));
1454 testing.expectEqual(@as(?i32, 1), max(i32, &[_]i32{1}, {}, asc_i32));
1455 testing.expectEqual(@as(?i32, 5), max(i32, &[_]i32{ 1, 2, 3, 4, 5 }, {}, asc_i32));
1456 testing.expectEqual(@as(?i32, 9), max(i32, &[_]i32{ 9, 3, 8, 2, 5 }, {}, asc_i32));
1457 testing.expectEqual(@as(?i32, 1), max(i32, &[_]i32{ 1, 1, 1, 1, 1 }, {}, asc_i32));
1458 testing.expectEqual(@as(?i32, 10), max(i32, &[_]i32{ -10, 1, 10 }, {}, asc_i32));
1459 testing.expectEqual(@as(?i32, 3), max(i32, &[_]i32{ 6, 3, 5, 7, 6 }, {}, desc_i32));
13331460}
13341461
1335pub fn isSorted(comptime T: type, items: []const T, lessThan: fn (lhs: T, rhs: T) bool) bool {
1462pub fn isSorted(
1463 comptime T: type,
1464 items: []const T,
1465 context: var,
1466 comptime lessThan: fn (context: @TypeOf(context), lhs: T, rhs: T) bool,
1467) bool {
13361468 var i: usize = 1;
13371469 while (i < items.len) : (i += 1) {
1338 if (lessThan(items[i], items[i - 1])) {
1470 if (lessThan(context, items[i], items[i - 1])) {
13391471 return false;
13401472 }
13411473 }
......@@ -1343,29 +1475,29 @@ pub fn isSorted(comptime T: type, items: []const T, lessThan: fn (lhs: T, rhs: T
13431475 return true;
13441476}
13451477
1346test "std.sort.isSorted" {
1347 testing.expect(isSorted(i32, &[_]i32{}, asc(i32)));
1348 testing.expect(isSorted(i32, &[_]i32{10}, asc(i32)));
1349 testing.expect(isSorted(i32, &[_]i32{ 1, 2, 3, 4, 5 }, asc(i32)));
1350 testing.expect(isSorted(i32, &[_]i32{ -10, 1, 1, 1, 10 }, asc(i32)));
1478test "isSorted" {
1479 testing.expect(isSorted(i32, &[_]i32{}, {}, asc_i32));
1480 testing.expect(isSorted(i32, &[_]i32{10}, {}, asc_i32));
1481 testing.expect(isSorted(i32, &[_]i32{ 1, 2, 3, 4, 5 }, {}, asc_i32));
1482 testing.expect(isSorted(i32, &[_]i32{ -10, 1, 1, 1, 10 }, {}, asc_i32));
13511483
1352 testing.expect(isSorted(i32, &[_]i32{}, desc(i32)));
1353 testing.expect(isSorted(i32, &[_]i32{-20}, desc(i32)));
1354 testing.expect(isSorted(i32, &[_]i32{ 3, 2, 1, 0, -1 }, desc(i32)));
1355 testing.expect(isSorted(i32, &[_]i32{ 10, -10 }, desc(i32)));
1484 testing.expect(isSorted(i32, &[_]i32{}, {}, desc_i32));
1485 testing.expect(isSorted(i32, &[_]i32{-20}, {}, desc_i32));
1486 testing.expect(isSorted(i32, &[_]i32{ 3, 2, 1, 0, -1 }, {}, desc_i32));
1487 testing.expect(isSorted(i32, &[_]i32{ 10, -10 }, {}, desc_i32));
13561488
1357 testing.expect(isSorted(i32, &[_]i32{ 1, 1, 1, 1, 1 }, asc(i32)));
1358 testing.expect(isSorted(i32, &[_]i32{ 1, 1, 1, 1, 1 }, desc(i32)));
1489 testing.expect(isSorted(i32, &[_]i32{ 1, 1, 1, 1, 1 }, {}, asc_i32));
1490 testing.expect(isSorted(i32, &[_]i32{ 1, 1, 1, 1, 1 }, {}, desc_i32));
13591491
1360 testing.expectEqual(false, isSorted(i32, &[_]i32{ 5, 4, 3, 2, 1 }, asc(i32)));
1361 testing.expectEqual(false, isSorted(i32, &[_]i32{ 1, 2, 3, 4, 5 }, desc(i32)));
1492 testing.expectEqual(false, isSorted(i32, &[_]i32{ 5, 4, 3, 2, 1 }, {}, asc_i32));
1493 testing.expectEqual(false, isSorted(i32, &[_]i32{ 1, 2, 3, 4, 5 }, {}, desc_i32));
13621494
1363 testing.expect(isSorted(u8, "abcd", asc(u8)));
1364 testing.expect(isSorted(u8, "zyxw", desc(u8)));
1495 testing.expect(isSorted(u8, "abcd", {}, asc_u8));
1496 testing.expect(isSorted(u8, "zyxw", {}, desc_u8));
13651497
1366 testing.expectEqual(false, isSorted(u8, "abcd", desc(u8)));
1367 testing.expectEqual(false, isSorted(u8, "zyxw", asc(u8)));
1498 testing.expectEqual(false, isSorted(u8, "abcd", {}, desc_u8));
1499 testing.expectEqual(false, isSorted(u8, "zyxw", {}, asc_u8));
13681500
1369 testing.expect(isSorted(u8, "ffff", asc(u8)));
1370 testing.expect(isSorted(u8, "ffff", desc(u8)));
1501 testing.expect(isSorted(u8, "ffff", {}, asc_u8));
1502 testing.expect(isSorted(u8, "ffff", {}, desc_u8));
13711503}
src-self-hosted/Module.zig+57-12
......@@ -576,6 +576,8 @@ pub fn update(self: *Module) !void {
576576 // TODO Use the cache hash file system to detect which source files changed.
577577 // Here we simulate a full cache miss.
578578 // Analyze the root source file now.
579 // Source files could have been loaded for any reason; to force a refresh we unload now.
580 self.root_scope.unload(self.allocator);
579581 self.analyzeRoot(self.root_scope) catch |err| switch (err) {
580582 error.AnalysisFail => {
581583 assert(self.totalErrorCount() != 0);
......@@ -594,8 +596,11 @@ pub fn update(self: *Module) !void {
594596 try self.deleteDecl(decl);
595597 }
596598
597 // Unload all the source files from memory.
598 self.root_scope.unload(self.allocator);
599 // If there are any errors, we anticipate the source files being loaded
600 // to report error messages. Otherwise we unload all source files to save memory.
601 if (self.totalErrorCount() == 0) {
602 self.root_scope.unload(self.allocator);
603 }
599604
600605 try self.bin_file.flush();
601606 self.link_error_flags = self.bin_file.error_flags;
......@@ -668,8 +673,8 @@ pub fn getAllErrorsAlloc(self: *Module) !AllErrors {
668673 assert(errors.items.len == self.totalErrorCount());
669674
670675 return AllErrors{
671 .arena = arena.state,
672676 .list = try arena.allocator.dupe(AllErrors.Message, errors.items),
677 .arena = arena.state,
673678 };
674679}
675680
......@@ -878,11 +883,11 @@ fn analyzeRoot(self: *Module, root_scope: *Scope.ZIRModule) !void {
878883 const decl = kv.value;
879884 deleted_decls.removeAssertDiscard(decl);
880885 const new_contents_hash = Decl.hashSimpleName(src_decl.contents);
886 //std.debug.warn("'{}' contents: '{}'\n", .{ src_decl.name, src_decl.contents });
881887 if (!mem.eql(u8, &new_contents_hash, &decl.contents_hash)) {
882 //std.debug.warn("noticed '{}' source changed\n", .{src_decl.name});
883 decl.analysis = .outdated;
888 //std.debug.warn("'{}' {x} => {x}\n", .{ src_decl.name, decl.contents_hash, new_contents_hash });
889 try self.markOutdatedDecl(decl);
884890 decl.contents_hash = new_contents_hash;
885 try self.work_queue.writeItem(.{ .re_analyze_decl = decl });
886891 }
887892 } else if (src_decl.cast(zir.Inst.Export)) |export_inst| {
888893 try exports_to_resolve.append(&export_inst.base);
......@@ -905,6 +910,8 @@ fn analyzeRoot(self: *Module, root_scope: *Scope.ZIRModule) !void {
905910}
906911
907912fn deleteDecl(self: *Module, decl: *Decl) !void {
913 try self.deletion_set.ensureCapacity(self.allocator, self.deletion_set.items.len + decl.dependencies.items.len);
914
908915 //std.debug.warn("deleting decl '{}'\n", .{decl.name});
909916 const name_hash = decl.fullyQualifiedNameHash();
910917 self.decl_table.removeAssertDiscard(name_hash);
......@@ -916,17 +923,20 @@ fn deleteDecl(self: *Module, decl: *Decl) !void {
916923 // another reference to it may turn up.
917924 assert(!dep.deletion_flag);
918925 dep.deletion_flag = true;
919 try self.deletion_set.append(self.allocator, dep);
926 self.deletion_set.appendAssumeCapacity(dep);
920927 }
921928 }
922929 // Anything that depends on this deleted decl certainly needs to be re-analyzed.
923930 for (decl.dependants.items) |dep| {
924931 dep.removeDependency(decl);
925932 if (dep.analysis != .outdated) {
926 dep.analysis = .outdated;
927 try self.work_queue.writeItem(.{ .re_analyze_decl = dep });
933 // TODO Move this failure possibility to the top of the function.
934 try self.markOutdatedDecl(dep);
928935 }
929936 }
937 if (self.failed_decls.remove(decl)) |entry| {
938 entry.value.destroy(self.allocator);
939 }
930940 self.deleteDeclExports(decl);
931941 self.bin_file.freeDecl(decl);
932942 decl.destroy(self.allocator);
......@@ -1083,20 +1093,31 @@ fn reAnalyzeDecl(self: *Module, decl: *Decl, old_inst: *zir.Inst) InnerError!voi
10831093 .codegen_failure_retryable,
10841094 .complete,
10851095 => if (dep.generation != self.generation) {
1086 dep.analysis = .outdated;
1087 try self.work_queue.writeItem(.{ .re_analyze_decl = dep });
1096 try self.markOutdatedDecl(dep);
10881097 },
10891098 }
10901099 }
10911100 }
10921101}
10931102
1103fn markOutdatedDecl(self: *Module, decl: *Decl) !void {
1104 //std.debug.warn("mark {} outdated\n", .{decl.name});
1105 try self.work_queue.writeItem(.{ .re_analyze_decl = decl });
1106 if (self.failed_decls.remove(decl)) |entry| {
1107 entry.value.destroy(self.allocator);
1108 }
1109 decl.analysis = .outdated;
1110}
1111
10941112fn resolveDecl(self: *Module, scope: *Scope, old_inst: *zir.Inst) InnerError!*Decl {
10951113 const hash = Decl.hashSimpleName(old_inst.name);
10961114 if (self.decl_table.get(hash)) |kv| {
10971115 const decl = kv.value;
10981116 try self.reAnalyzeDecl(decl, old_inst);
10991117 return decl;
1118 } else if (old_inst.cast(zir.Inst.DeclVal)) |decl_val| {
1119 // This is just a named reference to another decl.
1120 return self.analyzeDeclVal(scope, decl_val);
11001121 } else {
11011122 const new_decl = blk: {
11021123 try self.decl_table.ensureCapacity(self.decl_table.size + 1);
......@@ -1442,7 +1463,9 @@ fn analyzeInst(self: *Module, scope: *Scope, old_inst: *zir.Inst) InnerError!*In
14421463 switch (old_inst.tag) {
14431464 .breakpoint => return self.analyzeInstBreakpoint(scope, old_inst.cast(zir.Inst.Breakpoint).?),
14441465 .call => return self.analyzeInstCall(scope, old_inst.cast(zir.Inst.Call).?),
1466 .compileerror => return self.analyzeInstCompileError(scope, old_inst.cast(zir.Inst.CompileError).?),
14451467 .declref => return self.analyzeInstDeclRef(scope, old_inst.cast(zir.Inst.DeclRef).?),
1468 .declval => return self.analyzeInstDeclVal(scope, old_inst.cast(zir.Inst.DeclVal).?),
14461469 .str => {
14471470 const bytes = old_inst.cast(zir.Inst.Str).?.positionals.bytes;
14481471 // The bytes references memory inside the ZIR module, which can get deallocated
......@@ -1480,6 +1503,10 @@ fn analyzeInst(self: *Module, scope: *Scope, old_inst: *zir.Inst) InnerError!*In
14801503 }
14811504}
14821505
1506fn analyzeInstCompileError(self: *Module, scope: *Scope, inst: *zir.Inst.CompileError) InnerError!*Inst {
1507 return self.fail(scope, inst.base.src, "{}", .{inst.positionals.msg});
1508}
1509
14831510fn analyzeInstBreakpoint(self: *Module, scope: *Scope, inst: *zir.Inst.Breakpoint) InnerError!*Inst {
14841511 const b = try self.requireRuntimeBlock(scope, inst.base.src);
14851512 return self.addNewInstArgs(b, inst.base.src, Type.initTag(.void), Inst.Breakpoint, Inst.Args(Inst.Breakpoint){});
......@@ -1501,6 +1528,24 @@ fn analyzeInstDeclRef(self: *Module, scope: *Scope, inst: *zir.Inst.DeclRef) Inn
15011528 return self.analyzeDeclRef(scope, inst.base.src, decl);
15021529}
15031530
1531fn analyzeDeclVal(self: *Module, scope: *Scope, inst: *zir.Inst.DeclVal) InnerError!*Decl {
1532 const decl_name = inst.positionals.name;
1533 // This will need to get more fleshed out when there are proper structs & namespaces.
1534 const zir_module = scope.namespace();
1535 const src_decl = zir_module.contents.module.findDecl(decl_name) orelse
1536 return self.fail(scope, inst.base.src, "use of undeclared identifier '{}'", .{decl_name});
1537
1538 const decl = try self.resolveCompleteDecl(scope, src_decl);
1539
1540 return decl;
1541}
1542
1543fn analyzeInstDeclVal(self: *Module, scope: *Scope, inst: *zir.Inst.DeclVal) InnerError!*Inst {
1544 const decl = try self.analyzeDeclVal(scope, inst);
1545 const ptr = try self.analyzeDeclRef(scope, inst.base.src, decl);
1546 return self.analyzeDeref(scope, inst.base.src, ptr, inst.base.src);
1547}
1548
15041549fn analyzeDeclRef(self: *Module, scope: *Scope, src: usize, decl: *Decl) InnerError!*Inst {
15051550 const decl_tv = try decl.typedValue();
15061551 const ty_payload = try scope.arena().create(Type.Payload.SingleConstPointer);
......@@ -1621,7 +1666,7 @@ fn analyzeInstFnType(self: *Module, scope: *Scope, fntype: *zir.Inst.FnType) Inn
16211666}
16221667
16231668fn analyzeInstPrimitive(self: *Module, scope: *Scope, primitive: *zir.Inst.Primitive) InnerError!*Inst {
1624 return self.constType(scope, primitive.base.src, primitive.positionals.tag.toType());
1669 return self.constInst(scope, primitive.base.src, primitive.positionals.tag.toTypedValue());
16251670}
16261671
16271672fn analyzeInstAs(self: *Module, scope: *Scope, as: *zir.Inst.As) InnerError!*Inst {
src-self-hosted/main.zig+15-1
......@@ -407,7 +407,21 @@ fn buildOutputType(
407407 std.debug.warn("-fno-emit-bin not supported yet", .{});
408408 process.exit(1);
409409 },
410 .yes_default_path => try std.fmt.allocPrint(arena, "{}{}", .{ root_name, target_info.target.exeFileExt() }),
410 .yes_default_path => switch (output_mode) {
411 .Exe => try std.fmt.allocPrint(arena, "{}{}", .{ root_name, target_info.target.exeFileExt() }),
412 .Lib => blk: {
413 const suffix = switch (link_mode orelse .Static) {
414 .Static => target_info.target.staticLibSuffix(),
415 .Dynamic => target_info.target.dynamicLibSuffix(),
416 };
417 break :blk try std.fmt.allocPrint(arena, "{}{}{}", .{
418 target_info.target.libPrefix(),
419 root_name,
420 suffix,
421 });
422 },
423 .Obj => try std.fmt.allocPrint(arena, "{}{}", .{ root_name, target_info.target.oFileExt() }),
424 },
411425 .yes => |p| p,
412426 };
413427
src-self-hosted/test.zig+111-29
......@@ -27,9 +27,32 @@ pub const TestContext = struct {
2727
2828 pub const ZIRTransformCase = struct {
2929 name: []const u8,
30 src: [:0]const u8,
31 expected_zir: []const u8,
3230 cross_target: std.zig.CrossTarget,
31 updates: std.ArrayList(Update),
32
33 pub const Update = struct {
34 expected: Expected,
35 src: [:0]const u8,
36 };
37
38 pub const Expected = union(enum) {
39 zir: []const u8,
40 errors: []const []const u8,
41 };
42
43 pub fn addZIR(case: *ZIRTransformCase, src: [:0]const u8, zir_text: []const u8) void {
44 case.updates.append(.{
45 .src = src,
46 .expected = .{ .zir = zir_text },
47 }) catch unreachable;
48 }
49
50 pub fn addError(case: *ZIRTransformCase, src: [:0]const u8, errors: []const []const u8) void {
51 case.updates.append(.{
52 .src = src,
53 .expected = .{ .errors = errors },
54 }) catch unreachable;
55 }
3356 };
3457
3558 pub fn addZIRCompareOutput(
......@@ -52,14 +75,32 @@ pub const TestContext = struct {
5275 src: [:0]const u8,
5376 expected_zir: []const u8,
5477 ) void {
55 ctx.zir_transform_cases.append(.{
78 const case = ctx.zir_transform_cases.addOne() catch unreachable;
79 case.* = .{
5680 .name = name,
57 .src = src,
58 .expected_zir = expected_zir,
5981 .cross_target = cross_target,
82 .updates = std.ArrayList(ZIRTransformCase.Update).init(std.heap.page_allocator),
83 };
84 case.updates.append(.{
85 .src = src,
86 .expected = .{ .zir = expected_zir },
6087 }) catch unreachable;
6188 }
6289
90 pub fn addZIRMulti(
91 ctx: *TestContext,
92 name: []const u8,
93 cross_target: std.zig.CrossTarget,
94 ) *ZIRTransformCase {
95 const case = ctx.zir_transform_cases.addOne() catch unreachable;
96 case.* = .{
97 .name = name,
98 .cross_target = cross_target,
99 .updates = std.ArrayList(ZIRTransformCase.Update).init(std.heap.page_allocator),
100 };
101 return case;
102 }
103
63104 fn init(self: *TestContext) !void {
64105 self.* = .{
65106 .zir_cmp_output_cases = std.ArrayList(ZIRCompareOutputCase).init(std.heap.page_allocator),
......@@ -178,13 +219,11 @@ pub const TestContext = struct {
178219 var tmp = std.testing.tmpDir(.{});
179220 defer tmp.cleanup();
180221
181 var prg_node = root_node.start(case.name, 3);
182 prg_node.activate();
183 defer prg_node.end();
222 var update_node = root_node.start(case.name, case.updates.items.len);
223 update_node.activate();
224 defer update_node.end();
184225
185226 const tmp_src_path = "test-case.zir";
186 try tmp.dir.writeFile(tmp_src_path, case.src);
187
188227 const root_pkg = try Package.create(allocator, tmp.dir, ".", tmp_src_path);
189228 defer root_pkg.destroy();
190229
......@@ -198,25 +237,68 @@ pub const TestContext = struct {
198237 });
199238 defer module.deinit();
200239
201 var module_node = prg_node.start("parse/analysis/codegen", null);
202 module_node.activate();
203 try module.update();
204 module_node.end();
205
206 var emit_node = prg_node.start("emit", null);
207 emit_node.activate();
208 var new_zir_module = try zir.emit(allocator, module);
209 defer new_zir_module.deinit(allocator);
210 emit_node.end();
211
212 var write_node = prg_node.start("write", null);
213 write_node.activate();
214 var out_zir = std.ArrayList(u8).init(allocator);
215 defer out_zir.deinit();
216 try new_zir_module.writeToStream(allocator, out_zir.outStream());
217 write_node.end();
218
219 std.testing.expectEqualSlices(u8, case.expected_zir, out_zir.items);
240 for (case.updates.items) |update| {
241 var prg_node = update_node.start("", 3);
242 prg_node.activate();
243 defer prg_node.end();
244
245 try tmp.dir.writeFile(tmp_src_path, update.src);
246
247 var module_node = prg_node.start("parse/analysis/codegen", null);
248 module_node.activate();
249 try module.update();
250 module_node.end();
251
252 switch (update.expected) {
253 .zir => |expected_zir| {
254 var emit_node = prg_node.start("emit", null);
255 emit_node.activate();
256 var new_zir_module = try zir.emit(allocator, module);
257 defer new_zir_module.deinit(allocator);
258 emit_node.end();
259
260 var write_node = prg_node.start("write", null);
261 write_node.activate();
262 var out_zir = std.ArrayList(u8).init(allocator);
263 defer out_zir.deinit();
264 try new_zir_module.writeToStream(allocator, out_zir.outStream());
265 write_node.end();
266
267 std.testing.expectEqualSlices(u8, expected_zir, out_zir.items);
268 },
269 .errors => |expected_errors| {
270 var all_errors = try module.getAllErrorsAlloc();
271 defer all_errors.deinit(module.allocator);
272 for (expected_errors) |expected_error| {
273 for (all_errors.list) |full_err_msg| {
274 const text = try std.fmt.allocPrint(allocator, ":{}:{}: error: {}", .{
275 full_err_msg.line + 1,
276 full_err_msg.column + 1,
277 full_err_msg.msg,
278 });
279 defer allocator.free(text);
280 if (std.mem.eql(u8, text, expected_error)) {
281 break;
282 }
283 } else {
284 std.debug.warn(
285 "{}\nExpected this error:\n================\n{}\n================\nBut found these errors:\n================\n",
286 .{ case.name, expected_error },
287 );
288 for (all_errors.list) |full_err_msg| {
289 std.debug.warn(":{}:{}: error: {}\n", .{
290 full_err_msg.line + 1,
291 full_err_msg.column + 1,
292 full_err_msg.msg,
293 });
294 }
295 std.debug.warn("================\nTest failed\n", .{});
296 std.process.exit(1);
297 }
298 }
299 },
300 }
301 }
220302 }
221303};
222304
src-self-hosted/type.zig+22
......@@ -51,6 +51,7 @@ pub const Type = extern union {
5151 .comptime_float => return .ComptimeFloat,
5252 .noreturn => return .NoReturn,
5353 .@"null" => return .Null,
54 .@"undefined" => return .Undefined,
5455
5556 .fn_noreturn_no_args => return .Fn,
5657 .fn_naked_noreturn_no_args => return .Fn,
......@@ -201,6 +202,7 @@ pub const Type = extern union {
201202 => return out_stream.writeAll(@tagName(t)),
202203
203204 .@"null" => return out_stream.writeAll("@TypeOf(null)"),
205 .@"undefined" => return out_stream.writeAll("@TypeOf(undefined)"),
204206
205207 .const_slice_u8 => return out_stream.writeAll("[]const u8"),
206208 .fn_noreturn_no_args => return out_stream.writeAll("fn() noreturn"),
......@@ -265,6 +267,7 @@ pub const Type = extern union {
265267 .comptime_float => return Value.initTag(.comptime_float_type),
266268 .noreturn => return Value.initTag(.noreturn_type),
267269 .@"null" => return Value.initTag(.null_type),
270 .@"undefined" => return Value.initTag(.undefined_type),
268271 .fn_noreturn_no_args => return Value.initTag(.fn_noreturn_no_args_type),
269272 .fn_naked_noreturn_no_args => return Value.initTag(.fn_naked_noreturn_no_args_type),
270273 .fn_ccc_void_no_args => return Value.initTag(.fn_ccc_void_no_args_type),
......@@ -318,6 +321,7 @@ pub const Type = extern union {
318321 .comptime_float,
319322 .noreturn,
320323 .@"null",
324 .@"undefined",
321325 => false,
322326 };
323327 }
......@@ -378,6 +382,7 @@ pub const Type = extern union {
378382 .comptime_float,
379383 .noreturn,
380384 .@"null",
385 .@"undefined",
381386 => unreachable,
382387 };
383388 }
......@@ -410,6 +415,7 @@ pub const Type = extern union {
410415 .comptime_float,
411416 .noreturn,
412417 .@"null",
418 .@"undefined",
413419 .array,
414420 .array_u8_sentinel_0,
415421 .const_slice_u8,
......@@ -454,6 +460,7 @@ pub const Type = extern union {
454460 .comptime_float,
455461 .noreturn,
456462 .@"null",
463 .@"undefined",
457464 .array,
458465 .array_u8_sentinel_0,
459466 .single_const_pointer,
......@@ -498,6 +505,7 @@ pub const Type = extern union {
498505 .comptime_float,
499506 .noreturn,
500507 .@"null",
508 .@"undefined",
501509 .array,
502510 .array_u8_sentinel_0,
503511 .fn_noreturn_no_args,
......@@ -543,6 +551,7 @@ pub const Type = extern union {
543551 .comptime_float,
544552 .noreturn,
545553 .@"null",
554 .@"undefined",
546555 .fn_noreturn_no_args,
547556 .fn_naked_noreturn_no_args,
548557 .fn_ccc_void_no_args,
......@@ -586,6 +595,7 @@ pub const Type = extern union {
586595 .comptime_float,
587596 .noreturn,
588597 .@"null",
598 .@"undefined",
589599 .fn_noreturn_no_args,
590600 .fn_naked_noreturn_no_args,
591601 .fn_ccc_void_no_args,
......@@ -630,6 +640,7 @@ pub const Type = extern union {
630640 .comptime_float,
631641 .noreturn,
632642 .@"null",
643 .@"undefined",
633644 .fn_noreturn_no_args,
634645 .fn_naked_noreturn_no_args,
635646 .fn_ccc_void_no_args,
......@@ -662,6 +673,7 @@ pub const Type = extern union {
662673 .comptime_float,
663674 .noreturn,
664675 .@"null",
676 .@"undefined",
665677 .fn_noreturn_no_args,
666678 .fn_naked_noreturn_no_args,
667679 .fn_ccc_void_no_args,
......@@ -707,6 +719,7 @@ pub const Type = extern union {
707719 .comptime_float,
708720 .noreturn,
709721 .@"null",
722 .@"undefined",
710723 .fn_noreturn_no_args,
711724 .fn_naked_noreturn_no_args,
712725 .fn_ccc_void_no_args,
......@@ -781,6 +794,7 @@ pub const Type = extern union {
781794 .comptime_float,
782795 .noreturn,
783796 .@"null",
797 .@"undefined",
784798 .array,
785799 .single_const_pointer,
786800 .single_const_pointer_to_comptime_int,
......@@ -826,6 +840,7 @@ pub const Type = extern union {
826840 .comptime_float,
827841 .noreturn,
828842 .@"null",
843 .@"undefined",
829844 .array,
830845 .single_const_pointer,
831846 .single_const_pointer_to_comptime_int,
......@@ -870,6 +885,7 @@ pub const Type = extern union {
870885 .comptime_float,
871886 .noreturn,
872887 .@"null",
888 .@"undefined",
873889 .array,
874890 .single_const_pointer,
875891 .single_const_pointer_to_comptime_int,
......@@ -914,6 +930,7 @@ pub const Type = extern union {
914930 .comptime_float,
915931 .noreturn,
916932 .@"null",
933 .@"undefined",
917934 .array,
918935 .single_const_pointer,
919936 .single_const_pointer_to_comptime_int,
......@@ -958,6 +975,7 @@ pub const Type = extern union {
958975 .comptime_float,
959976 .noreturn,
960977 .@"null",
978 .@"undefined",
961979 .array,
962980 .single_const_pointer,
963981 .single_const_pointer_to_comptime_int,
......@@ -1013,6 +1031,7 @@ pub const Type = extern union {
10131031 .anyerror,
10141032 .noreturn,
10151033 .@"null",
1034 .@"undefined",
10161035 .fn_noreturn_no_args,
10171036 .fn_naked_noreturn_no_args,
10181037 .fn_ccc_void_no_args,
......@@ -1062,6 +1081,7 @@ pub const Type = extern union {
10621081 .void,
10631082 .noreturn,
10641083 .@"null",
1084 .@"undefined",
10651085 => return true,
10661086
10671087 .int_unsigned => return ty.cast(Payload.IntUnsigned).?.bits == 0,
......@@ -1115,6 +1135,7 @@ pub const Type = extern union {
11151135 .void,
11161136 .noreturn,
11171137 .@"null",
1138 .@"undefined",
11181139 .int_unsigned,
11191140 .int_signed,
11201141 .array,
......@@ -1157,6 +1178,7 @@ pub const Type = extern union {
11571178 comptime_float,
11581179 noreturn,
11591180 @"null",
1181 @"undefined",
11601182 fn_noreturn_no_args,
11611183 fn_naked_noreturn_no_args,
11621184 fn_ccc_void_no_args,
src-self-hosted/value.zig+12
......@@ -47,6 +47,7 @@ pub const Value = extern union {
4747 comptime_float_type,
4848 noreturn_type,
4949 null_type,
50 undefined_type,
5051 fn_noreturn_no_args_type,
5152 fn_naked_noreturn_no_args_type,
5253 fn_ccc_void_no_args_type,
......@@ -141,6 +142,7 @@ pub const Value = extern union {
141142 .comptime_float_type => return out_stream.writeAll("comptime_float"),
142143 .noreturn_type => return out_stream.writeAll("noreturn"),
143144 .null_type => return out_stream.writeAll("@TypeOf(null)"),
145 .undefined_type => return out_stream.writeAll("@TypeOf(undefined)"),
144146 .fn_noreturn_no_args_type => return out_stream.writeAll("fn() noreturn"),
145147 .fn_naked_noreturn_no_args_type => return out_stream.writeAll("fn() callconv(.Naked) noreturn"),
146148 .fn_ccc_void_no_args_type => return out_stream.writeAll("fn() callconv(.C) void"),
......@@ -225,6 +227,7 @@ pub const Value = extern union {
225227 .comptime_float_type => Type.initTag(.comptime_float),
226228 .noreturn_type => Type.initTag(.noreturn),
227229 .null_type => Type.initTag(.@"null"),
230 .undefined_type => Type.initTag(.@"undefined"),
228231 .fn_noreturn_no_args_type => Type.initTag(.fn_noreturn_no_args),
229232 .fn_naked_noreturn_no_args_type => Type.initTag(.fn_naked_noreturn_no_args),
230233 .fn_ccc_void_no_args_type => Type.initTag(.fn_ccc_void_no_args),
......@@ -281,6 +284,7 @@ pub const Value = extern union {
281284 .comptime_float_type,
282285 .noreturn_type,
283286 .null_type,
287 .undefined_type,
284288 .fn_noreturn_no_args_type,
285289 .fn_naked_noreturn_no_args_type,
286290 .fn_ccc_void_no_args_type,
......@@ -339,6 +343,7 @@ pub const Value = extern union {
339343 .comptime_float_type,
340344 .noreturn_type,
341345 .null_type,
346 .undefined_type,
342347 .fn_noreturn_no_args_type,
343348 .fn_naked_noreturn_no_args_type,
344349 .fn_ccc_void_no_args_type,
......@@ -398,6 +403,7 @@ pub const Value = extern union {
398403 .comptime_float_type,
399404 .noreturn_type,
400405 .null_type,
406 .undefined_type,
401407 .fn_noreturn_no_args_type,
402408 .fn_naked_noreturn_no_args_type,
403409 .fn_ccc_void_no_args_type,
......@@ -462,6 +468,7 @@ pub const Value = extern union {
462468 .comptime_float_type,
463469 .noreturn_type,
464470 .null_type,
471 .undefined_type,
465472 .fn_noreturn_no_args_type,
466473 .fn_naked_noreturn_no_args_type,
467474 .fn_ccc_void_no_args_type,
......@@ -555,6 +562,7 @@ pub const Value = extern union {
555562 .comptime_float_type,
556563 .noreturn_type,
557564 .null_type,
565 .undefined_type,
558566 .fn_noreturn_no_args_type,
559567 .fn_naked_noreturn_no_args_type,
560568 .fn_ccc_void_no_args_type,
......@@ -610,6 +618,7 @@ pub const Value = extern union {
610618 .comptime_float_type,
611619 .noreturn_type,
612620 .null_type,
621 .undefined_type,
613622 .fn_noreturn_no_args_type,
614623 .fn_naked_noreturn_no_args_type,
615624 .fn_ccc_void_no_args_type,
......@@ -710,6 +719,7 @@ pub const Value = extern union {
710719 .comptime_float_type,
711720 .noreturn_type,
712721 .null_type,
722 .undefined_type,
713723 .fn_noreturn_no_args_type,
714724 .fn_naked_noreturn_no_args_type,
715725 .fn_ccc_void_no_args_type,
......@@ -771,6 +781,7 @@ pub const Value = extern union {
771781 .comptime_float_type,
772782 .noreturn_type,
773783 .null_type,
784 .undefined_type,
774785 .fn_noreturn_no_args_type,
775786 .fn_naked_noreturn_no_args_type,
776787 .fn_ccc_void_no_args_type,
......@@ -849,6 +860,7 @@ pub const Value = extern union {
849860 .comptime_float_type,
850861 .noreturn_type,
851862 .null_type,
863 .undefined_type,
852864 .fn_noreturn_no_args_type,
853865 .fn_naked_noreturn_no_args_type,
854866 .fn_ccc_void_no_args_type,
src-self-hosted/zir.zig+302-141
......@@ -27,9 +27,12 @@ pub const Inst = struct {
2727 pub const Tag = enum {
2828 breakpoint,
2929 call,
30 /// Represents a reference to a global decl by name.
31 /// The syntax `@foo` is equivalent to `declref("foo")`.
30 compileerror,
31 /// Represents a pointer to a global decl by name.
3232 declref,
33 /// The syntax `@foo` is equivalent to `declval("foo")`.
34 /// declval is equivalent to declref followed by deref.
35 declval,
3336 str,
3437 int,
3538 ptrtoint,
......@@ -59,6 +62,8 @@ pub const Inst = struct {
5962 .breakpoint => Breakpoint,
6063 .call => Call,
6164 .declref => DeclRef,
65 .declval => DeclVal,
66 .compileerror => CompileError,
6267 .str => Str,
6368 .int => Int,
6469 .ptrtoint => PtrToInt,
......@@ -122,6 +127,26 @@ pub const Inst = struct {
122127 kw_args: struct {},
123128 };
124129
130 pub const DeclVal = struct {
131 pub const base_tag = Tag.declval;
132 base: Inst,
133
134 positionals: struct {
135 name: []const u8,
136 },
137 kw_args: struct {},
138 };
139
140 pub const CompileError = struct {
141 pub const base_tag = Tag.compileerror;
142 base: Inst,
143
144 positionals: struct {
145 msg: []const u8,
146 },
147 kw_args: struct {},
148 };
149
125150 pub const Str = struct {
126151 pub const base_tag = Tag.str;
127152 base: Inst,
......@@ -254,11 +279,11 @@ pub const Inst = struct {
254279 base: Inst,
255280
256281 positionals: struct {
257 tag: BuiltinType,
282 tag: Builtin,
258283 },
259284 kw_args: struct {},
260285
261 pub const BuiltinType = enum {
286 pub const Builtin = enum {
262287 isize,
263288 usize,
264289 c_short,
......@@ -282,32 +307,42 @@ pub const Inst = struct {
282307 anyerror,
283308 comptime_int,
284309 comptime_float,
310 @"true",
311 @"false",
312 @"null",
313 @"undefined",
314 void_value,
285315
286 pub fn toType(self: BuiltinType) Type {
316 pub fn toTypedValue(self: Builtin) TypedValue {
287317 return switch (self) {
288 .isize => Type.initTag(.isize),
289 .usize => Type.initTag(.usize),
290 .c_short => Type.initTag(.c_short),
291 .c_ushort => Type.initTag(.c_ushort),
292 .c_int => Type.initTag(.c_int),
293 .c_uint => Type.initTag(.c_uint),
294 .c_long => Type.initTag(.c_long),
295 .c_ulong => Type.initTag(.c_ulong),
296 .c_longlong => Type.initTag(.c_longlong),
297 .c_ulonglong => Type.initTag(.c_ulonglong),
298 .c_longdouble => Type.initTag(.c_longdouble),
299 .c_void => Type.initTag(.c_void),
300 .f16 => Type.initTag(.f16),
301 .f32 => Type.initTag(.f32),
302 .f64 => Type.initTag(.f64),
303 .f128 => Type.initTag(.f128),
304 .bool => Type.initTag(.bool),
305 .void => Type.initTag(.void),
306 .noreturn => Type.initTag(.noreturn),
307 .type => Type.initTag(.type),
308 .anyerror => Type.initTag(.anyerror),
309 .comptime_int => Type.initTag(.comptime_int),
310 .comptime_float => Type.initTag(.comptime_float),
318 .isize => .{ .ty = Type.initTag(.type), .val = Value.initTag(.isize_type) },
319 .usize => .{ .ty = Type.initTag(.type), .val = Value.initTag(.usize_type) },
320 .c_short => .{ .ty = Type.initTag(.type), .val = Value.initTag(.c_short_type) },
321 .c_ushort => .{ .ty = Type.initTag(.type), .val = Value.initTag(.c_ushort_type) },
322 .c_int => .{ .ty = Type.initTag(.type), .val = Value.initTag(.c_int_type) },
323 .c_uint => .{ .ty = Type.initTag(.type), .val = Value.initTag(.c_uint_type) },
324 .c_long => .{ .ty = Type.initTag(.type), .val = Value.initTag(.c_long_type) },
325 .c_ulong => .{ .ty = Type.initTag(.type), .val = Value.initTag(.c_ulong_type) },
326 .c_longlong => .{ .ty = Type.initTag(.type), .val = Value.initTag(.c_longlong_type) },
327 .c_ulonglong => .{ .ty = Type.initTag(.type), .val = Value.initTag(.c_ulonglong_type) },
328 .c_longdouble => .{ .ty = Type.initTag(.type), .val = Value.initTag(.c_longdouble_type) },
329 .c_void => .{ .ty = Type.initTag(.type), .val = Value.initTag(.c_void_type) },
330 .f16 => .{ .ty = Type.initTag(.type), .val = Value.initTag(.f16_type) },
331 .f32 => .{ .ty = Type.initTag(.type), .val = Value.initTag(.f32_type) },
332 .f64 => .{ .ty = Type.initTag(.type), .val = Value.initTag(.f64_type) },
333 .f128 => .{ .ty = Type.initTag(.type), .val = Value.initTag(.f128_type) },
334 .bool => .{ .ty = Type.initTag(.type), .val = Value.initTag(.bool_type) },
335 .void => .{ .ty = Type.initTag(.type), .val = Value.initTag(.void_type) },
336 .noreturn => .{ .ty = Type.initTag(.type), .val = Value.initTag(.noreturn_type) },
337 .type => .{ .ty = Type.initTag(.type), .val = Value.initTag(.type_type) },
338 .anyerror => .{ .ty = Type.initTag(.type), .val = Value.initTag(.anyerror_type) },
339 .comptime_int => .{ .ty = Type.initTag(.type), .val = Value.initTag(.comptime_int_type) },
340 .comptime_float => .{ .ty = Type.initTag(.type), .val = Value.initTag(.comptime_float_type) },
341 .@"true" => .{ .ty = Type.initTag(.bool), .val = Value.initTag(.bool_true) },
342 .@"false" => .{ .ty = Type.initTag(.bool), .val = Value.initTag(.bool_false) },
343 .@"null" => .{ .ty = Type.initTag(.@"null"), .val = Value.initTag(.null_value) },
344 .@"undefined" => .{ .ty = Type.initTag(.@"undefined"), .val = Value.initTag(.undef) },
345 .void_value => .{ .ty = Type.initTag(.void), .val = Value.initTag(.the_one_possible_value) },
311346 };
312347 }
313348 };
......@@ -440,7 +475,7 @@ pub const Module = struct {
440475 self.writeToStream(std.heap.page_allocator, std.io.getStdErr().outStream()) catch {};
441476 }
442477
443 const InstPtrTable = std.AutoHashMap(*Inst, struct { index: usize, fn_body: ?*Module.Body });
478 const InstPtrTable = std.AutoHashMap(*Inst, struct { inst: *Inst, index: ?usize });
444479
445480 /// TODO Look into making a table to speed this up.
446481 pub fn findDecl(self: Module, name: []const u8) ?*Inst {
......@@ -462,17 +497,17 @@ pub const Module = struct {
462497 try inst_table.ensureCapacity(self.decls.len);
463498
464499 for (self.decls) |decl, decl_i| {
465 try inst_table.putNoClobber(decl, .{ .index = decl_i, .fn_body = null });
500 try inst_table.putNoClobber(decl, .{ .inst = decl, .index = null });
466501
467502 if (decl.cast(Inst.Fn)) |fn_inst| {
468503 for (fn_inst.positionals.body.instructions) |inst, inst_i| {
469 try inst_table.putNoClobber(inst, .{ .index = inst_i, .fn_body = &fn_inst.positionals.body });
504 try inst_table.putNoClobber(inst, .{ .inst = inst, .index = inst_i });
470505 }
471506 }
472507 }
473508
474509 for (self.decls) |decl, i| {
475 try stream.print("@{} ", .{i});
510 try stream.print("@{} ", .{decl.name});
476511 try self.writeInstToStream(stream, decl, &inst_table);
477512 try stream.writeByte('\n');
478513 }
......@@ -489,6 +524,8 @@ pub const Module = struct {
489524 .breakpoint => return self.writeInstToStreamGeneric(stream, .breakpoint, decl, inst_table),
490525 .call => return self.writeInstToStreamGeneric(stream, .call, decl, inst_table),
491526 .declref => return self.writeInstToStreamGeneric(stream, .declref, decl, inst_table),
527 .declval => return self.writeInstToStreamGeneric(stream, .declval, decl, inst_table),
528 .compileerror => return self.writeInstToStreamGeneric(stream, .compileerror, decl, inst_table),
492529 .str => return self.writeInstToStreamGeneric(stream, .str, decl, inst_table),
493530 .int => return self.writeInstToStreamGeneric(stream, .int, decl, inst_table),
494531 .ptrtoint => return self.writeInstToStreamGeneric(stream, .ptrtoint, decl, inst_table),
......@@ -587,9 +624,18 @@ pub const Module = struct {
587624 }
588625
589626 fn writeInstParamToStream(self: Module, stream: var, inst: *Inst, inst_table: *const InstPtrTable) !void {
590 const info = inst_table.getValue(inst).?;
591 const prefix = if (info.fn_body == null) "@" else "%";
592 try stream.print("{}{}", .{ prefix, info.index });
627 if (inst_table.getValue(inst)) |info| {
628 if (info.index) |i| {
629 try stream.print("%{}", .{info.index});
630 } else {
631 try stream.print("@{}", .{info.inst.name});
632 }
633 } else if (inst.cast(Inst.DeclVal)) |decl_val| {
634 try stream.print("@{}", .{decl_val.positionals.name});
635 } else {
636 //try stream.print("?", .{});
637 unreachable;
638 }
593639 }
594640};
595641
......@@ -884,6 +930,7 @@ const Parser = struct {
884930 try requireEatBytes(self, ")");
885931
886932 inst_specific.base.contents = self.source[contents_start..self.i];
933 //std.debug.warn("parsed {} = '{}'\n", .{ inst_specific.base.name, inst_specific.base.contents });
887934
888935 return &inst_specific.base;
889936 }
......@@ -964,47 +1011,17 @@ const Parser = struct {
9641011 self.i = src;
9651012 return self.fail("unrecognized identifier: {}", .{bad_name});
9661013 } else {
967 const name_array = try self.arena.allocator.create(Inst.Str);
968 name_array.* = .{
969 .base = .{
970 .name = try self.generateName(),
971 .src = src,
972 .tag = Inst.Str.base_tag,
973 },
974 .positionals = .{ .bytes = ident },
975 .kw_args = .{},
976 };
977 const name = try self.arena.allocator.create(Inst.Ref);
978 name.* = .{
979 .base = .{
980 .name = try self.generateName(),
981 .src = src,
982 .tag = Inst.Ref.base_tag,
983 },
984 .positionals = .{ .operand = &name_array.base },
985 .kw_args = .{},
986 };
987 const declref = try self.arena.allocator.create(Inst.DeclRef);
988 declref.* = .{
989 .base = .{
990 .name = try self.generateName(),
991 .src = src,
992 .tag = Inst.DeclRef.base_tag,
993 },
994 .positionals = .{ .name = &name.base },
995 .kw_args = .{},
996 };
997 const deref = try self.arena.allocator.create(Inst.Deref);
998 deref.* = .{
1014 const declval = try self.arena.allocator.create(Inst.DeclVal);
1015 declval.* = .{
9991016 .base = .{
10001017 .name = try self.generateName(),
10011018 .src = src,
1002 .tag = Inst.Deref.base_tag,
1019 .tag = Inst.DeclVal.base_tag,
10031020 },
1004 .positionals = .{ .ptr = &declref.base },
1021 .positionals = .{ .name = ident },
10051022 .kw_args = .{},
10061023 };
1007 return &deref.base;
1024 return &declval.base;
10081025 }
10091026 };
10101027 if (local_ref) {
......@@ -1025,12 +1042,15 @@ pub fn emit(allocator: *Allocator, old_module: IrModule) !Module {
10251042 var ctx: EmitZIR = .{
10261043 .allocator = allocator,
10271044 .decls = .{},
1028 .decl_table = std.AutoHashMap(*ir.Inst, *Inst).init(allocator),
10291045 .arena = std.heap.ArenaAllocator.init(allocator),
10301046 .old_module = &old_module,
1047 .next_auto_name = 0,
1048 .names = std.StringHashMap(void).init(allocator),
1049 .primitive_table = std.AutoHashMap(Inst.Primitive.Builtin, *Inst).init(allocator),
10311050 };
10321051 defer ctx.decls.deinit(allocator);
1033 defer ctx.decl_table.deinit();
1052 defer ctx.names.deinit();
1053 defer ctx.primitive_table.deinit();
10341054 errdefer ctx.arena.deinit();
10351055
10361056 try ctx.emit();
......@@ -1046,47 +1066,90 @@ const EmitZIR = struct {
10461066 arena: std.heap.ArenaAllocator,
10471067 old_module: *const IrModule,
10481068 decls: std.ArrayListUnmanaged(*Inst),
1049 decl_table: std.AutoHashMap(*ir.Inst, *Inst),
1069 names: std.StringHashMap(void),
1070 next_auto_name: usize,
1071 primitive_table: std.AutoHashMap(Inst.Primitive.Builtin, *Inst),
10501072
10511073 fn emit(self: *EmitZIR) !void {
1052 var it = self.old_module.decl_exports.iterator();
1053 while (it.next()) |kv| {
1054 const decl = kv.key;
1055 const exports = kv.value;
1056 const export_value = try self.emitTypedValue(decl.src, decl.typed_value.most_recent.typed_value);
1057 for (exports) |module_export| {
1058 const symbol_name = try self.emitStringLiteral(module_export.src, module_export.options.name);
1059 const export_inst = try self.arena.allocator.create(Inst.Export);
1060 export_inst.* = .{
1061 .base = .{
1062 .name = try self.autoName(),
1063 .src = module_export.src,
1064 .tag = Inst.Export.base_tag,
1065 },
1066 .positionals = .{
1067 .symbol_name = symbol_name,
1068 .value = export_value,
1069 },
1070 .kw_args = .{},
1071 };
1072 try self.decls.append(self.allocator, &export_inst.base);
1074 // Put all the Decls in a list and sort them by name to avoid nondeterminism introduced
1075 // by the hash table.
1076 var src_decls = std.ArrayList(*IrModule.Decl).init(self.allocator);
1077 defer src_decls.deinit();
1078 try src_decls.ensureCapacity(self.old_module.decl_table.size);
1079 try self.decls.ensureCapacity(self.allocator, self.old_module.decl_table.size);
1080 try self.names.ensureCapacity(self.old_module.decl_table.size);
1081
1082 var decl_it = self.old_module.decl_table.iterator();
1083 while (decl_it.next()) |kv| {
1084 const decl = kv.value;
1085 src_decls.appendAssumeCapacity(decl);
1086 self.names.putAssumeCapacityNoClobber(mem.spanZ(decl.name), {});
1087 }
1088 std.sort.sort(*IrModule.Decl, src_decls.items, {}, (struct {
1089 fn lessThan(context: void, a: *IrModule.Decl, b: *IrModule.Decl) bool {
1090 return a.src < b.src;
1091 }
1092 }).lessThan);
1093
1094 // Emit all the decls.
1095 for (src_decls.items) |ir_decl| {
1096 if (self.old_module.export_owners.getValue(ir_decl)) |exports| {
1097 for (exports) |module_export| {
1098 const declval = try self.emitDeclVal(ir_decl.src, mem.spanZ(module_export.exported_decl.name));
1099 const symbol_name = try self.emitStringLiteral(module_export.src, module_export.options.name);
1100 const export_inst = try self.arena.allocator.create(Inst.Export);
1101 export_inst.* = .{
1102 .base = .{
1103 .name = try self.autoName(),
1104 .src = module_export.src,
1105 .tag = Inst.Export.base_tag,
1106 },
1107 .positionals = .{
1108 .symbol_name = symbol_name,
1109 .value = declval,
1110 },
1111 .kw_args = .{},
1112 };
1113 try self.decls.append(self.allocator, &export_inst.base);
1114 }
1115 } else {
1116 const new_decl = try self.emitTypedValue(ir_decl.src, ir_decl.typed_value.most_recent.typed_value);
1117 new_decl.name = try self.arena.allocator.dupe(u8, mem.spanZ(ir_decl.name));
10731118 }
10741119 }
10751120 }
10761121
1077 fn resolveInst(self: *EmitZIR, inst_table: *const std.AutoHashMap(*ir.Inst, *Inst), inst: *ir.Inst) !*Inst {
1122 fn resolveInst(self: *EmitZIR, inst_table: *std.AutoHashMap(*ir.Inst, *Inst), inst: *ir.Inst) !*Inst {
10781123 if (inst.cast(ir.Inst.Constant)) |const_inst| {
1079 if (self.decl_table.getValue(inst)) |decl| {
1080 return decl;
1081 }
1082 const new_decl = try self.emitTypedValue(inst.src, .{ .ty = inst.ty, .val = const_inst.val });
1083 try self.decl_table.putNoClobber(inst, new_decl);
1124 const new_decl = if (const_inst.val.cast(Value.Payload.Function)) |func_pl| blk: {
1125 const owner_decl = func_pl.func.owner_decl;
1126 break :blk try self.emitDeclVal(inst.src, mem.spanZ(owner_decl.name));
1127 } else if (const_inst.val.cast(Value.Payload.DeclRef)) |declref| blk: {
1128 break :blk try self.emitDeclRef(inst.src, declref.decl);
1129 } else blk: {
1130 break :blk try self.emitTypedValue(inst.src, .{ .ty = inst.ty, .val = const_inst.val });
1131 };
1132 try inst_table.putNoClobber(inst, new_decl);
10841133 return new_decl;
10851134 } else {
10861135 return inst_table.getValue(inst).?;
10871136 }
10881137 }
10891138
1139 fn emitDeclVal(self: *EmitZIR, src: usize, decl_name: []const u8) !*Inst {
1140 const declval = try self.arena.allocator.create(Inst.DeclVal);
1141 declval.* = .{
1142 .base = .{
1143 .name = try self.autoName(),
1144 .src = src,
1145 .tag = Inst.DeclVal.base_tag,
1146 },
1147 .positionals = .{ .name = try self.arena.allocator.dupe(u8, decl_name) },
1148 .kw_args = .{},
1149 };
1150 return &declval.base;
1151 }
1152
10901153 fn emitComptimeIntVal(self: *EmitZIR, src: usize, val: Value) !*Inst {
10911154 const big_int_space = try self.arena.allocator.create(Value.BigIntSpace);
10921155 const int_inst = try self.arena.allocator.create(Inst.Int);
......@@ -1105,8 +1168,31 @@ const EmitZIR = struct {
11051168 return &int_inst.base;
11061169 }
11071170
1171 fn emitDeclRef(self: *EmitZIR, src: usize, decl: *IrModule.Decl) !*Inst {
1172 const declval = try self.emitDeclVal(src, mem.spanZ(decl.name));
1173 const ref_inst = try self.arena.allocator.create(Inst.Ref);
1174 ref_inst.* = .{
1175 .base = .{
1176 .name = try self.autoName(),
1177 .src = src,
1178 .tag = Inst.Ref.base_tag,
1179 },
1180 .positionals = .{
1181 .operand = declval,
1182 },
1183 .kw_args = .{},
1184 };
1185 try self.decls.append(self.allocator, &ref_inst.base);
1186
1187 return &ref_inst.base;
1188 }
1189
11081190 fn emitTypedValue(self: *EmitZIR, src: usize, typed_value: TypedValue) Allocator.Error!*Inst {
11091191 const allocator = &self.arena.allocator;
1192 if (typed_value.val.cast(Value.Payload.DeclRef)) |decl_ref| {
1193 const decl = decl_ref.decl;
1194 return self.emitDeclRef(src, decl);
1195 }
11101196 switch (typed_value.ty.zigTypeTag()) {
11111197 .Pointer => {
11121198 const ptr_elem_type = typed_value.ty.elemType();
......@@ -1142,7 +1228,6 @@ const EmitZIR = struct {
11421228 },
11431229 .kw_args = .{},
11441230 };
1145 try self.decls.append(self.allocator, &as_inst.base);
11461231
11471232 return &as_inst.base;
11481233 },
......@@ -1159,7 +1244,44 @@ const EmitZIR = struct {
11591244 var instructions = std.ArrayList(*Inst).init(self.allocator);
11601245 defer instructions.deinit();
11611246
1162 try self.emitBody(module_fn.analysis.success, &inst_table, &instructions);
1247 switch (module_fn.analysis) {
1248 .queued => unreachable,
1249 .in_progress => unreachable,
1250 .success => |body| {
1251 try self.emitBody(body, &inst_table, &instructions);
1252 },
1253 .sema_failure => {
1254 const err_msg = self.old_module.failed_decls.getValue(module_fn.owner_decl).?;
1255 const fail_inst = try self.arena.allocator.create(Inst.CompileError);
1256 fail_inst.* = .{
1257 .base = .{
1258 .name = try self.autoName(),
1259 .src = src,
1260 .tag = Inst.CompileError.base_tag,
1261 },
1262 .positionals = .{
1263 .msg = try self.arena.allocator.dupe(u8, err_msg.msg),
1264 },
1265 .kw_args = .{},
1266 };
1267 try instructions.append(&fail_inst.base);
1268 },
1269 .dependency_failure => {
1270 const fail_inst = try self.arena.allocator.create(Inst.CompileError);
1271 fail_inst.* = .{
1272 .base = .{
1273 .name = try self.autoName(),
1274 .src = src,
1275 .tag = Inst.CompileError.base_tag,
1276 },
1277 .positionals = .{
1278 .msg = try self.arena.allocator.dupe(u8, "depends on another failed Decl"),
1279 },
1280 .kw_args = .{},
1281 };
1282 try instructions.append(&fail_inst.base);
1283 },
1284 }
11631285
11641286 const fn_type = try self.emitType(src, module_fn.fn_type);
11651287
......@@ -1182,6 +1304,33 @@ const EmitZIR = struct {
11821304 try self.decls.append(self.allocator, &fn_inst.base);
11831305 return &fn_inst.base;
11841306 },
1307 .Array => {
1308 // TODO more checks to make sure this can be emitted as a string literal
1309 //const array_elem_type = ptr_elem_type.elemType();
1310 //if (array_elem_type.eql(Type.initTag(.u8)) and
1311 // ptr_elem_type.hasSentinel(Value.initTag(.zero)))
1312 //{
1313 //}
1314 const bytes = typed_value.val.toAllocatedBytes(allocator) catch |err| switch (err) {
1315 error.AnalysisFail => unreachable,
1316 else => |e| return e,
1317 };
1318 const str_inst = try self.arena.allocator.create(Inst.Str);
1319 str_inst.* = .{
1320 .base = .{
1321 .name = try self.autoName(),
1322 .src = src,
1323 .tag = Inst.Str.base_tag,
1324 },
1325 .positionals = .{
1326 .bytes = bytes,
1327 },
1328 .kw_args = .{},
1329 };
1330 try self.decls.append(self.allocator, &str_inst.base);
1331 return &str_inst.base;
1332 },
1333 .Void => return self.emitPrimitive(src, .void_value),
11851334 else => |t| std.debug.panic("TODO implement emitTypedValue for {}", .{@tagName(t)}),
11861335 }
11871336 }
......@@ -1395,30 +1544,30 @@ const EmitZIR = struct {
13951544
13961545 fn emitType(self: *EmitZIR, src: usize, ty: Type) Allocator.Error!*Inst {
13971546 switch (ty.tag()) {
1398 .isize => return self.emitPrimitiveType(src, .isize),
1399 .usize => return self.emitPrimitiveType(src, .usize),
1400 .c_short => return self.emitPrimitiveType(src, .c_short),
1401 .c_ushort => return self.emitPrimitiveType(src, .c_ushort),
1402 .c_int => return self.emitPrimitiveType(src, .c_int),
1403 .c_uint => return self.emitPrimitiveType(src, .c_uint),
1404 .c_long => return self.emitPrimitiveType(src, .c_long),
1405 .c_ulong => return self.emitPrimitiveType(src, .c_ulong),
1406 .c_longlong => return self.emitPrimitiveType(src, .c_longlong),
1407 .c_ulonglong => return self.emitPrimitiveType(src, .c_ulonglong),
1408 .c_longdouble => return self.emitPrimitiveType(src, .c_longdouble),
1409 .c_void => return self.emitPrimitiveType(src, .c_void),
1410 .f16 => return self.emitPrimitiveType(src, .f16),
1411 .f32 => return self.emitPrimitiveType(src, .f32),
1412 .f64 => return self.emitPrimitiveType(src, .f64),
1413 .f128 => return self.emitPrimitiveType(src, .f128),
1414 .anyerror => return self.emitPrimitiveType(src, .anyerror),
1547 .isize => return self.emitPrimitive(src, .isize),
1548 .usize => return self.emitPrimitive(src, .usize),
1549 .c_short => return self.emitPrimitive(src, .c_short),
1550 .c_ushort => return self.emitPrimitive(src, .c_ushort),
1551 .c_int => return self.emitPrimitive(src, .c_int),
1552 .c_uint => return self.emitPrimitive(src, .c_uint),
1553 .c_long => return self.emitPrimitive(src, .c_long),
1554 .c_ulong => return self.emitPrimitive(src, .c_ulong),
1555 .c_longlong => return self.emitPrimitive(src, .c_longlong),
1556 .c_ulonglong => return self.emitPrimitive(src, .c_ulonglong),
1557 .c_longdouble => return self.emitPrimitive(src, .c_longdouble),
1558 .c_void => return self.emitPrimitive(src, .c_void),
1559 .f16 => return self.emitPrimitive(src, .f16),
1560 .f32 => return self.emitPrimitive(src, .f32),
1561 .f64 => return self.emitPrimitive(src, .f64),
1562 .f128 => return self.emitPrimitive(src, .f128),
1563 .anyerror => return self.emitPrimitive(src, .anyerror),
14151564 else => switch (ty.zigTypeTag()) {
1416 .Bool => return self.emitPrimitiveType(src, .bool),
1417 .Void => return self.emitPrimitiveType(src, .void),
1418 .NoReturn => return self.emitPrimitiveType(src, .noreturn),
1419 .Type => return self.emitPrimitiveType(src, .type),
1420 .ComptimeInt => return self.emitPrimitiveType(src, .comptime_int),
1421 .ComptimeFloat => return self.emitPrimitiveType(src, .comptime_float),
1565 .Bool => return self.emitPrimitive(src, .bool),
1566 .Void => return self.emitPrimitive(src, .void),
1567 .NoReturn => return self.emitPrimitive(src, .noreturn),
1568 .Type => return self.emitPrimitive(src, .type),
1569 .ComptimeInt => return self.emitPrimitive(src, .comptime_int),
1570 .ComptimeFloat => return self.emitPrimitive(src, .comptime_float),
14221571 .Fn => {
14231572 const param_types = try self.allocator.alloc(Type, ty.fnParamLen());
14241573 defer self.allocator.free(param_types);
......@@ -1453,24 +1602,36 @@ const EmitZIR = struct {
14531602 }
14541603
14551604 fn autoName(self: *EmitZIR) ![]u8 {
1456 return std.fmt.allocPrint(&self.arena.allocator, "{}", .{self.decls.items.len});
1605 while (true) {
1606 const proposed_name = try std.fmt.allocPrint(&self.arena.allocator, "unnamed${}", .{self.next_auto_name});
1607 self.next_auto_name += 1;
1608 const gop = try self.names.getOrPut(proposed_name);
1609 if (!gop.found_existing) {
1610 gop.kv.value = {};
1611 return proposed_name;
1612 }
1613 }
14571614 }
14581615
1459 fn emitPrimitiveType(self: *EmitZIR, src: usize, tag: Inst.Primitive.BuiltinType) !*Inst {
1460 const primitive_inst = try self.arena.allocator.create(Inst.Primitive);
1461 primitive_inst.* = .{
1462 .base = .{
1463 .name = try self.autoName(),
1464 .src = src,
1465 .tag = Inst.Primitive.base_tag,
1466 },
1467 .positionals = .{
1468 .tag = tag,
1469 },
1470 .kw_args = .{},
1471 };
1472 try self.decls.append(self.allocator, &primitive_inst.base);
1473 return &primitive_inst.base;
1616 fn emitPrimitive(self: *EmitZIR, src: usize, tag: Inst.Primitive.Builtin) !*Inst {
1617 const gop = try self.primitive_table.getOrPut(tag);
1618 if (!gop.found_existing) {
1619 const primitive_inst = try self.arena.allocator.create(Inst.Primitive);
1620 primitive_inst.* = .{
1621 .base = .{
1622 .name = try self.autoName(),
1623 .src = src,
1624 .tag = Inst.Primitive.base_tag,
1625 },
1626 .positionals = .{
1627 .tag = tag,
1628 },
1629 .kw_args = .{},
1630 };
1631 try self.decls.append(self.allocator, &primitive_inst.base);
1632 gop.kv.value = &primitive_inst.base;
1633 }
1634 return gop.kv.value;
14741635 }
14751636
14761637 fn emitStringLiteral(self: *EmitZIR, src: usize, str: []const u8) !*Inst {
test/stage2/zir.zig+142-12
......@@ -21,14 +21,17 @@ pub fn addCases(ctx: *TestContext) void {
2121 \\ %11 = return()
2222 \\})
2323 ,
24 \\@0 = primitive(void)
25 \\@1 = fntype([], @0, cc=C)
26 \\@2 = fn(@1, {
24 \\@void = primitive(void)
25 \\@fnty = fntype([], @void, cc=C)
26 \\@9 = str("entry")
27 \\@10 = ref(@9)
28 \\@unnamed$6 = str("entry")
29 \\@unnamed$7 = ref(@unnamed$6)
30 \\@unnamed$8 = export(@unnamed$7, @entry)
31 \\@unnamed$10 = fntype([], @void, cc=C)
32 \\@entry = fn(@unnamed$10, {
2733 \\ %0 = return()
2834 \\})
29 \\@3 = str("entry")
30 \\@4 = ref(@3)
31 \\@5 = export(@4, @2)
3235 \\
3336 );
3437 ctx.addZIRTransform("elemptr, add, cmp, condbr, return, breakpoint", linux_x64,
......@@ -68,17 +71,144 @@ pub fn addCases(ctx: *TestContext) void {
6871 \\@10 = ref(@9)
6972 \\@11 = export(@10, @entry)
7073 ,
71 \\@0 = primitive(void)
72 \\@1 = fntype([], @0, cc=C)
73 \\@2 = fn(@1, {
74 \\@void = primitive(void)
75 \\@fnty = fntype([], @void, cc=C)
76 \\@0 = int(0)
77 \\@1 = int(1)
78 \\@2 = int(2)
79 \\@3 = int(3)
80 \\@unnamed$7 = fntype([], @void, cc=C)
81 \\@entry = fn(@unnamed$7, {
7482 \\ %0 = return()
7583 \\})
76 \\@3 = str("entry")
77 \\@4 = ref(@3)
78 \\@5 = export(@4, @2)
84 \\@a = str("2\x08\x01\n")
85 \\@9 = str("entry")
86 \\@10 = ref(@9)
87 \\@unnamed$14 = str("entry")
88 \\@unnamed$15 = ref(@unnamed$14)
89 \\@unnamed$16 = export(@unnamed$15, @entry)
7990 \\
8091 );
8192
93 {
94 var case = ctx.addZIRMulti("reference cycle with compile error in the cycle", linux_x64);
95 case.addZIR(
96 \\@void = primitive(void)
97 \\@fnty = fntype([], @void, cc=C)
98 \\
99 \\@9 = str("entry")
100 \\@10 = ref(@9)
101 \\@11 = export(@10, @entry)
102 \\
103 \\@entry = fn(@fnty, {
104 \\ %0 = call(@a, [])
105 \\ %1 = return()
106 \\})
107 \\
108 \\@a = fn(@fnty, {
109 \\ %0 = call(@b, [])
110 \\ %1 = return()
111 \\})
112 \\
113 \\@b = fn(@fnty, {
114 \\ %0 = call(@a, [])
115 \\ %1 = return()
116 \\})
117 ,
118 \\@void = primitive(void)
119 \\@fnty = fntype([], @void, cc=C)
120 \\@9 = str("entry")
121 \\@10 = ref(@9)
122 \\@unnamed$6 = str("entry")
123 \\@unnamed$7 = ref(@unnamed$6)
124 \\@unnamed$8 = export(@unnamed$7, @entry)
125 \\@unnamed$12 = fntype([], @void, cc=C)
126 \\@entry = fn(@unnamed$12, {
127 \\ %0 = call(@a, [], modifier=auto)
128 \\ %1 = return()
129 \\})
130 \\@unnamed$17 = fntype([], @void, cc=C)
131 \\@a = fn(@unnamed$17, {
132 \\ %0 = call(@b, [], modifier=auto)
133 \\ %1 = return()
134 \\})
135 \\@unnamed$22 = fntype([], @void, cc=C)
136 \\@b = fn(@unnamed$22, {
137 \\ %0 = call(@a, [], modifier=auto)
138 \\ %1 = return()
139 \\})
140 \\
141 );
142 // Now we introduce a compile error
143 case.addError(
144 \\@void = primitive(void)
145 \\@fnty = fntype([], @void, cc=C)
146 \\
147 \\@9 = str("entry")
148 \\@10 = ref(@9)
149 \\@11 = export(@10, @entry)
150 \\
151 \\@entry = fn(@fnty, {
152 \\ %0 = call(@a, [])
153 \\ %1 = return()
154 \\})
155 \\
156 \\@a = fn(@fnty, {
157 \\ %0 = call(@b, [])
158 \\ %1 = return()
159 \\})
160 \\
161 \\@b = fn(@fnty, {
162 \\ %9 = compileerror("message")
163 \\ %0 = call(@a, [])
164 \\ %1 = return()
165 \\})
166 ,
167 &[_][]const u8{
168 ":19:21: error: message",
169 },
170 );
171 // Now we remove the call to `a`. `a` and `b` form a cycle, but no entry points are
172 // referencing either of them. This tests that the cycle is detected, and the error
173 // goes away.
174 case.addZIR(
175 \\@void = primitive(void)
176 \\@fnty = fntype([], @void, cc=C)
177 \\
178 \\@9 = str("entry")
179 \\@10 = ref(@9)
180 \\@11 = export(@10, @entry)
181 \\
182 \\@entry = fn(@fnty, {
183 \\ %1 = return()
184 \\})
185 \\
186 \\@a = fn(@fnty, {
187 \\ %0 = call(@b, [])
188 \\ %1 = return()
189 \\})
190 \\
191 \\@b = fn(@fnty, {
192 \\ %9 = compileerror("message")
193 \\ %0 = call(@a, [])
194 \\ %1 = return()
195 \\})
196 ,
197 \\@void = primitive(void)
198 \\@fnty = fntype([], @void, cc=C)
199 \\@9 = str("entry")
200 \\@10 = ref(@9)
201 \\@unnamed$6 = str("entry")
202 \\@unnamed$7 = ref(@unnamed$6)
203 \\@unnamed$8 = export(@unnamed$7, @entry)
204 \\@unnamed$10 = fntype([], @void, cc=C)
205 \\@entry = fn(@unnamed$10, {
206 \\ %0 = return()
207 \\})
208 \\
209 );
210 }
211
82212 if (std.Target.current.os.tag != .linux or
83213 std.Target.current.cpu.arch != .x86_64)
84214 {