authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2021-11-30 18:48:31-08:00
committergravatar for noreply@github.comGitHub <noreply@github.com> 2021-11-30 18:48:31-08:00
log7355a201336c8e3892427e5932fe5cdd46cf96df
tree4ccec922634586847d02f2324d0db75f25200188
parentdd62a6d2e8de522187fd096354e7156cca1821c5
parent066eaa5e9cbfde172449f6d95bb884c7d86ac10c
signaturebadge-question-mark Signed by PGP key 4AEE18F83AFDEB23

Merge pull request #10055 from leecannon/allocator_refactor

Allocgate

166 files changed, 1867 insertions(+), 1611 deletions(-)

ci/srht/update-download-page.zig+2-2
......@@ -6,7 +6,7 @@ pub fn main() !void {
66 var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
77 defer arena.deinit();
88
9 const allocator = &arena.allocator;
9 const allocator = arena.allocator();
1010
1111 const out_dir = "out";
1212 try std.fs.cwd().makePath(out_dir);
......@@ -18,7 +18,7 @@ pub fn main() !void {
1818}
1919
2020fn render(
21 allocator: *mem.Allocator,
21 allocator: mem.Allocator,
2222 in_file: []const u8,
2323 out_file: []const u8,
2424 fmt: enum {
doc/docgen.zig+11-11
......@@ -21,7 +21,7 @@ pub fn main() !void {
2121 var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
2222 defer arena.deinit();
2323
24 const allocator = &arena.allocator;
24 const allocator = arena.allocator();
2525
2626 var args_it = process.args();
2727
......@@ -342,7 +342,7 @@ const Action = enum {
342342 Close,
343343};
344344
345fn genToc(allocator: *Allocator, tokenizer: *Tokenizer) !Toc {
345fn genToc(allocator: Allocator, tokenizer: *Tokenizer) !Toc {
346346 var urls = std.StringHashMap(Token).init(allocator);
347347 errdefer urls.deinit();
348348
......@@ -708,7 +708,7 @@ fn genToc(allocator: *Allocator, tokenizer: *Tokenizer) !Toc {
708708 };
709709}
710710
711fn urlize(allocator: *Allocator, input: []const u8) ![]u8 {
711fn urlize(allocator: Allocator, input: []const u8) ![]u8 {
712712 var buf = std.ArrayList(u8).init(allocator);
713713 defer buf.deinit();
714714
......@@ -727,7 +727,7 @@ fn urlize(allocator: *Allocator, input: []const u8) ![]u8 {
727727 return buf.toOwnedSlice();
728728}
729729
730fn escapeHtml(allocator: *Allocator, input: []const u8) ![]u8 {
730fn escapeHtml(allocator: Allocator, input: []const u8) ![]u8 {
731731 var buf = std.ArrayList(u8).init(allocator);
732732 defer buf.deinit();
733733
......@@ -773,7 +773,7 @@ test "term color" {
773773 try testing.expectEqualSlices(u8, "A<span class=\"t32_1\">green</span>B", result);
774774}
775775
776fn termColor(allocator: *Allocator, input: []const u8) ![]u8 {
776fn termColor(allocator: Allocator, input: []const u8) ![]u8 {
777777 var buf = std.ArrayList(u8).init(allocator);
778778 defer buf.deinit();
779779
......@@ -883,7 +883,7 @@ fn writeEscapedLines(out: anytype, text: []const u8) !void {
883883}
884884
885885fn tokenizeAndPrintRaw(
886 allocator: *Allocator,
886 allocator: Allocator,
887887 docgen_tokenizer: *Tokenizer,
888888 out: anytype,
889889 source_token: Token,
......@@ -1137,7 +1137,7 @@ fn tokenizeAndPrintRaw(
11371137}
11381138
11391139fn tokenizeAndPrint(
1140 allocator: *Allocator,
1140 allocator: Allocator,
11411141 docgen_tokenizer: *Tokenizer,
11421142 out: anytype,
11431143 source_token: Token,
......@@ -1146,7 +1146,7 @@ fn tokenizeAndPrint(
11461146 return tokenizeAndPrintRaw(allocator, docgen_tokenizer, out, source_token, raw_src);
11471147}
11481148
1149fn printSourceBlock(allocator: *Allocator, docgen_tokenizer: *Tokenizer, out: anytype, syntax_block: SyntaxBlock) !void {
1149fn printSourceBlock(allocator: Allocator, docgen_tokenizer: *Tokenizer, out: anytype, syntax_block: SyntaxBlock) !void {
11501150 const source_type = @tagName(syntax_block.source_type);
11511151
11521152 try out.print("<figure><figcaption class=\"{s}-cap\"><cite class=\"file\">{s}</cite></figcaption><pre>", .{ source_type, syntax_block.name });
......@@ -1188,7 +1188,7 @@ fn printShell(out: anytype, shell_content: []const u8) !void {
11881188}
11891189
11901190fn genHtml(
1191 allocator: *Allocator,
1191 allocator: Allocator,
11921192 tokenizer: *Tokenizer,
11931193 toc: *Toc,
11941194 out: anytype,
......@@ -1687,7 +1687,7 @@ fn genHtml(
16871687 }
16881688}
16891689
1690fn exec(allocator: *Allocator, env_map: *std.BufMap, args: []const []const u8) !ChildProcess.ExecResult {
1690fn exec(allocator: Allocator, env_map: *std.BufMap, args: []const []const u8) !ChildProcess.ExecResult {
16911691 const result = try ChildProcess.exec(.{
16921692 .allocator = allocator,
16931693 .argv = args,
......@@ -1711,7 +1711,7 @@ fn exec(allocator: *Allocator, env_map: *std.BufMap, args: []const []const u8) !
17111711 return result;
17121712}
17131713
1714fn getBuiltinCode(allocator: *Allocator, env_map: *std.BufMap, zig_exe: []const u8) ![]const u8 {
1714fn getBuiltinCode(allocator: Allocator, env_map: *std.BufMap, zig_exe: []const u8) ![]const u8 {
17151715 const result = try exec(allocator, env_map, &[_][]const u8{ zig_exe, "build-obj", "--show-builtin" });
17161716 return result.stdout;
17171717}
doc/langref.html.in+14-14
......@@ -7362,7 +7362,7 @@ fn amain() !void {
73627362}
73637363
73647364var global_download_frame: anyframe = undefined;
7365fn fetchUrl(allocator: *Allocator, url: []const u8) ![]u8 {
7365fn fetchUrl(allocator: Allocator, url: []const u8) ![]u8 {
73667366 _ = url; // this is just an example, we don't actually do it!
73677367 const result = try allocator.dupe(u8, "this is the downloaded url contents");
73687368 errdefer allocator.free(result);
......@@ -7374,7 +7374,7 @@ fn fetchUrl(allocator: *Allocator, url: []const u8) ![]u8 {
73747374}
73757375
73767376var global_file_frame: anyframe = undefined;
7377fn readFile(allocator: *Allocator, filename: []const u8) ![]u8 {
7377fn readFile(allocator: Allocator, filename: []const u8) ![]u8 {
73787378 _ = filename; // this is just an example, we don't actually do it!
73797379 const result = try allocator.dupe(u8, "this is the file contents");
73807380 errdefer allocator.free(result);
......@@ -7433,7 +7433,7 @@ fn amain() !void {
74337433 std.debug.print("file_text: {s}\n", .{file_text});
74347434}
74357435
7436fn fetchUrl(allocator: *Allocator, url: []const u8) ![]u8 {
7436fn fetchUrl(allocator: Allocator, url: []const u8) ![]u8 {
74377437 _ = url; // this is just an example, we don't actually do it!
74387438 const result = try allocator.dupe(u8, "this is the downloaded url contents");
74397439 errdefer allocator.free(result);
......@@ -7441,7 +7441,7 @@ fn fetchUrl(allocator: *Allocator, url: []const u8) ![]u8 {
74417441 return result;
74427442}
74437443
7444fn readFile(allocator: *Allocator, filename: []const u8) ![]u8 {
7444fn readFile(allocator: Allocator, filename: []const u8) ![]u8 {
74457445 _ = filename; // this is just an example, we don't actually do it!
74467446 const result = try allocator.dupe(u8, "this is the file contents");
74477447 errdefer allocator.free(result);
......@@ -10050,8 +10050,8 @@ pub fn main() void {
1005010050 C has a default allocator - <code>malloc</code>, <code>realloc</code>, and <code>free</code>.
1005110051 When linking against libc, Zig exposes this allocator with {#syntax#}std.heap.c_allocator{#endsyntax#}.
1005210052 However, by convention, there is no default allocator in Zig. Instead, functions which need to
10053 allocate accept an {#syntax#}*Allocator{#endsyntax#} parameter. Likewise, data structures such as
10054 {#syntax#}std.ArrayList{#endsyntax#} accept an {#syntax#}*Allocator{#endsyntax#} parameter in
10053 allocate accept an {#syntax#}Allocator{#endsyntax#} parameter. Likewise, data structures such as
10054 {#syntax#}std.ArrayList{#endsyntax#} accept an {#syntax#}Allocator{#endsyntax#} parameter in
1005510055 their initialization functions:
1005610056 </p>
1005710057 {#code_begin|test|allocator#}
......@@ -10061,12 +10061,12 @@ const expect = std.testing.expect;
1006110061
1006210062test "using an allocator" {
1006310063 var buffer: [100]u8 = undefined;
10064 const allocator = &std.heap.FixedBufferAllocator.init(&buffer).allocator;
10064 const allocator = std.heap.FixedBufferAllocator.init(&buffer).allocator();
1006510065 const result = try concat(allocator, "foo", "bar");
1006610066 try expect(std.mem.eql(u8, "foobar", result));
1006710067}
1006810068
10069fn concat(allocator: *Allocator, a: []const u8, b: []const u8) ![]u8 {
10069fn concat(allocator: Allocator, a: []const u8, b: []const u8) ![]u8 {
1007010070 const result = try allocator.alloc(u8, a.len + b.len);
1007110071 std.mem.copy(u8, result, a);
1007210072 std.mem.copy(u8, result[a.len..], b);
......@@ -10091,7 +10091,7 @@ fn concat(allocator: *Allocator, a: []const u8, b: []const u8) ![]u8 {
1009110091 </p>
1009210092 <ol>
1009310093 <li>
10094 Are you making a library? In this case, best to accept an {#syntax#}*Allocator{#endsyntax#}
10094 Are you making a library? In this case, best to accept an {#syntax#}Allocator{#endsyntax#}
1009510095 as a parameter and allow your library's users to decide what allocator to use.
1009610096 </li>
1009710097 <li>Are you linking libc? In this case, {#syntax#}std.heap.c_allocator{#endsyntax#} is likely
......@@ -10114,7 +10114,7 @@ pub fn main() !void {
1011410114 var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
1011510115 defer arena.deinit();
1011610116
10117 const allocator = &arena.allocator;
10117 const allocator = arena.allocator();
1011810118
1011910119 const ptr = try allocator.create(i32);
1012010120 std.debug.print("ptr={*}\n", .{ptr});
......@@ -10200,7 +10200,7 @@ test "string literal to constant slice" {
1020010200 {#header_open|Implementing an Allocator#}
1020110201 <p>Zig programmers can implement their own allocators by fulfilling the Allocator interface.
1020210202 In order to do this one must read carefully the documentation comments in std/mem.zig and
10203 then supply a {#syntax#}reallocFn{#endsyntax#} and a {#syntax#}shrinkFn{#endsyntax#}.
10203 then supply a {#syntax#}allocFn{#endsyntax#} and a {#syntax#}resizeFn{#endsyntax#}.
1020410204 </p>
1020510205 <p>
1020610206 There are many example allocators to look at for inspiration. Look at std/heap.zig and
......@@ -10281,7 +10281,7 @@ test "string literal to constant slice" {
1028110281 <p>
1028210282 For example, the function's documentation may say "caller owns the returned memory", in which case
1028310283 the code that calls the function must have a plan for when to free that memory. Probably in this situation,
10284 the function will accept an {#syntax#}*Allocator{#endsyntax#} parameter.
10284 the function will accept an {#syntax#}Allocator{#endsyntax#} parameter.
1028510285 </p>
1028610286 <p>
1028710287 Sometimes the lifetime of a pointer may be more complicated. For example, the
......@@ -10820,7 +10820,7 @@ const std = @import("std");
1082010820
1082110821pub fn main() !void {
1082210822 var general_purpose_allocator = std.heap.GeneralPurposeAllocator(.{}){};
10823 const gpa = &general_purpose_allocator.allocator;
10823 const gpa = general_purpose_allocator.allocator();
1082410824 const args = try std.process.argsAlloc(gpa);
1082510825 defer std.process.argsFree(gpa, args);
1082610826
......@@ -10842,7 +10842,7 @@ const PreopenList = std.fs.wasi.PreopenList;
1084210842
1084310843pub fn main() !void {
1084410844 var general_purpose_allocator = std.heap.GeneralPurposeAllocator(.{}){};
10845 const gpa = &general_purpose_allocator.allocator;
10845 const gpa = general_purpose_allocator.allocator();
1084610846
1084710847 var preopens = PreopenList.init(gpa);
1084810848 defer preopens.deinit();
lib/std/Thread.zig+1-1
......@@ -460,7 +460,7 @@ const WindowsThreadImpl = struct {
460460 errdefer assert(windows.kernel32.HeapFree(heap_handle, 0, alloc_ptr) != 0);
461461
462462 const instance_bytes = @ptrCast([*]u8, alloc_ptr)[0..alloc_bytes];
463 const instance = std.heap.FixedBufferAllocator.init(instance_bytes).allocator.create(Instance) catch unreachable;
463 const instance = std.heap.FixedBufferAllocator.init(instance_bytes).allocator().create(Instance) catch unreachable;
464464 instance.* = .{
465465 .fn_args = args,
466466 .thread = .{
lib/std/array_hash_map.zig+33-33
......@@ -79,7 +79,7 @@ pub fn ArrayHashMap(
7979 comptime std.hash_map.verifyContext(Context, K, K, u32);
8080 return struct {
8181 unmanaged: Unmanaged,
82 allocator: *Allocator,
82 allocator: Allocator,
8383 ctx: Context,
8484
8585 /// The ArrayHashMapUnmanaged type using the same settings as this managed map.
......@@ -118,12 +118,12 @@ pub fn ArrayHashMap(
118118 const Self = @This();
119119
120120 /// Create an ArrayHashMap instance which will use a specified allocator.
121 pub fn init(allocator: *Allocator) Self {
121 pub fn init(allocator: Allocator) Self {
122122 if (@sizeOf(Context) != 0)
123123 @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call initContext instead.");
124124 return initContext(allocator, undefined);
125125 }
126 pub fn initContext(allocator: *Allocator, ctx: Context) Self {
126 pub fn initContext(allocator: Allocator, ctx: Context) Self {
127127 return .{
128128 .unmanaged = .{},
129129 .allocator = allocator,
......@@ -383,7 +383,7 @@ pub fn ArrayHashMap(
383383 /// Create a copy of the hash map which can be modified separately.
384384 /// The copy uses the same context as this instance, but the specified
385385 /// allocator.
386 pub fn cloneWithAllocator(self: Self, allocator: *Allocator) !Self {
386 pub fn cloneWithAllocator(self: Self, allocator: Allocator) !Self {
387387 var other = try self.unmanaged.cloneContext(allocator, self.ctx);
388388 return other.promoteContext(allocator, self.ctx);
389389 }
......@@ -396,7 +396,7 @@ pub fn ArrayHashMap(
396396 }
397397 /// Create a copy of the hash map which can be modified separately.
398398 /// The copy uses the specified allocator and context.
399 pub fn cloneWithAllocatorAndContext(self: Self, allocator: *Allocator, ctx: anytype) !ArrayHashMap(K, V, @TypeOf(ctx), store_hash) {
399 pub fn cloneWithAllocatorAndContext(self: Self, allocator: Allocator, ctx: anytype) !ArrayHashMap(K, V, @TypeOf(ctx), store_hash) {
400400 var other = try self.unmanaged.cloneContext(allocator, ctx);
401401 return other.promoteContext(allocator, ctx);
402402 }
......@@ -533,12 +533,12 @@ pub fn ArrayHashMapUnmanaged(
533533
534534 /// Convert from an unmanaged map to a managed map. After calling this,
535535 /// the promoted map should no longer be used.
536 pub fn promote(self: Self, allocator: *Allocator) Managed {
536 pub fn promote(self: Self, allocator: Allocator) Managed {
537537 if (@sizeOf(Context) != 0)
538538 @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call promoteContext instead.");
539539 return self.promoteContext(allocator, undefined);
540540 }
541 pub fn promoteContext(self: Self, allocator: *Allocator, ctx: Context) Managed {
541 pub fn promoteContext(self: Self, allocator: Allocator, ctx: Context) Managed {
542542 return .{
543543 .unmanaged = self,
544544 .allocator = allocator,
......@@ -549,7 +549,7 @@ pub fn ArrayHashMapUnmanaged(
549549 /// Frees the backing allocation and leaves the map in an undefined state.
550550 /// Note that this does not free keys or values. You must take care of that
551551 /// before calling this function, if it is needed.
552 pub fn deinit(self: *Self, allocator: *Allocator) void {
552 pub fn deinit(self: *Self, allocator: Allocator) void {
553553 self.entries.deinit(allocator);
554554 if (self.index_header) |header| {
555555 header.free(allocator);
......@@ -570,7 +570,7 @@ pub fn ArrayHashMapUnmanaged(
570570 }
571571
572572 /// Clears the map and releases the backing allocation
573 pub fn clearAndFree(self: *Self, allocator: *Allocator) void {
573 pub fn clearAndFree(self: *Self, allocator: Allocator) void {
574574 self.entries.shrinkAndFree(allocator, 0);
575575 if (self.index_header) |header| {
576576 header.free(allocator);
......@@ -633,24 +633,24 @@ pub fn ArrayHashMapUnmanaged(
633633 /// Otherwise, puts a new item with undefined value, and
634634 /// the `Entry` pointer points to it. Caller should then initialize
635635 /// the value (but not the key).
636 pub fn getOrPut(self: *Self, allocator: *Allocator, key: K) !GetOrPutResult {
636 pub fn getOrPut(self: *Self, allocator: Allocator, key: K) !GetOrPutResult {
637637 if (@sizeOf(Context) != 0)
638638 @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call getOrPutContext instead.");
639639 return self.getOrPutContext(allocator, key, undefined);
640640 }
641 pub fn getOrPutContext(self: *Self, allocator: *Allocator, key: K, ctx: Context) !GetOrPutResult {
641 pub fn getOrPutContext(self: *Self, allocator: Allocator, key: K, ctx: Context) !GetOrPutResult {
642642 const gop = try self.getOrPutContextAdapted(allocator, key, ctx, ctx);
643643 if (!gop.found_existing) {
644644 gop.key_ptr.* = key;
645645 }
646646 return gop;
647647 }
648 pub fn getOrPutAdapted(self: *Self, allocator: *Allocator, key: anytype, key_ctx: anytype) !GetOrPutResult {
648 pub fn getOrPutAdapted(self: *Self, allocator: Allocator, key: anytype, key_ctx: anytype) !GetOrPutResult {
649649 if (@sizeOf(Context) != 0)
650650 @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call getOrPutContextAdapted instead.");
651651 return self.getOrPutContextAdapted(allocator, key, key_ctx, undefined);
652652 }
653 pub fn getOrPutContextAdapted(self: *Self, allocator: *Allocator, key: anytype, key_ctx: anytype, ctx: Context) !GetOrPutResult {
653 pub fn getOrPutContextAdapted(self: *Self, allocator: Allocator, key: anytype, key_ctx: anytype, ctx: Context) !GetOrPutResult {
654654 self.ensureTotalCapacityContext(allocator, self.entries.len + 1, ctx) catch |err| {
655655 // "If key exists this function cannot fail."
656656 const index = self.getIndexAdapted(key, key_ctx) orelse return err;
......@@ -731,12 +731,12 @@ pub fn ArrayHashMapUnmanaged(
731731 }
732732 }
733733
734 pub fn getOrPutValue(self: *Self, allocator: *Allocator, key: K, value: V) !GetOrPutResult {
734 pub fn getOrPutValue(self: *Self, allocator: Allocator, key: K, value: V) !GetOrPutResult {
735735 if (@sizeOf(Context) != 0)
736736 @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call getOrPutValueContext instead.");
737737 return self.getOrPutValueContext(allocator, key, value, undefined);
738738 }
739 pub fn getOrPutValueContext(self: *Self, allocator: *Allocator, key: K, value: V, ctx: Context) !GetOrPutResult {
739 pub fn getOrPutValueContext(self: *Self, allocator: Allocator, key: K, value: V, ctx: Context) !GetOrPutResult {
740740 const res = try self.getOrPutContextAdapted(allocator, key, ctx, ctx);
741741 if (!res.found_existing) {
742742 res.key_ptr.* = key;
......@@ -749,12 +749,12 @@ pub fn ArrayHashMapUnmanaged(
749749
750750 /// Increases capacity, guaranteeing that insertions up until the
751751 /// `expected_count` will not cause an allocation, and therefore cannot fail.
752 pub fn ensureTotalCapacity(self: *Self, allocator: *Allocator, new_capacity: usize) !void {
752 pub fn ensureTotalCapacity(self: *Self, allocator: Allocator, new_capacity: usize) !void {
753753 if (@sizeOf(ByIndexContext) != 0)
754754 @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call ensureTotalCapacityContext instead.");
755755 return self.ensureTotalCapacityContext(allocator, new_capacity, undefined);
756756 }
757 pub fn ensureTotalCapacityContext(self: *Self, allocator: *Allocator, new_capacity: usize, ctx: Context) !void {
757 pub fn ensureTotalCapacityContext(self: *Self, allocator: Allocator, new_capacity: usize, ctx: Context) !void {
758758 if (new_capacity <= linear_scan_max) {
759759 try self.entries.ensureTotalCapacity(allocator, new_capacity);
760760 return;
......@@ -781,7 +781,7 @@ pub fn ArrayHashMapUnmanaged(
781781 /// therefore cannot fail.
782782 pub fn ensureUnusedCapacity(
783783 self: *Self,
784 allocator: *Allocator,
784 allocator: Allocator,
785785 additional_capacity: usize,
786786 ) !void {
787787 if (@sizeOf(ByIndexContext) != 0)
......@@ -790,7 +790,7 @@ pub fn ArrayHashMapUnmanaged(
790790 }
791791 pub fn ensureUnusedCapacityContext(
792792 self: *Self,
793 allocator: *Allocator,
793 allocator: Allocator,
794794 additional_capacity: usize,
795795 ctx: Context,
796796 ) !void {
......@@ -808,24 +808,24 @@ pub fn ArrayHashMapUnmanaged(
808808
809809 /// Clobbers any existing data. To detect if a put would clobber
810810 /// existing data, see `getOrPut`.
811 pub fn put(self: *Self, allocator: *Allocator, key: K, value: V) !void {
811 pub fn put(self: *Self, allocator: Allocator, key: K, value: V) !void {
812812 if (@sizeOf(Context) != 0)
813813 @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call putContext instead.");
814814 return self.putContext(allocator, key, value, undefined);
815815 }
816 pub fn putContext(self: *Self, allocator: *Allocator, key: K, value: V, ctx: Context) !void {
816 pub fn putContext(self: *Self, allocator: Allocator, key: K, value: V, ctx: Context) !void {
817817 const result = try self.getOrPutContext(allocator, key, ctx);
818818 result.value_ptr.* = value;
819819 }
820820
821821 /// Inserts a key-value pair into the hash map, asserting that no previous
822822 /// entry with the same key is already present
823 pub fn putNoClobber(self: *Self, allocator: *Allocator, key: K, value: V) !void {
823 pub fn putNoClobber(self: *Self, allocator: Allocator, key: K, value: V) !void {
824824 if (@sizeOf(Context) != 0)
825825 @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call putNoClobberContext instead.");
826826 return self.putNoClobberContext(allocator, key, value, undefined);
827827 }
828 pub fn putNoClobberContext(self: *Self, allocator: *Allocator, key: K, value: V, ctx: Context) !void {
828 pub fn putNoClobberContext(self: *Self, allocator: Allocator, key: K, value: V, ctx: Context) !void {
829829 const result = try self.getOrPutContext(allocator, key, ctx);
830830 assert(!result.found_existing);
831831 result.value_ptr.* = value;
......@@ -859,12 +859,12 @@ pub fn ArrayHashMapUnmanaged(
859859 }
860860
861861 /// Inserts a new `Entry` into the hash map, returning the previous one, if any.
862 pub fn fetchPut(self: *Self, allocator: *Allocator, key: K, value: V) !?KV {
862 pub fn fetchPut(self: *Self, allocator: Allocator, key: K, value: V) !?KV {
863863 if (@sizeOf(Context) != 0)
864864 @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call fetchPutContext instead.");
865865 return self.fetchPutContext(allocator, key, value, undefined);
866866 }
867 pub fn fetchPutContext(self: *Self, allocator: *Allocator, key: K, value: V, ctx: Context) !?KV {
867 pub fn fetchPutContext(self: *Self, allocator: Allocator, key: K, value: V, ctx: Context) !?KV {
868868 const gop = try self.getOrPutContext(allocator, key, ctx);
869869 var result: ?KV = null;
870870 if (gop.found_existing) {
......@@ -1132,12 +1132,12 @@ pub fn ArrayHashMapUnmanaged(
11321132
11331133 /// Create a copy of the hash map which can be modified separately.
11341134 /// The copy uses the same context and allocator as this instance.
1135 pub fn clone(self: Self, allocator: *Allocator) !Self {
1135 pub fn clone(self: Self, allocator: Allocator) !Self {
11361136 if (@sizeOf(ByIndexContext) != 0)
11371137 @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call cloneContext instead.");
11381138 return self.cloneContext(allocator, undefined);
11391139 }
1140 pub fn cloneContext(self: Self, allocator: *Allocator, ctx: Context) !Self {
1140 pub fn cloneContext(self: Self, allocator: Allocator, ctx: Context) !Self {
11411141 var other: Self = .{};
11421142 other.entries = try self.entries.clone(allocator);
11431143 errdefer other.entries.deinit(allocator);
......@@ -1152,12 +1152,12 @@ pub fn ArrayHashMapUnmanaged(
11521152
11531153 /// Rebuilds the key indexes. If the underlying entries has been modified directly, users
11541154 /// can call `reIndex` to update the indexes to account for these new entries.
1155 pub fn reIndex(self: *Self, allocator: *Allocator) !void {
1155 pub fn reIndex(self: *Self, allocator: Allocator) !void {
11561156 if (@sizeOf(ByIndexContext) != 0)
11571157 @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call reIndexContext instead.");
11581158 return self.reIndexContext(allocator, undefined);
11591159 }
1160 pub fn reIndexContext(self: *Self, allocator: *Allocator, ctx: Context) !void {
1160 pub fn reIndexContext(self: *Self, allocator: Allocator, ctx: Context) !void {
11611161 if (self.entries.capacity <= linear_scan_max) return;
11621162 // We're going to rebuild the index header and replace the existing one (if any). The
11631163 // indexes should sized such that they will be at most 60% full.
......@@ -1189,12 +1189,12 @@ pub fn ArrayHashMapUnmanaged(
11891189
11901190 /// Shrinks the underlying `Entry` array to `new_len` elements and discards any associated
11911191 /// index entries. Reduces allocated capacity.
1192 pub fn shrinkAndFree(self: *Self, allocator: *Allocator, new_len: usize) void {
1192 pub fn shrinkAndFree(self: *Self, allocator: Allocator, new_len: usize) void {
11931193 if (@sizeOf(ByIndexContext) != 0)
11941194 @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call shrinkAndFreeContext instead.");
11951195 return self.shrinkAndFreeContext(allocator, new_len, undefined);
11961196 }
1197 pub fn shrinkAndFreeContext(self: *Self, allocator: *Allocator, new_len: usize, ctx: Context) void {
1197 pub fn shrinkAndFreeContext(self: *Self, allocator: Allocator, new_len: usize, ctx: Context) void {
11981198 // Remove index entries from the new length onwards.
11991199 // Explicitly choose to ONLY remove index entries and not the underlying array list
12001200 // entries as we're going to remove them in the subsequent shrink call.
......@@ -1844,7 +1844,7 @@ const IndexHeader = struct {
18441844
18451845 /// Allocates an index header, and fills the entryIndexes array with empty.
18461846 /// The distance array contents are undefined.
1847 fn alloc(allocator: *Allocator, new_bit_index: u8) !*IndexHeader {
1847 fn alloc(allocator: Allocator, new_bit_index: u8) !*IndexHeader {
18481848 const len = @as(usize, 1) << @intCast(math.Log2Int(usize), new_bit_index);
18491849 const index_size = hash_map.capacityIndexSize(new_bit_index);
18501850 const nbytes = @sizeOf(IndexHeader) + index_size * len;
......@@ -1858,7 +1858,7 @@ const IndexHeader = struct {
18581858 }
18591859
18601860 /// Releases the memory for a header and its associated arrays.
1861 fn free(header: *IndexHeader, allocator: *Allocator) void {
1861 fn free(header: *IndexHeader, allocator: Allocator) void {
18621862 const index_size = hash_map.capacityIndexSize(header.bit_index);
18631863 const ptr = @ptrCast([*]align(@alignOf(IndexHeader)) u8, header);
18641864 const slice = ptr[0 .. @sizeOf(IndexHeader) + header.length() * index_size];
lib/std/array_list.zig+28-28
......@@ -42,12 +42,12 @@ pub fn ArrayListAligned(comptime T: type, comptime alignment: ?u29) type {
4242 /// How many T values this list can hold without allocating
4343 /// additional memory.
4444 capacity: usize,
45 allocator: *Allocator,
45 allocator: Allocator,
4646
4747 pub const Slice = if (alignment) |a| ([]align(a) T) else []T;
4848
4949 /// Deinitialize with `deinit` or use `toOwnedSlice`.
50 pub fn init(allocator: *Allocator) Self {
50 pub fn init(allocator: Allocator) Self {
5151 return Self{
5252 .items = &[_]T{},
5353 .capacity = 0,
......@@ -58,7 +58,7 @@ pub fn ArrayListAligned(comptime T: type, comptime alignment: ?u29) type {
5858 /// Initialize with capacity to hold at least `num` elements.
5959 /// The resulting capacity is likely to be equal to `num`.
6060 /// Deinitialize with `deinit` or use `toOwnedSlice`.
61 pub fn initCapacity(allocator: *Allocator, num: usize) !Self {
61 pub fn initCapacity(allocator: Allocator, num: usize) !Self {
6262 var self = Self.init(allocator);
6363 try self.ensureTotalCapacityPrecise(num);
6464 return self;
......@@ -74,7 +74,7 @@ pub fn ArrayListAligned(comptime T: type, comptime alignment: ?u29) type {
7474 /// ArrayList takes ownership of the passed in slice. The slice must have been
7575 /// allocated with `allocator`.
7676 /// Deinitialize with `deinit` or use `toOwnedSlice`.
77 pub fn fromOwnedSlice(allocator: *Allocator, slice: Slice) Self {
77 pub fn fromOwnedSlice(allocator: Allocator, slice: Slice) Self {
7878 return Self{
7979 .items = slice,
8080 .capacity = slice.len,
......@@ -457,33 +457,33 @@ pub fn ArrayListAlignedUnmanaged(comptime T: type, comptime alignment: ?u29) typ
457457 /// Initialize with capacity to hold at least num elements.
458458 /// The resulting capacity is likely to be equal to `num`.
459459 /// Deinitialize with `deinit` or use `toOwnedSlice`.
460 pub fn initCapacity(allocator: *Allocator, num: usize) !Self {
460 pub fn initCapacity(allocator: Allocator, num: usize) !Self {
461461 var self = Self{};
462462 try self.ensureTotalCapacityPrecise(allocator, num);
463463 return self;
464464 }
465465
466466 /// Release all allocated memory.
467 pub fn deinit(self: *Self, allocator: *Allocator) void {
467 pub fn deinit(self: *Self, allocator: Allocator) void {
468468 allocator.free(self.allocatedSlice());
469469 self.* = undefined;
470470 }
471471
472472 /// Convert this list into an analogous memory-managed one.
473473 /// The returned list has ownership of the underlying memory.
474 pub fn toManaged(self: *Self, allocator: *Allocator) ArrayListAligned(T, alignment) {
474 pub fn toManaged(self: *Self, allocator: Allocator) ArrayListAligned(T, alignment) {
475475 return .{ .items = self.items, .capacity = self.capacity, .allocator = allocator };
476476 }
477477
478478 /// The caller owns the returned memory. ArrayList becomes empty.
479 pub fn toOwnedSlice(self: *Self, allocator: *Allocator) Slice {
479 pub fn toOwnedSlice(self: *Self, allocator: Allocator) Slice {
480480 const result = allocator.shrink(self.allocatedSlice(), self.items.len);
481481 self.* = Self{};
482482 return result;
483483 }
484484
485485 /// The caller owns the returned memory. ArrayList becomes empty.
486 pub fn toOwnedSliceSentinel(self: *Self, allocator: *Allocator, comptime sentinel: T) ![:sentinel]T {
486 pub fn toOwnedSliceSentinel(self: *Self, allocator: Allocator, comptime sentinel: T) ![:sentinel]T {
487487 try self.append(allocator, sentinel);
488488 const result = self.toOwnedSlice(allocator);
489489 return result[0 .. result.len - 1 :sentinel];
......@@ -492,7 +492,7 @@ pub fn ArrayListAlignedUnmanaged(comptime T: type, comptime alignment: ?u29) typ
492492 /// Insert `item` at index `n`. Moves `list[n .. list.len]`
493493 /// to higher indices to make room.
494494 /// This operation is O(N).
495 pub fn insert(self: *Self, allocator: *Allocator, n: usize, item: T) !void {
495 pub fn insert(self: *Self, allocator: Allocator, n: usize, item: T) !void {
496496 try self.ensureUnusedCapacity(allocator, 1);
497497 self.items.len += 1;
498498
......@@ -503,7 +503,7 @@ pub fn ArrayListAlignedUnmanaged(comptime T: type, comptime alignment: ?u29) typ
503503 /// Insert slice `items` at index `i`. Moves `list[i .. list.len]` to
504504 /// higher indicices make room.
505505 /// This operation is O(N).
506 pub fn insertSlice(self: *Self, allocator: *Allocator, i: usize, items: []const T) !void {
506 pub fn insertSlice(self: *Self, allocator: Allocator, i: usize, items: []const T) !void {
507507 try self.ensureUnusedCapacity(allocator, items.len);
508508 self.items.len += items.len;
509509
......@@ -515,14 +515,14 @@ pub fn ArrayListAlignedUnmanaged(comptime T: type, comptime alignment: ?u29) typ
515515 /// Grows list if `len < new_items.len`.
516516 /// Shrinks list if `len > new_items.len`
517517 /// Invalidates pointers if this ArrayList is resized.
518 pub fn replaceRange(self: *Self, allocator: *Allocator, start: usize, len: usize, new_items: []const T) !void {
518 pub fn replaceRange(self: *Self, allocator: Allocator, start: usize, len: usize, new_items: []const T) !void {
519519 var managed = self.toManaged(allocator);
520520 try managed.replaceRange(start, len, new_items);
521521 self.* = managed.moveToUnmanaged();
522522 }
523523
524524 /// Extend the list by 1 element. Allocates more memory as necessary.
525 pub fn append(self: *Self, allocator: *Allocator, item: T) !void {
525 pub fn append(self: *Self, allocator: Allocator, item: T) !void {
526526 const new_item_ptr = try self.addOne(allocator);
527527 new_item_ptr.* = item;
528528 }
......@@ -563,7 +563,7 @@ pub fn ArrayListAlignedUnmanaged(comptime T: type, comptime alignment: ?u29) typ
563563
564564 /// Append the slice of items to the list. Allocates more
565565 /// memory as necessary.
566 pub fn appendSlice(self: *Self, allocator: *Allocator, items: []const T) !void {
566 pub fn appendSlice(self: *Self, allocator: Allocator, items: []const T) !void {
567567 try self.ensureUnusedCapacity(allocator, items.len);
568568 self.appendSliceAssumeCapacity(items);
569569 }
......@@ -580,7 +580,7 @@ pub fn ArrayListAlignedUnmanaged(comptime T: type, comptime alignment: ?u29) typ
580580
581581 pub const WriterContext = struct {
582582 self: *Self,
583 allocator: *Allocator,
583 allocator: Allocator,
584584 };
585585
586586 pub const Writer = if (T != u8)
......@@ -590,7 +590,7 @@ pub fn ArrayListAlignedUnmanaged(comptime T: type, comptime alignment: ?u29) typ
590590 std.io.Writer(WriterContext, error{OutOfMemory}, appendWrite);
591591
592592 /// Initializes a Writer which will append to the list.
593 pub fn writer(self: *Self, allocator: *Allocator) Writer {
593 pub fn writer(self: *Self, allocator: Allocator) Writer {
594594 return .{ .context = .{ .self = self, .allocator = allocator } };
595595 }
596596
......@@ -603,7 +603,7 @@ pub fn ArrayListAlignedUnmanaged(comptime T: type, comptime alignment: ?u29) typ
603603
604604 /// Append a value to the list `n` times.
605605 /// Allocates more memory as necessary.
606 pub fn appendNTimes(self: *Self, allocator: *Allocator, value: T, n: usize) !void {
606 pub fn appendNTimes(self: *Self, allocator: Allocator, value: T, n: usize) !void {
607607 const old_len = self.items.len;
608608 try self.resize(allocator, self.items.len + n);
609609 mem.set(T, self.items[old_len..self.items.len], value);
......@@ -621,13 +621,13 @@ pub fn ArrayListAlignedUnmanaged(comptime T: type, comptime alignment: ?u29) typ
621621
622622 /// Adjust the list's length to `new_len`.
623623 /// Does not initialize added items, if any.
624 pub fn resize(self: *Self, allocator: *Allocator, new_len: usize) !void {
624 pub fn resize(self: *Self, allocator: Allocator, new_len: usize) !void {
625625 try self.ensureTotalCapacity(allocator, new_len);
626626 self.items.len = new_len;
627627 }
628628
629629 /// Reduce allocated capacity to `new_len`.
630 pub fn shrinkAndFree(self: *Self, allocator: *Allocator, new_len: usize) void {
630 pub fn shrinkAndFree(self: *Self, allocator: Allocator, new_len: usize) void {
631631 assert(new_len <= self.items.len);
632632
633633 self.items = allocator.realloc(self.allocatedSlice(), new_len) catch |e| switch (e) {
......@@ -653,7 +653,7 @@ pub fn ArrayListAlignedUnmanaged(comptime T: type, comptime alignment: ?u29) typ
653653 }
654654
655655 /// Invalidates all element pointers.
656 pub fn clearAndFree(self: *Self, allocator: *Allocator) void {
656 pub fn clearAndFree(self: *Self, allocator: Allocator) void {
657657 allocator.free(self.allocatedSlice());
658658 self.items.len = 0;
659659 self.capacity = 0;
......@@ -663,7 +663,7 @@ pub fn ArrayListAlignedUnmanaged(comptime T: type, comptime alignment: ?u29) typ
663663
664664 /// Modify the array so that it can hold at least `new_capacity` items.
665665 /// Invalidates pointers if additional memory is needed.
666 pub fn ensureTotalCapacity(self: *Self, allocator: *Allocator, new_capacity: usize) !void {
666 pub fn ensureTotalCapacity(self: *Self, allocator: Allocator, new_capacity: usize) !void {
667667 var better_capacity = self.capacity;
668668 if (better_capacity >= new_capacity) return;
669669
......@@ -679,7 +679,7 @@ pub fn ArrayListAlignedUnmanaged(comptime T: type, comptime alignment: ?u29) typ
679679 /// Like `ensureTotalCapacity`, but the resulting capacity is much more likely
680680 /// (but not guaranteed) to be equal to `new_capacity`.
681681 /// Invalidates pointers if additional memory is needed.
682 pub fn ensureTotalCapacityPrecise(self: *Self, allocator: *Allocator, new_capacity: usize) !void {
682 pub fn ensureTotalCapacityPrecise(self: *Self, allocator: Allocator, new_capacity: usize) !void {
683683 if (self.capacity >= new_capacity) return;
684684
685685 const new_memory = try allocator.reallocAtLeast(self.allocatedSlice(), new_capacity);
......@@ -691,7 +691,7 @@ pub fn ArrayListAlignedUnmanaged(comptime T: type, comptime alignment: ?u29) typ
691691 /// Invalidates pointers if additional memory is needed.
692692 pub fn ensureUnusedCapacity(
693693 self: *Self,
694 allocator: *Allocator,
694 allocator: Allocator,
695695 additional_count: usize,
696696 ) !void {
697697 return self.ensureTotalCapacity(allocator, self.items.len + additional_count);
......@@ -706,7 +706,7 @@ pub fn ArrayListAlignedUnmanaged(comptime T: type, comptime alignment: ?u29) typ
706706
707707 /// Increase length by 1, returning pointer to the new item.
708708 /// The returned pointer becomes invalid when the list resized.
709 pub fn addOne(self: *Self, allocator: *Allocator) !*T {
709 pub fn addOne(self: *Self, allocator: Allocator) !*T {
710710 const newlen = self.items.len + 1;
711711 try self.ensureTotalCapacity(allocator, newlen);
712712 return self.addOneAssumeCapacity();
......@@ -726,7 +726,7 @@ pub fn ArrayListAlignedUnmanaged(comptime T: type, comptime alignment: ?u29) typ
726726 /// Resize the array, adding `n` new elements, which have `undefined` values.
727727 /// The return value is an array pointing to the newly allocated elements.
728728 /// The returned pointer becomes invalid when the list is resized.
729 pub fn addManyAsArray(self: *Self, allocator: *Allocator, comptime n: usize) !*[n]T {
729 pub fn addManyAsArray(self: *Self, allocator: Allocator, comptime n: usize) !*[n]T {
730730 const prev_len = self.items.len;
731731 try self.resize(allocator, self.items.len + n);
732732 return self.items[prev_len..][0..n];
......@@ -1119,7 +1119,7 @@ test "std.ArrayList/ArrayListUnmanaged.insertSlice" {
11191119test "std.ArrayList/ArrayListUnmanaged.replaceRange" {
11201120 var arena = std.heap.ArenaAllocator.init(testing.allocator);
11211121 defer arena.deinit();
1122 const a = &arena.allocator;
1122 const a = arena.allocator();
11231123
11241124 const init = [_]i32{ 1, 2, 3, 4, 5 };
11251125 const new = [_]i32{ 0, 0, 0 };
......@@ -1263,7 +1263,7 @@ test "std.ArrayList/ArrayListUnmanaged.shrink still sets length on error.OutOfMe
12631263 // use an arena allocator to make sure realloc returns error.OutOfMemory
12641264 var arena = std.heap.ArenaAllocator.init(testing.allocator);
12651265 defer arena.deinit();
1266 const a = &arena.allocator;
1266 const a = arena.allocator();
12671267
12681268 {
12691269 var list = ArrayList(i32).init(a);
......@@ -1361,7 +1361,7 @@ test "ArrayListAligned/ArrayListAlignedUnmanaged accepts unaligned slices" {
13611361
13621362test "std.ArrayList(u0)" {
13631363 // An ArrayList on zero-sized types should not need to allocate
1364 const a = &testing.FailingAllocator.init(testing.allocator, 0).allocator;
1364 const a = testing.FailingAllocator.init(testing.allocator, 0).allocator();
13651365
13661366 var list = ArrayList(u0).init(a);
13671367 defer list.deinit();
lib/std/ascii.zig+2-2
......@@ -301,7 +301,7 @@ test "lowerString" {
301301
302302/// Allocates a lower case copy of `ascii_string`.
303303/// Caller owns returned string and must free with `allocator`.
304pub fn allocLowerString(allocator: *std.mem.Allocator, ascii_string: []const u8) ![]u8 {
304pub fn allocLowerString(allocator: std.mem.Allocator, ascii_string: []const u8) ![]u8 {
305305 const result = try allocator.alloc(u8, ascii_string.len);
306306 return lowerString(result, ascii_string);
307307}
......@@ -330,7 +330,7 @@ test "upperString" {
330330
331331/// Allocates an upper case copy of `ascii_string`.
332332/// Caller owns returned string and must free with `allocator`.
333pub fn allocUpperString(allocator: *std.mem.Allocator, ascii_string: []const u8) ![]u8 {
333pub fn allocUpperString(allocator: std.mem.Allocator, ascii_string: []const u8) ![]u8 {
334334 const result = try allocator.alloc(u8, ascii_string.len);
335335 return upperString(result, ascii_string);
336336}
lib/std/atomic/queue.zig+3-3
......@@ -156,7 +156,7 @@ pub fn Queue(comptime T: type) type {
156156}
157157
158158const Context = struct {
159 allocator: *std.mem.Allocator,
159 allocator: std.mem.Allocator,
160160 queue: *Queue(i32),
161161 put_sum: isize,
162162 get_sum: isize,
......@@ -176,8 +176,8 @@ test "std.atomic.Queue" {
176176 var plenty_of_memory = try std.heap.page_allocator.alloc(u8, 300 * 1024);
177177 defer std.heap.page_allocator.free(plenty_of_memory);
178178
179 var fixed_buffer_allocator = std.heap.ThreadSafeFixedBufferAllocator.init(plenty_of_memory);
180 var a = &fixed_buffer_allocator.allocator;
179 var fixed_buffer_allocator = std.heap.FixedBufferAllocator.init(plenty_of_memory);
180 var a = fixed_buffer_allocator.threadSafeAllocator();
181181
182182 var queue = Queue(i32).init();
183183 var context = Context{
lib/std/atomic/stack.zig+3-3
......@@ -69,7 +69,7 @@ pub fn Stack(comptime T: type) type {
6969}
7070
7171const Context = struct {
72 allocator: *std.mem.Allocator,
72 allocator: std.mem.Allocator,
7373 stack: *Stack(i32),
7474 put_sum: isize,
7575 get_sum: isize,
......@@ -88,8 +88,8 @@ test "std.atomic.stack" {
8888 var plenty_of_memory = try std.heap.page_allocator.alloc(u8, 300 * 1024);
8989 defer std.heap.page_allocator.free(plenty_of_memory);
9090
91 var fixed_buffer_allocator = std.heap.ThreadSafeFixedBufferAllocator.init(plenty_of_memory);
92 var a = &fixed_buffer_allocator.allocator;
91 var fixed_buffer_allocator = std.heap.FixedBufferAllocator.init(plenty_of_memory);
92 var a = fixed_buffer_allocator.threadSafeAllocator();
9393
9494 var stack = Stack(i32).init();
9595 var context = Context{
lib/std/bit_set.zig+9-9
......@@ -476,7 +476,7 @@ pub const DynamicBitSetUnmanaged = struct {
476476
477477 /// Creates a bit set with no elements present.
478478 /// If bit_length is not zero, deinit must eventually be called.
479 pub fn initEmpty(bit_length: usize, allocator: *Allocator) !Self {
479 pub fn initEmpty(bit_length: usize, allocator: Allocator) !Self {
480480 var self = Self{};
481481 try self.resize(bit_length, false, allocator);
482482 return self;
......@@ -484,7 +484,7 @@ pub const DynamicBitSetUnmanaged = struct {
484484
485485 /// Creates a bit set with all elements present.
486486 /// If bit_length is not zero, deinit must eventually be called.
487 pub fn initFull(bit_length: usize, allocator: *Allocator) !Self {
487 pub fn initFull(bit_length: usize, allocator: Allocator) !Self {
488488 var self = Self{};
489489 try self.resize(bit_length, true, allocator);
490490 return self;
......@@ -493,7 +493,7 @@ pub const DynamicBitSetUnmanaged = struct {
493493 /// Resizes to a new bit_length. If the new length is larger
494494 /// than the old length, fills any added bits with `fill`.
495495 /// If new_len is not zero, deinit must eventually be called.
496 pub fn resize(self: *@This(), new_len: usize, fill: bool, allocator: *Allocator) !void {
496 pub fn resize(self: *@This(), new_len: usize, fill: bool, allocator: Allocator) !void {
497497 const old_len = self.bit_length;
498498
499499 const old_masks = numMasks(old_len);
......@@ -556,12 +556,12 @@ pub const DynamicBitSetUnmanaged = struct {
556556 /// deinitializes the array and releases its memory.
557557 /// The passed allocator must be the same one used for
558558 /// init* or resize in the past.
559 pub fn deinit(self: *Self, allocator: *Allocator) void {
559 pub fn deinit(self: *Self, allocator: Allocator) void {
560560 self.resize(0, false, allocator) catch unreachable;
561561 }
562562
563563 /// Creates a duplicate of this bit set, using the new allocator.
564 pub fn clone(self: *const Self, new_allocator: *Allocator) !Self {
564 pub fn clone(self: *const Self, new_allocator: Allocator) !Self {
565565 const num_masks = numMasks(self.bit_length);
566566 var copy = Self{};
567567 try copy.resize(self.bit_length, false, new_allocator);
......@@ -742,13 +742,13 @@ pub const DynamicBitSet = struct {
742742 pub const ShiftInt = std.math.Log2Int(MaskInt);
743743
744744 /// The allocator used by this bit set
745 allocator: *Allocator,
745 allocator: Allocator,
746746
747747 /// The number of valid items in this bit set
748748 unmanaged: DynamicBitSetUnmanaged = .{},
749749
750750 /// Creates a bit set with no elements present.
751 pub fn initEmpty(bit_length: usize, allocator: *Allocator) !Self {
751 pub fn initEmpty(bit_length: usize, allocator: Allocator) !Self {
752752 return Self{
753753 .unmanaged = try DynamicBitSetUnmanaged.initEmpty(bit_length, allocator),
754754 .allocator = allocator,
......@@ -756,7 +756,7 @@ pub const DynamicBitSet = struct {
756756 }
757757
758758 /// Creates a bit set with all elements present.
759 pub fn initFull(bit_length: usize, allocator: *Allocator) !Self {
759 pub fn initFull(bit_length: usize, allocator: Allocator) !Self {
760760 return Self{
761761 .unmanaged = try DynamicBitSetUnmanaged.initFull(bit_length, allocator),
762762 .allocator = allocator,
......@@ -777,7 +777,7 @@ pub const DynamicBitSet = struct {
777777 }
778778
779779 /// Creates a duplicate of this bit set, using the new allocator.
780 pub fn clone(self: *const Self, new_allocator: *Allocator) !Self {
780 pub fn clone(self: *const Self, new_allocator: Allocator) !Self {
781781 return Self{
782782 .unmanaged = try self.unmanaged.clone(new_allocator),
783783 .allocator = new_allocator,
lib/std/buf_map.zig+1-1
......@@ -14,7 +14,7 @@ pub const BufMap = struct {
1414 /// Create a BufMap backed by a specific allocator.
1515 /// That allocator will be used for both backing allocations
1616 /// and string deduplication.
17 pub fn init(allocator: *Allocator) BufMap {
17 pub fn init(allocator: Allocator) BufMap {
1818 var self = BufMap{ .hash_map = BufMapHashMap.init(allocator) };
1919 return self;
2020 }
lib/std/buf_set.zig+2-2
......@@ -16,7 +16,7 @@ pub const BufSet = struct {
1616 /// Create a BufSet using an allocator. The allocator will
1717 /// be used internally for both backing allocations and
1818 /// string duplication.
19 pub fn init(a: *Allocator) BufSet {
19 pub fn init(a: Allocator) BufSet {
2020 var self = BufSet{ .hash_map = BufSetHashMap.init(a) };
2121 return self;
2222 }
......@@ -67,7 +67,7 @@ pub const BufSet = struct {
6767 }
6868
6969 /// Get the allocator used by this set
70 pub fn allocator(self: *const BufSet) *Allocator {
70 pub fn allocator(self: *const BufSet) Allocator {
7171 return self.hash_map.allocator;
7272 }
7373
lib/std/build.zig+9-9
......@@ -28,7 +28,7 @@ pub const OptionsStep = @import("build/OptionsStep.zig");
2828pub const Builder = struct {
2929 install_tls: TopLevelStep,
3030 uninstall_tls: TopLevelStep,
31 allocator: *Allocator,
31 allocator: Allocator,
3232 user_input_options: UserInputOptionsMap,
3333 available_options_map: AvailableOptionsMap,
3434 available_options_list: ArrayList(AvailableOption),
......@@ -134,7 +134,7 @@ pub const Builder = struct {
134134 };
135135
136136 pub fn create(
137 allocator: *Allocator,
137 allocator: Allocator,
138138 zig_exe: []const u8,
139139 build_root: []const u8,
140140 cache_root: []const u8,
......@@ -1285,7 +1285,7 @@ test "builder.findProgram compiles" {
12851285 defer arena.deinit();
12861286
12871287 const builder = try Builder.create(
1288 &arena.allocator,
1288 arena.allocator(),
12891289 "zig",
12901290 "zig-cache",
12911291 "zig-cache",
......@@ -3080,7 +3080,7 @@ pub const Step = struct {
30803080 custom,
30813081 };
30823082
3083 pub fn init(id: Id, name: []const u8, allocator: *Allocator, makeFn: fn (*Step) anyerror!void) Step {
3083 pub fn init(id: Id, name: []const u8, allocator: Allocator, makeFn: fn (*Step) anyerror!void) Step {
30843084 return Step{
30853085 .id = id,
30863086 .name = allocator.dupe(u8, name) catch unreachable,
......@@ -3090,7 +3090,7 @@ pub const Step = struct {
30903090 .done_flag = false,
30913091 };
30923092 }
3093 pub fn initNoOp(id: Id, name: []const u8, allocator: *Allocator) Step {
3093 pub fn initNoOp(id: Id, name: []const u8, allocator: Allocator) Step {
30943094 return init(id, name, allocator, makeNoOp);
30953095 }
30963096
......@@ -3117,7 +3117,7 @@ pub const Step = struct {
31173117 }
31183118};
31193119
3120fn doAtomicSymLinks(allocator: *Allocator, output_path: []const u8, filename_major_only: []const u8, filename_name_only: []const u8) !void {
3120fn doAtomicSymLinks(allocator: Allocator, output_path: []const u8, filename_major_only: []const u8, filename_name_only: []const u8) !void {
31213121 const out_dir = fs.path.dirname(output_path) orelse ".";
31223122 const out_basename = fs.path.basename(output_path);
31233123 // sym link for libfoo.so.1 to libfoo.so.1.2.3
......@@ -3141,7 +3141,7 @@ fn doAtomicSymLinks(allocator: *Allocator, output_path: []const u8, filename_maj
31413141}
31423142
31433143/// Returned slice must be freed by the caller.
3144fn findVcpkgRoot(allocator: *Allocator) !?[]const u8 {
3144fn findVcpkgRoot(allocator: Allocator) !?[]const u8 {
31453145 const appdata_path = try fs.getAppDataDir(allocator, "vcpkg");
31463146 defer allocator.free(appdata_path);
31473147
......@@ -3210,7 +3210,7 @@ test "Builder.dupePkg()" {
32103210 var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
32113211 defer arena.deinit();
32123212 var builder = try Builder.create(
3213 &arena.allocator,
3213 arena.allocator(),
32143214 "test",
32153215 "test",
32163216 "test",
......@@ -3255,7 +3255,7 @@ test "LibExeObjStep.addPackage" {
32553255 defer arena.deinit();
32563256
32573257 var builder = try Builder.create(
3258 &arena.allocator,
3258 arena.allocator(),
32593259 "test",
32603260 "test",
32613261 "test",
lib/std/build/InstallRawStep.zig+2-2
......@@ -40,7 +40,7 @@ const BinaryElfOutput = struct {
4040 self.segments.deinit();
4141 }
4242
43 pub fn parse(allocator: *Allocator, elf_file: File) !Self {
43 pub fn parse(allocator: Allocator, elf_file: File) !Self {
4444 var self: Self = .{
4545 .segments = ArrayList(*BinaryElfSegment).init(allocator),
4646 .sections = ArrayList(*BinaryElfSection).init(allocator),
......@@ -298,7 +298,7 @@ fn containsValidAddressRange(segments: []*BinaryElfSegment) bool {
298298 return true;
299299}
300300
301fn emitRaw(allocator: *Allocator, elf_path: []const u8, raw_path: []const u8, format: RawFormat) !void {
301fn emitRaw(allocator: Allocator, elf_path: []const u8, raw_path: []const u8, format: RawFormat) !void {
302302 var elf_file = try fs.cwd().openFile(elf_path, .{});
303303 defer elf_file.close();
304304
lib/std/build/OptionsStep.zig+2-2
......@@ -274,7 +274,7 @@ test "OptionsStep" {
274274 var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
275275 defer arena.deinit();
276276 var builder = try Builder.create(
277 &arena.allocator,
277 arena.allocator(),
278278 "test",
279279 "test",
280280 "test",
......@@ -350,5 +350,5 @@ test "OptionsStep" {
350350 \\
351351 , options.contents.items);
352352
353 _ = try std.zig.parse(&arena.allocator, try options.contents.toOwnedSliceSentinel(0));
353 _ = try std.zig.parse(arena.allocator(), try options.contents.toOwnedSliceSentinel(0));
354354}
lib/std/builtin.zig+1-1
......@@ -75,7 +75,7 @@ pub const StackTrace = struct {
7575 };
7676 const tty_config = std.debug.detectTTYConfig();
7777 try writer.writeAll("\n");
78 std.debug.writeStackTrace(self, writer, &arena.allocator, debug_info, tty_config) catch |err| {
78 std.debug.writeStackTrace(self, writer, arena.allocator(), debug_info, tty_config) catch |err| {
7979 try writer.print("Unable to print stack trace: {s}\n", .{@errorName(err)});
8080 };
8181 try writer.writeAll("\n");
lib/std/child_process.zig+8-8
......@@ -23,7 +23,7 @@ pub const ChildProcess = struct {
2323 handle: if (builtin.os.tag == .windows) windows.HANDLE else void,
2424 thread_handle: if (builtin.os.tag == .windows) windows.HANDLE else void,
2525
26 allocator: *mem.Allocator,
26 allocator: mem.Allocator,
2727
2828 stdin: ?File,
2929 stdout: ?File,
......@@ -90,7 +90,7 @@ pub const ChildProcess = struct {
9090
9191 /// First argument in argv is the executable.
9292 /// On success must call deinit.
93 pub fn init(argv: []const []const u8, allocator: *mem.Allocator) !*ChildProcess {
93 pub fn init(argv: []const []const u8, allocator: mem.Allocator) !*ChildProcess {
9494 const child = try allocator.create(ChildProcess);
9595 child.* = ChildProcess{
9696 .allocator = allocator,
......@@ -329,7 +329,7 @@ pub const ChildProcess = struct {
329329 /// Spawns a child process, waits for it, collecting stdout and stderr, and then returns.
330330 /// If it succeeds, the caller owns result.stdout and result.stderr memory.
331331 pub fn exec(args: struct {
332 allocator: *mem.Allocator,
332 allocator: mem.Allocator,
333333 argv: []const []const u8,
334334 cwd: ?[]const u8 = null,
335335 cwd_dir: ?fs.Dir = null,
......@@ -541,7 +541,7 @@ pub const ChildProcess = struct {
541541
542542 var arena_allocator = std.heap.ArenaAllocator.init(self.allocator);
543543 defer arena_allocator.deinit();
544 const arena = &arena_allocator.allocator;
544 const arena = arena_allocator.allocator();
545545
546546 // The POSIX standard does not allow malloc() between fork() and execve(),
547547 // and `self.allocator` may be a libc allocator.
......@@ -931,7 +931,7 @@ fn windowsCreateProcess(app_name: [*:0]u16, cmd_line: [*:0]u16, envp_ptr: ?[*]u1
931931}
932932
933933/// Caller must dealloc.
934fn windowsCreateCommandLine(allocator: *mem.Allocator, argv: []const []const u8) ![:0]u8 {
934fn windowsCreateCommandLine(allocator: mem.Allocator, argv: []const []const u8) ![:0]u8 {
935935 var buf = std.ArrayList(u8).init(allocator);
936936 defer buf.deinit();
937937
......@@ -1081,7 +1081,7 @@ fn readIntFd(fd: i32) !ErrInt {
10811081}
10821082
10831083/// Caller must free result.
1084pub fn createWindowsEnvBlock(allocator: *mem.Allocator, env_map: *const BufMap) ![]u16 {
1084pub fn createWindowsEnvBlock(allocator: mem.Allocator, env_map: *const BufMap) ![]u16 {
10851085 // count bytes needed
10861086 const max_chars_needed = x: {
10871087 var max_chars_needed: usize = 4; // 4 for the final 4 null bytes
......@@ -1117,7 +1117,7 @@ pub fn createWindowsEnvBlock(allocator: *mem.Allocator, env_map: *const BufMap)
11171117 return allocator.shrink(result, i);
11181118}
11191119
1120pub fn createNullDelimitedEnvMap(arena: *mem.Allocator, env_map: *const std.BufMap) ![:null]?[*:0]u8 {
1120pub fn createNullDelimitedEnvMap(arena: mem.Allocator, env_map: *const std.BufMap) ![:null]?[*:0]u8 {
11211121 const envp_count = env_map.count();
11221122 const envp_buf = try arena.allocSentinel(?[*:0]u8, envp_count, null);
11231123 {
......@@ -1149,7 +1149,7 @@ test "createNullDelimitedEnvMap" {
11491149
11501150 var arena = std.heap.ArenaAllocator.init(allocator);
11511151 defer arena.deinit();
1152 const environ = try createNullDelimitedEnvMap(&arena.allocator, &envmap);
1152 const environ = try createNullDelimitedEnvMap(arena.allocator(), &envmap);
11531153
11541154 try testing.expectEqual(@as(usize, 5), environ.len);
11551155
lib/std/coff.zig+3-3
......@@ -98,7 +98,7 @@ pub const CoffError = error{
9898// Official documentation of the format: https://docs.microsoft.com/en-us/windows/win32/debug/pe-format
9999pub const Coff = struct {
100100 in_file: File,
101 allocator: *mem.Allocator,
101 allocator: mem.Allocator,
102102
103103 coff_header: CoffHeader,
104104 pe_header: OptionalHeader,
......@@ -107,7 +107,7 @@ pub const Coff = struct {
107107 guid: [16]u8,
108108 age: u32,
109109
110 pub fn init(allocator: *mem.Allocator, in_file: File) Coff {
110 pub fn init(allocator: mem.Allocator, in_file: File) Coff {
111111 return Coff{
112112 .in_file = in_file,
113113 .allocator = allocator,
......@@ -324,7 +324,7 @@ pub const Coff = struct {
324324 }
325325
326326 // Return an owned slice full of the section data
327 pub fn getSectionData(self: *Coff, comptime name: []const u8, allocator: *mem.Allocator) ![]u8 {
327 pub fn getSectionData(self: *Coff, comptime name: []const u8, allocator: mem.Allocator) ![]u8 {
328328 const sec = for (self.sections.items) |*sec| {
329329 if (mem.eql(u8, sec.header.name[0..name.len], name)) {
330330 break sec;
lib/std/compress/gzip.zig+3-3
......@@ -24,7 +24,7 @@ pub fn GzipStream(comptime ReaderType: type) type {
2424 error{ CorruptedData, WrongChecksum };
2525 pub const Reader = io.Reader(*Self, Error, read);
2626
27 allocator: *mem.Allocator,
27 allocator: mem.Allocator,
2828 inflater: deflate.InflateStream(ReaderType),
2929 in_reader: ReaderType,
3030 hasher: std.hash.Crc32,
......@@ -37,7 +37,7 @@ pub fn GzipStream(comptime ReaderType: type) type {
3737 modification_time: u32,
3838 },
3939
40 fn init(allocator: *mem.Allocator, source: ReaderType) !Self {
40 fn init(allocator: mem.Allocator, source: ReaderType) !Self {
4141 // gzip header format is specified in RFC1952
4242 const header = try source.readBytesNoEof(10);
4343
......@@ -152,7 +152,7 @@ pub fn GzipStream(comptime ReaderType: type) type {
152152 };
153153}
154154
155pub fn gzipStream(allocator: *mem.Allocator, reader: anytype) !GzipStream(@TypeOf(reader)) {
155pub fn gzipStream(allocator: mem.Allocator, reader: anytype) !GzipStream(@TypeOf(reader)) {
156156 return GzipStream(@TypeOf(reader)).init(allocator, reader);
157157}
158158
lib/std/compress/zlib.zig+3-3
......@@ -17,13 +17,13 @@ pub fn ZlibStream(comptime ReaderType: type) type {
1717 error{ WrongChecksum, Unsupported };
1818 pub const Reader = io.Reader(*Self, Error, read);
1919
20 allocator: *mem.Allocator,
20 allocator: mem.Allocator,
2121 inflater: deflate.InflateStream(ReaderType),
2222 in_reader: ReaderType,
2323 hasher: std.hash.Adler32,
2424 window_slice: []u8,
2525
26 fn init(allocator: *mem.Allocator, source: ReaderType) !Self {
26 fn init(allocator: mem.Allocator, source: ReaderType) !Self {
2727 // Zlib header format is specified in RFC1950
2828 const header = try source.readBytesNoEof(2);
2929
......@@ -88,7 +88,7 @@ pub fn ZlibStream(comptime ReaderType: type) type {
8888 };
8989}
9090
91pub fn zlibStream(allocator: *mem.Allocator, reader: anytype) !ZlibStream(@TypeOf(reader)) {
91pub fn zlibStream(allocator: mem.Allocator, reader: anytype) !ZlibStream(@TypeOf(reader)) {
9292 return ZlibStream(@TypeOf(reader)).init(allocator, reader);
9393}
9494
lib/std/crypto/argon2.zig+7-7
......@@ -201,7 +201,7 @@ fn initBlocks(
201201}
202202
203203fn processBlocks(
204 allocator: *mem.Allocator,
204 allocator: mem.Allocator,
205205 blocks: *Blocks,
206206 time: u32,
207207 memory: u32,
......@@ -240,7 +240,7 @@ fn processBlocksSt(
240240}
241241
242242fn processBlocksMt(
243 allocator: *mem.Allocator,
243 allocator: mem.Allocator,
244244 blocks: *Blocks,
245245 time: u32,
246246 memory: u32,
......@@ -480,7 +480,7 @@ fn indexAlpha(
480480///
481481/// Salt has to be at least 8 bytes length.
482482pub fn kdf(
483 allocator: *mem.Allocator,
483 allocator: mem.Allocator,
484484 derived_key: []u8,
485485 password: []const u8,
486486 salt: []const u8,
......@@ -524,7 +524,7 @@ const PhcFormatHasher = struct {
524524 };
525525
526526 pub fn create(
527 allocator: *mem.Allocator,
527 allocator: mem.Allocator,
528528 password: []const u8,
529529 params: Params,
530530 mode: Mode,
......@@ -550,7 +550,7 @@ const PhcFormatHasher = struct {
550550 }
551551
552552 pub fn verify(
553 allocator: *mem.Allocator,
553 allocator: mem.Allocator,
554554 str: []const u8,
555555 password: []const u8,
556556 ) HasherError!void {
......@@ -579,7 +579,7 @@ const PhcFormatHasher = struct {
579579///
580580/// Only phc encoding is supported.
581581pub const HashOptions = struct {
582 allocator: ?*mem.Allocator,
582 allocator: ?mem.Allocator,
583583 params: Params,
584584 mode: Mode = .argon2id,
585585 encoding: pwhash.Encoding = .phc,
......@@ -609,7 +609,7 @@ pub fn strHash(
609609///
610610/// Allocator is required for argon2.
611611pub const VerifyOptions = struct {
612 allocator: ?*mem.Allocator,
612 allocator: ?mem.Allocator,
613613};
614614
615615/// Verify that a previously computed hash is valid for a given password.
lib/std/crypto/bcrypt.zig+2-2
......@@ -368,7 +368,7 @@ const CryptFormatHasher = struct {
368368
369369/// Options for hashing a password.
370370pub const HashOptions = struct {
371 allocator: ?*mem.Allocator = null,
371 allocator: ?mem.Allocator = null,
372372 params: Params,
373373 encoding: pwhash.Encoding,
374374};
......@@ -394,7 +394,7 @@ pub fn strHash(
394394
395395/// Options for hash verification.
396396pub const VerifyOptions = struct {
397 allocator: ?*mem.Allocator = null,
397 allocator: ?mem.Allocator = null,
398398};
399399
400400/// Verify that a previously computed hash is valid for a given password.
lib/std/crypto/benchmark.zig+1-1
......@@ -363,7 +363,7 @@ pub fn main() !void {
363363
364364 var buffer: [1024]u8 = undefined;
365365 var fixed = std.heap.FixedBufferAllocator.init(buffer[0..]);
366 const args = try std.process.argsAlloc(&fixed.allocator);
366 const args = try std.process.argsAlloc(fixed.allocator());
367367
368368 var filter: ?[]u8 = "";
369369
lib/std/crypto/scrypt.zig+8-8
......@@ -161,7 +161,7 @@ pub const Params = struct {
161161///
162162/// scrypt is defined in RFC 7914.
163163///
164/// allocator: *mem.Allocator.
164/// allocator: mem.Allocator.
165165///
166166/// derived_key: Slice of appropriate size for generated key. Generally 16 or 32 bytes in length.
167167/// May be uninitialized. All bytes will be overwritten.
......@@ -173,7 +173,7 @@ pub const Params = struct {
173173///
174174/// params: Params.
175175pub fn kdf(
176 allocator: *mem.Allocator,
176 allocator: mem.Allocator,
177177 derived_key: []u8,
178178 password: []const u8,
179179 salt: []const u8,
......@@ -406,7 +406,7 @@ const PhcFormatHasher = struct {
406406
407407 /// Return a non-deterministic hash of the password encoded as a PHC-format string
408408 pub fn create(
409 allocator: *mem.Allocator,
409 allocator: mem.Allocator,
410410 password: []const u8,
411411 params: Params,
412412 buf: []u8,
......@@ -429,7 +429,7 @@ const PhcFormatHasher = struct {
429429
430430 /// Verify a password against a PHC-format encoded string
431431 pub fn verify(
432 allocator: *mem.Allocator,
432 allocator: mem.Allocator,
433433 str: []const u8,
434434 password: []const u8,
435435 ) HasherError!void {
......@@ -455,7 +455,7 @@ const CryptFormatHasher = struct {
455455
456456 /// Return a non-deterministic hash of the password encoded into the modular crypt format
457457 pub fn create(
458 allocator: *mem.Allocator,
458 allocator: mem.Allocator,
459459 password: []const u8,
460460 params: Params,
461461 buf: []u8,
......@@ -478,7 +478,7 @@ const CryptFormatHasher = struct {
478478
479479 /// Verify a password against a string in modular crypt format
480480 pub fn verify(
481 allocator: *mem.Allocator,
481 allocator: mem.Allocator,
482482 str: []const u8,
483483 password: []const u8,
484484 ) HasherError!void {
......@@ -497,7 +497,7 @@ const CryptFormatHasher = struct {
497497///
498498/// Allocator is required for scrypt.
499499pub const HashOptions = struct {
500 allocator: ?*mem.Allocator,
500 allocator: ?mem.Allocator,
501501 params: Params,
502502 encoding: pwhash.Encoding,
503503};
......@@ -520,7 +520,7 @@ pub fn strHash(
520520///
521521/// Allocator is required for scrypt.
522522pub const VerifyOptions = struct {
523 allocator: ?*mem.Allocator,
523 allocator: ?mem.Allocator,
524524};
525525
526526/// Verify that a previously computed hash is valid for a given password.
lib/std/cstr.zig+3-3
......@@ -33,7 +33,7 @@ fn testCStrFnsImpl() !void {
3333
3434/// Returns a mutable, null-terminated slice with the same length as `slice`.
3535/// Caller owns the returned memory.
36pub fn addNullByte(allocator: *mem.Allocator, slice: []const u8) ![:0]u8 {
36pub fn addNullByte(allocator: mem.Allocator, slice: []const u8) ![:0]u8 {
3737 const result = try allocator.alloc(u8, slice.len + 1);
3838 mem.copy(u8, result, slice);
3939 result[slice.len] = 0;
......@@ -48,13 +48,13 @@ test "addNullByte" {
4848}
4949
5050pub const NullTerminated2DArray = struct {
51 allocator: *mem.Allocator,
51 allocator: mem.Allocator,
5252 byte_count: usize,
5353 ptr: ?[*:null]?[*:0]u8,
5454
5555 /// Takes N lists of strings, concatenates the lists together, and adds a null terminator
5656 /// Caller must deinit result
57 pub fn fromSlices(allocator: *mem.Allocator, slices: []const []const []const u8) !NullTerminated2DArray {
57 pub fn fromSlices(allocator: mem.Allocator, slices: []const []const []const u8) !NullTerminated2DArray {
5858 var new_len: usize = 1; // 1 for the list null
5959 var byte_count: usize = 0;
6060 for (slices) |slice| {
lib/std/debug.zig+15-14
......@@ -29,7 +29,7 @@ pub const LineInfo = struct {
2929 line: u64,
3030 column: u64,
3131 file_name: []const u8,
32 allocator: ?*mem.Allocator,
32 allocator: ?mem.Allocator,
3333
3434 pub fn deinit(self: LineInfo) void {
3535 const allocator = self.allocator orelse return;
......@@ -339,7 +339,7 @@ const RESET = "\x1b[0m";
339339pub fn writeStackTrace(
340340 stack_trace: std.builtin.StackTrace,
341341 out_stream: anytype,
342 allocator: *mem.Allocator,
342 allocator: mem.Allocator,
343343 debug_info: *DebugInfo,
344344 tty_config: TTY.Config,
345345) !void {
......@@ -662,7 +662,7 @@ pub const OpenSelfDebugInfoError = error{
662662};
663663
664664/// TODO resources https://github.com/ziglang/zig/issues/4353
665pub fn openSelfDebugInfo(allocator: *mem.Allocator) anyerror!DebugInfo {
665pub fn openSelfDebugInfo(allocator: mem.Allocator) anyerror!DebugInfo {
666666 nosuspend {
667667 if (builtin.strip_debug_info)
668668 return error.MissingDebugInfo;
......@@ -688,7 +688,7 @@ pub fn openSelfDebugInfo(allocator: *mem.Allocator) anyerror!DebugInfo {
688688/// it themselves, even on error.
689689/// TODO resources https://github.com/ziglang/zig/issues/4353
690690/// TODO it's weird to take ownership even on error, rework this code.
691fn readCoffDebugInfo(allocator: *mem.Allocator, coff_file: File) !ModuleDebugInfo {
691fn readCoffDebugInfo(allocator: mem.Allocator, coff_file: File) !ModuleDebugInfo {
692692 nosuspend {
693693 errdefer coff_file.close();
694694
......@@ -755,7 +755,7 @@ fn chopSlice(ptr: []const u8, offset: u64, size: u64) ![]const u8 {
755755/// it themselves, even on error.
756756/// TODO resources https://github.com/ziglang/zig/issues/4353
757757/// TODO it's weird to take ownership even on error, rework this code.
758pub fn readElfDebugInfo(allocator: *mem.Allocator, elf_file: File) !ModuleDebugInfo {
758pub fn readElfDebugInfo(allocator: mem.Allocator, elf_file: File) !ModuleDebugInfo {
759759 nosuspend {
760760 const mapped_mem = try mapWholeFile(elf_file);
761761 const hdr = @ptrCast(*const elf.Ehdr, &mapped_mem[0]);
......@@ -827,7 +827,7 @@ pub fn readElfDebugInfo(allocator: *mem.Allocator, elf_file: File) !ModuleDebugI
827827/// This takes ownership of macho_file: users of this function should not close
828828/// it themselves, even on error.
829829/// TODO it's weird to take ownership even on error, rework this code.
830fn readMachODebugInfo(allocator: *mem.Allocator, macho_file: File) !ModuleDebugInfo {
830fn readMachODebugInfo(allocator: mem.Allocator, macho_file: File) !ModuleDebugInfo {
831831 const mapped_mem = try mapWholeFile(macho_file);
832832
833833 const hdr = @ptrCast(
......@@ -1025,10 +1025,10 @@ fn mapWholeFile(file: File) ![]align(mem.page_size) const u8 {
10251025}
10261026
10271027pub const DebugInfo = struct {
1028 allocator: *mem.Allocator,
1028 allocator: mem.Allocator,
10291029 address_map: std.AutoHashMap(usize, *ModuleDebugInfo),
10301030
1031 pub fn init(allocator: *mem.Allocator) DebugInfo {
1031 pub fn init(allocator: mem.Allocator) DebugInfo {
10321032 return DebugInfo{
10331033 .allocator = allocator,
10341034 .address_map = std.AutoHashMap(usize, *ModuleDebugInfo).init(allocator),
......@@ -1278,7 +1278,7 @@ pub const ModuleDebugInfo = switch (native_os) {
12781278 addr_table: std.StringHashMap(u64),
12791279 };
12801280
1281 pub fn allocator(self: @This()) *mem.Allocator {
1281 pub fn allocator(self: @This()) mem.Allocator {
12821282 return self.ofiles.allocator;
12831283 }
12841284
......@@ -1470,7 +1470,7 @@ pub const ModuleDebugInfo = switch (native_os) {
14701470 debug_data: PdbOrDwarf,
14711471 coff: *coff.Coff,
14721472
1473 pub fn allocator(self: @This()) *mem.Allocator {
1473 pub fn allocator(self: @This()) mem.Allocator {
14741474 return self.coff.allocator;
14751475 }
14761476
......@@ -1560,14 +1560,15 @@ fn getSymbolFromDwarf(address: u64, di: *DW.DwarfInfo) !SymbolInfo {
15601560}
15611561
15621562/// TODO multithreaded awareness
1563var debug_info_allocator: ?*mem.Allocator = null;
1563var debug_info_allocator: ?mem.Allocator = null;
15641564var debug_info_arena_allocator: std.heap.ArenaAllocator = undefined;
1565fn getDebugInfoAllocator() *mem.Allocator {
1565fn getDebugInfoAllocator() mem.Allocator {
15661566 if (debug_info_allocator) |a| return a;
15671567
15681568 debug_info_arena_allocator = std.heap.ArenaAllocator.init(std.heap.page_allocator);
1569 debug_info_allocator = &debug_info_arena_allocator.allocator;
1570 return &debug_info_arena_allocator.allocator;
1569 const allocator = debug_info_arena_allocator.allocator();
1570 debug_info_allocator = allocator;
1571 return allocator;
15711572}
15721573
15731574/// Whether or not the current target can print useful debug information when a segfault occurs.
lib/std/dwarf.zig+8-8
......@@ -466,7 +466,7 @@ fn readUnitLength(in_stream: anytype, endian: std.builtin.Endian, is_64: *bool)
466466}
467467
468468// TODO the nosuspends here are workarounds
469fn readAllocBytes(allocator: *mem.Allocator, in_stream: anytype, size: usize) ![]u8 {
469fn readAllocBytes(allocator: mem.Allocator, in_stream: anytype, size: usize) ![]u8 {
470470 const buf = try allocator.alloc(u8, size);
471471 errdefer allocator.free(buf);
472472 if ((try nosuspend in_stream.read(buf)) < size) return error.EndOfFile;
......@@ -481,18 +481,18 @@ fn readAddress(in_stream: anytype, endian: std.builtin.Endian, is_64: bool) !u64
481481 @as(u64, try in_stream.readInt(u32, endian));
482482}
483483
484fn parseFormValueBlockLen(allocator: *mem.Allocator, in_stream: anytype, size: usize) !FormValue {
484fn parseFormValueBlockLen(allocator: mem.Allocator, in_stream: anytype, size: usize) !FormValue {
485485 const buf = try readAllocBytes(allocator, in_stream, size);
486486 return FormValue{ .Block = buf };
487487}
488488
489489// TODO the nosuspends here are workarounds
490fn parseFormValueBlock(allocator: *mem.Allocator, in_stream: anytype, endian: std.builtin.Endian, size: usize) !FormValue {
490fn parseFormValueBlock(allocator: mem.Allocator, in_stream: anytype, endian: std.builtin.Endian, size: usize) !FormValue {
491491 const block_len = try nosuspend in_stream.readVarInt(usize, endian, size);
492492 return parseFormValueBlockLen(allocator, in_stream, block_len);
493493}
494494
495fn parseFormValueConstant(allocator: *mem.Allocator, in_stream: anytype, signed: bool, endian: std.builtin.Endian, comptime size: i32) !FormValue {
495fn parseFormValueConstant(allocator: mem.Allocator, in_stream: anytype, signed: bool, endian: std.builtin.Endian, comptime size: i32) !FormValue {
496496 _ = allocator;
497497 // TODO: Please forgive me, I've worked around zig not properly spilling some intermediate values here.
498498 // `nosuspend` should be removed from all the function calls once it is fixed.
......@@ -520,7 +520,7 @@ fn parseFormValueConstant(allocator: *mem.Allocator, in_stream: anytype, signed:
520520}
521521
522522// TODO the nosuspends here are workarounds
523fn parseFormValueRef(allocator: *mem.Allocator, in_stream: anytype, endian: std.builtin.Endian, size: i32) !FormValue {
523fn parseFormValueRef(allocator: mem.Allocator, in_stream: anytype, endian: std.builtin.Endian, size: i32) !FormValue {
524524 _ = allocator;
525525 return FormValue{
526526 .Ref = switch (size) {
......@@ -535,7 +535,7 @@ fn parseFormValueRef(allocator: *mem.Allocator, in_stream: anytype, endian: std.
535535}
536536
537537// TODO the nosuspends here are workarounds
538fn parseFormValue(allocator: *mem.Allocator, in_stream: anytype, form_id: u64, endian: std.builtin.Endian, is_64: bool) anyerror!FormValue {
538fn parseFormValue(allocator: mem.Allocator, in_stream: anytype, form_id: u64, endian: std.builtin.Endian, is_64: bool) anyerror!FormValue {
539539 return switch (form_id) {
540540 FORM.addr => FormValue{ .Address = try readAddress(in_stream, endian, @sizeOf(usize) == 8) },
541541 FORM.block1 => parseFormValueBlock(allocator, in_stream, endian, 1),
......@@ -604,7 +604,7 @@ pub const DwarfInfo = struct {
604604 compile_unit_list: ArrayList(CompileUnit) = undefined,
605605 func_list: ArrayList(Func) = undefined,
606606
607 pub fn allocator(self: DwarfInfo) *mem.Allocator {
607 pub fn allocator(self: DwarfInfo) mem.Allocator {
608608 return self.abbrev_table_list.allocator;
609609 }
610610
......@@ -1092,7 +1092,7 @@ pub const DwarfInfo = struct {
10921092/// the DwarfInfo fields before calling. These fields can be left undefined:
10931093/// * abbrev_table_list
10941094/// * compile_unit_list
1095pub fn openDwarfDebugInfo(di: *DwarfInfo, allocator: *mem.Allocator) !void {
1095pub fn openDwarfDebugInfo(di: *DwarfInfo, allocator: mem.Allocator) !void {
10961096 di.abbrev_table_list = ArrayList(AbbrevTableHeader).init(allocator);
10971097 di.compile_unit_list = ArrayList(CompileUnit).init(allocator);
10981098 di.func_list = ArrayList(Func).init(allocator);
lib/std/event/group.zig+3-3
......@@ -15,7 +15,7 @@ pub fn Group(comptime ReturnType: type) type {
1515 frame_stack: Stack,
1616 alloc_stack: AllocStack,
1717 lock: Lock,
18 allocator: *Allocator,
18 allocator: Allocator,
1919
2020 const Self = @This();
2121
......@@ -31,7 +31,7 @@ pub fn Group(comptime ReturnType: type) type {
3131 handle: anyframe->ReturnType,
3232 };
3333
34 pub fn init(allocator: *Allocator) Self {
34 pub fn init(allocator: Allocator) Self {
3535 return Self{
3636 .frame_stack = Stack.init(),
3737 .alloc_stack = AllocStack.init(),
......@@ -127,7 +127,7 @@ test "std.event.Group" {
127127
128128 _ = async testGroup(std.heap.page_allocator);
129129}
130fn testGroup(allocator: *Allocator) callconv(.Async) void {
130fn testGroup(allocator: Allocator) callconv(.Async) void {
131131 var count: usize = 0;
132132 var group = Group(void).init(allocator);
133133 var sleep_a_little_frame = async sleepALittle(&count);
lib/std/event/loop.zig+4-4
......@@ -173,12 +173,12 @@ pub const Loop = struct {
173173 // We need at least one of these in case the fs thread wants to use onNextTick
174174 const extra_thread_count = thread_count - 1;
175175 const resume_node_count = std.math.max(extra_thread_count, 1);
176 self.eventfd_resume_nodes = try self.arena.allocator.alloc(
176 self.eventfd_resume_nodes = try self.arena.allocator().alloc(
177177 std.atomic.Stack(ResumeNode.EventFd).Node,
178178 resume_node_count,
179179 );
180180
181 self.extra_threads = try self.arena.allocator.alloc(Thread, extra_thread_count);
181 self.extra_threads = try self.arena.allocator().alloc(Thread, extra_thread_count);
182182
183183 try self.initOsData(extra_thread_count);
184184 errdefer self.deinitOsData();
......@@ -727,7 +727,7 @@ pub const Loop = struct {
727727 /// with `allocator` and freed when the function returns.
728728 /// `func` must return void and it can be an async function.
729729 /// Yields to the event loop, running the function on the next tick.
730 pub fn runDetached(self: *Loop, alloc: *mem.Allocator, comptime func: anytype, args: anytype) error{OutOfMemory}!void {
730 pub fn runDetached(self: *Loop, alloc: mem.Allocator, comptime func: anytype, args: anytype) error{OutOfMemory}!void {
731731 if (!std.io.is_async) @compileError("Can't use runDetached in non-async mode!");
732732 if (@TypeOf(@call(.{}, func, args)) != void) {
733733 @compileError("`func` must not have a return value");
......@@ -735,7 +735,7 @@ pub const Loop = struct {
735735
736736 const Wrapper = struct {
737737 const Args = @TypeOf(args);
738 fn run(func_args: Args, loop: *Loop, allocator: *mem.Allocator) void {
738 fn run(func_args: Args, loop: *Loop, allocator: mem.Allocator) void {
739739 loop.beginOneEvent();
740740 loop.yield();
741741 @call(.{}, func, func_args); // compile error when called with non-void ret type
lib/std/event/rwlock.zig+1-1
......@@ -226,7 +226,7 @@ test "std.event.RwLock" {
226226 const expected_result = [1]i32{shared_it_count * @intCast(i32, shared_test_data.len)} ** shared_test_data.len;
227227 try testing.expectEqualSlices(i32, expected_result, shared_test_data);
228228}
229fn testLock(allocator: *Allocator, lock: *RwLock) callconv(.Async) void {
229fn testLock(allocator: Allocator, lock: *RwLock) callconv(.Async) void {
230230 var read_nodes: [100]Loop.NextTickNode = undefined;
231231 for (read_nodes) |*read_node| {
232232 const frame = allocator.create(@Frame(readRunner)) catch @panic("memory");
lib/std/fifo.zig+2-2
......@@ -33,7 +33,7 @@ pub fn LinearFifo(
3333 };
3434
3535 return struct {
36 allocator: if (buffer_type == .Dynamic) *Allocator else void,
36 allocator: if (buffer_type == .Dynamic) Allocator else void,
3737 buf: if (buffer_type == .Static) [buffer_type.Static]T else []T,
3838 head: usize,
3939 count: usize,
......@@ -69,7 +69,7 @@ pub fn LinearFifo(
6969 }
7070 },
7171 .Dynamic => struct {
72 pub fn init(allocator: *Allocator) Self {
72 pub fn init(allocator: Allocator) Self {
7373 return .{
7474 .allocator = allocator,
7575 .buf = &[_]T{},
lib/std/fmt.zig+2-2
......@@ -1803,7 +1803,7 @@ pub fn count(comptime fmt: []const u8, args: anytype) u64 {
18031803
18041804pub const AllocPrintError = error{OutOfMemory};
18051805
1806pub fn allocPrint(allocator: *mem.Allocator, comptime fmt: []const u8, args: anytype) AllocPrintError![]u8 {
1806pub fn allocPrint(allocator: mem.Allocator, comptime fmt: []const u8, args: anytype) AllocPrintError![]u8 {
18071807 const size = math.cast(usize, count(fmt, args)) catch |err| switch (err) {
18081808 // Output too long. Can't possibly allocate enough memory to display it.
18091809 error.Overflow => return error.OutOfMemory,
......@@ -1816,7 +1816,7 @@ pub fn allocPrint(allocator: *mem.Allocator, comptime fmt: []const u8, args: any
18161816
18171817pub const allocPrint0 = @compileError("deprecated; use allocPrintZ");
18181818
1819pub fn allocPrintZ(allocator: *mem.Allocator, comptime fmt: []const u8, args: anytype) AllocPrintError![:0]u8 {
1819pub fn allocPrintZ(allocator: mem.Allocator, comptime fmt: []const u8, args: anytype) AllocPrintError![:0]u8 {
18201820 const result = try allocPrint(allocator, fmt ++ "\x00", args);
18211821 return result[0 .. result.len - 1 :0];
18221822}
lib/std/fs.zig+8-8
......@@ -64,7 +64,7 @@ pub const need_async_thread = std.io.is_async and switch (builtin.os.tag) {
6464};
6565
6666/// TODO remove the allocator requirement from this API
67pub fn atomicSymLink(allocator: *Allocator, existing_path: []const u8, new_path: []const u8) !void {
67pub fn atomicSymLink(allocator: Allocator, existing_path: []const u8, new_path: []const u8) !void {
6868 if (cwd().symLink(existing_path, new_path, .{})) {
6969 return;
7070 } else |err| switch (err) {
......@@ -875,7 +875,7 @@ pub const Dir = struct {
875875 /// Must call `Walker.deinit` when done.
876876 /// The order of returned file system entries is undefined.
877877 /// `self` will not be closed after walking it.
878 pub fn walk(self: Dir, allocator: *Allocator) !Walker {
878 pub fn walk(self: Dir, allocator: Allocator) !Walker {
879879 var name_buffer = std.ArrayList(u8).init(allocator);
880880 errdefer name_buffer.deinit();
881881
......@@ -1393,7 +1393,7 @@ pub const Dir = struct {
13931393
13941394 /// Same as `Dir.realpath` except caller must free the returned memory.
13951395 /// See also `Dir.realpath`.
1396 pub fn realpathAlloc(self: Dir, allocator: *Allocator, pathname: []const u8) ![]u8 {
1396 pub fn realpathAlloc(self: Dir, allocator: Allocator, pathname: []const u8) ![]u8 {
13971397 // Use of MAX_PATH_BYTES here is valid as the realpath function does not
13981398 // have a variant that takes an arbitrary-size buffer.
13991399 // TODO(#4812): Consider reimplementing realpath or using the POSIX.1-2008
......@@ -1804,7 +1804,7 @@ pub const Dir = struct {
18041804
18051805 /// On success, caller owns returned buffer.
18061806 /// If the file is larger than `max_bytes`, returns `error.FileTooBig`.
1807 pub fn readFileAlloc(self: Dir, allocator: *mem.Allocator, file_path: []const u8, max_bytes: usize) ![]u8 {
1807 pub fn readFileAlloc(self: Dir, allocator: mem.Allocator, file_path: []const u8, max_bytes: usize) ![]u8 {
18081808 return self.readFileAllocOptions(allocator, file_path, max_bytes, null, @alignOf(u8), null);
18091809 }
18101810
......@@ -1815,7 +1815,7 @@ pub const Dir = struct {
18151815 /// Allows specifying alignment and a sentinel value.
18161816 pub fn readFileAllocOptions(
18171817 self: Dir,
1818 allocator: *mem.Allocator,
1818 allocator: mem.Allocator,
18191819 file_path: []const u8,
18201820 max_bytes: usize,
18211821 size_hint: ?usize,
......@@ -2464,7 +2464,7 @@ pub const SelfExePathError = os.ReadLinkError || os.SysCtlError || os.RealPathEr
24642464
24652465/// `selfExePath` except allocates the result on the heap.
24662466/// Caller owns returned memory.
2467pub fn selfExePathAlloc(allocator: *Allocator) ![]u8 {
2467pub fn selfExePathAlloc(allocator: Allocator) ![]u8 {
24682468 // Use of MAX_PATH_BYTES here is justified as, at least on one tested Linux
24692469 // system, readlink will completely fail to return a result larger than
24702470 // PATH_MAX even if given a sufficiently large buffer. This makes it
......@@ -2573,7 +2573,7 @@ pub fn selfExePathW() [:0]const u16 {
25732573
25742574/// `selfExeDirPath` except allocates the result on the heap.
25752575/// Caller owns returned memory.
2576pub fn selfExeDirPathAlloc(allocator: *Allocator) ![]u8 {
2576pub fn selfExeDirPathAlloc(allocator: Allocator) ![]u8 {
25772577 // Use of MAX_PATH_BYTES here is justified as, at least on one tested Linux
25782578 // system, readlink will completely fail to return a result larger than
25792579 // PATH_MAX even if given a sufficiently large buffer. This makes it
......@@ -2596,7 +2596,7 @@ pub fn selfExeDirPath(out_buffer: []u8) SelfExePathError![]const u8 {
25962596
25972597/// `realpath`, except caller must free the returned memory.
25982598/// See also `Dir.realpath`.
2599pub fn realpathAlloc(allocator: *Allocator, pathname: []const u8) ![]u8 {
2599pub fn realpathAlloc(allocator: Allocator, pathname: []const u8) ![]u8 {
26002600 // Use of MAX_PATH_BYTES here is valid as the realpath function does not
26012601 // have a variant that takes an arbitrary-size buffer.
26022602 // TODO(#4812): Consider reimplementing realpath or using the POSIX.1-2008
lib/std/fs/file.zig+2-2
......@@ -420,7 +420,7 @@ pub const File = struct {
420420 /// Reads all the bytes from the current position to the end of the file.
421421 /// On success, caller owns returned buffer.
422422 /// If the file is larger than `max_bytes`, returns `error.FileTooBig`.
423 pub fn readToEndAlloc(self: File, allocator: *mem.Allocator, max_bytes: usize) ![]u8 {
423 pub fn readToEndAlloc(self: File, allocator: mem.Allocator, max_bytes: usize) ![]u8 {
424424 return self.readToEndAllocOptions(allocator, max_bytes, null, @alignOf(u8), null);
425425 }
426426
......@@ -432,7 +432,7 @@ pub const File = struct {
432432 /// Allows specifying alignment and a sentinel value.
433433 pub fn readToEndAllocOptions(
434434 self: File,
435 allocator: *mem.Allocator,
435 allocator: mem.Allocator,
436436 max_bytes: usize,
437437 size_hint: ?usize,
438438 comptime alignment: u29,
lib/std/fs/get_app_data_dir.zig+1-1
......@@ -12,7 +12,7 @@ pub const GetAppDataDirError = error{
1212
1313/// Caller owns returned memory.
1414/// TODO determine if we can remove the allocator requirement
15pub fn getAppDataDir(allocator: *mem.Allocator, appname: []const u8) GetAppDataDirError![]u8 {
15pub fn getAppDataDir(allocator: mem.Allocator, appname: []const u8) GetAppDataDirError![]u8 {
1616 switch (builtin.os.tag) {
1717 .windows => {
1818 var dir_path_ptr: [*:0]u16 = undefined;
lib/std/fs/path.zig+9-9
......@@ -35,7 +35,7 @@ pub fn isSep(byte: u8) bool {
3535
3636/// This is different from mem.join in that the separator will not be repeated if
3737/// it is found at the end or beginning of a pair of consecutive paths.
38fn joinSepMaybeZ(allocator: *Allocator, separator: u8, sepPredicate: fn (u8) bool, paths: []const []const u8, zero: bool) ![]u8 {
38fn joinSepMaybeZ(allocator: Allocator, separator: u8, sepPredicate: fn (u8) bool, paths: []const []const u8, zero: bool) ![]u8 {
3939 if (paths.len == 0) return if (zero) try allocator.dupe(u8, &[1]u8{0}) else &[0]u8{};
4040
4141 // Find first non-empty path index.
......@@ -99,13 +99,13 @@ fn joinSepMaybeZ(allocator: *Allocator, separator: u8, sepPredicate: fn (u8) boo
9999
100100/// Naively combines a series of paths with the native path seperator.
101101/// Allocates memory for the result, which must be freed by the caller.
102pub fn join(allocator: *Allocator, paths: []const []const u8) ![]u8 {
102pub fn join(allocator: Allocator, paths: []const []const u8) ![]u8 {
103103 return joinSepMaybeZ(allocator, sep, isSep, paths, false);
104104}
105105
106106/// Naively combines a series of paths with the native path seperator and null terminator.
107107/// Allocates memory for the result, which must be freed by the caller.
108pub fn joinZ(allocator: *Allocator, paths: []const []const u8) ![:0]u8 {
108pub fn joinZ(allocator: Allocator, paths: []const []const u8) ![:0]u8 {
109109 const out = try joinSepMaybeZ(allocator, sep, isSep, paths, true);
110110 return out[0 .. out.len - 1 :0];
111111}
......@@ -445,7 +445,7 @@ fn asciiEqlIgnoreCase(s1: []const u8, s2: []const u8) bool {
445445}
446446
447447/// On Windows, this calls `resolveWindows` and on POSIX it calls `resolvePosix`.
448pub fn resolve(allocator: *Allocator, paths: []const []const u8) ![]u8 {
448pub fn resolve(allocator: Allocator, paths: []const []const u8) ![]u8 {
449449 if (native_os == .windows) {
450450 return resolveWindows(allocator, paths);
451451 } else {
......@@ -461,7 +461,7 @@ pub fn resolve(allocator: *Allocator, paths: []const []const u8) ![]u8 {
461461/// Path separators are canonicalized to '\\' and drives are canonicalized to capital letters.
462462/// Note: all usage of this function should be audited due to the existence of symlinks.
463463/// Without performing actual syscalls, resolving `..` could be incorrect.
464pub fn resolveWindows(allocator: *Allocator, paths: []const []const u8) ![]u8 {
464pub fn resolveWindows(allocator: Allocator, paths: []const []const u8) ![]u8 {
465465 if (paths.len == 0) {
466466 assert(native_os == .windows); // resolveWindows called on non windows can't use getCwd
467467 return process.getCwdAlloc(allocator);
......@@ -647,7 +647,7 @@ pub fn resolveWindows(allocator: *Allocator, paths: []const []const u8) ![]u8 {
647647/// If all paths are relative it uses the current working directory as a starting point.
648648/// Note: all usage of this function should be audited due to the existence of symlinks.
649649/// Without performing actual syscalls, resolving `..` could be incorrect.
650pub fn resolvePosix(allocator: *Allocator, paths: []const []const u8) ![]u8 {
650pub fn resolvePosix(allocator: Allocator, paths: []const []const u8) ![]u8 {
651651 if (paths.len == 0) {
652652 assert(native_os != .windows); // resolvePosix called on windows can't use getCwd
653653 return process.getCwdAlloc(allocator);
......@@ -1058,7 +1058,7 @@ fn testBasenameWindows(input: []const u8, expected_output: []const u8) !void {
10581058/// resolve to the same path (after calling `resolve` on each), a zero-length
10591059/// string is returned.
10601060/// On Windows this canonicalizes the drive to a capital letter and paths to `\\`.
1061pub fn relative(allocator: *Allocator, from: []const u8, to: []const u8) ![]u8 {
1061pub fn relative(allocator: Allocator, from: []const u8, to: []const u8) ![]u8 {
10621062 if (native_os == .windows) {
10631063 return relativeWindows(allocator, from, to);
10641064 } else {
......@@ -1066,7 +1066,7 @@ pub fn relative(allocator: *Allocator, from: []const u8, to: []const u8) ![]u8 {
10661066 }
10671067}
10681068
1069pub fn relativeWindows(allocator: *Allocator, from: []const u8, to: []const u8) ![]u8 {
1069pub fn relativeWindows(allocator: Allocator, from: []const u8, to: []const u8) ![]u8 {
10701070 const resolved_from = try resolveWindows(allocator, &[_][]const u8{from});
10711071 defer allocator.free(resolved_from);
10721072
......@@ -1139,7 +1139,7 @@ pub fn relativeWindows(allocator: *Allocator, from: []const u8, to: []const u8)
11391139 return [_]u8{};
11401140}
11411141
1142pub fn relativePosix(allocator: *Allocator, from: []const u8, to: []const u8) ![]u8 {
1142pub fn relativePosix(allocator: Allocator, from: []const u8, to: []const u8) ![]u8 {
11431143 const resolved_from = try resolvePosix(allocator, &[_][]const u8{from});
11441144 defer allocator.free(resolved_from);
11451145
lib/std/fs/test.zig+28-22
......@@ -52,9 +52,11 @@ test "accessAbsolute" {
5252
5353 var arena = ArenaAllocator.init(testing.allocator);
5454 defer arena.deinit();
55 const allocator = arena.allocator();
56
5557 const base_path = blk: {
56 const relative_path = try fs.path.join(&arena.allocator, &[_][]const u8{ "zig-cache", "tmp", tmp.sub_path[0..] });
57 break :blk try fs.realpathAlloc(&arena.allocator, relative_path);
58 const relative_path = try fs.path.join(allocator, &[_][]const u8{ "zig-cache", "tmp", tmp.sub_path[0..] });
59 break :blk try fs.realpathAlloc(allocator, relative_path);
5860 };
5961
6062 try fs.accessAbsolute(base_path, .{});
......@@ -69,9 +71,11 @@ test "openDirAbsolute" {
6971 try tmp.dir.makeDir("subdir");
7072 var arena = ArenaAllocator.init(testing.allocator);
7173 defer arena.deinit();
74 const allocator = arena.allocator();
75
7276 const base_path = blk: {
73 const relative_path = try fs.path.join(&arena.allocator, &[_][]const u8{ "zig-cache", "tmp", tmp.sub_path[0..], "subdir" });
74 break :blk try fs.realpathAlloc(&arena.allocator, relative_path);
77 const relative_path = try fs.path.join(allocator, &[_][]const u8{ "zig-cache", "tmp", tmp.sub_path[0..], "subdir" });
78 break :blk try fs.realpathAlloc(allocator, relative_path);
7579 };
7680
7781 {
......@@ -80,8 +84,8 @@ test "openDirAbsolute" {
8084 }
8185
8286 for ([_][]const u8{ ".", ".." }) |sub_path| {
83 const dir_path = try fs.path.join(&arena.allocator, &[_][]const u8{ base_path, sub_path });
84 defer arena.allocator.free(dir_path);
87 const dir_path = try fs.path.join(allocator, &[_][]const u8{ base_path, sub_path });
88 defer allocator.free(dir_path);
8589 var dir = try fs.openDirAbsolute(dir_path, .{});
8690 defer dir.close();
8791 }
......@@ -107,12 +111,12 @@ test "readLinkAbsolute" {
107111 // Get base abs path
108112 var arena = ArenaAllocator.init(testing.allocator);
109113 defer arena.deinit();
114 const allocator = arena.allocator();
110115
111116 const base_path = blk: {
112 const relative_path = try fs.path.join(&arena.allocator, &[_][]const u8{ "zig-cache", "tmp", tmp.sub_path[0..] });
113 break :blk try fs.realpathAlloc(&arena.allocator, relative_path);
117 const relative_path = try fs.path.join(allocator, &[_][]const u8{ "zig-cache", "tmp", tmp.sub_path[0..] });
118 break :blk try fs.realpathAlloc(allocator, relative_path);
114119 };
115 const allocator = &arena.allocator;
116120
117121 {
118122 const target_path = try fs.path.join(allocator, &[_][]const u8{ base_path, "file.txt" });
......@@ -158,15 +162,16 @@ test "Dir.Iterator" {
158162
159163 var arena = ArenaAllocator.init(testing.allocator);
160164 defer arena.deinit();
165 const allocator = arena.allocator();
161166
162 var entries = std.ArrayList(Dir.Entry).init(&arena.allocator);
167 var entries = std.ArrayList(Dir.Entry).init(allocator);
163168
164169 // Create iterator.
165170 var iter = tmp_dir.dir.iterate();
166171 while (try iter.next()) |entry| {
167172 // We cannot just store `entry` as on Windows, we're re-using the name buffer
168173 // which means we'll actually share the `name` pointer between entries!
169 const name = try arena.allocator.dupe(u8, entry.name);
174 const name = try allocator.dupe(u8, entry.name);
170175 try entries.append(Dir.Entry{ .name = name, .kind = entry.kind });
171176 }
172177
......@@ -202,25 +207,26 @@ test "Dir.realpath smoke test" {
202207
203208 var arena = ArenaAllocator.init(testing.allocator);
204209 defer arena.deinit();
210 const allocator = arena.allocator();
205211
206212 const base_path = blk: {
207 const relative_path = try fs.path.join(&arena.allocator, &[_][]const u8{ "zig-cache", "tmp", tmp_dir.sub_path[0..] });
208 break :blk try fs.realpathAlloc(&arena.allocator, relative_path);
213 const relative_path = try fs.path.join(allocator, &[_][]const u8{ "zig-cache", "tmp", tmp_dir.sub_path[0..] });
214 break :blk try fs.realpathAlloc(allocator, relative_path);
209215 };
210216
211217 // First, test non-alloc version
212218 {
213219 var buf1: [fs.MAX_PATH_BYTES]u8 = undefined;
214220 const file_path = try tmp_dir.dir.realpath("test_file", buf1[0..]);
215 const expected_path = try fs.path.join(&arena.allocator, &[_][]const u8{ base_path, "test_file" });
221 const expected_path = try fs.path.join(allocator, &[_][]const u8{ base_path, "test_file" });
216222
217223 try testing.expect(mem.eql(u8, file_path, expected_path));
218224 }
219225
220226 // Next, test alloc version
221227 {
222 const file_path = try tmp_dir.dir.realpathAlloc(&arena.allocator, "test_file");
223 const expected_path = try fs.path.join(&arena.allocator, &[_][]const u8{ base_path, "test_file" });
228 const file_path = try tmp_dir.dir.realpathAlloc(allocator, "test_file");
229 const expected_path = try fs.path.join(allocator, &[_][]const u8{ base_path, "test_file" });
224230
225231 try testing.expect(mem.eql(u8, file_path, expected_path));
226232 }
......@@ -476,11 +482,11 @@ test "renameAbsolute" {
476482 // Get base abs path
477483 var arena = ArenaAllocator.init(testing.allocator);
478484 defer arena.deinit();
479 const allocator = &arena.allocator;
485 const allocator = arena.allocator();
480486
481487 const base_path = blk: {
482 const relative_path = try fs.path.join(&arena.allocator, &[_][]const u8{ "zig-cache", "tmp", tmp_dir.sub_path[0..] });
483 break :blk try fs.realpathAlloc(&arena.allocator, relative_path);
488 const relative_path = try fs.path.join(allocator, &[_][]const u8{ "zig-cache", "tmp", tmp_dir.sub_path[0..] });
489 break :blk try fs.realpathAlloc(allocator, relative_path);
484490 };
485491
486492 try testing.expectError(error.FileNotFound, fs.renameAbsolute(
......@@ -987,11 +993,11 @@ test ". and .. in absolute functions" {
987993
988994 var arena = ArenaAllocator.init(testing.allocator);
989995 defer arena.deinit();
990 const allocator = &arena.allocator;
996 const allocator = arena.allocator();
991997
992998 const base_path = blk: {
993 const relative_path = try fs.path.join(&arena.allocator, &[_][]const u8{ "zig-cache", "tmp", tmp.sub_path[0..] });
994 break :blk try fs.realpathAlloc(&arena.allocator, relative_path);
999 const relative_path = try fs.path.join(allocator, &[_][]const u8{ "zig-cache", "tmp", tmp.sub_path[0..] });
1000 break :blk try fs.realpathAlloc(allocator, relative_path);
9951001 };
9961002
9971003 const subdir_path = try fs.path.join(allocator, &[_][]const u8{ base_path, "./subdir" });
lib/std/fs/wasi.zig+1-1
......@@ -80,7 +80,7 @@ pub const PreopenList = struct {
8080 pub const Error = error{ OutOfMemory, Overflow } || os.UnexpectedError;
8181
8282 /// Deinitialize with `deinit`.
83 pub fn init(allocator: *Allocator) Self {
83 pub fn init(allocator: Allocator) Self {
8484 return Self{ .buffer = InnerList.init(allocator) };
8585 }
8686
lib/std/fs/watch.zig+3-3
......@@ -30,7 +30,7 @@ pub fn Watch(comptime V: type) type {
3030 return struct {
3131 channel: event.Channel(Event.Error!Event),
3232 os_data: OsData,
33 allocator: *Allocator,
33 allocator: Allocator,
3434
3535 const OsData = switch (builtin.os.tag) {
3636 // TODO https://github.com/ziglang/zig/issues/3778
......@@ -96,7 +96,7 @@ pub fn Watch(comptime V: type) type {
9696 pub const Error = WatchEventError;
9797 };
9898
99 pub fn init(allocator: *Allocator, event_buf_count: usize) !*Self {
99 pub fn init(allocator: Allocator, event_buf_count: usize) !*Self {
100100 const self = try allocator.create(Self);
101101 errdefer allocator.destroy(self);
102102
......@@ -648,7 +648,7 @@ test "write a file, watch it, write it again, delete it" {
648648 return testWriteWatchWriteDelete(std.testing.allocator);
649649}
650650
651fn testWriteWatchWriteDelete(allocator: *Allocator) !void {
651fn testWriteWatchWriteDelete(allocator: Allocator) !void {
652652 const file_path = try std.fs.path.join(allocator, &[_][]const u8{ test_tmp_dir, "file.txt" });
653653 defer allocator.free(file_path);
654654
lib/std/hash/auto_hash.zig+1-1
......@@ -309,7 +309,7 @@ test "hash struct deep" {
309309
310310 const Self = @This();
311311
312 pub fn init(allocator: *mem.Allocator, a_: u32, b_: u16, c_: bool) !Self {
312 pub fn init(allocator: mem.Allocator, a_: u32, b_: u16, c_: bool) !Self {
313313 const ptr = try allocator.create(bool);
314314 ptr.* = c_;
315315 return Self{ .a = a_, .b = b_, .c = ptr };
lib/std/hash/benchmark.zig+1-1
......@@ -165,7 +165,7 @@ pub fn main() !void {
165165
166166 var buffer: [1024]u8 = undefined;
167167 var fixed = std.heap.FixedBufferAllocator.init(buffer[0..]);
168 const args = try std.process.argsAlloc(&fixed.allocator);
168 const args = try std.process.argsAlloc(fixed.allocator());
169169
170170 var filter: ?[]u8 = "";
171171 var count: usize = mode(128 * MiB);
lib/std/hash_map.zig+31-31
......@@ -363,7 +363,7 @@ pub fn HashMap(
363363 comptime verifyContext(Context, K, K, u64);
364364 return struct {
365365 unmanaged: Unmanaged,
366 allocator: *Allocator,
366 allocator: Allocator,
367367 ctx: Context,
368368
369369 /// The type of the unmanaged hash map underlying this wrapper
......@@ -390,7 +390,7 @@ pub fn HashMap(
390390 /// Create a managed hash map with an empty context.
391391 /// If the context is not zero-sized, you must use
392392 /// initContext(allocator, ctx) instead.
393 pub fn init(allocator: *Allocator) Self {
393 pub fn init(allocator: Allocator) Self {
394394 if (@sizeOf(Context) != 0) {
395395 @compileError("Context must be specified! Call initContext(allocator, ctx) instead.");
396396 }
......@@ -402,7 +402,7 @@ pub fn HashMap(
402402 }
403403
404404 /// Create a managed hash map with a context
405 pub fn initContext(allocator: *Allocator, ctx: Context) Self {
405 pub fn initContext(allocator: Allocator, ctx: Context) Self {
406406 return .{
407407 .unmanaged = .{},
408408 .allocator = allocator,
......@@ -636,7 +636,7 @@ pub fn HashMap(
636636 }
637637
638638 /// Creates a copy of this map, using a specified allocator
639 pub fn cloneWithAllocator(self: Self, new_allocator: *Allocator) !Self {
639 pub fn cloneWithAllocator(self: Self, new_allocator: Allocator) !Self {
640640 var other = try self.unmanaged.cloneContext(new_allocator, self.ctx);
641641 return other.promoteContext(new_allocator, self.ctx);
642642 }
......@@ -650,7 +650,7 @@ pub fn HashMap(
650650 /// Creates a copy of this map, using a specified allocator and context.
651651 pub fn cloneWithAllocatorAndContext(
652652 self: Self,
653 new_allocator: *Allocator,
653 new_allocator: Allocator,
654654 new_ctx: anytype,
655655 ) !HashMap(K, V, @TypeOf(new_ctx), max_load_percentage) {
656656 var other = try self.unmanaged.cloneContext(new_allocator, new_ctx);
......@@ -841,13 +841,13 @@ pub fn HashMapUnmanaged(
841841
842842 pub const Managed = HashMap(K, V, Context, max_load_percentage);
843843
844 pub fn promote(self: Self, allocator: *Allocator) Managed {
844 pub fn promote(self: Self, allocator: Allocator) Managed {
845845 if (@sizeOf(Context) != 0)
846846 @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call promoteContext instead.");
847847 return promoteContext(self, allocator, undefined);
848848 }
849849
850 pub fn promoteContext(self: Self, allocator: *Allocator, ctx: Context) Managed {
850 pub fn promoteContext(self: Self, allocator: Allocator, ctx: Context) Managed {
851851 return .{
852852 .unmanaged = self,
853853 .allocator = allocator,
......@@ -859,7 +859,7 @@ pub fn HashMapUnmanaged(
859859 return size * 100 < max_load_percentage * cap;
860860 }
861861
862 pub fn deinit(self: *Self, allocator: *Allocator) void {
862 pub fn deinit(self: *Self, allocator: Allocator) void {
863863 self.deallocate(allocator);
864864 self.* = undefined;
865865 }
......@@ -872,20 +872,20 @@ pub fn HashMapUnmanaged(
872872
873873 pub const ensureCapacity = @compileError("deprecated; call `ensureUnusedCapacity` or `ensureTotalCapacity`");
874874
875 pub fn ensureTotalCapacity(self: *Self, allocator: *Allocator, new_size: Size) !void {
875 pub fn ensureTotalCapacity(self: *Self, allocator: Allocator, new_size: Size) !void {
876876 if (@sizeOf(Context) != 0)
877877 @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call ensureTotalCapacityContext instead.");
878878 return ensureTotalCapacityContext(self, allocator, new_size, undefined);
879879 }
880 pub fn ensureTotalCapacityContext(self: *Self, allocator: *Allocator, new_size: Size, ctx: Context) !void {
880 pub fn ensureTotalCapacityContext(self: *Self, allocator: Allocator, new_size: Size, ctx: Context) !void {
881881 if (new_size > self.size)
882882 try self.growIfNeeded(allocator, new_size - self.size, ctx);
883883 }
884884
885 pub fn ensureUnusedCapacity(self: *Self, allocator: *Allocator, additional_size: Size) !void {
885 pub fn ensureUnusedCapacity(self: *Self, allocator: Allocator, additional_size: Size) !void {
886886 return ensureUnusedCapacityContext(self, allocator, additional_size, undefined);
887887 }
888 pub fn ensureUnusedCapacityContext(self: *Self, allocator: *Allocator, additional_size: Size, ctx: Context) !void {
888 pub fn ensureUnusedCapacityContext(self: *Self, allocator: Allocator, additional_size: Size, ctx: Context) !void {
889889 return ensureTotalCapacityContext(self, allocator, self.count() + additional_size, ctx);
890890 }
891891
......@@ -897,7 +897,7 @@ pub fn HashMapUnmanaged(
897897 }
898898 }
899899
900 pub fn clearAndFree(self: *Self, allocator: *Allocator) void {
900 pub fn clearAndFree(self: *Self, allocator: Allocator) void {
901901 self.deallocate(allocator);
902902 self.size = 0;
903903 self.available = 0;
......@@ -962,12 +962,12 @@ pub fn HashMapUnmanaged(
962962 }
963963
964964 /// Insert an entry in the map. Assumes it is not already present.
965 pub fn putNoClobber(self: *Self, allocator: *Allocator, key: K, value: V) !void {
965 pub fn putNoClobber(self: *Self, allocator: Allocator, key: K, value: V) !void {
966966 if (@sizeOf(Context) != 0)
967967 @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call putNoClobberContext instead.");
968968 return self.putNoClobberContext(allocator, key, value, undefined);
969969 }
970 pub fn putNoClobberContext(self: *Self, allocator: *Allocator, key: K, value: V, ctx: Context) !void {
970 pub fn putNoClobberContext(self: *Self, allocator: Allocator, key: K, value: V, ctx: Context) !void {
971971 assert(!self.containsContext(key, ctx));
972972 try self.growIfNeeded(allocator, 1, ctx);
973973
......@@ -1021,12 +1021,12 @@ pub fn HashMapUnmanaged(
10211021 }
10221022
10231023 /// Inserts a new `Entry` into the hash map, returning the previous one, if any.
1024 pub fn fetchPut(self: *Self, allocator: *Allocator, key: K, value: V) !?KV {
1024 pub fn fetchPut(self: *Self, allocator: Allocator, key: K, value: V) !?KV {
10251025 if (@sizeOf(Context) != 0)
10261026 @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call fetchPutContext instead.");
10271027 return self.fetchPutContext(allocator, key, value, undefined);
10281028 }
1029 pub fn fetchPutContext(self: *Self, allocator: *Allocator, key: K, value: V, ctx: Context) !?KV {
1029 pub fn fetchPutContext(self: *Self, allocator: Allocator, key: K, value: V, ctx: Context) !?KV {
10301030 const gop = try self.getOrPutContext(allocator, key, ctx);
10311031 var result: ?KV = null;
10321032 if (gop.found_existing) {
......@@ -1157,12 +1157,12 @@ pub fn HashMapUnmanaged(
11571157 }
11581158
11591159 /// Insert an entry if the associated key is not already present, otherwise update preexisting value.
1160 pub fn put(self: *Self, allocator: *Allocator, key: K, value: V) !void {
1160 pub fn put(self: *Self, allocator: Allocator, key: K, value: V) !void {
11611161 if (@sizeOf(Context) != 0)
11621162 @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call putContext instead.");
11631163 return self.putContext(allocator, key, value, undefined);
11641164 }
1165 pub fn putContext(self: *Self, allocator: *Allocator, key: K, value: V, ctx: Context) !void {
1165 pub fn putContext(self: *Self, allocator: Allocator, key: K, value: V, ctx: Context) !void {
11661166 const result = try self.getOrPutContext(allocator, key, ctx);
11671167 result.value_ptr.* = value;
11681168 }
......@@ -1231,24 +1231,24 @@ pub fn HashMapUnmanaged(
12311231 return null;
12321232 }
12331233
1234 pub fn getOrPut(self: *Self, allocator: *Allocator, key: K) !GetOrPutResult {
1234 pub fn getOrPut(self: *Self, allocator: Allocator, key: K) !GetOrPutResult {
12351235 if (@sizeOf(Context) != 0)
12361236 @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call getOrPutContext instead.");
12371237 return self.getOrPutContext(allocator, key, undefined);
12381238 }
1239 pub fn getOrPutContext(self: *Self, allocator: *Allocator, key: K, ctx: Context) !GetOrPutResult {
1239 pub fn getOrPutContext(self: *Self, allocator: Allocator, key: K, ctx: Context) !GetOrPutResult {
12401240 const gop = try self.getOrPutContextAdapted(allocator, key, ctx, ctx);
12411241 if (!gop.found_existing) {
12421242 gop.key_ptr.* = key;
12431243 }
12441244 return gop;
12451245 }
1246 pub fn getOrPutAdapted(self: *Self, allocator: *Allocator, key: anytype, key_ctx: anytype) !GetOrPutResult {
1246 pub fn getOrPutAdapted(self: *Self, allocator: Allocator, key: anytype, key_ctx: anytype) !GetOrPutResult {
12471247 if (@sizeOf(Context) != 0)
12481248 @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call getOrPutContextAdapted instead.");
12491249 return self.getOrPutContextAdapted(allocator, key, key_ctx, undefined);
12501250 }
1251 pub fn getOrPutContextAdapted(self: *Self, allocator: *Allocator, key: anytype, key_ctx: anytype, ctx: Context) !GetOrPutResult {
1251 pub fn getOrPutContextAdapted(self: *Self, allocator: Allocator, key: anytype, key_ctx: anytype, ctx: Context) !GetOrPutResult {
12521252 self.growIfNeeded(allocator, 1, ctx) catch |err| {
12531253 // If allocation fails, try to do the lookup anyway.
12541254 // If we find an existing item, we can return it.
......@@ -1341,12 +1341,12 @@ pub fn HashMapUnmanaged(
13411341 };
13421342 }
13431343
1344 pub fn getOrPutValue(self: *Self, allocator: *Allocator, key: K, value: V) !Entry {
1344 pub fn getOrPutValue(self: *Self, allocator: Allocator, key: K, value: V) !Entry {
13451345 if (@sizeOf(Context) != 0)
13461346 @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call getOrPutValueContext instead.");
13471347 return self.getOrPutValueContext(allocator, key, value, undefined);
13481348 }
1349 pub fn getOrPutValueContext(self: *Self, allocator: *Allocator, key: K, value: V, ctx: Context) !Entry {
1349 pub fn getOrPutValueContext(self: *Self, allocator: Allocator, key: K, value: V, ctx: Context) !Entry {
13501350 const res = try self.getOrPutAdapted(allocator, key, ctx);
13511351 if (!res.found_existing) {
13521352 res.key_ptr.* = key;
......@@ -1403,18 +1403,18 @@ pub fn HashMapUnmanaged(
14031403 return @truncate(Size, max_load - self.available);
14041404 }
14051405
1406 fn growIfNeeded(self: *Self, allocator: *Allocator, new_count: Size, ctx: Context) !void {
1406 fn growIfNeeded(self: *Self, allocator: Allocator, new_count: Size, ctx: Context) !void {
14071407 if (new_count > self.available) {
14081408 try self.grow(allocator, capacityForSize(self.load() + new_count), ctx);
14091409 }
14101410 }
14111411
1412 pub fn clone(self: Self, allocator: *Allocator) !Self {
1412 pub fn clone(self: Self, allocator: Allocator) !Self {
14131413 if (@sizeOf(Context) != 0)
14141414 @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call cloneContext instead.");
14151415 return self.cloneContext(allocator, @as(Context, undefined));
14161416 }
1417 pub fn cloneContext(self: Self, allocator: *Allocator, new_ctx: anytype) !HashMapUnmanaged(K, V, @TypeOf(new_ctx), max_load_percentage) {
1417 pub fn cloneContext(self: Self, allocator: Allocator, new_ctx: anytype) !HashMapUnmanaged(K, V, @TypeOf(new_ctx), max_load_percentage) {
14181418 var other = HashMapUnmanaged(K, V, @TypeOf(new_ctx), max_load_percentage){};
14191419 if (self.size == 0)
14201420 return other;
......@@ -1439,7 +1439,7 @@ pub fn HashMapUnmanaged(
14391439 return other;
14401440 }
14411441
1442 fn grow(self: *Self, allocator: *Allocator, new_capacity: Size, ctx: Context) !void {
1442 fn grow(self: *Self, allocator: Allocator, new_capacity: Size, ctx: Context) !void {
14431443 @setCold(true);
14441444 const new_cap = std.math.max(new_capacity, minimal_capacity);
14451445 assert(new_cap > self.capacity());
......@@ -1470,7 +1470,7 @@ pub fn HashMapUnmanaged(
14701470 std.mem.swap(Self, self, &map);
14711471 }
14721472
1473 fn allocate(self: *Self, allocator: *Allocator, new_capacity: Size) !void {
1473 fn allocate(self: *Self, allocator: Allocator, new_capacity: Size) !void {
14741474 const header_align = @alignOf(Header);
14751475 const key_align = if (@sizeOf(K) == 0) 1 else @alignOf(K);
14761476 const val_align = if (@sizeOf(V) == 0) 1 else @alignOf(V);
......@@ -1503,7 +1503,7 @@ pub fn HashMapUnmanaged(
15031503 self.metadata = @intToPtr([*]Metadata, metadata);
15041504 }
15051505
1506 fn deallocate(self: *Self, allocator: *Allocator) void {
1506 fn deallocate(self: *Self, allocator: Allocator) void {
15071507 if (self.metadata == null) return;
15081508
15091509 const header_align = @alignOf(Header);
lib/std/heap.zig+241-192
......@@ -97,13 +97,12 @@ const CAllocator = struct {
9797 }
9898
9999 fn alloc(
100 allocator: *Allocator,
100 _: *c_void,
101101 len: usize,
102102 alignment: u29,
103103 len_align: u29,
104104 return_address: usize,
105105 ) error{OutOfMemory}![]u8 {
106 _ = allocator;
107106 _ = return_address;
108107 assert(len > 0);
109108 assert(std.math.isPowerOfTwo(alignment));
......@@ -124,20 +123,15 @@ const CAllocator = struct {
124123 }
125124
126125 fn resize(
127 allocator: *Allocator,
126 _: *c_void,
128127 buf: []u8,
129128 buf_align: u29,
130129 new_len: usize,
131130 len_align: u29,
132131 return_address: usize,
133 ) Allocator.Error!usize {
134 _ = allocator;
132 ) ?usize {
135133 _ = buf_align;
136134 _ = return_address;
137 if (new_len == 0) {
138 alignedFree(buf.ptr);
139 return 0;
140 }
141135 if (new_len <= buf.len) {
142136 return mem.alignAllocLen(buf.len, new_len, len_align);
143137 }
......@@ -147,17 +141,32 @@ const CAllocator = struct {
147141 return mem.alignAllocLen(full_len, new_len, len_align);
148142 }
149143 }
150 return error.OutOfMemory;
144 return null;
145 }
146
147 fn free(
148 _: *c_void,
149 buf: []u8,
150 buf_align: u29,
151 return_address: usize,
152 ) void {
153 _ = buf_align;
154 _ = return_address;
155 alignedFree(buf.ptr);
151156 }
152157};
153158
154159/// Supports the full Allocator interface, including alignment, and exploiting
155160/// `malloc_usable_size` if available. For an allocator that directly calls
156161/// `malloc`/`free`, see `raw_c_allocator`.
157pub const c_allocator = &c_allocator_state;
158var c_allocator_state = Allocator{
159 .allocFn = CAllocator.alloc,
160 .resizeFn = CAllocator.resize,
162pub const c_allocator = Allocator{
163 .ptr = undefined,
164 .vtable = &c_allocator_vtable,
165};
166const c_allocator_vtable = Allocator.VTable{
167 .alloc = CAllocator.alloc,
168 .resize = CAllocator.resize,
169 .free = CAllocator.free,
161170};
162171
163172/// Asserts allocations are within `@alignOf(std.c.max_align_t)` and directly calls
......@@ -165,20 +174,23 @@ var c_allocator_state = Allocator{
165174/// This allocator is safe to use as the backing allocator with
166175/// `ArenaAllocator` for example and is more optimal in such a case
167176/// than `c_allocator`.
168pub const raw_c_allocator = &raw_c_allocator_state;
169var raw_c_allocator_state = Allocator{
170 .allocFn = rawCAlloc,
171 .resizeFn = rawCResize,
177pub const raw_c_allocator = Allocator{
178 .ptr = undefined,
179 .vtable = &raw_c_allocator_vtable,
180};
181const raw_c_allocator_vtable = Allocator.VTable{
182 .alloc = rawCAlloc,
183 .resize = rawCResize,
184 .free = rawCFree,
172185};
173186
174187fn rawCAlloc(
175 self: *Allocator,
188 _: *c_void,
176189 len: usize,
177190 ptr_align: u29,
178191 len_align: u29,
179192 ret_addr: usize,
180193) Allocator.Error![]u8 {
181 _ = self;
182194 _ = len_align;
183195 _ = ret_addr;
184196 assert(ptr_align <= @alignOf(std.c.max_align_t));
......@@ -187,43 +199,46 @@ fn rawCAlloc(
187199}
188200
189201fn rawCResize(
190 self: *Allocator,
202 _: *c_void,
191203 buf: []u8,
192204 old_align: u29,
193205 new_len: usize,
194206 len_align: u29,
195207 ret_addr: usize,
196) Allocator.Error!usize {
197 _ = self;
208) ?usize {
198209 _ = old_align;
199210 _ = ret_addr;
200 if (new_len == 0) {
201 c.free(buf.ptr);
202 return 0;
203 }
204211 if (new_len <= buf.len) {
205212 return mem.alignAllocLen(buf.len, new_len, len_align);
206213 }
207 return error.OutOfMemory;
214 return null;
215}
216
217fn rawCFree(
218 _: *c_void,
219 buf: []u8,
220 old_align: u29,
221 ret_addr: usize,
222) void {
223 _ = old_align;
224 _ = ret_addr;
225 c.free(buf.ptr);
208226}
209227
210228/// This allocator makes a syscall directly for every allocation and free.
211229/// Thread-safe and lock-free.
212230pub const page_allocator = if (builtin.target.isWasm())
213 &wasm_page_allocator_state
231 Allocator{
232 .ptr = undefined,
233 .vtable = &WasmPageAllocator.vtable,
234 }
214235else if (builtin.target.os.tag == .freestanding)
215236 root.os.heap.page_allocator
216237else
217 &page_allocator_state;
218
219var page_allocator_state = Allocator{
220 .allocFn = PageAllocator.alloc,
221 .resizeFn = PageAllocator.resize,
222};
223var wasm_page_allocator_state = Allocator{
224 .allocFn = WasmPageAllocator.alloc,
225 .resizeFn = WasmPageAllocator.resize,
226};
238 Allocator{
239 .ptr = undefined,
240 .vtable = &PageAllocator.vtable,
241 };
227242
228243/// Verifies that the adjusted length will still map to the full length
229244pub fn alignPageAllocLen(full_len: usize, len: usize, len_align: u29) usize {
......@@ -236,8 +251,13 @@ pub fn alignPageAllocLen(full_len: usize, len: usize, len_align: u29) usize {
236251pub var next_mmap_addr_hint: ?[*]align(mem.page_size) u8 = null;
237252
238253const PageAllocator = struct {
239 fn alloc(allocator: *Allocator, n: usize, alignment: u29, len_align: u29, ra: usize) error{OutOfMemory}![]u8 {
240 _ = allocator;
254 const vtable = Allocator.VTable{
255 .alloc = alloc,
256 .resize = resize,
257 .free = free,
258 };
259
260 fn alloc(_: *c_void, n: usize, alignment: u29, len_align: u29, ra: usize) error{OutOfMemory}![]u8 {
241261 _ = ra;
242262 assert(n > 0);
243263 const aligned_len = mem.alignForward(n, mem.page_size);
......@@ -335,30 +355,19 @@ const PageAllocator = struct {
335355 }
336356
337357 fn resize(
338 allocator: *Allocator,
358 _: *c_void,
339359 buf_unaligned: []u8,
340360 buf_align: u29,
341361 new_size: usize,
342362 len_align: u29,
343363 return_address: usize,
344 ) Allocator.Error!usize {
345 _ = allocator;
364 ) ?usize {
346365 _ = buf_align;
347366 _ = return_address;
348367 const new_size_aligned = mem.alignForward(new_size, mem.page_size);
349368
350369 if (builtin.os.tag == .windows) {
351370 const w = os.windows;
352 if (new_size == 0) {
353 // From the docs:
354 // "If the dwFreeType parameter is MEM_RELEASE, this parameter
355 // must be 0 (zero). The function frees the entire region that
356 // is reserved in the initial allocation call to VirtualAlloc."
357 // So we can only use MEM_RELEASE when actually releasing the
358 // whole allocation.
359 w.VirtualFree(buf_unaligned.ptr, 0, w.MEM_RELEASE);
360 return 0;
361 }
362371 if (new_size <= buf_unaligned.len) {
363372 const base_addr = @ptrToInt(buf_unaligned.ptr);
364373 const old_addr_end = base_addr + buf_unaligned.len;
......@@ -378,7 +387,7 @@ const PageAllocator = struct {
378387 if (new_size_aligned <= old_size_aligned) {
379388 return alignPageAllocLen(new_size_aligned, new_size, len_align);
380389 }
381 return error.OutOfMemory;
390 return null;
382391 }
383392
384393 const buf_aligned_len = mem.alignForward(buf_unaligned.len, mem.page_size);
......@@ -389,14 +398,25 @@ const PageAllocator = struct {
389398 const ptr = @alignCast(mem.page_size, buf_unaligned.ptr + new_size_aligned);
390399 // TODO: if the next_mmap_addr_hint is within the unmapped range, update it
391400 os.munmap(ptr[0 .. buf_aligned_len - new_size_aligned]);
392 if (new_size_aligned == 0)
393 return 0;
394401 return alignPageAllocLen(new_size_aligned, new_size, len_align);
395402 }
396403
397404 // TODO: call mremap
398405 // TODO: if the next_mmap_addr_hint is within the remapped range, update it
399 return error.OutOfMemory;
406 return null;
407 }
408
409 fn free(_: *c_void, buf_unaligned: []u8, buf_align: u29, return_address: usize) void {
410 _ = buf_align;
411 _ = return_address;
412
413 if (builtin.os.tag == .windows) {
414 os.windows.VirtualFree(buf_unaligned.ptr, 0, os.windows.MEM_RELEASE);
415 } else {
416 const buf_aligned_len = mem.alignForward(buf_unaligned.len, mem.page_size);
417 const ptr = @alignCast(mem.page_size, buf_unaligned.ptr);
418 os.munmap(ptr[0..buf_aligned_len]);
419 }
400420 }
401421};
402422
......@@ -407,6 +427,12 @@ const WasmPageAllocator = struct {
407427 }
408428 }
409429
430 const vtable = Allocator.VTable{
431 .alloc = alloc,
432 .resize = resize,
433 .free = free,
434 };
435
410436 const PageStatus = enum(u1) {
411437 used = 0,
412438 free = 1,
......@@ -492,8 +518,7 @@ const WasmPageAllocator = struct {
492518 return mem.alignForward(memsize, mem.page_size) / mem.page_size;
493519 }
494520
495 fn alloc(allocator: *Allocator, len: usize, alignment: u29, len_align: u29, ra: usize) error{OutOfMemory}![]u8 {
496 _ = allocator;
521 fn alloc(_: *c_void, len: usize, alignment: u29, len_align: u29, ra: usize) error{OutOfMemory}![]u8 {
497522 _ = ra;
498523 const page_count = nPages(len);
499524 const page_idx = try allocPages(page_count, alignment);
......@@ -548,45 +573,57 @@ const WasmPageAllocator = struct {
548573 }
549574
550575 fn resize(
551 allocator: *Allocator,
576 _: *c_void,
552577 buf: []u8,
553578 buf_align: u29,
554579 new_len: usize,
555580 len_align: u29,
556581 return_address: usize,
557 ) error{OutOfMemory}!usize {
558 _ = allocator;
582 ) ?usize {
559583 _ = buf_align;
560584 _ = return_address;
561585 const aligned_len = mem.alignForward(buf.len, mem.page_size);
562 if (new_len > aligned_len) return error.OutOfMemory;
586 if (new_len > aligned_len) return null;
563587 const current_n = nPages(aligned_len);
564588 const new_n = nPages(new_len);
565589 if (new_n != current_n) {
566590 const base = nPages(@ptrToInt(buf.ptr));
567591 freePages(base + new_n, base + current_n);
568592 }
569 return if (new_len == 0) 0 else alignPageAllocLen(new_n * mem.page_size, new_len, len_align);
593 return alignPageAllocLen(new_n * mem.page_size, new_len, len_align);
594 }
595
596 fn free(
597 _: *c_void,
598 buf: []u8,
599 buf_align: u29,
600 return_address: usize,
601 ) void {
602 _ = buf_align;
603 _ = return_address;
604 const aligned_len = mem.alignForward(buf.len, mem.page_size);
605 const current_n = nPages(aligned_len);
606 const base = nPages(@ptrToInt(buf.ptr));
607 freePages(base, base + current_n);
570608 }
571609};
572610
573611pub const HeapAllocator = switch (builtin.os.tag) {
574612 .windows => struct {
575 allocator: Allocator,
576613 heap_handle: ?HeapHandle,
577614
578615 const HeapHandle = os.windows.HANDLE;
579616
580617 pub fn init() HeapAllocator {
581618 return HeapAllocator{
582 .allocator = Allocator{
583 .allocFn = alloc,
584 .resizeFn = resize,
585 },
586619 .heap_handle = null,
587620 };
588621 }
589622
623 pub fn allocator(self: *HeapAllocator) Allocator {
624 return Allocator.init(self, alloc, resize, free);
625 }
626
590627 pub fn deinit(self: *HeapAllocator) void {
591628 if (self.heap_handle) |heap_handle| {
592629 os.windows.HeapDestroy(heap_handle);
......@@ -598,14 +635,13 @@ pub const HeapAllocator = switch (builtin.os.tag) {
598635 }
599636
600637 fn alloc(
601 allocator: *Allocator,
638 self: *HeapAllocator,
602639 n: usize,
603640 ptr_align: u29,
604641 len_align: u29,
605642 return_address: usize,
606643 ) error{OutOfMemory}![]u8 {
607644 _ = return_address;
608 const self = @fieldParentPtr(HeapAllocator, "allocator", allocator);
609645
610646 const amt = n + ptr_align - 1 + @sizeOf(usize);
611647 const optional_heap_handle = @atomicLoad(?HeapHandle, &self.heap_handle, .SeqCst);
......@@ -632,20 +668,15 @@ pub const HeapAllocator = switch (builtin.os.tag) {
632668 }
633669
634670 fn resize(
635 allocator: *Allocator,
671 self: *HeapAllocator,
636672 buf: []u8,
637673 buf_align: u29,
638674 new_size: usize,
639675 len_align: u29,
640676 return_address: usize,
641 ) error{OutOfMemory}!usize {
677 ) ?usize {
642678 _ = buf_align;
643679 _ = return_address;
644 const self = @fieldParentPtr(HeapAllocator, "allocator", allocator);
645 if (new_size == 0) {
646 os.windows.HeapFree(self.heap_handle.?, 0, @intToPtr(*c_void, getRecordPtr(buf).*));
647 return 0;
648 }
649680
650681 const root_addr = getRecordPtr(buf).*;
651682 const align_offset = @ptrToInt(buf.ptr) - root_addr;
......@@ -655,7 +686,7 @@ pub const HeapAllocator = switch (builtin.os.tag) {
655686 os.windows.HEAP_REALLOC_IN_PLACE_ONLY,
656687 @intToPtr(*c_void, root_addr),
657688 amt,
658 ) orelse return error.OutOfMemory;
689 ) orelse return null;
659690 assert(new_ptr == @intToPtr(*c_void, root_addr));
660691 const return_len = init: {
661692 if (len_align == 0) break :init new_size;
......@@ -667,6 +698,17 @@ pub const HeapAllocator = switch (builtin.os.tag) {
667698 getRecordPtr(buf.ptr[0..return_len]).* = root_addr;
668699 return return_len;
669700 }
701
702 fn free(
703 self: *HeapAllocator,
704 buf: []u8,
705 buf_align: u29,
706 return_address: usize,
707 ) void {
708 _ = buf_align;
709 _ = return_address;
710 os.windows.HeapFree(self.heap_handle.?, 0, @intToPtr(*c_void, getRecordPtr(buf).*));
711 }
670712 },
671713 else => @compileError("Unsupported OS"),
672714};
......@@ -682,21 +724,32 @@ fn sliceContainsSlice(container: []u8, slice: []u8) bool {
682724}
683725
684726pub const FixedBufferAllocator = struct {
685 allocator: Allocator,
686727 end_index: usize,
687728 buffer: []u8,
688729
689730 pub fn init(buffer: []u8) FixedBufferAllocator {
690731 return FixedBufferAllocator{
691 .allocator = Allocator{
692 .allocFn = alloc,
693 .resizeFn = resize,
694 },
695732 .buffer = buffer,
696733 .end_index = 0,
697734 };
698735 }
699736
737 /// *WARNING* using this at the same time as the interface returned by `threadSafeAllocator` is not thread safe
738 pub fn allocator(self: *FixedBufferAllocator) Allocator {
739 return Allocator.init(self, alloc, resize, free);
740 }
741
742 /// Provides a lock free thread safe `Allocator` interface to the underlying `FixedBufferAllocator`
743 /// *WARNING* using this at the same time as the interface returned by `getAllocator` is not thread safe
744 pub fn threadSafeAllocator(self: *FixedBufferAllocator) Allocator {
745 return Allocator.init(
746 self,
747 threadSafeAlloc,
748 Allocator.NoResize(FixedBufferAllocator).noResize,
749 Allocator.NoOpFree(FixedBufferAllocator).noOpFree,
750 );
751 }
752
700753 pub fn ownsPtr(self: *FixedBufferAllocator, ptr: [*]u8) bool {
701754 return sliceContainsPtr(self.buffer, ptr);
702755 }
......@@ -707,15 +760,14 @@ pub const FixedBufferAllocator = struct {
707760
708761 /// NOTE: this will not work in all cases, if the last allocation had an adjusted_index
709762 /// then we won't be able to determine what the last allocation was. This is because
710 /// the alignForward operation done in alloc is not reverisible.
763 /// the alignForward operation done in alloc is not reversible.
711764 pub fn isLastAllocation(self: *FixedBufferAllocator, buf: []u8) bool {
712765 return buf.ptr + buf.len == self.buffer.ptr + self.end_index;
713766 }
714767
715 fn alloc(allocator: *Allocator, n: usize, ptr_align: u29, len_align: u29, ra: usize) ![]u8 {
768 fn alloc(self: *FixedBufferAllocator, n: usize, ptr_align: u29, len_align: u29, ra: usize) ![]u8 {
716769 _ = len_align;
717770 _ = ra;
718 const self = @fieldParentPtr(FixedBufferAllocator, "allocator", allocator);
719771 const adjust_off = mem.alignPointerOffset(self.buffer.ptr + self.end_index, ptr_align) orelse
720772 return error.OutOfMemory;
721773 const adjusted_index = self.end_index + adjust_off;
......@@ -730,97 +782,78 @@ pub const FixedBufferAllocator = struct {
730782 }
731783
732784 fn resize(
733 allocator: *Allocator,
785 self: *FixedBufferAllocator,
734786 buf: []u8,
735787 buf_align: u29,
736788 new_size: usize,
737789 len_align: u29,
738790 return_address: usize,
739 ) Allocator.Error!usize {
791 ) ?usize {
740792 _ = buf_align;
741793 _ = return_address;
742 const self = @fieldParentPtr(FixedBufferAllocator, "allocator", allocator);
743794 assert(self.ownsSlice(buf)); // sanity check
744795
745796 if (!self.isLastAllocation(buf)) {
746 if (new_size > buf.len)
747 return error.OutOfMemory;
748 return if (new_size == 0) 0 else mem.alignAllocLen(buf.len, new_size, len_align);
797 if (new_size > buf.len) return null;
798 return mem.alignAllocLen(buf.len, new_size, len_align);
749799 }
750800
751801 if (new_size <= buf.len) {
752802 const sub = buf.len - new_size;
753803 self.end_index -= sub;
754 return if (new_size == 0) 0 else mem.alignAllocLen(buf.len - sub, new_size, len_align);
804 return mem.alignAllocLen(buf.len - sub, new_size, len_align);
755805 }
756806
757807 const add = new_size - buf.len;
758 if (add + self.end_index > self.buffer.len) {
759 return error.OutOfMemory;
760 }
808 if (add + self.end_index > self.buffer.len) return null;
809
761810 self.end_index += add;
762811 return new_size;
763812 }
764813
765 pub fn reset(self: *FixedBufferAllocator) void {
766 self.end_index = 0;
767 }
768};
814 fn free(
815 self: *FixedBufferAllocator,
816 buf: []u8,
817 buf_align: u29,
818 return_address: usize,
819 ) void {
820 _ = buf_align;
821 _ = return_address;
822 assert(self.ownsSlice(buf)); // sanity check
769823
770pub const ThreadSafeFixedBufferAllocator = blk: {
771 if (builtin.single_threaded) {
772 break :blk FixedBufferAllocator;
773 } else {
774 // lock free
775 break :blk struct {
776 allocator: Allocator,
777 end_index: usize,
778 buffer: []u8,
779
780 pub fn init(buffer: []u8) ThreadSafeFixedBufferAllocator {
781 return ThreadSafeFixedBufferAllocator{
782 .allocator = Allocator{
783 .allocFn = alloc,
784 .resizeFn = Allocator.noResize,
785 },
786 .buffer = buffer,
787 .end_index = 0,
788 };
789 }
824 if (self.isLastAllocation(buf)) {
825 self.end_index -= buf.len;
826 }
827 }
790828
791 fn alloc(allocator: *Allocator, n: usize, ptr_align: u29, len_align: u29, ra: usize) ![]u8 {
792 _ = len_align;
793 _ = ra;
794 const self = @fieldParentPtr(ThreadSafeFixedBufferAllocator, "allocator", allocator);
795 var end_index = @atomicLoad(usize, &self.end_index, .SeqCst);
796 while (true) {
797 const adjust_off = mem.alignPointerOffset(self.buffer.ptr + end_index, ptr_align) orelse
798 return error.OutOfMemory;
799 const adjusted_index = end_index + adjust_off;
800 const new_end_index = adjusted_index + n;
801 if (new_end_index > self.buffer.len) {
802 return error.OutOfMemory;
803 }
804 end_index = @cmpxchgWeak(usize, &self.end_index, end_index, new_end_index, .SeqCst, .SeqCst) orelse return self.buffer[adjusted_index..new_end_index];
805 }
829 fn threadSafeAlloc(self: *FixedBufferAllocator, n: usize, ptr_align: u29, len_align: u29, ra: usize) ![]u8 {
830 _ = len_align;
831 _ = ra;
832 var end_index = @atomicLoad(usize, &self.end_index, .SeqCst);
833 while (true) {
834 const adjust_off = mem.alignPointerOffset(self.buffer.ptr + end_index, ptr_align) orelse
835 return error.OutOfMemory;
836 const adjusted_index = end_index + adjust_off;
837 const new_end_index = adjusted_index + n;
838 if (new_end_index > self.buffer.len) {
839 return error.OutOfMemory;
806840 }
841 end_index = @cmpxchgWeak(usize, &self.end_index, end_index, new_end_index, .SeqCst, .SeqCst) orelse return self.buffer[adjusted_index..new_end_index];
842 }
843 }
807844
808 pub fn reset(self: *ThreadSafeFixedBufferAllocator) void {
809 self.end_index = 0;
810 }
811 };
845 pub fn reset(self: *FixedBufferAllocator) void {
846 self.end_index = 0;
812847 }
813848};
814849
815pub fn stackFallback(comptime size: usize, fallback_allocator: *Allocator) StackFallbackAllocator(size) {
850pub const ThreadSafeFixedBufferAllocator = @compileError("ThreadSafeFixedBufferAllocator has been replaced with `threadSafeAllocator` on FixedBufferAllocator");
851
852pub fn stackFallback(comptime size: usize, fallback_allocator: Allocator) StackFallbackAllocator(size) {
816853 return StackFallbackAllocator(size){
817854 .buffer = undefined,
818855 .fallback_allocator = fallback_allocator,
819856 .fixed_buffer_allocator = undefined,
820 .allocator = Allocator{
821 .allocFn = StackFallbackAllocator(size).alloc,
822 .resizeFn = StackFallbackAllocator(size).resize,
823 },
824857 };
825858}
826859
......@@ -829,40 +862,51 @@ pub fn StackFallbackAllocator(comptime size: usize) type {
829862 const Self = @This();
830863
831864 buffer: [size]u8,
832 allocator: Allocator,
833 fallback_allocator: *Allocator,
865 fallback_allocator: Allocator,
834866 fixed_buffer_allocator: FixedBufferAllocator,
835867
836 pub fn get(self: *Self) *Allocator {
868 /// WARNING: This functions both fetches a `std.mem.Allocator` interface to this allocator *and* resets the internal buffer allocator
869 pub fn get(self: *Self) Allocator {
837870 self.fixed_buffer_allocator = FixedBufferAllocator.init(self.buffer[0..]);
838 return &self.allocator;
871 return Allocator.init(self, alloc, resize, free);
839872 }
840873
841874 fn alloc(
842 allocator: *Allocator,
875 self: *Self,
843876 len: usize,
844877 ptr_align: u29,
845878 len_align: u29,
846879 return_address: usize,
847880 ) error{OutOfMemory}![]u8 {
848 const self = @fieldParentPtr(Self, "allocator", allocator);
849 return FixedBufferAllocator.alloc(&self.fixed_buffer_allocator.allocator, len, ptr_align, len_align, return_address) catch
850 return self.fallback_allocator.allocFn(self.fallback_allocator, len, ptr_align, len_align, return_address);
881 return FixedBufferAllocator.alloc(&self.fixed_buffer_allocator, len, ptr_align, len_align, return_address) catch
882 return self.fallback_allocator.rawAlloc(len, ptr_align, len_align, return_address);
851883 }
852884
853885 fn resize(
854 allocator: *Allocator,
886 self: *Self,
855887 buf: []u8,
856888 buf_align: u29,
857889 new_len: usize,
858890 len_align: u29,
859891 return_address: usize,
860 ) error{OutOfMemory}!usize {
861 const self = @fieldParentPtr(Self, "allocator", allocator);
892 ) ?usize {
862893 if (self.fixed_buffer_allocator.ownsPtr(buf.ptr)) {
863 return FixedBufferAllocator.resize(&self.fixed_buffer_allocator.allocator, buf, buf_align, new_len, len_align, return_address);
894 return FixedBufferAllocator.resize(&self.fixed_buffer_allocator, buf, buf_align, new_len, len_align, return_address);
864895 } else {
865 return self.fallback_allocator.resizeFn(self.fallback_allocator, buf, buf_align, new_len, len_align, return_address);
896 return self.fallback_allocator.rawResize(buf, buf_align, new_len, len_align, return_address);
897 }
898 }
899
900 fn free(
901 self: *Self,
902 buf: []u8,
903 buf_align: u29,
904 return_address: usize,
905 ) void {
906 if (self.fixed_buffer_allocator.ownsPtr(buf.ptr)) {
907 return FixedBufferAllocator.free(&self.fixed_buffer_allocator, buf, buf_align, return_address);
908 } else {
909 return self.fallback_allocator.rawFree(buf, buf_align, return_address);
866910 }
867911 }
868912 };
......@@ -950,8 +994,8 @@ test "HeapAllocator" {
950994 if (builtin.os.tag == .windows) {
951995 var heap_allocator = HeapAllocator.init();
952996 defer heap_allocator.deinit();
997 const allocator = heap_allocator.allocator();
953998
954 const allocator = &heap_allocator.allocator;
955999 try testAllocator(allocator);
9561000 try testAllocatorAligned(allocator);
9571001 try testAllocatorLargeAlignment(allocator);
......@@ -962,36 +1006,39 @@ test "HeapAllocator" {
9621006test "ArenaAllocator" {
9631007 var arena_allocator = ArenaAllocator.init(page_allocator);
9641008 defer arena_allocator.deinit();
1009 const allocator = arena_allocator.allocator();
9651010
966 try testAllocator(&arena_allocator.allocator);
967 try testAllocatorAligned(&arena_allocator.allocator);
968 try testAllocatorLargeAlignment(&arena_allocator.allocator);
969 try testAllocatorAlignedShrink(&arena_allocator.allocator);
1011 try testAllocator(allocator);
1012 try testAllocatorAligned(allocator);
1013 try testAllocatorLargeAlignment(allocator);
1014 try testAllocatorAlignedShrink(allocator);
9701015}
9711016
9721017var test_fixed_buffer_allocator_memory: [800000 * @sizeOf(u64)]u8 = undefined;
9731018test "FixedBufferAllocator" {
9741019 var fixed_buffer_allocator = mem.validationWrap(FixedBufferAllocator.init(test_fixed_buffer_allocator_memory[0..]));
1020 const allocator = fixed_buffer_allocator.allocator();
9751021
976 try testAllocator(&fixed_buffer_allocator.allocator);
977 try testAllocatorAligned(&fixed_buffer_allocator.allocator);
978 try testAllocatorLargeAlignment(&fixed_buffer_allocator.allocator);
979 try testAllocatorAlignedShrink(&fixed_buffer_allocator.allocator);
1022 try testAllocator(allocator);
1023 try testAllocatorAligned(allocator);
1024 try testAllocatorLargeAlignment(allocator);
1025 try testAllocatorAlignedShrink(allocator);
9801026}
9811027
9821028test "FixedBufferAllocator.reset" {
9831029 var buf: [8]u8 align(@alignOf(u64)) = undefined;
9841030 var fba = FixedBufferAllocator.init(buf[0..]);
1031 const allocator = fba.allocator();
9851032
9861033 const X = 0xeeeeeeeeeeeeeeee;
9871034 const Y = 0xffffffffffffffff;
9881035
989 var x = try fba.allocator.create(u64);
1036 var x = try allocator.create(u64);
9901037 x.* = X;
991 try testing.expectError(error.OutOfMemory, fba.allocator.create(u64));
1038 try testing.expectError(error.OutOfMemory, allocator.create(u64));
9921039
9931040 fba.reset();
994 var y = try fba.allocator.create(u64);
1041 var y = try allocator.create(u64);
9951042 y.* = Y;
9961043
9971044 // we expect Y to have overwritten X.
......@@ -1014,23 +1061,25 @@ test "FixedBufferAllocator Reuse memory on realloc" {
10141061 // check if we re-use the memory
10151062 {
10161063 var fixed_buffer_allocator = FixedBufferAllocator.init(small_fixed_buffer[0..]);
1064 const allocator = fixed_buffer_allocator.allocator();
10171065
1018 var slice0 = try fixed_buffer_allocator.allocator.alloc(u8, 5);
1066 var slice0 = try allocator.alloc(u8, 5);
10191067 try testing.expect(slice0.len == 5);
1020 var slice1 = try fixed_buffer_allocator.allocator.realloc(slice0, 10);
1068 var slice1 = try allocator.realloc(slice0, 10);
10211069 try testing.expect(slice1.ptr == slice0.ptr);
10221070 try testing.expect(slice1.len == 10);
1023 try testing.expectError(error.OutOfMemory, fixed_buffer_allocator.allocator.realloc(slice1, 11));
1071 try testing.expectError(error.OutOfMemory, allocator.realloc(slice1, 11));
10241072 }
10251073 // check that we don't re-use the memory if it's not the most recent block
10261074 {
10271075 var fixed_buffer_allocator = FixedBufferAllocator.init(small_fixed_buffer[0..]);
1076 const allocator = fixed_buffer_allocator.allocator();
10281077
1029 var slice0 = try fixed_buffer_allocator.allocator.alloc(u8, 2);
1078 var slice0 = try allocator.alloc(u8, 2);
10301079 slice0[0] = 1;
10311080 slice0[1] = 2;
1032 var slice1 = try fixed_buffer_allocator.allocator.alloc(u8, 2);
1033 var slice2 = try fixed_buffer_allocator.allocator.realloc(slice0, 4);
1081 var slice1 = try allocator.alloc(u8, 2);
1082 var slice2 = try allocator.realloc(slice0, 4);
10341083 try testing.expect(slice0.ptr != slice2.ptr);
10351084 try testing.expect(slice1.ptr != slice2.ptr);
10361085 try testing.expect(slice2[0] == 1);
......@@ -1038,19 +1087,19 @@ test "FixedBufferAllocator Reuse memory on realloc" {
10381087 }
10391088}
10401089
1041test "ThreadSafeFixedBufferAllocator" {
1042 var fixed_buffer_allocator = ThreadSafeFixedBufferAllocator.init(test_fixed_buffer_allocator_memory[0..]);
1090test "Thread safe FixedBufferAllocator" {
1091 var fixed_buffer_allocator = FixedBufferAllocator.init(test_fixed_buffer_allocator_memory[0..]);
10431092
1044 try testAllocator(&fixed_buffer_allocator.allocator);
1045 try testAllocatorAligned(&fixed_buffer_allocator.allocator);
1046 try testAllocatorLargeAlignment(&fixed_buffer_allocator.allocator);
1047 try testAllocatorAlignedShrink(&fixed_buffer_allocator.allocator);
1093 try testAllocator(fixed_buffer_allocator.threadSafeAllocator());
1094 try testAllocatorAligned(fixed_buffer_allocator.threadSafeAllocator());
1095 try testAllocatorLargeAlignment(fixed_buffer_allocator.threadSafeAllocator());
1096 try testAllocatorAlignedShrink(fixed_buffer_allocator.threadSafeAllocator());
10481097}
10491098
10501099/// This one should not try alignments that exceed what C malloc can handle.
1051pub fn testAllocator(base_allocator: *mem.Allocator) !void {
1100pub fn testAllocator(base_allocator: mem.Allocator) !void {
10521101 var validationAllocator = mem.validationWrap(base_allocator);
1053 const allocator = &validationAllocator.allocator;
1102 const allocator = validationAllocator.allocator();
10541103
10551104 var slice = try allocator.alloc(*i32, 100);
10561105 try testing.expect(slice.len == 100);
......@@ -1094,9 +1143,9 @@ pub fn testAllocator(base_allocator: *mem.Allocator) !void {
10941143 allocator.free(oversize);
10951144}
10961145
1097pub fn testAllocatorAligned(base_allocator: *mem.Allocator) !void {
1146pub fn testAllocatorAligned(base_allocator: mem.Allocator) !void {
10981147 var validationAllocator = mem.validationWrap(base_allocator);
1099 const allocator = &validationAllocator.allocator;
1148 const allocator = validationAllocator.allocator();
11001149
11011150 // Test a few alignment values, smaller and bigger than the type's one
11021151 inline for ([_]u29{ 1, 2, 4, 8, 16, 32, 64 }) |alignment| {
......@@ -1124,9 +1173,9 @@ pub fn testAllocatorAligned(base_allocator: *mem.Allocator) !void {
11241173 }
11251174}
11261175
1127pub fn testAllocatorLargeAlignment(base_allocator: *mem.Allocator) !void {
1176pub fn testAllocatorLargeAlignment(base_allocator: mem.Allocator) !void {
11281177 var validationAllocator = mem.validationWrap(base_allocator);
1129 const allocator = &validationAllocator.allocator;
1178 const allocator = validationAllocator.allocator();
11301179
11311180 //Maybe a platform's page_size is actually the same as or
11321181 // very near usize?
......@@ -1156,12 +1205,12 @@ pub fn testAllocatorLargeAlignment(base_allocator: *mem.Allocator) !void {
11561205 allocator.free(slice);
11571206}
11581207
1159pub fn testAllocatorAlignedShrink(base_allocator: *mem.Allocator) !void {
1208pub fn testAllocatorAlignedShrink(base_allocator: mem.Allocator) !void {
11601209 var validationAllocator = mem.validationWrap(base_allocator);
1161 const allocator = &validationAllocator.allocator;
1210 const allocator = validationAllocator.allocator();
11621211
11631212 var debug_buffer: [1000]u8 = undefined;
1164 const debug_allocator = &FixedBufferAllocator.init(&debug_buffer).allocator;
1213 const debug_allocator = FixedBufferAllocator.init(&debug_buffer).allocator();
11651214
11661215 const alloc_size = mem.page_size * 2 + 50;
11671216 var slice = try allocator.alignedAlloc(u8, 16, alloc_size);
lib/std/heap/arena_allocator.zig+29-24
......@@ -6,9 +6,7 @@ const Allocator = std.mem.Allocator;
66/// This allocator takes an existing allocator, wraps it, and provides an interface
77/// where you can allocate without freeing, and then free it all together.
88pub const ArenaAllocator = struct {
9 allocator: Allocator,
10
11 child_allocator: *Allocator,
9 child_allocator: Allocator,
1210 state: State,
1311
1412 /// Inner state of ArenaAllocator. Can be stored rather than the entire ArenaAllocator
......@@ -17,21 +15,21 @@ pub const ArenaAllocator = struct {
1715 buffer_list: std.SinglyLinkedList([]u8) = @as(std.SinglyLinkedList([]u8), .{}),
1816 end_index: usize = 0,
1917
20 pub fn promote(self: State, child_allocator: *Allocator) ArenaAllocator {
18 pub fn promote(self: State, child_allocator: Allocator) ArenaAllocator {
2119 return .{
22 .allocator = Allocator{
23 .allocFn = alloc,
24 .resizeFn = resize,
25 },
2620 .child_allocator = child_allocator,
2721 .state = self,
2822 };
2923 }
3024 };
3125
26 pub fn allocator(self: *ArenaAllocator) Allocator {
27 return Allocator.init(self, alloc, resize, free);
28 }
29
3230 const BufNode = std.SinglyLinkedList([]u8).Node;
3331
34 pub fn init(child_allocator: *Allocator) ArenaAllocator {
32 pub fn init(child_allocator: Allocator) ArenaAllocator {
3533 return (State{}).promote(child_allocator);
3634 }
3735
......@@ -49,7 +47,7 @@ pub const ArenaAllocator = struct {
4947 const actual_min_size = minimum_size + (@sizeOf(BufNode) + 16);
5048 const big_enough_len = prev_len + actual_min_size;
5149 const len = big_enough_len + big_enough_len / 2;
52 const buf = try self.child_allocator.allocFn(self.child_allocator, len, @alignOf(BufNode), 1, @returnAddress());
50 const buf = try self.child_allocator.rawAlloc(len, @alignOf(BufNode), 1, @returnAddress());
5351 const buf_node = @ptrCast(*BufNode, @alignCast(@alignOf(BufNode), buf.ptr));
5452 buf_node.* = BufNode{
5553 .data = buf,
......@@ -60,10 +58,9 @@ pub const ArenaAllocator = struct {
6058 return buf_node;
6159 }
6260
63 fn alloc(allocator: *Allocator, n: usize, ptr_align: u29, len_align: u29, ra: usize) ![]u8 {
61 fn alloc(self: *ArenaAllocator, n: usize, ptr_align: u29, len_align: u29, ra: usize) ![]u8 {
6462 _ = len_align;
6563 _ = ra;
66 const self = @fieldParentPtr(ArenaAllocator, "allocator", allocator);
6764
6865 var cur_node = if (self.state.buffer_list.first) |first_node| first_node else try self.createNode(0, n + ptr_align);
6966 while (true) {
......@@ -81,27 +78,23 @@ pub const ArenaAllocator = struct {
8178
8279 const bigger_buf_size = @sizeOf(BufNode) + new_end_index;
8380 // Try to grow the buffer in-place
84 cur_node.data = self.child_allocator.resize(cur_node.data, bigger_buf_size) catch |err| switch (err) {
85 error.OutOfMemory => {
86 // Allocate a new node if that's not possible
87 cur_node = try self.createNode(cur_buf.len, n + ptr_align);
88 continue;
89 },
81 cur_node.data = self.child_allocator.resize(cur_node.data, bigger_buf_size) orelse {
82 // Allocate a new node if that's not possible
83 cur_node = try self.createNode(cur_buf.len, n + ptr_align);
84 continue;
9085 };
9186 }
9287 }
9388
94 fn resize(allocator: *Allocator, buf: []u8, buf_align: u29, new_len: usize, len_align: u29, ret_addr: usize) Allocator.Error!usize {
89 fn resize(self: *ArenaAllocator, buf: []u8, buf_align: u29, new_len: usize, len_align: u29, ret_addr: usize) ?usize {
9590 _ = buf_align;
9691 _ = len_align;
9792 _ = ret_addr;
98 const self = @fieldParentPtr(ArenaAllocator, "allocator", allocator);
9993
100 const cur_node = self.state.buffer_list.first orelse return error.OutOfMemory;
94 const cur_node = self.state.buffer_list.first orelse return null;
10195 const cur_buf = cur_node.data[@sizeOf(BufNode)..];
10296 if (@ptrToInt(cur_buf.ptr) + self.state.end_index != @ptrToInt(buf.ptr) + buf.len) {
103 if (new_len > buf.len)
104 return error.OutOfMemory;
97 if (new_len > buf.len) return null;
10598 return new_len;
10699 }
107100
......@@ -112,7 +105,19 @@ pub const ArenaAllocator = struct {
112105 self.state.end_index += new_len - buf.len;
113106 return new_len;
114107 } else {
115 return error.OutOfMemory;
108 return null;
109 }
110 }
111
112 fn free(self: *ArenaAllocator, buf: []u8, buf_align: u29, ret_addr: usize) void {
113 _ = buf_align;
114 _ = ret_addr;
115
116 const cur_node = self.state.buffer_list.first orelse return;
117 const cur_buf = cur_node.data[@sizeOf(BufNode)..];
118
119 if (@ptrToInt(cur_buf.ptr) + self.state.end_index == @ptrToInt(buf.ptr) + buf.len) {
120 self.state.end_index -= buf.len;
116121 }
117122 }
118123};
lib/std/heap/general_purpose_allocator.zig+209-114
......@@ -172,11 +172,7 @@ pub const Config = struct {
172172
173173pub fn GeneralPurposeAllocator(comptime config: Config) type {
174174 return struct {
175 allocator: Allocator = Allocator{
176 .allocFn = alloc,
177 .resizeFn = resize,
178 },
179 backing_allocator: *Allocator = std.heap.page_allocator,
175 backing_allocator: Allocator = std.heap.page_allocator,
180176 buckets: [small_bucket_count]?*BucketHeader = [1]?*BucketHeader{null} ** small_bucket_count,
181177 large_allocations: LargeAllocTable = .{},
182178 empty_buckets: if (config.retain_metadata) ?*BucketHeader else void =
......@@ -284,6 +280,10 @@ pub fn GeneralPurposeAllocator(comptime config: Config) type {
284280 }
285281 };
286282
283 pub fn allocator(self: *Self) Allocator {
284 return Allocator.init(self, alloc, resize, free);
285 }
286
287287 fn bucketStackTrace(
288288 bucket: *BucketHeader,
289289 size_class: usize,
......@@ -388,7 +388,7 @@ pub fn GeneralPurposeAllocator(comptime config: Config) type {
388388 var it = self.large_allocations.iterator();
389389 while (it.next()) |large| {
390390 if (large.value_ptr.freed) {
391 _ = self.backing_allocator.resizeFn(self.backing_allocator, large.value_ptr.bytes, large.value_ptr.ptr_align, 0, 0, @returnAddress()) catch unreachable;
391 self.backing_allocator.rawFree(large.value_ptr.bytes, large.value_ptr.ptr_align, @returnAddress());
392392 }
393393 }
394394 }
......@@ -517,7 +517,7 @@ pub fn GeneralPurposeAllocator(comptime config: Config) type {
517517 new_size: usize,
518518 len_align: u29,
519519 ret_addr: usize,
520 ) Error!usize {
520 ) ?usize {
521521 const entry = self.large_allocations.getEntry(@ptrToInt(old_mem.ptr)) orelse {
522522 if (config.safety) {
523523 @panic("Invalid free");
......@@ -529,9 +529,6 @@ pub fn GeneralPurposeAllocator(comptime config: Config) type {
529529 if (config.retain_metadata and entry.value_ptr.freed) {
530530 if (config.safety) {
531531 reportDoubleFree(ret_addr, entry.value_ptr.getStackTrace(.alloc), entry.value_ptr.getStackTrace(.free));
532 // Recoverable if this is a free.
533 if (new_size == 0)
534 return @as(usize, 0);
535532 @panic("Unrecoverable double free");
536533 } else {
537534 unreachable;
......@@ -555,12 +552,12 @@ pub fn GeneralPurposeAllocator(comptime config: Config) type {
555552
556553 // Do memory limit accounting with requested sizes rather than what backing_allocator returns
557554 // because if we want to return error.OutOfMemory, we have to leave allocation untouched, and
558 // that is impossible to guarantee after calling backing_allocator.resizeFn.
555 // that is impossible to guarantee after calling backing_allocator.rawResize.
559556 const prev_req_bytes = self.total_requested_bytes;
560557 if (config.enable_memory_limit) {
561558 const new_req_bytes = prev_req_bytes + new_size - entry.value_ptr.requested_size;
562559 if (new_req_bytes > prev_req_bytes and new_req_bytes > self.requested_memory_limit) {
563 return error.OutOfMemory;
560 return null;
564561 }
565562 self.total_requested_bytes = new_req_bytes;
566563 }
......@@ -568,29 +565,12 @@ pub fn GeneralPurposeAllocator(comptime config: Config) type {
568565 self.total_requested_bytes = prev_req_bytes;
569566 };
570567
571 const result_len = if (config.never_unmap and new_size == 0)
572 0
573 else
574 try self.backing_allocator.resizeFn(self.backing_allocator, old_mem, old_align, new_size, len_align, ret_addr);
568 const result_len = self.backing_allocator.rawResize(old_mem, old_align, new_size, len_align, ret_addr) orelse return null;
575569
576570 if (config.enable_memory_limit) {
577571 entry.value_ptr.requested_size = new_size;
578572 }
579573
580 if (result_len == 0) {
581 if (config.verbose_log) {
582 log.info("large free {d} bytes at {*}", .{ old_mem.len, old_mem.ptr });
583 }
584
585 if (!config.retain_metadata) {
586 assert(self.large_allocations.remove(@ptrToInt(old_mem.ptr)));
587 } else {
588 entry.value_ptr.freed = true;
589 entry.value_ptr.captureStackTrace(ret_addr, .free);
590 }
591 return 0;
592 }
593
594574 if (config.verbose_log) {
595575 log.info("large resize {d} bytes at {*} to {d}", .{
596576 old_mem.len, old_mem.ptr, new_size,
......@@ -601,20 +581,76 @@ pub fn GeneralPurposeAllocator(comptime config: Config) type {
601581 return result_len;
602582 }
603583
584 /// This function assumes the object is in the large object storage regardless
585 /// of the parameters.
586 fn freeLarge(
587 self: *Self,
588 old_mem: []u8,
589 old_align: u29,
590 ret_addr: usize,
591 ) void {
592 _ = old_align;
593
594 const entry = self.large_allocations.getEntry(@ptrToInt(old_mem.ptr)) orelse {
595 if (config.safety) {
596 @panic("Invalid free");
597 } else {
598 unreachable;
599 }
600 };
601
602 if (config.retain_metadata and entry.value_ptr.freed) {
603 if (config.safety) {
604 reportDoubleFree(ret_addr, entry.value_ptr.getStackTrace(.alloc), entry.value_ptr.getStackTrace(.free));
605 return;
606 } else {
607 unreachable;
608 }
609 }
610
611 if (config.safety and old_mem.len != entry.value_ptr.bytes.len) {
612 var addresses: [stack_n]usize = [1]usize{0} ** stack_n;
613 var free_stack_trace = StackTrace{
614 .instruction_addresses = &addresses,
615 .index = 0,
616 };
617 std.debug.captureStackTrace(ret_addr, &free_stack_trace);
618 log.err("Allocation size {d} bytes does not match free size {d}. Allocation: {s} Free: {s}", .{
619 entry.value_ptr.bytes.len,
620 old_mem.len,
621 entry.value_ptr.getStackTrace(.alloc),
622 free_stack_trace,
623 });
624 }
625
626 if (config.enable_memory_limit) {
627 self.total_requested_bytes -= entry.value_ptr.requested_size;
628 }
629
630 if (config.verbose_log) {
631 log.info("large free {d} bytes at {*}", .{ old_mem.len, old_mem.ptr });
632 }
633
634 if (!config.retain_metadata) {
635 assert(self.large_allocations.remove(@ptrToInt(old_mem.ptr)));
636 } else {
637 entry.value_ptr.freed = true;
638 entry.value_ptr.captureStackTrace(ret_addr, .free);
639 }
640 }
641
604642 pub fn setRequestedMemoryLimit(self: *Self, limit: usize) void {
605643 self.requested_memory_limit = limit;
606644 }
607645
608646 fn resize(
609 allocator: *Allocator,
647 self: *Self,
610648 old_mem: []u8,
611649 old_align: u29,
612650 new_size: usize,
613651 len_align: u29,
614652 ret_addr: usize,
615 ) Error!usize {
616 const self = @fieldParentPtr(Self, "allocator", allocator);
617
653 ) ?usize {
618654 self.mutex.lock();
619655 defer self.mutex.unlock();
620656
......@@ -658,9 +694,6 @@ pub fn GeneralPurposeAllocator(comptime config: Config) type {
658694 if (!is_used) {
659695 if (config.safety) {
660696 reportDoubleFree(ret_addr, bucketStackTrace(bucket, size_class, slot_index, .alloc), bucketStackTrace(bucket, size_class, slot_index, .free));
661 // Recoverable if this is a free.
662 if (new_size == 0)
663 return @as(usize, 0);
664697 @panic("Unrecoverable double free");
665698 } else {
666699 unreachable;
......@@ -672,7 +705,7 @@ pub fn GeneralPurposeAllocator(comptime config: Config) type {
672705 if (config.enable_memory_limit) {
673706 const new_req_bytes = prev_req_bytes + new_size - old_mem.len;
674707 if (new_req_bytes > prev_req_bytes and new_req_bytes > self.requested_memory_limit) {
675 return error.OutOfMemory;
708 return null;
676709 }
677710 self.total_requested_bytes = new_req_bytes;
678711 }
......@@ -680,52 +713,6 @@ pub fn GeneralPurposeAllocator(comptime config: Config) type {
680713 self.total_requested_bytes = prev_req_bytes;
681714 };
682715
683 if (new_size == 0) {
684 // Capture stack trace to be the "first free", in case a double free happens.
685 bucket.captureStackTrace(ret_addr, size_class, slot_index, .free);
686
687 used_byte.* &= ~(@as(u8, 1) << used_bit_index);
688 bucket.used_count -= 1;
689 if (bucket.used_count == 0) {
690 if (bucket.next == bucket) {
691 // it's the only bucket and therefore the current one
692 self.buckets[bucket_index] = null;
693 } else {
694 bucket.next.prev = bucket.prev;
695 bucket.prev.next = bucket.next;
696 self.buckets[bucket_index] = bucket.prev;
697 }
698 if (!config.never_unmap) {
699 self.backing_allocator.free(bucket.page[0..page_size]);
700 }
701 if (!config.retain_metadata) {
702 self.freeBucket(bucket, size_class);
703 } else {
704 // move alloc_cursor to end so we can tell size_class later
705 const slot_count = @divExact(page_size, size_class);
706 bucket.alloc_cursor = @truncate(SlotIndex, slot_count);
707 if (self.empty_buckets) |prev_bucket| {
708 // empty_buckets is ordered newest to oldest through prev so that if
709 // config.never_unmap is false and backing_allocator reuses freed memory
710 // then searchBuckets will always return the newer, relevant bucket
711 bucket.prev = prev_bucket;
712 bucket.next = prev_bucket.next;
713 prev_bucket.next = bucket;
714 bucket.next.prev = bucket;
715 } else {
716 bucket.prev = bucket;
717 bucket.next = bucket;
718 }
719 self.empty_buckets = bucket;
720 }
721 } else {
722 @memset(old_mem.ptr, undefined, old_mem.len);
723 }
724 if (config.verbose_log) {
725 log.info("small free {d} bytes at {*}", .{ old_mem.len, old_mem.ptr });
726 }
727 return @as(usize, 0);
728 }
729716 const new_aligned_size = math.max(new_size, old_align);
730717 const new_size_class = math.ceilPowerOfTwoAssert(usize, new_aligned_size);
731718 if (new_size_class <= size_class) {
......@@ -739,7 +726,115 @@ pub fn GeneralPurposeAllocator(comptime config: Config) type {
739726 }
740727 return new_size;
741728 }
742 return error.OutOfMemory;
729 return null;
730 }
731
732 fn free(
733 self: *Self,
734 old_mem: []u8,
735 old_align: u29,
736 ret_addr: usize,
737 ) void {
738 self.mutex.lock();
739 defer self.mutex.unlock();
740
741 assert(old_mem.len != 0);
742
743 const aligned_size = math.max(old_mem.len, old_align);
744 if (aligned_size > largest_bucket_object_size) {
745 self.freeLarge(old_mem, old_align, ret_addr);
746 return;
747 }
748 const size_class_hint = math.ceilPowerOfTwoAssert(usize, aligned_size);
749
750 var bucket_index = math.log2(size_class_hint);
751 var size_class: usize = size_class_hint;
752 const bucket = while (bucket_index < small_bucket_count) : (bucket_index += 1) {
753 if (searchBucket(self.buckets[bucket_index], @ptrToInt(old_mem.ptr))) |bucket| {
754 // move bucket to head of list to optimize search for nearby allocations
755 self.buckets[bucket_index] = bucket;
756 break bucket;
757 }
758 size_class *= 2;
759 } else blk: {
760 if (config.retain_metadata) {
761 if (!self.large_allocations.contains(@ptrToInt(old_mem.ptr))) {
762 // object not in active buckets or a large allocation, so search empty buckets
763 if (searchBucket(self.empty_buckets, @ptrToInt(old_mem.ptr))) |bucket| {
764 // bucket is empty so is_used below will always be false and we exit there
765 break :blk bucket;
766 } else {
767 @panic("Invalid free");
768 }
769 }
770 }
771 self.freeLarge(old_mem, old_align, ret_addr);
772 return;
773 };
774 const byte_offset = @ptrToInt(old_mem.ptr) - @ptrToInt(bucket.page);
775 const slot_index = @intCast(SlotIndex, byte_offset / size_class);
776 const used_byte_index = slot_index / 8;
777 const used_bit_index = @intCast(u3, slot_index % 8);
778 const used_byte = bucket.usedBits(used_byte_index);
779 const is_used = @truncate(u1, used_byte.* >> used_bit_index) != 0;
780 if (!is_used) {
781 if (config.safety) {
782 reportDoubleFree(ret_addr, bucketStackTrace(bucket, size_class, slot_index, .alloc), bucketStackTrace(bucket, size_class, slot_index, .free));
783 // Recoverable if this is a free.
784 return;
785 } else {
786 unreachable;
787 }
788 }
789
790 // Definitely an in-use small alloc now.
791 if (config.enable_memory_limit) {
792 self.total_requested_bytes -= old_mem.len;
793 }
794
795 // Capture stack trace to be the "first free", in case a double free happens.
796 bucket.captureStackTrace(ret_addr, size_class, slot_index, .free);
797
798 used_byte.* &= ~(@as(u8, 1) << used_bit_index);
799 bucket.used_count -= 1;
800 if (bucket.used_count == 0) {
801 if (bucket.next == bucket) {
802 // it's the only bucket and therefore the current one
803 self.buckets[bucket_index] = null;
804 } else {
805 bucket.next.prev = bucket.prev;
806 bucket.prev.next = bucket.next;
807 self.buckets[bucket_index] = bucket.prev;
808 }
809 if (!config.never_unmap) {
810 self.backing_allocator.free(bucket.page[0..page_size]);
811 }
812 if (!config.retain_metadata) {
813 self.freeBucket(bucket, size_class);
814 } else {
815 // move alloc_cursor to end so we can tell size_class later
816 const slot_count = @divExact(page_size, size_class);
817 bucket.alloc_cursor = @truncate(SlotIndex, slot_count);
818 if (self.empty_buckets) |prev_bucket| {
819 // empty_buckets is ordered newest to oldest through prev so that if
820 // config.never_unmap is false and backing_allocator reuses freed memory
821 // then searchBuckets will always return the newer, relevant bucket
822 bucket.prev = prev_bucket;
823 bucket.next = prev_bucket.next;
824 prev_bucket.next = bucket;
825 bucket.next.prev = bucket;
826 } else {
827 bucket.prev = bucket;
828 bucket.next = bucket;
829 }
830 self.empty_buckets = bucket;
831 }
832 } else {
833 @memset(old_mem.ptr, undefined, old_mem.len);
834 }
835 if (config.verbose_log) {
836 log.info("small free {d} bytes at {*}", .{ old_mem.len, old_mem.ptr });
837 }
743838 }
744839
745840 // Returns true if an allocation of `size` bytes is within the specified
......@@ -755,9 +850,7 @@ pub fn GeneralPurposeAllocator(comptime config: Config) type {
755850 return true;
756851 }
757852
758 fn alloc(allocator: *Allocator, len: usize, ptr_align: u29, len_align: u29, ret_addr: usize) Error![]u8 {
759 const self = @fieldParentPtr(Self, "allocator", allocator);
760
853 fn alloc(self: *Self, len: usize, ptr_align: u29, len_align: u29, ret_addr: usize) Error![]u8 {
761854 self.mutex.lock();
762855 defer self.mutex.unlock();
763856
......@@ -768,7 +861,7 @@ pub fn GeneralPurposeAllocator(comptime config: Config) type {
768861 const new_aligned_size = math.max(len, ptr_align);
769862 if (new_aligned_size > largest_bucket_object_size) {
770863 try self.large_allocations.ensureUnusedCapacity(self.backing_allocator, 1);
771 const slice = try self.backing_allocator.allocFn(self.backing_allocator, len, ptr_align, len_align, ret_addr);
864 const slice = try self.backing_allocator.rawAlloc(len, ptr_align, len_align, ret_addr);
772865
773866 const gop = self.large_allocations.getOrPutAssumeCapacity(@ptrToInt(slice.ptr));
774867 if (config.retain_metadata and !config.never_unmap) {
......@@ -834,7 +927,7 @@ const test_config = Config{};
834927test "small allocations - free in same order" {
835928 var gpa = GeneralPurposeAllocator(test_config){};
836929 defer std.testing.expect(!gpa.deinit()) catch @panic("leak");
837 const allocator = &gpa.allocator;
930 const allocator = gpa.allocator();
838931
839932 var list = std.ArrayList(*u64).init(std.testing.allocator);
840933 defer list.deinit();
......@@ -853,7 +946,7 @@ test "small allocations - free in same order" {
853946test "small allocations - free in reverse order" {
854947 var gpa = GeneralPurposeAllocator(test_config){};
855948 defer std.testing.expect(!gpa.deinit()) catch @panic("leak");
856 const allocator = &gpa.allocator;
949 const allocator = gpa.allocator();
857950
858951 var list = std.ArrayList(*u64).init(std.testing.allocator);
859952 defer list.deinit();
......@@ -872,7 +965,7 @@ test "small allocations - free in reverse order" {
872965test "large allocations" {
873966 var gpa = GeneralPurposeAllocator(test_config){};
874967 defer std.testing.expect(!gpa.deinit()) catch @panic("leak");
875 const allocator = &gpa.allocator;
968 const allocator = gpa.allocator();
876969
877970 const ptr1 = try allocator.alloc(u64, 42768);
878971 const ptr2 = try allocator.alloc(u64, 52768);
......@@ -885,7 +978,7 @@ test "large allocations" {
885978test "realloc" {
886979 var gpa = GeneralPurposeAllocator(test_config){};
887980 defer std.testing.expect(!gpa.deinit()) catch @panic("leak");
888 const allocator = &gpa.allocator;
981 const allocator = gpa.allocator();
889982
890983 var slice = try allocator.alignedAlloc(u8, @alignOf(u32), 1);
891984 defer allocator.free(slice);
......@@ -907,7 +1000,7 @@ test "realloc" {
9071000test "shrink" {
9081001 var gpa = GeneralPurposeAllocator(test_config){};
9091002 defer std.testing.expect(!gpa.deinit()) catch @panic("leak");
910 const allocator = &gpa.allocator;
1003 const allocator = gpa.allocator();
9111004
9121005 var slice = try allocator.alloc(u8, 20);
9131006 defer allocator.free(slice);
......@@ -930,7 +1023,7 @@ test "shrink" {
9301023test "large object - grow" {
9311024 var gpa = GeneralPurposeAllocator(test_config){};
9321025 defer std.testing.expect(!gpa.deinit()) catch @panic("leak");
933 const allocator = &gpa.allocator;
1026 const allocator = gpa.allocator();
9341027
9351028 var slice1 = try allocator.alloc(u8, page_size * 2 - 20);
9361029 defer allocator.free(slice1);
......@@ -948,7 +1041,7 @@ test "large object - grow" {
9481041test "realloc small object to large object" {
9491042 var gpa = GeneralPurposeAllocator(test_config){};
9501043 defer std.testing.expect(!gpa.deinit()) catch @panic("leak");
951 const allocator = &gpa.allocator;
1044 const allocator = gpa.allocator();
9521045
9531046 var slice = try allocator.alloc(u8, 70);
9541047 defer allocator.free(slice);
......@@ -965,14 +1058,14 @@ test "realloc small object to large object" {
9651058test "shrink large object to large object" {
9661059 var gpa = GeneralPurposeAllocator(test_config){};
9671060 defer std.testing.expect(!gpa.deinit()) catch @panic("leak");
968 const allocator = &gpa.allocator;
1061 const allocator = gpa.allocator();
9691062
9701063 var slice = try allocator.alloc(u8, page_size * 2 + 50);
9711064 defer allocator.free(slice);
9721065 slice[0] = 0x12;
9731066 slice[60] = 0x34;
9741067
975 slice = try allocator.resize(slice, page_size * 2 + 1);
1068 slice = allocator.resize(slice, page_size * 2 + 1) orelse return;
9761069 try std.testing.expect(slice[0] == 0x12);
9771070 try std.testing.expect(slice[60] == 0x34);
9781071
......@@ -988,10 +1081,10 @@ test "shrink large object to large object" {
9881081test "shrink large object to large object with larger alignment" {
9891082 var gpa = GeneralPurposeAllocator(test_config){};
9901083 defer std.testing.expect(!gpa.deinit()) catch @panic("leak");
991 const allocator = &gpa.allocator;
1084 const allocator = gpa.allocator();
9921085
9931086 var debug_buffer: [1000]u8 = undefined;
994 const debug_allocator = &std.heap.FixedBufferAllocator.init(&debug_buffer).allocator;
1087 const debug_allocator = std.heap.FixedBufferAllocator.init(&debug_buffer).allocator();
9951088
9961089 const alloc_size = page_size * 2 + 50;
9971090 var slice = try allocator.alignedAlloc(u8, 16, alloc_size);
......@@ -1023,7 +1116,7 @@ test "shrink large object to large object with larger alignment" {
10231116test "realloc large object to small object" {
10241117 var gpa = GeneralPurposeAllocator(test_config){};
10251118 defer std.testing.expect(!gpa.deinit()) catch @panic("leak");
1026 const allocator = &gpa.allocator;
1119 const allocator = gpa.allocator();
10271120
10281121 var slice = try allocator.alloc(u8, page_size * 2 + 50);
10291122 defer allocator.free(slice);
......@@ -1041,7 +1134,7 @@ test "overrideable mutexes" {
10411134 .mutex = std.Thread.Mutex{},
10421135 };
10431136 defer std.testing.expect(!gpa.deinit()) catch @panic("leak");
1044 const allocator = &gpa.allocator;
1137 const allocator = gpa.allocator();
10451138
10461139 const ptr = try allocator.create(i32);
10471140 defer allocator.destroy(ptr);
......@@ -1050,7 +1143,7 @@ test "overrideable mutexes" {
10501143test "non-page-allocator backing allocator" {
10511144 var gpa = GeneralPurposeAllocator(.{}){ .backing_allocator = std.testing.allocator };
10521145 defer std.testing.expect(!gpa.deinit()) catch @panic("leak");
1053 const allocator = &gpa.allocator;
1146 const allocator = gpa.allocator();
10541147
10551148 const ptr = try allocator.create(i32);
10561149 defer allocator.destroy(ptr);
......@@ -1059,10 +1152,10 @@ test "non-page-allocator backing allocator" {
10591152test "realloc large object to larger alignment" {
10601153 var gpa = GeneralPurposeAllocator(test_config){};
10611154 defer std.testing.expect(!gpa.deinit()) catch @panic("leak");
1062 const allocator = &gpa.allocator;
1155 const allocator = gpa.allocator();
10631156
10641157 var debug_buffer: [1000]u8 = undefined;
1065 const debug_allocator = &std.heap.FixedBufferAllocator.init(&debug_buffer).allocator;
1158 const debug_allocator = std.heap.FixedBufferAllocator.init(&debug_buffer).allocator();
10661159
10671160 var slice = try allocator.alignedAlloc(u8, 16, page_size * 2 + 50);
10681161 defer allocator.free(slice);
......@@ -1098,9 +1191,9 @@ test "realloc large object to larger alignment" {
10981191
10991192test "large object shrinks to small but allocation fails during shrink" {
11001193 var failing_allocator = std.testing.FailingAllocator.init(std.heap.page_allocator, 3);
1101 var gpa = GeneralPurposeAllocator(.{}){ .backing_allocator = &failing_allocator.allocator };
1194 var gpa = GeneralPurposeAllocator(.{}){ .backing_allocator = failing_allocator.allocator() };
11021195 defer std.testing.expect(!gpa.deinit()) catch @panic("leak");
1103 const allocator = &gpa.allocator;
1196 const allocator = gpa.allocator();
11041197
11051198 var slice = try allocator.alloc(u8, page_size * 2 + 50);
11061199 defer allocator.free(slice);
......@@ -1117,7 +1210,7 @@ test "large object shrinks to small but allocation fails during shrink" {
11171210test "objects of size 1024 and 2048" {
11181211 var gpa = GeneralPurposeAllocator(test_config){};
11191212 defer std.testing.expect(!gpa.deinit()) catch @panic("leak");
1120 const allocator = &gpa.allocator;
1213 const allocator = gpa.allocator();
11211214
11221215 const slice = try allocator.alloc(u8, 1025);
11231216 const slice2 = try allocator.alloc(u8, 3000);
......@@ -1129,7 +1222,7 @@ test "objects of size 1024 and 2048" {
11291222test "setting a memory cap" {
11301223 var gpa = GeneralPurposeAllocator(.{ .enable_memory_limit = true }){};
11311224 defer std.testing.expect(!gpa.deinit()) catch @panic("leak");
1132 const allocator = &gpa.allocator;
1225 const allocator = gpa.allocator();
11331226
11341227 gpa.setRequestedMemoryLimit(1010);
11351228
......@@ -1158,9 +1251,9 @@ test "double frees" {
11581251 defer std.testing.expect(!backing_gpa.deinit()) catch @panic("leak");
11591252
11601253 const GPA = GeneralPurposeAllocator(.{ .safety = true, .never_unmap = true, .retain_metadata = true });
1161 var gpa = GPA{ .backing_allocator = &backing_gpa.allocator };
1254 var gpa = GPA{ .backing_allocator = backing_gpa.allocator() };
11621255 defer std.testing.expect(!gpa.deinit()) catch @panic("leak");
1163 const allocator = &gpa.allocator;
1256 const allocator = gpa.allocator();
11641257
11651258 // detect a small allocation double free, even though bucket is emptied
11661259 const index: usize = 6;
......@@ -1195,10 +1288,12 @@ test "double frees" {
11951288test "bug 9995 fix, large allocs count requested size not backing size" {
11961289 // with AtLeast, buffer likely to be larger than requested, especially when shrinking
11971290 var gpa = GeneralPurposeAllocator(.{ .enable_memory_limit = true }){};
1198 var buf = try gpa.allocator.allocAdvanced(u8, 1, page_size + 1, .at_least);
1291 const allocator = gpa.allocator();
1292
1293 var buf = try allocator.allocAdvanced(u8, 1, page_size + 1, .at_least);
11991294 try std.testing.expect(gpa.total_requested_bytes == page_size + 1);
1200 buf = try gpa.allocator.reallocAtLeast(buf, 1);
1295 buf = try allocator.reallocAtLeast(buf, 1);
12011296 try std.testing.expect(gpa.total_requested_bytes == 1);
1202 buf = try gpa.allocator.reallocAtLeast(buf, 2);
1297 buf = try allocator.reallocAtLeast(buf, 2);
12031298 try std.testing.expect(gpa.total_requested_bytes == 2);
12041299}
lib/std/heap/log_to_writer_allocator.zig+30-24
......@@ -5,33 +5,31 @@ const Allocator = std.mem.Allocator;
55/// on every call to the allocator. Writer errors are ignored.
66pub fn LogToWriterAllocator(comptime Writer: type) type {
77 return struct {
8 allocator: Allocator,
9 parent_allocator: *Allocator,
8 parent_allocator: Allocator,
109 writer: Writer,
1110
1211 const Self = @This();
1312
14 pub fn init(parent_allocator: *Allocator, writer: Writer) Self {
13 pub fn init(parent_allocator: Allocator, writer: Writer) Self {
1514 return Self{
16 .allocator = Allocator{
17 .allocFn = alloc,
18 .resizeFn = resize,
19 },
2015 .parent_allocator = parent_allocator,
2116 .writer = writer,
2217 };
2318 }
2419
20 pub fn allocator(self: *Self) Allocator {
21 return Allocator.init(self, alloc, resize, free);
22 }
23
2524 fn alloc(
26 allocator: *Allocator,
25 self: *Self,
2726 len: usize,
2827 ptr_align: u29,
2928 len_align: u29,
3029 ra: usize,
3130 ) error{OutOfMemory}![]u8 {
32 const self = @fieldParentPtr(Self, "allocator", allocator);
3331 self.writer.print("alloc : {}", .{len}) catch {};
34 const result = self.parent_allocator.allocFn(self.parent_allocator, len, ptr_align, len_align, ra);
32 const result = self.parent_allocator.rawAlloc(len, ptr_align, len_align, ra);
3533 if (result) |_| {
3634 self.writer.print(" success!\n", .{}) catch {};
3735 } else |_| {
......@@ -41,31 +39,39 @@ pub fn LogToWriterAllocator(comptime Writer: type) type {
4139 }
4240
4341 fn resize(
44 allocator: *Allocator,
42 self: *Self,
4543 buf: []u8,
4644 buf_align: u29,
4745 new_len: usize,
4846 len_align: u29,
4947 ra: usize,
50 ) error{OutOfMemory}!usize {
51 const self = @fieldParentPtr(Self, "allocator", allocator);
52 if (new_len == 0) {
53 self.writer.print("free : {}\n", .{buf.len}) catch {};
54 } else if (new_len <= buf.len) {
48 ) ?usize {
49 if (new_len <= buf.len) {
5550 self.writer.print("shrink: {} to {}\n", .{ buf.len, new_len }) catch {};
5651 } else {
5752 self.writer.print("expand: {} to {}", .{ buf.len, new_len }) catch {};
5853 }
59 if (self.parent_allocator.resizeFn(self.parent_allocator, buf, buf_align, new_len, len_align, ra)) |resized_len| {
54
55 if (self.parent_allocator.rawResize(buf, buf_align, new_len, len_align, ra)) |resized_len| {
6056 if (new_len > buf.len) {
6157 self.writer.print(" success!\n", .{}) catch {};
6258 }
6359 return resized_len;
64 } else |e| {
65 std.debug.assert(new_len > buf.len);
66 self.writer.print(" failure!\n", .{}) catch {};
67 return e;
6860 }
61
62 std.debug.assert(new_len > buf.len);
63 self.writer.print(" failure!\n", .{}) catch {};
64 return null;
65 }
66
67 fn free(
68 self: *Self,
69 buf: []u8,
70 buf_align: u29,
71 ra: usize,
72 ) void {
73 self.writer.print("free : {}\n", .{buf.len}) catch {};
74 self.parent_allocator.rawFree(buf, buf_align, ra);
6975 }
7076 };
7177}
......@@ -73,7 +79,7 @@ pub fn LogToWriterAllocator(comptime Writer: type) type {
7379/// This allocator is used in front of another allocator and logs to the provided writer
7480/// on every call to the allocator. Writer errors are ignored.
7581pub fn logToWriterAllocator(
76 parent_allocator: *Allocator,
82 parent_allocator: Allocator,
7783 writer: anytype,
7884) LogToWriterAllocator(@TypeOf(writer)) {
7985 return LogToWriterAllocator(@TypeOf(writer)).init(parent_allocator, writer);
......@@ -85,12 +91,12 @@ test "LogToWriterAllocator" {
8591
8692 var allocator_buf: [10]u8 = undefined;
8793 var fixedBufferAllocator = std.mem.validationWrap(std.heap.FixedBufferAllocator.init(&allocator_buf));
88 const allocator = &logToWriterAllocator(&fixedBufferAllocator.allocator, fbs.writer()).allocator;
94 const allocator = logToWriterAllocator(fixedBufferAllocator.allocator(), fbs.writer()).allocator();
8995
9096 var a = try allocator.alloc(u8, 10);
9197 a = allocator.shrink(a, 5);
9298 try std.testing.expect(a.len == 5);
93 try std.testing.expectError(error.OutOfMemory, allocator.resize(a, 20));
99 try std.testing.expect(allocator.resize(a, 20) == null);
94100 allocator.free(a);
95101
96102 try std.testing.expectEqualSlices(u8,
lib/std/heap/logging_allocator.zig+31-27
......@@ -22,21 +22,20 @@ pub fn ScopedLoggingAllocator(
2222 const log = std.log.scoped(scope);
2323
2424 return struct {
25 allocator: Allocator,
26 parent_allocator: *Allocator,
25 parent_allocator: Allocator,
2726
2827 const Self = @This();
2928
30 pub fn init(parent_allocator: *Allocator) Self {
29 pub fn init(parent_allocator: Allocator) Self {
3130 return .{
32 .allocator = Allocator{
33 .allocFn = alloc,
34 .resizeFn = resize,
35 },
3631 .parent_allocator = parent_allocator,
3732 };
3833 }
3934
35 pub fn allocator(self: *Self) Allocator {
36 return Allocator.init(self, alloc, resize, free);
37 }
38
4039 // This function is required as the `std.log.log` function is not public
4140 inline fn logHelper(comptime log_level: std.log.Level, comptime format: []const u8, args: anytype) void {
4241 switch (log_level) {
......@@ -48,14 +47,13 @@ pub fn ScopedLoggingAllocator(
4847 }
4948
5049 fn alloc(
51 allocator: *Allocator,
50 self: *Self,
5251 len: usize,
5352 ptr_align: u29,
5453 len_align: u29,
5554 ra: usize,
5655 ) error{OutOfMemory}![]u8 {
57 const self = @fieldParentPtr(Self, "allocator", allocator);
58 const result = self.parent_allocator.allocFn(self.parent_allocator, len, ptr_align, len_align, ra);
56 const result = self.parent_allocator.rawAlloc(len, ptr_align, len_align, ra);
5957 if (result) |_| {
6058 logHelper(
6159 success_log_level,
......@@ -73,19 +71,15 @@ pub fn ScopedLoggingAllocator(
7371 }
7472
7573 fn resize(
76 allocator: *Allocator,
74 self: *Self,
7775 buf: []u8,
7876 buf_align: u29,
7977 new_len: usize,
8078 len_align: u29,
8179 ra: usize,
82 ) error{OutOfMemory}!usize {
83 const self = @fieldParentPtr(Self, "allocator", allocator);
84
85 if (self.parent_allocator.resizeFn(self.parent_allocator, buf, buf_align, new_len, len_align, ra)) |resized_len| {
86 if (new_len == 0) {
87 logHelper(success_log_level, "free - success - len: {}", .{buf.len});
88 } else if (new_len <= buf.len) {
80 ) ?usize {
81 if (self.parent_allocator.rawResize(buf, buf_align, new_len, len_align, ra)) |resized_len| {
82 if (new_len <= buf.len) {
8983 logHelper(
9084 success_log_level,
9185 "shrink - success - {} to {}, len_align: {}, buf_align: {}",
......@@ -100,15 +94,25 @@ pub fn ScopedLoggingAllocator(
10094 }
10195
10296 return resized_len;
103 } else |err| {
104 std.debug.assert(new_len > buf.len);
105 logHelper(
106 failure_log_level,
107 "expand - failure: {s} - {} to {}, len_align: {}, buf_align: {}",
108 .{ @errorName(err), buf.len, new_len, len_align, buf_align },
109 );
110 return err;
11197 }
98
99 std.debug.assert(new_len > buf.len);
100 logHelper(
101 failure_log_level,
102 "expand - failure - {} to {}, len_align: {}, buf_align: {}",
103 .{ buf.len, new_len, len_align, buf_align },
104 );
105 return null;
106 }
107
108 fn free(
109 self: *Self,
110 buf: []u8,
111 buf_align: u29,
112 ra: usize,
113 ) void {
114 self.parent_allocator.rawFree(buf, buf_align, ra);
115 logHelper(success_log_level, "free - len: {}", .{buf.len});
112116 }
113117 };
114118}
......@@ -116,6 +120,6 @@ pub fn ScopedLoggingAllocator(
116120/// This allocator is used in front of another allocator and logs to `std.log`
117121/// on every call to the allocator.
118122/// For logging to a `std.io.Writer` see `std.heap.LogToWriterAllocator`
119pub fn loggingAllocator(parent_allocator: *Allocator) LoggingAllocator(.debug, .err) {
123pub fn loggingAllocator(parent_allocator: Allocator) LoggingAllocator(.debug, .err) {
120124 return LoggingAllocator(.debug, .err).init(parent_allocator);
121125}
lib/std/io/buffered_atomic_file.zig+2-2
......@@ -7,7 +7,7 @@ pub const BufferedAtomicFile = struct {
77 atomic_file: fs.AtomicFile,
88 file_writer: File.Writer,
99 buffered_writer: BufferedWriter,
10 allocator: *mem.Allocator,
10 allocator: mem.Allocator,
1111
1212 pub const buffer_size = 4096;
1313 pub const BufferedWriter = std.io.BufferedWriter(buffer_size, File.Writer);
......@@ -16,7 +16,7 @@ pub const BufferedAtomicFile = struct {
1616 /// TODO when https://github.com/ziglang/zig/issues/2761 is solved
1717 /// this API will not need an allocator
1818 pub fn create(
19 allocator: *mem.Allocator,
19 allocator: mem.Allocator,
2020 dir: fs.Dir,
2121 dest_path: []const u8,
2222 atomic_file_options: fs.Dir.AtomicFileOptions,
lib/std/io/peek_stream.zig+1-1
......@@ -38,7 +38,7 @@ pub fn PeekStream(
3838 }
3939 },
4040 .Dynamic => struct {
41 pub fn init(base: ReaderType, allocator: *mem.Allocator) Self {
41 pub fn init(base: ReaderType, allocator: mem.Allocator) Self {
4242 return .{
4343 .unbuffered_reader = base,
4444 .fifo = FifoType.init(allocator),
lib/std/io/reader.zig+3-3
......@@ -88,7 +88,7 @@ pub fn Reader(
8888 /// memory would be greater than `max_size`, returns `error.StreamTooLong`.
8989 /// Caller owns returned memory.
9090 /// If this function returns an error, the contents from the stream read so far are lost.
91 pub fn readAllAlloc(self: Self, allocator: *mem.Allocator, max_size: usize) ![]u8 {
91 pub fn readAllAlloc(self: Self, allocator: mem.Allocator, max_size: usize) ![]u8 {
9292 var array_list = std.ArrayList(u8).init(allocator);
9393 defer array_list.deinit();
9494 try self.readAllArrayList(&array_list, max_size);
......@@ -127,7 +127,7 @@ pub fn Reader(
127127 /// If this function returns an error, the contents from the stream read so far are lost.
128128 pub fn readUntilDelimiterAlloc(
129129 self: Self,
130 allocator: *mem.Allocator,
130 allocator: mem.Allocator,
131131 delimiter: u8,
132132 max_size: usize,
133133 ) ![]u8 {
......@@ -163,7 +163,7 @@ pub fn Reader(
163163 /// If this function returns an error, the contents from the stream read so far are lost.
164164 pub fn readUntilDelimiterOrEofAlloc(
165165 self: Self,
166 allocator: *mem.Allocator,
166 allocator: mem.Allocator,
167167 delimiter: u8,
168168 max_size: usize,
169169 ) !?[]u8 {
lib/std/json.zig+16-14
......@@ -1476,7 +1476,7 @@ fn parsedEqual(a: anytype, b: @TypeOf(a)) bool {
14761476}
14771477
14781478pub const ParseOptions = struct {
1479 allocator: ?*Allocator = null,
1479 allocator: ?Allocator = null,
14801480
14811481 /// Behaviour when a duplicate field is encountered.
14821482 duplicate_field_behavior: enum {
......@@ -2033,7 +2033,7 @@ test "parse into tagged union" {
20332033
20342034 { // failing allocations should be bubbled up instantly without trying next member
20352035 var fail_alloc = testing.FailingAllocator.init(testing.allocator, 0);
2036 const options = ParseOptions{ .allocator = &fail_alloc.allocator };
2036 const options = ParseOptions{ .allocator = fail_alloc.allocator() };
20372037 const T = union(enum) {
20382038 // both fields here match the input
20392039 string: []const u8,
......@@ -2081,7 +2081,7 @@ test "parse union bubbles up AllocatorRequired" {
20812081
20822082test "parseFree descends into tagged union" {
20832083 var fail_alloc = testing.FailingAllocator.init(testing.allocator, 1);
2084 const options = ParseOptions{ .allocator = &fail_alloc.allocator };
2084 const options = ParseOptions{ .allocator = fail_alloc.allocator() };
20852085 const T = union(enum) {
20862086 int: i32,
20872087 float: f64,
......@@ -2328,7 +2328,7 @@ test "parse into double recursive union definition" {
23282328
23292329/// A non-stream JSON parser which constructs a tree of Value's.
23302330pub const Parser = struct {
2331 allocator: *Allocator,
2331 allocator: Allocator,
23322332 state: State,
23332333 copy_strings: bool,
23342334 // Stores parent nodes and un-combined Values.
......@@ -2341,7 +2341,7 @@ pub const Parser = struct {
23412341 Simple,
23422342 };
23432343
2344 pub fn init(allocator: *Allocator, copy_strings: bool) Parser {
2344 pub fn init(allocator: Allocator, copy_strings: bool) Parser {
23452345 return Parser{
23462346 .allocator = allocator,
23472347 .state = .Simple,
......@@ -2364,9 +2364,10 @@ pub const Parser = struct {
23642364
23652365 var arena = ArenaAllocator.init(p.allocator);
23662366 errdefer arena.deinit();
2367 const allocator = arena.allocator();
23672368
23682369 while (try s.next()) |token| {
2369 try p.transition(&arena.allocator, input, s.i - 1, token);
2370 try p.transition(allocator, input, s.i - 1, token);
23702371 }
23712372
23722373 debug.assert(p.stack.items.len == 1);
......@@ -2379,7 +2380,7 @@ pub const Parser = struct {
23792380
23802381 // Even though p.allocator exists, we take an explicit allocator so that allocation state
23812382 // can be cleaned up on error correctly during a `parse` on call.
2382 fn transition(p: *Parser, allocator: *Allocator, input: []const u8, i: usize, token: Token) !void {
2383 fn transition(p: *Parser, allocator: Allocator, input: []const u8, i: usize, token: Token) !void {
23832384 switch (p.state) {
23842385 .ObjectKey => switch (token) {
23852386 .ObjectEnd => {
......@@ -2536,7 +2537,7 @@ pub const Parser = struct {
25362537 }
25372538 }
25382539
2539 fn parseString(p: *Parser, allocator: *Allocator, s: std.meta.TagPayload(Token, Token.String), input: []const u8, i: usize) !Value {
2540 fn parseString(p: *Parser, allocator: Allocator, s: std.meta.TagPayload(Token, Token.String), input: []const u8, i: usize) !Value {
25402541 const slice = s.slice(input, i);
25412542 switch (s.escapes) {
25422543 .None => return Value{ .String = if (p.copy_strings) try allocator.dupe(u8, slice) else slice },
......@@ -2737,7 +2738,7 @@ test "write json then parse it" {
27372738 try testing.expect(mem.eql(u8, tree.root.Object.get("str").?.String, "hello"));
27382739}
27392740
2740fn testParse(arena_allocator: *std.mem.Allocator, json_str: []const u8) !Value {
2741fn testParse(arena_allocator: std.mem.Allocator, json_str: []const u8) !Value {
27412742 var p = Parser.init(arena_allocator, false);
27422743 return (try p.parse(json_str)).root;
27432744}
......@@ -2745,13 +2746,13 @@ fn testParse(arena_allocator: *std.mem.Allocator, json_str: []const u8) !Value {
27452746test "parsing empty string gives appropriate error" {
27462747 var arena_allocator = std.heap.ArenaAllocator.init(std.testing.allocator);
27472748 defer arena_allocator.deinit();
2748 try testing.expectError(error.UnexpectedEndOfJson, testParse(&arena_allocator.allocator, ""));
2749 try testing.expectError(error.UnexpectedEndOfJson, testParse(arena_allocator.allocator(), ""));
27492750}
27502751
27512752test "integer after float has proper type" {
27522753 var arena_allocator = std.heap.ArenaAllocator.init(std.testing.allocator);
27532754 defer arena_allocator.deinit();
2754 const json = try testParse(&arena_allocator.allocator,
2755 const json = try testParse(arena_allocator.allocator(),
27552756 \\{
27562757 \\ "float": 3.14,
27572758 \\ "ints": [1, 2, 3]
......@@ -2786,7 +2787,7 @@ test "escaped characters" {
27862787 \\}
27872788 ;
27882789
2789 const obj = (try testParse(&arena_allocator.allocator, input)).Object;
2790 const obj = (try testParse(arena_allocator.allocator(), input)).Object;
27902791
27912792 try testing.expectEqualSlices(u8, obj.get("backslash").?.String, "\\");
27922793 try testing.expectEqualSlices(u8, obj.get("forwardslash").?.String, "/");
......@@ -2812,11 +2813,12 @@ test "string copy option" {
28122813
28132814 var arena_allocator = std.heap.ArenaAllocator.init(std.testing.allocator);
28142815 defer arena_allocator.deinit();
2816 const allocator = arena_allocator.allocator();
28152817
2816 const tree_nocopy = try Parser.init(&arena_allocator.allocator, false).parse(input);
2818 const tree_nocopy = try Parser.init(allocator, false).parse(input);
28172819 const obj_nocopy = tree_nocopy.root.Object;
28182820
2819 const tree_copy = try Parser.init(&arena_allocator.allocator, true).parse(input);
2821 const tree_copy = try Parser.init(allocator, true).parse(input);
28202822 const obj_copy = tree_copy.root.Object;
28212823
28222824 for ([_][]const u8{ "noescape", "simple", "unicode", "surrogatepair" }) |field_name| {
lib/std/json/write_stream.zig+2-2
......@@ -243,7 +243,7 @@ test "json write stream" {
243243 try w.beginObject();
244244
245245 try w.objectField("object");
246 try w.emitJson(try getJsonObject(&arena_allocator.allocator));
246 try w.emitJson(try getJsonObject(arena_allocator.allocator()));
247247
248248 try w.objectField("string");
249249 try w.emitString("This is a string");
......@@ -286,7 +286,7 @@ test "json write stream" {
286286 try std.testing.expect(std.mem.eql(u8, expected, result));
287287}
288288
289fn getJsonObject(allocator: *std.mem.Allocator) !std.json.Value {
289fn getJsonObject(allocator: std.mem.Allocator) !std.json.Value {
290290 var value = std.json.Value{ .Object = std.json.ObjectMap.init(allocator) };
291291 try value.Object.put("one", std.json.Value{ .Integer = @intCast(i64, 1) });
292292 try value.Object.put("two", std.json.Value{ .Float = 2.0 });
lib/std/math/big/int.zig+17-17
......@@ -142,7 +142,7 @@ pub const Mutable = struct {
142142
143143 /// Asserts that the allocator owns the limbs memory. If this is not the case,
144144 /// use `toConst().toManaged()`.
145 pub fn toManaged(self: Mutable, allocator: *Allocator) Managed {
145 pub fn toManaged(self: Mutable, allocator: Allocator) Managed {
146146 return .{
147147 .allocator = allocator,
148148 .limbs = self.limbs,
......@@ -283,7 +283,7 @@ pub const Mutable = struct {
283283 base: u8,
284284 value: []const u8,
285285 limbs_buffer: []Limb,
286 allocator: ?*Allocator,
286 allocator: ?Allocator,
287287 ) error{InvalidCharacter}!void {
288288 assert(base >= 2 and base <= 16);
289289
......@@ -608,7 +608,7 @@ pub const Mutable = struct {
608608 /// rma is given by `a.limbs.len + b.limbs.len`.
609609 ///
610610 /// `limbs_buffer` is used for temporary storage. The amount required is given by `calcMulLimbsBufferLen`.
611 pub fn mul(rma: *Mutable, a: Const, b: Const, limbs_buffer: []Limb, allocator: ?*Allocator) void {
611 pub fn mul(rma: *Mutable, a: Const, b: Const, limbs_buffer: []Limb, allocator: ?Allocator) void {
612612 var buf_index: usize = 0;
613613
614614 const a_copy = if (rma.limbs.ptr == a.limbs.ptr) blk: {
......@@ -638,7 +638,7 @@ pub const Mutable = struct {
638638 ///
639639 /// If `allocator` is provided, it will be used for temporary storage to improve
640640 /// multiplication performance. `error.OutOfMemory` is handled with a fallback algorithm.
641 pub fn mulNoAlias(rma: *Mutable, a: Const, b: Const, allocator: ?*Allocator) void {
641 pub fn mulNoAlias(rma: *Mutable, a: Const, b: Const, allocator: ?Allocator) void {
642642 assert(rma.limbs.ptr != a.limbs.ptr); // illegal aliasing
643643 assert(rma.limbs.ptr != b.limbs.ptr); // illegal aliasing
644644
......@@ -674,7 +674,7 @@ pub const Mutable = struct {
674674 signedness: Signedness,
675675 bit_count: usize,
676676 limbs_buffer: []Limb,
677 allocator: ?*Allocator,
677 allocator: ?Allocator,
678678 ) void {
679679 var buf_index: usize = 0;
680680 const req_limbs = calcTwosCompLimbCount(bit_count);
......@@ -714,7 +714,7 @@ pub const Mutable = struct {
714714 b: Const,
715715 signedness: Signedness,
716716 bit_count: usize,
717 allocator: ?*Allocator,
717 allocator: ?Allocator,
718718 ) void {
719719 assert(rma.limbs.ptr != a.limbs.ptr); // illegal aliasing
720720 assert(rma.limbs.ptr != b.limbs.ptr); // illegal aliasing
......@@ -763,7 +763,7 @@ pub const Mutable = struct {
763763 ///
764764 /// If `allocator` is provided, it will be used for temporary storage to improve
765765 /// multiplication performance. `error.OutOfMemory` is handled with a fallback algorithm.
766 pub fn sqrNoAlias(rma: *Mutable, a: Const, opt_allocator: ?*Allocator) void {
766 pub fn sqrNoAlias(rma: *Mutable, a: Const, opt_allocator: ?Allocator) void {
767767 _ = opt_allocator;
768768 assert(rma.limbs.ptr != a.limbs.ptr); // illegal aliasing
769769
......@@ -1660,7 +1660,7 @@ pub const Const = struct {
16601660 positive: bool,
16611661
16621662 /// The result is an independent resource which is managed by the caller.
1663 pub fn toManaged(self: Const, allocator: *Allocator) Allocator.Error!Managed {
1663 pub fn toManaged(self: Const, allocator: Allocator) Allocator.Error!Managed {
16641664 const limbs = try allocator.alloc(Limb, math.max(Managed.default_capacity, self.limbs.len));
16651665 mem.copy(Limb, limbs, self.limbs);
16661666 return Managed{
......@@ -1873,7 +1873,7 @@ pub const Const = struct {
18731873 /// Caller owns returned memory.
18741874 /// Asserts that `base` is in the range [2, 16].
18751875 /// See also `toString`, a lower level function than this.
1876 pub fn toStringAlloc(self: Const, allocator: *Allocator, base: u8, case: std.fmt.Case) Allocator.Error![]u8 {
1876 pub fn toStringAlloc(self: Const, allocator: Allocator, base: u8, case: std.fmt.Case) Allocator.Error![]u8 {
18771877 assert(base >= 2);
18781878 assert(base <= 16);
18791879
......@@ -2092,7 +2092,7 @@ pub const Managed = struct {
20922092 pub const default_capacity = 4;
20932093
20942094 /// Allocator used by the Managed when requesting memory.
2095 allocator: *Allocator,
2095 allocator: Allocator,
20962096
20972097 /// Raw digits. These are:
20982098 ///
......@@ -2109,7 +2109,7 @@ pub const Managed = struct {
21092109
21102110 /// Creates a new `Managed`. `default_capacity` limbs will be allocated immediately.
21112111 /// The integer value after initializing is `0`.
2112 pub fn init(allocator: *Allocator) !Managed {
2112 pub fn init(allocator: Allocator) !Managed {
21132113 return initCapacity(allocator, default_capacity);
21142114 }
21152115
......@@ -2131,7 +2131,7 @@ pub const Managed = struct {
21312131 /// Creates a new `Managed` with value `value`.
21322132 ///
21332133 /// This is identical to an `init`, followed by a `set`.
2134 pub fn initSet(allocator: *Allocator, value: anytype) !Managed {
2134 pub fn initSet(allocator: Allocator, value: anytype) !Managed {
21352135 var s = try Managed.init(allocator);
21362136 try s.set(value);
21372137 return s;
......@@ -2140,7 +2140,7 @@ pub const Managed = struct {
21402140 /// Creates a new Managed with a specific capacity. If capacity < default_capacity then the
21412141 /// default capacity will be used instead.
21422142 /// The integer value after initializing is `0`.
2143 pub fn initCapacity(allocator: *Allocator, capacity: usize) !Managed {
2143 pub fn initCapacity(allocator: Allocator, capacity: usize) !Managed {
21442144 return Managed{
21452145 .allocator = allocator,
21462146 .metadata = 1,
......@@ -2206,7 +2206,7 @@ pub const Managed = struct {
22062206 return other.cloneWithDifferentAllocator(other.allocator);
22072207 }
22082208
2209 pub fn cloneWithDifferentAllocator(other: Managed, allocator: *Allocator) !Managed {
2209 pub fn cloneWithDifferentAllocator(other: Managed, allocator: Allocator) !Managed {
22102210 return Managed{
22112211 .allocator = allocator,
22122212 .metadata = other.metadata,
......@@ -2347,7 +2347,7 @@ pub const Managed = struct {
23472347
23482348 /// Converts self to a string in the requested base. Memory is allocated from the provided
23492349 /// allocator and not the one present in self.
2350 pub fn toString(self: Managed, allocator: *Allocator, base: u8, case: std.fmt.Case) ![]u8 {
2350 pub fn toString(self: Managed, allocator: Allocator, base: u8, case: std.fmt.Case) ![]u8 {
23512351 _ = allocator;
23522352 if (base < 2 or base > 16) return error.InvalidBase;
23532353 return self.toConst().toStringAlloc(self.allocator, base, case);
......@@ -2784,7 +2784,7 @@ const AccOp = enum {
27842784/// r MUST NOT alias any of a or b.
27852785///
27862786/// The result is computed modulo `r.len`. When `r.len >= a.len + b.len`, no overflow occurs.
2787fn llmulacc(comptime op: AccOp, opt_allocator: ?*Allocator, r: []Limb, a: []const Limb, b: []const Limb) void {
2787fn llmulacc(comptime op: AccOp, opt_allocator: ?Allocator, r: []Limb, a: []const Limb, b: []const Limb) void {
27882788 @setRuntimeSafety(debug_safety);
27892789 assert(r.len >= a.len);
27902790 assert(r.len >= b.len);
......@@ -2819,7 +2819,7 @@ fn llmulacc(comptime op: AccOp, opt_allocator: ?*Allocator, r: []Limb, a: []cons
28192819/// The result is computed modulo `r.len`. When `r.len >= a.len + b.len`, no overflow occurs.
28202820fn llmulaccKaratsuba(
28212821 comptime op: AccOp,
2822 allocator: *Allocator,
2822 allocator: Allocator,
28232823 r: []Limb,
28242824 a: []const Limb,
28252825 b: []const Limb,
lib/std/math/big/rational.zig+1-1
......@@ -29,7 +29,7 @@ pub const Rational = struct {
2929
3030 /// Create a new Rational. A small amount of memory will be allocated on initialization.
3131 /// This will be 2 * Int.default_capacity.
32 pub fn init(a: *Allocator) !Rational {
32 pub fn init(a: Allocator) !Rational {
3333 return Rational{
3434 .p = try Int.init(a),
3535 .q = try Int.initSet(a, 1),
lib/std/mem.zig+53-33
......@@ -37,24 +37,26 @@ pub const Allocator = @import("mem/Allocator.zig");
3737pub fn ValidationAllocator(comptime T: type) type {
3838 return struct {
3939 const Self = @This();
40 allocator: Allocator,
40
4141 underlying_allocator: T,
42 pub fn init(allocator: T) @This() {
42
43 pub fn init(underlying_allocator: T) @This() {
4344 return .{
44 .allocator = .{
45 .allocFn = alloc,
46 .resizeFn = resize,
47 },
48 .underlying_allocator = allocator,
45 .underlying_allocator = underlying_allocator,
4946 };
5047 }
51 fn getUnderlyingAllocatorPtr(self: *@This()) *Allocator {
52 if (T == *Allocator) return self.underlying_allocator;
53 if (*T == *Allocator) return &self.underlying_allocator;
54 return &self.underlying_allocator.allocator;
48
49 pub fn allocator(self: *Self) Allocator {
50 return Allocator.init(self, alloc, resize, free);
5551 }
52
53 fn getUnderlyingAllocatorPtr(self: *Self) Allocator {
54 if (T == Allocator) return self.underlying_allocator;
55 return self.underlying_allocator.allocator();
56 }
57
5658 pub fn alloc(
57 allocator: *Allocator,
59 self: *Self,
5860 n: usize,
5961 ptr_align: u29,
6062 len_align: u29,
......@@ -67,9 +69,8 @@ pub fn ValidationAllocator(comptime T: type) type {
6769 assert(n >= len_align);
6870 }
6971
70 const self = @fieldParentPtr(@This(), "allocator", allocator);
7172 const underlying = self.getUnderlyingAllocatorPtr();
72 const result = try underlying.allocFn(underlying, n, ptr_align, len_align, ret_addr);
73 const result = try underlying.rawAlloc(n, ptr_align, len_align, ret_addr);
7374 assert(mem.isAligned(@ptrToInt(result.ptr), ptr_align));
7475 if (len_align == 0) {
7576 assert(result.len == n);
......@@ -79,22 +80,22 @@ pub fn ValidationAllocator(comptime T: type) type {
7980 }
8081 return result;
8182 }
83
8284 pub fn resize(
83 allocator: *Allocator,
85 self: *Self,
8486 buf: []u8,
8587 buf_align: u29,
8688 new_len: usize,
8789 len_align: u29,
8890 ret_addr: usize,
89 ) Allocator.Error!usize {
91 ) ?usize {
9092 assert(buf.len > 0);
9193 if (len_align != 0) {
9294 assert(mem.isAlignedAnyAlign(new_len, len_align));
9395 assert(new_len >= len_align);
9496 }
95 const self = @fieldParentPtr(@This(), "allocator", allocator);
9697 const underlying = self.getUnderlyingAllocatorPtr();
97 const result = try underlying.resizeFn(underlying, buf, buf_align, new_len, len_align, ret_addr);
98 const result = underlying.rawResize(buf, buf_align, new_len, len_align, ret_addr) orelse return null;
9899 if (len_align == 0) {
99100 assert(result == new_len);
100101 } else {
......@@ -103,7 +104,20 @@ pub fn ValidationAllocator(comptime T: type) type {
103104 }
104105 return result;
105106 }
106 pub usingnamespace if (T == *Allocator or !@hasDecl(T, "reset")) struct {} else struct {
107
108 pub fn free(
109 self: *Self,
110 buf: []u8,
111 buf_align: u29,
112 ret_addr: usize,
113 ) void {
114 _ = self;
115 _ = buf_align;
116 _ = ret_addr;
117 assert(buf.len > 0);
118 }
119
120 pub usingnamespace if (T == Allocator or !@hasDecl(T, "reset")) struct {} else struct {
107121 pub fn reset(self: *Self) void {
108122 self.underlying_allocator.reset();
109123 }
......@@ -130,12 +144,18 @@ pub fn alignAllocLen(full_len: usize, alloc_len: usize, len_align: u29) usize {
130144 return adjusted;
131145}
132146
133var failAllocator = Allocator{
134 .allocFn = failAllocatorAlloc,
135 .resizeFn = Allocator.noResize,
147const fail_allocator = Allocator{
148 .ptr = undefined,
149 .vtable = &failAllocator_vtable,
150};
151
152const failAllocator_vtable = Allocator.VTable{
153 .alloc = failAllocatorAlloc,
154 .resize = Allocator.NoResize(c_void).noResize,
155 .free = Allocator.NoOpFree(c_void).noOpFree,
136156};
137fn failAllocatorAlloc(self: *Allocator, n: usize, alignment: u29, len_align: u29, ra: usize) Allocator.Error![]u8 {
138 _ = self;
157
158fn failAllocatorAlloc(_: *c_void, n: usize, alignment: u29, len_align: u29, ra: usize) Allocator.Error![]u8 {
139159 _ = n;
140160 _ = alignment;
141161 _ = len_align;
......@@ -144,8 +164,8 @@ fn failAllocatorAlloc(self: *Allocator, n: usize, alignment: u29, len_align: u29
144164}
145165
146166test "mem.Allocator basics" {
147 try testing.expectError(error.OutOfMemory, failAllocator.alloc(u8, 1));
148 try testing.expectError(error.OutOfMemory, failAllocator.allocSentinel(u8, 1, 0));
167 try testing.expectError(error.OutOfMemory, fail_allocator.alloc(u8, 1));
168 try testing.expectError(error.OutOfMemory, fail_allocator.allocSentinel(u8, 1, 0));
149169}
150170
151171test "Allocator.resize" {
......@@ -168,7 +188,7 @@ test "Allocator.resize" {
168188 defer testing.allocator.free(values);
169189
170190 for (values) |*v, i| v.* = @intCast(T, i);
171 values = try testing.allocator.resize(values, values.len + 10);
191 values = testing.allocator.resize(values, values.len + 10) orelse return error.OutOfMemory;
172192 try testing.expect(values.len == 110);
173193 }
174194
......@@ -183,7 +203,7 @@ test "Allocator.resize" {
183203 defer testing.allocator.free(values);
184204
185205 for (values) |*v, i| v.* = @intToFloat(T, i);
186 values = try testing.allocator.resize(values, values.len + 10);
206 values = testing.allocator.resize(values, values.len + 10) orelse return error.OutOfMemory;
187207 try testing.expect(values.len == 110);
188208 }
189209}
......@@ -1786,18 +1806,18 @@ pub fn SplitIterator(comptime T: type) type {
17861806
17871807/// Naively combines a series of slices with a separator.
17881808/// Allocates memory for the result, which must be freed by the caller.
1789pub fn join(allocator: *Allocator, separator: []const u8, slices: []const []const u8) ![]u8 {
1809pub fn join(allocator: Allocator, separator: []const u8, slices: []const []const u8) ![]u8 {
17901810 return joinMaybeZ(allocator, separator, slices, false);
17911811}
17921812
17931813/// Naively combines a series of slices with a separator and null terminator.
17941814/// Allocates memory for the result, which must be freed by the caller.
1795pub fn joinZ(allocator: *Allocator, separator: []const u8, slices: []const []const u8) ![:0]u8 {
1815pub fn joinZ(allocator: Allocator, separator: []const u8, slices: []const []const u8) ![:0]u8 {
17961816 const out = try joinMaybeZ(allocator, separator, slices, true);
17971817 return out[0 .. out.len - 1 :0];
17981818}
17991819
1800fn joinMaybeZ(allocator: *Allocator, separator: []const u8, slices: []const []const u8, zero: bool) ![]u8 {
1820fn joinMaybeZ(allocator: Allocator, separator: []const u8, slices: []const []const u8, zero: bool) ![]u8 {
18011821 if (slices.len == 0) return if (zero) try allocator.dupe(u8, &[1]u8{0}) else &[0]u8{};
18021822
18031823 const total_len = blk: {
......@@ -1876,7 +1896,7 @@ test "mem.joinZ" {
18761896}
18771897
18781898/// Copies each T from slices into a new slice that exactly holds all the elements.
1879pub fn concat(allocator: *Allocator, comptime T: type, slices: []const []const T) ![]T {
1899pub fn concat(allocator: Allocator, comptime T: type, slices: []const []const T) ![]T {
18801900 if (slices.len == 0) return &[0]T{};
18811901
18821902 const total_len = blk: {
......@@ -2318,7 +2338,7 @@ test "replacementSize" {
23182338}
23192339
23202340/// Perform a replacement on an allocated buffer of pre-determined size. Caller must free returned memory.
2321pub fn replaceOwned(comptime T: type, allocator: *Allocator, input: []const T, needle: []const T, replacement: []const T) Allocator.Error![]T {
2341pub fn replaceOwned(comptime T: type, allocator: Allocator, input: []const T, needle: []const T, replacement: []const T) Allocator.Error![]T {
23222342 var output = try allocator.alloc(T, replacementSize(T, input, needle, replacement));
23232343 _ = replace(T, input, needle, replacement, output);
23242344 return output;
lib/std/mem/Allocator.zig+205-164
......@@ -5,155 +5,168 @@ const assert = std.debug.assert;
55const math = std.math;
66const mem = std.mem;
77const Allocator = @This();
8const builtin = @import("builtin");
89
910pub const Error = error{OutOfMemory};
1011
11/// Attempt to allocate at least `len` bytes aligned to `ptr_align`.
12///
13/// If `len_align` is `0`, then the length returned MUST be exactly `len` bytes,
14/// otherwise, the length must be aligned to `len_align`.
15///
16/// `len` must be greater than or equal to `len_align` and must be aligned by `len_align`.
17///
18/// `ret_addr` is optionally provided as the first return address of the allocation call stack.
19/// If the value is `0` it means no return address has been provided.
20allocFn: fn (self: *Allocator, len: usize, ptr_align: u29, len_align: u29, ret_addr: usize) Error![]u8,
12// The type erased pointer to the allocator implementation
13ptr: *c_void,
14vtable: *const VTable,
15
16pub const VTable = struct {
17 /// Attempt to allocate at least `len` bytes aligned to `ptr_align`.
18 ///
19 /// If `len_align` is `0`, then the length returned MUST be exactly `len` bytes,
20 /// otherwise, the length must be aligned to `len_align`.
21 ///
22 /// `len` must be greater than or equal to `len_align` and must be aligned by `len_align`.
23 ///
24 /// `ret_addr` is optionally provided as the first return address of the allocation call stack.
25 /// If the value is `0` it means no return address has been provided.
26 alloc: fn (ptr: *c_void, len: usize, ptr_align: u29, len_align: u29, ret_addr: usize) Error![]u8,
27
28 /// Attempt to expand or shrink memory in place. `buf.len` must equal the most recent
29 /// length returned by `alloc` or `resize`. `buf_align` must equal the same value
30 /// that was passed as the `ptr_align` parameter to the original `alloc` call.
31 ///
32 /// `null` can only be returned if `new_len` is greater than `buf.len`.
33 /// If `buf` cannot be expanded to accomodate `new_len`, then the allocation MUST be
34 /// unmodified and `null` MUST be returned.
35 ///
36 /// If `len_align` is `0`, then the length returned MUST be exactly `len` bytes,
37 /// otherwise, the length must be aligned to `len_align`. Note that `len_align` does *not*
38 /// provide a way to modify the alignment of a pointer. Rather it provides an API for
39 /// accepting more bytes of memory from the allocator than requested.
40 ///
41 /// `new_len` must be greater than zero, greater than or equal to `len_align` and must be aligned by `len_align`.
42 ///
43 /// `ret_addr` is optionally provided as the first return address of the allocation call stack.
44 /// If the value is `0` it means no return address has been provided.
45 resize: fn (ptr: *c_void, buf: []u8, buf_align: u29, new_len: usize, len_align: u29, ret_addr: usize) ?usize,
46
47 /// Free and invalidate a buffer. `buf.len` must equal the most recent length returned by `alloc` or `resize`.
48 /// `buf_align` must equal the same value that was passed as the `ptr_align` parameter to the original `alloc` call.
49 ///
50 /// `ret_addr` is optionally provided as the first return address of the allocation call stack.
51 /// If the value is `0` it means no return address has been provided.
52 free: fn (ptr: *c_void, buf: []u8, buf_align: u29, ret_addr: usize) void,
53};
54
55pub fn init(
56 pointer: anytype,
57 comptime allocFn: fn (ptr: @TypeOf(pointer), len: usize, ptr_align: u29, len_align: u29, ret_addr: usize) Error![]u8,
58 comptime resizeFn: fn (ptr: @TypeOf(pointer), buf: []u8, buf_align: u29, new_len: usize, len_align: u29, ret_addr: usize) ?usize,
59 comptime freeFn: fn (ptr: @TypeOf(pointer), buf: []u8, buf_align: u29, ret_addr: usize) void,
60) Allocator {
61 const Ptr = @TypeOf(pointer);
62 const ptr_info = @typeInfo(Ptr);
63
64 assert(ptr_info == .Pointer); // Must be a pointer
65 assert(ptr_info.Pointer.size == .One); // Must be a single-item pointer
66
67 const alignment = ptr_info.Pointer.alignment;
68
69 const gen = struct {
70 fn alloc(ptr: *c_void, len: usize, ptr_align: u29, len_align: u29, ret_addr: usize) Error![]u8 {
71 const self = @ptrCast(Ptr, @alignCast(alignment, ptr));
72 return @call(.{ .modifier = .always_inline }, allocFn, .{ self, len, ptr_align, len_align, ret_addr });
73 }
74 fn resize(ptr: *c_void, buf: []u8, buf_align: u29, new_len: usize, len_align: u29, ret_addr: usize) ?usize {
75 assert(new_len != 0);
76 const self = @ptrCast(Ptr, @alignCast(alignment, ptr));
77 return @call(.{ .modifier = .always_inline }, resizeFn, .{ self, buf, buf_align, new_len, len_align, ret_addr });
78 }
79 fn free(ptr: *c_void, buf: []u8, buf_align: u29, ret_addr: usize) void {
80 const self = @ptrCast(Ptr, @alignCast(alignment, ptr));
81 @call(.{ .modifier = .always_inline }, freeFn, .{ self, buf, buf_align, ret_addr });
82 }
83 };
2184
22/// Attempt to expand or shrink memory in place. `buf.len` must equal the most recent
23/// length returned by `allocFn` or `resizeFn`. `buf_align` must equal the same value
24/// that was passed as the `ptr_align` parameter to the original `allocFn` call.
25///
26/// Passing a `new_len` of 0 frees and invalidates the buffer such that it can no
27/// longer be passed to `resizeFn`.
28///
29/// error.OutOfMemory can only be returned if `new_len` is greater than `buf.len`.
30/// If `buf` cannot be expanded to accomodate `new_len`, then the allocation MUST be
31/// unmodified and error.OutOfMemory MUST be returned.
32///
33/// If `len_align` is `0`, then the length returned MUST be exactly `len` bytes,
34/// otherwise, the length must be aligned to `len_align`. Note that `len_align` does *not*
35/// provide a way to modify the alignment of a pointer. Rather it provides an API for
36/// accepting more bytes of memory from the allocator than requested.
37///
38/// `new_len` must be greater than or equal to `len_align` and must be aligned by `len_align`.
39///
40/// `ret_addr` is optionally provided as the first return address of the allocation call stack.
41/// If the value is `0` it means no return address has been provided.
42resizeFn: fn (self: *Allocator, buf: []u8, buf_align: u29, new_len: usize, len_align: u29, ret_addr: usize) Error!usize,
85 const vtable = VTable{
86 .alloc = gen.alloc,
87 .resize = gen.resize,
88 .free = gen.free,
89 };
4390
44/// Set to resizeFn if in-place resize is not supported.
45pub fn noResize(
46 self: *Allocator,
47 buf: []u8,
48 buf_align: u29,
49 new_len: usize,
50 len_align: u29,
51 ret_addr: usize,
52) Error!usize {
53 _ = self;
54 _ = buf_align;
55 _ = len_align;
56 _ = ret_addr;
57 if (new_len > buf.len)
58 return error.OutOfMemory;
59 return new_len;
91 return .{
92 .ptr = pointer,
93 .vtable = &vtable,
94 };
6095}
6196
62/// Realloc is used to modify the size or alignment of an existing allocation,
63/// as well as to provide the allocator with an opportunity to move an allocation
64/// to a better location.
65/// When the size/alignment is greater than the previous allocation, this function
66/// returns `error.OutOfMemory` when the requested new allocation could not be granted.
67/// When the size/alignment is less than or equal to the previous allocation,
68/// this function returns `error.OutOfMemory` when the allocator decides the client
69/// would be better off keeping the extra alignment/size. Clients will call
70/// `resizeFn` when they require the allocator to track a new alignment/size,
71/// and so this function should only return success when the allocator considers
72/// the reallocation desirable from the allocator's perspective.
73/// As an example, `std.ArrayList` tracks a "capacity", and therefore can handle
74/// reallocation failure, even when `new_n` <= `old_mem.len`. A `FixedBufferAllocator`
75/// would always return `error.OutOfMemory` for `reallocFn` when the size/alignment
76/// is less than or equal to the old allocation, because it cannot reclaim the memory,
77/// and thus the `std.ArrayList` would be better off retaining its capacity.
78/// When `reallocFn` returns,
79/// `return_value[0..min(old_mem.len, new_byte_count)]` must be the same
80/// as `old_mem` was when `reallocFn` is called. The bytes of
81/// `return_value[old_mem.len..]` have undefined values.
82/// The returned slice must have its pointer aligned at least to `new_alignment` bytes.
83pub fn reallocBytes(
84 self: *Allocator,
85 /// Guaranteed to be the same as what was returned from most recent call to
86 /// `allocFn` or `resizeFn`.
87 /// If `old_mem.len == 0` then this is a new allocation and `new_byte_count`
88 /// is guaranteed to be >= 1.
89 old_mem: []u8,
90 /// If `old_mem.len == 0` then this is `undefined`, otherwise:
91 /// Guaranteed to be the same as what was passed to `allocFn`.
92 /// Guaranteed to be >= 1.
93 /// Guaranteed to be a power of 2.
94 old_alignment: u29,
95 /// If `new_byte_count` is 0 then this is a free and it is guaranteed that
96 /// `old_mem.len != 0`.
97 new_byte_count: usize,
98 /// Guaranteed to be >= 1.
99 /// Guaranteed to be a power of 2.
100 /// Returned slice's pointer must have this alignment.
101 new_alignment: u29,
102 /// 0 indicates the length of the slice returned MUST match `new_byte_count` exactly
103 /// non-zero means the length of the returned slice must be aligned by `len_align`
104 /// `new_len` must be aligned by `len_align`
105 len_align: u29,
106 return_address: usize,
107) Error![]u8 {
108 if (old_mem.len == 0) {
109 const new_mem = try self.allocFn(self, new_byte_count, new_alignment, len_align, return_address);
110 // TODO: https://github.com/ziglang/zig/issues/4298
111 @memset(new_mem.ptr, undefined, new_byte_count);
112 return new_mem;
113 }
97/// Set resizeFn to `NoResize(AllocatorType).noResize` if in-place resize is not supported.
98pub fn NoResize(comptime AllocatorType: type) type {
99 return struct {
100 pub fn noResize(
101 self: *AllocatorType,
102 buf: []u8,
103 buf_align: u29,
104 new_len: usize,
105 len_align: u29,
106 ret_addr: usize,
107 ) ?usize {
108 _ = self;
109 _ = buf_align;
110 _ = len_align;
111 _ = ret_addr;
112 return if (new_len > buf.len) null else new_len;
113 }
114 };
115}
114116
115 if (mem.isAligned(@ptrToInt(old_mem.ptr), new_alignment)) {
116 if (new_byte_count <= old_mem.len) {
117 const shrunk_len = self.shrinkBytes(old_mem, old_alignment, new_byte_count, len_align, return_address);
118 return old_mem.ptr[0..shrunk_len];
117/// Set freeFn to `NoOpFree(AllocatorType).noOpFree` if free is a no-op.
118pub fn NoOpFree(comptime AllocatorType: type) type {
119 return struct {
120 pub fn noOpFree(
121 self: *AllocatorType,
122 buf: []u8,
123 buf_align: u29,
124 ret_addr: usize,
125 ) void {
126 _ = self;
127 _ = buf;
128 _ = buf_align;
129 _ = ret_addr;
119130 }
120 if (self.resizeFn(self, old_mem, old_alignment, new_byte_count, len_align, return_address)) |resized_len| {
121 assert(resized_len >= new_byte_count);
122 // TODO: https://github.com/ziglang/zig/issues/4298
123 @memset(old_mem.ptr + new_byte_count, undefined, resized_len - new_byte_count);
124 return old_mem.ptr[0..resized_len];
125 } else |_| {}
126 }
127 if (new_byte_count <= old_mem.len and new_alignment <= old_alignment) {
128 return error.OutOfMemory;
129 }
130 return self.moveBytes(old_mem, old_alignment, new_byte_count, new_alignment, len_align, return_address);
131 };
131132}
132133
133/// Move the given memory to a new location in the given allocator to accomodate a new
134/// size and alignment.
135fn moveBytes(
136 self: *Allocator,
137 old_mem: []u8,
138 old_align: u29,
139 new_len: usize,
140 new_alignment: u29,
141 len_align: u29,
142 return_address: usize,
143) Error![]u8 {
144 assert(old_mem.len > 0);
145 assert(new_len > 0);
146 const new_mem = try self.allocFn(self, new_len, new_alignment, len_align, return_address);
147 @memcpy(new_mem.ptr, old_mem.ptr, math.min(new_len, old_mem.len));
148 // TODO https://github.com/ziglang/zig/issues/4298
149 @memset(old_mem.ptr, undefined, old_mem.len);
150 _ = self.shrinkBytes(old_mem, old_align, 0, 0, return_address);
151 return new_mem;
134/// Set freeFn to `PanicFree(AllocatorType).noOpFree` if free is not a supported operation.
135pub fn PanicFree(comptime AllocatorType: type) type {
136 return struct {
137 pub fn noOpFree(
138 self: *AllocatorType,
139 buf: []u8,
140 buf_align: u29,
141 ret_addr: usize,
142 ) void {
143 _ = self;
144 _ = buf;
145 _ = buf_align;
146 _ = ret_addr;
147 @panic("free is not a supported operation for the allocator: " ++ @typeName(AllocatorType));
148 }
149 };
150}
151
152/// This function is not intended to be called except from within the implementation of an Allocator
153pub inline fn rawAlloc(self: Allocator, len: usize, ptr_align: u29, len_align: u29, ret_addr: usize) Error![]u8 {
154 return self.vtable.alloc(self.ptr, len, ptr_align, len_align, ret_addr);
155}
156
157/// This function is not intended to be called except from within the implementation of an Allocator
158pub inline fn rawResize(self: Allocator, buf: []u8, buf_align: u29, new_len: usize, len_align: u29, ret_addr: usize) ?usize {
159 return self.vtable.resize(self.ptr, buf, buf_align, new_len, len_align, ret_addr);
160}
161
162/// This function is not intended to be called except from within the implementation of an Allocator
163pub inline fn rawFree(self: Allocator, buf: []u8, buf_align: u29, ret_addr: usize) void {
164 return self.vtable.free(self.ptr, buf, buf_align, ret_addr);
152165}
153166
154167/// Returns a pointer to undefined memory.
155168/// Call `destroy` with the result to free the memory.
156pub fn create(self: *Allocator, comptime T: type) Error!*T {
169pub fn create(self: Allocator, comptime T: type) Error!*T {
157170 if (@sizeOf(T) == 0) return @as(*T, undefined);
158171 const slice = try self.allocAdvancedWithRetAddr(T, null, 1, .exact, @returnAddress());
159172 return &slice[0];
......@@ -161,12 +174,12 @@ pub fn create(self: *Allocator, comptime T: type) Error!*T {
161174
162175/// `ptr` should be the return value of `create`, or otherwise
163176/// have the same address and alignment property.
164pub fn destroy(self: *Allocator, ptr: anytype) void {
177pub fn destroy(self: Allocator, ptr: anytype) void {
165178 const info = @typeInfo(@TypeOf(ptr)).Pointer;
166179 const T = info.child;
167180 if (@sizeOf(T) == 0) return;
168181 const non_const_ptr = @intToPtr([*]u8, @ptrToInt(ptr));
169 _ = self.shrinkBytes(non_const_ptr[0..@sizeOf(T)], info.alignment, 0, 0, @returnAddress());
182 self.rawFree(non_const_ptr[0..@sizeOf(T)], info.alignment, @returnAddress());
170183}
171184
172185/// Allocates an array of `n` items of type `T` and sets all the
......@@ -177,12 +190,12 @@ pub fn destroy(self: *Allocator, ptr: anytype) void {
177190/// call `free` when done.
178191///
179192/// For allocating a single item, see `create`.
180pub fn alloc(self: *Allocator, comptime T: type, n: usize) Error![]T {
193pub fn alloc(self: Allocator, comptime T: type, n: usize) Error![]T {
181194 return self.allocAdvancedWithRetAddr(T, null, n, .exact, @returnAddress());
182195}
183196
184197pub fn allocWithOptions(
185 self: *Allocator,
198 self: Allocator,
186199 comptime Elem: type,
187200 n: usize,
188201 /// null means naturally aligned
......@@ -193,7 +206,7 @@ pub fn allocWithOptions(
193206}
194207
195208pub fn allocWithOptionsRetAddr(
196 self: *Allocator,
209 self: Allocator,
197210 comptime Elem: type,
198211 n: usize,
199212 /// null means naturally aligned
......@@ -227,7 +240,7 @@ fn AllocWithOptionsPayload(comptime Elem: type, comptime alignment: ?u29, compti
227240///
228241/// For allocating a single item, see `create`.
229242pub fn allocSentinel(
230 self: *Allocator,
243 self: Allocator,
231244 comptime Elem: type,
232245 n: usize,
233246 comptime sentinel: Elem,
......@@ -236,7 +249,7 @@ pub fn allocSentinel(
236249}
237250
238251pub fn alignedAlloc(
239 self: *Allocator,
252 self: Allocator,
240253 comptime T: type,
241254 /// null means naturally aligned
242255 comptime alignment: ?u29,
......@@ -246,7 +259,7 @@ pub fn alignedAlloc(
246259}
247260
248261pub fn allocAdvanced(
249 self: *Allocator,
262 self: Allocator,
250263 comptime T: type,
251264 /// null means naturally aligned
252265 comptime alignment: ?u29,
......@@ -259,7 +272,7 @@ pub fn allocAdvanced(
259272pub const Exact = enum { exact, at_least };
260273
261274pub fn allocAdvancedWithRetAddr(
262 self: *Allocator,
275 self: Allocator,
263276 comptime T: type,
264277 /// null means naturally aligned
265278 comptime alignment: ?u29,
......@@ -285,7 +298,7 @@ pub fn allocAdvancedWithRetAddr(
285298 .exact => 0,
286299 .at_least => size_of_T,
287300 };
288 const byte_slice = try self.allocFn(self, byte_count, a, len_align, return_address);
301 const byte_slice = try self.rawAlloc(byte_count, a, len_align, return_address);
289302 switch (exact) {
290303 .exact => assert(byte_slice.len == byte_count),
291304 .at_least => assert(byte_slice.len >= byte_count),
......@@ -301,7 +314,7 @@ pub fn allocAdvancedWithRetAddr(
301314}
302315
303316/// Increases or decreases the size of an allocation. It is guaranteed to not move the pointer.
304pub fn resize(self: *Allocator, old_mem: anytype, new_n: usize) Error!@TypeOf(old_mem) {
317pub fn resize(self: Allocator, old_mem: anytype, new_n: usize) ?@TypeOf(old_mem) {
305318 const Slice = @typeInfo(@TypeOf(old_mem)).Pointer;
306319 const T = Slice.child;
307320 if (new_n == 0) {
......@@ -309,8 +322,8 @@ pub fn resize(self: *Allocator, old_mem: anytype, new_n: usize) Error!@TypeOf(ol
309322 return &[0]T{};
310323 }
311324 const old_byte_slice = mem.sliceAsBytes(old_mem);
312 const new_byte_count = math.mul(usize, @sizeOf(T), new_n) catch return Error.OutOfMemory;
313 const rc = try self.resizeFn(self, old_byte_slice, Slice.alignment, new_byte_count, 0, @returnAddress());
325 const new_byte_count = math.mul(usize, @sizeOf(T), new_n) catch return null;
326 const rc = self.rawResize(old_byte_slice, Slice.alignment, new_byte_count, 0, @returnAddress()) orelse return null;
314327 assert(rc == new_byte_count);
315328 const new_byte_slice = old_byte_slice.ptr[0..new_byte_count];
316329 return mem.bytesAsSlice(T, new_byte_slice);
......@@ -326,7 +339,7 @@ pub fn resize(self: *Allocator, old_mem: anytype, new_n: usize) Error!@TypeOf(ol
326339/// in `std.ArrayList.shrink`.
327340/// If you need guaranteed success, call `shrink`.
328341/// If `new_n` is 0, this is the same as `free` and it always succeeds.
329pub fn realloc(self: *Allocator, old_mem: anytype, new_n: usize) t: {
342pub fn realloc(self: Allocator, old_mem: anytype, new_n: usize) t: {
330343 const Slice = @typeInfo(@TypeOf(old_mem)).Pointer;
331344 break :t Error![]align(Slice.alignment) Slice.child;
332345} {
......@@ -334,7 +347,7 @@ pub fn realloc(self: *Allocator, old_mem: anytype, new_n: usize) t: {
334347 return self.reallocAdvancedWithRetAddr(old_mem, old_alignment, new_n, .exact, @returnAddress());
335348}
336349
337pub fn reallocAtLeast(self: *Allocator, old_mem: anytype, new_n: usize) t: {
350pub fn reallocAtLeast(self: Allocator, old_mem: anytype, new_n: usize) t: {
338351 const Slice = @typeInfo(@TypeOf(old_mem)).Pointer;
339352 break :t Error![]align(Slice.alignment) Slice.child;
340353} {
......@@ -346,7 +359,7 @@ pub fn reallocAtLeast(self: *Allocator, old_mem: anytype, new_n: usize) t: {
346359/// a new alignment, which can be larger, smaller, or the same as the old
347360/// allocation.
348361pub fn reallocAdvanced(
349 self: *Allocator,
362 self: Allocator,
350363 old_mem: anytype,
351364 comptime new_alignment: u29,
352365 new_n: usize,
......@@ -356,7 +369,7 @@ pub fn reallocAdvanced(
356369}
357370
358371pub fn reallocAdvancedWithRetAddr(
359 self: *Allocator,
372 self: Allocator,
360373 old_mem: anytype,
361374 comptime new_alignment: u29,
362375 new_n: usize,
......@@ -380,8 +393,31 @@ pub fn reallocAdvancedWithRetAddr(
380393 .exact => 0,
381394 .at_least => @sizeOf(T),
382395 };
383 const new_byte_slice = try self.reallocBytes(old_byte_slice, Slice.alignment, byte_count, new_alignment, len_align, return_address);
384 return mem.bytesAsSlice(T, @alignCast(new_alignment, new_byte_slice));
396
397 if (mem.isAligned(@ptrToInt(old_byte_slice.ptr), new_alignment)) {
398 if (byte_count <= old_byte_slice.len) {
399 const shrunk_len = self.shrinkBytes(old_byte_slice, Slice.alignment, byte_count, len_align, return_address);
400 return mem.bytesAsSlice(T, @alignCast(new_alignment, old_byte_slice.ptr[0..shrunk_len]));
401 }
402
403 if (self.rawResize(old_byte_slice, Slice.alignment, byte_count, len_align, return_address)) |resized_len| {
404 // TODO: https://github.com/ziglang/zig/issues/4298
405 @memset(old_byte_slice.ptr + byte_count, undefined, resized_len - byte_count);
406 return mem.bytesAsSlice(T, @alignCast(new_alignment, old_byte_slice.ptr[0..resized_len]));
407 }
408 }
409
410 if (byte_count <= old_byte_slice.len and new_alignment <= Slice.alignment) {
411 return error.OutOfMemory;
412 }
413
414 const new_mem = try self.rawAlloc(byte_count, new_alignment, len_align, return_address);
415 @memcpy(new_mem.ptr, old_byte_slice.ptr, math.min(byte_count, old_byte_slice.len));
416 // TODO https://github.com/ziglang/zig/issues/4298
417 @memset(old_byte_slice.ptr, undefined, old_byte_slice.len);
418 self.rawFree(old_byte_slice, Slice.alignment, return_address);
419
420 return mem.bytesAsSlice(T, @alignCast(new_alignment, new_mem));
385421}
386422
387423/// Prefer calling realloc to shrink if you can tolerate failure, such as
......@@ -389,7 +425,7 @@ pub fn reallocAdvancedWithRetAddr(
389425/// Shrink always succeeds, and `new_n` must be <= `old_mem.len`.
390426/// Returned slice has same alignment as old_mem.
391427/// Shrinking to 0 is the same as calling `free`.
392pub fn shrink(self: *Allocator, old_mem: anytype, new_n: usize) t: {
428pub fn shrink(self: Allocator, old_mem: anytype, new_n: usize) t: {
393429 const Slice = @typeInfo(@TypeOf(old_mem)).Pointer;
394430 break :t []align(Slice.alignment) Slice.child;
395431} {
......@@ -401,7 +437,7 @@ pub fn shrink(self: *Allocator, old_mem: anytype, new_n: usize) t: {
401437/// a new alignment, which must be smaller or the same as the old
402438/// allocation.
403439pub fn alignedShrink(
404 self: *Allocator,
440 self: Allocator,
405441 old_mem: anytype,
406442 comptime new_alignment: u29,
407443 new_n: usize,
......@@ -413,7 +449,7 @@ pub fn alignedShrink(
413449/// the return address of the first stack frame, which may be relevant for
414450/// allocators which collect stack traces.
415451pub fn alignedShrinkWithRetAddr(
416 self: *Allocator,
452 self: Allocator,
417453 old_mem: anytype,
418454 comptime new_alignment: u29,
419455 new_n: usize,
......@@ -424,6 +460,11 @@ pub fn alignedShrinkWithRetAddr(
424460
425461 if (new_n == old_mem.len)
426462 return old_mem;
463 if (new_n == 0) {
464 self.free(old_mem);
465 return @as([*]align(new_alignment) T, undefined)[0..0];
466 }
467
427468 assert(new_n < old_mem.len);
428469 assert(new_alignment <= Slice.alignment);
429470
......@@ -440,7 +481,7 @@ pub fn alignedShrinkWithRetAddr(
440481
441482/// Free an array allocated with `alloc`. To free a single item,
442483/// see `destroy`.
443pub fn free(self: *Allocator, memory: anytype) void {
484pub fn free(self: Allocator, memory: anytype) void {
444485 const Slice = @typeInfo(@TypeOf(memory)).Pointer;
445486 const bytes = mem.sliceAsBytes(memory);
446487 const bytes_len = bytes.len + if (Slice.sentinel != null) @sizeOf(Slice.child) else 0;
......@@ -448,30 +489,30 @@ pub fn free(self: *Allocator, memory: anytype) void {
448489 const non_const_ptr = @intToPtr([*]u8, @ptrToInt(bytes.ptr));
449490 // TODO: https://github.com/ziglang/zig/issues/4298
450491 @memset(non_const_ptr, undefined, bytes_len);
451 _ = self.shrinkBytes(non_const_ptr[0..bytes_len], Slice.alignment, 0, 0, @returnAddress());
492 self.rawFree(non_const_ptr[0..bytes_len], Slice.alignment, @returnAddress());
452493}
453494
454495/// Copies `m` to newly allocated memory. Caller owns the memory.
455pub fn dupe(allocator: *Allocator, comptime T: type, m: []const T) ![]T {
496pub fn dupe(allocator: Allocator, comptime T: type, m: []const T) ![]T {
456497 const new_buf = try allocator.alloc(T, m.len);
457498 mem.copy(T, new_buf, m);
458499 return new_buf;
459500}
460501
461502/// Copies `m` to newly allocated memory, with a null-terminated element. Caller owns the memory.
462pub fn dupeZ(allocator: *Allocator, comptime T: type, m: []const T) ![:0]T {
503pub fn dupeZ(allocator: Allocator, comptime T: type, m: []const T) ![:0]T {
463504 const new_buf = try allocator.alloc(T, m.len + 1);
464505 mem.copy(T, new_buf, m);
465506 new_buf[m.len] = 0;
466507 return new_buf[0..m.len :0];
467508}
468509
469/// Call `resizeFn`, but caller guarantees that `new_len` <= `buf.len` meaning
470/// error.OutOfMemory should be impossible.
510/// Call `vtable.resize`, but caller guarantees that `new_len` <= `buf.len` meaning
511/// than a `null` return value should be impossible.
471512/// This function allows a runtime `buf_align` value. Callers should generally prefer
472513/// to call `shrink` directly.
473514pub fn shrinkBytes(
474 self: *Allocator,
515 self: Allocator,
475516 buf: []u8,
476517 buf_align: u29,
477518 new_len: usize,
......@@ -479,5 +520,5 @@ pub fn shrinkBytes(
479520 return_address: usize,
480521) usize {
481522 assert(new_len <= buf.len);
482 return self.resizeFn(self, buf, buf_align, new_len, len_align, return_address) catch unreachable;
523 return self.rawResize(buf, buf_align, new_len, len_align, return_address) orelse unreachable;
483524}
lib/std/multi_array_list.zig+10-10
......@@ -59,7 +59,7 @@ pub fn MultiArrayList(comptime S: type) type {
5959 };
6060 }
6161
62 pub fn deinit(self: *Slice, gpa: *Allocator) void {
62 pub fn deinit(self: *Slice, gpa: Allocator) void {
6363 var other = self.toMultiArrayList();
6464 other.deinit(gpa);
6565 self.* = undefined;
......@@ -106,7 +106,7 @@ pub fn MultiArrayList(comptime S: type) type {
106106 };
107107
108108 /// Release all allocated memory.
109 pub fn deinit(self: *Self, gpa: *Allocator) void {
109 pub fn deinit(self: *Self, gpa: Allocator) void {
110110 gpa.free(self.allocatedBytes());
111111 self.* = undefined;
112112 }
......@@ -161,7 +161,7 @@ pub fn MultiArrayList(comptime S: type) type {
161161 }
162162
163163 /// Extend the list by 1 element. Allocates more memory as necessary.
164 pub fn append(self: *Self, gpa: *Allocator, elem: S) !void {
164 pub fn append(self: *Self, gpa: Allocator, elem: S) !void {
165165 try self.ensureUnusedCapacity(gpa, 1);
166166 self.appendAssumeCapacity(elem);
167167 }
......@@ -188,7 +188,7 @@ pub fn MultiArrayList(comptime S: type) type {
188188 /// after and including the specified index back by one and
189189 /// sets the given index to the specified element. May reallocate
190190 /// and invalidate iterators.
191 pub fn insert(self: *Self, gpa: *Allocator, index: usize, elem: S) void {
191 pub fn insert(self: *Self, gpa: Allocator, index: usize, elem: S) void {
192192 try self.ensureUnusedCapacity(gpa, 1);
193193 self.insertAssumeCapacity(index, elem);
194194 }
......@@ -242,7 +242,7 @@ pub fn MultiArrayList(comptime S: type) type {
242242
243243 /// Adjust the list's length to `new_len`.
244244 /// Does not initialize added items, if any.
245 pub fn resize(self: *Self, gpa: *Allocator, new_len: usize) !void {
245 pub fn resize(self: *Self, gpa: Allocator, new_len: usize) !void {
246246 try self.ensureTotalCapacity(gpa, new_len);
247247 self.len = new_len;
248248 }
......@@ -250,7 +250,7 @@ pub fn MultiArrayList(comptime S: type) type {
250250 /// Attempt to reduce allocated capacity to `new_len`.
251251 /// If `new_len` is greater than zero, this may fail to reduce the capacity,
252252 /// but the data remains intact and the length is updated to new_len.
253 pub fn shrinkAndFree(self: *Self, gpa: *Allocator, new_len: usize) void {
253 pub fn shrinkAndFree(self: *Self, gpa: Allocator, new_len: usize) void {
254254 if (new_len == 0) {
255255 gpa.free(self.allocatedBytes());
256256 self.* = .{};
......@@ -314,7 +314,7 @@ pub fn MultiArrayList(comptime S: type) type {
314314 /// Modify the array so that it can hold at least `new_capacity` items.
315315 /// Implements super-linear growth to achieve amortized O(1) append operations.
316316 /// Invalidates pointers if additional memory is needed.
317 pub fn ensureTotalCapacity(self: *Self, gpa: *Allocator, new_capacity: usize) !void {
317 pub fn ensureTotalCapacity(self: *Self, gpa: Allocator, new_capacity: usize) !void {
318318 var better_capacity = self.capacity;
319319 if (better_capacity >= new_capacity) return;
320320
......@@ -328,14 +328,14 @@ pub fn MultiArrayList(comptime S: type) type {
328328
329329 /// Modify the array so that it can hold at least `additional_count` **more** items.
330330 /// Invalidates pointers if additional memory is needed.
331 pub fn ensureUnusedCapacity(self: *Self, gpa: *Allocator, additional_count: usize) !void {
331 pub fn ensureUnusedCapacity(self: *Self, gpa: Allocator, additional_count: usize) !void {
332332 return self.ensureTotalCapacity(gpa, self.len + additional_count);
333333 }
334334
335335 /// Modify the array so that it can hold exactly `new_capacity` items.
336336 /// Invalidates pointers if additional memory is needed.
337337 /// `new_capacity` must be greater or equal to `len`.
338 pub fn setCapacity(self: *Self, gpa: *Allocator, new_capacity: usize) !void {
338 pub fn setCapacity(self: *Self, gpa: Allocator, new_capacity: usize) !void {
339339 assert(new_capacity >= self.len);
340340 const new_bytes = try gpa.allocAdvanced(
341341 u8,
......@@ -372,7 +372,7 @@ pub fn MultiArrayList(comptime S: type) type {
372372
373373 /// Create a copy of this list with a new backing store,
374374 /// using the specified allocator.
375 pub fn clone(self: Self, gpa: *Allocator) !Self {
375 pub fn clone(self: Self, gpa: Allocator) !Self {
376376 var result = Self{};
377377 errdefer result.deinit(gpa);
378378 try result.ensureTotalCapacity(gpa, self.len);
lib/std/net.zig+5-5
......@@ -664,7 +664,7 @@ pub const AddressList = struct {
664664};
665665
666666/// All memory allocated with `allocator` will be freed before this function returns.
667pub fn tcpConnectToHost(allocator: *mem.Allocator, name: []const u8, port: u16) !Stream {
667pub fn tcpConnectToHost(allocator: mem.Allocator, name: []const u8, port: u16) !Stream {
668668 const list = try getAddressList(allocator, name, port);
669669 defer list.deinit();
670670
......@@ -699,12 +699,12 @@ pub fn tcpConnectToAddress(address: Address) !Stream {
699699}
700700
701701/// Call `AddressList.deinit` on the result.
702pub fn getAddressList(allocator: *mem.Allocator, name: []const u8, port: u16) !*AddressList {
702pub fn getAddressList(allocator: mem.Allocator, name: []const u8, port: u16) !*AddressList {
703703 const result = blk: {
704704 var arena = std.heap.ArenaAllocator.init(allocator);
705705 errdefer arena.deinit();
706706
707 const result = try arena.allocator.create(AddressList);
707 const result = try arena.allocator().create(AddressList);
708708 result.* = AddressList{
709709 .arena = arena,
710710 .addrs = undefined,
......@@ -712,7 +712,7 @@ pub fn getAddressList(allocator: *mem.Allocator, name: []const u8, port: u16) !*
712712 };
713713 break :blk result;
714714 };
715 const arena = &result.arena.allocator;
715 const arena = result.arena.allocator();
716716 errdefer result.arena.deinit();
717717
718718 if (builtin.target.os.tag == .windows or builtin.link_libc) {
......@@ -1303,7 +1303,7 @@ const ResolvConf = struct {
13031303
13041304/// Ignores lines longer than 512 bytes.
13051305/// TODO: https://github.com/ziglang/zig/issues/2765 and https://github.com/ziglang/zig/issues/2761
1306fn getResolvConf(allocator: *mem.Allocator, rc: *ResolvConf) !void {
1306fn getResolvConf(allocator: mem.Allocator, rc: *ResolvConf) !void {
13071307 rc.* = ResolvConf{
13081308 .ns = std.ArrayList(LookupAddr).init(allocator),
13091309 .search = std.ArrayList(u8).init(allocator),
lib/std/net/test.zig+1-1
......@@ -230,7 +230,7 @@ test "listen on ipv4 try connect on ipv6 then ipv4" {
230230 try await client_frame;
231231}
232232
233fn testClientToHost(allocator: *mem.Allocator, name: []const u8, port: u16) anyerror!void {
233fn testClientToHost(allocator: mem.Allocator, name: []const u8, port: u16) anyerror!void {
234234 if (builtin.os.tag == .wasi) return error.SkipZigTest;
235235
236236 const connection = try net.tcpConnectToHost(allocator, name, port);
lib/std/os/test.zig+10-9
......@@ -58,10 +58,11 @@ test "open smoke test" {
5858 // Get base abs path
5959 var arena = ArenaAllocator.init(testing.allocator);
6060 defer arena.deinit();
61 const allocator = arena.allocator();
6162
6263 const base_path = blk: {
63 const relative_path = try fs.path.join(&arena.allocator, &[_][]const u8{ "zig-cache", "tmp", tmp.sub_path[0..] });
64 break :blk try fs.realpathAlloc(&arena.allocator, relative_path);
64 const relative_path = try fs.path.join(allocator, &[_][]const u8{ "zig-cache", "tmp", tmp.sub_path[0..] });
65 break :blk try fs.realpathAlloc(allocator, relative_path);
6566 };
6667
6768 var file_path: []u8 = undefined;
......@@ -69,34 +70,34 @@ test "open smoke test" {
6970 const mode: os.mode_t = if (native_os == .windows) 0 else 0o666;
7071
7172 // Create some file using `open`.
72 file_path = try fs.path.join(&arena.allocator, &[_][]const u8{ base_path, "some_file" });
73 file_path = try fs.path.join(allocator, &[_][]const u8{ base_path, "some_file" });
7374 fd = try os.open(file_path, os.O.RDWR | os.O.CREAT | os.O.EXCL, mode);
7475 os.close(fd);
7576
7677 // Try this again with the same flags. This op should fail with error.PathAlreadyExists.
77 file_path = try fs.path.join(&arena.allocator, &[_][]const u8{ base_path, "some_file" });
78 file_path = try fs.path.join(allocator, &[_][]const u8{ base_path, "some_file" });
7879 try expectError(error.PathAlreadyExists, os.open(file_path, os.O.RDWR | os.O.CREAT | os.O.EXCL, mode));
7980
8081 // Try opening without `O.EXCL` flag.
81 file_path = try fs.path.join(&arena.allocator, &[_][]const u8{ base_path, "some_file" });
82 file_path = try fs.path.join(allocator, &[_][]const u8{ base_path, "some_file" });
8283 fd = try os.open(file_path, os.O.RDWR | os.O.CREAT, mode);
8384 os.close(fd);
8485
8586 // Try opening as a directory which should fail.
86 file_path = try fs.path.join(&arena.allocator, &[_][]const u8{ base_path, "some_file" });
87 file_path = try fs.path.join(allocator, &[_][]const u8{ base_path, "some_file" });
8788 try expectError(error.NotDir, os.open(file_path, os.O.RDWR | os.O.DIRECTORY, mode));
8889
8990 // Create some directory
90 file_path = try fs.path.join(&arena.allocator, &[_][]const u8{ base_path, "some_dir" });
91 file_path = try fs.path.join(allocator, &[_][]const u8{ base_path, "some_dir" });
9192 try os.mkdir(file_path, mode);
9293
9394 // Open dir using `open`
94 file_path = try fs.path.join(&arena.allocator, &[_][]const u8{ base_path, "some_dir" });
95 file_path = try fs.path.join(allocator, &[_][]const u8{ base_path, "some_dir" });
9596 fd = try os.open(file_path, os.O.RDONLY | os.O.DIRECTORY, mode);
9697 os.close(fd);
9798
9899 // Try opening as file which should fail.
99 file_path = try fs.path.join(&arena.allocator, &[_][]const u8{ base_path, "some_dir" });
100 file_path = try fs.path.join(allocator, &[_][]const u8{ base_path, "some_dir" });
100101 try expectError(error.IsDir, os.open(file_path, os.O.RDWR, mode));
101102}
102103
lib/std/pdb.zig+4-4
......@@ -460,7 +460,7 @@ pub const PDBStringTableHeader = packed struct {
460460 ByteSize: u32,
461461};
462462
463fn readSparseBitVector(stream: anytype, allocator: *mem.Allocator) ![]u32 {
463fn readSparseBitVector(stream: anytype, allocator: mem.Allocator) ![]u32 {
464464 const num_words = try stream.readIntLittle(u32);
465465 var list = ArrayList(u32).init(allocator);
466466 errdefer list.deinit();
......@@ -481,7 +481,7 @@ fn readSparseBitVector(stream: anytype, allocator: *mem.Allocator) ![]u32 {
481481pub const Pdb = struct {
482482 in_file: File,
483483 msf: Msf,
484 allocator: *mem.Allocator,
484 allocator: mem.Allocator,
485485 string_table: ?*MsfStream,
486486 dbi: ?*MsfStream,
487487 modules: []Module,
......@@ -500,7 +500,7 @@ pub const Pdb = struct {
500500 checksum_offset: ?usize,
501501 };
502502
503 pub fn init(allocator: *mem.Allocator, path: []const u8) !Pdb {
503 pub fn init(allocator: mem.Allocator, path: []const u8) !Pdb {
504504 const file = try fs.cwd().openFile(path, .{ .intended_io_mode = .blocking });
505505 errdefer file.close();
506506
......@@ -858,7 +858,7 @@ const Msf = struct {
858858 directory: MsfStream,
859859 streams: []MsfStream,
860860
861 fn init(allocator: *mem.Allocator, file: File) !Msf {
861 fn init(allocator: mem.Allocator, file: File) !Msf {
862862 const in = file.reader();
863863
864864 const superblock = try in.readStruct(SuperBlock);
lib/std/priority_dequeue.zig+4-4
......@@ -21,10 +21,10 @@ pub fn PriorityDequeue(comptime T: type, comptime compareFn: fn (T, T) Order) ty
2121
2222 items: []T,
2323 len: usize,
24 allocator: *Allocator,
24 allocator: Allocator,
2525
2626 /// Initialize and return a new priority dequeue.
27 pub fn init(allocator: *Allocator) Self {
27 pub fn init(allocator: Allocator) Self {
2828 return Self{
2929 .items = &[_]T{},
3030 .len = 0,
......@@ -336,7 +336,7 @@ pub fn PriorityDequeue(comptime T: type, comptime compareFn: fn (T, T) Order) ty
336336 /// Dequeue takes ownership of the passed in slice. The slice must have been
337337 /// allocated with `allocator`.
338338 /// De-initialize with `deinit`.
339 pub fn fromOwnedSlice(allocator: *Allocator, items: []T) Self {
339 pub fn fromOwnedSlice(allocator: Allocator, items: []T) Self {
340340 var queue = Self{
341341 .items = items,
342342 .len = items.len,
......@@ -945,7 +945,7 @@ fn fuzzTestMinMax(rng: std.rand.Random, queue_size: usize) !void {
945945 }
946946}
947947
948fn generateRandomSlice(allocator: *std.mem.Allocator, rng: std.rand.Random, size: usize) ![]u32 {
948fn generateRandomSlice(allocator: std.mem.Allocator, rng: std.rand.Random, size: usize) ![]u32 {
949949 var array = std.ArrayList(u32).init(allocator);
950950 try array.ensureTotalCapacity(size);
951951
lib/std/priority_queue.zig+3-3
......@@ -20,10 +20,10 @@ pub fn PriorityQueue(comptime T: type, comptime compareFn: fn (a: T, b: T) Order
2020
2121 items: []T,
2222 len: usize,
23 allocator: *Allocator,
23 allocator: Allocator,
2424
2525 /// Initialize and return a priority queue.
26 pub fn init(allocator: *Allocator) Self {
26 pub fn init(allocator: Allocator) Self {
2727 return Self{
2828 .items = &[_]T{},
2929 .len = 0,
......@@ -153,7 +153,7 @@ pub fn PriorityQueue(comptime T: type, comptime compareFn: fn (a: T, b: T) Order
153153 /// PriorityQueue takes ownership of the passed in slice. The slice must have been
154154 /// allocated with `allocator`.
155155 /// Deinitialize with `deinit`.
156 pub fn fromOwnedSlice(allocator: *Allocator, items: []T) Self {
156 pub fn fromOwnedSlice(allocator: Allocator, items: []T) Self {
157157 var queue = Self{
158158 .items = items,
159159 .len = items.len,
lib/std/process.zig+20-20
......@@ -21,7 +21,7 @@ pub fn getCwd(out_buffer: []u8) ![]u8 {
2121}
2222
2323/// Caller must free the returned memory.
24pub fn getCwdAlloc(allocator: *Allocator) ![]u8 {
24pub fn getCwdAlloc(allocator: Allocator) ![]u8 {
2525 // The use of MAX_PATH_BYTES here is just a heuristic: most paths will fit
2626 // in stack_buf, avoiding an extra allocation in the common case.
2727 var stack_buf: [fs.MAX_PATH_BYTES]u8 = undefined;
......@@ -54,7 +54,7 @@ test "getCwdAlloc" {
5454}
5555
5656/// Caller owns resulting `BufMap`.
57pub fn getEnvMap(allocator: *Allocator) !BufMap {
57pub fn getEnvMap(allocator: Allocator) !BufMap {
5858 var result = BufMap.init(allocator);
5959 errdefer result.deinit();
6060
......@@ -154,7 +154,7 @@ pub const GetEnvVarOwnedError = error{
154154};
155155
156156/// Caller must free returned memory.
157pub fn getEnvVarOwned(allocator: *mem.Allocator, key: []const u8) GetEnvVarOwnedError![]u8 {
157pub fn getEnvVarOwned(allocator: mem.Allocator, key: []const u8) GetEnvVarOwnedError![]u8 {
158158 if (builtin.os.tag == .windows) {
159159 const result_w = blk: {
160160 const key_w = try std.unicode.utf8ToUtf16LeWithNull(allocator, key);
......@@ -183,10 +183,10 @@ pub fn hasEnvVarConstant(comptime key: []const u8) bool {
183183 }
184184}
185185
186pub fn hasEnvVar(allocator: *Allocator, key: []const u8) error{OutOfMemory}!bool {
186pub fn hasEnvVar(allocator: Allocator, key: []const u8) error{OutOfMemory}!bool {
187187 if (builtin.os.tag == .windows) {
188188 var stack_alloc = std.heap.stackFallback(256 * @sizeOf(u16), allocator);
189 const key_w = try std.unicode.utf8ToUtf16LeWithNull(&stack_alloc.allocator, key);
189 const key_w = try std.unicode.utf8ToUtf16LeWithNull(stack_alloc.get(), key);
190190 defer stack_alloc.allocator.free(key_w);
191191 return std.os.getenvW(key_w) != null;
192192 } else {
......@@ -227,7 +227,7 @@ pub const ArgIteratorPosix = struct {
227227};
228228
229229pub const ArgIteratorWasi = struct {
230 allocator: *mem.Allocator,
230 allocator: mem.Allocator,
231231 index: usize,
232232 args: [][:0]u8,
233233
......@@ -235,7 +235,7 @@ pub const ArgIteratorWasi = struct {
235235
236236 /// You must call deinit to free the internal buffer of the
237237 /// iterator after you are done.
238 pub fn init(allocator: *mem.Allocator) InitError!ArgIteratorWasi {
238 pub fn init(allocator: mem.Allocator) InitError!ArgIteratorWasi {
239239 const fetched_args = try ArgIteratorWasi.internalInit(allocator);
240240 return ArgIteratorWasi{
241241 .allocator = allocator,
......@@ -244,7 +244,7 @@ pub const ArgIteratorWasi = struct {
244244 };
245245 }
246246
247 fn internalInit(allocator: *mem.Allocator) InitError![][:0]u8 {
247 fn internalInit(allocator: mem.Allocator) InitError![][:0]u8 {
248248 const w = os.wasi;
249249 var count: usize = undefined;
250250 var buf_size: usize = undefined;
......@@ -325,7 +325,7 @@ pub const ArgIteratorWindows = struct {
325325 }
326326
327327 /// You must free the returned memory when done.
328 pub fn next(self: *ArgIteratorWindows, allocator: *Allocator) ?(NextError![:0]u8) {
328 pub fn next(self: *ArgIteratorWindows, allocator: Allocator) ?(NextError![:0]u8) {
329329 // march forward over whitespace
330330 while (true) : (self.index += 1) {
331331 const character = self.getPointAtIndex();
......@@ -379,7 +379,7 @@ pub const ArgIteratorWindows = struct {
379379 }
380380 }
381381
382 fn internalNext(self: *ArgIteratorWindows, allocator: *Allocator) NextError![:0]u8 {
382 fn internalNext(self: *ArgIteratorWindows, allocator: Allocator) NextError![:0]u8 {
383383 var buf = std.ArrayList(u16).init(allocator);
384384 defer buf.deinit();
385385
......@@ -423,7 +423,7 @@ pub const ArgIteratorWindows = struct {
423423 }
424424 }
425425
426 fn convertFromWindowsCmdLineToUTF8(allocator: *Allocator, buf: []u16) NextError![:0]u8 {
426 fn convertFromWindowsCmdLineToUTF8(allocator: Allocator, buf: []u16) NextError![:0]u8 {
427427 return std.unicode.utf16leToUtf8AllocZ(allocator, buf) catch |err| switch (err) {
428428 error.ExpectedSecondSurrogateHalf,
429429 error.DanglingSurrogateHalf,
......@@ -463,7 +463,7 @@ pub const ArgIterator = struct {
463463 pub const InitError = ArgIteratorWasi.InitError;
464464
465465 /// You must deinitialize iterator's internal buffers by calling `deinit` when done.
466 pub fn initWithAllocator(allocator: *mem.Allocator) InitError!ArgIterator {
466 pub fn initWithAllocator(allocator: mem.Allocator) InitError!ArgIterator {
467467 if (builtin.os.tag == .wasi and !builtin.link_libc) {
468468 return ArgIterator{ .inner = try InnerType.init(allocator) };
469469 }
......@@ -474,7 +474,7 @@ pub const ArgIterator = struct {
474474 pub const NextError = ArgIteratorWindows.NextError;
475475
476476 /// You must free the returned memory when done.
477 pub fn next(self: *ArgIterator, allocator: *Allocator) ?(NextError![:0]u8) {
477 pub fn next(self: *ArgIterator, allocator: Allocator) ?(NextError![:0]u8) {
478478 if (builtin.os.tag == .windows) {
479479 return self.inner.next(allocator);
480480 } else {
......@@ -513,7 +513,7 @@ pub fn args() ArgIterator {
513513}
514514
515515/// You must deinitialize iterator's internal buffers by calling `deinit` when done.
516pub fn argsWithAllocator(allocator: *mem.Allocator) ArgIterator.InitError!ArgIterator {
516pub fn argsWithAllocator(allocator: mem.Allocator) ArgIterator.InitError!ArgIterator {
517517 return ArgIterator.initWithAllocator(allocator);
518518}
519519
......@@ -539,7 +539,7 @@ test "args iterator" {
539539}
540540
541541/// Caller must call argsFree on result.
542pub fn argsAlloc(allocator: *mem.Allocator) ![][:0]u8 {
542pub fn argsAlloc(allocator: mem.Allocator) ![][:0]u8 {
543543 // TODO refactor to only make 1 allocation.
544544 var it = if (builtin.os.tag == .wasi) try argsWithAllocator(allocator) else args();
545545 defer it.deinit();
......@@ -579,7 +579,7 @@ pub fn argsAlloc(allocator: *mem.Allocator) ![][:0]u8 {
579579 return result_slice_list;
580580}
581581
582pub fn argsFree(allocator: *mem.Allocator, args_alloc: []const [:0]u8) void {
582pub fn argsFree(allocator: mem.Allocator, args_alloc: []const [:0]u8) void {
583583 var total_bytes: usize = 0;
584584 for (args_alloc) |arg| {
585585 total_bytes += @sizeOf([]u8) + arg.len + 1;
......@@ -741,7 +741,7 @@ pub fn getBaseAddress() usize {
741741/// requirement from `std.zig.system.NativeTargetInfo.detect`. Most likely this will require
742742/// introducing a new, lower-level function which takes a callback function, and then this
743743/// function which takes an allocator can exist on top of it.
744pub fn getSelfExeSharedLibPaths(allocator: *Allocator) error{OutOfMemory}![][:0]u8 {
744pub fn getSelfExeSharedLibPaths(allocator: Allocator) error{OutOfMemory}![][:0]u8 {
745745 switch (builtin.link_mode) {
746746 .Static => return &[_][:0]u8{},
747747 .Dynamic => {},
......@@ -833,7 +833,7 @@ pub const ExecvError = std.os.ExecveError || error{OutOfMemory};
833833/// This function also uses the PATH environment variable to get the full path to the executable.
834834/// Due to the heap-allocation, it is illegal to call this function in a fork() child.
835835/// For that use case, use the `std.os` functions directly.
836pub fn execv(allocator: *mem.Allocator, argv: []const []const u8) ExecvError {
836pub fn execv(allocator: mem.Allocator, argv: []const []const u8) ExecvError {
837837 return execve(allocator, argv, null);
838838}
839839
......@@ -846,7 +846,7 @@ pub fn execv(allocator: *mem.Allocator, argv: []const []const u8) ExecvError {
846846/// Due to the heap-allocation, it is illegal to call this function in a fork() child.
847847/// For that use case, use the `std.os` functions directly.
848848pub fn execve(
849 allocator: *mem.Allocator,
849 allocator: mem.Allocator,
850850 argv: []const []const u8,
851851 env_map: ?*const std.BufMap,
852852) ExecvError {
......@@ -854,7 +854,7 @@ pub fn execve(
854854
855855 var arena_allocator = std.heap.ArenaAllocator.init(allocator);
856856 defer arena_allocator.deinit();
857 const arena = &arena_allocator.allocator;
857 const arena = arena_allocator.allocator();
858858
859859 const argv_buf = try arena.allocSentinel(?[*:0]u8, argv.len, null);
860860 for (argv) |arg, i| argv_buf[i] = (try arena.dupeZ(u8, arg)).ptr;
lib/std/special/build_runner.zig+1-1
......@@ -16,7 +16,7 @@ pub fn main() !void {
1616 var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
1717 defer arena.deinit();
1818
19 const allocator = &arena.allocator;
19 const allocator = arena.allocator();
2020 var args = try process.argsAlloc(allocator);
2121 defer process.argsFree(allocator, args);
2222
lib/std/special/test_runner.zig+1-1
......@@ -10,7 +10,7 @@ var args_buffer: [std.fs.MAX_PATH_BYTES + std.mem.page_size]u8 = undefined;
1010var args_allocator = std.heap.FixedBufferAllocator.init(&args_buffer);
1111
1212fn processArgs() void {
13 const args = std.process.argsAlloc(&args_allocator.allocator) catch {
13 const args = std.process.argsAlloc(args_allocator.allocator()) catch {
1414 @panic("Too many bytes passed over the CLI to the test runner");
1515 };
1616 if (args.len != 2) {
lib/std/target.zig+3-3
......@@ -1323,15 +1323,15 @@ pub const Target = struct {
13231323
13241324 pub const stack_align = 16;
13251325
1326 pub fn zigTriple(self: Target, allocator: *mem.Allocator) ![]u8 {
1326 pub fn zigTriple(self: Target, allocator: mem.Allocator) ![]u8 {
13271327 return std.zig.CrossTarget.fromTarget(self).zigTriple(allocator);
13281328 }
13291329
1330 pub fn linuxTripleSimple(allocator: *mem.Allocator, cpu_arch: Cpu.Arch, os_tag: Os.Tag, abi: Abi) ![]u8 {
1330 pub fn linuxTripleSimple(allocator: mem.Allocator, cpu_arch: Cpu.Arch, os_tag: Os.Tag, abi: Abi) ![]u8 {
13311331 return std.fmt.allocPrint(allocator, "{s}-{s}-{s}", .{ @tagName(cpu_arch), @tagName(os_tag), @tagName(abi) });
13321332 }
13331333
1334 pub fn linuxTriple(self: Target, allocator: *mem.Allocator) ![]u8 {
1334 pub fn linuxTriple(self: Target, allocator: mem.Allocator) ![]u8 {
13351335 return linuxTripleSimple(allocator, self.cpu.arch, self.os.tag, self.abi);
13361336 }
13371337
lib/std/testing.zig+3-3
......@@ -7,11 +7,11 @@ const print = std.debug.print;
77pub const FailingAllocator = @import("testing/failing_allocator.zig").FailingAllocator;
88
99/// This should only be used in temporary test programs.
10pub const allocator = &allocator_instance.allocator;
10pub const allocator = allocator_instance.allocator();
1111pub var allocator_instance = std.heap.GeneralPurposeAllocator(.{}){};
1212
13pub const failing_allocator = &failing_allocator_instance.allocator;
14pub var failing_allocator_instance = FailingAllocator.init(&base_allocator_instance.allocator, 0);
13pub const failing_allocator = failing_allocator_instance.allocator();
14pub var failing_allocator_instance = FailingAllocator.init(base_allocator_instance.allocator(), 0);
1515
1616pub var base_allocator_instance = std.heap.FixedBufferAllocator.init("");
1717
lib/std/testing/failing_allocator.zig+24-22
......@@ -12,10 +12,9 @@ const mem = std.mem;
1212/// Then use `failing_allocator` anywhere you would have used a
1313/// different allocator.
1414pub const FailingAllocator = struct {
15 allocator: mem.Allocator,
1615 index: usize,
1716 fail_index: usize,
18 internal_allocator: *mem.Allocator,
17 internal_allocator: mem.Allocator,
1918 allocated_bytes: usize,
2019 freed_bytes: usize,
2120 allocations: usize,
......@@ -29,34 +28,33 @@ pub const FailingAllocator = struct {
2928 /// var a = try failing_alloc.create(i32);
3029 /// var b = try failing_alloc.create(i32);
3130 /// testing.expectError(error.OutOfMemory, failing_alloc.create(i32));
32 pub fn init(allocator: *mem.Allocator, fail_index: usize) FailingAllocator {
31 pub fn init(internal_allocator: mem.Allocator, fail_index: usize) FailingAllocator {
3332 return FailingAllocator{
34 .internal_allocator = allocator,
33 .internal_allocator = internal_allocator,
3534 .fail_index = fail_index,
3635 .index = 0,
3736 .allocated_bytes = 0,
3837 .freed_bytes = 0,
3938 .allocations = 0,
4039 .deallocations = 0,
41 .allocator = mem.Allocator{
42 .allocFn = alloc,
43 .resizeFn = resize,
44 },
4540 };
4641 }
4742
43 pub fn allocator(self: *FailingAllocator) mem.Allocator {
44 return mem.Allocator.init(self, alloc, resize, free);
45 }
46
4847 fn alloc(
49 allocator: *std.mem.Allocator,
48 self: *FailingAllocator,
5049 len: usize,
5150 ptr_align: u29,
5251 len_align: u29,
5352 return_address: usize,
5453 ) error{OutOfMemory}![]u8 {
55 const self = @fieldParentPtr(FailingAllocator, "allocator", allocator);
5654 if (self.index == self.fail_index) {
5755 return error.OutOfMemory;
5856 }
59 const result = try self.internal_allocator.allocFn(self.internal_allocator, len, ptr_align, len_align, return_address);
57 const result = try self.internal_allocator.rawAlloc(len, ptr_align, len_align, return_address);
6058 self.allocated_bytes += result.len;
6159 self.allocations += 1;
6260 self.index += 1;
......@@ -64,26 +62,30 @@ pub const FailingAllocator = struct {
6462 }
6563
6664 fn resize(
67 allocator: *std.mem.Allocator,
65 self: *FailingAllocator,
6866 old_mem: []u8,
6967 old_align: u29,
7068 new_len: usize,
7169 len_align: u29,
7270 ra: usize,
73 ) error{OutOfMemory}!usize {
74 const self = @fieldParentPtr(FailingAllocator, "allocator", allocator);
75 const r = self.internal_allocator.resizeFn(self.internal_allocator, old_mem, old_align, new_len, len_align, ra) catch |e| {
76 std.debug.assert(new_len > old_mem.len);
77 return e;
78 };
79 if (new_len == 0) {
80 self.deallocations += 1;
81 self.freed_bytes += old_mem.len;
82 } else if (r < old_mem.len) {
71 ) ?usize {
72 const r = self.internal_allocator.rawResize(old_mem, old_align, new_len, len_align, ra) orelse return null;
73 if (r < old_mem.len) {
8374 self.freed_bytes += old_mem.len - r;
8475 } else {
8576 self.allocated_bytes += r - old_mem.len;
8677 }
8778 return r;
8879 }
80
81 fn free(
82 self: *FailingAllocator,
83 old_mem: []u8,
84 old_align: u29,
85 ra: usize,
86 ) void {
87 self.internal_allocator.rawFree(old_mem, old_align, ra);
88 self.deallocations += 1;
89 self.freed_bytes += old_mem.len;
90 }
8991};
lib/std/unicode.zig+3-3
......@@ -550,7 +550,7 @@ fn testDecode(bytes: []const u8) !u21 {
550550}
551551
552552/// Caller must free returned memory.
553pub fn utf16leToUtf8Alloc(allocator: *mem.Allocator, utf16le: []const u16) ![]u8 {
553pub fn utf16leToUtf8Alloc(allocator: mem.Allocator, utf16le: []const u16) ![]u8 {
554554 // optimistically guess that it will all be ascii.
555555 var result = try std.ArrayList(u8).initCapacity(allocator, utf16le.len);
556556 errdefer result.deinit();
......@@ -567,7 +567,7 @@ pub fn utf16leToUtf8Alloc(allocator: *mem.Allocator, utf16le: []const u16) ![]u8
567567}
568568
569569/// Caller must free returned memory.
570pub fn utf16leToUtf8AllocZ(allocator: *mem.Allocator, utf16le: []const u16) ![:0]u8 {
570pub fn utf16leToUtf8AllocZ(allocator: mem.Allocator, utf16le: []const u16) ![:0]u8 {
571571 // optimistically guess that it will all be ascii.
572572 var result = try std.ArrayList(u8).initCapacity(allocator, utf16le.len);
573573 errdefer result.deinit();
......@@ -661,7 +661,7 @@ test "utf16leToUtf8" {
661661 }
662662}
663663
664pub fn utf8ToUtf16LeWithNull(allocator: *mem.Allocator, utf8: []const u8) ![:0]u16 {
664pub fn utf8ToUtf16LeWithNull(allocator: mem.Allocator, utf8: []const u8) ![:0]u16 {
665665 // optimistically guess that it will not require surrogate pairs
666666 var result = try std.ArrayList(u16).initCapacity(allocator, utf8.len + 1);
667667 errdefer result.deinit();
lib/std/wasm.zig+1-1
......@@ -361,7 +361,7 @@ pub const Type = struct {
361361 std.mem.eql(Valtype, self.returns, other.returns);
362362 }
363363
364 pub fn deinit(self: *Type, gpa: *std.mem.Allocator) void {
364 pub fn deinit(self: *Type, gpa: std.mem.Allocator) void {
365365 gpa.free(self.params);
366366 gpa.free(self.returns);
367367 self.* = undefined;
lib/std/zig.zig+1-1
......@@ -100,7 +100,7 @@ pub const BinNameOptions = struct {
100100};
101101
102102/// Returns the standard file system basename of a binary generated by the Zig compiler.
103pub fn binNameAlloc(allocator: *std.mem.Allocator, options: BinNameOptions) error{OutOfMemory}![]u8 {
103pub fn binNameAlloc(allocator: std.mem.Allocator, options: BinNameOptions) error{OutOfMemory}![]u8 {
104104 const root_name = options.root_name;
105105 const target = options.target;
106106 const ofmt = options.object_format orelse target.getObjectFormat();
lib/std/zig/Ast.zig+2-2
......@@ -34,7 +34,7 @@ pub const Location = struct {
3434 line_end: usize,
3535};
3636
37pub fn deinit(tree: *Tree, gpa: *mem.Allocator) void {
37pub fn deinit(tree: *Tree, gpa: mem.Allocator) void {
3838 tree.tokens.deinit(gpa);
3939 tree.nodes.deinit(gpa);
4040 gpa.free(tree.extra_data);
......@@ -52,7 +52,7 @@ pub const RenderError = error{
5252/// for allocating extra stack memory if needed, because this function utilizes recursion.
5353/// Note: that's not actually true yet, see https://github.com/ziglang/zig/issues/1006.
5454/// Caller owns the returned slice of bytes, allocated with `gpa`.
55pub fn render(tree: Tree, gpa: *mem.Allocator) RenderError![]u8 {
55pub fn render(tree: Tree, gpa: mem.Allocator) RenderError![]u8 {
5656 var buffer = std.ArrayList(u8).init(gpa);
5757 defer buffer.deinit();
5858
lib/std/zig/CrossTarget.zig+4-4
......@@ -520,7 +520,7 @@ pub fn isNative(self: CrossTarget) bool {
520520 return self.isNativeCpu() and self.isNativeOs() and self.isNativeAbi();
521521}
522522
523pub fn zigTriple(self: CrossTarget, allocator: *mem.Allocator) error{OutOfMemory}![]u8 {
523pub fn zigTriple(self: CrossTarget, allocator: mem.Allocator) error{OutOfMemory}![]u8 {
524524 if (self.isNative()) {
525525 return allocator.dupe(u8, "native");
526526 }
......@@ -559,13 +559,13 @@ pub fn zigTriple(self: CrossTarget, allocator: *mem.Allocator) error{OutOfMemory
559559 return result.toOwnedSlice();
560560}
561561
562pub fn allocDescription(self: CrossTarget, allocator: *mem.Allocator) ![]u8 {
562pub fn allocDescription(self: CrossTarget, allocator: mem.Allocator) ![]u8 {
563563 // TODO is there anything else worthy of the description that is not
564564 // already captured in the triple?
565565 return self.zigTriple(allocator);
566566}
567567
568pub fn linuxTriple(self: CrossTarget, allocator: *mem.Allocator) ![]u8 {
568pub fn linuxTriple(self: CrossTarget, allocator: mem.Allocator) ![]u8 {
569569 return Target.linuxTripleSimple(allocator, self.getCpuArch(), self.getOsTag(), self.getAbi());
570570}
571571
......@@ -576,7 +576,7 @@ pub fn wantSharedLibSymLinks(self: CrossTarget) bool {
576576pub const VcpkgLinkage = std.builtin.LinkMode;
577577
578578/// Returned slice must be freed by the caller.
579pub fn vcpkgTriplet(self: CrossTarget, allocator: *mem.Allocator, linkage: VcpkgLinkage) ![]u8 {
579pub fn vcpkgTriplet(self: CrossTarget, allocator: mem.Allocator, linkage: VcpkgLinkage) ![]u8 {
580580 const arch = switch (self.getCpuArch()) {
581581 .i386 => "x86",
582582 .x86_64 => "x64",
lib/std/zig/parse.zig+2-2
......@@ -11,7 +11,7 @@ pub const Error = error{ParseError} || Allocator.Error;
1111
1212/// Result should be freed with tree.deinit() when there are
1313/// no more references to any of the tokens or nodes.
14pub fn parse(gpa: *Allocator, source: [:0]const u8) Allocator.Error!Ast {
14pub fn parse(gpa: Allocator, source: [:0]const u8) Allocator.Error!Ast {
1515 var tokens = Ast.TokenList{};
1616 defer tokens.deinit(gpa);
1717
......@@ -81,7 +81,7 @@ const null_node: Node.Index = 0;
8181
8282/// Represents in-progress parsing, will be converted to an Ast after completion.
8383const Parser = struct {
84 gpa: *Allocator,
84 gpa: Allocator,
8585 source: []const u8,
8686 token_tags: []const Token.Tag,
8787 token_starts: []const Ast.ByteOffset,
lib/std/zig/parser_test.zig+9-8
......@@ -1220,7 +1220,7 @@ test "zig fmt: doc comments on param decl" {
12201220 try testCanonical(
12211221 \\pub const Allocator = struct {
12221222 \\ shrinkFn: fn (
1223 \\ self: *Allocator,
1223 \\ self: Allocator,
12241224 \\ /// Guaranteed to be the same as what was returned from most recent call to
12251225 \\ /// `allocFn`, `reallocFn`, or `shrinkFn`.
12261226 \\ old_mem: []u8,
......@@ -4250,7 +4250,7 @@ test "zig fmt: Only indent multiline string literals in function calls" {
42504250
42514251test "zig fmt: Don't add extra newline after if" {
42524252 try testCanonical(
4253 \\pub fn atomicSymLink(allocator: *Allocator, existing_path: []const u8, new_path: []const u8) !void {
4253 \\pub fn atomicSymLink(allocator: Allocator, existing_path: []const u8, new_path: []const u8) !void {
42544254 \\ if (cwd().symLink(existing_path, new_path, .{})) {
42554255 \\ return;
42564256 \\ }
......@@ -5319,7 +5319,7 @@ const maxInt = std.math.maxInt;
53195319
53205320var fixed_buffer_mem: [100 * 1024]u8 = undefined;
53215321
5322fn testParse(source: [:0]const u8, allocator: *mem.Allocator, anything_changed: *bool) ![]u8 {
5322fn testParse(source: [:0]const u8, allocator: mem.Allocator, anything_changed: *bool) ![]u8 {
53235323 const stderr = io.getStdErr().writer();
53245324
53255325 var tree = try std.zig.parse(allocator, source);
......@@ -5351,9 +5351,10 @@ fn testTransform(source: [:0]const u8, expected_source: []const u8) !void {
53515351 const needed_alloc_count = x: {
53525352 // Try it once with unlimited memory, make sure it works
53535353 var fixed_allocator = std.heap.FixedBufferAllocator.init(fixed_buffer_mem[0..]);
5354 var failing_allocator = std.testing.FailingAllocator.init(&fixed_allocator.allocator, maxInt(usize));
5354 var failing_allocator = std.testing.FailingAllocator.init(fixed_allocator.allocator(), maxInt(usize));
5355 const allocator = failing_allocator.allocator();
53555356 var anything_changed: bool = undefined;
5356 const result_source = try testParse(source, &failing_allocator.allocator, &anything_changed);
5357 const result_source = try testParse(source, allocator, &anything_changed);
53575358 try std.testing.expectEqualStrings(expected_source, result_source);
53585359 const changes_expected = source.ptr != expected_source.ptr;
53595360 if (anything_changed != changes_expected) {
......@@ -5361,16 +5362,16 @@ fn testTransform(source: [:0]const u8, expected_source: []const u8) !void {
53615362 return error.TestFailed;
53625363 }
53635364 try std.testing.expect(anything_changed == changes_expected);
5364 failing_allocator.allocator.free(result_source);
5365 allocator.free(result_source);
53655366 break :x failing_allocator.index;
53665367 };
53675368
53685369 var fail_index: usize = 0;
53695370 while (fail_index < needed_alloc_count) : (fail_index += 1) {
53705371 var fixed_allocator = std.heap.FixedBufferAllocator.init(fixed_buffer_mem[0..]);
5371 var failing_allocator = std.testing.FailingAllocator.init(&fixed_allocator.allocator, fail_index);
5372 var failing_allocator = std.testing.FailingAllocator.init(fixed_allocator.allocator(), fail_index);
53725373 var anything_changed: bool = undefined;
5373 if (testParse(source, &failing_allocator.allocator, &anything_changed)) |_| {
5374 if (testParse(source, failing_allocator.allocator(), &anything_changed)) |_| {
53745375 return error.NondeterministicMemoryUsage;
53755376 } else |err| switch (err) {
53765377 error.OutOfMemory => {
lib/std/zig/perf_test.zig+1-1
......@@ -33,7 +33,7 @@ pub fn main() !void {
3333
3434fn testOnce() usize {
3535 var fixed_buf_alloc = std.heap.FixedBufferAllocator.init(fixed_buffer_mem[0..]);
36 var allocator = &fixed_buf_alloc.allocator;
36 var allocator = fixed_buf_alloc.allocator();
3737 _ = std.zig.parse(allocator, source) catch @panic("parse failure");
3838 return fixed_buf_alloc.end_index;
3939}
lib/std/zig/render.zig+24-24
......@@ -37,7 +37,7 @@ pub fn renderTree(buffer: *std.ArrayList(u8), tree: Ast) Error!void {
3737}
3838
3939/// Render all members in the given slice, keeping empty lines where appropriate
40fn renderMembers(gpa: *Allocator, ais: *Ais, tree: Ast, members: []const Ast.Node.Index) Error!void {
40fn renderMembers(gpa: Allocator, ais: *Ais, tree: Ast, members: []const Ast.Node.Index) Error!void {
4141 if (members.len == 0) return;
4242 try renderMember(gpa, ais, tree, members[0], .newline);
4343 for (members[1..]) |member| {
......@@ -46,7 +46,7 @@ fn renderMembers(gpa: *Allocator, ais: *Ais, tree: Ast, members: []const Ast.Nod
4646 }
4747}
4848
49fn renderMember(gpa: *Allocator, ais: *Ais, tree: Ast, decl: Ast.Node.Index, space: Space) Error!void {
49fn renderMember(gpa: Allocator, ais: *Ais, tree: Ast, decl: Ast.Node.Index, space: Space) Error!void {
5050 const token_tags = tree.tokens.items(.tag);
5151 const main_tokens = tree.nodes.items(.main_token);
5252 const datas = tree.nodes.items(.data);
......@@ -168,7 +168,7 @@ fn renderMember(gpa: *Allocator, ais: *Ais, tree: Ast, decl: Ast.Node.Index, spa
168168}
169169
170170/// Render all expressions in the slice, keeping empty lines where appropriate
171fn renderExpressions(gpa: *Allocator, ais: *Ais, tree: Ast, expressions: []const Ast.Node.Index, space: Space) Error!void {
171fn renderExpressions(gpa: Allocator, ais: *Ais, tree: Ast, expressions: []const Ast.Node.Index, space: Space) Error!void {
172172 if (expressions.len == 0) return;
173173 try renderExpression(gpa, ais, tree, expressions[0], space);
174174 for (expressions[1..]) |expression| {
......@@ -177,7 +177,7 @@ fn renderExpressions(gpa: *Allocator, ais: *Ais, tree: Ast, expressions: []const
177177 }
178178}
179179
180fn renderExpression(gpa: *Allocator, ais: *Ais, tree: Ast, node: Ast.Node.Index, space: Space) Error!void {
180fn renderExpression(gpa: Allocator, ais: *Ais, tree: Ast, node: Ast.Node.Index, space: Space) Error!void {
181181 const token_tags = tree.tokens.items(.tag);
182182 const main_tokens = tree.nodes.items(.main_token);
183183 const node_tags = tree.nodes.items(.tag);
......@@ -710,7 +710,7 @@ fn renderExpression(gpa: *Allocator, ais: *Ais, tree: Ast, node: Ast.Node.Index,
710710}
711711
712712fn renderArrayType(
713 gpa: *Allocator,
713 gpa: Allocator,
714714 ais: *Ais,
715715 tree: Ast,
716716 array_type: Ast.full.ArrayType,
......@@ -732,7 +732,7 @@ fn renderArrayType(
732732}
733733
734734fn renderPtrType(
735 gpa: *Allocator,
735 gpa: Allocator,
736736 ais: *Ais,
737737 tree: Ast,
738738 ptr_type: Ast.full.PtrType,
......@@ -825,7 +825,7 @@ fn renderPtrType(
825825}
826826
827827fn renderSlice(
828 gpa: *Allocator,
828 gpa: Allocator,
829829 ais: *Ais,
830830 tree: Ast,
831831 slice_node: Ast.Node.Index,
......@@ -861,7 +861,7 @@ fn renderSlice(
861861}
862862
863863fn renderAsmOutput(
864 gpa: *Allocator,
864 gpa: Allocator,
865865 ais: *Ais,
866866 tree: Ast,
867867 asm_output: Ast.Node.Index,
......@@ -891,7 +891,7 @@ fn renderAsmOutput(
891891}
892892
893893fn renderAsmInput(
894 gpa: *Allocator,
894 gpa: Allocator,
895895 ais: *Ais,
896896 tree: Ast,
897897 asm_input: Ast.Node.Index,
......@@ -912,7 +912,7 @@ fn renderAsmInput(
912912 return renderToken(ais, tree, datas[asm_input].rhs, space); // rparen
913913}
914914
915fn renderVarDecl(gpa: *Allocator, ais: *Ais, tree: Ast, var_decl: Ast.full.VarDecl) Error!void {
915fn renderVarDecl(gpa: Allocator, ais: *Ais, tree: Ast, var_decl: Ast.full.VarDecl) Error!void {
916916 if (var_decl.visib_token) |visib_token| {
917917 try renderToken(ais, tree, visib_token, Space.space); // pub
918918 }
......@@ -1019,7 +1019,7 @@ fn renderVarDecl(gpa: *Allocator, ais: *Ais, tree: Ast, var_decl: Ast.full.VarDe
10191019 return renderToken(ais, tree, var_decl.ast.mut_token + 2, .newline); // ;
10201020}
10211021
1022fn renderIf(gpa: *Allocator, ais: *Ais, tree: Ast, if_node: Ast.full.If, space: Space) Error!void {
1022fn renderIf(gpa: Allocator, ais: *Ais, tree: Ast, if_node: Ast.full.If, space: Space) Error!void {
10231023 return renderWhile(gpa, ais, tree, .{
10241024 .ast = .{
10251025 .while_token = if_node.ast.if_token,
......@@ -1038,7 +1038,7 @@ fn renderIf(gpa: *Allocator, ais: *Ais, tree: Ast, if_node: Ast.full.If, space:
10381038
10391039/// Note that this function is additionally used to render if and for expressions, with
10401040/// respective values set to null.
1041fn renderWhile(gpa: *Allocator, ais: *Ais, tree: Ast, while_node: Ast.full.While, space: Space) Error!void {
1041fn renderWhile(gpa: Allocator, ais: *Ais, tree: Ast, while_node: Ast.full.While, space: Space) Error!void {
10421042 const node_tags = tree.nodes.items(.tag);
10431043 const token_tags = tree.tokens.items(.tag);
10441044
......@@ -1141,7 +1141,7 @@ fn renderWhile(gpa: *Allocator, ais: *Ais, tree: Ast, while_node: Ast.full.While
11411141}
11421142
11431143fn renderContainerField(
1144 gpa: *Allocator,
1144 gpa: Allocator,
11451145 ais: *Ais,
11461146 tree: Ast,
11471147 field: Ast.full.ContainerField,
......@@ -1215,7 +1215,7 @@ fn renderContainerField(
12151215}
12161216
12171217fn renderBuiltinCall(
1218 gpa: *Allocator,
1218 gpa: Allocator,
12191219 ais: *Ais,
12201220 tree: Ast,
12211221 builtin_token: Ast.TokenIndex,
......@@ -1272,7 +1272,7 @@ fn renderBuiltinCall(
12721272 }
12731273}
12741274
1275fn renderFnProto(gpa: *Allocator, ais: *Ais, tree: Ast, fn_proto: Ast.full.FnProto, space: Space) Error!void {
1275fn renderFnProto(gpa: Allocator, ais: *Ais, tree: Ast, fn_proto: Ast.full.FnProto, space: Space) Error!void {
12761276 const token_tags = tree.tokens.items(.tag);
12771277 const token_starts = tree.tokens.items(.start);
12781278
......@@ -1488,7 +1488,7 @@ fn renderFnProto(gpa: *Allocator, ais: *Ais, tree: Ast, fn_proto: Ast.full.FnPro
14881488}
14891489
14901490fn renderSwitchCase(
1491 gpa: *Allocator,
1491 gpa: Allocator,
14921492 ais: *Ais,
14931493 tree: Ast,
14941494 switch_case: Ast.full.SwitchCase,
......@@ -1541,7 +1541,7 @@ fn renderSwitchCase(
15411541}
15421542
15431543fn renderBlock(
1544 gpa: *Allocator,
1544 gpa: Allocator,
15451545 ais: *Ais,
15461546 tree: Ast,
15471547 block_node: Ast.Node.Index,
......@@ -1581,7 +1581,7 @@ fn renderBlock(
15811581}
15821582
15831583fn renderStructInit(
1584 gpa: *Allocator,
1584 gpa: Allocator,
15851585 ais: *Ais,
15861586 tree: Ast,
15871587 struct_node: Ast.Node.Index,
......@@ -1640,7 +1640,7 @@ fn renderStructInit(
16401640}
16411641
16421642fn renderArrayInit(
1643 gpa: *Allocator,
1643 gpa: Allocator,
16441644 ais: *Ais,
16451645 tree: Ast,
16461646 array_init: Ast.full.ArrayInit,
......@@ -1859,7 +1859,7 @@ fn renderArrayInit(
18591859}
18601860
18611861fn renderContainerDecl(
1862 gpa: *Allocator,
1862 gpa: Allocator,
18631863 ais: *Ais,
18641864 tree: Ast,
18651865 container_decl_node: Ast.Node.Index,
......@@ -1956,7 +1956,7 @@ fn renderContainerDecl(
19561956}
19571957
19581958fn renderAsm(
1959 gpa: *Allocator,
1959 gpa: Allocator,
19601960 ais: *Ais,
19611961 tree: Ast,
19621962 asm_node: Ast.full.Asm,
......@@ -2105,7 +2105,7 @@ fn renderAsm(
21052105}
21062106
21072107fn renderCall(
2108 gpa: *Allocator,
2108 gpa: Allocator,
21092109 ais: *Ais,
21102110 tree: Ast,
21112111 call: Ast.full.Call,
......@@ -2180,7 +2180,7 @@ fn renderCall(
21802180
21812181/// Renders the given expression indented, popping the indent before rendering
21822182/// any following line comments
2183fn renderExpressionIndented(gpa: *Allocator, ais: *Ais, tree: Ast, node: Ast.Node.Index, space: Space) Error!void {
2183fn renderExpressionIndented(gpa: Allocator, ais: *Ais, tree: Ast, node: Ast.Node.Index, space: Space) Error!void {
21842184 const token_starts = tree.tokens.items(.start);
21852185 const token_tags = tree.tokens.items(.tag);
21862186
......@@ -2238,7 +2238,7 @@ fn renderExpressionIndented(gpa: *Allocator, ais: *Ais, tree: Ast, node: Ast.Nod
22382238
22392239/// Render an expression, and the comma that follows it, if it is present in the source.
22402240/// If a comma is present, and `space` is `Space.comma`, render only a single comma.
2241fn renderExpressionComma(gpa: *Allocator, ais: *Ais, tree: Ast, node: Ast.Node.Index, space: Space) Error!void {
2241fn renderExpressionComma(gpa: Allocator, ais: *Ais, tree: Ast, node: Ast.Node.Index, space: Space) Error!void {
22422242 const token_tags = tree.tokens.items(.tag);
22432243 const maybe_comma = tree.lastToken(node) + 1;
22442244 if (token_tags[maybe_comma] == .comma and space != .comma) {
lib/std/zig/string_literal.zig+2-2
......@@ -131,7 +131,7 @@ pub fn parseAppend(buf: *std.ArrayList(u8), bytes: []const u8) error{OutOfMemory
131131
132132/// Higher level API. Does not return extra info about parse errors.
133133/// Caller owns returned memory.
134pub fn parseAlloc(allocator: *std.mem.Allocator, bytes: []const u8) ParseError![]u8 {
134pub fn parseAlloc(allocator: std.mem.Allocator, bytes: []const u8) ParseError![]u8 {
135135 var buf = std.ArrayList(u8).init(allocator);
136136 defer buf.deinit();
137137
......@@ -147,7 +147,7 @@ test "parse" {
147147
148148 var fixed_buf_mem: [32]u8 = undefined;
149149 var fixed_buf_alloc = std.heap.FixedBufferAllocator.init(fixed_buf_mem[0..]);
150 var alloc = &fixed_buf_alloc.allocator;
150 var alloc = fixed_buf_alloc.allocator();
151151
152152 try expect(eql(u8, "foo", try parseAlloc(alloc, "\"foo\"")));
153153 try expect(eql(u8, "foo", try parseAlloc(alloc, "\"f\x6f\x6f\"")));
lib/std/zig/system.zig+3-3
......@@ -21,7 +21,7 @@ pub const NativePaths = struct {
2121 rpaths: ArrayList([:0]u8),
2222 warnings: ArrayList([:0]u8),
2323
24 pub fn detect(allocator: *Allocator, native_info: NativeTargetInfo) !NativePaths {
24 pub fn detect(allocator: Allocator, native_info: NativeTargetInfo) !NativePaths {
2525 const native_target = native_info.target;
2626
2727 var self: NativePaths = .{
......@@ -237,7 +237,7 @@ pub const NativeTargetInfo = struct {
237237 /// Any resources this function allocates are released before returning, and so there is no
238238 /// deinitialization method.
239239 /// TODO Remove the Allocator requirement from this function.
240 pub fn detect(allocator: *Allocator, cross_target: CrossTarget) DetectError!NativeTargetInfo {
240 pub fn detect(allocator: Allocator, cross_target: CrossTarget) DetectError!NativeTargetInfo {
241241 var os = cross_target.getOsTag().defaultVersionRange(cross_target.getCpuArch());
242242 if (cross_target.os_tag == null) {
243243 switch (builtin.target.os.tag) {
......@@ -441,7 +441,7 @@ pub const NativeTargetInfo = struct {
441441 /// we fall back to the defaults.
442442 /// TODO Remove the Allocator requirement from this function.
443443 fn detectAbiAndDynamicLinker(
444 allocator: *Allocator,
444 allocator: Allocator,
445445 cpu: Target.Cpu,
446446 os: Target.Os,
447447 cross_target: CrossTarget,
lib/std/zig/system/darwin.zig+3-3
......@@ -11,7 +11,7 @@ pub const macos = @import("darwin/macos.zig");
1111/// Therefore, we resort to the same tool used by Homebrew, namely, invoking `xcode-select --print-path`
1212/// and checking if the status is nonzero or the returned string in nonempty.
1313/// https://github.com/Homebrew/brew/blob/e119bdc571dcb000305411bc1e26678b132afb98/Library/Homebrew/brew.sh#L630
14pub fn isDarwinSDKInstalled(allocator: *Allocator) bool {
14pub fn isDarwinSDKInstalled(allocator: Allocator) bool {
1515 const argv = &[_][]const u8{ "/usr/bin/xcode-select", "--print-path" };
1616 const result = std.ChildProcess.exec(.{ .allocator = allocator, .argv = argv }) catch return false;
1717 defer {
......@@ -29,7 +29,7 @@ pub fn isDarwinSDKInstalled(allocator: *Allocator) bool {
2929/// Calls `xcrun --sdk <target_sdk> --show-sdk-path` which fetches the path to the SDK sysroot (if any).
3030/// Subsequently calls `xcrun --sdk <target_sdk> --show-sdk-version` which fetches version of the SDK.
3131/// The caller needs to deinit the resulting struct.
32pub fn getDarwinSDK(allocator: *Allocator, target: Target) ?DarwinSDK {
32pub fn getDarwinSDK(allocator: Allocator, target: Target) ?DarwinSDK {
3333 const is_simulator_abi = target.abi == .simulator;
3434 const sdk = switch (target.os.tag) {
3535 .macos => "macosx",
......@@ -82,7 +82,7 @@ pub const DarwinSDK = struct {
8282 path: []const u8,
8383 version: Version,
8484
85 pub fn deinit(self: DarwinSDK, allocator: *Allocator) void {
85 pub fn deinit(self: DarwinSDK, allocator: Allocator) void {
8686 allocator.free(self.path);
8787 }
8888};
src/Air.zig+1-1
......@@ -841,7 +841,7 @@ pub fn extraData(air: Air, comptime T: type, index: usize) struct { data: T, end
841841 };
842842}
843843
844pub fn deinit(air: *Air, gpa: *std.mem.Allocator) void {
844pub fn deinit(air: *Air, gpa: std.mem.Allocator) void {
845845 air.instructions.deinit(gpa);
846846 gpa.free(air.extra);
847847 gpa.free(air.values);
src/AstGen.zig+17-16
......@@ -16,7 +16,7 @@ const indexToRef = Zir.indexToRef;
1616const trace = @import("tracy.zig").trace;
1717const BuiltinFn = @import("BuiltinFn.zig");
1818
19gpa: *Allocator,
19gpa: Allocator,
2020tree: *const Ast,
2121instructions: std.MultiArrayList(Zir.Inst) = .{},
2222extra: ArrayListUnmanaged(u32) = .{},
......@@ -33,7 +33,7 @@ source_line: u32 = 0,
3333source_column: u32 = 0,
3434/// Used for temporary allocations; freed after AstGen is complete.
3535/// The resulting ZIR code has no references to anything in this arena.
36arena: *Allocator,
36arena: Allocator,
3737string_table: std.HashMapUnmanaged(u32, void, StringIndexContext, std.hash_map.default_max_load_percentage) = .{},
3838compile_errors: ArrayListUnmanaged(Zir.Inst.CompileErrors.Item) = .{},
3939/// The topmost block of the current function.
......@@ -92,13 +92,13 @@ fn appendRefsAssumeCapacity(astgen: *AstGen, refs: []const Zir.Inst.Ref) void {
9292 astgen.extra.appendSliceAssumeCapacity(coerced);
9393}
9494
95pub fn generate(gpa: *Allocator, tree: Ast) Allocator.Error!Zir {
95pub fn generate(gpa: Allocator, tree: Ast) Allocator.Error!Zir {
9696 var arena = std.heap.ArenaAllocator.init(gpa);
9797 defer arena.deinit();
9898
9999 var astgen: AstGen = .{
100100 .gpa = gpa,
101 .arena = &arena.allocator,
101 .arena = arena.allocator(),
102102 .tree = &tree,
103103 };
104104 defer astgen.deinit(gpa);
......@@ -196,7 +196,7 @@ pub fn generate(gpa: *Allocator, tree: Ast) Allocator.Error!Zir {
196196 };
197197}
198198
199pub fn deinit(astgen: *AstGen, gpa: *Allocator) void {
199pub fn deinit(astgen: *AstGen, gpa: Allocator) void {
200200 astgen.instructions.deinit(gpa);
201201 astgen.extra.deinit(gpa);
202202 astgen.string_table.deinit(gpa);
......@@ -1939,6 +1939,7 @@ fn blockExprStmts(gz: *GenZir, parent_scope: *Scope, statements: []const Ast.Nod
19391939
19401940 var block_arena = std.heap.ArenaAllocator.init(gz.astgen.gpa);
19411941 defer block_arena.deinit();
1942 const block_arena_allocator = block_arena.allocator();
19421943
19431944 var noreturn_src_node: Ast.Node.Index = 0;
19441945 var scope = parent_scope;
......@@ -1959,13 +1960,13 @@ fn blockExprStmts(gz: *GenZir, parent_scope: *Scope, statements: []const Ast.Nod
19591960 }
19601961 switch (node_tags[statement]) {
19611962 // zig fmt: off
1962 .global_var_decl => scope = try varDecl(gz, scope, statement, &block_arena.allocator, tree.globalVarDecl(statement)),
1963 .local_var_decl => scope = try varDecl(gz, scope, statement, &block_arena.allocator, tree.localVarDecl(statement)),
1964 .simple_var_decl => scope = try varDecl(gz, scope, statement, &block_arena.allocator, tree.simpleVarDecl(statement)),
1965 .aligned_var_decl => scope = try varDecl(gz, scope, statement, &block_arena.allocator, tree.alignedVarDecl(statement)),
1963 .global_var_decl => scope = try varDecl(gz, scope, statement, block_arena_allocator, tree.globalVarDecl(statement)),
1964 .local_var_decl => scope = try varDecl(gz, scope, statement, block_arena_allocator, tree.localVarDecl(statement)),
1965 .simple_var_decl => scope = try varDecl(gz, scope, statement, block_arena_allocator, tree.simpleVarDecl(statement)),
1966 .aligned_var_decl => scope = try varDecl(gz, scope, statement, block_arena_allocator, tree.alignedVarDecl(statement)),
19661967
1967 .@"defer" => scope = try makeDeferScope(gz.astgen, scope, statement, &block_arena.allocator, .defer_normal),
1968 .@"errdefer" => scope = try makeDeferScope(gz.astgen, scope, statement, &block_arena.allocator, .defer_error),
1968 .@"defer" => scope = try makeDeferScope(gz.astgen, scope, statement, block_arena_allocator, .defer_normal),
1969 .@"errdefer" => scope = try makeDeferScope(gz.astgen, scope, statement, block_arena_allocator, .defer_error),
19691970
19701971 .assign => try assign(gz, scope, statement),
19711972
......@@ -2460,7 +2461,7 @@ fn makeDeferScope(
24602461 astgen: *AstGen,
24612462 scope: *Scope,
24622463 node: Ast.Node.Index,
2463 block_arena: *Allocator,
2464 block_arena: Allocator,
24642465 scope_tag: Scope.Tag,
24652466) InnerError!*Scope {
24662467 const tree = astgen.tree;
......@@ -2486,7 +2487,7 @@ fn varDecl(
24862487 gz: *GenZir,
24872488 scope: *Scope,
24882489 node: Ast.Node.Index,
2489 block_arena: *Allocator,
2490 block_arena: Allocator,
24902491 var_decl: Ast.full.VarDecl,
24912492) InnerError!*Scope {
24922493 try emitDbgNode(gz, node);
......@@ -3030,7 +3031,7 @@ const WipMembers = struct {
30303031 /// (4 for src_hash + line + name + value + align + link_section + address_space)
30313032 const max_decl_size = 10;
30323033
3033 pub fn init(gpa: *Allocator, payload: *ArrayListUnmanaged(u32), decl_count: u32, field_count: u32, comptime bits_per_field: u32, comptime max_field_size: u32) Allocator.Error!Self {
3034 pub fn init(gpa: Allocator, payload: *ArrayListUnmanaged(u32), decl_count: u32, field_count: u32, comptime bits_per_field: u32, comptime max_field_size: u32) Allocator.Error!Self {
30343035 const payload_top = @intCast(u32, payload.items.len);
30353036 const decls_start = payload_top + (decl_count + decls_per_u32 - 1) / decls_per_u32;
30363037 const field_bits_start = decls_start + decl_count * max_decl_size;
......@@ -6178,7 +6179,7 @@ fn tunnelThroughClosure(
61786179 ns: ?*Scope.Namespace,
61796180 value: Zir.Inst.Ref,
61806181 token: Ast.TokenIndex,
6181 gpa: *Allocator,
6182 gpa: Allocator,
61826183) !Zir.Inst.Ref {
61836184 // For trivial values, we don't need a tunnel.
61846185 // Just return the ref.
......@@ -8852,7 +8853,7 @@ const Scope = struct {
88528853 /// ref of the capture for decls in this namespace
88538854 captures: std.AutoArrayHashMapUnmanaged(Zir.Inst.Index, Zir.Inst.Index) = .{},
88548855
8855 pub fn deinit(self: *Namespace, gpa: *Allocator) void {
8856 pub fn deinit(self: *Namespace, gpa: Allocator) void {
88568857 self.decls.deinit(gpa);
88578858 self.captures.deinit(gpa);
88588859 self.* = undefined;
src/Cache.zig+2-2
......@@ -1,4 +1,4 @@
1gpa: *Allocator,
1gpa: Allocator,
22manifest_dir: fs.Dir,
33hash: HashHelper = .{},
44
......@@ -48,7 +48,7 @@ pub const File = struct {
4848 bin_digest: BinDigest,
4949 contents: ?[]const u8,
5050
51 pub fn deinit(self: *File, allocator: *Allocator) void {
51 pub fn deinit(self: *File, allocator: Allocator) void {
5252 if (self.path) |owned_slice| {
5353 allocator.free(owned_slice);
5454 self.path = null;
src/Compilation.zig+49-46
......@@ -36,7 +36,7 @@ const libtsan = @import("libtsan.zig");
3636const Zir = @import("Zir.zig");
3737
3838/// General-purpose allocator. Used for both temporary and long-term storage.
39gpa: *Allocator,
39gpa: Allocator,
4040/// Arena-allocated memory used during initialization. Should be untouched until deinit.
4141arena_state: std.heap.ArenaAllocator.State,
4242bin_file: *link.File,
......@@ -164,7 +164,7 @@ pub const CRTFile = struct {
164164 lock: Cache.Lock,
165165 full_object_path: []const u8,
166166
167 fn deinit(self: *CRTFile, gpa: *Allocator) void {
167 fn deinit(self: *CRTFile, gpa: Allocator) void {
168168 self.lock.release();
169169 gpa.free(self.full_object_path);
170170 self.* = undefined;
......@@ -253,14 +253,14 @@ pub const CObject = struct {
253253 line: u32,
254254 column: u32,
255255
256 pub fn destroy(em: *ErrorMsg, gpa: *Allocator) void {
256 pub fn destroy(em: *ErrorMsg, gpa: Allocator) void {
257257 gpa.free(em.msg);
258258 gpa.destroy(em);
259259 }
260260 };
261261
262262 /// Returns if there was failure.
263 pub fn clearStatus(self: *CObject, gpa: *Allocator) bool {
263 pub fn clearStatus(self: *CObject, gpa: Allocator) bool {
264264 switch (self.status) {
265265 .new => return false,
266266 .failure, .failure_retryable => {
......@@ -276,7 +276,7 @@ pub const CObject = struct {
276276 }
277277 }
278278
279 pub fn destroy(self: *CObject, gpa: *Allocator) void {
279 pub fn destroy(self: *CObject, gpa: Allocator) void {
280280 _ = self.clearStatus(gpa);
281281 gpa.destroy(self);
282282 }
......@@ -305,7 +305,7 @@ pub const MiscError = struct {
305305 msg: []u8,
306306 children: ?AllErrors = null,
307307
308 pub fn deinit(misc_err: *MiscError, gpa: *Allocator) void {
308 pub fn deinit(misc_err: *MiscError, gpa: Allocator) void {
309309 gpa.free(misc_err.msg);
310310 if (misc_err.children) |*children| {
311311 children.deinit(gpa);
......@@ -402,7 +402,7 @@ pub const AllErrors = struct {
402402 }
403403 };
404404
405 pub fn deinit(self: *AllErrors, gpa: *Allocator) void {
405 pub fn deinit(self: *AllErrors, gpa: Allocator) void {
406406 self.arena.promote(gpa).deinit();
407407 }
408408
......@@ -412,28 +412,29 @@ pub const AllErrors = struct {
412412 errors: *std.ArrayList(Message),
413413 module_err_msg: Module.ErrorMsg,
414414 ) !void {
415 const notes = try arena.allocator.alloc(Message, module_err_msg.notes.len);
415 const allocator = arena.allocator();
416 const notes = try allocator.alloc(Message, module_err_msg.notes.len);
416417 for (notes) |*note, i| {
417418 const module_note = module_err_msg.notes[i];
418419 const source = try module_note.src_loc.file_scope.getSource(module.gpa);
419420 const byte_offset = try module_note.src_loc.byteOffset(module.gpa);
420421 const loc = std.zig.findLineColumn(source, byte_offset);
421 const file_path = try module_note.src_loc.file_scope.fullPath(&arena.allocator);
422 const file_path = try module_note.src_loc.file_scope.fullPath(allocator);
422423 note.* = .{
423424 .src = .{
424425 .src_path = file_path,
425 .msg = try arena.allocator.dupe(u8, module_note.msg),
426 .msg = try allocator.dupe(u8, module_note.msg),
426427 .byte_offset = byte_offset,
427428 .line = @intCast(u32, loc.line),
428429 .column = @intCast(u32, loc.column),
429 .source_line = try arena.allocator.dupe(u8, loc.source_line),
430 .source_line = try allocator.dupe(u8, loc.source_line),
430431 },
431432 };
432433 }
433434 if (module_err_msg.src_loc.lazy == .entire_file) {
434435 try errors.append(.{
435436 .plain = .{
436 .msg = try arena.allocator.dupe(u8, module_err_msg.msg),
437 .msg = try allocator.dupe(u8, module_err_msg.msg),
437438 },
438439 });
439440 return;
......@@ -441,22 +442,22 @@ pub const AllErrors = struct {
441442 const source = try module_err_msg.src_loc.file_scope.getSource(module.gpa);
442443 const byte_offset = try module_err_msg.src_loc.byteOffset(module.gpa);
443444 const loc = std.zig.findLineColumn(source, byte_offset);
444 const file_path = try module_err_msg.src_loc.file_scope.fullPath(&arena.allocator);
445 const file_path = try module_err_msg.src_loc.file_scope.fullPath(allocator);
445446 try errors.append(.{
446447 .src = .{
447448 .src_path = file_path,
448 .msg = try arena.allocator.dupe(u8, module_err_msg.msg),
449 .msg = try allocator.dupe(u8, module_err_msg.msg),
449450 .byte_offset = byte_offset,
450451 .line = @intCast(u32, loc.line),
451452 .column = @intCast(u32, loc.column),
452453 .notes = notes,
453 .source_line = try arena.allocator.dupe(u8, loc.source_line),
454 .source_line = try allocator.dupe(u8, loc.source_line),
454455 },
455456 });
456457 }
457458
458459 pub fn addZir(
459 arena: *Allocator,
460 arena: Allocator,
460461 errors: *std.ArrayList(Message),
461462 file: *Module.File,
462463 ) !void {
......@@ -548,18 +549,19 @@ pub const AllErrors = struct {
548549 msg: []const u8,
549550 optional_children: ?AllErrors,
550551 ) !void {
551 const duped_msg = try arena.allocator.dupe(u8, msg);
552 const allocator = arena.allocator();
553 const duped_msg = try allocator.dupe(u8, msg);
552554 if (optional_children) |*children| {
553555 try errors.append(.{ .plain = .{
554556 .msg = duped_msg,
555 .notes = try dupeList(children.list, &arena.allocator),
557 .notes = try dupeList(children.list, allocator),
556558 } });
557559 } else {
558560 try errors.append(.{ .plain = .{ .msg = duped_msg } });
559561 }
560562 }
561563
562 fn dupeList(list: []const Message, arena: *Allocator) Allocator.Error![]Message {
564 fn dupeList(list: []const Message, arena: Allocator) Allocator.Error![]Message {
563565 const duped_list = try arena.alloc(Message, list.len);
564566 for (list) |item, i| {
565567 duped_list[i] = switch (item) {
......@@ -589,7 +591,7 @@ pub const Directory = struct {
589591 path: ?[]const u8,
590592 handle: std.fs.Dir,
591593
592 pub fn join(self: Directory, allocator: *Allocator, paths: []const []const u8) ![]u8 {
594 pub fn join(self: Directory, allocator: Allocator, paths: []const []const u8) ![]u8 {
593595 if (self.path) |p| {
594596 // TODO clean way to do this with only 1 allocation
595597 const part2 = try std.fs.path.join(allocator, paths);
......@@ -600,7 +602,7 @@ pub const Directory = struct {
600602 }
601603 }
602604
603 pub fn joinZ(self: Directory, allocator: *Allocator, paths: []const []const u8) ![:0]u8 {
605 pub fn joinZ(self: Directory, allocator: Allocator, paths: []const []const u8) ![:0]u8 {
604606 if (self.path) |p| {
605607 // TODO clean way to do this with only 1 allocation
606608 const part2 = try std.fs.path.join(allocator, paths);
......@@ -786,7 +788,7 @@ fn addPackageTableToCacheHash(
786788 seen_table: *std.AutoHashMap(*Package, void),
787789 hash_type: union(enum) { path_bytes, files: *Cache.Manifest },
788790) (error{OutOfMemory} || std.os.GetCwdError)!void {
789 const allocator = &arena.allocator;
791 const allocator = arena.allocator();
790792
791793 const packages = try allocator.alloc(Package.Table.KV, pkg_table.count());
792794 {
......@@ -829,7 +831,7 @@ fn addPackageTableToCacheHash(
829831 }
830832}
831833
832pub fn create(gpa: *Allocator, options: InitOptions) !*Compilation {
834pub fn create(gpa: Allocator, options: InitOptions) !*Compilation {
833835 const is_dyn_lib = switch (options.output_mode) {
834836 .Obj, .Exe => false,
835837 .Lib => (options.link_mode orelse .Static) == .Dynamic,
......@@ -850,7 +852,7 @@ pub fn create(gpa: *Allocator, options: InitOptions) !*Compilation {
850852 // initialization and then is freed in deinit().
851853 var arena_allocator = std.heap.ArenaAllocator.init(gpa);
852854 errdefer arena_allocator.deinit();
853 const arena = &arena_allocator.allocator;
855 const arena = arena_allocator.allocator();
854856
855857 // We put the `Compilation` itself in the arena. Freeing the arena will free the module.
856858 // It's initialized later after we prepare the initialization options.
......@@ -1212,7 +1214,7 @@ pub fn create(gpa: *Allocator, options: InitOptions) !*Compilation {
12121214 {
12131215 var local_arena = std.heap.ArenaAllocator.init(gpa);
12141216 defer local_arena.deinit();
1215 var seen_table = std.AutoHashMap(*Package, void).init(&local_arena.allocator);
1217 var seen_table = std.AutoHashMap(*Package, void).init(local_arena.allocator());
12161218 try addPackageTableToCacheHash(&hash, &local_arena, main_pkg.table, &seen_table, .path_bytes);
12171219 }
12181220 hash.add(valgrind);
......@@ -2015,6 +2017,7 @@ pub fn totalErrorCount(self: *Compilation) usize {
20152017pub fn getAllErrorsAlloc(self: *Compilation) !AllErrors {
20162018 var arena = std.heap.ArenaAllocator.init(self.gpa);
20172019 errdefer arena.deinit();
2020 const arena_allocator = arena.allocator();
20182021
20192022 var errors = std.ArrayList(AllErrors.Message).init(self.gpa);
20202023 defer errors.deinit();
......@@ -2028,8 +2031,8 @@ pub fn getAllErrorsAlloc(self: *Compilation) !AllErrors {
20282031 // C error reporting bubbling up.
20292032 try errors.append(.{
20302033 .src = .{
2031 .src_path = try arena.allocator.dupe(u8, c_object.src.src_path),
2032 .msg = try std.fmt.allocPrint(&arena.allocator, "unable to build C object: {s}", .{
2034 .src_path = try arena_allocator.dupe(u8, c_object.src.src_path),
2035 .msg = try std.fmt.allocPrint(arena_allocator, "unable to build C object: {s}", .{
20332036 err_msg.msg,
20342037 }),
20352038 .byte_offset = 0,
......@@ -2054,7 +2057,7 @@ pub fn getAllErrorsAlloc(self: *Compilation) !AllErrors {
20542057 // must have completed successfully.
20552058 const tree = try entry.key_ptr.*.getTree(module.gpa);
20562059 assert(tree.errors.len == 0);
2057 try AllErrors.addZir(&arena.allocator, &errors, entry.key_ptr.*);
2060 try AllErrors.addZir(arena_allocator, &errors, entry.key_ptr.*);
20582061 }
20592062 }
20602063 }
......@@ -2093,7 +2096,7 @@ pub fn getAllErrorsAlloc(self: *Compilation) !AllErrors {
20932096 if (errors.items.len == 0 and self.link_error_flags.no_entry_point_found) {
20942097 try errors.append(.{
20952098 .plain = .{
2096 .msg = try std.fmt.allocPrint(&arena.allocator, "no entry point found", .{}),
2099 .msg = try std.fmt.allocPrint(arena_allocator, "no entry point found", .{}),
20972100 },
20982101 });
20992102 }
......@@ -2125,7 +2128,7 @@ pub fn getAllErrorsAlloc(self: *Compilation) !AllErrors {
21252128 assert(errors.items.len == self.totalErrorCount());
21262129
21272130 return AllErrors{
2128 .list = try arena.allocator.dupe(AllErrors.Message, errors.items),
2131 .list = try arena_allocator.dupe(AllErrors.Message, errors.items),
21292132 .arena = arena.state,
21302133 };
21312134}
......@@ -2296,7 +2299,7 @@ fn processOneJob(comp: *Compilation, job: Job, main_progress_node: *std.Progress
22962299
22972300 var tmp_arena = std.heap.ArenaAllocator.init(gpa);
22982301 defer tmp_arena.deinit();
2299 const sema_arena = &tmp_arena.allocator;
2302 const sema_arena = tmp_arena.allocator();
23002303
23012304 const sema_frame = tracy.namedFrame("sema");
23022305 var sema_frame_ended = false;
......@@ -2391,7 +2394,7 @@ fn processOneJob(comp: *Compilation, job: Job, main_progress_node: *std.Progress
23912394 .decl = decl,
23922395 .fwd_decl = fwd_decl.toManaged(gpa),
23932396 .typedefs = c_codegen.TypedefMap.init(gpa),
2394 .typedefs_arena = &typedefs_arena.allocator,
2397 .typedefs_arena = typedefs_arena.allocator(),
23952398 };
23962399 defer dg.fwd_decl.deinit();
23972400 defer dg.typedefs.deinit();
......@@ -2845,7 +2848,7 @@ pub fn cImport(comp: *Compilation, c_src: []const u8) !CImportResult {
28452848 const digest = if (!actual_hit) digest: {
28462849 var arena_allocator = std.heap.ArenaAllocator.init(comp.gpa);
28472850 defer arena_allocator.deinit();
2848 const arena = &arena_allocator.allocator;
2851 const arena = arena_allocator.allocator();
28492852
28502853 const tmp_digest = man.hash.peek();
28512854 const tmp_dir_sub_path = try std.fs.path.join(arena, &[_][]const u8{ "o", &tmp_digest });
......@@ -3100,7 +3103,7 @@ fn updateCObject(comp: *Compilation, c_object: *CObject, c_obj_prog_node: *std.P
31003103
31013104 var arena_allocator = std.heap.ArenaAllocator.init(comp.gpa);
31023105 defer arena_allocator.deinit();
3103 const arena = &arena_allocator.allocator;
3106 const arena = arena_allocator.allocator();
31043107
31053108 const c_source_basename = std.fs.path.basename(c_object.src.src_path);
31063109
......@@ -3267,7 +3270,7 @@ fn updateCObject(comp: *Compilation, c_object: *CObject, c_obj_prog_node: *std.P
32673270 };
32683271}
32693272
3270pub fn tmpFilePath(comp: *Compilation, arena: *Allocator, suffix: []const u8) error{OutOfMemory}![]const u8 {
3273pub fn tmpFilePath(comp: *Compilation, arena: Allocator, suffix: []const u8) error{OutOfMemory}![]const u8 {
32713274 const s = std.fs.path.sep_str;
32723275 const rand_int = std.crypto.random.int(u64);
32733276 if (comp.local_cache_directory.path) |p| {
......@@ -3279,7 +3282,7 @@ pub fn tmpFilePath(comp: *Compilation, arena: *Allocator, suffix: []const u8) er
32793282
32803283pub fn addTranslateCCArgs(
32813284 comp: *Compilation,
3282 arena: *Allocator,
3285 arena: Allocator,
32833286 argv: *std.ArrayList([]const u8),
32843287 ext: FileExt,
32853288 out_dep_path: ?[]const u8,
......@@ -3293,7 +3296,7 @@ pub fn addTranslateCCArgs(
32933296/// Add common C compiler args between translate-c and C object compilation.
32943297pub fn addCCArgs(
32953298 comp: *const Compilation,
3296 arena: *Allocator,
3299 arena: Allocator,
32973300 argv: *std.ArrayList([]const u8),
32983301 ext: FileExt,
32993302 out_dep_path: ?[]const u8,
......@@ -3780,7 +3783,7 @@ const LibCDirs = struct {
37803783 libc_installation: ?*const LibCInstallation,
37813784};
37823785
3783fn getZigShippedLibCIncludeDirsDarwin(arena: *Allocator, zig_lib_dir: []const u8, target: Target) !LibCDirs {
3786fn getZigShippedLibCIncludeDirsDarwin(arena: Allocator, zig_lib_dir: []const u8, target: Target) !LibCDirs {
37843787 const arch_name = @tagName(target.cpu.arch);
37853788 const os_name = try std.fmt.allocPrint(arena, "{s}.{d}", .{
37863789 @tagName(target.os.tag),
......@@ -3812,7 +3815,7 @@ fn getZigShippedLibCIncludeDirsDarwin(arena: *Allocator, zig_lib_dir: []const u8
38123815}
38133816
38143817fn detectLibCIncludeDirs(
3815 arena: *Allocator,
3818 arena: Allocator,
38163819 zig_lib_dir: []const u8,
38173820 target: Target,
38183821 is_native_abi: bool,
......@@ -3937,7 +3940,7 @@ fn detectLibCIncludeDirs(
39373940 };
39383941}
39393942
3940fn detectLibCFromLibCInstallation(arena: *Allocator, target: Target, lci: *const LibCInstallation) !LibCDirs {
3943fn detectLibCFromLibCInstallation(arena: Allocator, target: Target, lci: *const LibCInstallation) !LibCDirs {
39413944 var list = try std.ArrayList([]const u8).initCapacity(arena, 4);
39423945
39433946 list.appendAssumeCapacity(lci.include_dir.?);
......@@ -3969,7 +3972,7 @@ fn detectLibCFromLibCInstallation(arena: *Allocator, target: Target, lci: *const
39693972 };
39703973}
39713974
3972pub fn get_libc_crt_file(comp: *Compilation, arena: *Allocator, basename: []const u8) ![]const u8 {
3975pub fn get_libc_crt_file(comp: *Compilation, arena: Allocator, basename: []const u8) ![]const u8 {
39733976 if (comp.wantBuildGLibCFromSource() or
39743977 comp.wantBuildMuslFromSource() or
39753978 comp.wantBuildMinGWFromSource() or
......@@ -4070,7 +4073,7 @@ pub fn dump_argv(argv: []const []const u8) void {
40704073 std.debug.print("{s}\n", .{argv[argv.len - 1]});
40714074}
40724075
4073pub fn generateBuiltinZigSource(comp: *Compilation, allocator: *Allocator) Allocator.Error![]u8 {
4076pub fn generateBuiltinZigSource(comp: *Compilation, allocator: Allocator) Allocator.Error![]u8 {
40744077 const t = trace(@src());
40754078 defer t.end();
40764079
......@@ -4421,7 +4424,7 @@ fn updateStage1Module(comp: *Compilation, main_progress_node: *std.Progress.Node
44214424
44224425 var arena_allocator = std.heap.ArenaAllocator.init(comp.gpa);
44234426 defer arena_allocator.deinit();
4424 const arena = &arena_allocator.allocator;
4427 const arena = arena_allocator.allocator();
44254428
44264429 // Here we use the legacy stage1 C++ compiler to compile Zig code.
44274430 const mod = comp.bin_file.options.module.?;
......@@ -4458,7 +4461,7 @@ fn updateStage1Module(comp: *Compilation, main_progress_node: *std.Progress.Node
44584461
44594462 _ = try man.addFile(main_zig_file, null);
44604463 {
4461 var seen_table = std.AutoHashMap(*Package, void).init(&arena_allocator.allocator);
4464 var seen_table = std.AutoHashMap(*Package, void).init(arena_allocator.allocator());
44624465 try addPackageTableToCacheHash(&man.hash, &arena_allocator, mod.main_pkg.table, &seen_table, .{ .files = &man });
44634466 }
44644467 man.hash.add(comp.bin_file.options.valgrind);
......@@ -4721,14 +4724,14 @@ fn updateStage1Module(comp: *Compilation, main_progress_node: *std.Progress.Node
47214724 comp.stage1_lock = man.toOwnedLock();
47224725}
47234726
4724fn stage1LocPath(arena: *Allocator, opt_loc: ?EmitLoc, cache_directory: Directory) ![]const u8 {
4727fn stage1LocPath(arena: Allocator, opt_loc: ?EmitLoc, cache_directory: Directory) ![]const u8 {
47254728 const loc = opt_loc orelse return "";
47264729 const directory = loc.directory orelse cache_directory;
47274730 return directory.join(arena, &[_][]const u8{loc.basename});
47284731}
47294732
47304733fn createStage1Pkg(
4731 arena: *Allocator,
4734 arena: Allocator,
47324735 name: []const u8,
47334736 pkg: *Package,
47344737 parent_pkg: ?*stage1.Pkg,
src/DepTokenizer.zig+1-1
......@@ -878,7 +878,7 @@ test "error prereq - continuation expecting end-of-line" {
878878// - tokenize input, emit textual representation, and compare to expect
879879fn depTokenizer(input: []const u8, expect: []const u8) !void {
880880 var arena_allocator = std.heap.ArenaAllocator.init(std.testing.allocator);
881 const arena = &arena_allocator.allocator;
881 const arena = arena_allocator.allocator();
882882 defer arena_allocator.deinit();
883883
884884 var it: Tokenizer = .{ .bytes = input };
src/Liveness.zig+3-3
......@@ -51,7 +51,7 @@ pub const SwitchBr = struct {
5151 else_death_count: u32,
5252};
5353
54pub fn analyze(gpa: *Allocator, air: Air, zir: Zir) Allocator.Error!Liveness {
54pub fn analyze(gpa: Allocator, air: Air, zir: Zir) Allocator.Error!Liveness {
5555 const tracy = trace(@src());
5656 defer tracy.end();
5757
......@@ -136,7 +136,7 @@ pub fn getCondBr(l: Liveness, inst: Air.Inst.Index) CondBrSlices {
136136 };
137137}
138138
139pub fn deinit(l: *Liveness, gpa: *Allocator) void {
139pub fn deinit(l: *Liveness, gpa: Allocator) void {
140140 gpa.free(l.tomb_bits);
141141 gpa.free(l.extra);
142142 l.special.deinit(gpa);
......@@ -150,7 +150,7 @@ pub const OperandInt = std.math.Log2Int(Bpi);
150150
151151/// In-progress data; on successful analysis converted into `Liveness`.
152152const Analysis = struct {
153 gpa: *Allocator,
153 gpa: Allocator,
154154 air: Air,
155155 table: std.AutoHashMapUnmanaged(Air.Inst.Index, void),
156156 tomb_bits: []usize,
src/Module.zig+66-61
......@@ -30,7 +30,7 @@ const target_util = @import("target.zig");
3030const build_options = @import("build_options");
3131
3232/// General-purpose allocator. Used for both temporary and long-term storage.
33gpa: *Allocator,
33gpa: Allocator,
3434comp: *Compilation,
3535
3636/// Where our incremental compilation metadata serialization will go.
......@@ -299,10 +299,10 @@ pub const CaptureScope = struct {
299299pub const WipCaptureScope = struct {
300300 scope: *CaptureScope,
301301 finalized: bool,
302 gpa: *Allocator,
303 perm_arena: *Allocator,
302 gpa: Allocator,
303 perm_arena: Allocator,
304304
305 pub fn init(gpa: *Allocator, perm_arena: *Allocator, parent: ?*CaptureScope) !@This() {
305 pub fn init(gpa: Allocator, perm_arena: Allocator, parent: ?*CaptureScope) !@This() {
306306 const scope = try perm_arena.create(CaptureScope);
307307 scope.* = .{ .parent = parent };
308308 return @This(){
......@@ -469,7 +469,7 @@ pub const Decl = struct {
469469
470470 pub const DepsTable = std.AutoArrayHashMapUnmanaged(*Decl, void);
471471
472 pub fn clearName(decl: *Decl, gpa: *Allocator) void {
472 pub fn clearName(decl: *Decl, gpa: Allocator) void {
473473 gpa.free(mem.sliceTo(decl.name, 0));
474474 decl.name = undefined;
475475 }
......@@ -499,7 +499,7 @@ pub const Decl = struct {
499499 }
500500 }
501501
502 pub fn clearValues(decl: *Decl, gpa: *Allocator) void {
502 pub fn clearValues(decl: *Decl, gpa: Allocator) void {
503503 if (decl.getFunction()) |func| {
504504 func.deinit(gpa);
505505 gpa.destroy(func);
......@@ -517,7 +517,7 @@ pub const Decl = struct {
517517
518518 pub fn finalizeNewArena(decl: *Decl, arena: *std.heap.ArenaAllocator) !void {
519519 assert(decl.value_arena == null);
520 const arena_state = try arena.allocator.create(std.heap.ArenaAllocator.State);
520 const arena_state = try arena.allocator().create(std.heap.ArenaAllocator.State);
521521 arena_state.* = arena.state;
522522 decl.value_arena = arena_state;
523523 }
......@@ -636,7 +636,7 @@ pub const Decl = struct {
636636 return decl.src_namespace.renderFullyQualifiedDebugName(unqualified_name, writer);
637637 }
638638
639 pub fn getFullyQualifiedName(decl: Decl, gpa: *Allocator) ![:0]u8 {
639 pub fn getFullyQualifiedName(decl: Decl, gpa: Allocator) ![:0]u8 {
640640 var buffer = std.ArrayList(u8).init(gpa);
641641 defer buffer.deinit();
642642 try decl.renderFullyQualifiedName(buffer.writer());
......@@ -855,7 +855,7 @@ pub const Struct = struct {
855855 is_comptime: bool,
856856 };
857857
858 pub fn getFullyQualifiedName(s: *Struct, gpa: *Allocator) ![:0]u8 {
858 pub fn getFullyQualifiedName(s: *Struct, gpa: Allocator) ![:0]u8 {
859859 return s.owner_decl.getFullyQualifiedName(gpa);
860860 }
861861
......@@ -999,7 +999,7 @@ pub const Union = struct {
999999
10001000 pub const Fields = std.StringArrayHashMapUnmanaged(Field);
10011001
1002 pub fn getFullyQualifiedName(s: *Union, gpa: *Allocator) ![:0]u8 {
1002 pub fn getFullyQualifiedName(s: *Union, gpa: Allocator) ![:0]u8 {
10031003 return s.owner_decl.getFullyQualifiedName(gpa);
10041004 }
10051005
......@@ -1178,7 +1178,7 @@ pub const Opaque = struct {
11781178 };
11791179 }
11801180
1181 pub fn getFullyQualifiedName(s: *Opaque, gpa: *Allocator) ![:0]u8 {
1181 pub fn getFullyQualifiedName(s: *Opaque, gpa: Allocator) ![:0]u8 {
11821182 return s.owner_decl.getFullyQualifiedName(gpa);
11831183 }
11841184};
......@@ -1225,7 +1225,7 @@ pub const Fn = struct {
12251225 success,
12261226 };
12271227
1228 pub fn deinit(func: *Fn, gpa: *Allocator) void {
1228 pub fn deinit(func: *Fn, gpa: Allocator) void {
12291229 if (func.getInferredErrorSet()) |map| {
12301230 map.deinit(gpa);
12311231 }
......@@ -1422,27 +1422,27 @@ pub const File = struct {
14221422 /// successful, this field is unloaded.
14231423 prev_zir: ?*Zir = null,
14241424
1425 pub fn unload(file: *File, gpa: *Allocator) void {
1425 pub fn unload(file: *File, gpa: Allocator) void {
14261426 file.unloadTree(gpa);
14271427 file.unloadSource(gpa);
14281428 file.unloadZir(gpa);
14291429 }
14301430
1431 pub fn unloadTree(file: *File, gpa: *Allocator) void {
1431 pub fn unloadTree(file: *File, gpa: Allocator) void {
14321432 if (file.tree_loaded) {
14331433 file.tree_loaded = false;
14341434 file.tree.deinit(gpa);
14351435 }
14361436 }
14371437
1438 pub fn unloadSource(file: *File, gpa: *Allocator) void {
1438 pub fn unloadSource(file: *File, gpa: Allocator) void {
14391439 if (file.source_loaded) {
14401440 file.source_loaded = false;
14411441 gpa.free(file.source);
14421442 }
14431443 }
14441444
1445 pub fn unloadZir(file: *File, gpa: *Allocator) void {
1445 pub fn unloadZir(file: *File, gpa: Allocator) void {
14461446 if (file.zir_loaded) {
14471447 file.zir_loaded = false;
14481448 file.zir.deinit(gpa);
......@@ -1466,7 +1466,7 @@ pub const File = struct {
14661466 file.* = undefined;
14671467 }
14681468
1469 pub fn getSource(file: *File, gpa: *Allocator) ![:0]const u8 {
1469 pub fn getSource(file: *File, gpa: Allocator) ![:0]const u8 {
14701470 if (file.source_loaded) return file.source;
14711471
14721472 const root_dir_path = file.pkg.root_src_directory.path orelse ".";
......@@ -1499,7 +1499,7 @@ pub const File = struct {
14991499 return source;
15001500 }
15011501
1502 pub fn getTree(file: *File, gpa: *Allocator) !*const Ast {
1502 pub fn getTree(file: *File, gpa: Allocator) !*const Ast {
15031503 if (file.tree_loaded) return &file.tree;
15041504
15051505 const source = try file.getSource(gpa);
......@@ -1531,7 +1531,7 @@ pub const File = struct {
15311531 };
15321532 }
15331533
1534 pub fn fullyQualifiedNameZ(file: File, gpa: *Allocator) ![:0]u8 {
1534 pub fn fullyQualifiedNameZ(file: File, gpa: Allocator) ![:0]u8 {
15351535 var buf = std.ArrayList(u8).init(gpa);
15361536 defer buf.deinit();
15371537 try file.renderFullyQualifiedName(buf.writer());
......@@ -1539,7 +1539,7 @@ pub const File = struct {
15391539 }
15401540
15411541 /// Returns the full path to this file relative to its package.
1542 pub fn fullPath(file: File, ally: *Allocator) ![]u8 {
1542 pub fn fullPath(file: File, ally: Allocator) ![]u8 {
15431543 return file.pkg.root_src_directory.join(ally, &[_][]const u8{file.sub_file_path});
15441544 }
15451545
......@@ -1594,7 +1594,7 @@ pub const ErrorMsg = struct {
15941594 notes: []ErrorMsg = &.{},
15951595
15961596 pub fn create(
1597 gpa: *Allocator,
1597 gpa: Allocator,
15981598 src_loc: SrcLoc,
15991599 comptime format: []const u8,
16001600 args: anytype,
......@@ -1607,13 +1607,13 @@ pub const ErrorMsg = struct {
16071607
16081608 /// Assumes the ErrorMsg struct and msg were both allocated with `gpa`,
16091609 /// as well as all notes.
1610 pub fn destroy(err_msg: *ErrorMsg, gpa: *Allocator) void {
1610 pub fn destroy(err_msg: *ErrorMsg, gpa: Allocator) void {
16111611 err_msg.deinit(gpa);
16121612 gpa.destroy(err_msg);
16131613 }
16141614
16151615 pub fn init(
1616 gpa: *Allocator,
1616 gpa: Allocator,
16171617 src_loc: SrcLoc,
16181618 comptime format: []const u8,
16191619 args: anytype,
......@@ -1624,7 +1624,7 @@ pub const ErrorMsg = struct {
16241624 };
16251625 }
16261626
1627 pub fn deinit(err_msg: *ErrorMsg, gpa: *Allocator) void {
1627 pub fn deinit(err_msg: *ErrorMsg, gpa: Allocator) void {
16281628 for (err_msg.notes) |*note| {
16291629 note.deinit(gpa);
16301630 }
......@@ -1651,7 +1651,7 @@ pub const SrcLoc = struct {
16511651 return @bitCast(Ast.Node.Index, offset + @bitCast(i32, src_loc.parent_decl_node));
16521652 }
16531653
1654 pub fn byteOffset(src_loc: SrcLoc, gpa: *Allocator) !u32 {
1654 pub fn byteOffset(src_loc: SrcLoc, gpa: Allocator) !u32 {
16551655 switch (src_loc.lazy) {
16561656 .unneeded => unreachable,
16571657 .entire_file => return 0,
......@@ -2066,7 +2066,7 @@ pub const SrcLoc = struct {
20662066
20672067 pub fn byteOffsetBuiltinCallArg(
20682068 src_loc: SrcLoc,
2069 gpa: *Allocator,
2069 gpa: Allocator,
20702070 node_off: i32,
20712071 arg_index: u32,
20722072 ) !u32 {
......@@ -2464,7 +2464,7 @@ pub fn deinit(mod: *Module) void {
24642464 }
24652465}
24662466
2467fn freeExportList(gpa: *Allocator, export_list: []*Export) void {
2467fn freeExportList(gpa: Allocator, export_list: []*Export) void {
24682468 for (export_list) |exp| {
24692469 gpa.free(exp.options.name);
24702470 if (exp.options.section) |s| gpa.free(s);
......@@ -2871,7 +2871,7 @@ pub fn astGenFile(mod: *Module, file: *File) !void {
28712871/// * Decl.zir_index
28722872/// * Fn.zir_body_inst
28732873/// * Decl.zir_decl_index
2874fn updateZirRefs(gpa: *Allocator, file: *File, old_zir: Zir) !void {
2874fn updateZirRefs(gpa: Allocator, file: *File, old_zir: Zir) !void {
28752875 const new_zir = file.zir;
28762876
28772877 // Maps from old ZIR to new ZIR, struct_decl, enum_decl, etc. Any instruction which
......@@ -2965,7 +2965,7 @@ fn updateZirRefs(gpa: *Allocator, file: *File, old_zir: Zir) !void {
29652965}
29662966
29672967pub fn mapOldZirToNew(
2968 gpa: *Allocator,
2968 gpa: Allocator,
29692969 old_zir: Zir,
29702970 new_zir: Zir,
29712971 inst_map: *std.AutoHashMapUnmanaged(Zir.Inst.Index, Zir.Inst.Index),
......@@ -3159,10 +3159,11 @@ pub fn semaFile(mod: *Module, file: *File) SemaError!void {
31593159 const gpa = mod.gpa;
31603160 var new_decl_arena = std.heap.ArenaAllocator.init(gpa);
31613161 errdefer new_decl_arena.deinit();
3162 const new_decl_arena_allocator = new_decl_arena.allocator();
31623163
3163 const struct_obj = try new_decl_arena.allocator.create(Module.Struct);
3164 const struct_ty = try Type.Tag.@"struct".create(&new_decl_arena.allocator, struct_obj);
3165 const struct_val = try Value.Tag.ty.create(&new_decl_arena.allocator, struct_ty);
3164 const struct_obj = try new_decl_arena_allocator.create(Module.Struct);
3165 const struct_ty = try Type.Tag.@"struct".create(new_decl_arena_allocator, struct_obj);
3166 const struct_val = try Value.Tag.ty.create(new_decl_arena_allocator, struct_ty);
31663167 const ty_ty = comptime Type.initTag(.type);
31673168 struct_obj.* = .{
31683169 .owner_decl = undefined, // set below
......@@ -3202,12 +3203,13 @@ pub fn semaFile(mod: *Module, file: *File) SemaError!void {
32023203
32033204 var sema_arena = std.heap.ArenaAllocator.init(gpa);
32043205 defer sema_arena.deinit();
3206 const sema_arena_allocator = sema_arena.allocator();
32053207
32063208 var sema: Sema = .{
32073209 .mod = mod,
32083210 .gpa = gpa,
3209 .arena = &sema_arena.allocator,
3210 .perm_arena = &new_decl_arena.allocator,
3211 .arena = sema_arena_allocator,
3212 .perm_arena = new_decl_arena_allocator,
32113213 .code = file.zir,
32123214 .owner_decl = new_decl,
32133215 .func = null,
......@@ -3216,7 +3218,7 @@ pub fn semaFile(mod: *Module, file: *File) SemaError!void {
32163218 };
32173219 defer sema.deinit();
32183220
3219 var wip_captures = try WipCaptureScope.init(gpa, &new_decl_arena.allocator, null);
3221 var wip_captures = try WipCaptureScope.init(gpa, new_decl_arena_allocator, null);
32203222 defer wip_captures.deinit();
32213223
32223224 var block_scope: Sema.Block = .{
......@@ -3265,15 +3267,17 @@ fn semaDecl(mod: *Module, decl: *Decl) !bool {
32653267 // We need the memory for the Type to go into the arena for the Decl
32663268 var decl_arena = std.heap.ArenaAllocator.init(gpa);
32673269 errdefer decl_arena.deinit();
3270 const decl_arena_allocator = decl_arena.allocator();
32683271
32693272 var analysis_arena = std.heap.ArenaAllocator.init(gpa);
32703273 defer analysis_arena.deinit();
3274 const analysis_arena_allocator = analysis_arena.allocator();
32713275
32723276 var sema: Sema = .{
32733277 .mod = mod,
32743278 .gpa = gpa,
3275 .arena = &analysis_arena.allocator,
3276 .perm_arena = &decl_arena.allocator,
3279 .arena = analysis_arena_allocator,
3280 .perm_arena = decl_arena_allocator,
32773281 .code = zir,
32783282 .owner_decl = decl,
32793283 .func = null,
......@@ -3296,7 +3300,7 @@ fn semaDecl(mod: *Module, decl: *Decl) !bool {
32963300 }
32973301 log.debug("semaDecl {*} ({s})", .{ decl, decl.name });
32983302
3299 var wip_captures = try WipCaptureScope.init(gpa, &decl_arena.allocator, decl.src_scope);
3303 var wip_captures = try WipCaptureScope.init(gpa, decl_arena_allocator, decl.src_scope);
33003304 defer wip_captures.deinit();
33013305
33023306 var block_scope: Sema.Block = .{
......@@ -3356,7 +3360,7 @@ fn semaDecl(mod: *Module, decl: *Decl) !bool {
33563360 // not the struct itself.
33573361 try sema.resolveTypeLayout(&block_scope, src, decl_tv.ty);
33583362
3359 const decl_arena_state = try decl_arena.allocator.create(std.heap.ArenaAllocator.State);
3363 const decl_arena_state = try decl_arena_allocator.create(std.heap.ArenaAllocator.State);
33603364
33613365 if (decl.is_usingnamespace) {
33623366 const ty_ty = Type.initTag(.type);
......@@ -3370,7 +3374,7 @@ fn semaDecl(mod: *Module, decl: *Decl) !bool {
33703374 }
33713375
33723376 decl.ty = ty_ty;
3373 decl.val = try Value.Tag.ty.create(&decl_arena.allocator, ty);
3377 decl.val = try Value.Tag.ty.create(decl_arena_allocator, ty);
33743378 decl.align_val = Value.initTag(.null_value);
33753379 decl.linksection_val = Value.initTag(.null_value);
33763380 decl.has_tv = true;
......@@ -3400,10 +3404,10 @@ fn semaDecl(mod: *Module, decl: *Decl) !bool {
34003404 decl.clearValues(gpa);
34013405 }
34023406
3403 decl.ty = try decl_tv.ty.copy(&decl_arena.allocator);
3404 decl.val = try decl_tv.val.copy(&decl_arena.allocator);
3405 decl.align_val = try align_val.copy(&decl_arena.allocator);
3406 decl.linksection_val = try linksection_val.copy(&decl_arena.allocator);
3407 decl.ty = try decl_tv.ty.copy(decl_arena_allocator);
3408 decl.val = try decl_tv.val.copy(decl_arena_allocator);
3409 decl.align_val = try align_val.copy(decl_arena_allocator);
3410 decl.linksection_val = try linksection_val.copy(decl_arena_allocator);
34073411 decl.@"addrspace" = address_space;
34083412 decl.has_tv = true;
34093413 decl.owns_tv = owns_tv;
......@@ -3453,7 +3457,7 @@ fn semaDecl(mod: *Module, decl: *Decl) !bool {
34533457 decl.owns_tv = true;
34543458 queue_linker_work = true;
34553459
3456 const copied_init = try variable.init.copy(&decl_arena.allocator);
3460 const copied_init = try variable.init.copy(decl_arena_allocator);
34573461 variable.init = copied_init;
34583462 }
34593463 },
......@@ -3476,10 +3480,10 @@ fn semaDecl(mod: *Module, decl: *Decl) !bool {
34763480 },
34773481 }
34783482
3479 decl.ty = try decl_tv.ty.copy(&decl_arena.allocator);
3480 decl.val = try decl_tv.val.copy(&decl_arena.allocator);
3481 decl.align_val = try align_val.copy(&decl_arena.allocator);
3482 decl.linksection_val = try linksection_val.copy(&decl_arena.allocator);
3483 decl.ty = try decl_tv.ty.copy(decl_arena_allocator);
3484 decl.val = try decl_tv.val.copy(decl_arena_allocator);
3485 decl.align_val = try align_val.copy(decl_arena_allocator);
3486 decl.linksection_val = try linksection_val.copy(decl_arena_allocator);
34833487 decl.@"addrspace" = address_space;
34843488 decl.has_tv = true;
34853489 decl_arena_state.* = decl_arena.state;
......@@ -4119,7 +4123,7 @@ fn deleteDeclExports(mod: *Module, decl: *Decl) void {
41194123 mod.gpa.free(kv.value);
41204124}
41214125
4122pub fn analyzeFnBody(mod: *Module, decl: *Decl, func: *Fn, arena: *Allocator) SemaError!Air {
4126pub fn analyzeFnBody(mod: *Module, decl: *Decl, func: *Fn, arena: Allocator) SemaError!Air {
41234127 const tracy = trace(@src());
41244128 defer tracy.end();
41254129
......@@ -4128,12 +4132,13 @@ pub fn analyzeFnBody(mod: *Module, decl: *Decl, func: *Fn, arena: *Allocator) Se
41284132 // Use the Decl's arena for captured values.
41294133 var decl_arena = decl.value_arena.?.promote(gpa);
41304134 defer decl.value_arena.?.* = decl_arena.state;
4135 const decl_arena_allocator = decl_arena.allocator();
41314136
41324137 var sema: Sema = .{
41334138 .mod = mod,
41344139 .gpa = gpa,
41354140 .arena = arena,
4136 .perm_arena = &decl_arena.allocator,
4141 .perm_arena = decl_arena_allocator,
41374142 .code = decl.getFileScope().zir,
41384143 .owner_decl = decl,
41394144 .func = func,
......@@ -4147,7 +4152,7 @@ pub fn analyzeFnBody(mod: *Module, decl: *Decl, func: *Fn, arena: *Allocator) Se
41474152 try sema.air_extra.ensureTotalCapacity(gpa, reserved_count);
41484153 sema.air_extra.items.len += reserved_count;
41494154
4150 var wip_captures = try WipCaptureScope.init(gpa, &decl_arena.allocator, decl.src_scope);
4155 var wip_captures = try WipCaptureScope.init(gpa, decl_arena_allocator, decl.src_scope);
41514156 defer wip_captures.deinit();
41524157
41534158 var inner_block: Sema.Block = .{
......@@ -4427,7 +4432,7 @@ pub fn getNextAnonNameIndex(mod: *Module) usize {
44274432 return @atomicRmw(usize, &mod.next_anon_name_index, .Add, 1, .Monotonic);
44284433}
44294434
4430pub fn makeIntType(arena: *Allocator, signedness: std.builtin.Signedness, bits: u16) !Type {
4435pub fn makeIntType(arena: Allocator, signedness: std.builtin.Signedness, bits: u16) !Type {
44314436 const int_payload = try arena.create(Type.Payload.Bits);
44324437 int_payload.* = .{
44334438 .base = .{
......@@ -4459,7 +4464,7 @@ pub fn errNoteNonLazy(
44594464}
44604465
44614466pub fn errorUnionType(
4462 arena: *Allocator,
4467 arena: Allocator,
44634468 error_set: Type,
44644469 payload: Type,
44654470) Allocator.Error!Type {
......@@ -4511,7 +4516,7 @@ pub const SwitchProngSrc = union(enum) {
45114516 /// the LazySrcLoc in order to emit a compile error.
45124517 pub fn resolve(
45134518 prong_src: SwitchProngSrc,
4514 gpa: *Allocator,
4519 gpa: Allocator,
45154520 decl: *Decl,
45164521 switch_node_offset: i32,
45174522 range_expand: RangeExpand,
......@@ -4605,7 +4610,7 @@ pub const PeerTypeCandidateSrc = union(enum) {
46054610
46064611 pub fn resolve(
46074612 self: PeerTypeCandidateSrc,
4608 gpa: *Allocator,
4613 gpa: Allocator,
46094614 decl: *Decl,
46104615 candidate_i: usize,
46114616 ) ?LazySrcLoc {
......@@ -4751,7 +4756,7 @@ pub fn populateTestFunctions(mod: *Module) !void {
47514756 // decl reference it as a slice.
47524757 var new_decl_arena = std.heap.ArenaAllocator.init(gpa);
47534758 errdefer new_decl_arena.deinit();
4754 const arena = &new_decl_arena.allocator;
4759 const arena = new_decl_arena.allocator();
47554760
47564761 const test_fn_vals = try arena.alloc(Value, mod.test_functions.count());
47574762 const array_decl = try mod.createAnonymousDeclFromDecl(decl, decl.src_namespace, null, .{
......@@ -4770,10 +4775,10 @@ pub fn populateTestFunctions(mod: *Module) !void {
47704775 const test_name_decl = n: {
47714776 var name_decl_arena = std.heap.ArenaAllocator.init(gpa);
47724777 errdefer name_decl_arena.deinit();
4773 const bytes = try name_decl_arena.allocator.dupe(u8, test_name_slice);
4778 const bytes = try arena.dupe(u8, test_name_slice);
47744779 const test_name_decl = try mod.createAnonymousDeclFromDecl(array_decl, array_decl.src_namespace, null, .{
4775 .ty = try Type.Tag.array_u8.create(&name_decl_arena.allocator, bytes.len),
4776 .val = try Value.Tag.bytes.create(&name_decl_arena.allocator, bytes),
4780 .ty = try Type.Tag.array_u8.create(arena, bytes.len),
4781 .val = try Value.Tag.bytes.create(arena, bytes),
47774782 });
47784783 try test_name_decl.finalizeNewArena(&name_decl_arena);
47794784 break :n test_name_decl;
......@@ -4802,7 +4807,7 @@ pub fn populateTestFunctions(mod: *Module) !void {
48024807 {
48034808 var new_decl_arena = std.heap.ArenaAllocator.init(gpa);
48044809 errdefer new_decl_arena.deinit();
4805 const arena = &new_decl_arena.allocator;
4810 const arena = new_decl_arena.allocator();
48064811
48074812 // This copy accesses the old Decl Type/Value so it must be done before `clearValues`.
48084813 const new_ty = try Type.Tag.const_slice.create(arena, try tmp_test_fn_ty.copy(arena));
src/Package.zig+6-6
......@@ -21,7 +21,7 @@ root_src_directory_owned: bool = false,
2121
2222/// Allocate a Package. No references to the slices passed are kept.
2323pub fn create(
24 gpa: *Allocator,
24 gpa: Allocator,
2525 /// Null indicates the current working directory
2626 root_src_dir_path: ?[]const u8,
2727 /// Relative to root_src_dir_path
......@@ -49,7 +49,7 @@ pub fn create(
4949}
5050
5151pub fn createWithDir(
52 gpa: *Allocator,
52 gpa: Allocator,
5353 directory: Compilation.Directory,
5454 /// Relative to `directory`. If null, means `directory` is the root src dir
5555 /// and is owned externally.
......@@ -87,7 +87,7 @@ pub fn createWithDir(
8787
8888/// Free all memory associated with this package. It does not destroy any packages
8989/// inside its table; the caller is responsible for calling destroy() on them.
90pub fn destroy(pkg: *Package, gpa: *Allocator) void {
90pub fn destroy(pkg: *Package, gpa: Allocator) void {
9191 gpa.free(pkg.root_src_path);
9292
9393 if (pkg.root_src_directory_owned) {
......@@ -104,7 +104,7 @@ pub fn destroy(pkg: *Package, gpa: *Allocator) void {
104104}
105105
106106/// Only frees memory associated with the table.
107pub fn deinitTable(pkg: *Package, gpa: *Allocator) void {
107pub fn deinitTable(pkg: *Package, gpa: Allocator) void {
108108 var it = pkg.table.keyIterator();
109109 while (it.next()) |key| {
110110 gpa.free(key.*);
......@@ -113,13 +113,13 @@ pub fn deinitTable(pkg: *Package, gpa: *Allocator) void {
113113 pkg.table.deinit(gpa);
114114}
115115
116pub fn add(pkg: *Package, gpa: *Allocator, name: []const u8, package: *Package) !void {
116pub fn add(pkg: *Package, gpa: Allocator, name: []const u8, package: *Package) !void {
117117 try pkg.table.ensureUnusedCapacity(gpa, 1);
118118 const name_dupe = try gpa.dupe(u8, name);
119119 pkg.table.putAssumeCapacityNoClobber(name_dupe, package);
120120}
121121
122pub fn addAndAdopt(parent: *Package, gpa: *Allocator, name: []const u8, child: *Package) !void {
122pub fn addAndAdopt(parent: *Package, gpa: Allocator, name: []const u8, child: *Package) !void {
123123 assert(child.parent == null); // make up your mind, who is the parent??
124124 child.parent = parent;
125125 return parent.add(gpa, name, child);
src/RangeSet.zig+1-1
......@@ -13,7 +13,7 @@ pub const Range = struct {
1313 src: SwitchProngSrc,
1414};
1515
16pub fn init(allocator: *std.mem.Allocator) RangeSet {
16pub fn init(allocator: std.mem.Allocator) RangeSet {
1717 return .{
1818 .ranges = std.ArrayList(Range).init(allocator),
1919 };
src/Sema.zig+73-63
......@@ -7,13 +7,13 @@
77
88mod: *Module,
99/// Alias to `mod.gpa`.
10gpa: *Allocator,
10gpa: Allocator,
1111/// Points to the temporary arena allocator of the Sema.
1212/// This arena will be cleared when the sema is destroyed.
13arena: *Allocator,
13arena: Allocator,
1414/// Points to the arena allocator for the owner_decl.
1515/// This arena will persist until the decl is invalidated.
16perm_arena: *Allocator,
16perm_arena: Allocator,
1717code: Zir,
1818air_instructions: std.MultiArrayList(Air.Inst) = .{},
1919air_extra: std.ArrayListUnmanaged(u32) = .{},
......@@ -417,8 +417,8 @@ pub const Block = struct {
417417 new_decl_arena: std.heap.ArenaAllocator,
418418 finished: bool,
419419
420 pub fn arena(wad: *WipAnonDecl) *Allocator {
421 return &wad.new_decl_arena.allocator;
420 pub fn arena(wad: *WipAnonDecl) Allocator {
421 return wad.new_decl_arena.allocator();
422422 }
423423
424424 pub fn deinit(wad: *WipAnonDecl) void {
......@@ -1594,10 +1594,11 @@ fn zirStructDecl(
15941594
15951595 var new_decl_arena = std.heap.ArenaAllocator.init(sema.gpa);
15961596 errdefer new_decl_arena.deinit();
1597 const new_decl_arena_allocator = new_decl_arena.allocator();
15971598
1598 const struct_obj = try new_decl_arena.allocator.create(Module.Struct);
1599 const struct_ty = try Type.Tag.@"struct".create(&new_decl_arena.allocator, struct_obj);
1600 const struct_val = try Value.Tag.ty.create(&new_decl_arena.allocator, struct_ty);
1599 const struct_obj = try new_decl_arena_allocator.create(Module.Struct);
1600 const struct_ty = try Type.Tag.@"struct".create(new_decl_arena_allocator, struct_obj);
1601 const struct_val = try Value.Tag.ty.create(new_decl_arena_allocator, struct_ty);
16011602 const type_name = try sema.createTypeName(block, small.name_strategy);
16021603 const new_decl = try sema.mod.createAnonymousDeclNamed(block, .{
16031604 .ty = Type.type,
......@@ -1698,15 +1699,16 @@ fn zirEnumDecl(
16981699
16991700 var new_decl_arena = std.heap.ArenaAllocator.init(gpa);
17001701 errdefer new_decl_arena.deinit();
1702 const new_decl_arena_allocator = new_decl_arena.allocator();
17011703
1702 const enum_obj = try new_decl_arena.allocator.create(Module.EnumFull);
1703 const enum_ty_payload = try new_decl_arena.allocator.create(Type.Payload.EnumFull);
1704 const enum_obj = try new_decl_arena_allocator.create(Module.EnumFull);
1705 const enum_ty_payload = try new_decl_arena_allocator.create(Type.Payload.EnumFull);
17041706 enum_ty_payload.* = .{
17051707 .base = .{ .tag = if (small.nonexhaustive) .enum_nonexhaustive else .enum_full },
17061708 .data = enum_obj,
17071709 };
17081710 const enum_ty = Type.initPayload(&enum_ty_payload.base);
1709 const enum_val = try Value.Tag.ty.create(&new_decl_arena.allocator, enum_ty);
1711 const enum_val = try Value.Tag.ty.create(new_decl_arena_allocator, enum_ty);
17101712 const type_name = try sema.createTypeName(block, small.name_strategy);
17111713 const new_decl = try mod.createAnonymousDeclNamed(block, .{
17121714 .ty = Type.type,
......@@ -1790,17 +1792,17 @@ fn zirEnumDecl(
17901792 break :blk try sema.resolveType(block, src, tag_type_ref);
17911793 }
17921794 const bits = std.math.log2_int_ceil(usize, fields_len);
1793 break :blk try Type.Tag.int_unsigned.create(&new_decl_arena.allocator, bits);
1795 break :blk try Type.Tag.int_unsigned.create(new_decl_arena_allocator, bits);
17941796 };
17951797 enum_obj.tag_ty = tag_ty;
17961798 }
17971799
1798 try enum_obj.fields.ensureTotalCapacity(&new_decl_arena.allocator, fields_len);
1800 try enum_obj.fields.ensureTotalCapacity(new_decl_arena_allocator, fields_len);
17991801 const any_values = for (sema.code.extra[body_end..][0..bit_bags_count]) |bag| {
18001802 if (bag != 0) break true;
18011803 } else false;
18021804 if (any_values) {
1803 try enum_obj.values.ensureTotalCapacityContext(&new_decl_arena.allocator, fields_len, .{
1805 try enum_obj.values.ensureTotalCapacityContext(new_decl_arena_allocator, fields_len, .{
18041806 .ty = enum_obj.tag_ty,
18051807 });
18061808 }
......@@ -1820,7 +1822,7 @@ fn zirEnumDecl(
18201822 extra_index += 1;
18211823
18221824 // This string needs to outlive the ZIR code.
1823 const field_name = try new_decl_arena.allocator.dupe(u8, field_name_zir);
1825 const field_name = try new_decl_arena_allocator.dupe(u8, field_name_zir);
18241826
18251827 const gop = enum_obj.fields.getOrPutAssumeCapacity(field_name);
18261828 if (gop.found_existing) {
......@@ -1843,12 +1845,12 @@ fn zirEnumDecl(
18431845 // that points to this default value expression rather than the struct.
18441846 // But only resolve the source location if we need to emit a compile error.
18451847 const tag_val = (try sema.resolveInstConst(block, src, tag_val_ref)).val;
1846 const copied_tag_val = try tag_val.copy(&new_decl_arena.allocator);
1848 const copied_tag_val = try tag_val.copy(new_decl_arena_allocator);
18471849 enum_obj.values.putAssumeCapacityNoClobberContext(copied_tag_val, {}, .{
18481850 .ty = enum_obj.tag_ty,
18491851 });
18501852 } else if (any_values) {
1851 const tag_val = try Value.Tag.int_u64.create(&new_decl_arena.allocator, field_i);
1853 const tag_val = try Value.Tag.int_u64.create(new_decl_arena_allocator, field_i);
18521854 enum_obj.values.putAssumeCapacityNoClobberContext(tag_val, {}, .{ .ty = enum_obj.tag_ty });
18531855 }
18541856 }
......@@ -1887,16 +1889,17 @@ fn zirUnionDecl(
18871889
18881890 var new_decl_arena = std.heap.ArenaAllocator.init(sema.gpa);
18891891 errdefer new_decl_arena.deinit();
1892 const new_decl_arena_allocator = new_decl_arena.allocator();
18901893
1891 const union_obj = try new_decl_arena.allocator.create(Module.Union);
1894 const union_obj = try new_decl_arena_allocator.create(Module.Union);
18921895 const type_tag: Type.Tag = if (small.has_tag_type or small.auto_enum_tag) .union_tagged else .@"union";
1893 const union_payload = try new_decl_arena.allocator.create(Type.Payload.Union);
1896 const union_payload = try new_decl_arena_allocator.create(Type.Payload.Union);
18941897 union_payload.* = .{
18951898 .base = .{ .tag = type_tag },
18961899 .data = union_obj,
18971900 };
18981901 const union_ty = Type.initPayload(&union_payload.base);
1899 const union_val = try Value.Tag.ty.create(&new_decl_arena.allocator, union_ty);
1902 const union_val = try Value.Tag.ty.create(new_decl_arena_allocator, union_ty);
19001903 const type_name = try sema.createTypeName(block, small.name_strategy);
19011904 const new_decl = try sema.mod.createAnonymousDeclNamed(block, .{
19021905 .ty = Type.type,
......@@ -1955,15 +1958,16 @@ fn zirOpaqueDecl(
19551958
19561959 var new_decl_arena = std.heap.ArenaAllocator.init(gpa);
19571960 errdefer new_decl_arena.deinit();
1961 const new_decl_arena_allocator = new_decl_arena.allocator();
19581962
1959 const opaque_obj = try new_decl_arena.allocator.create(Module.Opaque);
1960 const opaque_ty_payload = try new_decl_arena.allocator.create(Type.Payload.Opaque);
1963 const opaque_obj = try new_decl_arena_allocator.create(Module.Opaque);
1964 const opaque_ty_payload = try new_decl_arena_allocator.create(Type.Payload.Opaque);
19611965 opaque_ty_payload.* = .{
19621966 .base = .{ .tag = .@"opaque" },
19631967 .data = opaque_obj,
19641968 };
19651969 const opaque_ty = Type.initPayload(&opaque_ty_payload.base);
1966 const opaque_val = try Value.Tag.ty.create(&new_decl_arena.allocator, opaque_ty);
1970 const opaque_val = try Value.Tag.ty.create(new_decl_arena_allocator, opaque_ty);
19671971 const type_name = try sema.createTypeName(block, small.name_strategy);
19681972 const new_decl = try mod.createAnonymousDeclNamed(block, .{
19691973 .ty = Type.type,
......@@ -2008,10 +2012,11 @@ fn zirErrorSetDecl(
20082012
20092013 var new_decl_arena = std.heap.ArenaAllocator.init(gpa);
20102014 errdefer new_decl_arena.deinit();
2015 const new_decl_arena_allocator = new_decl_arena.allocator();
20112016
2012 const error_set = try new_decl_arena.allocator.create(Module.ErrorSet);
2013 const error_set_ty = try Type.Tag.error_set.create(&new_decl_arena.allocator, error_set);
2014 const error_set_val = try Value.Tag.ty.create(&new_decl_arena.allocator, error_set_ty);
2017 const error_set = try new_decl_arena_allocator.create(Module.ErrorSet);
2018 const error_set_ty = try Type.Tag.error_set.create(new_decl_arena_allocator, error_set);
2019 const error_set_val = try Value.Tag.ty.create(new_decl_arena_allocator, error_set_ty);
20152020 const type_name = try sema.createTypeName(block, name_strategy);
20162021 const new_decl = try sema.mod.createAnonymousDeclNamed(block, .{
20172022 .ty = Type.type,
......@@ -2019,9 +2024,9 @@ fn zirErrorSetDecl(
20192024 }, type_name);
20202025 new_decl.owns_tv = true;
20212026 errdefer sema.mod.abortAnonDecl(new_decl);
2022 const names = try new_decl_arena.allocator.alloc([]const u8, fields.len);
2027 const names = try new_decl_arena_allocator.alloc([]const u8, fields.len);
20232028 for (fields) |str_index, i| {
2024 names[i] = try new_decl_arena.allocator.dupe(u8, sema.code.nullTerminatedString(str_index));
2029 names[i] = try new_decl_arena_allocator.dupe(u8, sema.code.nullTerminatedString(str_index));
20252030 }
20262031 error_set.* = .{
20272032 .owner_decl = new_decl,
......@@ -3935,7 +3940,7 @@ fn analyzeCall(
39353940 {
39363941 var arena_allocator = std.heap.ArenaAllocator.init(gpa);
39373942 errdefer arena_allocator.deinit();
3938 const arena = &arena_allocator.allocator;
3943 const arena = arena_allocator.allocator();
39393944
39403945 for (memoized_call_key.args) |*arg| {
39413946 arg.* = try arg.*.copy(arena);
......@@ -4069,6 +4074,7 @@ fn analyzeCall(
40694074
40704075 var new_decl_arena = std.heap.ArenaAllocator.init(sema.gpa);
40714076 errdefer new_decl_arena.deinit();
4077 const new_decl_arena_allocator = new_decl_arena.allocator();
40724078
40734079 // Re-run the block that creates the function, with the comptime parameters
40744080 // pre-populated inside `inst_map`. This causes `param_comptime` and
......@@ -4078,13 +4084,13 @@ fn analyzeCall(
40784084 .mod = mod,
40794085 .gpa = gpa,
40804086 .arena = sema.arena,
4081 .perm_arena = &new_decl_arena.allocator,
4087 .perm_arena = new_decl_arena_allocator,
40824088 .code = fn_zir,
40834089 .owner_decl = new_decl,
40844090 .func = null,
40854091 .fn_ret_ty = Type.void,
40864092 .owner_func = null,
4087 .comptime_args = try new_decl_arena.allocator.alloc(TypedValue, uncasted_args.len),
4093 .comptime_args = try new_decl_arena_allocator.alloc(TypedValue, uncasted_args.len),
40884094 .comptime_args_fn_inst = module_fn.zir_body_inst,
40894095 .preallocated_new_func = new_module_func,
40904096 };
......@@ -4168,7 +4174,7 @@ fn analyzeCall(
41684174 else => continue,
41694175 }
41704176 const arg = child_sema.inst_map.get(inst).?;
4171 const copied_arg_ty = try child_sema.typeOf(arg).copy(&new_decl_arena.allocator);
4177 const copied_arg_ty = try child_sema.typeOf(arg).copy(new_decl_arena_allocator);
41724178 if (child_sema.resolveMaybeUndefValAllowVariables(
41734179 &child_block,
41744180 .unneeded,
......@@ -4176,7 +4182,7 @@ fn analyzeCall(
41764182 ) catch unreachable) |arg_val| {
41774183 child_sema.comptime_args[arg_i] = .{
41784184 .ty = copied_arg_ty,
4179 .val = try arg_val.copy(&new_decl_arena.allocator),
4185 .val = try arg_val.copy(new_decl_arena_allocator),
41804186 };
41814187 } else {
41824188 child_sema.comptime_args[arg_i] = .{
......@@ -4191,8 +4197,8 @@ fn analyzeCall(
41914197 try wip_captures.finalize();
41924198
41934199 // Populate the Decl ty/val with the function and its type.
4194 new_decl.ty = try child_sema.typeOf(new_func_inst).copy(&new_decl_arena.allocator);
4195 new_decl.val = try Value.Tag.function.create(&new_decl_arena.allocator, new_func);
4200 new_decl.ty = try child_sema.typeOf(new_func_inst).copy(new_decl_arena_allocator);
4201 new_decl.val = try Value.Tag.function.create(new_decl_arena_allocator, new_func);
41964202 new_decl.analysis = .complete;
41974203
41984204 log.debug("generic function '{s}' instantiated with type {}", .{
......@@ -6047,8 +6053,8 @@ fn zirSwitchBlock(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError
60476053 defer arena.deinit();
60486054
60496055 const target = sema.mod.getTarget();
6050 const min_int = try operand_ty.minInt(&arena.allocator, target);
6051 const max_int = try operand_ty.maxInt(&arena.allocator, target);
6056 const min_int = try operand_ty.minInt(arena.allocator(), target);
6057 const max_int = try operand_ty.maxInt(arena.allocator(), target);
60526058 if (try range_set.spans(min_int, max_int, operand_ty)) {
60536059 if (special_prong == .@"else") {
60546060 return sema.fail(
......@@ -12793,9 +12799,9 @@ const ComptimePtrMutationKit = struct {
1279312799 ty: Type,
1279412800 decl_arena: std.heap.ArenaAllocator = undefined,
1279512801
12796 fn beginArena(self: *ComptimePtrMutationKit, gpa: *Allocator) *Allocator {
12802 fn beginArena(self: *ComptimePtrMutationKit, gpa: Allocator) Allocator {
1279712803 self.decl_arena = self.decl_ref_mut.decl.value_arena.?.promote(gpa);
12798 return &self.decl_arena.allocator;
12804 return self.decl_arena.allocator();
1279912805 }
1280012806
1280112807 fn finishArena(self: *ComptimePtrMutationKit) void {
......@@ -14287,6 +14293,7 @@ fn semaStructFields(
1428714293
1428814294 var decl_arena = decl.value_arena.?.promote(gpa);
1428914295 defer decl.value_arena.?.* = decl_arena.state;
14296 const decl_arena_allocator = decl_arena.allocator();
1429014297
1429114298 var analysis_arena = std.heap.ArenaAllocator.init(gpa);
1429214299 defer analysis_arena.deinit();
......@@ -14294,8 +14301,8 @@ fn semaStructFields(
1429414301 var sema: Sema = .{
1429514302 .mod = mod,
1429614303 .gpa = gpa,
14297 .arena = &analysis_arena.allocator,
14298 .perm_arena = &decl_arena.allocator,
14304 .arena = analysis_arena.allocator(),
14305 .perm_arena = decl_arena_allocator,
1429914306 .code = zir,
1430014307 .owner_decl = decl,
1430114308 .func = null,
......@@ -14304,7 +14311,7 @@ fn semaStructFields(
1430414311 };
1430514312 defer sema.deinit();
1430614313
14307 var wip_captures = try WipCaptureScope.init(gpa, &decl_arena.allocator, decl.src_scope);
14314 var wip_captures = try WipCaptureScope.init(gpa, decl_arena_allocator, decl.src_scope);
1430814315 defer wip_captures.deinit();
1430914316
1431014317 var block_scope: Block = .{
......@@ -14328,7 +14335,7 @@ fn semaStructFields(
1432814335
1432914336 try wip_captures.finalize();
1433014337
14331 try struct_obj.fields.ensureTotalCapacity(&decl_arena.allocator, fields_len);
14338 try struct_obj.fields.ensureTotalCapacity(decl_arena_allocator, fields_len);
1433214339
1433314340 const bits_per_field = 4;
1433414341 const fields_per_u32 = 32 / bits_per_field;
......@@ -14359,7 +14366,7 @@ fn semaStructFields(
1435914366 extra_index += 1;
1436014367
1436114368 // This string needs to outlive the ZIR code.
14362 const field_name = try decl_arena.allocator.dupe(u8, field_name_zir);
14369 const field_name = try decl_arena_allocator.dupe(u8, field_name_zir);
1436314370 const field_ty: Type = if (field_type_ref == .none)
1436414371 Type.initTag(.noreturn)
1436514372 else
......@@ -14371,7 +14378,7 @@ fn semaStructFields(
1437114378 const gop = struct_obj.fields.getOrPutAssumeCapacity(field_name);
1437214379 assert(!gop.found_existing);
1437314380 gop.value_ptr.* = .{
14374 .ty = try field_ty.copy(&decl_arena.allocator),
14381 .ty = try field_ty.copy(decl_arena_allocator),
1437514382 .abi_align = Value.initTag(.abi_align_default),
1437614383 .default_val = Value.initTag(.unreachable_value),
1437714384 .is_comptime = is_comptime,
......@@ -14385,7 +14392,7 @@ fn semaStructFields(
1438514392 // that points to this alignment expression rather than the struct.
1438614393 // But only resolve the source location if we need to emit a compile error.
1438714394 const abi_align_val = (try sema.resolveInstConst(&block_scope, src, align_ref)).val;
14388 gop.value_ptr.abi_align = try abi_align_val.copy(&decl_arena.allocator);
14395 gop.value_ptr.abi_align = try abi_align_val.copy(decl_arena_allocator);
1438914396 }
1439014397 if (has_default) {
1439114398 const default_ref = @intToEnum(Zir.Inst.Ref, zir.extra[extra_index]);
......@@ -14396,7 +14403,7 @@ fn semaStructFields(
1439614403 // But only resolve the source location if we need to emit a compile error.
1439714404 const default_val = (try sema.resolveMaybeUndefVal(&block_scope, src, default_inst)) orelse
1439814405 return sema.failWithNeededComptime(&block_scope, src);
14399 gop.value_ptr.default_val = try default_val.copy(&decl_arena.allocator);
14406 gop.value_ptr.default_val = try default_val.copy(decl_arena_allocator);
1440014407 }
1440114408 }
1440214409}
......@@ -14454,6 +14461,7 @@ fn semaUnionFields(mod: *Module, union_obj: *Module.Union) CompileError!void {
1445414461
1445514462 var decl_arena = union_obj.owner_decl.value_arena.?.promote(gpa);
1445614463 defer union_obj.owner_decl.value_arena.?.* = decl_arena.state;
14464 const decl_arena_allocator = decl_arena.allocator();
1445714465
1445814466 var analysis_arena = std.heap.ArenaAllocator.init(gpa);
1445914467 defer analysis_arena.deinit();
......@@ -14461,8 +14469,8 @@ fn semaUnionFields(mod: *Module, union_obj: *Module.Union) CompileError!void {
1446114469 var sema: Sema = .{
1446214470 .mod = mod,
1446314471 .gpa = gpa,
14464 .arena = &analysis_arena.allocator,
14465 .perm_arena = &decl_arena.allocator,
14472 .arena = analysis_arena.allocator(),
14473 .perm_arena = decl_arena_allocator,
1446614474 .code = zir,
1446714475 .owner_decl = decl,
1446814476 .func = null,
......@@ -14471,7 +14479,7 @@ fn semaUnionFields(mod: *Module, union_obj: *Module.Union) CompileError!void {
1447114479 };
1447214480 defer sema.deinit();
1447314481
14474 var wip_captures = try WipCaptureScope.init(gpa, &decl_arena.allocator, decl.src_scope);
14482 var wip_captures = try WipCaptureScope.init(gpa, decl_arena_allocator, decl.src_scope);
1447514483 defer wip_captures.deinit();
1447614484
1447714485 var block_scope: Block = .{
......@@ -14495,7 +14503,7 @@ fn semaUnionFields(mod: *Module, union_obj: *Module.Union) CompileError!void {
1449514503
1449614504 try wip_captures.finalize();
1449714505
14498 try union_obj.fields.ensureTotalCapacity(&decl_arena.allocator, fields_len);
14506 try union_obj.fields.ensureTotalCapacity(decl_arena_allocator, fields_len);
1449914507
1450014508 var int_tag_ty: Type = undefined;
1450114509 var enum_field_names: ?*Module.EnumNumbered.NameMap = null;
......@@ -14571,7 +14579,7 @@ fn semaUnionFields(mod: *Module, union_obj: *Module.Union) CompileError!void {
1457114579 }
1457214580
1457314581 // This string needs to outlive the ZIR code.
14574 const field_name = try decl_arena.allocator.dupe(u8, field_name_zir);
14582 const field_name = try decl_arena_allocator.dupe(u8, field_name_zir);
1457514583 if (enum_field_names) |set| {
1457614584 set.putAssumeCapacity(field_name, {});
1457714585 }
......@@ -14589,7 +14597,7 @@ fn semaUnionFields(mod: *Module, union_obj: *Module.Union) CompileError!void {
1458914597 const gop = union_obj.fields.getOrPutAssumeCapacity(field_name);
1459014598 assert(!gop.found_existing);
1459114599 gop.value_ptr.* = .{
14592 .ty = try field_ty.copy(&decl_arena.allocator),
14600 .ty = try field_ty.copy(decl_arena_allocator),
1459314601 .abi_align = Value.initTag(.abi_align_default),
1459414602 };
1459514603
......@@ -14598,7 +14606,7 @@ fn semaUnionFields(mod: *Module, union_obj: *Module.Union) CompileError!void {
1459814606 // that points to this alignment expression rather than the struct.
1459914607 // But only resolve the source location if we need to emit a compile error.
1460014608 const abi_align_val = (try sema.resolveInstConst(&block_scope, src, align_ref)).val;
14601 gop.value_ptr.abi_align = try abi_align_val.copy(&decl_arena.allocator);
14609 gop.value_ptr.abi_align = try abi_align_val.copy(decl_arena_allocator);
1460214610 } else {
1460314611 gop.value_ptr.abi_align = Value.initTag(.abi_align_default);
1460414612 }
......@@ -14615,15 +14623,16 @@ fn generateUnionTagTypeNumbered(
1461514623
1461614624 var new_decl_arena = std.heap.ArenaAllocator.init(sema.gpa);
1461714625 errdefer new_decl_arena.deinit();
14626 const new_decl_arena_allocator = new_decl_arena.allocator();
1461814627
14619 const enum_obj = try new_decl_arena.allocator.create(Module.EnumNumbered);
14620 const enum_ty_payload = try new_decl_arena.allocator.create(Type.Payload.EnumNumbered);
14628 const enum_obj = try new_decl_arena_allocator.create(Module.EnumNumbered);
14629 const enum_ty_payload = try new_decl_arena_allocator.create(Type.Payload.EnumNumbered);
1462114630 enum_ty_payload.* = .{
1462214631 .base = .{ .tag = .enum_numbered },
1462314632 .data = enum_obj,
1462414633 };
1462514634 const enum_ty = Type.initPayload(&enum_ty_payload.base);
14626 const enum_val = try Value.Tag.ty.create(&new_decl_arena.allocator, enum_ty);
14635 const enum_val = try Value.Tag.ty.create(new_decl_arena_allocator, enum_ty);
1462714636 // TODO better type name
1462814637 const new_decl = try mod.createAnonymousDecl(block, .{
1462914638 .ty = Type.type,
......@@ -14640,8 +14649,8 @@ fn generateUnionTagTypeNumbered(
1464014649 .node_offset = 0,
1464114650 };
1464214651 // Here we pre-allocate the maps using the decl arena.
14643 try enum_obj.fields.ensureTotalCapacity(&new_decl_arena.allocator, fields_len);
14644 try enum_obj.values.ensureTotalCapacityContext(&new_decl_arena.allocator, fields_len, .{ .ty = int_ty });
14652 try enum_obj.fields.ensureTotalCapacity(new_decl_arena_allocator, fields_len);
14653 try enum_obj.values.ensureTotalCapacityContext(new_decl_arena_allocator, fields_len, .{ .ty = int_ty });
1464514654 try new_decl.finalizeNewArena(&new_decl_arena);
1464614655 return enum_ty;
1464714656}
......@@ -14651,15 +14660,16 @@ fn generateUnionTagTypeSimple(sema: *Sema, block: *Block, fields_len: u32) !Type
1465114660
1465214661 var new_decl_arena = std.heap.ArenaAllocator.init(sema.gpa);
1465314662 errdefer new_decl_arena.deinit();
14663 const new_decl_arena_allocator = new_decl_arena.allocator();
1465414664
14655 const enum_obj = try new_decl_arena.allocator.create(Module.EnumSimple);
14656 const enum_ty_payload = try new_decl_arena.allocator.create(Type.Payload.EnumSimple);
14665 const enum_obj = try new_decl_arena_allocator.create(Module.EnumSimple);
14666 const enum_ty_payload = try new_decl_arena_allocator.create(Type.Payload.EnumSimple);
1465714667 enum_ty_payload.* = .{
1465814668 .base = .{ .tag = .enum_simple },
1465914669 .data = enum_obj,
1466014670 };
1466114671 const enum_ty = Type.initPayload(&enum_ty_payload.base);
14662 const enum_val = try Value.Tag.ty.create(&new_decl_arena.allocator, enum_ty);
14672 const enum_val = try Value.Tag.ty.create(new_decl_arena_allocator, enum_ty);
1466314673 // TODO better type name
1466414674 const new_decl = try mod.createAnonymousDecl(block, .{
1466514675 .ty = Type.type,
......@@ -14674,7 +14684,7 @@ fn generateUnionTagTypeSimple(sema: *Sema, block: *Block, fields_len: u32) !Type
1467414684 .node_offset = 0,
1467514685 };
1467614686 // Here we pre-allocate the maps using the decl arena.
14677 try enum_obj.fields.ensureTotalCapacity(&new_decl_arena.allocator, fields_len);
14687 try enum_obj.fields.ensureTotalCapacity(new_decl_arena_allocator, fields_len);
1467814688 try new_decl.finalizeNewArena(&new_decl_arena);
1467914689 return enum_ty;
1468014690}
src/ThreadPool.zig+2-2
......@@ -9,7 +9,7 @@ const ThreadPool = @This();
99
1010mutex: std.Thread.Mutex = .{},
1111is_running: bool = true,
12allocator: *std.mem.Allocator,
12allocator: std.mem.Allocator,
1313workers: []Worker,
1414run_queue: RunQueue = .{},
1515idle_queue: IdleQueue = .{},
......@@ -55,7 +55,7 @@ const Worker = struct {
5555 }
5656};
5757
58pub fn init(self: *ThreadPool, allocator: *std.mem.Allocator) !void {
58pub fn init(self: *ThreadPool, allocator: std.mem.Allocator) !void {
5959 self.* = .{
6060 .allocator = allocator,
6161 .workers = &[_]Worker{},
src/TypedValue.zig+2-2
......@@ -16,14 +16,14 @@ pub const Managed = struct {
1616 /// If this is `null` then there is no memory management needed.
1717 arena: ?*std.heap.ArenaAllocator.State = null,
1818
19 pub fn deinit(self: *Managed, allocator: *Allocator) void {
19 pub fn deinit(self: *Managed, allocator: Allocator) void {
2020 if (self.arena) |a| a.promote(allocator).deinit();
2121 self.* = undefined;
2222 }
2323};
2424
2525/// Assumes arena allocation. Does a recursive copy.
26pub fn copy(self: TypedValue, arena: *Allocator) error{OutOfMemory}!TypedValue {
26pub fn copy(self: TypedValue, arena: Allocator) error{OutOfMemory}!TypedValue {
2727 return TypedValue{
2828 .ty = try self.ty.copy(arena),
2929 .val = try self.val.copy(arena),
src/Zir.zig+1-1
......@@ -101,7 +101,7 @@ pub fn hasCompileErrors(code: Zir) bool {
101101 return code.extra[@enumToInt(ExtraIndex.compile_errors)] != 0;
102102}
103103
104pub fn deinit(code: *Zir, gpa: *Allocator) void {
104pub fn deinit(code: *Zir, gpa: Allocator) void {
105105 code.instructions.deinit(gpa);
106106 gpa.free(code.string_bytes);
107107 gpa.free(code.extra);
src/arch/aarch64/CodeGen.zig+2-2
......@@ -33,7 +33,7 @@ const InnerError = error{
3333 CodegenFail,
3434};
3535
36gpa: *Allocator,
36gpa: Allocator,
3737air: Air,
3838liveness: Liveness,
3939bin_file: *link.File,
......@@ -164,7 +164,7 @@ const MCValue = union(enum) {
164164const Branch = struct {
165165 inst_table: std.AutoArrayHashMapUnmanaged(Air.Inst.Index, MCValue) = .{},
166166
167 fn deinit(self: *Branch, gpa: *Allocator) void {
167 fn deinit(self: *Branch, gpa: Allocator) void {
168168 self.inst_table.deinit(gpa);
169169 self.* = undefined;
170170 }
src/arch/aarch64/Mir.zig+1-1
......@@ -229,7 +229,7 @@ pub const Inst = struct {
229229 // }
230230};
231231
232pub fn deinit(mir: *Mir, gpa: *std.mem.Allocator) void {
232pub fn deinit(mir: *Mir, gpa: std.mem.Allocator) void {
233233 mir.instructions.deinit(gpa);
234234 gpa.free(mir.extra);
235235 mir.* = undefined;
src/arch/arm/CodeGen.zig+2-2
......@@ -33,7 +33,7 @@ const InnerError = error{
3333 CodegenFail,
3434};
3535
36gpa: *Allocator,
36gpa: Allocator,
3737air: Air,
3838liveness: Liveness,
3939bin_file: *link.File,
......@@ -164,7 +164,7 @@ const MCValue = union(enum) {
164164const Branch = struct {
165165 inst_table: std.AutoArrayHashMapUnmanaged(Air.Inst.Index, MCValue) = .{},
166166
167 fn deinit(self: *Branch, gpa: *Allocator) void {
167 fn deinit(self: *Branch, gpa: Allocator) void {
168168 self.inst_table.deinit(gpa);
169169 self.* = undefined;
170170 }
src/arch/arm/Mir.zig+1-1
......@@ -193,7 +193,7 @@ pub const Inst = struct {
193193 // }
194194};
195195
196pub fn deinit(mir: *Mir, gpa: *std.mem.Allocator) void {
196pub fn deinit(mir: *Mir, gpa: std.mem.Allocator) void {
197197 mir.instructions.deinit(gpa);
198198 gpa.free(mir.extra);
199199 mir.* = undefined;
src/arch/riscv64/CodeGen.zig+2-2
......@@ -33,7 +33,7 @@ const InnerError = error{
3333 CodegenFail,
3434};
3535
36gpa: *Allocator,
36gpa: Allocator,
3737air: Air,
3838liveness: Liveness,
3939bin_file: *link.File,
......@@ -158,7 +158,7 @@ const MCValue = union(enum) {
158158const Branch = struct {
159159 inst_table: std.AutoArrayHashMapUnmanaged(Air.Inst.Index, MCValue) = .{},
160160
161 fn deinit(self: *Branch, gpa: *Allocator) void {
161 fn deinit(self: *Branch, gpa: Allocator) void {
162162 self.inst_table.deinit(gpa);
163163 self.* = undefined;
164164 }
src/arch/riscv64/Mir.zig+1-1
......@@ -101,7 +101,7 @@ pub const Inst = struct {
101101 // }
102102};
103103
104pub fn deinit(mir: *Mir, gpa: *std.mem.Allocator) void {
104pub fn deinit(mir: *Mir, gpa: std.mem.Allocator) void {
105105 mir.instructions.deinit(gpa);
106106 gpa.free(mir.extra);
107107 mir.* = undefined;
src/arch/wasm/CodeGen.zig+2-2
......@@ -508,7 +508,7 @@ const Self = @This();
508508decl: *Decl,
509509air: Air,
510510liveness: Liveness,
511gpa: *mem.Allocator,
511gpa: mem.Allocator,
512512/// Table to save `WValue`'s generated by an `Air.Inst`
513513values: ValueTable,
514514/// Mapping from Air.Inst.Index to block ids
......@@ -983,7 +983,7 @@ const CallWValues = struct {
983983 args: []WValue,
984984 return_value: WValue,
985985
986 fn deinit(self: *CallWValues, gpa: *Allocator) void {
986 fn deinit(self: *CallWValues, gpa: Allocator) void {
987987 gpa.free(self.args);
988988 self.* = undefined;
989989 }
src/arch/wasm/Mir.zig+1-1
......@@ -411,7 +411,7 @@ pub const Inst = struct {
411411 };
412412};
413413
414pub fn deinit(self: *Mir, gpa: *std.mem.Allocator) void {
414pub fn deinit(self: *Mir, gpa: std.mem.Allocator) void {
415415 self.instructions.deinit(gpa);
416416 gpa.free(self.extra);
417417 self.* = undefined;
src/arch/x86_64/CodeGen.zig+2-2
......@@ -33,7 +33,7 @@ const InnerError = error{
3333 CodegenFail,
3434};
3535
36gpa: *Allocator,
36gpa: Allocator,
3737air: Air,
3838liveness: Liveness,
3939bin_file: *link.File,
......@@ -174,7 +174,7 @@ pub const MCValue = union(enum) {
174174const Branch = struct {
175175 inst_table: std.AutoArrayHashMapUnmanaged(Air.Inst.Index, MCValue) = .{},
176176
177 fn deinit(self: *Branch, gpa: *Allocator) void {
177 fn deinit(self: *Branch, gpa: Allocator) void {
178178 self.inst_table.deinit(gpa);
179179 self.* = undefined;
180180 }
src/arch/x86_64/Mir.zig+1-1
......@@ -347,7 +347,7 @@ pub const ArgDbgInfo = struct {
347347 arg_index: u32,
348348};
349349
350pub fn deinit(mir: *Mir, gpa: *std.mem.Allocator) void {
350pub fn deinit(mir: *Mir, gpa: std.mem.Allocator) void {
351351 mir.instructions.deinit(gpa);
352352 gpa.free(mir.extra);
353353 mir.* = undefined;
src/codegen/c.zig+4-3
......@@ -163,14 +163,14 @@ pub const Object = struct {
163163
164164/// This data is available both when outputting .c code and when outputting an .h file.
165165pub const DeclGen = struct {
166 gpa: *std.mem.Allocator,
166 gpa: std.mem.Allocator,
167167 module: *Module,
168168 decl: *Decl,
169169 fwd_decl: std.ArrayList(u8),
170170 error_msg: ?*Module.ErrorMsg,
171171 /// The key of this map is Type which has references to typedefs_arena.
172172 typedefs: TypedefMap,
173 typedefs_arena: *std.mem.Allocator,
173 typedefs_arena: std.mem.Allocator,
174174
175175 fn fail(dg: *DeclGen, comptime format: []const u8, args: anytype) error{ AnalysisFail, OutOfMemory } {
176176 @setCold(true);
......@@ -390,6 +390,7 @@ pub const DeclGen = struct {
390390 // Fall back to generic implementation.
391391 var arena = std.heap.ArenaAllocator.init(dg.module.gpa);
392392 defer arena.deinit();
393 const arena_allocator = arena.allocator();
393394
394395 try writer.writeAll("{");
395396 var index: usize = 0;
......@@ -397,7 +398,7 @@ pub const DeclGen = struct {
397398 const elem_ty = ty.elemType();
398399 while (index < len) : (index += 1) {
399400 if (index != 0) try writer.writeAll(",");
400 const elem_val = try val.elemValue(&arena.allocator, index);
401 const elem_val = try val.elemValue(arena_allocator, index);
401402 try dg.renderValue(writer, elem_ty, elem_val);
402403 }
403404 if (ty.sentinel()) |sentinel_val| {
src/codegen/llvm.zig+13-13
......@@ -23,7 +23,7 @@ const LazySrcLoc = Module.LazySrcLoc;
2323
2424const Error = error{ OutOfMemory, CodegenFail };
2525
26pub fn targetTriple(allocator: *Allocator, target: std.Target) ![:0]u8 {
26pub fn targetTriple(allocator: Allocator, target: std.Target) ![:0]u8 {
2727 const llvm_arch = switch (target.cpu.arch) {
2828 .arm => "arm",
2929 .armeb => "armeb",
......@@ -190,14 +190,14 @@ pub const Object = struct {
190190 std.hash_map.default_max_load_percentage,
191191 );
192192
193 pub fn create(gpa: *Allocator, sub_path: []const u8, options: link.Options) !*Object {
193 pub fn create(gpa: Allocator, sub_path: []const u8, options: link.Options) !*Object {
194194 const obj = try gpa.create(Object);
195195 errdefer gpa.destroy(obj);
196196 obj.* = try Object.init(gpa, sub_path, options);
197197 return obj;
198198 }
199199
200 pub fn init(gpa: *Allocator, sub_path: []const u8, options: link.Options) !Object {
200 pub fn init(gpa: Allocator, sub_path: []const u8, options: link.Options) !Object {
201201 const context = llvm.Context.create();
202202 errdefer context.dispose();
203203
......@@ -287,7 +287,7 @@ pub const Object = struct {
287287 };
288288 }
289289
290 pub fn deinit(self: *Object, gpa: *Allocator) void {
290 pub fn deinit(self: *Object, gpa: Allocator) void {
291291 self.target_machine.dispose();
292292 self.llvm_module.dispose();
293293 self.context.dispose();
......@@ -297,13 +297,13 @@ pub const Object = struct {
297297 self.* = undefined;
298298 }
299299
300 pub fn destroy(self: *Object, gpa: *Allocator) void {
300 pub fn destroy(self: *Object, gpa: Allocator) void {
301301 self.deinit(gpa);
302302 gpa.destroy(self);
303303 }
304304
305305 fn locPath(
306 arena: *Allocator,
306 arena: Allocator,
307307 opt_loc: ?Compilation.EmitLoc,
308308 cache_directory: Compilation.Directory,
309309 ) !?[*:0]u8 {
......@@ -331,7 +331,7 @@ pub const Object = struct {
331331
332332 var arena_allocator = std.heap.ArenaAllocator.init(comp.gpa);
333333 defer arena_allocator.deinit();
334 const arena = &arena_allocator.allocator;
334 const arena = arena_allocator.allocator();
335335
336336 const mod = comp.bin_file.options.module.?;
337337 const cache_dir = mod.zig_cache_artifact_directory;
......@@ -554,7 +554,7 @@ pub const DeclGen = struct {
554554 object: *Object,
555555 module: *Module,
556556 decl: *Module.Decl,
557 gpa: *Allocator,
557 gpa: Allocator,
558558 err_msg: ?*Module.ErrorMsg,
559559
560560 fn todo(self: *DeclGen, comptime format: []const u8, args: anytype) Error {
......@@ -779,7 +779,7 @@ pub const DeclGen = struct {
779779
780780 // The Type memory is ephemeral; since we want to store a longer-lived
781781 // reference, we need to copy it here.
782 gop.key_ptr.* = try t.copy(&dg.object.type_map_arena.allocator);
782 gop.key_ptr.* = try t.copy(dg.object.type_map_arena.allocator());
783783
784784 const opaque_obj = t.castTag(.@"opaque").?.data;
785785 const name = try opaque_obj.getFullyQualifiedName(gpa);
......@@ -837,7 +837,7 @@ pub const DeclGen = struct {
837837
838838 // The Type memory is ephemeral; since we want to store a longer-lived
839839 // reference, we need to copy it here.
840 gop.key_ptr.* = try t.copy(&dg.object.type_map_arena.allocator);
840 gop.key_ptr.* = try t.copy(dg.object.type_map_arena.allocator());
841841
842842 const struct_obj = t.castTag(.@"struct").?.data;
843843
......@@ -871,7 +871,7 @@ pub const DeclGen = struct {
871871
872872 // The Type memory is ephemeral; since we want to store a longer-lived
873873 // reference, we need to copy it here.
874 gop.key_ptr.* = try t.copy(&dg.object.type_map_arena.allocator);
874 gop.key_ptr.* = try t.copy(dg.object.type_map_arena.allocator());
875875
876876 const union_obj = t.cast(Type.Payload.Union).?.data;
877877 const target = dg.module.getTarget();
......@@ -1621,7 +1621,7 @@ pub const DeclGen = struct {
16211621};
16221622
16231623pub const FuncGen = struct {
1624 gpa: *Allocator,
1624 gpa: Allocator,
16251625 dg: *DeclGen,
16261626 air: Air,
16271627 liveness: Liveness,
......@@ -2485,7 +2485,7 @@ pub const FuncGen = struct {
24852485
24862486 var arena_allocator = std.heap.ArenaAllocator.init(self.gpa);
24872487 defer arena_allocator.deinit();
2488 const arena = &arena_allocator.allocator;
2488 const arena = arena_allocator.allocator();
24892489
24902490 const llvm_params_len = args.len;
24912491 const llvm_param_types = try arena.alloc(*const llvm.Type, llvm_params_len);
src/codegen/spirv.zig+2-2
......@@ -70,7 +70,7 @@ pub fn writeInstructionWithString(code: *std.ArrayList(Word), opcode: Opcode, ar
7070/// of data which needs to be persistent over different calls to Decl code generation.
7171pub const SPIRVModule = struct {
7272 /// A general-purpose allocator which may be used to allocate temporary resources required for compilation.
73 gpa: *Allocator,
73 gpa: Allocator,
7474
7575 /// The parent module.
7676 module: *Module,
......@@ -103,7 +103,7 @@ pub const SPIRVModule = struct {
103103 /// just the ones for OpLine. Note that OpLine needs the result of OpString, and not that of OpSource.
104104 file_names: std.StringHashMap(ResultId),
105105
106 pub fn init(gpa: *Allocator, module: *Module) SPIRVModule {
106 pub fn init(gpa: Allocator, module: *Module) SPIRVModule {
107107 return .{
108108 .gpa = gpa,
109109 .module = module,
src/crash_report.zig+1-1
......@@ -85,7 +85,7 @@ fn dumpStatusReport() !void {
8585 const anal = zir_state orelse return;
8686 // Note: We have the panic mutex here, so we can safely use the global crash heap.
8787 var fba = std.heap.FixedBufferAllocator.init(&crash_heap);
88 const allocator = &fba.allocator;
88 const allocator = fba.allocator();
8989
9090 const stderr = io.getStdErr().writer();
9191 const block: *Sema.Block = anal.block;
src/glibc.zig+12-12
......@@ -34,7 +34,7 @@ pub const ABI = struct {
3434 version_table: std.AutoHashMapUnmanaged(target_util.ArchOsAbi, [*]VerList),
3535 arena_state: std.heap.ArenaAllocator.State,
3636
37 pub fn destroy(abi: *ABI, gpa: *Allocator) void {
37 pub fn destroy(abi: *ABI, gpa: Allocator) void {
3838 abi.version_table.deinit(gpa);
3939 abi.arena_state.promote(gpa).deinit(); // Frees the ABI memory too.
4040 }
......@@ -59,13 +59,13 @@ pub const LoadMetaDataError = error{
5959
6060/// This function will emit a log error when there is a problem with the zig installation and then return
6161/// `error.ZigInstallationCorrupt`.
62pub fn loadMetaData(gpa: *Allocator, zig_lib_dir: std.fs.Dir) LoadMetaDataError!*ABI {
62pub fn loadMetaData(gpa: Allocator, zig_lib_dir: std.fs.Dir) LoadMetaDataError!*ABI {
6363 const tracy = trace(@src());
6464 defer tracy.end();
6565
6666 var arena_allocator = std.heap.ArenaAllocator.init(gpa);
6767 errdefer arena_allocator.deinit();
68 const arena = &arena_allocator.allocator;
68 const arena = arena_allocator.allocator();
6969
7070 var all_versions = std.ArrayListUnmanaged(std.builtin.Version){};
7171 var all_functions = std.ArrayListUnmanaged(Fn){};
......@@ -256,7 +256,7 @@ pub fn buildCRTFile(comp: *Compilation, crt_file: CRTFile) !void {
256256 const gpa = comp.gpa;
257257 var arena_allocator = std.heap.ArenaAllocator.init(gpa);
258258 defer arena_allocator.deinit();
259 const arena = &arena_allocator.allocator;
259 const arena = arena_allocator.allocator();
260260
261261 switch (crt_file) {
262262 .crti_o => {
......@@ -433,7 +433,7 @@ pub fn buildCRTFile(comp: *Compilation, crt_file: CRTFile) !void {
433433 }
434434}
435435
436fn start_asm_path(comp: *Compilation, arena: *Allocator, basename: []const u8) ![]const u8 {
436fn start_asm_path(comp: *Compilation, arena: Allocator, basename: []const u8) ![]const u8 {
437437 const arch = comp.getTarget().cpu.arch;
438438 const is_ppc = arch == .powerpc or arch == .powerpc64 or arch == .powerpc64le;
439439 const is_aarch64 = arch == .aarch64 or arch == .aarch64_be;
......@@ -493,7 +493,7 @@ fn start_asm_path(comp: *Compilation, arena: *Allocator, basename: []const u8) !
493493 return result.items;
494494}
495495
496fn add_include_dirs(comp: *Compilation, arena: *Allocator, args: *std.ArrayList([]const u8)) error{OutOfMemory}!void {
496fn add_include_dirs(comp: *Compilation, arena: Allocator, args: *std.ArrayList([]const u8)) error{OutOfMemory}!void {
497497 const target = comp.getTarget();
498498 const arch = target.cpu.arch;
499499 const opt_nptl: ?[]const u8 = if (target.os.tag == .linux) "nptl" else "htl";
......@@ -566,7 +566,7 @@ fn add_include_dirs(comp: *Compilation, arena: *Allocator, args: *std.ArrayList(
566566}
567567
568568fn add_include_dirs_arch(
569 arena: *Allocator,
569 arena: Allocator,
570570 args: *std.ArrayList([]const u8),
571571 arch: std.Target.Cpu.Arch,
572572 opt_nptl: ?[]const u8,
......@@ -677,14 +677,14 @@ fn add_include_dirs_arch(
677677 }
678678}
679679
680fn path_from_lib(comp: *Compilation, arena: *Allocator, sub_path: []const u8) ![]const u8 {
680fn path_from_lib(comp: *Compilation, arena: Allocator, sub_path: []const u8) ![]const u8 {
681681 return path.join(arena, &[_][]const u8{ comp.zig_lib_directory.path.?, sub_path });
682682}
683683
684684const lib_libc = "libc" ++ path.sep_str;
685685const lib_libc_glibc = lib_libc ++ "glibc" ++ path.sep_str;
686686
687fn lib_path(comp: *Compilation, arena: *Allocator, sub_path: []const u8) ![]const u8 {
687fn lib_path(comp: *Compilation, arena: Allocator, sub_path: []const u8) ![]const u8 {
688688 return path.join(arena, &[_][]const u8{ comp.zig_lib_directory.path.?, sub_path });
689689}
690690
......@@ -692,7 +692,7 @@ pub const BuiltSharedObjects = struct {
692692 lock: Cache.Lock,
693693 dir_path: []u8,
694694
695 pub fn deinit(self: *BuiltSharedObjects, gpa: *Allocator) void {
695 pub fn deinit(self: *BuiltSharedObjects, gpa: Allocator) void {
696696 self.lock.release();
697697 gpa.free(self.dir_path);
698698 self.* = undefined;
......@@ -711,7 +711,7 @@ pub fn buildSharedObjects(comp: *Compilation) !void {
711711
712712 var arena_allocator = std.heap.ArenaAllocator.init(comp.gpa);
713713 defer arena_allocator.deinit();
714 const arena = &arena_allocator.allocator;
714 const arena = arena_allocator.allocator();
715715
716716 const target = comp.getTarget();
717717 const target_version = target.os.version_range.linux.glibc;
......@@ -915,7 +915,7 @@ pub fn buildSharedObjects(comp: *Compilation) !void {
915915
916916fn buildSharedLib(
917917 comp: *Compilation,
918 arena: *Allocator,
918 arena: Allocator,
919919 zig_cache_directory: Compilation.Directory,
920920 bin_directory: Compilation.Directory,
921921 asm_file_basename: []const u8,
src/introspect.zig+3-3
......@@ -33,7 +33,7 @@ fn testZigInstallPrefix(base_dir: fs.Dir) ?Compilation.Directory {
3333}
3434
3535/// Both the directory handle and the path are newly allocated resources which the caller now owns.
36pub fn findZigLibDir(gpa: *mem.Allocator) !Compilation.Directory {
36pub fn findZigLibDir(gpa: mem.Allocator) !Compilation.Directory {
3737 const self_exe_path = try fs.selfExePathAlloc(gpa);
3838 defer gpa.free(self_exe_path);
3939
......@@ -42,7 +42,7 @@ pub fn findZigLibDir(gpa: *mem.Allocator) !Compilation.Directory {
4242
4343/// Both the directory handle and the path are newly allocated resources which the caller now owns.
4444pub fn findZigLibDirFromSelfExe(
45 allocator: *mem.Allocator,
45 allocator: mem.Allocator,
4646 self_exe_path: []const u8,
4747) error{ OutOfMemory, FileNotFound }!Compilation.Directory {
4848 const cwd = fs.cwd();
......@@ -61,7 +61,7 @@ pub fn findZigLibDirFromSelfExe(
6161}
6262
6363/// Caller owns returned memory.
64pub fn resolveGlobalCacheDir(allocator: *mem.Allocator) ![]u8 {
64pub fn resolveGlobalCacheDir(allocator: mem.Allocator) ![]u8 {
6565 if (std.process.getEnvVarOwned(allocator, "ZIG_GLOBAL_CACHE_DIR")) |value| {
6666 if (value.len > 0) {
6767 return value;
src/libc_installation.zig+4-4
......@@ -39,7 +39,7 @@ pub const LibCInstallation = struct {
3939 };
4040
4141 pub fn parse(
42 allocator: *Allocator,
42 allocator: Allocator,
4343 libc_file: []const u8,
4444 target: std.zig.CrossTarget,
4545 ) !LibCInstallation {
......@@ -175,7 +175,7 @@ pub const LibCInstallation = struct {
175175 }
176176
177177 pub const FindNativeOptions = struct {
178 allocator: *Allocator,
178 allocator: Allocator,
179179
180180 /// If enabled, will print human-friendly errors to stderr.
181181 verbose: bool = false,
......@@ -234,7 +234,7 @@ pub const LibCInstallation = struct {
234234 }
235235
236236 /// Must be the same allocator passed to `parse` or `findNative`.
237 pub fn deinit(self: *LibCInstallation, allocator: *Allocator) void {
237 pub fn deinit(self: *LibCInstallation, allocator: Allocator) void {
238238 const fields = std.meta.fields(LibCInstallation);
239239 inline for (fields) |field| {
240240 if (@field(self, field.name)) |payload| {
......@@ -562,7 +562,7 @@ pub const LibCInstallation = struct {
562562};
563563
564564pub const CCPrintFileNameOptions = struct {
565 allocator: *Allocator,
565 allocator: Allocator,
566566 search_basename: []const u8,
567567 want_dirname: enum { full_path, only_dir },
568568 verbose: bool = false,
src/libcxx.zig+2-2
......@@ -89,7 +89,7 @@ pub fn buildLibCXX(comp: *Compilation) !void {
8989
9090 var arena_allocator = std.heap.ArenaAllocator.init(comp.gpa);
9191 defer arena_allocator.deinit();
92 const arena = &arena_allocator.allocator;
92 const arena = arena_allocator.allocator();
9393
9494 const root_name = "c++";
9595 const output_mode = .Lib;
......@@ -236,7 +236,7 @@ pub fn buildLibCXXABI(comp: *Compilation) !void {
236236
237237 var arena_allocator = std.heap.ArenaAllocator.init(comp.gpa);
238238 defer arena_allocator.deinit();
239 const arena = &arena_allocator.allocator;
239 const arena = arena_allocator.allocator();
240240
241241 const root_name = "c++abi";
242242 const output_mode = .Lib;
src/libtsan.zig+1-1
......@@ -15,7 +15,7 @@ pub fn buildTsan(comp: *Compilation) !void {
1515
1616 var arena_allocator = std.heap.ArenaAllocator.init(comp.gpa);
1717 defer arena_allocator.deinit();
18 const arena = &arena_allocator.allocator;
18 const arena = arena_allocator.allocator();
1919
2020 const root_name = "tsan";
2121 const output_mode = .Lib;
src/libunwind.zig+1-1
......@@ -17,7 +17,7 @@ pub fn buildStaticLib(comp: *Compilation) !void {
1717
1818 var arena_allocator = std.heap.ArenaAllocator.init(comp.gpa);
1919 defer arena_allocator.deinit();
20 const arena = &arena_allocator.allocator;
20 const arena = arena_allocator.allocator();
2121
2222 const root_name = "unwind";
2323 const output_mode = .Lib;
src/link.zig+3-3
......@@ -165,7 +165,7 @@ pub const File = struct {
165165 tag: Tag,
166166 options: Options,
167167 file: ?fs.File,
168 allocator: *Allocator,
168 allocator: Allocator,
169169 /// When linking with LLD, this linker code will output an object file only at
170170 /// this location, and then this path can be placed on the LLD linker line.
171171 intermediary_basename: ?[]const u8 = null,
......@@ -221,7 +221,7 @@ pub const File = struct {
221221 /// incremental linking fails, falls back to truncating the file and
222222 /// rewriting it. A malicious file is detected as incremental link failure
223223 /// and does not cause Illegal Behavior. This operation is not atomic.
224 pub fn openPath(allocator: *Allocator, options: Options) !*File {
224 pub fn openPath(allocator: Allocator, options: Options) !*File {
225225 if (options.object_format == .macho) {
226226 return &(try MachO.openPath(allocator, options)).base;
227227 }
......@@ -628,7 +628,7 @@ pub const File = struct {
628628
629629 var arena_allocator = std.heap.ArenaAllocator.init(base.allocator);
630630 defer arena_allocator.deinit();
631 const arena = &arena_allocator.allocator;
631 const arena = arena_allocator.allocator();
632632
633633 const directory = base.options.emit.?.directory; // Just an alias to make it shorter to type.
634634
src/link/C.zig+5-5
......@@ -36,7 +36,7 @@ const DeclBlock = struct {
3636 /// Any arena memory the Type points to lives in the `arena` field of `C`.
3737 typedefs: codegen.TypedefMap.Unmanaged = .{},
3838
39 fn deinit(db: *DeclBlock, gpa: *Allocator) void {
39 fn deinit(db: *DeclBlock, gpa: Allocator) void {
4040 db.code.deinit(gpa);
4141 db.fwd_decl.deinit(gpa);
4242 for (db.typedefs.values()) |typedef| {
......@@ -47,7 +47,7 @@ const DeclBlock = struct {
4747 }
4848};
4949
50pub fn openPath(gpa: *Allocator, sub_path: []const u8, options: link.Options) !*C {
50pub fn openPath(gpa: Allocator, sub_path: []const u8, options: link.Options) !*C {
5151 assert(options.object_format == .c);
5252
5353 if (options.use_llvm) return error.LLVMHasNoCBackend;
......@@ -128,7 +128,7 @@ pub fn updateFunc(self: *C, module: *Module, func: *Module.Fn, air: Air, livenes
128128 .decl = decl,
129129 .fwd_decl = fwd_decl.toManaged(module.gpa),
130130 .typedefs = typedefs.promote(module.gpa),
131 .typedefs_arena = &self.arena.allocator,
131 .typedefs_arena = self.arena.allocator(),
132132 },
133133 .code = code.toManaged(module.gpa),
134134 .indent_writer = undefined, // set later so we can get a pointer to object.code
......@@ -193,7 +193,7 @@ pub fn updateDecl(self: *C, module: *Module, decl: *Module.Decl) !void {
193193 .decl = decl,
194194 .fwd_decl = fwd_decl.toManaged(module.gpa),
195195 .typedefs = typedefs.promote(module.gpa),
196 .typedefs_arena = &self.arena.allocator,
196 .typedefs_arena = self.arena.allocator(),
197197 },
198198 .code = code.toManaged(module.gpa),
199199 .indent_writer = undefined, // set later so we can get a pointer to object.code
......@@ -336,7 +336,7 @@ const Flush = struct {
336336 std.hash_map.default_max_load_percentage,
337337 );
338338
339 fn deinit(f: *Flush, gpa: *Allocator) void {
339 fn deinit(f: *Flush, gpa: Allocator) void {
340340 f.all_buffers.deinit(gpa);
341341 f.err_typedef_buf.deinit(gpa);
342342 f.typedefs.deinit(gpa);
src/link/Coff.zig+4-4
......@@ -125,7 +125,7 @@ pub const TextBlock = struct {
125125
126126pub const SrcFn = void;
127127
128pub fn openPath(allocator: *Allocator, sub_path: []const u8, options: link.Options) !*Coff {
128pub fn openPath(allocator: Allocator, sub_path: []const u8, options: link.Options) !*Coff {
129129 assert(options.object_format == .coff);
130130
131131 if (build_options.have_llvm and options.use_llvm) {
......@@ -396,7 +396,7 @@ pub fn openPath(allocator: *Allocator, sub_path: []const u8, options: link.Optio
396396 return self;
397397}
398398
399pub fn createEmpty(gpa: *Allocator, options: link.Options) !*Coff {
399pub fn createEmpty(gpa: Allocator, options: link.Options) !*Coff {
400400 const ptr_width: PtrWidth = switch (options.target.cpu.arch.ptrBitWidth()) {
401401 0...32 => .p32,
402402 33...64 => .p64,
......@@ -877,7 +877,7 @@ fn linkWithLLD(self: *Coff, comp: *Compilation) !void {
877877
878878 var arena_allocator = std.heap.ArenaAllocator.init(self.base.allocator);
879879 defer arena_allocator.deinit();
880 const arena = &arena_allocator.allocator;
880 const arena = arena_allocator.allocator();
881881
882882 const directory = self.base.options.emit.?.directory; // Just an alias to make it shorter to type.
883883
......@@ -1394,7 +1394,7 @@ fn linkWithLLD(self: *Coff, comp: *Compilation) !void {
13941394 }
13951395}
13961396
1397fn findLib(self: *Coff, arena: *Allocator, name: []const u8) !?[]const u8 {
1397fn findLib(self: *Coff, arena: Allocator, name: []const u8) !?[]const u8 {
13981398 for (self.base.options.lib_dirs) |lib_dir| {
13991399 const full_path = try fs.path.join(arena, &.{ lib_dir, name });
14001400 fs.cwd().access(full_path, .{}) catch |err| switch (err) {
src/link/Elf.zig+5-5
......@@ -228,7 +228,7 @@ pub const SrcFn = struct {
228228 };
229229};
230230
231pub fn openPath(allocator: *Allocator, sub_path: []const u8, options: link.Options) !*Elf {
231pub fn openPath(allocator: Allocator, sub_path: []const u8, options: link.Options) !*Elf {
232232 assert(options.object_format == .elf);
233233
234234 if (build_options.have_llvm and options.use_llvm) {
......@@ -281,7 +281,7 @@ pub fn openPath(allocator: *Allocator, sub_path: []const u8, options: link.Optio
281281 return self;
282282}
283283
284pub fn createEmpty(gpa: *Allocator, options: link.Options) !*Elf {
284pub fn createEmpty(gpa: Allocator, options: link.Options) !*Elf {
285285 const ptr_width: PtrWidth = switch (options.target.cpu.arch.ptrBitWidth()) {
286286 0...32 => .p32,
287287 33...64 => .p64,
......@@ -1243,7 +1243,7 @@ fn linkWithLLD(self: *Elf, comp: *Compilation) !void {
12431243
12441244 var arena_allocator = std.heap.ArenaAllocator.init(self.base.allocator);
12451245 defer arena_allocator.deinit();
1246 const arena = &arena_allocator.allocator;
1246 const arena = arena_allocator.allocator();
12471247
12481248 const directory = self.base.options.emit.?.directory; // Just an alias to make it shorter to type.
12491249
......@@ -2205,7 +2205,7 @@ pub fn freeDecl(self: *Elf, decl: *Module.Decl) void {
22052205 }
22062206}
22072207
2208fn deinitRelocs(gpa: *Allocator, table: *File.DbgInfoTypeRelocsTable) void {
2208fn deinitRelocs(gpa: Allocator, table: *File.DbgInfoTypeRelocsTable) void {
22092209 var it = table.valueIterator();
22102210 while (it.next()) |value| {
22112211 value.relocs.deinit(gpa);
......@@ -3360,7 +3360,7 @@ const CsuObjects = struct {
33603360 crtend: ?[]const u8 = null,
33613361 crtn: ?[]const u8 = null,
33623362
3363 fn init(arena: *mem.Allocator, link_options: link.Options, comp: *const Compilation) !CsuObjects {
3363 fn init(arena: mem.Allocator, link_options: link.Options, comp: *const Compilation) !CsuObjects {
33643364 // crt objects are only required for libc.
33653365 if (!link_options.link_libc) return CsuObjects{};
33663366
src/link/MachO.zig+8-8
......@@ -280,7 +280,7 @@ pub const SrcFn = struct {
280280 };
281281};
282282
283pub fn openPath(allocator: *Allocator, options: link.Options) !*MachO {
283pub fn openPath(allocator: Allocator, options: link.Options) !*MachO {
284284 assert(options.object_format == .macho);
285285
286286 const use_stage1 = build_options.is_stage1 and options.use_stage1;
......@@ -366,7 +366,7 @@ pub fn openPath(allocator: *Allocator, options: link.Options) !*MachO {
366366 return self;
367367}
368368
369pub fn createEmpty(gpa: *Allocator, options: link.Options) !*MachO {
369pub fn createEmpty(gpa: Allocator, options: link.Options) !*MachO {
370370 const self = try gpa.create(MachO);
371371 const cpu_arch = options.target.cpu.arch;
372372 const os_tag = options.target.os.tag;
......@@ -412,7 +412,7 @@ pub fn flushModule(self: *MachO, comp: *Compilation) !void {
412412
413413 var arena_allocator = std.heap.ArenaAllocator.init(self.base.allocator);
414414 defer arena_allocator.deinit();
415 const arena = &arena_allocator.allocator;
415 const arena = arena_allocator.allocator();
416416
417417 const directory = self.base.options.emit.?.directory; // Just an alias to make it shorter to type.
418418
......@@ -1032,7 +1032,7 @@ pub fn flushObject(self: *MachO, comp: *Compilation) !void {
10321032}
10331033
10341034fn resolveSearchDir(
1035 arena: *Allocator,
1035 arena: Allocator,
10361036 dir: []const u8,
10371037 syslibroot: ?[]const u8,
10381038) !?[]const u8 {
......@@ -1074,7 +1074,7 @@ fn resolveSearchDir(
10741074}
10751075
10761076fn resolveLib(
1077 arena: *Allocator,
1077 arena: Allocator,
10781078 search_dirs: []const []const u8,
10791079 name: []const u8,
10801080 ext: []const u8,
......@@ -1098,7 +1098,7 @@ fn resolveLib(
10981098}
10991099
11001100fn resolveFramework(
1101 arena: *Allocator,
1101 arena: Allocator,
11021102 search_dirs: []const []const u8,
11031103 name: []const u8,
11041104 ext: []const u8,
......@@ -1288,7 +1288,7 @@ fn parseDependentLibs(self: *MachO, syslibroot: ?[]const u8, dependent_libs: any
12881288 // TODO this should not be performed if the user specifies `-flat_namespace` flag.
12891289 // See ld64 manpages.
12901290 var arena_alloc = std.heap.ArenaAllocator.init(self.base.allocator);
1291 const arena = &arena_alloc.allocator;
1291 const arena = arena_alloc.allocator();
12921292 defer arena_alloc.deinit();
12931293
12941294 while (dependent_libs.readItem()) |*id| {
......@@ -5379,7 +5379,7 @@ fn snapshotState(self: *MachO) !void {
53795379
53805380 var arena_allocator = std.heap.ArenaAllocator.init(self.base.allocator);
53815381 defer arena_allocator.deinit();
5382 const arena = &arena_allocator.allocator;
5382 const arena = arena_allocator.allocator();
53835383
53845384 const out_file = try emit.directory.handle.createFile("snapshots.json", .{
53855385 .truncate = self.cold_start,
src/link/MachO/Archive.zig+5-5
......@@ -92,7 +92,7 @@ const ar_hdr = extern struct {
9292 }
9393};
9494
95pub fn deinit(self: *Archive, allocator: *Allocator) void {
95pub fn deinit(self: *Archive, allocator: Allocator) void {
9696 for (self.toc.keys()) |*key| {
9797 allocator.free(key.*);
9898 }
......@@ -103,7 +103,7 @@ pub fn deinit(self: *Archive, allocator: *Allocator) void {
103103 allocator.free(self.name);
104104}
105105
106pub fn parse(self: *Archive, allocator: *Allocator, target: std.Target) !void {
106pub fn parse(self: *Archive, allocator: Allocator, target: std.Target) !void {
107107 const reader = self.file.reader();
108108 self.library_offset = try fat.getLibraryOffset(reader, target);
109109 try self.file.seekTo(self.library_offset);
......@@ -128,7 +128,7 @@ pub fn parse(self: *Archive, allocator: *Allocator, target: std.Target) !void {
128128 try reader.context.seekTo(0);
129129}
130130
131fn parseName(allocator: *Allocator, header: ar_hdr, reader: anytype) ![]u8 {
131fn parseName(allocator: Allocator, header: ar_hdr, reader: anytype) ![]u8 {
132132 const name_or_length = try header.nameOrLength();
133133 var name: []u8 = undefined;
134134 switch (name_or_length) {
......@@ -146,7 +146,7 @@ fn parseName(allocator: *Allocator, header: ar_hdr, reader: anytype) ![]u8 {
146146 return name;
147147}
148148
149fn parseTableOfContents(self: *Archive, allocator: *Allocator, reader: anytype) !void {
149fn parseTableOfContents(self: *Archive, allocator: Allocator, reader: anytype) !void {
150150 const symtab_size = try reader.readIntLittle(u32);
151151 var symtab = try allocator.alloc(u8, symtab_size);
152152 defer allocator.free(symtab);
......@@ -188,7 +188,7 @@ fn parseTableOfContents(self: *Archive, allocator: *Allocator, reader: anytype)
188188 }
189189}
190190
191pub fn parseObject(self: Archive, allocator: *Allocator, target: std.Target, offset: u32) !Object {
191pub fn parseObject(self: Archive, allocator: Allocator, target: std.Target, offset: u32) !Object {
192192 const reader = self.file.reader();
193193 try reader.context.seekTo(offset + self.library_offset);
194194
src/link/MachO/Atom.zig+2-2
......@@ -195,7 +195,7 @@ pub const empty = Atom{
195195 .dbg_info_len = undefined,
196196};
197197
198pub fn deinit(self: *Atom, allocator: *Allocator) void {
198pub fn deinit(self: *Atom, allocator: Allocator) void {
199199 self.dices.deinit(allocator);
200200 self.lazy_bindings.deinit(allocator);
201201 self.bindings.deinit(allocator);
......@@ -246,7 +246,7 @@ pub fn freeListEligible(self: Atom, macho_file: MachO) bool {
246246
247247const RelocContext = struct {
248248 base_addr: u64 = 0,
249 allocator: *Allocator,
249 allocator: Allocator,
250250 object: *Object,
251251 macho_file: *MachO,
252252};
src/link/MachO/CodeSignature.zig+2-2
......@@ -58,7 +58,7 @@ cdir: ?CodeDirectory = null,
5858
5959pub fn calcAdhocSignature(
6060 self: *CodeSignature,
61 allocator: *Allocator,
61 allocator: Allocator,
6262 file: fs.File,
6363 id: []const u8,
6464 text_segment: macho.segment_command_64,
......@@ -145,7 +145,7 @@ pub fn write(self: CodeSignature, writer: anytype) !void {
145145 try self.cdir.?.write(writer);
146146}
147147
148pub fn deinit(self: *CodeSignature, allocator: *Allocator) void {
148pub fn deinit(self: *CodeSignature, allocator: Allocator) void {
149149 if (self.cdir) |*cdir| {
150150 cdir.data.deinit(allocator);
151151 }
src/link/MachO/DebugSymbols.zig+9-9
......@@ -104,7 +104,7 @@ const min_nop_size = 2;
104104
105105/// You must call this function *after* `MachO.populateMissingMetadata()`
106106/// has been called to get a viable debug symbols output.
107pub fn populateMissingMetadata(self: *DebugSymbols, allocator: *Allocator) !void {
107pub fn populateMissingMetadata(self: *DebugSymbols, allocator: Allocator) !void {
108108 if (self.uuid_cmd_index == null) {
109109 const base_cmd = self.base.load_commands.items[self.base.uuid_cmd_index.?];
110110 self.uuid_cmd_index = @intCast(u16, self.load_commands.items.len);
......@@ -268,7 +268,7 @@ fn allocateSection(self: *DebugSymbols, sectname: []const u8, size: u64, alignme
268268 return index;
269269}
270270
271pub fn flushModule(self: *DebugSymbols, allocator: *Allocator, options: link.Options) !void {
271pub fn flushModule(self: *DebugSymbols, allocator: Allocator, options: link.Options) !void {
272272 // TODO This linker code currently assumes there is only 1 compilation unit and it corresponds to the
273273 // Zig source code.
274274 const module = options.module orelse return error.LinkingWithoutZigSourceUnimplemented;
......@@ -577,7 +577,7 @@ pub fn flushModule(self: *DebugSymbols, allocator: *Allocator, options: link.Opt
577577 assert(!self.debug_string_table_dirty);
578578}
579579
580pub fn deinit(self: *DebugSymbols, allocator: *Allocator) void {
580pub fn deinit(self: *DebugSymbols, allocator: Allocator) void {
581581 self.dbg_info_decl_free_list.deinit(allocator);
582582 self.dbg_line_fn_free_list.deinit(allocator);
583583 self.debug_string_table.deinit(allocator);
......@@ -588,7 +588,7 @@ pub fn deinit(self: *DebugSymbols, allocator: *Allocator) void {
588588 self.file.close();
589589}
590590
591fn copySegmentCommand(self: *DebugSymbols, allocator: *Allocator, base_cmd: SegmentCommand) !SegmentCommand {
591fn copySegmentCommand(self: *DebugSymbols, allocator: Allocator, base_cmd: SegmentCommand) !SegmentCommand {
592592 var cmd = SegmentCommand{
593593 .inner = .{
594594 .segname = undefined,
......@@ -648,7 +648,7 @@ fn updateDwarfSegment(self: *DebugSymbols) void {
648648}
649649
650650/// Writes all load commands and section headers.
651fn writeLoadCommands(self: *DebugSymbols, allocator: *Allocator) !void {
651fn writeLoadCommands(self: *DebugSymbols, allocator: Allocator) !void {
652652 if (!self.load_commands_dirty) return;
653653
654654 var sizeofcmds: u32 = 0;
......@@ -834,7 +834,7 @@ pub const DeclDebugBuffers = struct {
834834/// Caller owns the returned memory.
835835pub fn initDeclDebugBuffers(
836836 self: *DebugSymbols,
837 allocator: *Allocator,
837 allocator: Allocator,
838838 module: *Module,
839839 decl: *Module.Decl,
840840) !DeclDebugBuffers {
......@@ -930,7 +930,7 @@ pub fn initDeclDebugBuffers(
930930
931931pub fn commitDeclDebugInfo(
932932 self: *DebugSymbols,
933 allocator: *Allocator,
933 allocator: Allocator,
934934 module: *Module,
935935 decl: *Module.Decl,
936936 debug_buffers: *DeclDebugBuffers,
......@@ -1141,7 +1141,7 @@ fn addDbgInfoType(
11411141
11421142fn updateDeclDebugInfoAllocation(
11431143 self: *DebugSymbols,
1144 allocator: *Allocator,
1144 allocator: Allocator,
11451145 text_block: *TextBlock,
11461146 len: u32,
11471147) !void {
......@@ -1256,7 +1256,7 @@ fn getDebugLineProgramEnd(self: DebugSymbols) u32 {
12561256}
12571257
12581258/// TODO Improve this to use a table.
1259fn makeDebugString(self: *DebugSymbols, allocator: *Allocator, bytes: []const u8) !u32 {
1259fn makeDebugString(self: *DebugSymbols, allocator: Allocator, bytes: []const u8) !u32 {
12601260 try self.debug_string_table.ensureUnusedCapacity(allocator, bytes.len + 1);
12611261 const result = self.debug_string_table.items.len;
12621262 self.debug_string_table.appendSliceAssumeCapacity(bytes);
src/link/MachO/Dylib.zig+16-16
......@@ -44,7 +44,7 @@ pub const Id = struct {
4444 current_version: u32,
4545 compatibility_version: u32,
4646
47 pub fn default(allocator: *Allocator, name: []const u8) !Id {
47 pub fn default(allocator: Allocator, name: []const u8) !Id {
4848 return Id{
4949 .name = try allocator.dupe(u8, name),
5050 .timestamp = 2,
......@@ -53,7 +53,7 @@ pub const Id = struct {
5353 };
5454 }
5555
56 pub fn fromLoadCommand(allocator: *Allocator, lc: commands.GenericCommandWithData(macho.dylib_command)) !Id {
56 pub fn fromLoadCommand(allocator: Allocator, lc: commands.GenericCommandWithData(macho.dylib_command)) !Id {
5757 const dylib = lc.inner.dylib;
5858 const dylib_name = @ptrCast([*:0]const u8, lc.data[dylib.name - @sizeOf(macho.dylib_command) ..]);
5959 const name = try allocator.dupe(u8, mem.sliceTo(dylib_name, 0));
......@@ -66,7 +66,7 @@ pub const Id = struct {
6666 };
6767 }
6868
69 pub fn deinit(id: *Id, allocator: *Allocator) void {
69 pub fn deinit(id: *Id, allocator: Allocator) void {
7070 allocator.free(id.name);
7171 }
7272
......@@ -125,7 +125,7 @@ pub const Id = struct {
125125 }
126126};
127127
128pub fn deinit(self: *Dylib, allocator: *Allocator) void {
128pub fn deinit(self: *Dylib, allocator: Allocator) void {
129129 for (self.load_commands.items) |*lc| {
130130 lc.deinit(allocator);
131131 }
......@@ -143,7 +143,7 @@ pub fn deinit(self: *Dylib, allocator: *Allocator) void {
143143 }
144144}
145145
146pub fn parse(self: *Dylib, allocator: *Allocator, target: std.Target, dependent_libs: anytype) !void {
146pub fn parse(self: *Dylib, allocator: Allocator, target: std.Target, dependent_libs: anytype) !void {
147147 log.debug("parsing shared library '{s}'", .{self.name});
148148
149149 self.library_offset = try fat.getLibraryOffset(self.file.reader(), target);
......@@ -170,7 +170,7 @@ pub fn parse(self: *Dylib, allocator: *Allocator, target: std.Target, dependent_
170170 try self.parseSymbols(allocator);
171171}
172172
173fn readLoadCommands(self: *Dylib, allocator: *Allocator, reader: anytype, dependent_libs: anytype) !void {
173fn readLoadCommands(self: *Dylib, allocator: Allocator, reader: anytype, dependent_libs: anytype) !void {
174174 const should_lookup_reexports = self.header.?.flags & macho.MH_NO_REEXPORTED_DYLIBS == 0;
175175
176176 try self.load_commands.ensureUnusedCapacity(allocator, self.header.?.ncmds);
......@@ -203,7 +203,7 @@ fn readLoadCommands(self: *Dylib, allocator: *Allocator, reader: anytype, depend
203203 }
204204}
205205
206fn parseId(self: *Dylib, allocator: *Allocator) !void {
206fn parseId(self: *Dylib, allocator: Allocator) !void {
207207 const index = self.id_cmd_index orelse {
208208 log.debug("no LC_ID_DYLIB load command found; using hard-coded defaults...", .{});
209209 self.id = try Id.default(allocator, self.name);
......@@ -212,7 +212,7 @@ fn parseId(self: *Dylib, allocator: *Allocator) !void {
212212 self.id = try Id.fromLoadCommand(allocator, self.load_commands.items[index].Dylib);
213213}
214214
215fn parseSymbols(self: *Dylib, allocator: *Allocator) !void {
215fn parseSymbols(self: *Dylib, allocator: Allocator) !void {
216216 const index = self.symtab_cmd_index orelse return;
217217 const symtab_cmd = self.load_commands.items[index].Symtab;
218218
......@@ -236,7 +236,7 @@ fn parseSymbols(self: *Dylib, allocator: *Allocator) !void {
236236 }
237237}
238238
239fn addObjCClassSymbol(self: *Dylib, allocator: *Allocator, sym_name: []const u8) !void {
239fn addObjCClassSymbol(self: *Dylib, allocator: Allocator, sym_name: []const u8) !void {
240240 const expanded = &[_][]const u8{
241241 try std.fmt.allocPrint(allocator, "_OBJC_CLASS_$_{s}", .{sym_name}),
242242 try std.fmt.allocPrint(allocator, "_OBJC_METACLASS_$_{s}", .{sym_name}),
......@@ -248,29 +248,29 @@ fn addObjCClassSymbol(self: *Dylib, allocator: *Allocator, sym_name: []const u8)
248248 }
249249}
250250
251fn addObjCIVarSymbol(self: *Dylib, allocator: *Allocator, sym_name: []const u8) !void {
251fn addObjCIVarSymbol(self: *Dylib, allocator: Allocator, sym_name: []const u8) !void {
252252 const expanded = try std.fmt.allocPrint(allocator, "_OBJC_IVAR_$_{s}", .{sym_name});
253253 if (self.symbols.contains(expanded)) return;
254254 try self.symbols.putNoClobber(allocator, expanded, .{});
255255}
256256
257fn addObjCEhTypeSymbol(self: *Dylib, allocator: *Allocator, sym_name: []const u8) !void {
257fn addObjCEhTypeSymbol(self: *Dylib, allocator: Allocator, sym_name: []const u8) !void {
258258 const expanded = try std.fmt.allocPrint(allocator, "_OBJC_EHTYPE_$_{s}", .{sym_name});
259259 if (self.symbols.contains(expanded)) return;
260260 try self.symbols.putNoClobber(allocator, expanded, .{});
261261}
262262
263fn addSymbol(self: *Dylib, allocator: *Allocator, sym_name: []const u8) !void {
263fn addSymbol(self: *Dylib, allocator: Allocator, sym_name: []const u8) !void {
264264 if (self.symbols.contains(sym_name)) return;
265265 try self.symbols.putNoClobber(allocator, try allocator.dupe(u8, sym_name), {});
266266}
267267
268268const TargetMatcher = struct {
269 allocator: *Allocator,
269 allocator: Allocator,
270270 target: std.Target,
271271 target_strings: std.ArrayListUnmanaged([]const u8) = .{},
272272
273 fn init(allocator: *Allocator, target: std.Target) !TargetMatcher {
273 fn init(allocator: Allocator, target: std.Target) !TargetMatcher {
274274 var self = TargetMatcher{
275275 .allocator = allocator,
276276 .target = target,
......@@ -297,7 +297,7 @@ const TargetMatcher = struct {
297297 self.target_strings.deinit(self.allocator);
298298 }
299299
300 fn targetToAppleString(allocator: *Allocator, target: std.Target) ![]const u8 {
300 fn targetToAppleString(allocator: Allocator, target: std.Target) ![]const u8 {
301301 const arch = switch (target.cpu.arch) {
302302 .aarch64 => "arm64",
303303 .x86_64 => "x86_64",
......@@ -336,7 +336,7 @@ const TargetMatcher = struct {
336336
337337pub fn parseFromStub(
338338 self: *Dylib,
339 allocator: *Allocator,
339 allocator: Allocator,
340340 target: std.Target,
341341 lib_stub: LibStub,
342342 dependent_libs: anytype,
src/link/MachO/Object.zig+11-11
......@@ -74,7 +74,7 @@ const DebugInfo = struct {
7474 debug_line: []u8,
7575 debug_ranges: []u8,
7676
77 pub fn parseFromObject(allocator: *Allocator, object: *const Object) !?DebugInfo {
77 pub fn parseFromObject(allocator: Allocator, object: *const Object) !?DebugInfo {
7878 var debug_info = blk: {
7979 const index = object.dwarf_debug_info_index orelse return null;
8080 break :blk try object.readSection(allocator, index);
......@@ -118,7 +118,7 @@ const DebugInfo = struct {
118118 };
119119 }
120120
121 pub fn deinit(self: *DebugInfo, allocator: *Allocator) void {
121 pub fn deinit(self: *DebugInfo, allocator: Allocator) void {
122122 allocator.free(self.debug_info);
123123 allocator.free(self.debug_abbrev);
124124 allocator.free(self.debug_str);
......@@ -130,7 +130,7 @@ const DebugInfo = struct {
130130 }
131131};
132132
133pub fn deinit(self: *Object, allocator: *Allocator) void {
133pub fn deinit(self: *Object, allocator: Allocator) void {
134134 for (self.load_commands.items) |*lc| {
135135 lc.deinit(allocator);
136136 }
......@@ -160,7 +160,7 @@ pub fn deinit(self: *Object, allocator: *Allocator) void {
160160 }
161161}
162162
163pub fn free(self: *Object, allocator: *Allocator, macho_file: *MachO) void {
163pub fn free(self: *Object, allocator: Allocator, macho_file: *MachO) void {
164164 log.debug("freeObject {*}", .{self});
165165
166166 var it = self.end_atoms.iterator();
......@@ -227,7 +227,7 @@ fn freeAtoms(self: *Object, macho_file: *MachO) void {
227227 }
228228}
229229
230pub fn parse(self: *Object, allocator: *Allocator, target: std.Target) !void {
230pub fn parse(self: *Object, allocator: Allocator, target: std.Target) !void {
231231 const reader = self.file.reader();
232232 if (self.file_offset) |offset| {
233233 try reader.context.seekTo(offset);
......@@ -263,7 +263,7 @@ pub fn parse(self: *Object, allocator: *Allocator, target: std.Target) !void {
263263 try self.parseDebugInfo(allocator);
264264}
265265
266pub fn readLoadCommands(self: *Object, allocator: *Allocator, reader: anytype) !void {
266pub fn readLoadCommands(self: *Object, allocator: Allocator, reader: anytype) !void {
267267 const header = self.header orelse unreachable; // Unreachable here signifies a fatal unexplored condition.
268268 const offset = self.file_offset orelse 0;
269269
......@@ -381,7 +381,7 @@ fn filterDice(dices: []macho.data_in_code_entry, start_addr: u64, end_addr: u64)
381381 return dices[start..end];
382382}
383383
384pub fn parseIntoAtoms(self: *Object, allocator: *Allocator, macho_file: *MachO) !void {
384pub fn parseIntoAtoms(self: *Object, allocator: Allocator, macho_file: *MachO) !void {
385385 const tracy = trace(@src());
386386 defer tracy.end();
387387
......@@ -555,7 +555,7 @@ pub fn parseIntoAtoms(self: *Object, allocator: *Allocator, macho_file: *MachO)
555555 }
556556}
557557
558fn parseSymtab(self: *Object, allocator: *Allocator) !void {
558fn parseSymtab(self: *Object, allocator: Allocator) !void {
559559 const index = self.symtab_cmd_index orelse return;
560560 const symtab_cmd = self.load_commands.items[index].Symtab;
561561
......@@ -571,7 +571,7 @@ fn parseSymtab(self: *Object, allocator: *Allocator) !void {
571571 try self.strtab.appendSlice(allocator, strtab);
572572}
573573
574pub fn parseDebugInfo(self: *Object, allocator: *Allocator) !void {
574pub fn parseDebugInfo(self: *Object, allocator: Allocator) !void {
575575 log.debug("parsing debug info in '{s}'", .{self.name});
576576
577577 var debug_info = blk: {
......@@ -603,7 +603,7 @@ pub fn parseDebugInfo(self: *Object, allocator: *Allocator) !void {
603603 }
604604}
605605
606pub fn parseDataInCode(self: *Object, allocator: *Allocator) !void {
606pub fn parseDataInCode(self: *Object, allocator: Allocator) !void {
607607 const index = self.data_in_code_cmd_index orelse return;
608608 const data_in_code = self.load_commands.items[index].LinkeditData;
609609
......@@ -623,7 +623,7 @@ pub fn parseDataInCode(self: *Object, allocator: *Allocator) !void {
623623 }
624624}
625625
626fn readSection(self: Object, allocator: *Allocator, index: u16) ![]u8 {
626fn readSection(self: Object, allocator: Allocator, index: u16) ![]u8 {
627627 const seg = self.load_commands.items[self.segment_cmd_index.?].Segment;
628628 const sect = seg.sections.items[index];
629629 var buffer = try allocator.alloc(u8, @intCast(usize, sect.size));
src/link/MachO/Trie.zig+9-9
......@@ -65,7 +65,7 @@ pub const Node = struct {
6565 to: *Node,
6666 label: []u8,
6767
68 fn deinit(self: *Edge, allocator: *Allocator) void {
68 fn deinit(self: *Edge, allocator: Allocator) void {
6969 self.to.deinit(allocator);
7070 allocator.destroy(self.to);
7171 allocator.free(self.label);
......@@ -75,7 +75,7 @@ pub const Node = struct {
7575 }
7676 };
7777
78 fn deinit(self: *Node, allocator: *Allocator) void {
78 fn deinit(self: *Node, allocator: Allocator) void {
7979 for (self.edges.items) |*edge| {
8080 edge.deinit(allocator);
8181 }
......@@ -83,7 +83,7 @@ pub const Node = struct {
8383 }
8484
8585 /// Inserts a new node starting from `self`.
86 fn put(self: *Node, allocator: *Allocator, label: []const u8) !*Node {
86 fn put(self: *Node, allocator: Allocator, label: []const u8) !*Node {
8787 // Check for match with edges from this node.
8888 for (self.edges.items) |*edge| {
8989 const match = mem.indexOfDiff(u8, edge.label, label) orelse return edge.to;
......@@ -126,7 +126,7 @@ pub const Node = struct {
126126 }
127127
128128 /// Recursively parses the node from the input byte stream.
129 fn read(self: *Node, allocator: *Allocator, reader: anytype) Trie.ReadError!usize {
129 fn read(self: *Node, allocator: Allocator, reader: anytype) Trie.ReadError!usize {
130130 self.node_dirty = true;
131131 const trie_offset = try reader.context.getPos();
132132 self.trie_offset = trie_offset;
......@@ -308,7 +308,7 @@ pub const ExportSymbol = struct {
308308/// Insert a symbol into the trie, updating the prefixes in the process.
309309/// This operation may change the layout of the trie by splicing edges in
310310/// certain circumstances.
311pub fn put(self: *Trie, allocator: *Allocator, symbol: ExportSymbol) !void {
311pub fn put(self: *Trie, allocator: Allocator, symbol: ExportSymbol) !void {
312312 try self.createRoot(allocator);
313313 const node = try self.root.?.put(allocator, symbol.name);
314314 node.terminal_info = .{
......@@ -322,7 +322,7 @@ pub fn put(self: *Trie, allocator: *Allocator, symbol: ExportSymbol) !void {
322322/// This step performs multiple passes through the trie ensuring
323323/// there are no gaps after every `Node` is ULEB128 encoded.
324324/// Call this method before trying to `write` the trie to a byte stream.
325pub fn finalize(self: *Trie, allocator: *Allocator) !void {
325pub fn finalize(self: *Trie, allocator: Allocator) !void {
326326 if (!self.trie_dirty) return;
327327
328328 self.ordered_nodes.shrinkRetainingCapacity(0);
......@@ -361,7 +361,7 @@ const ReadError = error{
361361};
362362
363363/// Parse the trie from a byte stream.
364pub fn read(self: *Trie, allocator: *Allocator, reader: anytype) ReadError!usize {
364pub fn read(self: *Trie, allocator: Allocator, reader: anytype) ReadError!usize {
365365 try self.createRoot(allocator);
366366 return self.root.?.read(allocator, reader);
367367}
......@@ -377,7 +377,7 @@ pub fn write(self: Trie, writer: anytype) !u64 {
377377 return counting_writer.bytes_written;
378378}
379379
380pub fn deinit(self: *Trie, allocator: *Allocator) void {
380pub fn deinit(self: *Trie, allocator: Allocator) void {
381381 if (self.root) |root| {
382382 root.deinit(allocator);
383383 allocator.destroy(root);
......@@ -385,7 +385,7 @@ pub fn deinit(self: *Trie, allocator: *Allocator) void {
385385 self.ordered_nodes.deinit(allocator);
386386}
387387
388fn createRoot(self: *Trie, allocator: *Allocator) !void {
388fn createRoot(self: *Trie, allocator: Allocator) !void {
389389 if (self.root == null) {
390390 const root = try allocator.create(Node);
391391 root.* = .{ .base = self };
src/link/MachO/commands.zig+8-8
......@@ -50,7 +50,7 @@ pub const LoadCommand = union(enum) {
5050 Rpath: GenericCommandWithData(macho.rpath_command),
5151 Unknown: GenericCommandWithData(macho.load_command),
5252
53 pub fn read(allocator: *Allocator, reader: anytype) !LoadCommand {
53 pub fn read(allocator: Allocator, reader: anytype) !LoadCommand {
5454 const header = try reader.readStruct(macho.load_command);
5555 var buffer = try allocator.alloc(u8, header.cmdsize);
5656 defer allocator.free(buffer);
......@@ -177,7 +177,7 @@ pub const LoadCommand = union(enum) {
177177 };
178178 }
179179
180 pub fn deinit(self: *LoadCommand, allocator: *Allocator) void {
180 pub fn deinit(self: *LoadCommand, allocator: Allocator) void {
181181 return switch (self.*) {
182182 .Segment => |*x| x.deinit(allocator),
183183 .Dylinker => |*x| x.deinit(allocator),
......@@ -218,7 +218,7 @@ pub const SegmentCommand = struct {
218218 inner: macho.segment_command_64,
219219 sections: std.ArrayListUnmanaged(macho.section_64) = .{},
220220
221 pub fn read(alloc: *Allocator, reader: anytype) !SegmentCommand {
221 pub fn read(alloc: Allocator, reader: anytype) !SegmentCommand {
222222 const inner = try reader.readStruct(macho.segment_command_64);
223223 var segment = SegmentCommand{
224224 .inner = inner,
......@@ -241,7 +241,7 @@ pub const SegmentCommand = struct {
241241 }
242242 }
243243
244 pub fn deinit(self: *SegmentCommand, alloc: *Allocator) void {
244 pub fn deinit(self: *SegmentCommand, alloc: Allocator) void {
245245 self.sections.deinit(alloc);
246246 }
247247
......@@ -299,7 +299,7 @@ pub fn GenericCommandWithData(comptime Cmd: type) type {
299299
300300 const Self = @This();
301301
302 pub fn read(allocator: *Allocator, reader: anytype) !Self {
302 pub fn read(allocator: Allocator, reader: anytype) !Self {
303303 const inner = try reader.readStruct(Cmd);
304304 var data = try allocator.alloc(u8, inner.cmdsize - @sizeOf(Cmd));
305305 errdefer allocator.free(data);
......@@ -315,7 +315,7 @@ pub fn GenericCommandWithData(comptime Cmd: type) type {
315315 try writer.writeAll(self.data);
316316 }
317317
318 pub fn deinit(self: *Self, allocator: *Allocator) void {
318 pub fn deinit(self: *Self, allocator: Allocator) void {
319319 allocator.free(self.data);
320320 }
321321
......@@ -327,7 +327,7 @@ pub fn GenericCommandWithData(comptime Cmd: type) type {
327327}
328328
329329pub fn createLoadDylibCommand(
330 allocator: *Allocator,
330 allocator: Allocator,
331331 name: []const u8,
332332 timestamp: u32,
333333 current_version: u32,
......@@ -395,7 +395,7 @@ pub fn sectionIsDontDeadStripIfReferencesLive(sect: macho.section_64) bool {
395395 return sectionAttrs(sect) & macho.S_ATTR_LIVE_SUPPORT != 0;
396396}
397397
398fn testRead(allocator: *Allocator, buffer: []const u8, expected: anytype) !void {
398fn testRead(allocator: Allocator, buffer: []const u8, expected: anytype) !void {
399399 var stream = io.fixedBufferStream(buffer);
400400 var given = try LoadCommand.read(allocator, stream.reader());
401401 defer given.deinit(allocator);
src/link/Plan9.zig+3-3
......@@ -132,7 +132,7 @@ pub fn defaultBaseAddrs(arch: std.Target.Cpu.Arch) Bases {
132132
133133pub const PtrWidth = enum { p32, p64 };
134134
135pub fn createEmpty(gpa: *Allocator, options: link.Options) !*Plan9 {
135pub fn createEmpty(gpa: Allocator, options: link.Options) !*Plan9 {
136136 if (options.use_llvm)
137137 return error.LLVMBackendDoesNotSupportPlan9;
138138 const sixtyfour_bit: bool = switch (options.target.cpu.arch.ptrBitWidth()) {
......@@ -168,7 +168,7 @@ fn putFn(self: *Plan9, decl: *Module.Decl, out: FnDeclOutput) !void {
168168 try fn_map_res.value_ptr.functions.put(gpa, decl, out);
169169 } else {
170170 const file = decl.getFileScope();
171 const arena = &self.path_arena.allocator;
171 const arena = self.path_arena.allocator();
172172 // each file gets a symbol
173173 fn_map_res.value_ptr.* = .{
174174 .sym_index = blk: {
......@@ -621,7 +621,7 @@ pub fn deinit(self: *Plan9) void {
621621
622622pub const Export = ?usize;
623623pub const base_tag = .plan9;
624pub fn openPath(allocator: *Allocator, sub_path: []const u8, options: link.Options) !*Plan9 {
624pub fn openPath(allocator: Allocator, sub_path: []const u8, options: link.Options) !*Plan9 {
625625 if (options.use_llvm)
626626 return error.LLVMBackendDoesNotSupportPlan9;
627627 assert(options.object_format == .plan9);
src/link/SpirV.zig+2-2
......@@ -58,7 +58,7 @@ const DeclGenContext = struct {
5858 liveness: Liveness,
5959};
6060
61pub fn createEmpty(gpa: *Allocator, options: link.Options) !*SpirV {
61pub fn createEmpty(gpa: Allocator, options: link.Options) !*SpirV {
6262 const spirv = try gpa.create(SpirV);
6363 spirv.* = .{
6464 .base = .{
......@@ -87,7 +87,7 @@ pub fn createEmpty(gpa: *Allocator, options: link.Options) !*SpirV {
8787 return spirv;
8888}
8989
90pub fn openPath(allocator: *Allocator, sub_path: []const u8, options: link.Options) !*SpirV {
90pub fn openPath(allocator: Allocator, sub_path: []const u8, options: link.Options) !*SpirV {
9191 assert(options.object_format == .spirv);
9292
9393 if (options.use_llvm) return error.LLVM_BackendIsTODO_ForSpirV; // TODO: LLVM Doesn't support SpirV at all.
src/link/Wasm.zig+3-3
......@@ -97,7 +97,7 @@ pub const FnData = struct {
9797 };
9898};
9999
100pub fn openPath(allocator: *Allocator, sub_path: []const u8, options: link.Options) !*Wasm {
100pub fn openPath(allocator: Allocator, sub_path: []const u8, options: link.Options) !*Wasm {
101101 assert(options.object_format == .wasm);
102102
103103 if (build_options.have_llvm and options.use_llvm) {
......@@ -138,7 +138,7 @@ pub fn openPath(allocator: *Allocator, sub_path: []const u8, options: link.Optio
138138 return wasm_bin;
139139}
140140
141pub fn createEmpty(gpa: *Allocator, options: link.Options) !*Wasm {
141pub fn createEmpty(gpa: Allocator, options: link.Options) !*Wasm {
142142 const wasm_bin = try gpa.create(Wasm);
143143 wasm_bin.* = .{
144144 .base = .{
......@@ -950,7 +950,7 @@ fn linkWithLLD(self: *Wasm, comp: *Compilation) !void {
950950
951951 var arena_allocator = std.heap.ArenaAllocator.init(self.base.allocator);
952952 defer arena_allocator.deinit();
953 const arena = &arena_allocator.allocator;
953 const arena = arena_allocator.allocator();
954954
955955 const directory = self.base.options.emit.?.directory; // Just an alias to make it shorter to type.
956956
src/link/Wasm/Atom.zig+1-1
......@@ -42,7 +42,7 @@ pub const empty: Atom = .{
4242};
4343
4444/// Frees all resources owned by this `Atom`.
45pub fn deinit(self: *Atom, gpa: *Allocator) void {
45pub fn deinit(self: *Atom, gpa: Allocator) void {
4646 self.relocs.deinit(gpa);
4747 self.code.deinit(gpa);
4848}
src/link/tapi.zig+5-5
......@@ -106,7 +106,7 @@ pub const LibStub = struct {
106106 /// Typed contents of the tbd file.
107107 inner: []Tbd,
108108
109 pub fn loadFromFile(allocator: *Allocator, file: fs.File) !LibStub {
109 pub fn loadFromFile(allocator: Allocator, file: fs.File) !LibStub {
110110 const source = try file.readToEndAlloc(allocator, std.math.maxInt(u32));
111111 defer allocator.free(source);
112112
......@@ -120,7 +120,7 @@ pub const LibStub = struct {
120120 err: {
121121 log.debug("trying to parse as []TbdV4", .{});
122122 const inner = lib_stub.yaml.parse([]TbdV4) catch break :err;
123 var out = try lib_stub.yaml.arena.allocator.alloc(Tbd, inner.len);
123 var out = try lib_stub.yaml.arena.allocator().alloc(Tbd, inner.len);
124124 for (inner) |doc, i| {
125125 out[i] = .{ .v4 = doc };
126126 }
......@@ -130,7 +130,7 @@ pub const LibStub = struct {
130130 err: {
131131 log.debug("trying to parse as TbdV4", .{});
132132 const inner = lib_stub.yaml.parse(TbdV4) catch break :err;
133 var out = try lib_stub.yaml.arena.allocator.alloc(Tbd, 1);
133 var out = try lib_stub.yaml.arena.allocator().alloc(Tbd, 1);
134134 out[0] = .{ .v4 = inner };
135135 break :blk out;
136136 }
......@@ -138,7 +138,7 @@ pub const LibStub = struct {
138138 err: {
139139 log.debug("trying to parse as []TbdV3", .{});
140140 const inner = lib_stub.yaml.parse([]TbdV3) catch break :err;
141 var out = try lib_stub.yaml.arena.allocator.alloc(Tbd, inner.len);
141 var out = try lib_stub.yaml.arena.allocator().alloc(Tbd, inner.len);
142142 for (inner) |doc, i| {
143143 out[i] = .{ .v3 = doc };
144144 }
......@@ -148,7 +148,7 @@ pub const LibStub = struct {
148148 err: {
149149 log.debug("trying to parse as TbdV3", .{});
150150 const inner = lib_stub.yaml.parse(TbdV3) catch break :err;
151 var out = try lib_stub.yaml.arena.allocator.alloc(Tbd, 1);
151 var out = try lib_stub.yaml.arena.allocator().alloc(Tbd, 1);
152152 out[0] = .{ .v3 = inner };
153153 break :blk out;
154154 }
src/link/tapi/parse.zig+7-7
......@@ -37,7 +37,7 @@ pub const Node = struct {
3737 return @fieldParentPtr(T, "base", self);
3838 }
3939
40 pub fn deinit(self: *Node, allocator: *Allocator) void {
40 pub fn deinit(self: *Node, allocator: Allocator) void {
4141 switch (self.tag) {
4242 .doc => @fieldParentPtr(Node.Doc, "base", self).deinit(allocator),
4343 .map => @fieldParentPtr(Node.Map, "base", self).deinit(allocator),
......@@ -69,7 +69,7 @@ pub const Node = struct {
6969
7070 pub const base_tag: Node.Tag = .doc;
7171
72 pub fn deinit(self: *Doc, allocator: *Allocator) void {
72 pub fn deinit(self: *Doc, allocator: Allocator) void {
7373 if (self.value) |node| {
7474 node.deinit(allocator);
7575 allocator.destroy(node);
......@@ -113,7 +113,7 @@ pub const Node = struct {
113113 value: *Node,
114114 };
115115
116 pub fn deinit(self: *Map, allocator: *Allocator) void {
116 pub fn deinit(self: *Map, allocator: Allocator) void {
117117 for (self.values.items) |entry| {
118118 entry.value.deinit(allocator);
119119 allocator.destroy(entry.value);
......@@ -149,7 +149,7 @@ pub const Node = struct {
149149
150150 pub const base_tag: Node.Tag = .list;
151151
152 pub fn deinit(self: *List, allocator: *Allocator) void {
152 pub fn deinit(self: *List, allocator: Allocator) void {
153153 for (self.values.items) |node| {
154154 node.deinit(allocator);
155155 allocator.destroy(node);
......@@ -198,12 +198,12 @@ pub const Node = struct {
198198};
199199
200200pub const Tree = struct {
201 allocator: *Allocator,
201 allocator: Allocator,
202202 source: []const u8,
203203 tokens: []Token,
204204 docs: std.ArrayListUnmanaged(*Node) = .{},
205205
206 pub fn init(allocator: *Allocator) Tree {
206 pub fn init(allocator: Allocator) Tree {
207207 return .{
208208 .allocator = allocator,
209209 .source = undefined,
......@@ -266,7 +266,7 @@ pub const Tree = struct {
266266};
267267
268268const Parser = struct {
269 allocator: *Allocator,
269 allocator: Allocator,
270270 tree: *Tree,
271271 token_it: *TokenIterator,
272272 scopes: std.ArrayListUnmanaged(Scope) = .{},
src/link/tapi/yaml.zig+9-8
......@@ -149,7 +149,7 @@ pub const Value = union(ValueType) {
149149 };
150150 }
151151
152 fn fromNode(arena: *Allocator, tree: *const Tree, node: *const Node, type_hint: ?ValueType) YamlError!Value {
152 fn fromNode(arena: Allocator, tree: *const Tree, node: *const Node, type_hint: ?ValueType) YamlError!Value {
153153 if (node.cast(Node.Doc)) |doc| {
154154 const inner = doc.value orelse {
155155 // empty doc
......@@ -246,17 +246,18 @@ pub const Yaml = struct {
246246 }
247247 }
248248
249 pub fn load(allocator: *Allocator, source: []const u8) !Yaml {
249 pub fn load(allocator: Allocator, source: []const u8) !Yaml {
250250 var arena = ArenaAllocator.init(allocator);
251 const arena_allocator = arena.allocator();
251252
252 var tree = Tree.init(&arena.allocator);
253 var tree = Tree.init(arena_allocator);
253254 try tree.parse(source);
254255
255 var docs = std.ArrayList(Value).init(&arena.allocator);
256 var docs = std.ArrayList(Value).init(arena_allocator);
256257 try docs.ensureUnusedCapacity(tree.docs.items.len);
257258
258259 for (tree.docs.items) |node| {
259 const value = try Value.fromNode(&arena.allocator, &tree, node, null);
260 const value = try Value.fromNode(arena_allocator, &tree, node, null);
260261 docs.appendAssumeCapacity(value);
261262 }
262263
......@@ -299,7 +300,7 @@ pub const Yaml = struct {
299300 .Pointer => |info| {
300301 switch (info.size) {
301302 .Slice => {
302 var parsed = try self.arena.allocator.alloc(info.child, self.docs.items.len);
303 var parsed = try self.arena.allocator().alloc(info.child, self.docs.items.len);
303304 for (self.docs.items) |doc, i| {
304305 parsed[i] = try self.parseValue(info.child, doc);
305306 }
......@@ -361,7 +362,7 @@ pub const Yaml = struct {
361362
362363 inline for (struct_info.fields) |field| {
363364 const value: ?Value = map.get(field.name) orelse blk: {
364 const field_name = try mem.replaceOwned(u8, &self.arena.allocator, field.name, "_", "-");
365 const field_name = try mem.replaceOwned(u8, self.arena.allocator(), field.name, "_", "-");
365366 break :blk map.get(field_name);
366367 };
367368
......@@ -382,7 +383,7 @@ pub const Yaml = struct {
382383
383384 fn parsePointer(self: *Yaml, comptime T: type, value: Value) Error!T {
384385 const ptr_info = @typeInfo(T).Pointer;
385 const arena = &self.arena.allocator;
386 const arena = self.arena.allocator();
386387
387388 switch (ptr_info.size) {
388389 .Slice => {
src/main.zig+36-36
......@@ -139,7 +139,7 @@ pub fn main() anyerror!void {
139139 const gpa = gpa: {
140140 if (!builtin.link_libc) {
141141 gpa_need_deinit = true;
142 break :gpa &general_purpose_allocator.allocator;
142 break :gpa general_purpose_allocator.allocator();
143143 }
144144 // We would prefer to use raw libc allocator here, but cannot
145145 // use it if it won't support the alignment we need.
......@@ -153,19 +153,19 @@ pub fn main() anyerror!void {
153153 };
154154 var arena_instance = std.heap.ArenaAllocator.init(gpa);
155155 defer arena_instance.deinit();
156 const arena = &arena_instance.allocator;
156 const arena = arena_instance.allocator();
157157
158158 const args = try process.argsAlloc(arena);
159159
160160 if (tracy.enable_allocation) {
161161 var gpa_tracy = tracy.tracyAllocator(gpa);
162 return mainArgs(&gpa_tracy.allocator, arena, args);
162 return mainArgs(gpa_tracy.allocator(), arena, args);
163163 }
164164
165165 return mainArgs(gpa, arena, args);
166166}
167167
168pub fn mainArgs(gpa: *Allocator, arena: *Allocator, args: []const []const u8) !void {
168pub fn mainArgs(gpa: Allocator, arena: Allocator, args: []const []const u8) !void {
169169 if (args.len <= 1) {
170170 std.log.info("{s}", .{usage});
171171 fatal("expected command argument", .{});
......@@ -536,7 +536,7 @@ const Emit = union(enum) {
536536 }
537537};
538538
539fn optionalStringEnvVar(arena: *Allocator, name: []const u8) !?[]const u8 {
539fn optionalStringEnvVar(arena: Allocator, name: []const u8) !?[]const u8 {
540540 if (std.process.getEnvVarOwned(arena, name)) |value| {
541541 return value;
542542 } else |err| switch (err) {
......@@ -555,8 +555,8 @@ const ArgMode = union(enum) {
555555};
556556
557557fn buildOutputType(
558 gpa: *Allocator,
559 arena: *Allocator,
558 gpa: Allocator,
559 arena: Allocator,
560560 all_args: []const []const u8,
561561 arg_mode: ArgMode,
562562) !void {
......@@ -2648,7 +2648,7 @@ fn buildOutputType(
26482648}
26492649
26502650fn parseCrossTargetOrReportFatalError(
2651 allocator: *Allocator,
2651 allocator: Allocator,
26522652 opts: std.zig.CrossTarget.ParseOptions,
26532653) !std.zig.CrossTarget {
26542654 var opts_with_diags = opts;
......@@ -2689,8 +2689,8 @@ fn parseCrossTargetOrReportFatalError(
26892689
26902690fn runOrTest(
26912691 comp: *Compilation,
2692 gpa: *Allocator,
2693 arena: *Allocator,
2692 gpa: Allocator,
2693 arena: Allocator,
26942694 emit_bin_loc: ?Compilation.EmitLoc,
26952695 test_exec_args: []const ?[]const u8,
26962696 self_exe_path: []const u8,
......@@ -2821,7 +2821,7 @@ const AfterUpdateHook = union(enum) {
28212821 update: []const u8,
28222822};
28232823
2824fn updateModule(gpa: *Allocator, comp: *Compilation, hook: AfterUpdateHook) !void {
2824fn updateModule(gpa: Allocator, comp: *Compilation, hook: AfterUpdateHook) !void {
28252825 try comp.update();
28262826
28272827 var errors = try comp.getAllErrorsAlloc();
......@@ -2875,7 +2875,7 @@ fn updateModule(gpa: *Allocator, comp: *Compilation, hook: AfterUpdateHook) !voi
28752875 }
28762876}
28772877
2878fn freePkgTree(gpa: *Allocator, pkg: *Package, free_parent: bool) void {
2878fn freePkgTree(gpa: Allocator, pkg: *Package, free_parent: bool) void {
28792879 {
28802880 var it = pkg.table.valueIterator();
28812881 while (it.next()) |value| {
......@@ -2887,7 +2887,7 @@ fn freePkgTree(gpa: *Allocator, pkg: *Package, free_parent: bool) void {
28872887 }
28882888}
28892889
2890fn cmdTranslateC(comp: *Compilation, arena: *Allocator, enable_cache: bool) !void {
2890fn cmdTranslateC(comp: *Compilation, arena: Allocator, enable_cache: bool) !void {
28912891 if (!build_options.have_llvm)
28922892 fatal("cannot translate-c: compiler built without LLVM extensions", .{});
28932893
......@@ -3034,7 +3034,7 @@ pub const usage_libc =
30343034 \\
30353035;
30363036
3037pub fn cmdLibC(gpa: *Allocator, args: []const []const u8) !void {
3037pub fn cmdLibC(gpa: Allocator, args: []const []const u8) !void {
30383038 var input_file: ?[]const u8 = null;
30393039 var target_arch_os_abi: []const u8 = "native";
30403040 {
......@@ -3103,8 +3103,8 @@ pub const usage_init =
31033103;
31043104
31053105pub fn cmdInit(
3106 gpa: *Allocator,
3107 arena: *Allocator,
3106 gpa: Allocator,
3107 arena: Allocator,
31083108 args: []const []const u8,
31093109 output_mode: std.builtin.OutputMode,
31103110) !void {
......@@ -3199,7 +3199,7 @@ pub const usage_build =
31993199 \\
32003200;
32013201
3202pub fn cmdBuild(gpa: *Allocator, arena: *Allocator, args: []const []const u8) !void {
3202pub fn cmdBuild(gpa: Allocator, arena: Allocator, args: []const []const u8) !void {
32033203 var prominent_compile_errors: bool = false;
32043204
32053205 // We want to release all the locks before executing the child process, so we make a nice
......@@ -3439,7 +3439,7 @@ pub fn cmdBuild(gpa: *Allocator, arena: *Allocator, args: []const []const u8) !v
34393439 }
34403440}
34413441
3442fn argvCmd(allocator: *Allocator, argv: []const []const u8) ![]u8 {
3442fn argvCmd(allocator: Allocator, argv: []const []const u8) ![]u8 {
34433443 var cmd = std.ArrayList(u8).init(allocator);
34443444 defer cmd.deinit();
34453445 for (argv[0 .. argv.len - 1]) |arg| {
......@@ -3451,7 +3451,7 @@ fn argvCmd(allocator: *Allocator, argv: []const []const u8) ![]u8 {
34513451}
34523452
34533453fn readSourceFileToEndAlloc(
3454 allocator: *mem.Allocator,
3454 allocator: mem.Allocator,
34553455 input: *const fs.File,
34563456 size_hint: ?usize,
34573457) ![:0]u8 {
......@@ -3521,14 +3521,14 @@ const Fmt = struct {
35213521 any_error: bool,
35223522 check_ast: bool,
35233523 color: Color,
3524 gpa: *Allocator,
3525 arena: *Allocator,
3524 gpa: Allocator,
3525 arena: Allocator,
35263526 out_buffer: std.ArrayList(u8),
35273527
35283528 const SeenMap = std.AutoHashMap(fs.File.INode, void);
35293529};
35303530
3531pub fn cmdFmt(gpa: *Allocator, arena: *Allocator, args: []const []const u8) !void {
3531pub fn cmdFmt(gpa: Allocator, arena: Allocator, args: []const []const u8) !void {
35323532 var color: Color = .auto;
35333533 var stdin_flag: bool = false;
35343534 var check_flag: bool = false;
......@@ -3622,7 +3622,7 @@ pub fn cmdFmt(gpa: *Allocator, arena: *Allocator, args: []const []const u8) !voi
36223622 var errors = std.ArrayList(Compilation.AllErrors.Message).init(gpa);
36233623 defer errors.deinit();
36243624
3625 try Compilation.AllErrors.addZir(&arena_instance.allocator, &errors, &file);
3625 try Compilation.AllErrors.addZir(arena_instance.allocator(), &errors, &file);
36263626 const ttyconf: std.debug.TTY.Config = switch (color) {
36273627 .auto => std.debug.detectTTYConfig(),
36283628 .on => .escape_codes,
......@@ -3821,7 +3821,7 @@ fn fmtPathFile(
38213821 var errors = std.ArrayList(Compilation.AllErrors.Message).init(fmt.gpa);
38223822 defer errors.deinit();
38233823
3824 try Compilation.AllErrors.addZir(&arena_instance.allocator, &errors, &file);
3824 try Compilation.AllErrors.addZir(arena_instance.allocator(), &errors, &file);
38253825 const ttyconf: std.debug.TTY.Config = switch (fmt.color) {
38263826 .auto => std.debug.detectTTYConfig(),
38273827 .on => .escape_codes,
......@@ -3858,8 +3858,8 @@ fn fmtPathFile(
38583858}
38593859
38603860fn printErrMsgToStdErr(
3861 gpa: *mem.Allocator,
3862 arena: *mem.Allocator,
3861 gpa: mem.Allocator,
3862 arena: mem.Allocator,
38633863 parse_error: Ast.Error,
38643864 tree: Ast,
38653865 path: []const u8,
......@@ -3941,7 +3941,7 @@ extern "c" fn ZigClang_main(argc: c_int, argv: [*:null]?[*:0]u8) c_int;
39413941extern "c" fn ZigLlvmAr_main(argc: c_int, argv: [*:null]?[*:0]u8) c_int;
39423942
39433943/// TODO https://github.com/ziglang/zig/issues/3257
3944fn punt_to_clang(arena: *Allocator, args: []const []const u8) error{OutOfMemory} {
3944fn punt_to_clang(arena: Allocator, args: []const []const u8) error{OutOfMemory} {
39453945 if (!build_options.have_llvm)
39463946 fatal("`zig cc` and `zig c++` unavailable: compiler built without LLVM extensions", .{});
39473947 // Convert the args to the format Clang expects.
......@@ -3955,7 +3955,7 @@ fn punt_to_clang(arena: *Allocator, args: []const []const u8) error{OutOfMemory}
39553955}
39563956
39573957/// TODO https://github.com/ziglang/zig/issues/3257
3958fn punt_to_llvm_ar(arena: *Allocator, args: []const []const u8) error{OutOfMemory} {
3958fn punt_to_llvm_ar(arena: Allocator, args: []const []const u8) error{OutOfMemory} {
39593959 if (!build_options.have_llvm)
39603960 fatal("`zig ar`, `zig dlltool`, `zig ranlib', and `zig lib` unavailable: compiler built without LLVM extensions", .{});
39613961
......@@ -3976,7 +3976,7 @@ fn punt_to_llvm_ar(arena: *Allocator, args: []const []const u8) error{OutOfMemor
39763976/// * `lld-link` - COFF
39773977/// * `wasm-ld` - WebAssembly
39783978/// TODO https://github.com/ziglang/zig/issues/3257
3979pub fn punt_to_lld(arena: *Allocator, args: []const []const u8) error{OutOfMemory} {
3979pub fn punt_to_lld(arena: Allocator, args: []const []const u8) error{OutOfMemory} {
39803980 if (!build_options.have_llvm)
39813981 fatal("`zig {s}` unavailable: compiler built without LLVM extensions", .{args[0]});
39823982 // Convert the args to the format LLD expects.
......@@ -4012,7 +4012,7 @@ pub const ClangArgIterator = struct {
40124012 argv: []const []const u8,
40134013 next_index: usize,
40144014 root_args: ?*Args,
4015 allocator: *Allocator,
4015 allocator: Allocator,
40164016
40174017 pub const ZigEquivalent = enum {
40184018 target,
......@@ -4072,7 +4072,7 @@ pub const ClangArgIterator = struct {
40724072 argv: []const []const u8,
40734073 };
40744074
4075 fn init(allocator: *Allocator, argv: []const []const u8) ClangArgIterator {
4075 fn init(allocator: Allocator, argv: []const []const u8) ClangArgIterator {
40764076 return .{
40774077 .next_index = 2, // `zig cc foo` this points to `foo`
40784078 .has_next = argv.len > 2,
......@@ -4311,7 +4311,7 @@ test "fds" {
43114311 gimmeMoreOfThoseSweetSweetFileDescriptors();
43124312}
43134313
4314fn detectNativeTargetInfo(gpa: *Allocator, cross_target: std.zig.CrossTarget) !std.zig.system.NativeTargetInfo {
4314fn detectNativeTargetInfo(gpa: Allocator, cross_target: std.zig.CrossTarget) !std.zig.system.NativeTargetInfo {
43154315 return std.zig.system.NativeTargetInfo.detect(gpa, cross_target);
43164316}
43174317
......@@ -4346,8 +4346,8 @@ const usage_ast_check =
43464346;
43474347
43484348pub fn cmdAstCheck(
4349 gpa: *Allocator,
4350 arena: *Allocator,
4349 gpa: Allocator,
4350 arena: Allocator,
43514351 args: []const []const u8,
43524352) !void {
43534353 const Module = @import("Module.zig");
......@@ -4516,8 +4516,8 @@ pub fn cmdAstCheck(
45164516
45174517/// This is only enabled for debug builds.
45184518pub fn cmdChangelist(
4519 gpa: *Allocator,
4520 arena: *Allocator,
4519 gpa: Allocator,
4520 arena: Allocator,
45214521 args: []const []const u8,
45224522) !void {
45234523 const Module = @import("Module.zig");
src/mingw.zig+4-4
......@@ -25,7 +25,7 @@ pub fn buildCRTFile(comp: *Compilation, crt_file: CRTFile) !void {
2525 }
2626 var arena_allocator = std.heap.ArenaAllocator.init(comp.gpa);
2727 defer arena_allocator.deinit();
28 const arena = &arena_allocator.allocator;
28 const arena = arena_allocator.allocator();
2929
3030 switch (crt_file) {
3131 .crt2_o => {
......@@ -252,7 +252,7 @@ pub fn buildCRTFile(comp: *Compilation, crt_file: CRTFile) !void {
252252
253253fn add_cc_args(
254254 comp: *Compilation,
255 arena: *Allocator,
255 arena: Allocator,
256256 args: *std.ArrayList([]const u8),
257257) error{OutOfMemory}!void {
258258 try args.appendSlice(&[_][]const u8{
......@@ -281,7 +281,7 @@ fn add_cc_args(
281281pub fn buildImportLib(comp: *Compilation, lib_name: []const u8) !void {
282282 var arena_allocator = std.heap.ArenaAllocator.init(comp.gpa);
283283 defer arena_allocator.deinit();
284 const arena = &arena_allocator.allocator;
284 const arena = arena_allocator.allocator();
285285
286286 const def_file_path = findDef(comp, arena, lib_name) catch |err| switch (err) {
287287 error.FileNotFound => {
......@@ -428,7 +428,7 @@ pub fn buildImportLib(comp: *Compilation, lib_name: []const u8) !void {
428428}
429429
430430/// This function body is verbose but all it does is test 3 different paths and see if a .def file exists.
431fn findDef(comp: *Compilation, allocator: *Allocator, lib_name: []const u8) ![]u8 {
431fn findDef(comp: *Compilation, allocator: Allocator, lib_name: []const u8) ![]u8 {
432432 const target = comp.getTarget();
433433
434434 const lib_path = switch (target.cpu.arch) {
src/musl.zig+4-4
......@@ -25,7 +25,7 @@ pub fn buildCRTFile(comp: *Compilation, crt_file: CRTFile) !void {
2525 const gpa = comp.gpa;
2626 var arena_allocator = std.heap.ArenaAllocator.init(gpa);
2727 defer arena_allocator.deinit();
28 const arena = &arena_allocator.allocator;
28 const arena = arena_allocator.allocator();
2929
3030 switch (crt_file) {
3131 .crti_o => {
......@@ -310,7 +310,7 @@ const Ext = enum {
310310 o3,
311311};
312312
313fn addSrcFile(arena: *Allocator, source_table: *std.StringArrayHashMap(Ext), file_path: []const u8) !void {
313fn addSrcFile(arena: Allocator, source_table: *std.StringArrayHashMap(Ext), file_path: []const u8) !void {
314314 const ext: Ext = ext: {
315315 if (mem.endsWith(u8, file_path, ".c")) {
316316 if (mem.startsWith(u8, file_path, "musl/src/malloc/") or
......@@ -344,7 +344,7 @@ fn addSrcFile(arena: *Allocator, source_table: *std.StringArrayHashMap(Ext), fil
344344
345345fn addCcArgs(
346346 comp: *Compilation,
347 arena: *Allocator,
347 arena: Allocator,
348348 args: *std.ArrayList([]const u8),
349349 want_O3: bool,
350350) error{OutOfMemory}!void {
......@@ -394,7 +394,7 @@ fn addCcArgs(
394394 });
395395}
396396
397fn start_asm_path(comp: *Compilation, arena: *Allocator, basename: []const u8) ![]const u8 {
397fn start_asm_path(comp: *Compilation, arena: Allocator, basename: []const u8) ![]const u8 {
398398 const target = comp.getTarget();
399399 return comp.zig_lib_directory.join(arena, &[_][]const u8{
400400 "libc", "musl", "crt", archName(target.cpu.arch), basename,
src/print_air.zig+4-4
......@@ -8,7 +8,7 @@ const Zir = @import("Zir.zig");
88const Air = @import("Air.zig");
99const Liveness = @import("Liveness.zig");
1010
11pub fn dump(gpa: *Allocator, air: Air, zir: Zir, liveness: Liveness) void {
11pub fn dump(gpa: Allocator, air: Air, zir: Zir, liveness: Liveness) void {
1212 const instruction_bytes = air.instructions.len *
1313 // Here we don't use @sizeOf(Air.Inst.Data) because it would include
1414 // the debug safety tag but we want to measure release size.
......@@ -47,7 +47,7 @@ pub fn dump(gpa: *Allocator, air: Air, zir: Zir, liveness: Liveness) void {
4747
4848 var writer: Writer = .{
4949 .gpa = gpa,
50 .arena = &arena.allocator,
50 .arena = arena.allocator(),
5151 .air = air,
5252 .zir = zir,
5353 .liveness = liveness,
......@@ -60,8 +60,8 @@ pub fn dump(gpa: *Allocator, air: Air, zir: Zir, liveness: Liveness) void {
6060}
6161
6262const Writer = struct {
63 gpa: *Allocator,
64 arena: *Allocator,
63 gpa: Allocator,
64 arena: Allocator,
6565 air: Air,
6666 zir: Zir,
6767 liveness: Liveness,
src/print_env.zig+1-1
......@@ -4,7 +4,7 @@ const introspect = @import("introspect.zig");
44const Allocator = std.mem.Allocator;
55const fatal = @import("main.zig").fatal;
66
7pub fn cmdEnv(gpa: *Allocator, args: []const []const u8, stdout: std.fs.File.Writer) !void {
7pub fn cmdEnv(gpa: Allocator, args: []const []const u8, stdout: std.fs.File.Writer) !void {
88 _ = args;
99 const self_exe_path = try std.fs.selfExePathAlloc(gpa);
1010 defer gpa.free(self_exe_path);
src/print_targets.zig+1-1
......@@ -11,7 +11,7 @@ const introspect = @import("introspect.zig");
1111const fatal = @import("main.zig").fatal;
1212
1313pub fn cmdTargets(
14 allocator: *Allocator,
14 allocator: Allocator,
1515 args: []const []const u8,
1616 /// Output stream
1717 stdout: anytype,
src/print_zir.zig+8-8
......@@ -10,7 +10,7 @@ const LazySrcLoc = Module.LazySrcLoc;
1010
1111/// Write human-readable, debug formatted ZIR code to a file.
1212pub fn renderAsTextToFile(
13 gpa: *Allocator,
13 gpa: Allocator,
1414 scope_file: *Module.File,
1515 fs_file: std.fs.File,
1616) !void {
......@@ -19,7 +19,7 @@ pub fn renderAsTextToFile(
1919
2020 var writer: Writer = .{
2121 .gpa = gpa,
22 .arena = &arena.allocator,
22 .arena = arena.allocator(),
2323 .file = scope_file,
2424 .code = scope_file.zir,
2525 .indent = 0,
......@@ -61,7 +61,7 @@ pub fn renderAsTextToFile(
6161}
6262
6363pub fn renderInstructionContext(
64 gpa: *Allocator,
64 gpa: Allocator,
6565 block: []const Zir.Inst.Index,
6666 block_index: usize,
6767 scope_file: *Module.File,
......@@ -74,7 +74,7 @@ pub fn renderInstructionContext(
7474
7575 var writer: Writer = .{
7676 .gpa = gpa,
77 .arena = &arena.allocator,
77 .arena = arena.allocator(),
7878 .file = scope_file,
7979 .code = scope_file.zir,
8080 .indent = if (indent < 2) 2 else indent,
......@@ -94,7 +94,7 @@ pub fn renderInstructionContext(
9494}
9595
9696pub fn renderSingleInstruction(
97 gpa: *Allocator,
97 gpa: Allocator,
9898 inst: Zir.Inst.Index,
9999 scope_file: *Module.File,
100100 parent_decl_node: Ast.Node.Index,
......@@ -106,7 +106,7 @@ pub fn renderSingleInstruction(
106106
107107 var writer: Writer = .{
108108 .gpa = gpa,
109 .arena = &arena.allocator,
109 .arena = arena.allocator(),
110110 .file = scope_file,
111111 .code = scope_file.zir,
112112 .indent = indent,
......@@ -120,8 +120,8 @@ pub fn renderSingleInstruction(
120120}
121121
122122const Writer = struct {
123 gpa: *Allocator,
124 arena: *Allocator,
123 gpa: Allocator,
124 arena: Allocator,
125125 file: *Module.File,
126126 code: Zir,
127127 indent: u32,
src/register_manager.zig+1-1
......@@ -254,7 +254,7 @@ const MockRegister2 = enum(u2) {
254254
255255fn MockFunction(comptime Register: type) type {
256256 return struct {
257 allocator: *Allocator,
257 allocator: Allocator,
258258 register_manager: RegisterManager(Self, Register, &Register.callee_preserved_regs) = .{},
259259 spilled: std.ArrayListUnmanaged(Register) = .{},
260260
src/stage1.zig+1-1
......@@ -38,7 +38,7 @@ pub fn main(argc: c_int, argv: [*][*:0]u8) callconv(.C) c_int {
3838 const gpa = std.heap.c_allocator;
3939 var arena_instance = std.heap.ArenaAllocator.init(gpa);
4040 defer arena_instance.deinit();
41 const arena = &arena_instance.allocator;
41 const arena = arena_instance.allocator();
4242
4343 const args = arena.alloc([]const u8, @intCast(usize, argc)) catch fatal("{s}", .{"OutOfMemory"});
4444 for (args) |*arg, i| {
src/test.zig+2-2
......@@ -680,7 +680,7 @@ pub const TestContext = struct {
680680 }
681681
682682 fn runOneCase(
683 allocator: *Allocator,
683 allocator: Allocator,
684684 root_node: *std.Progress.Node,
685685 case: Case,
686686 zig_lib_directory: Compilation.Directory,
......@@ -692,7 +692,7 @@ pub const TestContext = struct {
692692
693693 var arena_allocator = std.heap.ArenaAllocator.init(allocator);
694694 defer arena_allocator.deinit();
695 const arena = &arena_allocator.allocator;
695 const arena = arena_allocator.allocator();
696696
697697 var tmp = std.testing.tmpDir(.{});
698698 defer tmp.cleanup();
src/tracy.zig+27-26
......@@ -103,29 +103,27 @@ pub inline fn traceNamed(comptime src: std.builtin.SourceLocation, comptime name
103103 }
104104}
105105
106pub fn tracyAllocator(allocator: *std.mem.Allocator) TracyAllocator(null) {
106pub fn tracyAllocator(allocator: std.mem.Allocator) TracyAllocator(null) {
107107 return TracyAllocator(null).init(allocator);
108108}
109109
110110pub fn TracyAllocator(comptime name: ?[:0]const u8) type {
111111 return struct {
112 allocator: std.mem.Allocator,
113 parent_allocator: *std.mem.Allocator,
112 parent_allocator: std.mem.Allocator,
114113
115114 const Self = @This();
116115
117 pub fn init(allocator: *std.mem.Allocator) Self {
116 pub fn init(parent_allocator: std.mem.Allocator) Self {
118117 return .{
119 .parent_allocator = allocator,
120 .allocator = .{
121 .allocFn = allocFn,
122 .resizeFn = resizeFn,
123 },
118 .parent_allocator = parent_allocator,
124119 };
125120 }
126121
127 fn allocFn(allocator: *std.mem.Allocator, len: usize, ptr_align: u29, len_align: u29, ret_addr: usize) std.mem.Allocator.Error![]u8 {
128 const self = @fieldParentPtr(Self, "allocator", allocator);
122 pub fn allocator(self: *Self) std.mem.Allocator {
123 return std.mem.Allocator.init(self, allocFn, resizeFn, freeFn);
124 }
125
126 fn allocFn(self: *Self, len: usize, ptr_align: u29, len_align: u29, ret_addr: usize) std.mem.Allocator.Error![]u8 {
129127 const result = self.parent_allocator.allocFn(self.parent_allocator, len, ptr_align, len_align, ret_addr);
130128 if (result) |data| {
131129 if (data.len != 0) {
......@@ -141,9 +139,7 @@ pub fn TracyAllocator(comptime name: ?[:0]const u8) type {
141139 return result;
142140 }
143141
144 fn resizeFn(allocator: *std.mem.Allocator, buf: []u8, buf_align: u29, new_len: usize, len_align: u29, ret_addr: usize) std.mem.Allocator.Error!usize {
145 const self = @fieldParentPtr(Self, "allocator", allocator);
146
142 fn resizeFn(self: *Self, buf: []u8, buf_align: u29, new_len: usize, len_align: u29, ret_addr: usize) std.mem.Allocator.Error!usize {
147143 if (self.parent_allocator.resizeFn(self.parent_allocator, buf, buf_align, new_len, len_align, ret_addr)) |resized_len| {
148144 // this condition is to handle free being called on an empty slice that was never even allocated
149145 // example case: `std.process.getSelfExeSharedLibPaths` can return `&[_][:0]u8{}`
......@@ -155,21 +151,26 @@ pub fn TracyAllocator(comptime name: ?[:0]const u8) type {
155151 }
156152 }
157153
158 if (resized_len != 0) {
159 // this was a shrink or a resize
160 if (name) |n| {
161 allocNamed(buf.ptr, resized_len, n);
162 } else {
163 alloc(buf.ptr, resized_len);
164 }
154 if (name) |n| {
155 allocNamed(buf.ptr, resized_len, n);
156 } else {
157 alloc(buf.ptr, resized_len);
165158 }
166159
167160 return resized_len;
168 } else |err| {
169 // this is not really an error condition, during normal operation the compiler hits this case thousands of times
170 // due to this emitting messages for it is both slow and causes clutter
171 // messageColor("allocation resize failed", 0xFF0000);
172 return err;
161 }
162
163 // during normal operation the compiler hits this case thousands of times due to this
164 // emitting messages for it is both slow and causes clutter
165 return null;
166 }
167
168 fn freeFn(self: *Self, buf: []u8, buf_align: u29, ret_addr: usize) void {
169 self.parent_allocator.rawFree(buf, buf_align, ret_addr);
170 if (name) |n| {
171 freeNamed(buf.ptr, n);
172 } else {
173 free(buf.ptr);
173174 }
174175 }
175176 };
src/translate_c.zig+15-14
......@@ -305,8 +305,8 @@ const Scope = struct {
305305};
306306
307307pub const Context = struct {
308 gpa: *mem.Allocator,
309 arena: *mem.Allocator,
308 gpa: mem.Allocator,
309 arena: mem.Allocator,
310310 source_manager: *clang.SourceManager,
311311 decl_table: std.AutoArrayHashMapUnmanaged(usize, []const u8) = .{},
312312 alias_list: AliasList,
......@@ -351,7 +351,7 @@ pub const Context = struct {
351351};
352352
353353pub fn translate(
354 gpa: *mem.Allocator,
354 gpa: mem.Allocator,
355355 args_begin: [*]?[*]const u8,
356356 args_end: [*]?[*]const u8,
357357 errors: *[]ClangErrMsg,
......@@ -373,13 +373,14 @@ pub fn translate(
373373 // from this function.
374374 var arena = std.heap.ArenaAllocator.init(gpa);
375375 errdefer arena.deinit();
376 const arena_allocator = arena.allocator();
376377
377378 var context = Context{
378379 .gpa = gpa,
379 .arena = &arena.allocator,
380 .arena = arena_allocator,
380381 .source_manager = ast_unit.getSourceManager(),
381382 .alias_list = AliasList.init(gpa),
382 .global_scope = try arena.allocator.create(Scope.Root),
383 .global_scope = try arena_allocator.create(Scope.Root),
383384 .clang_context = ast_unit.getASTContext(),
384385 .pattern_list = try PatternList.init(gpa),
385386 };
......@@ -1448,7 +1449,7 @@ fn makeShuffleMask(c: *Context, scope: *Scope, expr: *const clang.ShuffleVectorE
14481449}
14491450
14501451/// @typeInfo(@TypeOf(vec_node)).Vector.<field>
1451fn vectorTypeInfo(arena: *mem.Allocator, vec_node: Node, field: []const u8) TransError!Node {
1452fn vectorTypeInfo(arena: mem.Allocator, vec_node: Node, field: []const u8) TransError!Node {
14521453 const typeof_call = try Tag.typeof.create(arena, vec_node);
14531454 const typeinfo_call = try Tag.typeinfo.create(arena, typeof_call);
14541455 const vector_type_info = try Tag.field_access.create(arena, .{ .lhs = typeinfo_call, .field_name = "Vector" });
......@@ -1536,7 +1537,7 @@ fn transOffsetOfExpr(
15361537/// will become very large positive numbers but that is ok since we only use this in
15371538/// pointer arithmetic expressions, where wraparound will ensure we get the correct value.
15381539/// node -> @bitCast(usize, @intCast(isize, node))
1539fn usizeCastForWrappingPtrArithmetic(gpa: *mem.Allocator, node: Node) TransError!Node {
1540fn usizeCastForWrappingPtrArithmetic(gpa: mem.Allocator, node: Node) TransError!Node {
15401541 const intcast_node = try Tag.int_cast.create(gpa, .{
15411542 .lhs = try Tag.type.create(gpa, "isize"),
15421543 .rhs = node,
......@@ -5072,7 +5073,7 @@ const PatternList = struct {
50725073 };
50735074
50745075 /// Assumes that `ms` represents a tokenized function-like macro.
5075 fn buildArgsHash(allocator: *mem.Allocator, ms: MacroSlicer, hash: *ArgsPositionMap) MacroProcessingError!void {
5076 fn buildArgsHash(allocator: mem.Allocator, ms: MacroSlicer, hash: *ArgsPositionMap) MacroProcessingError!void {
50765077 assert(ms.tokens.len > 2);
50775078 assert(ms.tokens[0].id == .Identifier);
50785079 assert(ms.tokens[1].id == .LParen);
......@@ -5098,7 +5099,7 @@ const PatternList = struct {
50985099 impl: []const u8,
50995100 args_hash: ArgsPositionMap,
51005101
5101 fn init(self: *Pattern, allocator: *mem.Allocator, template: [2][]const u8) Error!void {
5102 fn init(self: *Pattern, allocator: mem.Allocator, template: [2][]const u8) Error!void {
51025103 const source = template[0];
51035104 const impl = template[1];
51045105
......@@ -5120,7 +5121,7 @@ const PatternList = struct {
51205121 };
51215122 }
51225123
5123 fn deinit(self: *Pattern, allocator: *mem.Allocator) void {
5124 fn deinit(self: *Pattern, allocator: mem.Allocator) void {
51245125 self.args_hash.deinit(allocator);
51255126 allocator.free(self.tokens);
51265127 }
......@@ -5171,7 +5172,7 @@ const PatternList = struct {
51715172 }
51725173 };
51735174
5174 fn init(allocator: *mem.Allocator) Error!PatternList {
5175 fn init(allocator: mem.Allocator) Error!PatternList {
51755176 const patterns = try allocator.alloc(Pattern, templates.len);
51765177 for (templates) |template, i| {
51775178 try patterns[i].init(allocator, template);
......@@ -5179,12 +5180,12 @@ const PatternList = struct {
51795180 return PatternList{ .patterns = patterns };
51805181 }
51815182
5182 fn deinit(self: *PatternList, allocator: *mem.Allocator) void {
5183 fn deinit(self: *PatternList, allocator: mem.Allocator) void {
51835184 for (self.patterns) |*pattern| pattern.deinit(allocator);
51845185 allocator.free(self.patterns);
51855186 }
51865187
5187 fn match(self: PatternList, allocator: *mem.Allocator, ms: MacroSlicer) Error!?Pattern {
5188 fn match(self: PatternList, allocator: mem.Allocator, ms: MacroSlicer) Error!?Pattern {
51885189 var args_hash: ArgsPositionMap = .{};
51895190 defer args_hash.deinit(allocator);
51905191
......@@ -5211,7 +5212,7 @@ const MacroSlicer = struct {
52115212test "Macro matching" {
52125213 const helper = struct {
52135214 const MacroFunctions = @import("std").zig.c_translation.Macros;
5214 fn checkMacro(allocator: *mem.Allocator, pattern_list: PatternList, source: []const u8, comptime expected_match: ?[]const u8) !void {
5215 fn checkMacro(allocator: mem.Allocator, pattern_list: PatternList, source: []const u8, comptime expected_match: ?[]const u8) !void {
52155216 var tok_list = std.ArrayList(CToken).init(allocator);
52165217 defer tok_list.deinit();
52175218 try tokenizeMacro(source, &tok_list);
src/translate_c/ast.zig+3-3
......@@ -378,7 +378,7 @@ pub const Node = extern union {
378378 return .{ .tag_if_small_enough = @enumToInt(t) };
379379 }
380380
381 pub fn create(comptime t: Tag, ally: *Allocator, data: Data(t)) error{OutOfMemory}!Node {
381 pub fn create(comptime t: Tag, ally: Allocator, data: Data(t)) error{OutOfMemory}!Node {
382382 const ptr = try ally.create(t.Type());
383383 ptr.* = .{
384384 .base = .{ .tag = t },
......@@ -717,7 +717,7 @@ pub const Payload = struct {
717717
718718/// Converts the nodes into a Zig Ast.
719719/// Caller must free the source slice.
720pub fn render(gpa: *Allocator, nodes: []const Node) !std.zig.Ast {
720pub fn render(gpa: Allocator, nodes: []const Node) !std.zig.Ast {
721721 var ctx = Context{
722722 .gpa = gpa,
723723 .buf = std.ArrayList(u8).init(gpa),
......@@ -783,7 +783,7 @@ const TokenIndex = std.zig.Ast.TokenIndex;
783783const TokenTag = std.zig.Token.Tag;
784784
785785const Context = struct {
786 gpa: *Allocator,
786 gpa: Allocator,
787787 buf: std.ArrayList(u8) = .{},
788788 nodes: std.zig.Ast.NodeList = .{},
789789 extra_data: std.ArrayListUnmanaged(std.zig.Ast.Node.Index) = .{},
src/type.zig+15-15
......@@ -728,7 +728,7 @@ pub const Type = extern union {
728728 }
729729 };
730730
731 pub fn copy(self: Type, allocator: *Allocator) error{OutOfMemory}!Type {
731 pub fn copy(self: Type, allocator: Allocator) error{OutOfMemory}!Type {
732732 if (@enumToInt(self.tag_if_small_enough) < Tag.no_payload_count) {
733733 return Type{ .tag_if_small_enough = self.tag_if_small_enough };
734734 } else switch (self.ptr_otherwise.tag) {
......@@ -905,7 +905,7 @@ pub const Type = extern union {
905905 }
906906 }
907907
908 fn copyPayloadShallow(self: Type, allocator: *Allocator, comptime T: type) error{OutOfMemory}!Type {
908 fn copyPayloadShallow(self: Type, allocator: Allocator, comptime T: type) error{OutOfMemory}!Type {
909909 const payload = self.cast(T).?;
910910 const new_payload = try allocator.create(T);
911911 new_payload.* = payload.*;
......@@ -1198,7 +1198,7 @@ pub const Type = extern union {
11981198 }
11991199
12001200 /// Returns a name suitable for `@typeName`.
1201 pub fn nameAlloc(ty: Type, arena: *Allocator) Allocator.Error![:0]const u8 {
1201 pub fn nameAlloc(ty: Type, arena: Allocator) Allocator.Error![:0]const u8 {
12021202 const t = ty.tag();
12031203 switch (t) {
12041204 .inferred_alloc_const => unreachable,
......@@ -1421,7 +1421,7 @@ pub const Type = extern union {
14211421 };
14221422 }
14231423
1424 pub fn toValue(self: Type, allocator: *Allocator) Allocator.Error!Value {
1424 pub fn toValue(self: Type, allocator: Allocator) Allocator.Error!Value {
14251425 switch (self.tag()) {
14261426 .u1 => return Value.initTag(.u1_type),
14271427 .u8 => return Value.initTag(.u8_type),
......@@ -2676,7 +2676,7 @@ pub const Type = extern union {
26762676 /// For [*]T, returns *T
26772677 /// For []T, returns *T
26782678 /// Handles const-ness and address spaces in particular.
2679 pub fn elemPtrType(ptr_ty: Type, arena: *Allocator) !Type {
2679 pub fn elemPtrType(ptr_ty: Type, arena: Allocator) !Type {
26802680 return try Type.ptr(arena, .{
26812681 .pointee_type = ptr_ty.elemType2(),
26822682 .mutable = ptr_ty.ptrIsMutable(),
......@@ -2731,7 +2731,7 @@ pub const Type = extern union {
27312731
27322732 /// Asserts that the type is an optional.
27332733 /// Same as `optionalChild` but allocates the buffer if needed.
2734 pub fn optionalChildAlloc(ty: Type, allocator: *Allocator) !Type {
2734 pub fn optionalChildAlloc(ty: Type, allocator: Allocator) !Type {
27352735 switch (ty.tag()) {
27362736 .optional => return ty.castTag(.optional).?.data,
27372737 .optional_single_mut_pointer => {
......@@ -3379,7 +3379,7 @@ pub const Type = extern union {
33793379 }
33803380
33813381 /// Asserts that self.zigTypeTag() == .Int.
3382 pub fn minInt(self: Type, arena: *Allocator, target: Target) !Value {
3382 pub fn minInt(self: Type, arena: Allocator, target: Target) !Value {
33833383 assert(self.zigTypeTag() == .Int);
33843384 const info = self.intInfo(target);
33853385
......@@ -3404,7 +3404,7 @@ pub const Type = extern union {
34043404 }
34053405
34063406 /// Asserts that self.zigTypeTag() == .Int.
3407 pub fn maxInt(self: Type, arena: *Allocator, target: Target) !Value {
3407 pub fn maxInt(self: Type, arena: Allocator, target: Target) !Value {
34083408 assert(self.zigTypeTag() == .Int);
34093409 const info = self.intInfo(target);
34103410
......@@ -4008,7 +4008,7 @@ pub const Type = extern union {
40084008 return .{ .tag_if_small_enough = t };
40094009 }
40104010
4011 pub fn create(comptime t: Tag, ally: *Allocator, data: Data(t)) error{OutOfMemory}!file_struct.Type {
4011 pub fn create(comptime t: Tag, ally: Allocator, data: Data(t)) error{OutOfMemory}!file_struct.Type {
40124012 const p = try ally.create(t.Type());
40134013 p.* = .{
40144014 .base = .{ .tag = t },
......@@ -4104,7 +4104,7 @@ pub const Type = extern union {
41044104 functions: std.AutoHashMapUnmanaged(*Module.Fn, void),
41054105 is_anyerror: bool,
41064106
4107 pub fn addErrorSet(self: *Data, gpa: *Allocator, err_set_ty: Type) !void {
4107 pub fn addErrorSet(self: *Data, gpa: Allocator, err_set_ty: Type) !void {
41084108 switch (err_set_ty.tag()) {
41094109 .error_set => {
41104110 const names = err_set_ty.castTag(.error_set).?.data.names();
......@@ -4225,7 +4225,7 @@ pub const Type = extern union {
42254225 pub const @"type" = initTag(.type);
42264226 pub const @"anyerror" = initTag(.anyerror);
42274227
4228 pub fn ptr(arena: *Allocator, d: Payload.Pointer.Data) !Type {
4228 pub fn ptr(arena: Allocator, d: Payload.Pointer.Data) !Type {
42294229 assert(d.host_size == 0 or d.bit_offset < d.host_size * 8);
42304230
42314231 if (d.sentinel != null or d.@"align" != 0 or d.@"addrspace" != .generic or
......@@ -4260,7 +4260,7 @@ pub const Type = extern union {
42604260 }
42614261
42624262 pub fn array(
4263 arena: *Allocator,
4263 arena: Allocator,
42644264 len: u64,
42654265 sent: ?Value,
42664266 elem_type: Type,
......@@ -4289,14 +4289,14 @@ pub const Type = extern union {
42894289 });
42904290 }
42914291
4292 pub fn vector(arena: *Allocator, len: u64, elem_type: Type) Allocator.Error!Type {
4292 pub fn vector(arena: Allocator, len: u64, elem_type: Type) Allocator.Error!Type {
42934293 return Tag.vector.create(arena, .{
42944294 .len = len,
42954295 .elem_type = elem_type,
42964296 });
42974297 }
42984298
4299 pub fn optional(arena: *Allocator, child_type: Type) Allocator.Error!Type {
4299 pub fn optional(arena: Allocator, child_type: Type) Allocator.Error!Type {
43004300 switch (child_type.tag()) {
43014301 .single_const_pointer => return Type.Tag.optional_single_const_pointer.create(
43024302 arena,
......@@ -4317,7 +4317,7 @@ pub const Type = extern union {
43174317 return @intCast(u16, base + @boolToInt(upper < max));
43184318 }
43194319
4320 pub fn smallestUnsignedInt(arena: *Allocator, max: u64) !Type {
4320 pub fn smallestUnsignedInt(arena: Allocator, max: u64) !Type {
43214321 const bits = smallestUnsignedBits(max);
43224322 return switch (bits) {
43234323 1 => initTag(.u1),
src/value.zig+46-46
......@@ -297,7 +297,7 @@ pub const Value = extern union {
297297 };
298298 }
299299
300 pub fn create(comptime t: Tag, ally: *Allocator, data: Data(t)) error{OutOfMemory}!Value {
300 pub fn create(comptime t: Tag, ally: Allocator, data: Data(t)) error{OutOfMemory}!Value {
301301 const ptr = try ally.create(t.Type());
302302 ptr.* = .{
303303 .base = .{ .tag = t },
......@@ -363,7 +363,7 @@ pub const Value = extern union {
363363
364364 /// It's intentional that this function is not passed a corresponding Type, so that
365365 /// a Value can be copied from a Sema to a Decl prior to resolving struct/union field types.
366 pub fn copy(self: Value, arena: *Allocator) error{OutOfMemory}!Value {
366 pub fn copy(self: Value, arena: Allocator) error{OutOfMemory}!Value {
367367 if (@enumToInt(self.tag_if_small_enough) < Tag.no_payload_count) {
368368 return Value{ .tag_if_small_enough = self.tag_if_small_enough };
369369 } else switch (self.ptr_otherwise.tag) {
......@@ -578,7 +578,7 @@ pub const Value = extern union {
578578 }
579579 }
580580
581 fn copyPayloadShallow(self: Value, arena: *Allocator, comptime T: type) error{OutOfMemory}!Value {
581 fn copyPayloadShallow(self: Value, arena: Allocator, comptime T: type) error{OutOfMemory}!Value {
582582 const payload = self.cast(T).?;
583583 const new_payload = try arena.create(T);
584584 new_payload.* = payload.*;
......@@ -747,7 +747,7 @@ pub const Value = extern union {
747747
748748 /// Asserts that the value is representable as an array of bytes.
749749 /// Copies the value into a freshly allocated slice of memory, which is owned by the caller.
750 pub fn toAllocatedBytes(val: Value, ty: Type, allocator: *Allocator) ![]u8 {
750 pub fn toAllocatedBytes(val: Value, ty: Type, allocator: Allocator) ![]u8 {
751751 switch (val.tag()) {
752752 .bytes => {
753753 const bytes = val.castTag(.bytes).?.data;
......@@ -1035,7 +1035,7 @@ pub const Value = extern union {
10351035 }
10361036 }
10371037
1038 pub fn readFromMemory(ty: Type, target: Target, buffer: []const u8, arena: *Allocator) !Value {
1038 pub fn readFromMemory(ty: Type, target: Target, buffer: []const u8, arena: Allocator) !Value {
10391039 switch (ty.zigTypeTag()) {
10401040 .Int => {
10411041 const int_info = ty.intInfo(target);
......@@ -1185,7 +1185,7 @@ pub const Value = extern union {
11851185 }
11861186 }
11871187
1188 pub fn popCount(val: Value, ty: Type, target: Target, arena: *Allocator) !Value {
1188 pub fn popCount(val: Value, ty: Type, target: Target, arena: Allocator) !Value {
11891189 assert(!val.isUndef());
11901190
11911191 const info = ty.intInfo(target);
......@@ -1273,7 +1273,7 @@ pub const Value = extern union {
12731273
12741274 /// Converts an integer or a float to a float. May result in a loss of information.
12751275 /// Caller can find out by equality checking the result against the operand.
1276 pub fn floatCast(self: Value, arena: *Allocator, dest_ty: Type) !Value {
1276 pub fn floatCast(self: Value, arena: Allocator, dest_ty: Type) !Value {
12771277 switch (dest_ty.tag()) {
12781278 .f16 => return Value.Tag.float_16.create(arena, self.toFloat(f16)),
12791279 .f32 => return Value.Tag.float_32.create(arena, self.toFloat(f32)),
......@@ -1678,7 +1678,7 @@ pub const Value = extern union {
16781678
16791679 /// Asserts the value is a single-item pointer to an array, or an array,
16801680 /// or an unknown-length pointer, and returns the element value at the index.
1681 pub fn elemValue(val: Value, arena: *Allocator, index: usize) !Value {
1681 pub fn elemValue(val: Value, arena: Allocator, index: usize) !Value {
16821682 return elemValueAdvanced(val, index, arena, undefined);
16831683 }
16841684
......@@ -1691,7 +1691,7 @@ pub const Value = extern union {
16911691 pub fn elemValueAdvanced(
16921692 val: Value,
16931693 index: usize,
1694 arena: ?*Allocator,
1694 arena: ?Allocator,
16951695 buffer: *ElemValueBuffer,
16961696 ) error{OutOfMemory}!Value {
16971697 switch (val.tag()) {
......@@ -1732,7 +1732,7 @@ pub const Value = extern union {
17321732 }
17331733 }
17341734
1735 pub fn fieldValue(val: Value, allocator: *Allocator, index: usize) error{OutOfMemory}!Value {
1735 pub fn fieldValue(val: Value, allocator: Allocator, index: usize) error{OutOfMemory}!Value {
17361736 _ = allocator;
17371737 switch (val.tag()) {
17381738 .@"struct" => {
......@@ -1760,7 +1760,7 @@ pub const Value = extern union {
17601760 }
17611761
17621762 /// Returns a pointer to the element value at the index.
1763 pub fn elemPtr(self: Value, allocator: *Allocator, index: usize) !Value {
1763 pub fn elemPtr(self: Value, allocator: Allocator, index: usize) !Value {
17641764 switch (self.tag()) {
17651765 .elem_ptr => {
17661766 const elem_ptr = self.castTag(.elem_ptr).?.data;
......@@ -1874,7 +1874,7 @@ pub const Value = extern union {
18741874 };
18751875 }
18761876
1877 pub fn intToFloat(val: Value, arena: *Allocator, dest_ty: Type, target: Target) !Value {
1877 pub fn intToFloat(val: Value, arena: Allocator, dest_ty: Type, target: Target) !Value {
18781878 switch (val.tag()) {
18791879 .undef, .zero, .one => return val,
18801880 .the_only_possible_value => return Value.initTag(.zero), // for i0, u0
......@@ -1898,7 +1898,7 @@ pub const Value = extern union {
18981898 }
18991899 }
19001900
1901 fn intToFloatInner(x: anytype, arena: *Allocator, dest_ty: Type, target: Target) !Value {
1901 fn intToFloatInner(x: anytype, arena: Allocator, dest_ty: Type, target: Target) !Value {
19021902 switch (dest_ty.floatBits(target)) {
19031903 16 => return Value.Tag.float_16.create(arena, @intToFloat(f16, x)),
19041904 32 => return Value.Tag.float_32.create(arena, @intToFloat(f32, x)),
......@@ -1908,7 +1908,7 @@ pub const Value = extern union {
19081908 }
19091909 }
19101910
1911 fn floatToValue(float: f128, arena: *Allocator, dest_ty: Type, target: Target) !Value {
1911 fn floatToValue(float: f128, arena: Allocator, dest_ty: Type, target: Target) !Value {
19121912 switch (dest_ty.floatBits(target)) {
19131913 16 => return Value.Tag.float_16.create(arena, @floatCast(f16, float)),
19141914 32 => return Value.Tag.float_32.create(arena, @floatCast(f32, float)),
......@@ -1918,7 +1918,7 @@ pub const Value = extern union {
19181918 }
19191919 }
19201920
1921 pub fn floatToInt(val: Value, arena: *Allocator, dest_ty: Type, target: Target) error{ FloatCannotFit, OutOfMemory }!Value {
1921 pub fn floatToInt(val: Value, arena: Allocator, dest_ty: Type, target: Target) error{ FloatCannotFit, OutOfMemory }!Value {
19221922 const Limb = std.math.big.Limb;
19231923
19241924 var value = val.toFloat(f64); // TODO: f128 ?
......@@ -1969,7 +1969,7 @@ pub const Value = extern union {
19691969 lhs: Value,
19701970 rhs: Value,
19711971 ty: Type,
1972 arena: *Allocator,
1972 arena: Allocator,
19731973 target: Target,
19741974 ) !Value {
19751975 if (lhs.isUndef() or rhs.isUndef()) return Value.initTag(.undef);
......@@ -1993,7 +1993,7 @@ pub const Value = extern union {
19931993 return fromBigInt(arena, result_bigint.toConst());
19941994 }
19951995
1996 fn fromBigInt(arena: *Allocator, big_int: BigIntConst) !Value {
1996 fn fromBigInt(arena: Allocator, big_int: BigIntConst) !Value {
19971997 if (big_int.positive) {
19981998 if (big_int.to(u64)) |x| {
19991999 return Value.Tag.int_u64.create(arena, x);
......@@ -2014,7 +2014,7 @@ pub const Value = extern union {
20142014 lhs: Value,
20152015 rhs: Value,
20162016 ty: Type,
2017 arena: *Allocator,
2017 arena: Allocator,
20182018 target: Target,
20192019 ) !Value {
20202020 assert(!lhs.isUndef());
......@@ -2040,7 +2040,7 @@ pub const Value = extern union {
20402040 lhs: Value,
20412041 rhs: Value,
20422042 ty: Type,
2043 arena: *Allocator,
2043 arena: Allocator,
20442044 target: Target,
20452045 ) !Value {
20462046 if (lhs.isUndef() or rhs.isUndef()) return Value.initTag(.undef);
......@@ -2069,7 +2069,7 @@ pub const Value = extern union {
20692069 lhs: Value,
20702070 rhs: Value,
20712071 ty: Type,
2072 arena: *Allocator,
2072 arena: Allocator,
20732073 target: Target,
20742074 ) !Value {
20752075 assert(!lhs.isUndef());
......@@ -2095,7 +2095,7 @@ pub const Value = extern union {
20952095 lhs: Value,
20962096 rhs: Value,
20972097 ty: Type,
2098 arena: *Allocator,
2098 arena: Allocator,
20992099 target: Target,
21002100 ) !Value {
21012101 if (lhs.isUndef() or rhs.isUndef()) return Value.initTag(.undef);
......@@ -2129,7 +2129,7 @@ pub const Value = extern union {
21292129 lhs: Value,
21302130 rhs: Value,
21312131 ty: Type,
2132 arena: *Allocator,
2132 arena: Allocator,
21332133 target: Target,
21342134 ) !Value {
21352135 assert(!lhs.isUndef());
......@@ -2185,7 +2185,7 @@ pub const Value = extern union {
21852185 }
21862186
21872187 /// operands must be integers; handles undefined.
2188 pub fn bitwiseNot(val: Value, ty: Type, arena: *Allocator, target: Target) !Value {
2188 pub fn bitwiseNot(val: Value, ty: Type, arena: Allocator, target: Target) !Value {
21892189 if (val.isUndef()) return Value.initTag(.undef);
21902190
21912191 const info = ty.intInfo(target);
......@@ -2205,7 +2205,7 @@ pub const Value = extern union {
22052205 }
22062206
22072207 /// operands must be integers; handles undefined.
2208 pub fn bitwiseAnd(lhs: Value, rhs: Value, arena: *Allocator) !Value {
2208 pub fn bitwiseAnd(lhs: Value, rhs: Value, arena: Allocator) !Value {
22092209 if (lhs.isUndef() or rhs.isUndef()) return Value.initTag(.undef);
22102210
22112211 // TODO is this a performance issue? maybe we should try the operation without
......@@ -2225,7 +2225,7 @@ pub const Value = extern union {
22252225 }
22262226
22272227 /// operands must be integers; handles undefined.
2228 pub fn bitwiseNand(lhs: Value, rhs: Value, ty: Type, arena: *Allocator, target: Target) !Value {
2228 pub fn bitwiseNand(lhs: Value, rhs: Value, ty: Type, arena: Allocator, target: Target) !Value {
22292229 if (lhs.isUndef() or rhs.isUndef()) return Value.initTag(.undef);
22302230
22312231 const anded = try bitwiseAnd(lhs, rhs, arena);
......@@ -2239,7 +2239,7 @@ pub const Value = extern union {
22392239 }
22402240
22412241 /// operands must be integers; handles undefined.
2242 pub fn bitwiseOr(lhs: Value, rhs: Value, arena: *Allocator) !Value {
2242 pub fn bitwiseOr(lhs: Value, rhs: Value, arena: Allocator) !Value {
22432243 if (lhs.isUndef() or rhs.isUndef()) return Value.initTag(.undef);
22442244
22452245 // TODO is this a performance issue? maybe we should try the operation without
......@@ -2258,7 +2258,7 @@ pub const Value = extern union {
22582258 }
22592259
22602260 /// operands must be integers; handles undefined.
2261 pub fn bitwiseXor(lhs: Value, rhs: Value, arena: *Allocator) !Value {
2261 pub fn bitwiseXor(lhs: Value, rhs: Value, arena: Allocator) !Value {
22622262 if (lhs.isUndef() or rhs.isUndef()) return Value.initTag(.undef);
22632263
22642264 // TODO is this a performance issue? maybe we should try the operation without
......@@ -2277,7 +2277,7 @@ pub const Value = extern union {
22772277 return fromBigInt(arena, result_bigint.toConst());
22782278 }
22792279
2280 pub fn intAdd(lhs: Value, rhs: Value, allocator: *Allocator) !Value {
2280 pub fn intAdd(lhs: Value, rhs: Value, allocator: Allocator) !Value {
22812281 // TODO is this a performance issue? maybe we should try the operation without
22822282 // resorting to BigInt first.
22832283 var lhs_space: Value.BigIntSpace = undefined;
......@@ -2293,7 +2293,7 @@ pub const Value = extern union {
22932293 return fromBigInt(allocator, result_bigint.toConst());
22942294 }
22952295
2296 pub fn intSub(lhs: Value, rhs: Value, allocator: *Allocator) !Value {
2296 pub fn intSub(lhs: Value, rhs: Value, allocator: Allocator) !Value {
22972297 // TODO is this a performance issue? maybe we should try the operation without
22982298 // resorting to BigInt first.
22992299 var lhs_space: Value.BigIntSpace = undefined;
......@@ -2309,7 +2309,7 @@ pub const Value = extern union {
23092309 return fromBigInt(allocator, result_bigint.toConst());
23102310 }
23112311
2312 pub fn intDiv(lhs: Value, rhs: Value, allocator: *Allocator) !Value {
2312 pub fn intDiv(lhs: Value, rhs: Value, allocator: Allocator) !Value {
23132313 // TODO is this a performance issue? maybe we should try the operation without
23142314 // resorting to BigInt first.
23152315 var lhs_space: Value.BigIntSpace = undefined;
......@@ -2334,7 +2334,7 @@ pub const Value = extern union {
23342334 return fromBigInt(allocator, result_q.toConst());
23352335 }
23362336
2337 pub fn intDivFloor(lhs: Value, rhs: Value, allocator: *Allocator) !Value {
2337 pub fn intDivFloor(lhs: Value, rhs: Value, allocator: Allocator) !Value {
23382338 // TODO is this a performance issue? maybe we should try the operation without
23392339 // resorting to BigInt first.
23402340 var lhs_space: Value.BigIntSpace = undefined;
......@@ -2359,7 +2359,7 @@ pub const Value = extern union {
23592359 return fromBigInt(allocator, result_q.toConst());
23602360 }
23612361
2362 pub fn intRem(lhs: Value, rhs: Value, allocator: *Allocator) !Value {
2362 pub fn intRem(lhs: Value, rhs: Value, allocator: Allocator) !Value {
23632363 // TODO is this a performance issue? maybe we should try the operation without
23642364 // resorting to BigInt first.
23652365 var lhs_space: Value.BigIntSpace = undefined;
......@@ -2386,7 +2386,7 @@ pub const Value = extern union {
23862386 return fromBigInt(allocator, result_r.toConst());
23872387 }
23882388
2389 pub fn intMod(lhs: Value, rhs: Value, allocator: *Allocator) !Value {
2389 pub fn intMod(lhs: Value, rhs: Value, allocator: Allocator) !Value {
23902390 // TODO is this a performance issue? maybe we should try the operation without
23912391 // resorting to BigInt first.
23922392 var lhs_space: Value.BigIntSpace = undefined;
......@@ -2422,21 +2422,21 @@ pub const Value = extern union {
24222422 };
24232423 }
24242424
2425 pub fn floatRem(lhs: Value, rhs: Value, allocator: *Allocator) !Value {
2425 pub fn floatRem(lhs: Value, rhs: Value, allocator: Allocator) !Value {
24262426 _ = lhs;
24272427 _ = rhs;
24282428 _ = allocator;
24292429 @panic("TODO implement Value.floatRem");
24302430 }
24312431
2432 pub fn floatMod(lhs: Value, rhs: Value, allocator: *Allocator) !Value {
2432 pub fn floatMod(lhs: Value, rhs: Value, allocator: Allocator) !Value {
24332433 _ = lhs;
24342434 _ = rhs;
24352435 _ = allocator;
24362436 @panic("TODO implement Value.floatMod");
24372437 }
24382438
2439 pub fn intMul(lhs: Value, rhs: Value, allocator: *Allocator) !Value {
2439 pub fn intMul(lhs: Value, rhs: Value, allocator: Allocator) !Value {
24402440 // TODO is this a performance issue? maybe we should try the operation without
24412441 // resorting to BigInt first.
24422442 var lhs_space: Value.BigIntSpace = undefined;
......@@ -2457,7 +2457,7 @@ pub const Value = extern union {
24572457 return fromBigInt(allocator, result_bigint.toConst());
24582458 }
24592459
2460 pub fn intTrunc(val: Value, allocator: *Allocator, signedness: std.builtin.Signedness, bits: u16) !Value {
2460 pub fn intTrunc(val: Value, allocator: Allocator, signedness: std.builtin.Signedness, bits: u16) !Value {
24612461 var val_space: Value.BigIntSpace = undefined;
24622462 const val_bigint = val.toBigInt(&val_space);
24632463
......@@ -2471,7 +2471,7 @@ pub const Value = extern union {
24712471 return fromBigInt(allocator, result_bigint.toConst());
24722472 }
24732473
2474 pub fn shl(lhs: Value, rhs: Value, allocator: *Allocator) !Value {
2474 pub fn shl(lhs: Value, rhs: Value, allocator: Allocator) !Value {
24752475 // TODO is this a performance issue? maybe we should try the operation without
24762476 // resorting to BigInt first.
24772477 var lhs_space: Value.BigIntSpace = undefined;
......@@ -2494,7 +2494,7 @@ pub const Value = extern union {
24942494 lhs: Value,
24952495 rhs: Value,
24962496 ty: Type,
2497 arena: *Allocator,
2497 arena: Allocator,
24982498 target: Target,
24992499 ) !Value {
25002500 // TODO is this a performance issue? maybe we should try the operation without
......@@ -2517,7 +2517,7 @@ pub const Value = extern union {
25172517 return fromBigInt(arena, result_bigint.toConst());
25182518 }
25192519
2520 pub fn shr(lhs: Value, rhs: Value, allocator: *Allocator) !Value {
2520 pub fn shr(lhs: Value, rhs: Value, allocator: Allocator) !Value {
25212521 // TODO is this a performance issue? maybe we should try the operation without
25222522 // resorting to BigInt first.
25232523 var lhs_space: Value.BigIntSpace = undefined;
......@@ -2540,7 +2540,7 @@ pub const Value = extern union {
25402540 lhs: Value,
25412541 rhs: Value,
25422542 float_type: Type,
2543 arena: *Allocator,
2543 arena: Allocator,
25442544 ) !Value {
25452545 switch (float_type.tag()) {
25462546 .f16 => {
......@@ -2571,7 +2571,7 @@ pub const Value = extern union {
25712571 lhs: Value,
25722572 rhs: Value,
25732573 float_type: Type,
2574 arena: *Allocator,
2574 arena: Allocator,
25752575 ) !Value {
25762576 switch (float_type.tag()) {
25772577 .f16 => {
......@@ -2602,7 +2602,7 @@ pub const Value = extern union {
26022602 lhs: Value,
26032603 rhs: Value,
26042604 float_type: Type,
2605 arena: *Allocator,
2605 arena: Allocator,
26062606 ) !Value {
26072607 switch (float_type.tag()) {
26082608 .f16 => {
......@@ -2633,7 +2633,7 @@ pub const Value = extern union {
26332633 lhs: Value,
26342634 rhs: Value,
26352635 float_type: Type,
2636 arena: *Allocator,
2636 arena: Allocator,
26372637 ) !Value {
26382638 switch (float_type.tag()) {
26392639 .f16 => {
......@@ -2664,7 +2664,7 @@ pub const Value = extern union {
26642664 lhs: Value,
26652665 rhs: Value,
26662666 float_type: Type,
2667 arena: *Allocator,
2667 arena: Allocator,
26682668 ) !Value {
26692669 switch (float_type.tag()) {
26702670 .f16 => {
......@@ -2695,7 +2695,7 @@ pub const Value = extern union {
26952695 lhs: Value,
26962696 rhs: Value,
26972697 float_type: Type,
2698 arena: *Allocator,
2698 arena: Allocator,
26992699 ) !Value {
27002700 switch (float_type.tag()) {
27012701 .f16 => {
src/wasi_libc.zig+5-5
......@@ -67,7 +67,7 @@ pub fn buildCRTFile(comp: *Compilation, crt_file: CRTFile) !void {
6767 const gpa = comp.gpa;
6868 var arena_allocator = std.heap.ArenaAllocator.init(gpa);
6969 defer arena_allocator.deinit();
70 const arena = &arena_allocator.allocator;
70 const arena = arena_allocator.allocator();
7171
7272 switch (crt_file) {
7373 .crt1_reactor_o => {
......@@ -243,7 +243,7 @@ pub fn buildCRTFile(comp: *Compilation, crt_file: CRTFile) !void {
243243 }
244244}
245245
246fn sanitize(arena: *Allocator, file_path: []const u8) ![]const u8 {
246fn sanitize(arena: Allocator, file_path: []const u8) ![]const u8 {
247247 // TODO do this at comptime on the comptime data rather than at runtime
248248 // probably best to wait until self-hosted is done and our comptime execution
249249 // is faster and uses less memory.
......@@ -261,7 +261,7 @@ fn sanitize(arena: *Allocator, file_path: []const u8) ![]const u8 {
261261
262262fn addCCArgs(
263263 comp: *Compilation,
264 arena: *Allocator,
264 arena: Allocator,
265265 args: *std.ArrayList([]const u8),
266266 want_O3: bool,
267267) error{OutOfMemory}!void {
......@@ -292,7 +292,7 @@ fn addCCArgs(
292292
293293fn addLibcBottomHalfIncludes(
294294 comp: *Compilation,
295 arena: *Allocator,
295 arena: Allocator,
296296 args: *std.ArrayList([]const u8),
297297) error{OutOfMemory}!void {
298298 try args.appendSlice(&[_][]const u8{
......@@ -328,7 +328,7 @@ fn addLibcBottomHalfIncludes(
328328
329329fn addLibcTopHalfIncludes(
330330 comp: *Compilation,
331 arena: *Allocator,
331 arena: Allocator,
332332 args: *std.ArrayList([]const u8),
333333) error{OutOfMemory}!void {
334334 try args.appendSlice(&[_][]const u8{
test/behavior/async_fn.zig+3-3
......@@ -713,7 +713,7 @@ fn testAsyncAwaitTypicalUsage(
713713 }
714714
715715 var global_download_frame: anyframe = undefined;
716 fn fetchUrl(allocator: *std.mem.Allocator, url: []const u8) anyerror![]u8 {
716 fn fetchUrl(allocator: std.mem.Allocator, url: []const u8) anyerror![]u8 {
717717 _ = url;
718718 const result = try allocator.dupe(u8, "expected download text");
719719 errdefer allocator.free(result);
......@@ -727,7 +727,7 @@ fn testAsyncAwaitTypicalUsage(
727727 }
728728
729729 var global_file_frame: anyframe = undefined;
730 fn readFile(allocator: *std.mem.Allocator, filename: []const u8) anyerror![]u8 {
730 fn readFile(allocator: std.mem.Allocator, filename: []const u8) anyerror![]u8 {
731731 _ = filename;
732732 const result = try allocator.dupe(u8, "expected file text");
733733 errdefer allocator.free(result);
......@@ -912,7 +912,7 @@ test "recursive async function" {
912912
913913fn recursiveAsyncFunctionTest(comptime suspending_implementation: bool) type {
914914 return struct {
915 fn fib(allocator: *std.mem.Allocator, x: u32) error{OutOfMemory}!u32 {
915 fn fib(allocator: std.mem.Allocator, x: u32) error{OutOfMemory}!u32 {
916916 if (x <= 1) return x;
917917
918918 if (suspending_implementation) {
test/cli.zig+2-2
......@@ -5,7 +5,7 @@ const process = std.process;
55const fs = std.fs;
66const ChildProcess = std.ChildProcess;
77
8var a: *std.mem.Allocator = undefined;
8var a: std.mem.Allocator = undefined;
99
1010pub fn main() !void {
1111 var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
......@@ -16,7 +16,7 @@ pub fn main() !void {
1616 // skip my own exe name
1717 _ = arg_it.skip();
1818
19 a = &arena.allocator;
19 a = arena.allocator();
2020
2121 const zig_exe_rel = try (arg_it.next(a) orelse {
2222 std.debug.print("Expected first argument to be path to zig compiler\n", .{});
test/compare_output.zig+4-4
......@@ -491,12 +491,12 @@ pub fn addCases(cases: *tests.CompareOutputContext) void {
491491 \\pub fn main() !void {
492492 \\ var allocator_buf: [10]u8 = undefined;
493493 \\ var fixedBufferAllocator = std.mem.validationWrap(std.heap.FixedBufferAllocator.init(&allocator_buf));
494 \\ const allocator = &std.heap.loggingAllocator(&fixedBufferAllocator.allocator).allocator;
494 \\ const allocator = std.heap.loggingAllocator(fixedBufferAllocator.allocator()).allocator();
495495 \\
496496 \\ var a = try allocator.alloc(u8, 10);
497497 \\ a = allocator.shrink(a, 5);
498498 \\ try std.testing.expect(a.len == 5);
499 \\ try std.testing.expectError(error.OutOfMemory, allocator.resize(a, 20));
499 \\ try std.testing.expect(allocator.resize(a, 20) == null);
500500 \\ allocator.free(a);
501501 \\}
502502 \\
......@@ -514,8 +514,8 @@ pub fn addCases(cases: *tests.CompareOutputContext) void {
514514 ,
515515 \\debug: alloc - success - len: 10, ptr_align: 1, len_align: 0
516516 \\debug: shrink - success - 10 to 5, len_align: 0, buf_align: 1
517 \\error: expand - failure: OutOfMemory - 5 to 20, len_align: 0, buf_align: 1
518 \\debug: free - success - len: 5
517 \\error: expand - failure - 5 to 20, len_align: 0, buf_align: 1
518 \\debug: free - len: 5
519519 \\
520520 );
521521}
test/compile_errors.zig+1-1
......@@ -7569,7 +7569,7 @@ pub fn addCases(ctx: *TestContext) !void {
75697569 \\
75707570 \\export fn entry() void {
75717571 \\ const a = MdNode.Header {
7572 \\ .text = MdText.init(&std.testing.allocator),
7572 \\ .text = MdText.init(std.testing.allocator),
75737573 \\ .weight = HeaderWeight.H1,
75747574 \\ };
75757575 \\ _ = a;
test/standalone/brace_expansion/main.zig+1-1
......@@ -16,7 +16,7 @@ const Token = union(enum) {
1616};
1717
1818var gpa = std.heap.GeneralPurposeAllocator(.{}){};
19var global_allocator = &gpa.allocator;
19var global_allocator = gpa.allocator();
2020
2121fn tokenize(input: []const u8) !ArrayList(Token) {
2222 const State = enum {
test/standalone/cat/main.zig+1-1
......@@ -8,7 +8,7 @@ const warn = std.log.warn;
88pub fn main() !void {
99 var arena_instance = std.heap.ArenaAllocator.init(std.heap.page_allocator);
1010 defer arena_instance.deinit();
11 const arena = &arena_instance.allocator;
11 const arena = arena_instance.allocator();
1212
1313 const args = try process.argsAlloc(arena);
1414
tools/gen_spirv_spec.zig+1-1
......@@ -4,7 +4,7 @@ const g = @import("spirv/grammar.zig");
44pub fn main() !void {
55 var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
66 defer arena.deinit();
7 const allocator = &arena.allocator;
7 const allocator = arena.allocator();
88
99 const args = try std.process.argsAlloc(allocator);
1010 if (args.len != 2) {
tools/gen_stubs.zig+1-1
......@@ -25,7 +25,7 @@ pub fn main() !void {
2525
2626 var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
2727 defer arena.deinit();
28 const ally = &arena.allocator;
28 const ally = arena.allocator();
2929
3030 var symbols = std.ArrayList(Symbol).init(ally);
3131 var sections = std.ArrayList([]const u8).init(ally);
tools/merge_anal_dumps.zig+3-3
......@@ -9,7 +9,7 @@ pub fn main() anyerror!void {
99 var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
1010 defer arena.deinit();
1111
12 const allocator = &arena.allocator;
12 const allocator = arena.allocator();
1313
1414 const args = try std.process.argsAlloc(allocator);
1515
......@@ -160,7 +160,7 @@ const Dump = struct {
160160 const ErrorMap = std.HashMap(Error, usize, Error.hash, Error.eql, 80);
161161 const TypeMap = std.HashMap(Type, usize, Type.hash, Type.eql, 80);
162162
163 fn init(allocator: *mem.Allocator) Dump {
163 fn init(allocator: mem.Allocator) Dump {
164164 return Dump{
165165 .targets = std.ArrayList([]const u8).init(allocator),
166166 .file_list = std.ArrayList([]const u8).init(allocator),
......@@ -434,7 +434,7 @@ const Dump = struct {
434434 try jw.endObject();
435435 }
436436
437 fn a(self: Dump) *mem.Allocator {
437 fn a(self: Dump) mem.Allocator {
438438 return self.targets.allocator;
439439 }
440440
tools/process_headers.zig+1-1
......@@ -284,7 +284,7 @@ const LibCVendor = enum {
284284
285285pub fn main() !void {
286286 var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
287 const allocator = &arena.allocator;
287 const allocator = arena.allocator();
288288 const args = try std.process.argsAlloc(allocator);
289289 var search_paths = std.ArrayList([]const u8).init(allocator);
290290 var opt_out_dir: ?[]const u8 = null;
tools/update-license-headers.zig+1-1
......@@ -10,7 +10,7 @@ pub fn main() !void {
1010 defer root_node.end();
1111
1212 var arena_allocator = std.heap.ArenaAllocator.init(std.heap.page_allocator);
13 const arena = &arena_allocator.allocator;
13 const arena = arena_allocator.allocator();
1414
1515 const args = try std.process.argsAlloc(arena);
1616 const path_to_walk = args[1];
tools/update-linux-headers.zig+1-1
......@@ -131,7 +131,7 @@ const PathTable = std.StringHashMap(*TargetToHash);
131131
132132pub fn main() !void {
133133 var arena_state = std.heap.ArenaAllocator.init(std.heap.page_allocator);
134 const arena = &arena_state.allocator;
134 const arena = arena_state.allocator();
135135 const args = try std.process.argsAlloc(arena);
136136 var search_paths = std.ArrayList([]const u8).init(arena);
137137 var opt_out_dir: ?[]const u8 = null;
tools/update_clang_options.zig+1-1
......@@ -450,8 +450,8 @@ const cpu_targets = struct {
450450pub fn main() anyerror!void {
451451 var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
452452 defer arena.deinit();
453 const allocator = &arena.allocator;
454453
454 const allocator = arena.allocator();
455455 const args = try std.process.argsAlloc(allocator);
456456
457457 if (args.len <= 1) {
tools/update_cpu_features.zig+5-5
......@@ -769,7 +769,7 @@ const llvm_targets = [_]LlvmTarget{
769769pub fn main() anyerror!void {
770770 var arena_state = std.heap.ArenaAllocator.init(std.heap.page_allocator);
771771 defer arena_state.deinit();
772 const arena = &arena_state.allocator;
772 const arena = arena_state.allocator();
773773
774774 const args = try std.process.argsAlloc(arena);
775775 if (args.len <= 1) {
......@@ -845,7 +845,7 @@ fn processOneTarget(job: Job) anyerror!void {
845845
846846 var arena_state = std.heap.ArenaAllocator.init(std.heap.page_allocator);
847847 defer arena_state.deinit();
848 const arena = &arena_state.allocator;
848 const arena = arena_state.allocator();
849849
850850 var progress_node = job.root_progress.start(llvm_target.zig_name, 3);
851851 progress_node.activate();
......@@ -1244,7 +1244,7 @@ fn asciiLessThan(context: void, a: []const u8, b: []const u8) bool {
12441244 return std.ascii.lessThanIgnoreCase(a, b);
12451245}
12461246
1247fn llvmNameToZigName(arena: *mem.Allocator, llvm_name: []const u8) ![]const u8 {
1247fn llvmNameToZigName(arena: mem.Allocator, llvm_name: []const u8) ![]const u8 {
12481248 const duped = try arena.dupe(u8, llvm_name);
12491249 for (duped) |*byte| switch (byte.*) {
12501250 '-', '.' => byte.* = '_',
......@@ -1254,7 +1254,7 @@ fn llvmNameToZigName(arena: *mem.Allocator, llvm_name: []const u8) ![]const u8 {
12541254}
12551255
12561256fn llvmNameToZigNameOmit(
1257 arena: *mem.Allocator,
1257 arena: mem.Allocator,
12581258 llvm_target: LlvmTarget,
12591259 llvm_name: []const u8,
12601260) !?[]const u8 {
......@@ -1279,7 +1279,7 @@ fn hasSuperclass(obj: *json.ObjectMap, class_name: []const u8) bool {
12791279}
12801280
12811281fn pruneFeatures(
1282 arena: *mem.Allocator,
1282 arena: mem.Allocator,
12831283 features_table: std.StringHashMap(Feature),
12841284 deps_set: *std.StringHashMap(void),
12851285) !void {
tools/update_glibc.zig+1-1
......@@ -133,7 +133,7 @@ const Function = struct {
133133
134134pub fn main() !void {
135135 var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
136 const allocator = &arena.allocator;
136 const allocator = arena.allocator();
137137 const args = try std.process.argsAlloc(allocator);
138138 const in_glibc_dir = args[1]; // path to the unzipped tarball of glibc, e.g. ~/downloads/glibc-2.25
139139 const zig_src_dir = args[2]; // path to the source checkout of zig, lib dir, e.g. ~/zig-src/lib
tools/update_spirv_features.zig+3-3
......@@ -48,7 +48,7 @@ const Version = struct {
4848pub fn main() !void {
4949 var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
5050 defer arena.deinit();
51 const allocator = &arena.allocator;
51 const allocator = arena.allocator();
5252
5353 const args = try std.process.argsAlloc(allocator);
5454
......@@ -216,7 +216,7 @@ pub fn main() !void {
216216/// The *.grammar.json in SPIRV-Headers should have most of these as well, but with this we're sure to get only the actually
217217/// registered ones.
218218/// TODO: Unfortunately, neither repository contains a machine-readable list of extension dependencies.
219fn gather_extensions(allocator: *Allocator, spirv_registry_root: []const u8) ![]const []const u8 {
219fn gather_extensions(allocator: Allocator, spirv_registry_root: []const u8) ![]const []const u8 {
220220 const extensions_path = try fs.path.join(allocator, &.{ spirv_registry_root, "extensions" });
221221 var extensions_dir = try fs.cwd().openDir(extensions_path, .{ .iterate = true });
222222 defer extensions_dir.close();
......@@ -286,7 +286,7 @@ fn insertVersion(versions: *std.ArrayList(Version), version: ?[]const u8) !void
286286 try versions.append(ver);
287287}
288288
289fn gatherVersions(allocator: *Allocator, registry: g.CoreRegistry) ![]const Version {
289fn gatherVersions(allocator: Allocator, registry: g.CoreRegistry) ![]const Version {
290290 // Expected number of versions is small
291291 var versions = std.ArrayList(Version).init(allocator);
292292