authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2025-08-29 03:48:45-07:00
committergravatar for noreply@github.comGitHub <noreply@github.com> 2025-08-29 03:48:45-07:00
log4b948e8556b80cbc874415aa7c4bf9ac0027ffed
treeca48e7208aa23a24db82e8521c37a6c2abcd5dc1
parent640c11171bf8d13776629941f3305cf11c62c1f3
parent43fbc37a490442ffcecf9817877f542251fee664
signaturebadge-check Signed by PGP key B5690EEEBB952194

Merge pull request #25036 from ziglang/GenericWriter

std.Io: delete GenericWriter, AnyWriter, and null_writer

106 files changed, 2450 insertions(+), 3606 deletions(-)

lib/compiler/aro/aro/Attribute.zig+1-1
......@@ -780,7 +780,7 @@ fn ignoredAttrErr(p: *Parser, tok: TokenIndex, attr: Attribute.Tag, context: []c
780780 const strings_top = p.strings.items.len;
781781 defer p.strings.items.len = strings_top;
782782
783 try p.strings.writer().print("attribute '{s}' ignored on {s}", .{ @tagName(attr), context });
783 try p.strings.print("attribute '{s}' ignored on {s}", .{ @tagName(attr), context });
784784 const str = try p.comp.diagnostics.arena.allocator().dupe(u8, p.strings.items[strings_top..]);
785785 try p.errStr(.ignored_attribute, tok, str);
786786}
lib/compiler/aro/aro/Builtins/Builtin.zig+2-3
......@@ -119,8 +119,7 @@ pub fn nameFromUniqueIndex(index: u16, buf: []u8) []u8 {
119119
120120 var node_index: u16 = 0;
121121 var count: u16 = index;
122 var fbs = std.io.fixedBufferStream(buf);
123 const w = fbs.writer();
122 var w: std.Io.Writer = .fixed(buf);
124123
125124 while (true) {
126125 var sibling_index = dafsa[node_index].child_index;
......@@ -142,7 +141,7 @@ pub fn nameFromUniqueIndex(index: u16, buf: []u8) []u8 {
142141 if (count == 0) break;
143142 }
144143
145 return fbs.getWritten();
144 return w.buffered();
146145}
147146
148147/// We're 1 bit shy of being able to fit this in a u32:
lib/compiler/aro/aro/Compilation.zig+36-28
......@@ -16,6 +16,7 @@ const Pragma = @import("Pragma.zig");
1616const StrInt = @import("StringInterner.zig");
1717const record_layout = @import("record_layout.zig");
1818const target_util = @import("target.zig");
19const Writer = std.Io.Writer;
1920
2021pub const Error = error{
2122 /// A fatal error has ocurred and compilation has stopped.
......@@ -199,7 +200,7 @@ fn getTimestamp(comp: *Compilation) !u47 {
199200 return @intCast(std.math.clamp(timestamp, 0, max_timestamp));
200201}
201202
202fn generateDateAndTime(w: anytype, timestamp: u47) !void {
203fn generateDateAndTime(w: *Writer, timestamp: u47) !void {
203204 const epoch_seconds = EpochSeconds{ .secs = timestamp };
204205 const epoch_day = epoch_seconds.getEpochDay();
205206 const day_seconds = epoch_seconds.getDaySeconds();
......@@ -242,7 +243,7 @@ pub const SystemDefinesMode = enum {
242243 include_system_defines,
243244};
244245
245fn generateSystemDefines(comp: *Compilation, w: anytype) !void {
246fn generateSystemDefines(comp: *Compilation, w: *Writer) !void {
246247 const ptr_width = comp.target.ptrBitWidth();
247248
248249 if (comp.langopts.gnuc_version > 0) {
......@@ -533,11 +534,20 @@ fn generateSystemDefines(comp: *Compilation, w: anytype) !void {
533534pub fn generateBuiltinMacros(comp: *Compilation, system_defines_mode: SystemDefinesMode) !Source {
534535 try comp.generateBuiltinTypes();
535536
536 var buf = std.array_list.Managed(u8).init(comp.gpa);
537 defer buf.deinit();
537 var allocating: std.Io.Writer.Allocating = .init(comp.gpa);
538 defer allocating.deinit();
539
540 generateBuiltinMacrosWriter(comp, system_defines_mode, &allocating.writer) catch |err| switch (err) {
541 error.WriteFailed => return error.OutOfMemory,
542 else => |e| return e,
543 };
544
545 return comp.addSourceFromBuffer("<builtin>", allocating.written());
546}
538547
548pub fn generateBuiltinMacrosWriter(comp: *Compilation, system_defines_mode: SystemDefinesMode, buf: *Writer) !void {
539549 if (system_defines_mode == .include_system_defines) {
540 try buf.appendSlice(
550 try buf.writeAll(
541551 \\#define __VERSION__ "Aro
542552 ++ " " ++ @import("../backend.zig").version_str ++ "\"\n" ++
543553 \\#define __Aro__
......@@ -545,11 +555,11 @@ pub fn generateBuiltinMacros(comp: *Compilation, system_defines_mode: SystemDefi
545555 );
546556 }
547557
548 try buf.appendSlice("#define __STDC__ 1\n");
549 try buf.writer().print("#define __STDC_HOSTED__ {d}\n", .{@intFromBool(comp.target.os.tag != .freestanding)});
558 try buf.writeAll("#define __STDC__ 1\n");
559 try buf.print("#define __STDC_HOSTED__ {d}\n", .{@intFromBool(comp.target.os.tag != .freestanding)});
550560
551561 // standard macros
552 try buf.appendSlice(
562 try buf.writeAll(
553563 \\#define __STDC_NO_COMPLEX__ 1
554564 \\#define __STDC_NO_THREADS__ 1
555565 \\#define __STDC_NO_VLA__ 1
......@@ -561,23 +571,21 @@ pub fn generateBuiltinMacros(comp: *Compilation, system_defines_mode: SystemDefi
561571 \\
562572 );
563573 if (comp.langopts.standard.StdCVersionMacro()) |stdc_version| {
564 try buf.appendSlice("#define __STDC_VERSION__ ");
565 try buf.appendSlice(stdc_version);
566 try buf.append('\n');
574 try buf.writeAll("#define __STDC_VERSION__ ");
575 try buf.writeAll(stdc_version);
576 try buf.writeByte('\n');
567577 }
568578
569579 // timestamps
570580 const timestamp = try comp.getTimestamp();
571 try generateDateAndTime(buf.writer(), timestamp);
581 try generateDateAndTime(buf, timestamp);
572582
573583 if (system_defines_mode == .include_system_defines) {
574 try comp.generateSystemDefines(buf.writer());
584 try comp.generateSystemDefines(buf);
575585 }
576
577 return comp.addSourceFromBuffer("<builtin>", buf.items);
578586}
579587
580fn generateFloatMacros(w: anytype, prefix: []const u8, semantics: target_util.FPSemantics, ext: []const u8) !void {
588fn generateFloatMacros(w: *Writer, prefix: []const u8, semantics: target_util.FPSemantics, ext: []const u8) !void {
581589 const denormMin = semantics.chooseValue(
582590 []const u8,
583591 .{
......@@ -656,7 +664,7 @@ fn generateFloatMacros(w: anytype, prefix: []const u8, semantics: target_util.FP
656664 try w.print("#define {s}MIN__ {s}{s}\n", .{ prefix_slice, min, ext });
657665}
658666
659fn generateTypeMacro(w: anytype, mapper: StrInt.TypeMapper, name: []const u8, ty: Type, langopts: LangOpts) !void {
667fn generateTypeMacro(w: *Writer, mapper: StrInt.TypeMapper, name: []const u8, ty: Type, langopts: LangOpts) !void {
660668 try w.print("#define {s} ", .{name});
661669 try ty.print(mapper, langopts, w);
662670 try w.writeByte('\n');
......@@ -762,7 +770,7 @@ fn generateFastOrLeastType(
762770 bits: usize,
763771 kind: enum { least, fast },
764772 signedness: std.builtin.Signedness,
765 w: anytype,
773 w: *Writer,
766774 mapper: StrInt.TypeMapper,
767775) !void {
768776 const ty = comp.intLeastN(bits, signedness); // defining the fast types as the least types is permitted
......@@ -793,7 +801,7 @@ fn generateFastOrLeastType(
793801 try comp.generateFmt(prefix, w, ty);
794802}
795803
796fn generateFastAndLeastWidthTypes(comp: *Compilation, w: anytype, mapper: StrInt.TypeMapper) !void {
804fn generateFastAndLeastWidthTypes(comp: *Compilation, w: *Writer, mapper: StrInt.TypeMapper) !void {
797805 const sizes = [_]usize{ 8, 16, 32, 64 };
798806 for (sizes) |size| {
799807 try comp.generateFastOrLeastType(size, .least, .signed, w, mapper);
......@@ -803,7 +811,7 @@ fn generateFastAndLeastWidthTypes(comp: *Compilation, w: anytype, mapper: StrInt
803811 }
804812}
805813
806fn generateExactWidthTypes(comp: *const Compilation, w: anytype, mapper: StrInt.TypeMapper) !void {
814fn generateExactWidthTypes(comp: *const Compilation, w: *Writer, mapper: StrInt.TypeMapper) !void {
807815 try comp.generateExactWidthType(w, mapper, .schar);
808816
809817 if (comp.intSize(.short) > comp.intSize(.char)) {
......@@ -851,7 +859,7 @@ fn generateExactWidthTypes(comp: *const Compilation, w: anytype, mapper: StrInt.
851859 }
852860}
853861
854fn generateFmt(comp: *const Compilation, prefix: []const u8, w: anytype, ty: Type) !void {
862fn generateFmt(comp: *const Compilation, prefix: []const u8, w: *Writer, ty: Type) !void {
855863 const unsigned = ty.isUnsignedInt(comp);
856864 const modifier = ty.formatModifier();
857865 const formats = if (unsigned) "ouxX" else "di";
......@@ -860,7 +868,7 @@ fn generateFmt(comp: *const Compilation, prefix: []const u8, w: anytype, ty: Typ
860868 }
861869}
862870
863fn generateSuffixMacro(comp: *const Compilation, prefix: []const u8, w: anytype, ty: Type) !void {
871fn generateSuffixMacro(comp: *const Compilation, prefix: []const u8, w: *Writer, ty: Type) !void {
864872 return w.print("#define {s}_C_SUFFIX__ {s}\n", .{ prefix, ty.intValueSuffix(comp) });
865873}
866874
......@@ -868,7 +876,7 @@ fn generateSuffixMacro(comp: *const Compilation, prefix: []const u8, w: anytype,
868876/// Name macro (e.g. #define __UINT32_TYPE__ unsigned int)
869877/// Format strings (e.g. #define __UINT32_FMTu__ "u")
870878/// Suffix macro (e.g. #define __UINT32_C_SUFFIX__ U)
871fn generateExactWidthType(comp: *const Compilation, w: anytype, mapper: StrInt.TypeMapper, specifier: Type.Specifier) !void {
879fn generateExactWidthType(comp: *const Compilation, w: *Writer, mapper: StrInt.TypeMapper, specifier: Type.Specifier) !void {
872880 var ty = Type{ .specifier = specifier };
873881 const width = 8 * ty.sizeof(comp).?;
874882 const unsigned = ty.isUnsignedInt(comp);
......@@ -998,7 +1006,7 @@ fn generateVaListType(comp: *Compilation) !Type {
9981006 return ty;
9991007}
10001008
1001fn generateIntMax(comp: *const Compilation, w: anytype, name: []const u8, ty: Type) !void {
1009fn generateIntMax(comp: *const Compilation, w: *Writer, name: []const u8, ty: Type) !void {
10021010 const bit_count: u8 = @intCast(ty.sizeof(comp).? * 8);
10031011 const unsigned = ty.isUnsignedInt(comp);
10041012 const max: u128 = switch (bit_count) {
......@@ -1023,7 +1031,7 @@ pub fn wcharMax(comp: *const Compilation) u32 {
10231031 };
10241032}
10251033
1026fn generateExactWidthIntMax(comp: *const Compilation, w: anytype, specifier: Type.Specifier) !void {
1034fn generateExactWidthIntMax(comp: *const Compilation, w: *Writer, specifier: Type.Specifier) !void {
10271035 var ty = Type{ .specifier = specifier };
10281036 const bit_count: u8 = @intCast(ty.sizeof(comp).? * 8);
10291037 const unsigned = ty.isUnsignedInt(comp);
......@@ -1040,16 +1048,16 @@ fn generateExactWidthIntMax(comp: *const Compilation, w: anytype, specifier: Typ
10401048 return comp.generateIntMax(w, name, ty);
10411049}
10421050
1043fn generateIntWidth(comp: *Compilation, w: anytype, name: []const u8, ty: Type) !void {
1051fn generateIntWidth(comp: *Compilation, w: *Writer, name: []const u8, ty: Type) !void {
10441052 try w.print("#define __{s}_WIDTH__ {d}\n", .{ name, 8 * ty.sizeof(comp).? });
10451053}
10461054
1047fn generateIntMaxAndWidth(comp: *Compilation, w: anytype, name: []const u8, ty: Type) !void {
1055fn generateIntMaxAndWidth(comp: *Compilation, w: *Writer, name: []const u8, ty: Type) !void {
10481056 try comp.generateIntMax(w, name, ty);
10491057 try comp.generateIntWidth(w, name, ty);
10501058}
10511059
1052fn generateSizeofType(comp: *Compilation, w: anytype, name: []const u8, ty: Type) !void {
1060fn generateSizeofType(comp: *Compilation, w: *Writer, name: []const u8, ty: Type) !void {
10531061 try w.print("#define {s} {d}\n", .{ name, ty.sizeof(comp).? });
10541062}
10551063
lib/compiler/aro/aro/Parser.zig+121-45
......@@ -101,7 +101,7 @@ value_map: Tree.ValueMap,
101101
102102// buffers used during compilation
103103syms: SymbolStack = .{},
104strings: std.array_list.AlignedManaged(u8, .@"4"),
104strings: std.array_list.Managed(u8),
105105labels: std.array_list.Managed(Label),
106106list_buf: NodeList,
107107decl_buf: NodeList,
......@@ -447,7 +447,17 @@ pub fn typeStr(p: *Parser, ty: Type) ![]const u8 {
447447 defer p.strings.items.len = strings_top;
448448
449449 const mapper = p.comp.string_interner.getSlowTypeMapper();
450 try ty.print(mapper, p.comp.langopts, p.strings.writer());
450 {
451 var unmanaged = p.strings.moveToUnmanaged();
452 var allocating: std.Io.Writer.Allocating = .fromArrayList(p.comp.gpa, &unmanaged);
453 defer {
454 unmanaged = allocating.toArrayList();
455 p.strings = unmanaged.toManaged(p.comp.gpa);
456 }
457 ty.print(mapper, p.comp.langopts, &allocating.writer) catch |e| switch (e) {
458 error.WriteFailed => return error.OutOfMemory,
459 };
460 }
451461 return try p.comp.diagnostics.arena.allocator().dupe(u8, p.strings.items[strings_top..]);
452462}
453463
......@@ -455,7 +465,7 @@ pub fn typePairStr(p: *Parser, a: Type, b: Type) ![]const u8 {
455465 return p.typePairStrExtra(a, " and ", b);
456466}
457467
458pub fn typePairStrExtra(p: *Parser, a: Type, msg: []const u8, b: Type) ![]const u8 {
468pub fn typePairStrExtra(p: *Parser, a: Type, msg: []const u8, b: Type) Error![]const u8 {
459469 if (@import("builtin").mode != .Debug) {
460470 if (a.is(.invalid) or b.is(.invalid)) {
461471 return "Tried to render invalid type - this is an aro bug.";
......@@ -466,29 +476,60 @@ pub fn typePairStrExtra(p: *Parser, a: Type, msg: []const u8, b: Type) ![]const
466476
467477 try p.strings.append('\'');
468478 const mapper = p.comp.string_interner.getSlowTypeMapper();
469 try a.print(mapper, p.comp.langopts, p.strings.writer());
479 {
480 var unmanaged = p.strings.moveToUnmanaged();
481 var allocating: std.Io.Writer.Allocating = .fromArrayList(p.comp.gpa, &unmanaged);
482 defer {
483 unmanaged = allocating.toArrayList();
484 p.strings = unmanaged.toManaged(p.comp.gpa);
485 }
486 a.print(mapper, p.comp.langopts, &allocating.writer) catch |e| switch (e) {
487 error.WriteFailed => return error.OutOfMemory,
488 };
489 }
470490 try p.strings.append('\'');
471491 try p.strings.appendSlice(msg);
472492 try p.strings.append('\'');
473 try b.print(mapper, p.comp.langopts, p.strings.writer());
493 {
494 var unmanaged = p.strings.moveToUnmanaged();
495 var allocating: std.Io.Writer.Allocating = .fromArrayList(p.comp.gpa, &unmanaged);
496 defer {
497 unmanaged = allocating.toArrayList();
498 p.strings = unmanaged.toManaged(p.comp.gpa);
499 }
500 b.print(mapper, p.comp.langopts, &allocating.writer) catch |e| switch (e) {
501 error.WriteFailed => return error.OutOfMemory,
502 };
503 }
474504 try p.strings.append('\'');
475505 return try p.comp.diagnostics.arena.allocator().dupe(u8, p.strings.items[strings_top..]);
476506}
477507
478pub fn valueChangedStr(p: *Parser, res: *Result, old_value: Value, int_ty: Type) ![]const u8 {
508pub fn valueChangedStr(p: *Parser, res: *Result, old_value: Value, int_ty: Type) Error![]const u8 {
479509 const strings_top = p.strings.items.len;
480510 defer p.strings.items.len = strings_top;
481511
482 var w = p.strings.writer();
483512 const type_pair_str = try p.typePairStrExtra(res.ty, " to ", int_ty);
484 try w.writeAll(type_pair_str);
513 {
514 var unmanaged = p.strings.moveToUnmanaged();
515 var allocating: std.Io.Writer.Allocating = .fromArrayList(p.comp.gpa, &unmanaged);
516 defer {
517 unmanaged = allocating.toArrayList();
518 p.strings = unmanaged.toManaged(p.comp.gpa);
519 }
520 allocating.writer.writeAll(type_pair_str) catch return error.OutOfMemory;
485521
486 try w.writeAll(" changes ");
487 if (res.val.isZero(p.comp)) try w.writeAll("non-zero ");
488 try w.writeAll("value from ");
489 try old_value.print(res.ty, p.comp, w);
490 try w.writeAll(" to ");
491 try res.val.print(int_ty, p.comp, w);
522 allocating.writer.writeAll(" changes ") catch return error.OutOfMemory;
523 if (res.val.isZero(p.comp)) allocating.writer.writeAll("non-zero ") catch return error.OutOfMemory;
524 allocating.writer.writeAll("value from ") catch return error.OutOfMemory;
525 old_value.print(res.ty, p.comp, &allocating.writer) catch |e| switch (e) {
526 error.WriteFailed => return error.OutOfMemory,
527 };
528 allocating.writer.writeAll(" to ") catch return error.OutOfMemory;
529 res.val.print(int_ty, p.comp, &allocating.writer) catch |e| switch (e) {
530 error.WriteFailed => return error.OutOfMemory,
531 };
532 }
492533
493534 return try p.comp.diagnostics.arena.allocator().dupe(u8, p.strings.items[strings_top..]);
494535}
......@@ -498,9 +539,8 @@ fn checkDeprecatedUnavailable(p: *Parser, ty: Type, usage_tok: TokenIndex, decl_
498539 const strings_top = p.strings.items.len;
499540 defer p.strings.items.len = strings_top;
500541
501 const w = p.strings.writer();
502542 const msg_str = p.comp.interner.get(@"error".msg.ref()).bytes;
503 try w.print("call to '{s}' declared with attribute error: {f}", .{
543 try p.strings.print("call to '{s}' declared with attribute error: {f}", .{
504544 p.tokSlice(@"error".__name_tok), std.zig.fmtString(msg_str),
505545 });
506546 const str = try p.comp.diagnostics.arena.allocator().dupe(u8, p.strings.items[strings_top..]);
......@@ -510,9 +550,8 @@ fn checkDeprecatedUnavailable(p: *Parser, ty: Type, usage_tok: TokenIndex, decl_
510550 const strings_top = p.strings.items.len;
511551 defer p.strings.items.len = strings_top;
512552
513 const w = p.strings.writer();
514553 const msg_str = p.comp.interner.get(warning.msg.ref()).bytes;
515 try w.print("call to '{s}' declared with attribute warning: {f}", .{
554 try p.strings.print("call to '{s}' declared with attribute warning: {f}", .{
516555 p.tokSlice(warning.__name_tok), std.zig.fmtString(msg_str),
517556 });
518557 const str = try p.comp.diagnostics.arena.allocator().dupe(u8, p.strings.items[strings_top..]);
......@@ -532,17 +571,16 @@ fn errDeprecated(p: *Parser, tag: Diagnostics.Tag, tok_i: TokenIndex, msg: ?Valu
532571 const strings_top = p.strings.items.len;
533572 defer p.strings.items.len = strings_top;
534573
535 const w = p.strings.writer();
536 try w.print("'{s}' is ", .{p.tokSlice(tok_i)});
574 try p.strings.print("'{s}' is ", .{p.tokSlice(tok_i)});
537575 const reason: []const u8 = switch (tag) {
538576 .unavailable => "unavailable",
539577 .deprecated_declarations => "deprecated",
540578 else => unreachable,
541579 };
542 try w.writeAll(reason);
580 try p.strings.appendSlice(reason);
543581 if (msg) |m| {
544582 const str = p.comp.interner.get(m.ref()).bytes;
545 try w.print(": {f}", .{std.zig.fmtString(str)});
583 try p.strings.print(": {f}", .{std.zig.fmtString(str)});
546584 }
547585 const str = try p.comp.diagnostics.arena.allocator().dupe(u8, p.strings.items[strings_top..]);
548586 return p.errStr(tag, tok_i, str);
......@@ -681,7 +719,7 @@ fn diagnoseIncompleteDefinitions(p: *Parser) !void {
681719}
682720
683721/// root : (decl | assembly ';' | staticAssert)*
684pub fn parse(pp: *Preprocessor) Compilation.Error!Tree {
722pub fn parse(pp: *Preprocessor) Error!Tree {
685723 assert(pp.linemarkers == .none);
686724 pp.comp.pragmaEvent(.before_parse);
687725
......@@ -693,7 +731,7 @@ pub fn parse(pp: *Preprocessor) Compilation.Error!Tree {
693731 .gpa = pp.comp.gpa,
694732 .arena = arena.allocator(),
695733 .tok_ids = pp.tokens.items(.id),
696 .strings = std.array_list.AlignedManaged(u8, .@"4").init(pp.comp.gpa),
734 .strings = std.array_list.Managed(u8).init(pp.comp.gpa),
697735 .value_map = Tree.ValueMap.init(pp.comp.gpa),
698736 .data = NodeList.init(pp.comp.gpa),
699737 .labels = std.array_list.Managed(Label).init(pp.comp.gpa),
......@@ -1218,38 +1256,46 @@ fn decl(p: *Parser) Error!bool {
12181256 return true;
12191257}
12201258
1221fn staticAssertMessage(p: *Parser, cond_node: NodeIndex, message: Result) !?[]const u8 {
1259fn staticAssertMessage(p: *Parser, cond_node: NodeIndex, message: Result) Error!?[]const u8 {
12221260 const cond_tag = p.nodes.items(.tag)[@intFromEnum(cond_node)];
12231261 if (cond_tag != .builtin_types_compatible_p and message.node == .none) return null;
12241262
1225 var buf = std.array_list.Managed(u8).init(p.gpa);
1226 defer buf.deinit();
1263 var allocating: std.Io.Writer.Allocating = .init(p.gpa);
1264 defer allocating.deinit();
1265
1266 const buf = &allocating.writer;
12271267
12281268 if (cond_tag == .builtin_types_compatible_p) {
12291269 const mapper = p.comp.string_interner.getSlowTypeMapper();
12301270 const data = p.nodes.items(.data)[@intFromEnum(cond_node)].bin;
12311271
1232 try buf.appendSlice("'__builtin_types_compatible_p(");
1272 buf.writeAll("'__builtin_types_compatible_p(") catch return error.OutOfMemory;
12331273
12341274 const lhs_ty = p.nodes.items(.ty)[@intFromEnum(data.lhs)];
1235 try lhs_ty.print(mapper, p.comp.langopts, buf.writer());
1236 try buf.appendSlice(", ");
1275 lhs_ty.print(mapper, p.comp.langopts, buf) catch |e| switch (e) {
1276 error.WriteFailed => return error.OutOfMemory,
1277 };
1278 buf.writeAll(", ") catch return error.OutOfMemory;
12371279
12381280 const rhs_ty = p.nodes.items(.ty)[@intFromEnum(data.rhs)];
1239 try rhs_ty.print(mapper, p.comp.langopts, buf.writer());
1281 rhs_ty.print(mapper, p.comp.langopts, buf) catch |e| switch (e) {
1282 error.WriteFailed => return error.OutOfMemory,
1283 };
12401284
1241 try buf.appendSlice(")'");
1285 buf.writeAll(")'") catch return error.OutOfMemory;
12421286 }
12431287 if (message.node != .none) {
12441288 assert(p.nodes.items(.tag)[@intFromEnum(message.node)] == .string_literal_expr);
1245 if (buf.items.len > 0) {
1246 try buf.append(' ');
1289 if (buf.buffered().len > 0) {
1290 buf.writeByte(' ') catch return error.OutOfMemory;
12471291 }
12481292 const bytes = p.comp.interner.get(message.val.ref()).bytes;
1249 try buf.ensureUnusedCapacity(bytes.len);
1250 try Value.printString(bytes, message.ty, p.comp, buf.writer());
1293 try allocating.ensureUnusedCapacity(bytes.len);
1294 Value.printString(bytes, message.ty, p.comp, buf) catch |e| switch (e) {
1295 error.WriteFailed => return error.OutOfMemory,
1296 };
12511297 }
1252 return try p.comp.diagnostics.arena.allocator().dupe(u8, buf.items);
1298 return try p.comp.diagnostics.arena.allocator().dupe(u8, allocating.written());
12531299}
12541300
12551301/// staticAssert
......@@ -4981,7 +5027,7 @@ const CallExpr = union(enum) {
49815027 return true;
49825028 }
49835029
4984 fn checkVarArg(self: CallExpr, p: *Parser, first_after: TokenIndex, param_tok: TokenIndex, arg: *Result, arg_idx: u32) !void {
5030 fn checkVarArg(self: CallExpr, p: *Parser, first_after: TokenIndex, param_tok: TokenIndex, arg: *Result, arg_idx: u32) Error!void {
49855031 if (self == .standard) return;
49865032
49875033 const builtin_tok = p.nodes.items(.data)[@intFromEnum(self.builtin.node)].decl.name;
......@@ -5183,7 +5229,17 @@ pub const Result = struct {
51835229 const strings_top = p.strings.items.len;
51845230 defer p.strings.items.len = strings_top;
51855231
5186 try res.val.print(res.ty, p.comp, p.strings.writer());
5232 {
5233 var unmanaged = p.strings.moveToUnmanaged();
5234 var allocating: std.Io.Writer.Allocating = .fromArrayList(p.comp.gpa, &unmanaged);
5235 defer {
5236 unmanaged = allocating.toArrayList();
5237 p.strings = unmanaged.toManaged(p.comp.gpa);
5238 }
5239 res.val.print(res.ty, p.comp, &allocating.writer) catch |e| switch (e) {
5240 error.WriteFailed => return error.OutOfMemory,
5241 };
5242 }
51875243 return try p.comp.diagnostics.arena.allocator().dupe(u8, p.strings.items[strings_top..]);
51885244 }
51895245
......@@ -5347,7 +5403,7 @@ pub const Result = struct {
53475403 conditional,
53485404 add,
53495405 sub,
5350 }) !bool {
5406 }) Error!bool {
53515407 if (b.ty.specifier == .invalid) {
53525408 try a.saveValue(p);
53535409 a.ty = Type.invalid;
......@@ -5643,7 +5699,7 @@ pub const Result = struct {
56435699 }
56445700 }
56455701
5646 fn floatToIntWarning(res: *Result, p: *Parser, int_ty: Type, old_value: Value, change_kind: Value.FloatToIntChangeKind, tok: TokenIndex) !void {
5702 fn floatToIntWarning(res: *Result, p: *Parser, int_ty: Type, old_value: Value, change_kind: Value.FloatToIntChangeKind, tok: TokenIndex) Error!void {
56475703 switch (change_kind) {
56485704 .none => return p.errStr(.float_to_int, tok, try p.typePairStrExtra(res.ty, " to ", int_ty)),
56495705 .out_of_range => return p.errStr(.float_out_of_range, tok, try p.typePairStrExtra(res.ty, " to ", int_ty)),
......@@ -5866,7 +5922,7 @@ pub const Result = struct {
58665922 res.val = .{};
58675923 }
58685924
5869 fn castType(res: *Result, p: *Parser, to: Type, operand_tok: TokenIndex, l_paren: TokenIndex) !void {
5925 fn castType(res: *Result, p: *Parser, to: Type, operand_tok: TokenIndex, l_paren: TokenIndex) Error!void {
58705926 var cast_kind: Tree.CastKind = undefined;
58715927
58725928 if (to.is(.void)) {
......@@ -7595,9 +7651,19 @@ fn validateFieldAccess(p: *Parser, record_ty: *const Type.Record, expr_ty: Type,
75957651
75967652 p.strings.items.len = 0;
75977653
7598 try p.strings.writer().print("'{s}' in '", .{p.tokSlice(field_name_tok)});
7654 try p.strings.print("'{s}' in '", .{p.tokSlice(field_name_tok)});
75997655 const mapper = p.comp.string_interner.getSlowTypeMapper();
7600 try expr_ty.print(mapper, p.comp.langopts, p.strings.writer());
7656 {
7657 var unmanaged = p.strings.moveToUnmanaged();
7658 var allocating: std.Io.Writer.Allocating = .fromArrayList(p.comp.gpa, &unmanaged);
7659 defer {
7660 unmanaged = allocating.toArrayList();
7661 p.strings = unmanaged.toManaged(p.comp.gpa);
7662 }
7663 expr_ty.print(mapper, p.comp.langopts, &allocating.writer) catch |e| switch (e) {
7664 error.WriteFailed => return error.OutOfMemory,
7665 };
7666 }
76017667 try p.strings.append('\'');
76027668
76037669 const duped = try p.comp.diagnostics.arena.allocator().dupe(u8, p.strings.items);
......@@ -8016,7 +8082,17 @@ fn primaryExpr(p: *Parser) Error!Result {
80168082 defer p.strings.items.len = strings_top;
80178083
80188084 const mapper = p.comp.string_interner.getSlowTypeMapper();
8019 try Type.printNamed(func_ty, p.tokSlice(p.func.name), mapper, p.comp.langopts, p.strings.writer());
8085 {
8086 var unmanaged = p.strings.moveToUnmanaged();
8087 var allocating: std.Io.Writer.Allocating = .fromArrayList(p.comp.gpa, &unmanaged);
8088 defer {
8089 unmanaged = allocating.toArrayList();
8090 p.strings = unmanaged.toManaged(p.comp.gpa);
8091 }
8092 Type.printNamed(func_ty, p.tokSlice(p.func.name), mapper, p.comp.langopts, &allocating.writer) catch |e| switch (e) {
8093 error.WriteFailed => return error.OutOfMemory,
8094 };
8095 }
80208096 try p.strings.append(0);
80218097 const predef = try p.makePredefinedIdentifier(strings_top);
80228098 ty = predef.ty;
lib/compiler/aro/aro/Preprocessor.zig+12-17
......@@ -15,6 +15,7 @@ const TokenWithExpansionLocs = Tree.TokenWithExpansionLocs;
1515const Attribute = @import("Attribute.zig");
1616const features = @import("features.zig");
1717const Hideset = @import("Hideset.zig");
18const Writer = std.Io.Writer;
1819
1920const DefineMap = std.StringHashMapUnmanaged(Macro);
2021const RawTokenList = std.array_list.Managed(RawToken);
......@@ -982,7 +983,7 @@ fn expr(pp: *Preprocessor, tokenizer: *Tokenizer) MacroError!bool {
982983 .tok_i = @intCast(token_state.tokens_len),
983984 .arena = pp.arena.allocator(),
984985 .in_macro = true,
985 .strings = std.array_list.AlignedManaged(u8, .@"4").init(pp.comp.gpa),
986 .strings = std.array_list.Managed(u8).init(pp.comp.gpa),
986987
987988 .data = undefined,
988989 .value_map = undefined,
......@@ -1193,24 +1194,21 @@ fn expandObjMacro(pp: *Preprocessor, simple_macro: *const Macro) Error!ExpandBuf
11931194 .macro_file => {
11941195 const start = pp.comp.generated_buf.items.len;
11951196 const source = pp.comp.getSource(pp.expansion_source_loc.id);
1196 const w = pp.comp.generated_buf.writer(pp.gpa);
1197 try w.print("\"{s}\"\n", .{source.path});
1197 try pp.comp.generated_buf.print(pp.gpa, "\"{s}\"\n", .{source.path});
11981198
11991199 buf.appendAssumeCapacity(try pp.makeGeneratedToken(start, .string_literal, tok));
12001200 },
12011201 .macro_line => {
12021202 const start = pp.comp.generated_buf.items.len;
12031203 const source = pp.comp.getSource(pp.expansion_source_loc.id);
1204 const w = pp.comp.generated_buf.writer(pp.gpa);
1205 try w.print("{d}\n", .{source.physicalLine(pp.expansion_source_loc)});
1204 try pp.comp.generated_buf.print(pp.gpa, "{d}\n", .{source.physicalLine(pp.expansion_source_loc)});
12061205
12071206 buf.appendAssumeCapacity(try pp.makeGeneratedToken(start, .pp_num, tok));
12081207 },
12091208 .macro_counter => {
12101209 defer pp.counter += 1;
12111210 const start = pp.comp.generated_buf.items.len;
1212 const w = pp.comp.generated_buf.writer(pp.gpa);
1213 try w.print("{d}\n", .{pp.counter});
1211 try pp.comp.generated_buf.print(pp.gpa, "{d}\n", .{pp.counter});
12141212
12151213 buf.appendAssumeCapacity(try pp.makeGeneratedToken(start, .pp_num, tok));
12161214 },
......@@ -1682,8 +1680,7 @@ fn expandFuncMacro(
16821680 break :blk false;
16831681 } else try pp.handleBuiltinMacro(raw.id, arg, macro_tok.loc);
16841682 const start = pp.comp.generated_buf.items.len;
1685 const w = pp.comp.generated_buf.writer(pp.gpa);
1686 try w.print("{}\n", .{@intFromBool(result)});
1683 try pp.comp.generated_buf.print(pp.gpa, "{}\n", .{@intFromBool(result)});
16871684 try buf.append(try pp.makeGeneratedToken(start, .pp_num, tokFromRaw(raw)));
16881685 },
16891686 .macro_param_has_c_attribute => {
......@@ -2988,18 +2985,16 @@ fn embed(pp: *Preprocessor, tokenizer: *Tokenizer) MacroError!void {
29882985 // TODO: We currently only support systems with CHAR_BIT == 8
29892986 // If the target's CHAR_BIT is not 8, we need to write out correctly-sized embed_bytes
29902987 // and correctly account for the target's endianness
2991 const writer = pp.comp.generated_buf.writer(pp.gpa);
2992
29932988 {
29942989 const byte = embed_bytes[0];
29952990 const start = pp.comp.generated_buf.items.len;
2996 try writer.print("{d}", .{byte});
2991 try pp.comp.generated_buf.print(pp.gpa, "{d}", .{byte});
29972992 pp.addTokenAssumeCapacity(try pp.makeGeneratedToken(start, .embed_byte, filename_tok));
29982993 }
29992994
30002995 for (embed_bytes[1..]) |byte| {
30012996 const start = pp.comp.generated_buf.items.len;
3002 try writer.print(",{d}", .{byte});
2997 try pp.comp.generated_buf.print(pp.gpa, ",{d}", .{byte});
30032998 pp.addTokenAssumeCapacity(.{ .id = .comma, .loc = .{ .id = .generated, .byte_offset = @intCast(start) } });
30042999 pp.addTokenAssumeCapacity(try pp.makeGeneratedToken(start + 1, .embed_byte, filename_tok));
30053000 }
......@@ -3241,7 +3236,7 @@ fn findIncludeSource(pp: *Preprocessor, tokenizer: *Tokenizer, first: RawToken,
32413236
32423237fn printLinemarker(
32433238 pp: *Preprocessor,
3244 w: anytype,
3239 w: *Writer,
32453240 line_no: u32,
32463241 source: Source,
32473242 start_resume: enum(u8) { start, @"resume", none },
......@@ -3301,7 +3296,7 @@ pub const DumpMode = enum {
33013296/// Pretty-print the macro define or undef at location `loc`.
33023297/// We re-tokenize the directive because we are printing a macro that may have the same name as one in
33033298/// `pp.defines` but a different definition (due to being #undef'ed and then redefined)
3304fn prettyPrintMacro(pp: *Preprocessor, w: anytype, loc: Source.Location, parts: enum { name_only, name_and_body }) !void {
3299fn prettyPrintMacro(pp: *Preprocessor, w: *Writer, loc: Source.Location, parts: enum { name_only, name_and_body }) !void {
33053300 const source = pp.comp.getSource(loc.id);
33063301 var tokenizer: Tokenizer = .{
33073302 .buf = source.buf,
......@@ -3339,7 +3334,7 @@ fn prettyPrintMacro(pp: *Preprocessor, w: anytype, loc: Source.Location, parts:
33393334 }
33403335}
33413336
3342fn prettyPrintMacrosOnly(pp: *Preprocessor, w: anytype) !void {
3337fn prettyPrintMacrosOnly(pp: *Preprocessor, w: *Writer) !void {
33433338 var it = pp.defines.valueIterator();
33443339 while (it.next()) |macro| {
33453340 if (macro.is_builtin) continue;
......@@ -3351,7 +3346,7 @@ fn prettyPrintMacrosOnly(pp: *Preprocessor, w: anytype) !void {
33513346}
33523347
33533348/// Pretty print tokens and try to preserve whitespace.
3354pub fn prettyPrintTokens(pp: *Preprocessor, w: anytype, macro_dump_mode: DumpMode) !void {
3349pub fn prettyPrintTokens(pp: *Preprocessor, w: *Writer, macro_dump_mode: DumpMode) !void {
33553350 if (macro_dump_mode == .macros_only) {
33563351 return pp.prettyPrintMacrosOnly(w);
33573352 }
lib/compiler/aro/aro/Type.zig+9-8
......@@ -9,6 +9,7 @@ const StringInterner = @import("StringInterner.zig");
99const StringId = StringInterner.StringId;
1010const target_util = @import("target.zig");
1111const LangOpts = @import("LangOpts.zig");
12const Writer = std.Io.Writer;
1213
1314pub const Qualifiers = packed struct {
1415 @"const": bool = false,
......@@ -23,7 +24,7 @@ pub const Qualifiers = packed struct {
2324 return quals.@"const" or quals.restrict or quals.@"volatile" or quals.atomic;
2425 }
2526
26 pub fn dump(quals: Qualifiers, w: anytype) !void {
27 pub fn dump(quals: Qualifiers, w: *Writer) !void {
2728 if (quals.@"const") try w.writeAll("const ");
2829 if (quals.atomic) try w.writeAll("_Atomic ");
2930 if (quals.@"volatile") try w.writeAll("volatile ");
......@@ -2411,12 +2412,12 @@ pub fn intValueSuffix(ty: Type, comp: *const Compilation) []const u8 {
24112412}
24122413
24132414/// Print type in C style
2414pub fn print(ty: Type, mapper: StringInterner.TypeMapper, langopts: LangOpts, w: anytype) @TypeOf(w).Error!void {
2415pub fn print(ty: Type, mapper: StringInterner.TypeMapper, langopts: LangOpts, w: *Writer) Writer.Error!void {
24152416 _ = try ty.printPrologue(mapper, langopts, w);
24162417 try ty.printEpilogue(mapper, langopts, w);
24172418}
24182419
2419pub fn printNamed(ty: Type, name: []const u8, mapper: StringInterner.TypeMapper, langopts: LangOpts, w: anytype) @TypeOf(w).Error!void {
2420pub fn printNamed(ty: Type, name: []const u8, mapper: StringInterner.TypeMapper, langopts: LangOpts, w: *Writer) Writer.Error!void {
24202421 const simple = try ty.printPrologue(mapper, langopts, w);
24212422 if (simple) try w.writeByte(' ');
24222423 try w.writeAll(name);
......@@ -2426,7 +2427,7 @@ pub fn printNamed(ty: Type, name: []const u8, mapper: StringInterner.TypeMapper,
24262427const StringGetter = fn (TokenIndex) []const u8;
24272428
24282429/// return true if `ty` is simple
2429fn printPrologue(ty: Type, mapper: StringInterner.TypeMapper, langopts: LangOpts, w: anytype) @TypeOf(w).Error!bool {
2430fn printPrologue(ty: Type, mapper: StringInterner.TypeMapper, langopts: LangOpts, w: *Writer) Writer.Error!bool {
24302431 if (ty.qual.atomic) {
24312432 var non_atomic_ty = ty;
24322433 non_atomic_ty.qual.atomic = false;
......@@ -2497,7 +2498,7 @@ fn printPrologue(ty: Type, mapper: StringInterner.TypeMapper, langopts: LangOpts
24972498 return true;
24982499}
24992500
2500fn printEpilogue(ty: Type, mapper: StringInterner.TypeMapper, langopts: LangOpts, w: anytype) @TypeOf(w).Error!void {
2501fn printEpilogue(ty: Type, mapper: StringInterner.TypeMapper, langopts: LangOpts, w: *Writer) Writer.Error!void {
25012502 if (ty.qual.atomic) return;
25022503 if (ty.isPtr()) {
25032504 const elem_ty = ty.elemType();
......@@ -2564,7 +2565,7 @@ fn printEpilogue(ty: Type, mapper: StringInterner.TypeMapper, langopts: LangOpts
25642565const dump_detailed_containers = false;
25652566
25662567// Print as Zig types since those are actually readable
2567pub fn dump(ty: Type, mapper: StringInterner.TypeMapper, langopts: LangOpts, w: anytype) @TypeOf(w).Error!void {
2568pub fn dump(ty: Type, mapper: StringInterner.TypeMapper, langopts: LangOpts, w: *Writer) Writer.Error!void {
25682569 try ty.qual.dump(w);
25692570 switch (ty.specifier) {
25702571 .invalid => try w.writeAll("invalid"),
......@@ -2656,7 +2657,7 @@ pub fn dump(ty: Type, mapper: StringInterner.TypeMapper, langopts: LangOpts, w:
26562657 }
26572658}
26582659
2659fn dumpEnum(@"enum": *Enum, mapper: StringInterner.TypeMapper, w: anytype) @TypeOf(w).Error!void {
2660fn dumpEnum(@"enum": *Enum, mapper: StringInterner.TypeMapper, w: *Writer) Writer.Error!void {
26602661 try w.writeAll(" {");
26612662 for (@"enum".fields) |field| {
26622663 try w.print(" {s} = {d},", .{ mapper.lookup(field.name), field.value });
......@@ -2664,7 +2665,7 @@ fn dumpEnum(@"enum": *Enum, mapper: StringInterner.TypeMapper, w: anytype) @Type
26642665 try w.writeAll(" }");
26652666}
26662667
2667fn dumpRecord(record: *Record, mapper: StringInterner.TypeMapper, langopts: LangOpts, w: anytype) @TypeOf(w).Error!void {
2668fn dumpRecord(record: *Record, mapper: StringInterner.TypeMapper, langopts: LangOpts, w: *Writer) Writer.Error!void {
26682669 try w.writeAll(" {");
26692670 for (record.fields) |field| {
26702671 try w.writeByte(' ');
lib/compiler/aro/aro/Value.zig+3-2
......@@ -9,6 +9,7 @@ const Compilation = @import("Compilation.zig");
99const Type = @import("Type.zig");
1010const target_util = @import("target.zig");
1111const annex_g = @import("annex_g.zig");
12const Writer = std.Io.Writer;
1213
1314const Value = @This();
1415
......@@ -953,7 +954,7 @@ pub fn maxInt(ty: Type, comp: *Compilation) !Value {
953954 return twosCompIntLimit(.max, ty, comp);
954955}
955956
956pub fn print(v: Value, ty: Type, comp: *const Compilation, w: anytype) @TypeOf(w).Error!void {
957pub fn print(v: Value, ty: Type, comp: *const Compilation, w: *Writer) Writer.Error!void {
957958 if (ty.is(.bool)) {
958959 return w.writeAll(if (v.isZero(comp)) "false" else "true");
959960 }
......@@ -977,7 +978,7 @@ pub fn print(v: Value, ty: Type, comp: *const Compilation, w: anytype) @TypeOf(w
977978 }
978979}
979980
980pub fn printString(bytes: []const u8, ty: Type, comp: *const Compilation, w: anytype) @TypeOf(w).Error!void {
981pub fn printString(bytes: []const u8, ty: Type, comp: *const Compilation, w: *Writer) Writer.Error!void {
981982 const size: Compilation.CharUnitSize = @enumFromInt(ty.elemType().sizeof(comp).?);
982983 const without_null = bytes[0 .. bytes.len - @intFromEnum(size)];
983984 try w.writeByte('"');
lib/compiler/aro_translate_c.zig+10-8
......@@ -116,15 +116,17 @@ pub fn translate(
116116 var driver: aro.Driver = .{ .comp = comp };
117117 defer driver.deinit();
118118
119 var macro_buf = std.array_list.Managed(u8).init(gpa);
119 var macro_buf: std.Io.Writer.Allocating = .init(gpa);
120120 defer macro_buf.deinit();
121121
122 assert(!try driver.parseArgs(std.io.null_writer, macro_buf.writer(), args));
122 var trash: [64]u8 = undefined;
123 var discarding: std.Io.Writer.Discarding = .init(&trash);
124 assert(!try driver.parseArgs(&discarding.writer, &macro_buf.writer, args));
123125 assert(driver.inputs.items.len == 1);
124126 const source = driver.inputs.items[0];
125127
126128 const builtin_macros = try comp.generateBuiltinMacros(.include_system_defines);
127 const user_macros = try comp.addSourceFromBuffer("<command line>", macro_buf.items);
129 const user_macros = try comp.addSourceFromBuffer("<command line>", macro_buf.written());
128130
129131 var pp = try aro.Preprocessor.initDefault(comp);
130132 defer pp.deinit();
......@@ -698,11 +700,10 @@ fn transEnumDecl(c: *Context, scope: *Scope, enum_decl: *const Type.Enum, field_
698700}
699701
700702fn getTypeStr(c: *Context, ty: Type) ![]const u8 {
701 var buf: std.ArrayListUnmanaged(u8) = .empty;
702 defer buf.deinit(c.gpa);
703 const w = buf.writer(c.gpa);
704 try ty.print(c.mapper, c.comp.langopts, w);
705 return c.arena.dupe(u8, buf.items);
703 var allocating: std.Io.Writer.Allocating = .init(c.gpa);
704 defer allocating.deinit();
705 ty.print(c.mapper, c.comp.langopts, &allocating.writer) catch return error.OutOfMemory;
706 return c.arena.dupe(u8, allocating.written());
706707}
707708
708709fn transType(c: *Context, scope: *Scope, raw_ty: Type, qual_handling: Type.QualHandling, source_loc: TokenIndex) TypeError!ZigNode {
......@@ -1820,6 +1821,7 @@ pub fn main() !void {
18201821 var tree = translate(gpa, &aro_comp, args) catch |err| switch (err) {
18211822 error.ParsingFailed, error.FatalError => renderErrorsAndExit(&aro_comp),
18221823 error.OutOfMemory => return error.OutOfMemory,
1824 error.WriteFailed => return error.WriteFailed,
18231825 error.StreamTooLong => std.process.fatal("An input file was larger than 4GiB", .{}),
18241826 };
18251827 defer tree.deinit(gpa);
lib/compiler/aro_translate_c/ast.zig+1-1
......@@ -832,7 +832,7 @@ const Context = struct {
832832
833833 fn addTokenFmt(c: *Context, tag: TokenTag, comptime format: []const u8, args: anytype) Allocator.Error!TokenIndex {
834834 const start_index = c.buf.items.len;
835 try c.buf.writer().print(format ++ " ", args);
835 try c.buf.print(format ++ " ", args);
836836
837837 try c.tokens.append(c.gpa, .{
838838 .tag = tag,
lib/compiler/resinator/ani.zig+13-13
......@@ -16,31 +16,31 @@ const std = @import("std");
1616
1717const AF_ICON: u32 = 1;
1818
19pub fn isAnimatedIcon(reader: anytype) bool {
19pub fn isAnimatedIcon(reader: *std.Io.Reader) bool {
2020 const flags = getAniheaderFlags(reader) catch return false;
2121 return flags & AF_ICON == AF_ICON;
2222}
2323
24fn getAniheaderFlags(reader: anytype) !u32 {
25 const riff_header = try reader.readBytesNoEof(4);
26 if (!std.mem.eql(u8, &riff_header, "RIFF")) return error.InvalidFormat;
24fn getAniheaderFlags(reader: *std.Io.Reader) !u32 {
25 const riff_header = try reader.takeArray(4);
26 if (!std.mem.eql(u8, riff_header, "RIFF")) return error.InvalidFormat;
2727
28 _ = try reader.readInt(u32, .little); // size of RIFF chunk
28 _ = try reader.takeInt(u32, .little); // size of RIFF chunk
2929
30 const form_type = try reader.readBytesNoEof(4);
31 if (!std.mem.eql(u8, &form_type, "ACON")) return error.InvalidFormat;
30 const form_type = try reader.takeArray(4);
31 if (!std.mem.eql(u8, form_type, "ACON")) return error.InvalidFormat;
3232
3333 while (true) {
34 const chunk_id = try reader.readBytesNoEof(4);
35 const chunk_len = try reader.readInt(u32, .little);
36 if (!std.mem.eql(u8, &chunk_id, "anih")) {
34 const chunk_id = try reader.takeArray(4);
35 const chunk_len = try reader.takeInt(u32, .little);
36 if (!std.mem.eql(u8, chunk_id, "anih")) {
3737 // TODO: Move file cursor instead of skipBytes
38 try reader.skipBytes(chunk_len, .{});
38 try reader.discardAll(chunk_len);
3939 continue;
4040 }
4141
42 const aniheader = try reader.readStruct(ANIHEADER);
43 return std.mem.nativeToLittle(u32, aniheader.flags);
42 const aniheader = try reader.takeStruct(ANIHEADER, .little);
43 return aniheader.flags;
4444 }
4545}
4646
lib/compiler/resinator/ast.zig+40-40
......@@ -22,13 +22,13 @@ pub const Tree = struct {
2222 return @alignCast(@fieldParentPtr("base", self.node));
2323 }
2424
25 pub fn dump(self: *Tree, writer: anytype) @TypeOf(writer).Error!void {
25 pub fn dump(self: *Tree, writer: *std.io.Writer) !void {
2626 try self.node.dump(self, writer, 0);
2727 }
2828};
2929
3030pub const CodePageLookup = struct {
31 lookup: std.ArrayListUnmanaged(SupportedCodePage) = .empty,
31 lookup: std.ArrayList(SupportedCodePage) = .empty,
3232 allocator: Allocator,
3333 default_code_page: SupportedCodePage,
3434
......@@ -726,10 +726,10 @@ pub const Node = struct {
726726 pub fn dump(
727727 node: *const Node,
728728 tree: *const Tree,
729 writer: anytype,
729 writer: *std.io.Writer,
730730 indent: usize,
731 ) @TypeOf(writer).Error!void {
732 try writer.writeByteNTimes(' ', indent);
731 ) std.io.Writer.Error!void {
732 try writer.splatByteAll(' ', indent);
733733 try writer.writeAll(@tagName(node.id));
734734 switch (node.id) {
735735 .root => {
......@@ -768,11 +768,11 @@ pub const Node = struct {
768768 .grouped_expression => {
769769 const grouped: *const Node.GroupedExpression = @alignCast(@fieldParentPtr("base", node));
770770 try writer.writeAll("\n");
771 try writer.writeByteNTimes(' ', indent);
771 try writer.splatByteAll(' ', indent);
772772 try writer.writeAll(grouped.open_token.slice(tree.source));
773773 try writer.writeAll("\n");
774774 try grouped.expression.dump(tree, writer, indent + 1);
775 try writer.writeByteNTimes(' ', indent);
775 try writer.splatByteAll(' ', indent);
776776 try writer.writeAll(grouped.close_token.slice(tree.source));
777777 try writer.writeAll("\n");
778778 },
......@@ -790,13 +790,13 @@ pub const Node = struct {
790790 for (accelerators.optional_statements) |statement| {
791791 try statement.dump(tree, writer, indent + 1);
792792 }
793 try writer.writeByteNTimes(' ', indent);
793 try writer.splatByteAll(' ', indent);
794794 try writer.writeAll(accelerators.begin_token.slice(tree.source));
795795 try writer.writeAll("\n");
796796 for (accelerators.accelerators) |accelerator| {
797797 try accelerator.dump(tree, writer, indent + 1);
798798 }
799 try writer.writeByteNTimes(' ', indent);
799 try writer.splatByteAll(' ', indent);
800800 try writer.writeAll(accelerators.end_token.slice(tree.source));
801801 try writer.writeAll("\n");
802802 },
......@@ -815,25 +815,25 @@ pub const Node = struct {
815815 const dialog: *const Node.Dialog = @alignCast(@fieldParentPtr("base", node));
816816 try writer.print(" {s} {s} [{d} common_resource_attributes]\n", .{ dialog.id.slice(tree.source), dialog.type.slice(tree.source), dialog.common_resource_attributes.len });
817817 inline for (.{ "x", "y", "width", "height" }) |arg| {
818 try writer.writeByteNTimes(' ', indent + 1);
818 try writer.splatByteAll(' ', indent + 1);
819819 try writer.writeAll(arg ++ ":\n");
820820 try @field(dialog, arg).dump(tree, writer, indent + 2);
821821 }
822822 if (dialog.help_id) |help_id| {
823 try writer.writeByteNTimes(' ', indent + 1);
823 try writer.splatByteAll(' ', indent + 1);
824824 try writer.writeAll("help_id:\n");
825825 try help_id.dump(tree, writer, indent + 2);
826826 }
827827 for (dialog.optional_statements) |statement| {
828828 try statement.dump(tree, writer, indent + 1);
829829 }
830 try writer.writeByteNTimes(' ', indent);
830 try writer.splatByteAll(' ', indent);
831831 try writer.writeAll(dialog.begin_token.slice(tree.source));
832832 try writer.writeAll("\n");
833833 for (dialog.controls) |control| {
834834 try control.dump(tree, writer, indent + 1);
835835 }
836 try writer.writeByteNTimes(' ', indent);
836 try writer.splatByteAll(' ', indent);
837837 try writer.writeAll(dialog.end_token.slice(tree.source));
838838 try writer.writeAll("\n");
839839 },
......@@ -845,30 +845,30 @@ pub const Node = struct {
845845 }
846846 try writer.writeByte('\n');
847847 if (control.class) |class| {
848 try writer.writeByteNTimes(' ', indent + 1);
848 try writer.splatByteAll(' ', indent + 1);
849849 try writer.writeAll("class:\n");
850850 try class.dump(tree, writer, indent + 2);
851851 }
852852 inline for (.{ "id", "x", "y", "width", "height" }) |arg| {
853 try writer.writeByteNTimes(' ', indent + 1);
853 try writer.splatByteAll(' ', indent + 1);
854854 try writer.writeAll(arg ++ ":\n");
855855 try @field(control, arg).dump(tree, writer, indent + 2);
856856 }
857857 inline for (.{ "style", "exstyle", "help_id" }) |arg| {
858858 if (@field(control, arg)) |val_node| {
859 try writer.writeByteNTimes(' ', indent + 1);
859 try writer.splatByteAll(' ', indent + 1);
860860 try writer.writeAll(arg ++ ":\n");
861861 try val_node.dump(tree, writer, indent + 2);
862862 }
863863 }
864864 if (control.extra_data_begin != null) {
865 try writer.writeByteNTimes(' ', indent);
865 try writer.splatByteAll(' ', indent);
866866 try writer.writeAll(control.extra_data_begin.?.slice(tree.source));
867867 try writer.writeAll("\n");
868868 for (control.extra_data) |data_node| {
869869 try data_node.dump(tree, writer, indent + 1);
870870 }
871 try writer.writeByteNTimes(' ', indent);
871 try writer.splatByteAll(' ', indent);
872872 try writer.writeAll(control.extra_data_end.?.slice(tree.source));
873873 try writer.writeAll("\n");
874874 }
......@@ -877,17 +877,17 @@ pub const Node = struct {
877877 const toolbar: *const Node.Toolbar = @alignCast(@fieldParentPtr("base", node));
878878 try writer.print(" {s} {s} [{d} common_resource_attributes]\n", .{ toolbar.id.slice(tree.source), toolbar.type.slice(tree.source), toolbar.common_resource_attributes.len });
879879 inline for (.{ "button_width", "button_height" }) |arg| {
880 try writer.writeByteNTimes(' ', indent + 1);
880 try writer.splatByteAll(' ', indent + 1);
881881 try writer.writeAll(arg ++ ":\n");
882882 try @field(toolbar, arg).dump(tree, writer, indent + 2);
883883 }
884 try writer.writeByteNTimes(' ', indent);
884 try writer.splatByteAll(' ', indent);
885885 try writer.writeAll(toolbar.begin_token.slice(tree.source));
886886 try writer.writeAll("\n");
887887 for (toolbar.buttons) |button_or_sep| {
888888 try button_or_sep.dump(tree, writer, indent + 1);
889889 }
890 try writer.writeByteNTimes(' ', indent);
890 try writer.splatByteAll(' ', indent);
891891 try writer.writeAll(toolbar.end_token.slice(tree.source));
892892 try writer.writeAll("\n");
893893 },
......@@ -898,17 +898,17 @@ pub const Node = struct {
898898 try statement.dump(tree, writer, indent + 1);
899899 }
900900 if (menu.help_id) |help_id| {
901 try writer.writeByteNTimes(' ', indent + 1);
901 try writer.splatByteAll(' ', indent + 1);
902902 try writer.writeAll("help_id:\n");
903903 try help_id.dump(tree, writer, indent + 2);
904904 }
905 try writer.writeByteNTimes(' ', indent);
905 try writer.splatByteAll(' ', indent);
906906 try writer.writeAll(menu.begin_token.slice(tree.source));
907907 try writer.writeAll("\n");
908908 for (menu.items) |item| {
909909 try item.dump(tree, writer, indent + 1);
910910 }
911 try writer.writeByteNTimes(' ', indent);
911 try writer.splatByteAll(' ', indent);
912912 try writer.writeAll(menu.end_token.slice(tree.source));
913913 try writer.writeAll("\n");
914914 },
......@@ -926,7 +926,7 @@ pub const Node = struct {
926926 try writer.print(" {s} {s}\n", .{ menu_item.menuitem.slice(tree.source), menu_item.text.slice(tree.source) });
927927 inline for (.{ "id", "type", "state" }) |arg| {
928928 if (@field(menu_item, arg)) |val_node| {
929 try writer.writeByteNTimes(' ', indent + 1);
929 try writer.splatByteAll(' ', indent + 1);
930930 try writer.writeAll(arg ++ ":\n");
931931 try val_node.dump(tree, writer, indent + 2);
932932 }
......@@ -935,13 +935,13 @@ pub const Node = struct {
935935 .popup => {
936936 const popup: *const Node.Popup = @alignCast(@fieldParentPtr("base", node));
937937 try writer.print(" {s} {s} [{d} options]\n", .{ popup.popup.slice(tree.source), popup.text.slice(tree.source), popup.option_list.len });
938 try writer.writeByteNTimes(' ', indent);
938 try writer.splatByteAll(' ', indent);
939939 try writer.writeAll(popup.begin_token.slice(tree.source));
940940 try writer.writeAll("\n");
941941 for (popup.items) |item| {
942942 try item.dump(tree, writer, indent + 1);
943943 }
944 try writer.writeByteNTimes(' ', indent);
944 try writer.splatByteAll(' ', indent);
945945 try writer.writeAll(popup.end_token.slice(tree.source));
946946 try writer.writeAll("\n");
947947 },
......@@ -950,18 +950,18 @@ pub const Node = struct {
950950 try writer.print(" {s} {s}\n", .{ popup.popup.slice(tree.source), popup.text.slice(tree.source) });
951951 inline for (.{ "id", "type", "state", "help_id" }) |arg| {
952952 if (@field(popup, arg)) |val_node| {
953 try writer.writeByteNTimes(' ', indent + 1);
953 try writer.splatByteAll(' ', indent + 1);
954954 try writer.writeAll(arg ++ ":\n");
955955 try val_node.dump(tree, writer, indent + 2);
956956 }
957957 }
958 try writer.writeByteNTimes(' ', indent);
958 try writer.splatByteAll(' ', indent);
959959 try writer.writeAll(popup.begin_token.slice(tree.source));
960960 try writer.writeAll("\n");
961961 for (popup.items) |item| {
962962 try item.dump(tree, writer, indent + 1);
963963 }
964 try writer.writeByteNTimes(' ', indent);
964 try writer.splatByteAll(' ', indent);
965965 try writer.writeAll(popup.end_token.slice(tree.source));
966966 try writer.writeAll("\n");
967967 },
......@@ -971,13 +971,13 @@ pub const Node = struct {
971971 for (version_info.fixed_info) |fixed_info| {
972972 try fixed_info.dump(tree, writer, indent + 1);
973973 }
974 try writer.writeByteNTimes(' ', indent);
974 try writer.splatByteAll(' ', indent);
975975 try writer.writeAll(version_info.begin_token.slice(tree.source));
976976 try writer.writeAll("\n");
977977 for (version_info.block_statements) |block| {
978978 try block.dump(tree, writer, indent + 1);
979979 }
980 try writer.writeByteNTimes(' ', indent);
980 try writer.splatByteAll(' ', indent);
981981 try writer.writeAll(version_info.end_token.slice(tree.source));
982982 try writer.writeAll("\n");
983983 },
......@@ -994,13 +994,13 @@ pub const Node = struct {
994994 for (block.values) |value| {
995995 try value.dump(tree, writer, indent + 1);
996996 }
997 try writer.writeByteNTimes(' ', indent);
997 try writer.splatByteAll(' ', indent);
998998 try writer.writeAll(block.begin_token.slice(tree.source));
999999 try writer.writeAll("\n");
10001000 for (block.children) |child| {
10011001 try child.dump(tree, writer, indent + 1);
10021002 }
1003 try writer.writeByteNTimes(' ', indent);
1003 try writer.splatByteAll(' ', indent);
10041004 try writer.writeAll(block.end_token.slice(tree.source));
10051005 try writer.writeAll("\n");
10061006 },
......@@ -1025,13 +1025,13 @@ pub const Node = struct {
10251025 for (string_table.optional_statements) |statement| {
10261026 try statement.dump(tree, writer, indent + 1);
10271027 }
1028 try writer.writeByteNTimes(' ', indent);
1028 try writer.splatByteAll(' ', indent);
10291029 try writer.writeAll(string_table.begin_token.slice(tree.source));
10301030 try writer.writeAll("\n");
10311031 for (string_table.strings) |string| {
10321032 try string.dump(tree, writer, indent + 1);
10331033 }
1034 try writer.writeByteNTimes(' ', indent);
1034 try writer.splatByteAll(' ', indent);
10351035 try writer.writeAll(string_table.end_token.slice(tree.source));
10361036 try writer.writeAll("\n");
10371037 },
......@@ -1039,7 +1039,7 @@ pub const Node = struct {
10391039 try writer.writeAll("\n");
10401040 const string: *const Node.StringTableString = @alignCast(@fieldParentPtr("base", node));
10411041 try string.id.dump(tree, writer, indent + 1);
1042 try writer.writeByteNTimes(' ', indent + 1);
1042 try writer.splatByteAll(' ', indent + 1);
10431043 try writer.print("{s}\n", .{string.string.slice(tree.source)});
10441044 },
10451045 .language_statement => {
......@@ -1051,12 +1051,12 @@ pub const Node = struct {
10511051 .font_statement => {
10521052 const font: *const Node.FontStatement = @alignCast(@fieldParentPtr("base", node));
10531053 try writer.print(" {s} typeface: {s}\n", .{ font.identifier.slice(tree.source), font.typeface.slice(tree.source) });
1054 try writer.writeByteNTimes(' ', indent + 1);
1054 try writer.splatByteAll(' ', indent + 1);
10551055 try writer.writeAll("point_size:\n");
10561056 try font.point_size.dump(tree, writer, indent + 2);
10571057 inline for (.{ "weight", "italic", "char_set" }) |arg| {
10581058 if (@field(font, arg)) |arg_node| {
1059 try writer.writeByteNTimes(' ', indent + 1);
1059 try writer.splatByteAll(' ', indent + 1);
10601060 try writer.writeAll(arg ++ ":\n");
10611061 try arg_node.dump(tree, writer, indent + 2);
10621062 }
......@@ -1071,7 +1071,7 @@ pub const Node = struct {
10711071 const invalid: *const Node.Invalid = @alignCast(@fieldParentPtr("base", node));
10721072 try writer.print(" context.len: {}\n", .{invalid.context.len});
10731073 for (invalid.context) |context_token| {
1074 try writer.writeByteNTimes(' ', indent + 1);
1074 try writer.splatByteAll(' ', indent + 1);
10751075 try writer.print("{s}:{s}", .{ @tagName(context_token.id), context_token.slice(tree.source) });
10761076 try writer.writeByte('\n');
10771077 }
lib/compiler/resinator/bmp.zig+25-15
......@@ -27,6 +27,7 @@ pub const windows_format_id = std.mem.readInt(u16, "BM", native_endian);
2727pub const file_header_len = 14;
2828
2929pub const ReadError = error{
30 ReadFailed,
3031 UnexpectedEOF,
3132 InvalidFileHeader,
3233 ImpossiblePixelDataOffset,
......@@ -94,9 +95,12 @@ pub const BitmapInfo = struct {
9495 }
9596};
9697
97pub fn read(reader: anytype, max_size: u64) ReadError!BitmapInfo {
98pub fn read(reader: *std.Io.Reader, max_size: u64) ReadError!BitmapInfo {
9899 var bitmap_info: BitmapInfo = undefined;
99 const file_header = reader.readBytesNoEof(file_header_len) catch return error.UnexpectedEOF;
100 const file_header = reader.takeArray(file_header_len) catch |err| switch (err) {
101 error.EndOfStream => return error.UnexpectedEOF,
102 else => |e| return e,
103 };
100104
101105 const id = std.mem.readInt(u16, file_header[0..2], native_endian);
102106 if (id != windows_format_id) return error.InvalidFileHeader;
......@@ -104,14 +108,17 @@ pub fn read(reader: anytype, max_size: u64) ReadError!BitmapInfo {
104108 bitmap_info.pixel_data_offset = std.mem.readInt(u32, file_header[10..14], .little);
105109 if (bitmap_info.pixel_data_offset > max_size) return error.ImpossiblePixelDataOffset;
106110
107 bitmap_info.dib_header_size = reader.readInt(u32, .little) catch return error.UnexpectedEOF;
111 bitmap_info.dib_header_size = reader.takeInt(u32, .little) catch return error.UnexpectedEOF;
108112 if (bitmap_info.pixel_data_offset < file_header_len + bitmap_info.dib_header_size) return error.ImpossiblePixelDataOffset;
109113 const dib_version = BitmapHeader.Version.get(bitmap_info.dib_header_size);
110114 switch (dib_version) {
111115 .@"nt3.1", .@"nt4.0", .@"nt5.0" => {
112116 var dib_header_buf: [@sizeOf(BITMAPINFOHEADER)]u8 align(@alignOf(BITMAPINFOHEADER)) = undefined;
113117 std.mem.writeInt(u32, dib_header_buf[0..4], bitmap_info.dib_header_size, .little);
114 reader.readNoEof(dib_header_buf[4..]) catch return error.UnexpectedEOF;
118 reader.readSliceAll(dib_header_buf[4..]) catch |err| switch (err) {
119 error.EndOfStream => return error.UnexpectedEOF,
120 error.ReadFailed => |e| return e,
121 };
115122 var dib_header: *BITMAPINFOHEADER = @ptrCast(&dib_header_buf);
116123 structFieldsLittleToNative(BITMAPINFOHEADER, dib_header);
117124
......@@ -126,7 +133,10 @@ pub fn read(reader: anytype, max_size: u64) ReadError!BitmapInfo {
126133 .@"win2.0" => {
127134 var dib_header_buf: [@sizeOf(BITMAPCOREHEADER)]u8 align(@alignOf(BITMAPCOREHEADER)) = undefined;
128135 std.mem.writeInt(u32, dib_header_buf[0..4], bitmap_info.dib_header_size, .little);
129 reader.readNoEof(dib_header_buf[4..]) catch return error.UnexpectedEOF;
136 reader.readSliceAll(dib_header_buf[4..]) catch |err| switch (err) {
137 error.EndOfStream => return error.UnexpectedEOF,
138 error.ReadFailed => |e| return e,
139 };
130140 const dib_header: *BITMAPCOREHEADER = @ptrCast(&dib_header_buf);
131141 structFieldsLittleToNative(BITMAPCOREHEADER, dib_header);
132142
......@@ -238,26 +248,26 @@ fn structFieldsLittleToNative(comptime T: type, x: *T) void {
238248
239249test "read" {
240250 var bmp_data = "BM<\x00\x00\x00\x00\x00\x00\x006\x00\x00\x00(\x00\x00\x00\x01\x00\x00\x00\x01\x00\x00\x00\x01\x00\x10\x00\x00\x00\x00\x00\x06\x00\x00\x00\x12\x0b\x00\x00\x12\x0b\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\x7f\x00\x00\x00\x00".*;
241 var fbs = std.io.fixedBufferStream(&bmp_data);
251 var fbs: std.Io.Reader = .fixed(&bmp_data);
242252
243253 {
244 const bitmap = try read(fbs.reader(), bmp_data.len);
254 const bitmap = try read(&fbs, bmp_data.len);
245255 try std.testing.expectEqual(@as(u32, BitmapHeader.Version.@"nt3.1".len()), bitmap.dib_header_size);
246256 }
247257
248258 {
249 fbs.reset();
259 fbs.seek = 0;
250260 bmp_data[file_header_len] = 11;
251 try std.testing.expectError(error.UnknownBitmapVersion, read(fbs.reader(), bmp_data.len));
261 try std.testing.expectError(error.UnknownBitmapVersion, read(&fbs, bmp_data.len));
252262
253263 // restore
254264 bmp_data[file_header_len] = BitmapHeader.Version.@"nt3.1".len();
255265 }
256266
257267 {
258 fbs.reset();
268 fbs.seek = 0;
259269 bmp_data[0] = 'b';
260 try std.testing.expectError(error.InvalidFileHeader, read(fbs.reader(), bmp_data.len));
270 try std.testing.expectError(error.InvalidFileHeader, read(&fbs, bmp_data.len));
261271
262272 // restore
263273 bmp_data[0] = 'B';
......@@ -265,13 +275,13 @@ test "read" {
265275
266276 {
267277 const cutoff_len = file_header_len + BitmapHeader.Version.@"nt3.1".len() - 1;
268 var dib_cutoff_fbs = std.io.fixedBufferStream(bmp_data[0..cutoff_len]);
269 try std.testing.expectError(error.UnexpectedEOF, read(dib_cutoff_fbs.reader(), bmp_data.len));
278 var dib_cutoff_fbs: std.Io.Reader = .fixed(bmp_data[0..cutoff_len]);
279 try std.testing.expectError(error.UnexpectedEOF, read(&dib_cutoff_fbs, bmp_data.len));
270280 }
271281
272282 {
273283 const cutoff_len = file_header_len - 1;
274 var bmp_cutoff_fbs = std.io.fixedBufferStream(bmp_data[0..cutoff_len]);
275 try std.testing.expectError(error.UnexpectedEOF, read(bmp_cutoff_fbs.reader(), bmp_data.len));
284 var bmp_cutoff_fbs: std.Io.Reader = .fixed(bmp_data[0..cutoff_len]);
285 try std.testing.expectError(error.UnexpectedEOF, read(&bmp_cutoff_fbs, bmp_data.len));
276286 }
277287}
lib/compiler/resinator/cli.zig+77-138
......@@ -80,20 +80,20 @@ pub const usage_string_after_command_name =
8080 \\
8181;
8282
83pub fn writeUsage(writer: anytype, command_name: []const u8) !void {
83pub fn writeUsage(writer: *std.Io.Writer, command_name: []const u8) !void {
8484 try writer.writeAll("Usage: ");
8585 try writer.writeAll(command_name);
8686 try writer.writeAll(usage_string_after_command_name);
8787}
8888
8989pub const Diagnostics = struct {
90 errors: std.ArrayListUnmanaged(ErrorDetails) = .empty,
90 errors: std.ArrayList(ErrorDetails) = .empty,
9191 allocator: Allocator,
9292
9393 pub const ErrorDetails = struct {
9494 arg_index: usize,
9595 arg_span: ArgSpan = .{},
96 msg: std.ArrayListUnmanaged(u8) = .empty,
96 msg: std.ArrayList(u8) = .empty,
9797 type: Type = .err,
9898 print_args: bool = true,
9999
......@@ -148,7 +148,7 @@ pub const Options = struct {
148148 allocator: Allocator,
149149 input_source: IoSource = .{ .filename = &[_]u8{} },
150150 output_source: IoSource = .{ .filename = &[_]u8{} },
151 extra_include_paths: std.ArrayListUnmanaged([]const u8) = .empty,
151 extra_include_paths: std.ArrayList([]const u8) = .empty,
152152 ignore_include_env_var: bool = false,
153153 preprocess: Preprocess = .yes,
154154 default_language_id: ?u16 = null,
......@@ -295,7 +295,7 @@ pub const Options = struct {
295295 }
296296 }
297297
298 pub fn dumpVerbose(self: *const Options, writer: anytype) !void {
298 pub fn dumpVerbose(self: *const Options, writer: *std.Io.Writer) !void {
299299 const input_source_name = switch (self.input_source) {
300300 .stdio => "<stdin>",
301301 .filename => |filename| filename,
......@@ -520,8 +520,7 @@ pub fn parse(allocator: Allocator, args: []const []const u8, diagnostics: *Diagn
520520 // - or / on its own is an error
521521 else => {
522522 var err_details = Diagnostics.ErrorDetails{ .arg_index = arg_i, .arg_span = arg.optionAndAfterSpan() };
523 var msg_writer = err_details.msg.writer(allocator);
524 try msg_writer.print("invalid option: {s}", .{arg.prefixSlice()});
523 try err_details.msg.print(allocator, "invalid option: {s}", .{arg.prefixSlice()});
525524 try diagnostics.append(err_details);
526525 arg_i += 1;
527526 continue :next_arg;
......@@ -532,8 +531,7 @@ pub fn parse(allocator: Allocator, args: []const []const u8, diagnostics: *Diagn
532531 const args_remaining = args.len - arg_i;
533532 if (args_remaining <= 2 and arg.looksLikeFilepath()) {
534533 var err_details = Diagnostics.ErrorDetails{ .type = .note, .print_args = true, .arg_index = arg_i };
535 var msg_writer = err_details.msg.writer(allocator);
536 try msg_writer.writeAll("this argument was inferred to be a filepath, so argument parsing was terminated");
534 try err_details.msg.appendSlice(allocator, "this argument was inferred to be a filepath, so argument parsing was terminated");
537535 try diagnostics.append(err_details);
538536
539537 break;
......@@ -550,16 +548,14 @@ pub fn parse(allocator: Allocator, args: []const []const u8, diagnostics: *Diagn
550548 } else if (std.ascii.startsWithIgnoreCase(arg_name, ":output-format")) {
551549 const value = arg.value(":output-format".len, arg_i, args) catch {
552550 var err_details = Diagnostics.ErrorDetails{ .arg_index = arg_i, .arg_span = arg.missingSpan() };
553 var msg_writer = err_details.msg.writer(allocator);
554 try msg_writer.print("missing value after {s}{s} option", .{ arg.prefixSlice(), arg.optionWithoutPrefix(":output-format".len) });
551 try err_details.msg.print(allocator, "missing value after {s}{s} option", .{ arg.prefixSlice(), arg.optionWithoutPrefix(":output-format".len) });
555552 try diagnostics.append(err_details);
556553 arg_i += 1;
557554 break :next_arg;
558555 };
559556 output_format = std.meta.stringToEnum(Options.OutputFormat, value.slice) orelse blk: {
560557 var err_details = Diagnostics.ErrorDetails{ .arg_index = arg_i, .arg_span = value.argSpan(arg) };
561 var msg_writer = err_details.msg.writer(allocator);
562 try msg_writer.print("invalid output format setting: {s} ", .{value.slice});
558 try err_details.msg.print(allocator, "invalid output format setting: {s} ", .{value.slice});
563559 try diagnostics.append(err_details);
564560 break :blk output_format;
565561 };
......@@ -569,16 +565,14 @@ pub fn parse(allocator: Allocator, args: []const []const u8, diagnostics: *Diagn
569565 } else if (std.ascii.startsWithIgnoreCase(arg_name, ":auto-includes")) {
570566 const value = arg.value(":auto-includes".len, arg_i, args) catch {
571567 var err_details = Diagnostics.ErrorDetails{ .arg_index = arg_i, .arg_span = arg.missingSpan() };
572 var msg_writer = err_details.msg.writer(allocator);
573 try msg_writer.print("missing value after {s}{s} option", .{ arg.prefixSlice(), arg.optionWithoutPrefix(":auto-includes".len) });
568 try err_details.msg.print(allocator, "missing value after {s}{s} option", .{ arg.prefixSlice(), arg.optionWithoutPrefix(":auto-includes".len) });
574569 try diagnostics.append(err_details);
575570 arg_i += 1;
576571 break :next_arg;
577572 };
578573 options.auto_includes = std.meta.stringToEnum(Options.AutoIncludes, value.slice) orelse blk: {
579574 var err_details = Diagnostics.ErrorDetails{ .arg_index = arg_i, .arg_span = value.argSpan(arg) };
580 var msg_writer = err_details.msg.writer(allocator);
581 try msg_writer.print("invalid auto includes setting: {s} ", .{value.slice});
575 try err_details.msg.print(allocator, "invalid auto includes setting: {s} ", .{value.slice});
582576 try diagnostics.append(err_details);
583577 break :blk options.auto_includes;
584578 };
......@@ -587,16 +581,14 @@ pub fn parse(allocator: Allocator, args: []const []const u8, diagnostics: *Diagn
587581 } else if (std.ascii.startsWithIgnoreCase(arg_name, ":input-format")) {
588582 const value = arg.value(":input-format".len, arg_i, args) catch {
589583 var err_details = Diagnostics.ErrorDetails{ .arg_index = arg_i, .arg_span = arg.missingSpan() };
590 var msg_writer = err_details.msg.writer(allocator);
591 try msg_writer.print("missing value after {s}{s} option", .{ arg.prefixSlice(), arg.optionWithoutPrefix(":input-format".len) });
584 try err_details.msg.print(allocator, "missing value after {s}{s} option", .{ arg.prefixSlice(), arg.optionWithoutPrefix(":input-format".len) });
592585 try diagnostics.append(err_details);
593586 arg_i += 1;
594587 break :next_arg;
595588 };
596589 input_format = std.meta.stringToEnum(Options.InputFormat, value.slice) orelse blk: {
597590 var err_details = Diagnostics.ErrorDetails{ .arg_index = arg_i, .arg_span = value.argSpan(arg) };
598 var msg_writer = err_details.msg.writer(allocator);
599 try msg_writer.print("invalid input format setting: {s} ", .{value.slice});
591 try err_details.msg.print(allocator, "invalid input format setting: {s} ", .{value.slice});
600592 try diagnostics.append(err_details);
601593 break :blk input_format;
602594 };
......@@ -606,16 +598,14 @@ pub fn parse(allocator: Allocator, args: []const []const u8, diagnostics: *Diagn
606598 } else if (std.ascii.startsWithIgnoreCase(arg_name, ":depfile-fmt")) {
607599 const value = arg.value(":depfile-fmt".len, arg_i, args) catch {
608600 var err_details = Diagnostics.ErrorDetails{ .arg_index = arg_i, .arg_span = arg.missingSpan() };
609 var msg_writer = err_details.msg.writer(allocator);
610 try msg_writer.print("missing value after {s}{s} option", .{ arg.prefixSlice(), arg.optionWithoutPrefix(":depfile-fmt".len) });
601 try err_details.msg.print(allocator, "missing value after {s}{s} option", .{ arg.prefixSlice(), arg.optionWithoutPrefix(":depfile-fmt".len) });
611602 try diagnostics.append(err_details);
612603 arg_i += 1;
613604 break :next_arg;
614605 };
615606 options.depfile_fmt = std.meta.stringToEnum(Options.DepfileFormat, value.slice) orelse blk: {
616607 var err_details = Diagnostics.ErrorDetails{ .arg_index = arg_i, .arg_span = value.argSpan(arg) };
617 var msg_writer = err_details.msg.writer(allocator);
618 try msg_writer.print("invalid depfile format setting: {s} ", .{value.slice});
608 try err_details.msg.print(allocator, "invalid depfile format setting: {s} ", .{value.slice});
619609 try diagnostics.append(err_details);
620610 break :blk options.depfile_fmt;
621611 };
......@@ -624,8 +614,7 @@ pub fn parse(allocator: Allocator, args: []const []const u8, diagnostics: *Diagn
624614 } else if (std.ascii.startsWithIgnoreCase(arg_name, ":depfile")) {
625615 const value = arg.value(":depfile".len, arg_i, args) catch {
626616 var err_details = Diagnostics.ErrorDetails{ .arg_index = arg_i, .arg_span = arg.missingSpan() };
627 var msg_writer = err_details.msg.writer(allocator);
628 try msg_writer.print("missing value after {s}{s} option", .{ arg.prefixSlice(), arg.optionWithoutPrefix(":depfile".len) });
617 try err_details.msg.print(allocator, "missing value after {s}{s} option", .{ arg.prefixSlice(), arg.optionWithoutPrefix(":depfile".len) });
629618 try diagnostics.append(err_details);
630619 arg_i += 1;
631620 break :next_arg;
......@@ -643,8 +632,7 @@ pub fn parse(allocator: Allocator, args: []const []const u8, diagnostics: *Diagn
643632 } else if (std.ascii.startsWithIgnoreCase(arg_name, ":target")) {
644633 const value = arg.value(":target".len, arg_i, args) catch {
645634 var err_details = Diagnostics.ErrorDetails{ .arg_index = arg_i, .arg_span = arg.missingSpan() };
646 var msg_writer = err_details.msg.writer(allocator);
647 try msg_writer.print("missing value after {s}{s} option", .{ arg.prefixSlice(), arg.optionWithoutPrefix(":target".len) });
635 try err_details.msg.print(allocator, "missing value after {s}{s} option", .{ arg.prefixSlice(), arg.optionWithoutPrefix(":target".len) });
648636 try diagnostics.append(err_details);
649637 arg_i += 1;
650638 break :next_arg;
......@@ -655,8 +643,7 @@ pub fn parse(allocator: Allocator, args: []const []const u8, diagnostics: *Diagn
655643 const arch_str = target_it.first();
656644 const arch = cvtres.supported_targets.Arch.fromStringIgnoreCase(arch_str) orelse {
657645 var err_details = Diagnostics.ErrorDetails{ .arg_index = arg_i, .arg_span = value.argSpan(arg) };
658 var msg_writer = err_details.msg.writer(allocator);
659 try msg_writer.print("invalid or unsupported target architecture: {s}", .{arch_str});
646 try err_details.msg.print(allocator, "invalid or unsupported target architecture: {s}", .{arch_str});
660647 try diagnostics.append(err_details);
661648 arg_i += value.index_increment;
662649 continue :next_arg;
......@@ -680,13 +667,11 @@ pub fn parse(allocator: Allocator, args: []const []const u8, diagnostics: *Diagn
680667 .prefix_len = arg.prefixSlice().len,
681668 .value_offset = arg.name_offset + 3,
682669 } };
683 var msg_writer = err_details.msg.writer(allocator);
684 try msg_writer.print("missing value for {s}{s} option", .{ arg.prefixSlice(), arg.optionWithoutPrefix(3) });
670 try err_details.msg.print(allocator, "missing value for {s}{s} option", .{ arg.prefixSlice(), arg.optionWithoutPrefix(3) });
685671 try diagnostics.append(err_details);
686672 }
687673 var err_details = Diagnostics.ErrorDetails{ .type = .err, .arg_index = arg_i, .arg_span = arg.optionAndAfterSpan() };
688 var msg_writer = err_details.msg.writer(allocator);
689 try msg_writer.print("the {s}{s} option is unsupported", .{ arg.prefixSlice(), arg.optionWithoutPrefix(3) });
674 try err_details.msg.print(allocator, "the {s}{s} option is unsupported", .{ arg.prefixSlice(), arg.optionWithoutPrefix(3) });
690675 try diagnostics.append(err_details);
691676 arg_i += 1;
692677 continue :next_arg;
......@@ -695,16 +680,14 @@ pub fn parse(allocator: Allocator, args: []const []const u8, diagnostics: *Diagn
695680 else if (std.ascii.startsWithIgnoreCase(arg_name, "tn")) {
696681 const value = arg.value(2, arg_i, args) catch no_value: {
697682 var err_details = Diagnostics.ErrorDetails{ .arg_index = arg_i, .arg_span = arg.missingSpan() };
698 var msg_writer = err_details.msg.writer(allocator);
699 try msg_writer.print("missing value after {s}{s} option", .{ arg.prefixSlice(), arg.optionWithoutPrefix(2) });
683 try err_details.msg.print(allocator, "missing value after {s}{s} option", .{ arg.prefixSlice(), arg.optionWithoutPrefix(2) });
700684 try diagnostics.append(err_details);
701685 // dummy zero-length slice starting where the value would have been
702686 const value_start = arg.name_offset + 2;
703687 break :no_value Arg.Value{ .slice = arg.full[value_start..value_start] };
704688 };
705689 var err_details = Diagnostics.ErrorDetails{ .type = .err, .arg_index = arg_i, .arg_span = arg.optionAndAfterSpan() };
706 var msg_writer = err_details.msg.writer(allocator);
707 try msg_writer.print("the {s}{s} option is unsupported", .{ arg.prefixSlice(), arg.optionWithoutPrefix(2) });
690 try err_details.msg.print(allocator, "the {s}{s} option is unsupported", .{ arg.prefixSlice(), arg.optionWithoutPrefix(2) });
708691 try diagnostics.append(err_details);
709692 arg_i += value.index_increment;
710693 continue :next_arg;
......@@ -716,16 +699,14 @@ pub fn parse(allocator: Allocator, args: []const []const u8, diagnostics: *Diagn
716699 {
717700 const value = arg.value(2, arg_i, args) catch no_value: {
718701 var err_details = Diagnostics.ErrorDetails{ .arg_index = arg_i, .arg_span = arg.missingSpan() };
719 var msg_writer = err_details.msg.writer(allocator);
720 try msg_writer.print("missing value after {s}{s} option", .{ arg.prefixSlice(), arg.optionWithoutPrefix(2) });
702 try err_details.msg.print(allocator, "missing value after {s}{s} option", .{ arg.prefixSlice(), arg.optionWithoutPrefix(2) });
721703 try diagnostics.append(err_details);
722704 // dummy zero-length slice starting where the value would have been
723705 const value_start = arg.name_offset + 2;
724706 break :no_value Arg.Value{ .slice = arg.full[value_start..value_start] };
725707 };
726708 var err_details = Diagnostics.ErrorDetails{ .type = .err, .arg_index = arg_i, .arg_span = arg.optionAndAfterSpan() };
727 var msg_writer = err_details.msg.writer(allocator);
728 try msg_writer.print("the {s}{s} option is unsupported", .{ arg.prefixSlice(), arg.optionWithoutPrefix(2) });
709 try err_details.msg.print(allocator, "the {s}{s} option is unsupported", .{ arg.prefixSlice(), arg.optionWithoutPrefix(2) });
729710 try diagnostics.append(err_details);
730711 arg_i += value.index_increment;
731712 continue :next_arg;
......@@ -733,8 +714,7 @@ pub fn parse(allocator: Allocator, args: []const []const u8, diagnostics: *Diagn
733714 // Unsupported MUI options that do not need a value
734715 else if (std.ascii.startsWithIgnoreCase(arg_name, "g1")) {
735716 var err_details = Diagnostics.ErrorDetails{ .type = .err, .arg_index = arg_i, .arg_span = arg.optionSpan(2) };
736 var msg_writer = err_details.msg.writer(allocator);
737 try msg_writer.print("the {s}{s} option is unsupported", .{ arg.prefixSlice(), arg.optionWithoutPrefix(2) });
717 try err_details.msg.print(allocator, "the {s}{s} option is unsupported", .{ arg.prefixSlice(), arg.optionWithoutPrefix(2) });
738718 try diagnostics.append(err_details);
739719 arg.name_offset += 2;
740720 }
......@@ -747,15 +727,13 @@ pub fn parse(allocator: Allocator, args: []const []const u8, diagnostics: *Diagn
747727 std.ascii.startsWithIgnoreCase(arg_name, "ta"))
748728 {
749729 var err_details = Diagnostics.ErrorDetails{ .type = .err, .arg_index = arg_i, .arg_span = arg.optionSpan(2) };
750 var msg_writer = err_details.msg.writer(allocator);
751 try msg_writer.print("the {s}{s} option is unsupported", .{ arg.prefixSlice(), arg.optionWithoutPrefix(2) });
730 try err_details.msg.print(allocator, "the {s}{s} option is unsupported", .{ arg.prefixSlice(), arg.optionWithoutPrefix(2) });
752731 try diagnostics.append(err_details);
753732 arg.name_offset += 2;
754733 } else if (std.ascii.startsWithIgnoreCase(arg_name, "fo")) {
755734 const value = arg.value(2, arg_i, args) catch {
756735 var err_details = Diagnostics.ErrorDetails{ .arg_index = arg_i, .arg_span = arg.missingSpan() };
757 var msg_writer = err_details.msg.writer(allocator);
758 try msg_writer.print("missing output path after {s}{s} option", .{ arg.prefixSlice(), arg.optionWithoutPrefix(2) });
736 try err_details.msg.print(allocator, "missing output path after {s}{s} option", .{ arg.prefixSlice(), arg.optionWithoutPrefix(2) });
759737 try diagnostics.append(err_details);
760738 arg_i += 1;
761739 break :next_arg;
......@@ -767,8 +745,7 @@ pub fn parse(allocator: Allocator, args: []const []const u8, diagnostics: *Diagn
767745 } else if (std.ascii.startsWithIgnoreCase(arg_name, "sl")) {
768746 const value = arg.value(2, arg_i, args) catch {
769747 var err_details = Diagnostics.ErrorDetails{ .arg_index = arg_i, .arg_span = arg.missingSpan() };
770 var msg_writer = err_details.msg.writer(allocator);
771 try msg_writer.print("missing language tag after {s}{s} option", .{ arg.prefixSlice(), arg.optionWithoutPrefix(2) });
748 try err_details.msg.print(allocator, "missing language tag after {s}{s} option", .{ arg.prefixSlice(), arg.optionWithoutPrefix(2) });
772749 try diagnostics.append(err_details);
773750 arg_i += 1;
774751 break :next_arg;
......@@ -776,24 +753,20 @@ pub fn parse(allocator: Allocator, args: []const []const u8, diagnostics: *Diagn
776753 const percent_str = value.slice;
777754 const percent: u32 = parsePercent(percent_str) catch {
778755 var err_details = Diagnostics.ErrorDetails{ .arg_index = arg_i, .arg_span = value.argSpan(arg) };
779 var msg_writer = err_details.msg.writer(allocator);
780 try msg_writer.print("invalid percent format '{s}'", .{percent_str});
756 try err_details.msg.print(allocator, "invalid percent format '{s}'", .{percent_str});
781757 try diagnostics.append(err_details);
782758 var note_details = Diagnostics.ErrorDetails{ .type = .note, .print_args = false, .arg_index = arg_i };
783 var note_writer = note_details.msg.writer(allocator);
784 try note_writer.writeAll("string length percent must be an integer between 1 and 100 (inclusive)");
759 try note_details.msg.appendSlice(allocator, "string length percent must be an integer between 1 and 100 (inclusive)");
785760 try diagnostics.append(note_details);
786761 arg_i += value.index_increment;
787762 continue :next_arg;
788763 };
789764 if (percent == 0 or percent > 100) {
790765 var err_details = Diagnostics.ErrorDetails{ .arg_index = arg_i, .arg_span = value.argSpan(arg) };
791 var msg_writer = err_details.msg.writer(allocator);
792 try msg_writer.print("percent out of range: {} (parsed from '{s}')", .{ percent, percent_str });
766 try err_details.msg.print(allocator, "percent out of range: {} (parsed from '{s}')", .{ percent, percent_str });
793767 try diagnostics.append(err_details);
794768 var note_details = Diagnostics.ErrorDetails{ .type = .note, .print_args = false, .arg_index = arg_i };
795 var note_writer = note_details.msg.writer(allocator);
796 try note_writer.writeAll("string length percent must be an integer between 1 and 100 (inclusive)");
769 try note_details.msg.appendSlice(allocator, "string length percent must be an integer between 1 and 100 (inclusive)");
797770 try diagnostics.append(note_details);
798771 arg_i += value.index_increment;
799772 continue :next_arg;
......@@ -805,8 +778,7 @@ pub fn parse(allocator: Allocator, args: []const []const u8, diagnostics: *Diagn
805778 } else if (std.ascii.startsWithIgnoreCase(arg_name, "ln")) {
806779 const value = arg.value(2, arg_i, args) catch {
807780 var err_details = Diagnostics.ErrorDetails{ .arg_index = arg_i, .arg_span = arg.missingSpan() };
808 var msg_writer = err_details.msg.writer(allocator);
809 try msg_writer.print("missing language tag after {s}{s} option", .{ arg.prefixSlice(), arg.optionWithoutPrefix(2) });
781 try err_details.msg.print(allocator, "missing language tag after {s}{s} option", .{ arg.prefixSlice(), arg.optionWithoutPrefix(2) });
810782 try diagnostics.append(err_details);
811783 arg_i += 1;
812784 break :next_arg;
......@@ -814,16 +786,14 @@ pub fn parse(allocator: Allocator, args: []const []const u8, diagnostics: *Diagn
814786 const tag = value.slice;
815787 options.default_language_id = lang.tagToInt(tag) catch {
816788 var err_details = Diagnostics.ErrorDetails{ .arg_index = arg_i, .arg_span = value.argSpan(arg) };
817 var msg_writer = err_details.msg.writer(allocator);
818 try msg_writer.print("invalid language tag: {s}", .{tag});
789 try err_details.msg.print(allocator, "invalid language tag: {s}", .{tag});
819790 try diagnostics.append(err_details);
820791 arg_i += value.index_increment;
821792 continue :next_arg;
822793 };
823794 if (options.default_language_id.? == lang.LOCALE_CUSTOM_UNSPECIFIED) {
824795 var err_details = Diagnostics.ErrorDetails{ .type = .warning, .arg_index = arg_i, .arg_span = value.argSpan(arg) };
825 var msg_writer = err_details.msg.writer(allocator);
826 try msg_writer.print("language tag '{s}' does not have an assigned ID so it will be resolved to LOCALE_CUSTOM_UNSPECIFIED (id=0x{x})", .{ tag, lang.LOCALE_CUSTOM_UNSPECIFIED });
796 try err_details.msg.print(allocator, "language tag '{s}' does not have an assigned ID so it will be resolved to LOCALE_CUSTOM_UNSPECIFIED (id=0x{x})", .{ tag, lang.LOCALE_CUSTOM_UNSPECIFIED });
827797 try diagnostics.append(err_details);
828798 }
829799 arg_i += value.index_increment;
......@@ -831,8 +801,7 @@ pub fn parse(allocator: Allocator, args: []const []const u8, diagnostics: *Diagn
831801 } else if (std.ascii.startsWithIgnoreCase(arg_name, "l")) {
832802 const value = arg.value(1, arg_i, args) catch {
833803 var err_details = Diagnostics.ErrorDetails{ .arg_index = arg_i, .arg_span = arg.missingSpan() };
834 var msg_writer = err_details.msg.writer(allocator);
835 try msg_writer.print("missing language ID after {s}{s} option", .{ arg.prefixSlice(), arg.optionWithoutPrefix(1) });
804 try err_details.msg.print(allocator, "missing language ID after {s}{s} option", .{ arg.prefixSlice(), arg.optionWithoutPrefix(1) });
836805 try diagnostics.append(err_details);
837806 arg_i += 1;
838807 break :next_arg;
......@@ -840,8 +809,7 @@ pub fn parse(allocator: Allocator, args: []const []const u8, diagnostics: *Diagn
840809 const num_str = value.slice;
841810 options.default_language_id = lang.parseInt(num_str) catch {
842811 var err_details = Diagnostics.ErrorDetails{ .arg_index = arg_i, .arg_span = value.argSpan(arg) };
843 var msg_writer = err_details.msg.writer(allocator);
844 try msg_writer.print("invalid language ID: {s}", .{num_str});
812 try err_details.msg.print(allocator, "invalid language ID: {s}", .{num_str});
845813 try diagnostics.append(err_details);
846814 arg_i += value.index_increment;
847815 continue :next_arg;
......@@ -860,16 +828,14 @@ pub fn parse(allocator: Allocator, args: []const []const u8, diagnostics: *Diagn
860828 {
861829 const value = arg.value(1, arg_i, args) catch no_value: {
862830 var err_details = Diagnostics.ErrorDetails{ .arg_index = arg_i, .arg_span = arg.missingSpan() };
863 var msg_writer = err_details.msg.writer(allocator);
864 try msg_writer.print("missing value after {s}{s} option", .{ arg.prefixSlice(), arg.optionWithoutPrefix(1) });
831 try err_details.msg.print(allocator, "missing value after {s}{s} option", .{ arg.prefixSlice(), arg.optionWithoutPrefix(1) });
865832 try diagnostics.append(err_details);
866833 // dummy zero-length slice starting where the value would have been
867834 const value_start = arg.name_offset + 1;
868835 break :no_value Arg.Value{ .slice = arg.full[value_start..value_start] };
869836 };
870837 var err_details = Diagnostics.ErrorDetails{ .type = .err, .arg_index = arg_i, .arg_span = arg.optionAndAfterSpan() };
871 var msg_writer = err_details.msg.writer(allocator);
872 try msg_writer.print("the {s}{s} option is unsupported", .{ arg.prefixSlice(), arg.optionWithoutPrefix(1) });
838 try err_details.msg.print(allocator, "the {s}{s} option is unsupported", .{ arg.prefixSlice(), arg.optionWithoutPrefix(1) });
873839 try diagnostics.append(err_details);
874840 arg_i += value.index_increment;
875841 continue :next_arg;
......@@ -882,16 +848,14 @@ pub fn parse(allocator: Allocator, args: []const []const u8, diagnostics: *Diagn
882848 {
883849 const value = arg.value(1, arg_i, args) catch no_value: {
884850 var err_details = Diagnostics.ErrorDetails{ .arg_index = arg_i, .arg_span = arg.missingSpan() };
885 var msg_writer = err_details.msg.writer(allocator);
886 try msg_writer.print("missing value after {s}{s} option", .{ arg.prefixSlice(), arg.optionWithoutPrefix(1) });
851 try err_details.msg.print(allocator, "missing value after {s}{s} option", .{ arg.prefixSlice(), arg.optionWithoutPrefix(1) });
887852 try diagnostics.append(err_details);
888853 // dummy zero-length slice starting where the value would have been
889854 const value_start = arg.name_offset + 1;
890855 break :no_value Arg.Value{ .slice = arg.full[value_start..value_start] };
891856 };
892857 var err_details = Diagnostics.ErrorDetails{ .type = .err, .arg_index = arg_i, .arg_span = arg.optionAndAfterSpan() };
893 var msg_writer = err_details.msg.writer(allocator);
894 try msg_writer.print("the {s}{s} option is unsupported", .{ arg.prefixSlice(), arg.optionWithoutPrefix(1) });
858 try err_details.msg.print(allocator, "the {s}{s} option is unsupported", .{ arg.prefixSlice(), arg.optionWithoutPrefix(1) });
895859 try diagnostics.append(err_details);
896860 arg_i += value.index_increment;
897861 continue :next_arg;
......@@ -899,15 +863,13 @@ pub fn parse(allocator: Allocator, args: []const []const u8, diagnostics: *Diagn
899863 // 1 char unsupported LCX/LCE options that do not need a value
900864 else if (std.ascii.startsWithIgnoreCase(arg_name, "t")) {
901865 var err_details = Diagnostics.ErrorDetails{ .type = .err, .arg_index = arg_i, .arg_span = arg.optionSpan(1) };
902 var msg_writer = err_details.msg.writer(allocator);
903 try msg_writer.print("the {s}{s} option is unsupported", .{ arg.prefixSlice(), arg.optionWithoutPrefix(1) });
866 try err_details.msg.print(allocator, "the {s}{s} option is unsupported", .{ arg.prefixSlice(), arg.optionWithoutPrefix(1) });
904867 try diagnostics.append(err_details);
905868 arg.name_offset += 1;
906869 } else if (std.ascii.startsWithIgnoreCase(arg_name, "c")) {
907870 const value = arg.value(1, arg_i, args) catch {
908871 var err_details = Diagnostics.ErrorDetails{ .arg_index = arg_i, .arg_span = arg.missingSpan() };
909 var msg_writer = err_details.msg.writer(allocator);
910 try msg_writer.print("missing code page ID after {s}{s} option", .{ arg.prefixSlice(), arg.optionWithoutPrefix(1) });
872 try err_details.msg.print(allocator, "missing code page ID after {s}{s} option", .{ arg.prefixSlice(), arg.optionWithoutPrefix(1) });
911873 try diagnostics.append(err_details);
912874 arg_i += 1;
913875 break :next_arg;
......@@ -915,8 +877,7 @@ pub fn parse(allocator: Allocator, args: []const []const u8, diagnostics: *Diagn
915877 const num_str = value.slice;
916878 const code_page_id = std.fmt.parseUnsigned(u16, num_str, 10) catch {
917879 var err_details = Diagnostics.ErrorDetails{ .arg_index = arg_i, .arg_span = value.argSpan(arg) };
918 var msg_writer = err_details.msg.writer(allocator);
919 try msg_writer.print("invalid code page ID: {s}", .{num_str});
880 try err_details.msg.print(allocator, "invalid code page ID: {s}", .{num_str});
920881 try diagnostics.append(err_details);
921882 arg_i += value.index_increment;
922883 continue :next_arg;
......@@ -924,16 +885,14 @@ pub fn parse(allocator: Allocator, args: []const []const u8, diagnostics: *Diagn
924885 options.default_code_page = code_pages.getByIdentifierEnsureSupported(code_page_id) catch |err| switch (err) {
925886 error.InvalidCodePage => {
926887 var err_details = Diagnostics.ErrorDetails{ .arg_index = arg_i, .arg_span = value.argSpan(arg) };
927 var msg_writer = err_details.msg.writer(allocator);
928 try msg_writer.print("invalid or unknown code page ID: {}", .{code_page_id});
888 try err_details.msg.print(allocator, "invalid or unknown code page ID: {}", .{code_page_id});
929889 try diagnostics.append(err_details);
930890 arg_i += value.index_increment;
931891 continue :next_arg;
932892 },
933893 error.UnsupportedCodePage => {
934894 var err_details = Diagnostics.ErrorDetails{ .arg_index = arg_i, .arg_span = value.argSpan(arg) };
935 var msg_writer = err_details.msg.writer(allocator);
936 try msg_writer.print("unsupported code page: {s} (id={})", .{
895 try err_details.msg.print(allocator, "unsupported code page: {s} (id={})", .{
937896 @tagName(code_pages.getByIdentifier(code_page_id) catch unreachable),
938897 code_page_id,
939898 });
......@@ -957,8 +916,7 @@ pub fn parse(allocator: Allocator, args: []const []const u8, diagnostics: *Diagn
957916 } else if (std.ascii.startsWithIgnoreCase(arg_name, "i")) {
958917 const value = arg.value(1, arg_i, args) catch {
959918 var err_details = Diagnostics.ErrorDetails{ .arg_index = arg_i, .arg_span = arg.missingSpan() };
960 var msg_writer = err_details.msg.writer(allocator);
961 try msg_writer.print("missing include path after {s}{s} option", .{ arg.prefixSlice(), arg.optionWithoutPrefix(1) });
919 try err_details.msg.print(allocator, "missing include path after {s}{s} option", .{ arg.prefixSlice(), arg.optionWithoutPrefix(1) });
962920 try diagnostics.append(err_details);
963921 arg_i += 1;
964922 break :next_arg;
......@@ -986,15 +944,13 @@ pub fn parse(allocator: Allocator, args: []const []const u8, diagnostics: *Diagn
986944 // Undocumented option with unknown function
987945 // TODO: More investigation to figure out what it does (if anything)
988946 var err_details = Diagnostics.ErrorDetails{ .type = .warning, .arg_index = arg_i, .arg_span = arg.optionSpan(1) };
989 var msg_writer = err_details.msg.writer(allocator);
990 try msg_writer.print("option {s}{s} has no effect (it is undocumented and its function is unknown in the Win32 RC compiler)", .{ arg.prefixSlice(), arg.optionWithoutPrefix(1) });
947 try err_details.msg.print(allocator, "option {s}{s} has no effect (it is undocumented and its function is unknown in the Win32 RC compiler)", .{ arg.prefixSlice(), arg.optionWithoutPrefix(1) });
991948 try diagnostics.append(err_details);
992949 arg.name_offset += 1;
993950 } else if (std.ascii.startsWithIgnoreCase(arg_name, "d")) {
994951 const value = arg.value(1, arg_i, args) catch {
995952 var err_details = Diagnostics.ErrorDetails{ .arg_index = arg_i, .arg_span = arg.missingSpan() };
996 var msg_writer = err_details.msg.writer(allocator);
997 try msg_writer.print("missing symbol to define after {s}{s} option", .{ arg.prefixSlice(), arg.optionWithoutPrefix(1) });
953 try err_details.msg.print(allocator, "missing symbol to define after {s}{s} option", .{ arg.prefixSlice(), arg.optionWithoutPrefix(1) });
998954 try diagnostics.append(err_details);
999955 arg_i += 1;
1000956 break :next_arg;
......@@ -1009,8 +965,7 @@ pub fn parse(allocator: Allocator, args: []const []const u8, diagnostics: *Diagn
1009965 try options.define(symbol, symbol_value);
1010966 } else {
1011967 var err_details = Diagnostics.ErrorDetails{ .type = .warning, .arg_index = arg_i, .arg_span = value.argSpan(arg) };
1012 var msg_writer = err_details.msg.writer(allocator);
1013 try msg_writer.print("symbol \"{s}\" is not a valid identifier and therefore cannot be defined", .{symbol});
968 try err_details.msg.print(allocator, "symbol \"{s}\" is not a valid identifier and therefore cannot be defined", .{symbol});
1014969 try diagnostics.append(err_details);
1015970 }
1016971 arg_i += value.index_increment;
......@@ -1018,8 +973,7 @@ pub fn parse(allocator: Allocator, args: []const []const u8, diagnostics: *Diagn
1018973 } else if (std.ascii.startsWithIgnoreCase(arg_name, "u")) {
1019974 const value = arg.value(1, arg_i, args) catch {
1020975 var err_details = Diagnostics.ErrorDetails{ .arg_index = arg_i, .arg_span = arg.missingSpan() };
1021 var msg_writer = err_details.msg.writer(allocator);
1022 try msg_writer.print("missing symbol to undefine after {s}{s} option", .{ arg.prefixSlice(), arg.optionWithoutPrefix(1) });
976 try err_details.msg.print(allocator, "missing symbol to undefine after {s}{s} option", .{ arg.prefixSlice(), arg.optionWithoutPrefix(1) });
1023977 try diagnostics.append(err_details);
1024978 arg_i += 1;
1025979 break :next_arg;
......@@ -1029,16 +983,14 @@ pub fn parse(allocator: Allocator, args: []const []const u8, diagnostics: *Diagn
1029983 try options.undefine(symbol);
1030984 } else {
1031985 var err_details = Diagnostics.ErrorDetails{ .type = .warning, .arg_index = arg_i, .arg_span = value.argSpan(arg) };
1032 var msg_writer = err_details.msg.writer(allocator);
1033 try msg_writer.print("symbol \"{s}\" is not a valid identifier and therefore cannot be undefined", .{symbol});
986 try err_details.msg.print(allocator, "symbol \"{s}\" is not a valid identifier and therefore cannot be undefined", .{symbol});
1034987 try diagnostics.append(err_details);
1035988 }
1036989 arg_i += value.index_increment;
1037990 continue :next_arg;
1038991 } else {
1039992 var err_details = Diagnostics.ErrorDetails{ .arg_index = arg_i, .arg_span = arg.optionAndAfterSpan() };
1040 var msg_writer = err_details.msg.writer(allocator);
1041 try msg_writer.print("invalid option: {s}{s}", .{ arg.prefixSlice(), arg.name() });
993 try err_details.msg.print(allocator, "invalid option: {s}{s}", .{ arg.prefixSlice(), arg.name() });
1042994 try diagnostics.append(err_details);
1043995 arg_i += 1;
1044996 continue :next_arg;
......@@ -1055,16 +1007,14 @@ pub fn parse(allocator: Allocator, args: []const []const u8, diagnostics: *Diagn
10551007
10561008 if (positionals.len == 0) {
10571009 var err_details = Diagnostics.ErrorDetails{ .print_args = false, .arg_index = arg_i };
1058 var msg_writer = err_details.msg.writer(allocator);
1059 try msg_writer.writeAll("missing input filename");
1010 try err_details.msg.appendSlice(allocator, "missing input filename");
10601011 try diagnostics.append(err_details);
10611012
10621013 if (args.len > 0) {
10631014 const last_arg = args[args.len - 1];
10641015 if (arg_i > 0 and last_arg.len > 0 and last_arg[0] == '/' and isSupportedInputExtension(std.fs.path.extension(last_arg))) {
10651016 var note_details = Diagnostics.ErrorDetails{ .type = .note, .print_args = true, .arg_index = arg_i - 1 };
1066 var note_writer = note_details.msg.writer(allocator);
1067 try note_writer.writeAll("if this argument was intended to be the input filename, adding -- in front of it will exclude it from option parsing");
1017 try note_details.msg.appendSlice(allocator, "if this argument was intended to be the input filename, adding -- in front of it will exclude it from option parsing");
10681018 try diagnostics.append(note_details);
10691019 }
10701020 }
......@@ -1099,16 +1049,14 @@ pub fn parse(allocator: Allocator, args: []const []const u8, diagnostics: *Diagn
10991049 if (positionals.len > 1) {
11001050 if (output_filename != null) {
11011051 var err_details = Diagnostics.ErrorDetails{ .arg_index = arg_i + 1 };
1102 var msg_writer = err_details.msg.writer(allocator);
1103 try msg_writer.writeAll("output filename already specified");
1052 try err_details.msg.appendSlice(allocator, "output filename already specified");
11041053 try diagnostics.append(err_details);
11051054 var note_details = Diagnostics.ErrorDetails{
11061055 .type = .note,
11071056 .arg_index = output_filename_context.arg.index,
11081057 .arg_span = output_filename_context.arg.value.argSpan(output_filename_context.arg.arg),
11091058 };
1110 var note_writer = note_details.msg.writer(allocator);
1111 try note_writer.writeAll("output filename previously specified here");
1059 try note_details.msg.appendSlice(allocator, "output filename previously specified here");
11121060 try diagnostics.append(note_details);
11131061 } else {
11141062 output_filename = positionals[1];
......@@ -1173,16 +1121,15 @@ pub fn parse(allocator: Allocator, args: []const []const u8, diagnostics: *Diagn
11731121 var print_output_format_source_note: bool = false;
11741122 if (options.depfile_path != null and (options.input_format == .res or options.output_format == .rcpp)) {
11751123 var err_details = Diagnostics.ErrorDetails{ .type = .warning, .arg_index = depfile_context.index, .arg_span = depfile_context.value.argSpan(depfile_context.arg) };
1176 var msg_writer = err_details.msg.writer(allocator);
11771124 if (options.input_format == .res) {
1178 try msg_writer.print("the {s}{s} option was ignored because the input format is '{s}'", .{
1125 try err_details.msg.print(allocator, "the {s}{s} option was ignored because the input format is '{s}'", .{
11791126 depfile_context.arg.prefixSlice(),
11801127 depfile_context.arg.optionWithoutPrefix(depfile_context.option_len),
11811128 @tagName(options.input_format),
11821129 });
11831130 print_input_format_source_note = true;
11841131 } else if (options.output_format == .rcpp) {
1185 try msg_writer.print("the {s}{s} option was ignored because the output format is '{s}'", .{
1132 try err_details.msg.print(allocator, "the {s}{s} option was ignored because the output format is '{s}'", .{
11861133 depfile_context.arg.prefixSlice(),
11871134 depfile_context.arg.optionWithoutPrefix(depfile_context.option_len),
11881135 @tagName(options.output_format),
......@@ -1193,16 +1140,14 @@ pub fn parse(allocator: Allocator, args: []const []const u8, diagnostics: *Diagn
11931140 }
11941141 if (!isSupportedTransformation(options.input_format, options.output_format)) {
11951142 var err_details = Diagnostics.ErrorDetails{ .arg_index = input_filename_arg_i, .print_args = false };
1196 var msg_writer = err_details.msg.writer(allocator);
1197 try msg_writer.print("input format '{s}' cannot be converted to output format '{s}'", .{ @tagName(options.input_format), @tagName(options.output_format) });
1143 try err_details.msg.print(allocator, "input format '{s}' cannot be converted to output format '{s}'", .{ @tagName(options.input_format), @tagName(options.output_format) });
11981144 try diagnostics.append(err_details);
11991145 print_input_format_source_note = true;
12001146 print_output_format_source_note = true;
12011147 }
12021148 if (options.preprocess == .only and options.output_format != .rcpp) {
12031149 var err_details = Diagnostics.ErrorDetails{ .arg_index = preprocess_only_context.index };
1204 var msg_writer = err_details.msg.writer(allocator);
1205 try msg_writer.print("the {s}{s} option cannot be used with output format '{s}'", .{
1150 try err_details.msg.print(allocator, "the {s}{s} option cannot be used with output format '{s}'", .{
12061151 preprocess_only_context.arg.prefixSlice(),
12071152 preprocess_only_context.arg.optionWithoutPrefix(preprocess_only_context.option_len),
12081153 @tagName(options.output_format),
......@@ -1214,8 +1159,7 @@ pub fn parse(allocator: Allocator, args: []const []const u8, diagnostics: *Diagn
12141159 switch (input_format_source) {
12151160 .inferred_from_input_filename => {
12161161 var err_details = Diagnostics.ErrorDetails{ .type = .note, .arg_index = input_filename_arg_i };
1217 var msg_writer = err_details.msg.writer(allocator);
1218 try msg_writer.writeAll("the input format was inferred from the input filename");
1162 try err_details.msg.appendSlice(allocator, "the input format was inferred from the input filename");
12191163 try diagnostics.append(err_details);
12201164 },
12211165 .input_format_arg => {
......@@ -1224,8 +1168,7 @@ pub fn parse(allocator: Allocator, args: []const []const u8, diagnostics: *Diagn
12241168 .arg_index = input_format_context.index,
12251169 .arg_span = input_format_context.value.argSpan(input_format_context.arg),
12261170 };
1227 var msg_writer = err_details.msg.writer(allocator);
1228 try msg_writer.writeAll("the input format was specified here");
1171 try err_details.msg.appendSlice(allocator, "the input format was specified here");
12291172 try diagnostics.append(err_details);
12301173 },
12311174 }
......@@ -1234,11 +1177,10 @@ pub fn parse(allocator: Allocator, args: []const []const u8, diagnostics: *Diagn
12341177 switch (output_format_source) {
12351178 .inferred_from_input_filename, .unable_to_infer_from_input_filename => {
12361179 var err_details = Diagnostics.ErrorDetails{ .type = .note, .arg_index = input_filename_arg_i };
1237 var msg_writer = err_details.msg.writer(allocator);
12381180 if (output_format_source == .inferred_from_input_filename) {
1239 try msg_writer.writeAll("the output format was inferred from the input filename");
1181 try err_details.msg.appendSlice(allocator, "the output format was inferred from the input filename");
12401182 } else {
1241 try msg_writer.writeAll("the output format was unable to be inferred from the input filename, so the default was used");
1183 try err_details.msg.appendSlice(allocator, "the output format was unable to be inferred from the input filename, so the default was used");
12421184 }
12431185 try diagnostics.append(err_details);
12441186 },
......@@ -1248,11 +1190,10 @@ pub fn parse(allocator: Allocator, args: []const []const u8, diagnostics: *Diagn
12481190 .arg => |ctx| .{ .type = .note, .arg_index = ctx.index, .arg_span = ctx.value.argSpan(ctx.arg) },
12491191 .unspecified => unreachable,
12501192 };
1251 var msg_writer = err_details.msg.writer(allocator);
12521193 if (output_format_source == .inferred_from_output_filename) {
1253 try msg_writer.writeAll("the output format was inferred from the output filename");
1194 try err_details.msg.appendSlice(allocator, "the output format was inferred from the output filename");
12541195 } else {
1255 try msg_writer.writeAll("the output format was unable to be inferred from the output filename, so the default was used");
1196 try err_details.msg.appendSlice(allocator, "the output format was unable to be inferred from the output filename, so the default was used");
12561197 }
12571198 try diagnostics.append(err_details);
12581199 },
......@@ -1262,14 +1203,12 @@ pub fn parse(allocator: Allocator, args: []const []const u8, diagnostics: *Diagn
12621203 .arg_index = output_format_context.index,
12631204 .arg_span = output_format_context.value.argSpan(output_format_context.arg),
12641205 };
1265 var msg_writer = err_details.msg.writer(allocator);
1266 try msg_writer.writeAll("the output format was specified here");
1206 try err_details.msg.appendSlice(allocator, "the output format was specified here");
12671207 try diagnostics.append(err_details);
12681208 },
12691209 .inferred_from_preprocess_only => {
12701210 var err_details = Diagnostics.ErrorDetails{ .type = .note, .arg_index = preprocess_only_context.index };
1271 var msg_writer = err_details.msg.writer(allocator);
1272 try msg_writer.print("the output format was inferred from the usage of the {s}{s} option", .{
1211 try err_details.msg.print(allocator, "the output format was inferred from the usage of the {s}{s} option", .{
12731212 preprocess_only_context.arg.prefixSlice(),
12741213 preprocess_only_context.arg.optionWithoutPrefix(preprocess_only_context.option_len),
12751214 });
......@@ -1291,19 +1230,19 @@ pub fn parse(allocator: Allocator, args: []const []const u8, diagnostics: *Diagn
12911230}
12921231
12931232pub fn filepathWithExtension(allocator: Allocator, path: []const u8, ext: []const u8) ![]const u8 {
1294 var buf = std.array_list.Managed(u8).init(allocator);
1295 errdefer buf.deinit();
1233 var buf: std.ArrayList(u8) = .empty;
1234 errdefer buf.deinit(allocator);
12961235 if (std.fs.path.dirname(path)) |dirname| {
12971236 var end_pos = dirname.len;
12981237 // We want to ensure that we write a path separator at the end, so if the dirname
12991238 // doesn't end with a path sep then include the char after the dirname
13001239 // which must be a path sep.
13011240 if (!std.fs.path.isSep(dirname[dirname.len - 1])) end_pos += 1;
1302 try buf.appendSlice(path[0..end_pos]);
1241 try buf.appendSlice(allocator, path[0..end_pos]);
13031242 }
1304 try buf.appendSlice(std.fs.path.stem(path));
1305 try buf.appendSlice(ext);
1306 return try buf.toOwnedSlice();
1243 try buf.appendSlice(allocator, std.fs.path.stem(path));
1244 try buf.appendSlice(allocator, ext);
1245 return try buf.toOwnedSlice(allocator);
13071246}
13081247
13091248pub fn isSupportedInputExtension(ext: []const u8) bool {
......@@ -1537,7 +1476,7 @@ fn testParseOutput(args: []const []const u8, expected_output: []const u8) !?Opti
15371476 var options = parse(std.testing.allocator, args, &diagnostics) catch |err| switch (err) {
15381477 error.ParseError => {
15391478 try diagnostics.renderToWriter(args, &output.writer, .no_color);
1540 try std.testing.expectEqualStrings(expected_output, output.getWritten());
1479 try std.testing.expectEqualStrings(expected_output, output.written());
15411480 return null;
15421481 },
15431482 else => |e| return e,
......@@ -1545,7 +1484,7 @@ fn testParseOutput(args: []const []const u8, expected_output: []const u8) !?Opti
15451484 errdefer options.deinit();
15461485
15471486 try diagnostics.renderToWriter(args, &output.writer, .no_color);
1548 try std.testing.expectEqualStrings(expected_output, output.getWritten());
1487 try std.testing.expectEqualStrings(expected_output, output.written());
15491488 return options;
15501489}
15511490
lib/compiler/resinator/compile.zig+219-309
......@@ -35,10 +35,7 @@ pub const CompileOptions = struct {
3535 diagnostics: *Diagnostics,
3636 source_mappings: ?*SourceMappings = null,
3737 /// List of paths (absolute or relative to `cwd`) for every file that the resources within the .rc file depend on.
38 /// Items within the list will be allocated using the allocator of the ArrayList and must be
39 /// freed by the caller.
40 /// TODO: Maybe a dedicated struct for this purpose so that it's a bit nicer to work with.
41 dependencies_list: ?*std.array_list.Managed([]const u8) = null,
38 dependencies: ?*Dependencies = null,
4239 default_code_page: SupportedCodePage = .windows1252,
4340 /// If true, the first #pragma code_page directive only sets the input code page, but not the output code page.
4441 /// This check must be done before comments are removed from the file.
......@@ -61,7 +58,26 @@ pub const CompileOptions = struct {
6158 warn_instead_of_error_on_invalid_code_page: bool = false,
6259};
6360
64pub fn compile(allocator: Allocator, source: []const u8, writer: anytype, options: CompileOptions) !void {
61pub const Dependencies = struct {
62 list: std.ArrayList([]const u8),
63 allocator: Allocator,
64
65 pub fn init(allocator: Allocator) Dependencies {
66 return .{
67 .list = .empty,
68 .allocator = allocator,
69 };
70 }
71
72 pub fn deinit(self: *Dependencies) void {
73 for (self.list.items) |item| {
74 self.allocator.free(item);
75 }
76 self.list.deinit(self.allocator);
77 }
78};
79
80pub fn compile(allocator: Allocator, source: []const u8, writer: *std.Io.Writer, options: CompileOptions) !void {
6581 var lexer = lex.Lexer.init(source, .{
6682 .default_code_page = options.default_code_page,
6783 .source_mappings = options.source_mappings,
......@@ -74,12 +90,12 @@ pub fn compile(allocator: Allocator, source: []const u8, writer: anytype, option
7490 var tree = try parser.parse(allocator, options.diagnostics);
7591 defer tree.deinit();
7692
77 var search_dirs = std.array_list.Managed(SearchDir).init(allocator);
93 var search_dirs: std.ArrayList(SearchDir) = .empty;
7894 defer {
7995 for (search_dirs.items) |*search_dir| {
8096 search_dir.deinit(allocator);
8197 }
82 search_dirs.deinit();
98 search_dirs.deinit(allocator);
8399 }
84100
85101 if (options.source_mappings) |source_mappings| {
......@@ -89,7 +105,7 @@ pub fn compile(allocator: Allocator, source: []const u8, writer: anytype, option
89105 if (std.fs.path.dirname(root_path)) |root_dir_path| {
90106 var root_dir = try options.cwd.openDir(root_dir_path, .{});
91107 errdefer root_dir.close();
92 try search_dirs.append(.{ .dir = root_dir, .path = try allocator.dupe(u8, root_dir_path) });
108 try search_dirs.append(allocator, .{ .dir = root_dir, .path = try allocator.dupe(u8, root_dir_path) });
93109 }
94110 }
95111 // Re-open the passed in cwd since we want to be able to close it (std.fs.cwd() shouldn't be closed)
......@@ -111,14 +127,14 @@ pub fn compile(allocator: Allocator, source: []const u8, writer: anytype, option
111127 });
112128 return error.CompileError;
113129 };
114 try search_dirs.append(.{ .dir = cwd_dir, .path = null });
130 try search_dirs.append(allocator, .{ .dir = cwd_dir, .path = null });
115131 for (options.extra_include_paths) |extra_include_path| {
116132 var dir = openSearchPathDir(options.cwd, extra_include_path) catch {
117133 // TODO: maybe a warning that the search path is skipped?
118134 continue;
119135 };
120136 errdefer dir.close();
121 try search_dirs.append(.{ .dir = dir, .path = try allocator.dupe(u8, extra_include_path) });
137 try search_dirs.append(allocator, .{ .dir = dir, .path = try allocator.dupe(u8, extra_include_path) });
122138 }
123139 for (options.system_include_paths) |system_include_path| {
124140 var dir = openSearchPathDir(options.cwd, system_include_path) catch {
......@@ -126,7 +142,7 @@ pub fn compile(allocator: Allocator, source: []const u8, writer: anytype, option
126142 continue;
127143 };
128144 errdefer dir.close();
129 try search_dirs.append(.{ .dir = dir, .path = try allocator.dupe(u8, system_include_path) });
145 try search_dirs.append(allocator, .{ .dir = dir, .path = try allocator.dupe(u8, system_include_path) });
130146 }
131147 if (!options.ignore_include_env_var) {
132148 const INCLUDE = std.process.getEnvVarOwned(allocator, "INCLUDE") catch "";
......@@ -142,7 +158,7 @@ pub fn compile(allocator: Allocator, source: []const u8, writer: anytype, option
142158 while (it.next()) |search_path| {
143159 var dir = openSearchPathDir(options.cwd, search_path) catch continue;
144160 errdefer dir.close();
145 try search_dirs.append(.{ .dir = dir, .path = try allocator.dupe(u8, search_path) });
161 try search_dirs.append(allocator, .{ .dir = dir, .path = try allocator.dupe(u8, search_path) });
146162 }
147163 }
148164
......@@ -156,7 +172,7 @@ pub fn compile(allocator: Allocator, source: []const u8, writer: anytype, option
156172 .allocator = allocator,
157173 .cwd = options.cwd,
158174 .diagnostics = options.diagnostics,
159 .dependencies_list = options.dependencies_list,
175 .dependencies = options.dependencies,
160176 .input_code_pages = &tree.input_code_pages,
161177 .output_code_pages = &tree.output_code_pages,
162178 // This is only safe because we know search_dirs won't be modified past this point
......@@ -178,7 +194,7 @@ pub const Compiler = struct {
178194 cwd: std.fs.Dir,
179195 state: State = .{},
180196 diagnostics: *Diagnostics,
181 dependencies_list: ?*std.array_list.Managed([]const u8),
197 dependencies: ?*Dependencies,
182198 input_code_pages: *const CodePageLookup,
183199 output_code_pages: *const CodePageLookup,
184200 search_dirs: []SearchDir,
......@@ -194,7 +210,7 @@ pub const Compiler = struct {
194210 characteristics: u32 = 0,
195211 };
196212
197 pub fn writeRoot(self: *Compiler, root: *Node.Root, writer: anytype) !void {
213 pub fn writeRoot(self: *Compiler, root: *Node.Root, writer: *std.Io.Writer) !void {
198214 try writeEmptyResource(writer);
199215 for (root.body) |node| {
200216 try self.writeNode(node, writer);
......@@ -236,7 +252,7 @@ pub const Compiler = struct {
236252 }
237253 }
238254
239 pub fn writeNode(self: *Compiler, node: *Node, writer: anytype) !void {
255 pub fn writeNode(self: *Compiler, node: *Node, writer: *std.Io.Writer) !void {
240256 switch (node.id) {
241257 .root => unreachable, // writeRoot should be called directly instead
242258 .resource_external => try self.writeResourceExternal(@alignCast(@fieldParentPtr("base", node)), writer),
......@@ -279,32 +295,32 @@ pub const Compiler = struct {
279295 .literal, .number => {
280296 const slice = literal_node.token.slice(self.source);
281297 const code_page = self.input_code_pages.getForToken(literal_node.token);
282 var buf = try std.array_list.Managed(u8).initCapacity(self.allocator, slice.len);
283 errdefer buf.deinit();
298 var buf = try std.ArrayList(u8).initCapacity(self.allocator, slice.len);
299 errdefer buf.deinit(self.allocator);
284300
285301 var index: usize = 0;
286302 while (code_page.codepointAt(index, slice)) |codepoint| : (index += codepoint.byte_len) {
287303 const c = codepoint.value;
288304 if (c == code_pages.Codepoint.invalid) {
289 try buf.appendSlice("�");
305 try buf.appendSlice(self.allocator, "�");
290306 } else {
291307 // Anything that is not returned as an invalid codepoint must be encodable as UTF-8.
292308 const utf8_len = std.unicode.utf8CodepointSequenceLength(c) catch unreachable;
293 try buf.ensureUnusedCapacity(utf8_len);
309 try buf.ensureUnusedCapacity(self.allocator, utf8_len);
294310 _ = std.unicode.utf8Encode(c, buf.unusedCapacitySlice()) catch unreachable;
295311 buf.items.len += utf8_len;
296312 }
297313 }
298314
299 return buf.toOwnedSlice();
315 return buf.toOwnedSlice(self.allocator);
300316 },
301317 .quoted_ascii_string, .quoted_wide_string => {
302318 const slice = literal_node.token.slice(self.source);
303319 const column = literal_node.token.calculateColumn(self.source, 8, null);
304320 const bytes = SourceBytes{ .slice = slice, .code_page = self.input_code_pages.getForToken(literal_node.token) };
305321
306 var buf = std.array_list.Managed(u8).init(self.allocator);
307 errdefer buf.deinit();
322 var buf: std.ArrayList(u8) = .empty;
323 errdefer buf.deinit(self.allocator);
308324
309325 // Filenames are sort-of parsed as if they were wide strings, but the max escape width of
310326 // hex/octal escapes is still determined by the L prefix. Since we want to end up with
......@@ -320,19 +336,19 @@ pub const Compiler = struct {
320336 while (try parser.nextUnchecked()) |parsed| {
321337 const c = parsed.codepoint;
322338 if (c == code_pages.Codepoint.invalid) {
323 try buf.appendSlice("�");
339 try buf.appendSlice(self.allocator, "�");
324340 } else {
325341 var codepoint_buf: [4]u8 = undefined;
326342 // If the codepoint cannot be encoded, we fall back to �
327343 if (std.unicode.utf8Encode(c, &codepoint_buf)) |len| {
328 try buf.appendSlice(codepoint_buf[0..len]);
344 try buf.appendSlice(self.allocator, codepoint_buf[0..len]);
329345 } else |_| {
330 try buf.appendSlice("�");
346 try buf.appendSlice(self.allocator, "�");
331347 }
332348 }
333349 }
334350
335 return buf.toOwnedSlice();
351 return buf.toOwnedSlice(self.allocator);
336352 },
337353 else => unreachable, // no other token types should be in a filename literal node
338354 }
......@@ -386,10 +402,10 @@ pub const Compiler = struct {
386402 const file = try utils.openFileNotDir(std.fs.cwd(), path, .{});
387403 errdefer file.close();
388404
389 if (self.dependencies_list) |dependencies_list| {
390 const duped_path = try dependencies_list.allocator.dupe(u8, path);
391 errdefer dependencies_list.allocator.free(duped_path);
392 try dependencies_list.append(duped_path);
405 if (self.dependencies) |dependencies| {
406 const duped_path = try dependencies.allocator.dupe(u8, path);
407 errdefer dependencies.allocator.free(duped_path);
408 try dependencies.list.append(dependencies.allocator, duped_path);
393409 }
394410 }
395411
......@@ -398,12 +414,12 @@ pub const Compiler = struct {
398414 if (utils.openFileNotDir(search_dir.dir, path, .{})) |file| {
399415 errdefer file.close();
400416
401 if (self.dependencies_list) |dependencies_list| {
402 const searched_file_path = try std.fs.path.join(dependencies_list.allocator, &.{
417 if (self.dependencies) |dependencies| {
418 const searched_file_path = try std.fs.path.join(dependencies.allocator, &.{
403419 search_dir.path orelse "", path,
404420 });
405 errdefer dependencies_list.allocator.free(searched_file_path);
406 try dependencies_list.append(searched_file_path);
421 errdefer dependencies.allocator.free(searched_file_path);
422 try dependencies.list.append(dependencies.allocator, searched_file_path);
407423 }
408424
409425 return file;
......@@ -421,8 +437,8 @@ pub const Compiler = struct {
421437 const bytes = self.sourceBytesForToken(token);
422438 const output_code_page = self.output_code_pages.getForToken(token);
423439
424 var buf = try std.array_list.Managed(u8).initCapacity(self.allocator, bytes.slice.len);
425 errdefer buf.deinit();
440 var buf = try std.ArrayList(u8).initCapacity(self.allocator, bytes.slice.len);
441 errdefer buf.deinit(self.allocator);
426442
427443 var iterative_parser = literals.IterativeStringParser.init(bytes, .{
428444 .start_column = token.calculateColumn(self.source, 8, null),
......@@ -444,11 +460,11 @@ pub const Compiler = struct {
444460 switch (iterative_parser.declared_string_type) {
445461 .wide => {
446462 if (windows1252.bestFitFromCodepoint(c)) |best_fit| {
447 try buf.append(best_fit);
463 try buf.append(self.allocator, best_fit);
448464 } else if (c < 0x10000 or c == code_pages.Codepoint.invalid or parsed.escaped_surrogate_pair) {
449 try buf.append('?');
465 try buf.append(self.allocator, '?');
450466 } else {
451 try buf.appendSlice("??");
467 try buf.appendSlice(self.allocator, "??");
452468 }
453469 },
454470 .ascii => {
......@@ -456,30 +472,30 @@ pub const Compiler = struct {
456472 const truncated: u8 = @truncate(c);
457473 switch (output_code_page) {
458474 .utf8 => switch (truncated) {
459 0...0x7F => try buf.append(truncated),
460 else => try buf.append('?'),
475 0...0x7F => try buf.append(self.allocator, truncated),
476 else => try buf.append(self.allocator, '?'),
461477 },
462478 .windows1252 => {
463 try buf.append(truncated);
479 try buf.append(self.allocator, truncated);
464480 },
465481 }
466482 } else {
467483 if (windows1252.bestFitFromCodepoint(c)) |best_fit| {
468 try buf.append(best_fit);
484 try buf.append(self.allocator, best_fit);
469485 } else if (c < 0x10000 or c == code_pages.Codepoint.invalid) {
470 try buf.append('?');
486 try buf.append(self.allocator, '?');
471487 } else {
472 try buf.appendSlice("??");
488 try buf.appendSlice(self.allocator, "??");
473489 }
474490 }
475491 },
476492 }
477493 }
478494
479 return buf.toOwnedSlice();
495 return buf.toOwnedSlice(self.allocator);
480496 }
481497
482 pub fn writeResourceExternal(self: *Compiler, node: *Node.ResourceExternal, writer: anytype) !void {
498 pub fn writeResourceExternal(self: *Compiler, node: *Node.ResourceExternal, writer: *std.Io.Writer) !void {
483499 // Init header with data size zero for now, will need to fill it in later
484500 var header = try self.resourceHeader(node.id, node.type, .{});
485501 defer header.deinit(self.allocator);
......@@ -572,7 +588,7 @@ pub const Compiler = struct {
572588 switch (predefined_type) {
573589 .GROUP_ICON, .GROUP_CURSOR => {
574590 // Check for animated icon first
575 if (ani.isAnimatedIcon(file_reader.interface.adaptToOldInterface())) {
591 if (ani.isAnimatedIcon(&file_reader.interface)) {
576592 // Animated icons are just put into the resource unmodified,
577593 // and the resource type changes to ANIICON/ANICURSOR
578594
......@@ -584,7 +600,12 @@ pub const Compiler = struct {
584600 header.type_value.ordinal = @intFromEnum(new_predefined_type);
585601 header.memory_flags = MemoryFlags.defaults(new_predefined_type);
586602 header.applyMemoryFlags(node.common_resource_attributes, self.source);
587 header.data_size = @intCast(try file_reader.getSize());
603 header.data_size = std.math.cast(u32, try file_reader.getSize()) orelse {
604 return self.addErrorDetailsAndFail(.{
605 .err = .resource_data_size_exceeds_max,
606 .token = node.id,
607 });
608 };
588609
589610 try header.write(writer, self.errContext(node.id));
590611 try file_reader.seekTo(0);
......@@ -595,7 +616,7 @@ pub const Compiler = struct {
595616 // isAnimatedIcon moved the file cursor so reset to the start
596617 try file_reader.seekTo(0);
597618
598 const icon_dir = ico.read(self.allocator, file_reader.interface.adaptToOldInterface(), try file_reader.getSize()) catch |err| switch (err) {
619 const icon_dir = ico.read(self.allocator, &file_reader.interface, try file_reader.getSize()) catch |err| switch (err) {
599620 error.OutOfMemory => |e| return e,
600621 else => |e| {
601622 return self.iconReadError(
......@@ -861,7 +882,7 @@ pub const Compiler = struct {
861882 header.applyMemoryFlags(node.common_resource_attributes, self.source);
862883 const file_size = try file_reader.getSize();
863884
864 const bitmap_info = bmp.read(file_reader.interface.adaptToOldInterface(), file_size) catch |err| {
885 const bitmap_info = bmp.read(&file_reader.interface, file_size) catch |err| {
865886 const filename_string_index = try self.diagnostics.putString(filename_utf8);
866887 return self.addErrorDetailsAndFail(.{
867888 .err = .bmp_read_error,
......@@ -969,13 +990,19 @@ pub const Compiler = struct {
969990 header.data_size = @intCast(file_size);
970991 try header.write(writer, self.errContext(node.id));
971992
972 var header_slurping_reader = headerSlurpingReader(148, file_reader.interface.adaptToOldInterface());
973 var adapter = header_slurping_reader.reader().adaptToNewApi(&.{});
974 try writeResourceData(writer, &adapter.new_interface, header.data_size);
993 // Slurp the first 148 bytes separately so we can store them in the FontDir
994 var font_dir_header_buf: [148]u8 = @splat(0);
995 const populated_len: u32 = @intCast(try file_reader.interface.readSliceShort(&font_dir_header_buf));
996
997 // Write only the populated bytes slurped from the header
998 try writer.writeAll(font_dir_header_buf[0..populated_len]);
999 // Then write the rest of the bytes and the padding
1000 try writeResourceDataNoPadding(writer, &file_reader.interface, header.data_size - populated_len);
1001 try writeDataPadding(writer, header.data_size);
9751002
9761003 try self.state.font_dir.add(self.arena, FontDir.Font{
9771004 .id = header.name_value.ordinal,
978 .header_bytes = header_slurping_reader.slurped_header,
1005 .header_bytes = font_dir_header_buf,
9791006 }, node.id);
9801007 return;
9811008 },
......@@ -1053,7 +1080,7 @@ pub const Compiler = struct {
10531080 }
10541081 }
10551082
1056 pub fn write(self: Data, writer: anytype) !void {
1083 pub fn write(self: Data, writer: *std.Io.Writer) !void {
10571084 switch (self) {
10581085 .number => |number| switch (number.is_long) {
10591086 false => try writer.writeInt(WORD, number.asWord(), .little),
......@@ -1225,38 +1252,30 @@ pub const Compiler = struct {
12251252 }
12261253 }
12271254
1228 pub fn writeResourceRawData(self: *Compiler, node: *Node.ResourceRawData, writer: anytype) !void {
1229 var data_buffer = std.array_list.Managed(u8).init(self.allocator);
1255 pub fn writeResourceRawData(self: *Compiler, node: *Node.ResourceRawData, writer: *std.Io.Writer) !void {
1256 var data_buffer: std.Io.Writer.Allocating = .init(self.allocator);
12301257 defer data_buffer.deinit();
1231 // The header's data length field is a u32 so limit the resource's data size so that
1232 // we know we can always specify the real size.
1233 var limited_writer = limitedWriter(data_buffer.writer(), std.math.maxInt(u32));
1234 const data_writer = limited_writer.writer();
12351258
12361259 for (node.raw_data) |expression| {
12371260 const data = try self.evaluateDataExpression(expression);
12381261 defer data.deinit(self.allocator);
1239 data.write(data_writer) catch |err| switch (err) {
1240 error.NoSpaceLeft => {
1241 return self.addErrorDetailsAndFail(.{
1242 .err = .resource_data_size_exceeds_max,
1243 .token = node.id,
1244 });
1245 },
1246 else => |e| return e,
1247 };
1262 try data.write(&data_buffer.writer);
12481263 }
12491264
1250 // This intCast can't fail because the limitedWriter above guarantees that
1251 // we will never write more than maxInt(u32) bytes.
1252 const data_len: u32 = @intCast(data_buffer.items.len);
1265 // TODO: Limit data_buffer in some way to error when writing more than u32 max bytes
1266 const data_len: u32 = std.math.cast(u32, data_buffer.written().len) orelse {
1267 return self.addErrorDetailsAndFail(.{
1268 .err = .resource_data_size_exceeds_max,
1269 .token = node.id,
1270 });
1271 };
12531272 try self.writeResourceHeader(writer, node.id, node.type, data_len, node.common_resource_attributes, self.state.language);
12541273
1255 var data_fbs: std.Io.Reader = .fixed(data_buffer.items);
1274 var data_fbs: std.Io.Reader = .fixed(data_buffer.written());
12561275 try writeResourceData(writer, &data_fbs, data_len);
12571276 }
12581277
1259 pub fn writeResourceHeader(self: *Compiler, writer: anytype, id_token: Token, type_token: Token, data_size: u32, common_resource_attributes: []Token, language: res.Language) !void {
1278 pub fn writeResourceHeader(self: *Compiler, writer: *std.Io.Writer, id_token: Token, type_token: Token, data_size: u32, common_resource_attributes: []Token, language: res.Language) !void {
12601279 var header = try self.resourceHeader(id_token, type_token, .{
12611280 .language = language,
12621281 .data_size = data_size,
......@@ -1272,7 +1291,7 @@ pub const Compiler = struct {
12721291 try data_reader.streamExact(writer, data_size);
12731292 }
12741293
1275 pub fn writeResourceData(writer: anytype, data_reader: *std.Io.Reader, data_size: u32) !void {
1294 pub fn writeResourceData(writer: *std.Io.Writer, data_reader: *std.Io.Reader, data_size: u32) !void {
12761295 try writeResourceDataNoPadding(writer, data_reader, data_size);
12771296 try writeDataPadding(writer, data_size);
12781297 }
......@@ -1305,28 +1324,19 @@ pub const Compiler = struct {
13051324 }
13061325 }
13071326
1308 pub fn writeAccelerators(self: *Compiler, node: *Node.Accelerators, writer: anytype) !void {
1309 var data_buffer = std.array_list.Managed(u8).init(self.allocator);
1327 pub fn writeAccelerators(self: *Compiler, node: *Node.Accelerators, writer: *std.Io.Writer) !void {
1328 var data_buffer: std.Io.Writer.Allocating = .init(self.allocator);
13101329 defer data_buffer.deinit();
13111330
1312 // The header's data length field is a u32 so limit the resource's data size so that
1313 // we know we can always specify the real size.
1314 var limited_writer = limitedWriter(data_buffer.writer(), std.math.maxInt(u32));
1315 const data_writer = limited_writer.writer();
1331 try self.writeAcceleratorsData(node, &data_buffer.writer);
13161332
1317 self.writeAcceleratorsData(node, data_writer) catch |err| switch (err) {
1318 error.NoSpaceLeft => {
1319 return self.addErrorDetailsAndFail(.{
1320 .err = .resource_data_size_exceeds_max,
1321 .token = node.id,
1322 });
1323 },
1324 else => |e| return e,
1333 // TODO: Limit data_buffer in some way to error when writing more than u32 max bytes
1334 const data_size: u32 = std.math.cast(u32, data_buffer.written().len) orelse {
1335 return self.addErrorDetailsAndFail(.{
1336 .err = .resource_data_size_exceeds_max,
1337 .token = node.id,
1338 });
13251339 };
1326
1327 // This intCast can't fail because the limitedWriter above guarantees that
1328 // we will never write more than maxInt(u32) bytes.
1329 const data_size: u32 = @intCast(data_buffer.items.len);
13301340 var header = try self.resourceHeader(node.id, node.type, .{
13311341 .data_size = data_size,
13321342 });
......@@ -1337,13 +1347,13 @@ pub const Compiler = struct {
13371347
13381348 try header.write(writer, self.errContext(node.id));
13391349
1340 var data_fbs: std.Io.Reader = .fixed(data_buffer.items);
1350 var data_fbs: std.Io.Reader = .fixed(data_buffer.written());
13411351 try writeResourceData(writer, &data_fbs, data_size);
13421352 }
13431353
13441354 /// Expects `data_writer` to be a LimitedWriter limited to u32, meaning all writes to
13451355 /// the writer within this function could return error.NoSpaceLeft
1346 pub fn writeAcceleratorsData(self: *Compiler, node: *Node.Accelerators, data_writer: anytype) !void {
1356 pub fn writeAcceleratorsData(self: *Compiler, node: *Node.Accelerators, data_writer: *std.Io.Writer) !void {
13471357 for (node.accelerators, 0..) |accel_node, i| {
13481358 const accelerator: *Node.Accelerator = @alignCast(@fieldParentPtr("base", accel_node));
13491359 var modifiers = res.AcceleratorModifiers{};
......@@ -1404,13 +1414,9 @@ pub const Compiler = struct {
14041414 caption: ?Token = null,
14051415 };
14061416
1407 pub fn writeDialog(self: *Compiler, node: *Node.Dialog, writer: anytype) !void {
1408 var data_buffer = std.array_list.Managed(u8).init(self.allocator);
1417 pub fn writeDialog(self: *Compiler, node: *Node.Dialog, writer: *std.Io.Writer) !void {
1418 var data_buffer: std.Io.Writer.Allocating = .init(self.allocator);
14091419 defer data_buffer.deinit();
1410 // The header's data length field is a u32 so limit the resource's data size so that
1411 // we know we can always specify the real size.
1412 var limited_writer = limitedWriter(data_buffer.writer(), std.math.maxInt(u32));
1413 const data_writer = limited_writer.writer();
14141420
14151421 const resource = ResourceType.fromString(.{
14161422 .slice = node.type.slice(self.source),
......@@ -1671,21 +1677,18 @@ pub const Compiler = struct {
16711677 optional_statement_values.style |= res.WS.CAPTION;
16721678 }
16731679
1674 self.writeDialogHeaderAndStrings(
1680 // NOTE: Dialog header and menu/class/title strings can never exceed u32 bytes
1681 // on their own.
1682 try self.writeDialogHeaderAndStrings(
16751683 node,
1676 data_writer,
1684 &data_buffer.writer,
16771685 resource,
16781686 &optional_statement_values,
16791687 x,
16801688 y,
16811689 width,
16821690 height,
1683 ) catch |err| switch (err) {
1684 // Dialog header and menu/class/title strings can never exceed u32 bytes
1685 // on their own, so this error is unreachable.
1686 error.NoSpaceLeft => unreachable,
1687 else => |e| return e,
1688 };
1691 );
16891692
16901693 var controls_by_id = std.AutoHashMap(u32, *const Node.ControlStatement).init(self.allocator);
16911694 // Number of controls are guaranteed by the parser to be within maxInt(u16).
......@@ -1695,31 +1698,30 @@ pub const Compiler = struct {
16951698 for (node.controls) |control_node| {
16961699 const control: *Node.ControlStatement = @alignCast(@fieldParentPtr("base", control_node));
16971700
1698 self.writeDialogControl(
1701 try self.writeDialogControl(
16991702 control,
1700 data_writer,
1703 &data_buffer.writer,
17011704 resource,
17021705 // We know the data_buffer len is limited to u32 max.
1703 @intCast(data_buffer.items.len),
1706 @intCast(data_buffer.written().len),
17041707 &controls_by_id,
1705 ) catch |err| switch (err) {
1706 error.NoSpaceLeft => {
1707 try self.addErrorDetails(.{
1708 .err = .resource_data_size_exceeds_max,
1709 .token = node.id,
1710 });
1711 return self.addErrorDetailsAndFail(.{
1712 .err = .resource_data_size_exceeds_max,
1713 .type = .note,
1714 .token = control.type,
1715 });
1716 },
1717 else => |e| return e,
1718 };
1708 );
1709
1710 if (data_buffer.written().len > std.math.maxInt(u32)) {
1711 try self.addErrorDetails(.{
1712 .err = .resource_data_size_exceeds_max,
1713 .token = node.id,
1714 });
1715 return self.addErrorDetailsAndFail(.{
1716 .err = .resource_data_size_exceeds_max,
1717 .type = .note,
1718 .token = control.type,
1719 });
1720 }
17191721 }
17201722
17211723 // We know the data_buffer len is limited to u32 max.
1722 const data_size: u32 = @intCast(data_buffer.items.len);
1724 const data_size: u32 = @intCast(data_buffer.written().len);
17231725 var header = try self.resourceHeader(node.id, node.type, .{
17241726 .data_size = data_size,
17251727 });
......@@ -1730,14 +1732,14 @@ pub const Compiler = struct {
17301732
17311733 try header.write(writer, self.errContext(node.id));
17321734
1733 var data_fbs: std.Io.Reader = .fixed(data_buffer.items);
1735 var data_fbs: std.Io.Reader = .fixed(data_buffer.written());
17341736 try writeResourceData(writer, &data_fbs, data_size);
17351737 }
17361738
17371739 fn writeDialogHeaderAndStrings(
17381740 self: *Compiler,
17391741 node: *Node.Dialog,
1740 data_writer: anytype,
1742 data_writer: *std.Io.Writer,
17411743 resource: ResourceType,
17421744 optional_statement_values: *const DialogOptionalStatementValues,
17431745 x: Number,
......@@ -1797,7 +1799,7 @@ pub const Compiler = struct {
17971799 fn writeDialogControl(
17981800 self: *Compiler,
17991801 control: *Node.ControlStatement,
1800 data_writer: anytype,
1802 data_writer: *std.Io.Writer,
18011803 resource: ResourceType,
18021804 bytes_written_so_far: u32,
18031805 controls_by_id: *std.AutoHashMap(u32, *const Node.ControlStatement),
......@@ -1821,7 +1823,7 @@ pub const Compiler = struct {
18211823 .token = control.type,
18221824 });
18231825 }
1824 try data_writer.writeByteNTimes(0, num_padding);
1826 try data_writer.splatByteAll(0, num_padding);
18251827
18261828 const style = if (control.style) |style_expression|
18271829 // Certain styles are implied by the control type
......@@ -1973,40 +1975,37 @@ pub const Compiler = struct {
19731975 try NameOrOrdinal.writeEmpty(data_writer);
19741976 }
19751977
1976 var extra_data_buf = std.array_list.Managed(u8).init(self.allocator);
1977 defer extra_data_buf.deinit();
19781978 // The extra data byte length must be able to fit within a u16.
1979 var limited_extra_data_writer = limitedWriter(extra_data_buf.writer(), std.math.maxInt(u16));
1980 const extra_data_writer = limited_extra_data_writer.writer();
1979 var extra_data_buf: std.Io.Writer.Allocating = .init(self.allocator);
1980 defer extra_data_buf.deinit();
19811981 for (control.extra_data) |data_expression| {
19821982 const data = try self.evaluateDataExpression(data_expression);
19831983 defer data.deinit(self.allocator);
1984 data.write(extra_data_writer) catch |err| switch (err) {
1985 error.NoSpaceLeft => {
1986 try self.addErrorDetails(.{
1987 .err = .control_extra_data_size_exceeds_max,
1988 .token = control.type,
1989 });
1990 return self.addErrorDetailsAndFail(.{
1991 .err = .control_extra_data_size_exceeds_max,
1992 .type = .note,
1993 .token = data_expression.getFirstToken(),
1994 .token_span_end = data_expression.getLastToken(),
1995 });
1996 },
1997 else => |e| return e,
1998 };
1984 try data.write(&extra_data_buf.writer);
1985
1986 if (extra_data_buf.written().len > std.math.maxInt(u16)) {
1987 try self.addErrorDetails(.{
1988 .err = .control_extra_data_size_exceeds_max,
1989 .token = control.type,
1990 });
1991 return self.addErrorDetailsAndFail(.{
1992 .err = .control_extra_data_size_exceeds_max,
1993 .type = .note,
1994 .token = data_expression.getFirstToken(),
1995 .token_span_end = data_expression.getLastToken(),
1996 });
1997 }
19991998 }
20001999 // We know the extra_data_buf size fits within a u16.
2001 const extra_data_size: u16 = @intCast(extra_data_buf.items.len);
2000 const extra_data_size: u16 = @intCast(extra_data_buf.written().len);
20022001 try data_writer.writeInt(u16, extra_data_size, .little);
2003 try data_writer.writeAll(extra_data_buf.items);
2002 try data_writer.writeAll(extra_data_buf.written());
20042003 }
20052004
2006 pub fn writeToolbar(self: *Compiler, node: *Node.Toolbar, writer: anytype) !void {
2007 var data_buffer = std.array_list.Managed(u8).init(self.allocator);
2005 pub fn writeToolbar(self: *Compiler, node: *Node.Toolbar, writer: *std.Io.Writer) !void {
2006 var data_buffer: std.Io.Writer.Allocating = .init(self.allocator);
20082007 defer data_buffer.deinit();
2009 const data_writer = data_buffer.writer();
2008 const data_writer = &data_buffer.writer;
20102009
20112010 const button_width = evaluateNumberExpression(node.button_width, self.source, self.input_code_pages);
20122011 const button_height = evaluateNumberExpression(node.button_height, self.source, self.input_code_pages);
......@@ -2034,7 +2033,7 @@ pub const Compiler = struct {
20342033 }
20352034 }
20362035
2037 const data_size: u32 = @intCast(data_buffer.items.len);
2036 const data_size: u32 = @intCast(data_buffer.written().len);
20382037 var header = try self.resourceHeader(node.id, node.type, .{
20392038 .data_size = data_size,
20402039 });
......@@ -2044,7 +2043,7 @@ pub const Compiler = struct {
20442043
20452044 try header.write(writer, self.errContext(node.id));
20462045
2047 var data_fbs: std.Io.Reader = .fixed(data_buffer.items);
2046 var data_fbs: std.Io.Reader = .fixed(data_buffer.written());
20482047 try writeResourceData(writer, &data_fbs, data_size);
20492048 }
20502049
......@@ -2056,7 +2055,7 @@ pub const Compiler = struct {
20562055 node: *Node.FontStatement,
20572056 };
20582057
2059 pub fn writeDialogFont(self: *Compiler, resource: ResourceType, values: FontStatementValues, writer: anytype) !void {
2058 pub fn writeDialogFont(self: *Compiler, resource: ResourceType, values: FontStatementValues, writer: *std.Io.Writer) !void {
20602059 const node = values.node;
20612060 const point_size = evaluateNumberExpression(node.point_size, self.source, self.input_code_pages);
20622061 try writer.writeInt(u16, point_size.asWord(), .little);
......@@ -2081,13 +2080,9 @@ pub const Compiler = struct {
20812080 try writer.writeAll(std.mem.sliceAsBytes(typeface[0 .. typeface.len + 1]));
20822081 }
20832082
2084 pub fn writeMenu(self: *Compiler, node: *Node.Menu, writer: anytype) !void {
2085 var data_buffer = std.array_list.Managed(u8).init(self.allocator);
2083 pub fn writeMenu(self: *Compiler, node: *Node.Menu, writer: *std.Io.Writer) !void {
2084 var data_buffer: std.Io.Writer.Allocating = .init(self.allocator);
20862085 defer data_buffer.deinit();
2087 // The header's data length field is a u32 so limit the resource's data size so that
2088 // we know we can always specify the real size.
2089 var limited_writer = limitedWriter(data_buffer.writer(), std.math.maxInt(u32));
2090 const data_writer = limited_writer.writer();
20912086
20922087 const type_bytes = SourceBytes{
20932088 .slice = node.type.slice(self.source),
......@@ -2096,21 +2091,15 @@ pub const Compiler = struct {
20962091 const resource = ResourceType.fromString(type_bytes);
20972092 std.debug.assert(resource == .menu or resource == .menuex);
20982093
2099 var adapted = data_writer.adaptToNewApi(&.{});
2094 try self.writeMenuData(node, &data_buffer.writer, resource);
21002095
2101 self.writeMenuData(node, &adapted.new_interface, resource) catch |err| switch (err) {
2102 error.WriteFailed => {
2103 return self.addErrorDetailsAndFail(.{
2104 .err = .resource_data_size_exceeds_max,
2105 .token = node.id,
2106 });
2107 },
2108 else => |e| return e,
2096 // TODO: Limit data_buffer in some way to error when writing more than u32 max bytes
2097 const data_size: u32 = std.math.cast(u32, data_buffer.written().len) orelse {
2098 return self.addErrorDetailsAndFail(.{
2099 .err = .resource_data_size_exceeds_max,
2100 .token = node.id,
2101 });
21092102 };
2110
2111 // This intCast can't fail because the limitedWriter above guarantees that
2112 // we will never write more than maxInt(u32) bytes.
2113 const data_size: u32 = @intCast(data_buffer.items.len);
21142103 var header = try self.resourceHeader(node.id, node.type, .{
21152104 .data_size = data_size,
21162105 });
......@@ -2121,7 +2110,7 @@ pub const Compiler = struct {
21212110
21222111 try header.write(writer, self.errContext(node.id));
21232112
2124 var data_fbs: std.Io.Reader = .fixed(data_buffer.items);
2113 var data_fbs: std.Io.Reader = .fixed(data_buffer.written());
21252114 try writeResourceData(writer, &data_fbs, data_size);
21262115 }
21272116
......@@ -2264,13 +2253,11 @@ pub const Compiler = struct {
22642253 }
22652254 }
22662255
2267 pub fn writeVersionInfo(self: *Compiler, node: *Node.VersionInfo, writer: anytype) !void {
2268 var data_buffer = std.array_list.Managed(u8).init(self.allocator);
2256 pub fn writeVersionInfo(self: *Compiler, node: *Node.VersionInfo, writer: *std.Io.Writer) !void {
2257 // NOTE: The node's length field (which is inclusive of the length of all of its children) is a u16
2258 var data_buffer: std.Io.Writer.Allocating = .init(self.allocator);
22692259 defer data_buffer.deinit();
2270 // The node's length field (which is inclusive of the length of all of its children) is a u16
2271 // so limit the node's data size so that we know we can always specify the real size.
2272 var limited_writer = limitedWriter(data_buffer.writer(), std.math.maxInt(u16));
2273 const data_writer = limited_writer.writer();
2260 const data_writer = &data_buffer.writer;
22742261
22752262 try data_writer.writeInt(u16, 0, .little); // placeholder size
22762263 try data_writer.writeInt(u16, res.FixedFileInfo.byte_len, .little);
......@@ -2354,29 +2341,32 @@ pub const Compiler = struct {
23542341 try fixed_file_info.write(data_writer);
23552342
23562343 for (node.block_statements) |statement| {
2357 var adapted = data_writer.adaptToNewApi(&.{});
2358 self.writeVersionNode(statement, &adapted.new_interface, &data_buffer) catch |err| switch (err) {
2359 error.WriteFailed => {
2360 try self.addErrorDetails(.{
2361 .err = .version_node_size_exceeds_max,
2362 .token = node.id,
2363 });
2364 return self.addErrorDetailsAndFail(.{
2365 .err = .version_node_size_exceeds_max,
2366 .type = .note,
2367 .token = statement.getFirstToken(),
2368 .token_span_end = statement.getLastToken(),
2369 });
2344 var overflow = false;
2345 self.writeVersionNode(statement, data_writer) catch |err| switch (err) {
2346 error.NoSpaceLeft => {
2347 overflow = true;
23702348 },
23712349 else => |e| return e,
23722350 };
2351 if (overflow or data_buffer.written().len > std.math.maxInt(u16)) {
2352 try self.addErrorDetails(.{
2353 .err = .version_node_size_exceeds_max,
2354 .token = node.id,
2355 });
2356 return self.addErrorDetailsAndFail(.{
2357 .err = .version_node_size_exceeds_max,
2358 .type = .note,
2359 .token = statement.getFirstToken(),
2360 .token_span_end = statement.getLastToken(),
2361 });
2362 }
23732363 }
23742364
2375 // We know that data_buffer.items.len is within the limits of a u16, since we
2376 // limited the writer to maxInt(u16)
2377 const data_size: u16 = @intCast(data_buffer.items.len);
2365 // We know that data_buffer len is within the limits of a u16, since we check in the block
2366 // statements loop above which is the only place it can overflow.
2367 const data_size: u16 = @intCast(data_buffer.written().len);
23782368 // And now that we know the full size of this node (including its children), set its size
2379 std.mem.writeInt(u16, data_buffer.items[0..2], data_size, .little);
2369 std.mem.writeInt(u16, data_buffer.written()[0..2], data_size, .little);
23802370
23812371 var header = try self.resourceHeader(node.id, node.versioninfo, .{
23822372 .data_size = data_size,
......@@ -2387,22 +2377,21 @@ pub const Compiler = struct {
23872377
23882378 try header.write(writer, self.errContext(node.id));
23892379
2390 var data_fbs: std.Io.Reader = .fixed(data_buffer.items);
2380 var data_fbs: std.Io.Reader = .fixed(data_buffer.written());
23912381 try writeResourceData(writer, &data_fbs, data_size);
23922382 }
23932383
2394 /// Expects writer to be a LimitedWriter limited to u16, meaning all writes to
2395 /// the writer within this function could return error.NoSpaceLeft, and that buf.items.len
2396 /// will never be able to exceed maxInt(u16).
2397 pub fn writeVersionNode(self: *Compiler, node: *Node, writer: *std.Io.Writer, buf: *std.array_list.Managed(u8)) !void {
2384 /// Assumes that writer is Writer.Allocating (specifically, that buffered() gets the entire data)
2385 /// TODO: This function could be nicer if writer was guaranteed to fail if it wrote more than u16 max bytes
2386 pub fn writeVersionNode(self: *Compiler, node: *Node, writer: *std.Io.Writer) !void {
23982387 // We can assume that buf.items.len will never be able to exceed the limits of a u16
2399 try writeDataPadding(writer, @as(u16, @intCast(buf.items.len)));
2388 try writeDataPadding(writer, std.math.cast(u16, writer.buffered().len) orelse return error.NoSpaceLeft);
24002389
2401 const node_and_children_size_offset = buf.items.len;
2390 const node_and_children_size_offset = writer.buffered().len;
24022391 try writer.writeInt(u16, 0, .little); // placeholder for size
2403 const data_size_offset = buf.items.len;
2392 const data_size_offset = writer.buffered().len;
24042393 try writer.writeInt(u16, 0, .little); // placeholder for data size
2405 const data_type_offset = buf.items.len;
2394 const data_type_offset = writer.buffered().len;
24062395 // Data type is string unless the node contains values that are numbers.
24072396 try writer.writeInt(u16, res.VersionNode.type_string, .little);
24082397
......@@ -2432,7 +2421,7 @@ pub const Compiler = struct {
24322421 // during parsing, so we can just do the correct thing here.
24332422 var values_size: usize = 0;
24342423
2435 try writeDataPadding(writer, @intCast(buf.items.len));
2424 try writeDataPadding(writer, std.math.cast(u16, writer.buffered().len) orelse return error.NoSpaceLeft);
24362425
24372426 for (block_or_value.values, 0..) |value_value_node_uncasted, i| {
24382427 const value_value_node = value_value_node_uncasted.cast(.block_value_value).?;
......@@ -2471,26 +2460,26 @@ pub const Compiler = struct {
24712460 }
24722461 }
24732462 }
2474 var data_size_slice = buf.items[data_size_offset..];
2463 var data_size_slice = writer.buffered()[data_size_offset..];
24752464 std.mem.writeInt(u16, data_size_slice[0..@sizeOf(u16)], @as(u16, @intCast(values_size)), .little);
24762465
24772466 if (has_number_value) {
2478 const data_type_slice = buf.items[data_type_offset..];
2467 const data_type_slice = writer.buffered()[data_type_offset..];
24792468 std.mem.writeInt(u16, data_type_slice[0..@sizeOf(u16)], res.VersionNode.type_binary, .little);
24802469 }
24812470
24822471 if (node_type == .block) {
24832472 const block = block_or_value;
24842473 for (block.children) |child| {
2485 try self.writeVersionNode(child, writer, buf);
2474 try self.writeVersionNode(child, writer);
24862475 }
24872476 }
24882477 },
24892478 else => unreachable,
24902479 }
24912480
2492 const node_and_children_size = buf.items.len - node_and_children_size_offset;
2493 const node_and_children_size_slice = buf.items[node_and_children_size_offset..];
2481 const node_and_children_size = writer.buffered().len - node_and_children_size_offset;
2482 const node_and_children_size_slice = writer.buffered()[node_and_children_size_offset..];
24942483 std.mem.writeInt(u16, node_and_children_size_slice[0..@sizeOf(u16)], @as(u16, @intCast(node_and_children_size)), .little);
24952484 }
24962485
......@@ -2683,11 +2672,11 @@ pub const Compiler = struct {
26832672 return .{ .bytes = header_size, .padding_after_name = padding_after_name };
26842673 }
26852674
2686 pub fn writeAssertNoOverflow(self: ResourceHeader, writer: anytype) !void {
2675 pub fn writeAssertNoOverflow(self: ResourceHeader, writer: *std.Io.Writer) !void {
26872676 return self.writeSizeInfo(writer, self.calcSize() catch unreachable);
26882677 }
26892678
2690 pub fn write(self: ResourceHeader, writer: anytype, err_ctx: errors.DiagnosticsContext) !void {
2679 pub fn write(self: ResourceHeader, writer: *std.Io.Writer, err_ctx: errors.DiagnosticsContext) !void {
26912680 const size_info = self.calcSize() catch {
26922681 try err_ctx.diagnostics.append(.{
26932682 .err = .resource_data_size_exceeds_max,
......@@ -2825,7 +2814,7 @@ pub const Compiler = struct {
28252814 return null;
28262815 }
28272816
2828 pub fn writeEmptyResource(writer: anytype) !void {
2817 pub fn writeEmptyResource(writer: *std.Io.Writer) !void {
28292818 const header = ResourceHeader{
28302819 .name_value = .{ .ordinal = 0 },
28312820 .type_value = .{ .ordinal = 0 },
......@@ -2942,87 +2931,8 @@ pub const SearchDir = struct {
29422931 }
29432932};
29442933
2945/// Slurps the first `size` bytes read into `slurped_header`
2946pub fn HeaderSlurpingReader(comptime size: usize, comptime ReaderType: anytype) type {
2947 return struct {
2948 child_reader: ReaderType,
2949 bytes_read: usize = 0,
2950 slurped_header: [size]u8 = [_]u8{0x00} ** size,
2951
2952 pub const Error = ReaderType.Error;
2953 pub const Reader = std.io.GenericReader(*@This(), Error, read);
2954
2955 pub fn read(self: *@This(), buf: []u8) Error!usize {
2956 const amt = try self.child_reader.read(buf);
2957 if (self.bytes_read < size) {
2958 const bytes_to_add = @min(amt, size - self.bytes_read);
2959 const end_index = self.bytes_read + bytes_to_add;
2960 @memcpy(self.slurped_header[self.bytes_read..end_index], buf[0..bytes_to_add]);
2961 }
2962 self.bytes_read +|= amt;
2963 return amt;
2964 }
2965
2966 pub fn reader(self: *@This()) Reader {
2967 return .{ .context = self };
2968 }
2969 };
2970}
2971
2972pub fn headerSlurpingReader(comptime size: usize, reader: anytype) HeaderSlurpingReader(size, @TypeOf(reader)) {
2973 return .{ .child_reader = reader };
2974}
2975
2976/// Sort of like std.io.LimitedReader, but a Writer.
2977/// Returns an error if writing the requested number of bytes
2978/// would ever exceed bytes_left, i.e. it does not always
2979/// write up to the limit and instead will error if the
2980/// limit would be breached if the entire slice was written.
2981pub fn LimitedWriter(comptime WriterType: type) type {
2982 return struct {
2983 inner_writer: WriterType,
2984 bytes_left: u64,
2985
2986 pub const Error = error{NoSpaceLeft} || WriterType.Error;
2987 pub const Writer = std.io.GenericWriter(*Self, Error, write);
2988
2989 const Self = @This();
2990
2991 pub fn write(self: *Self, bytes: []const u8) Error!usize {
2992 if (bytes.len > self.bytes_left) return error.NoSpaceLeft;
2993 const amt = try self.inner_writer.write(bytes);
2994 self.bytes_left -= amt;
2995 return amt;
2996 }
2997
2998 pub fn writer(self: *Self) Writer {
2999 return .{ .context = self };
3000 }
3001 };
3002}
3003
3004/// Returns an initialised `LimitedWriter`
3005/// `bytes_left` is a `u64` to be able to take 64 bit file offsets
3006pub fn limitedWriter(inner_writer: anytype, bytes_left: u64) LimitedWriter(@TypeOf(inner_writer)) {
3007 return .{ .inner_writer = inner_writer, .bytes_left = bytes_left };
3008}
3009
3010test "limitedWriter basic usage" {
3011 var buf: [4]u8 = undefined;
3012 var fbs = std.io.fixedBufferStream(&buf);
3013 var limited_stream = limitedWriter(fbs.writer(), 4);
3014 var writer = limited_stream.writer();
3015
3016 try std.testing.expectEqual(@as(usize, 3), try writer.write("123"));
3017 try std.testing.expectEqualSlices(u8, "123", buf[0..3]);
3018 try std.testing.expectError(error.NoSpaceLeft, writer.write("45"));
3019 try std.testing.expectEqual(@as(usize, 1), try writer.write("4"));
3020 try std.testing.expectEqualSlices(u8, "1234", buf[0..4]);
3021 try std.testing.expectError(error.NoSpaceLeft, writer.write("5"));
3022}
3023
30242934pub const FontDir = struct {
3025 fonts: std.ArrayListUnmanaged(Font) = .empty,
2935 fonts: std.ArrayList(Font) = .empty,
30262936 /// To keep track of which ids are set and where they were set from
30272937 ids: std.AutoHashMapUnmanaged(u16, Token) = .empty,
30282938
......@@ -3040,7 +2950,7 @@ pub const FontDir = struct {
30402950 try self.fonts.append(allocator, font);
30412951 }
30422952
3043 pub fn writeResData(self: *FontDir, compiler: *Compiler, writer: anytype) !void {
2953 pub fn writeResData(self: *FontDir, compiler: *Compiler, writer: *std.Io.Writer) !void {
30442954 if (self.fonts.items.len == 0) return;
30452955
30462956 // We know the number of fonts is limited to maxInt(u16) because fonts
......@@ -3164,7 +3074,7 @@ pub const StringTable = struct {
31643074 blocks: std.AutoArrayHashMapUnmanaged(u16, Block) = .empty,
31653075
31663076 pub const Block = struct {
3167 strings: std.ArrayListUnmanaged(Token) = .empty,
3077 strings: std.ArrayList(Token) = .empty,
31683078 set_indexes: std.bit_set.IntegerBitSet(16) = .{ .mask = 0 },
31693079 memory_flags: MemoryFlags = MemoryFlags.defaults(res.RT.STRING),
31703080 characteristics: u32,
......@@ -3245,10 +3155,10 @@ pub const StringTable = struct {
32453155 try std.testing.expectEqualStrings("a", trimToDoubleNUL(u8, "a\x00\x00b"));
32463156 }
32473157
3248 pub fn writeResData(self: *Block, compiler: *Compiler, language: res.Language, block_id: u16, writer: anytype) !void {
3249 var data_buffer = std.array_list.Managed(u8).init(compiler.allocator);
3158 pub fn writeResData(self: *Block, compiler: *Compiler, language: res.Language, block_id: u16, writer: *std.Io.Writer) !void {
3159 var data_buffer: std.Io.Writer.Allocating = .init(compiler.allocator);
32503160 defer data_buffer.deinit();
3251 const data_writer = data_buffer.writer();
3161 const data_writer = &data_buffer.writer;
32523162
32533163 var i: u8 = 0;
32543164 var string_i: u8 = 0;
......@@ -3307,7 +3217,7 @@ pub const StringTable = struct {
33073217 // 16 * (131,070 + 2) = 2,097,152 which is well within the u32 max.
33083218 //
33093219 // Note: The string literal maximum length is enforced by the lexer.
3310 const data_size: u32 = @intCast(data_buffer.items.len);
3220 const data_size: u32 = @intCast(data_buffer.written().len);
33113221
33123222 const header = Compiler.ResourceHeader{
33133223 .name_value = .{ .ordinal = block_id },
......@@ -3322,7 +3232,7 @@ pub const StringTable = struct {
33223232 // we fully control and know are numbers, so they have a fixed size.
33233233 try header.writeAssertNoOverflow(writer);
33243234
3325 var data_fbs: std.Io.Reader = .fixed(data_buffer.items);
3235 var data_fbs: std.Io.Reader = .fixed(data_buffer.written());
33263236 try Compiler.writeResourceData(writer, &data_fbs, data_size);
33273237 }
33283238 };
lib/compiler/resinator/cvtres.zig+12-12
......@@ -43,7 +43,7 @@ pub const Resource = struct {
4343};
4444
4545pub const ParsedResources = struct {
46 list: std.ArrayListUnmanaged(Resource) = .empty,
46 list: std.ArrayList(Resource) = .empty,
4747 allocator: Allocator,
4848
4949 pub fn init(allocator: Allocator) ParsedResources {
......@@ -157,7 +157,7 @@ pub fn parseNameOrOrdinal(allocator: Allocator, reader: *std.Io.Reader) !NameOrO
157157 const ordinal_value = try reader.takeInt(u16, .little);
158158 return .{ .ordinal = ordinal_value };
159159 }
160 var name_buf = try std.ArrayListUnmanaged(u16).initCapacity(allocator, 16);
160 var name_buf = try std.ArrayList(u16).initCapacity(allocator, 16);
161161 errdefer name_buf.deinit(allocator);
162162 var code_unit = first_code_unit;
163163 while (code_unit != 0) {
......@@ -373,7 +373,7 @@ pub fn writeCoff(allocator: Allocator, writer: *std.Io.Writer, resources: []cons
373373 try writer.writeAll(string_table.bytes.items);
374374}
375375
376fn writeSymbol(writer: anytype, symbol: std.coff.Symbol) !void {
376fn writeSymbol(writer: *std.Io.Writer, symbol: std.coff.Symbol) !void {
377377 try writer.writeAll(&symbol.name);
378378 try writer.writeInt(u32, symbol.value, .little);
379379 try writer.writeInt(u16, @intFromEnum(symbol.section_number), .little);
......@@ -383,7 +383,7 @@ fn writeSymbol(writer: anytype, symbol: std.coff.Symbol) !void {
383383 try writer.writeInt(u8, symbol.number_of_aux_symbols, .little);
384384}
385385
386fn writeSectionDefinition(writer: anytype, def: std.coff.SectionDefinition) !void {
386fn writeSectionDefinition(writer: *std.Io.Writer, def: std.coff.SectionDefinition) !void {
387387 try writer.writeInt(u32, def.length, .little);
388388 try writer.writeInt(u16, def.number_of_relocations, .little);
389389 try writer.writeInt(u16, def.number_of_linenumbers, .little);
......@@ -417,7 +417,7 @@ pub const ResourceDirectoryEntry = extern struct {
417417 to_subdirectory: bool,
418418 },
419419
420 pub fn writeCoff(self: ResourceDirectoryEntry, writer: anytype) !void {
420 pub fn writeCoff(self: ResourceDirectoryEntry, writer: *std.Io.Writer) !void {
421421 try writer.writeInt(u32, @bitCast(self.entry), .little);
422422 try writer.writeInt(u32, @bitCast(self.offset), .little);
423423 }
......@@ -435,7 +435,7 @@ const ResourceTree = struct {
435435 type_to_name_map: std.ArrayHashMapUnmanaged(NameOrOrdinal, NameToLanguageMap, NameOrOrdinalHashContext, true),
436436 rsrc_string_table: std.ArrayHashMapUnmanaged(NameOrOrdinal, void, NameOrOrdinalHashContext, true),
437437 deduplicated_data: std.StringArrayHashMapUnmanaged(u32),
438 data_offsets: std.ArrayListUnmanaged(u32),
438 data_offsets: std.ArrayList(u32),
439439 rsrc02_len: u32,
440440 coff_options: CoffOptions,
441441 allocator: Allocator,
......@@ -675,13 +675,13 @@ const ResourceTree = struct {
675675 return &.{};
676676 }
677677
678 var level2_list: std.ArrayListUnmanaged(*const NameToLanguageMap) = .empty;
678 var level2_list: std.ArrayList(*const NameToLanguageMap) = .empty;
679679 defer level2_list.deinit(allocator);
680680
681 var level3_list: std.ArrayListUnmanaged(*const LanguageToResourceMap) = .empty;
681 var level3_list: std.ArrayList(*const LanguageToResourceMap) = .empty;
682682 defer level3_list.deinit(allocator);
683683
684 var resources_list: std.ArrayListUnmanaged(*const RelocatableResource) = .empty;
684 var resources_list: std.ArrayList(*const RelocatableResource) = .empty;
685685 defer resources_list.deinit(allocator);
686686
687687 var relocations = Relocations.init(allocator);
......@@ -896,7 +896,7 @@ const ResourceTree = struct {
896896 return symbols;
897897 }
898898
899 fn writeRelocation(writer: anytype, relocation: std.coff.Relocation) !void {
899 fn writeRelocation(writer: *std.Io.Writer, relocation: std.coff.Relocation) !void {
900900 try writer.writeInt(u32, relocation.virtual_address, .little);
901901 try writer.writeInt(u32, relocation.symbol_table_index, .little);
902902 try writer.writeInt(u16, relocation.type, .little);
......@@ -928,7 +928,7 @@ const Relocation = struct {
928928
929929const Relocations = struct {
930930 allocator: Allocator,
931 list: std.ArrayListUnmanaged(Relocation) = .empty,
931 list: std.ArrayList(Relocation) = .empty,
932932 cur_symbol_index: u32 = 5,
933933
934934 pub fn init(allocator: Allocator) Relocations {
......@@ -952,7 +952,7 @@ const Relocations = struct {
952952/// Does not do deduplication (only because there's no chance of duplicate strings in this
953953/// instance).
954954const StringTable = struct {
955 bytes: std.ArrayListUnmanaged(u8) = .empty,
955 bytes: std.ArrayList(u8) = .empty,
956956
957957 pub fn deinit(self: *StringTable, allocator: Allocator) void {
958958 self.bytes.deinit(allocator);
lib/compiler/resinator/errors.zig+25-28
......@@ -15,10 +15,10 @@ const builtin = @import("builtin");
1515const native_endian = builtin.cpu.arch.endian();
1616
1717pub const Diagnostics = struct {
18 errors: std.ArrayListUnmanaged(ErrorDetails) = .empty,
18 errors: std.ArrayList(ErrorDetails) = .empty,
1919 /// Append-only, cannot handle removing strings.
2020 /// Expects to own all strings within the list.
21 strings: std.ArrayListUnmanaged([]const u8) = .empty,
21 strings: std.ArrayList([]const u8) = .empty,
2222 allocator: std.mem.Allocator,
2323
2424 pub fn init(allocator: std.mem.Allocator) Diagnostics {
......@@ -256,7 +256,7 @@ pub const ErrorDetails = struct {
256256 .{ "literal", "unquoted literal" },
257257 });
258258
259 pub fn writeCommaSeparated(self: ExpectedTypes, writer: anytype) !void {
259 pub fn writeCommaSeparated(self: ExpectedTypes, writer: *std.Io.Writer) !void {
260260 const struct_info = @typeInfo(ExpectedTypes).@"struct";
261261 const num_real_fields = struct_info.fields.len - 1;
262262 const num_padding_bits = @bitSizeOf(ExpectedTypes) - num_real_fields;
......@@ -441,7 +441,7 @@ pub const ErrorDetails = struct {
441441 } };
442442 }
443443
444 pub fn render(self: ErrorDetails, writer: anytype, source: []const u8, strings: []const []const u8) !void {
444 pub fn render(self: ErrorDetails, writer: *std.Io.Writer, source: []const u8, strings: []const []const u8) !void {
445445 switch (self.err) {
446446 .unfinished_string_literal => {
447447 return writer.print("unfinished string literal at '{f}', expected closing '\"'", .{self.fmtToken(source)});
......@@ -987,12 +987,14 @@ pub fn renderErrorMessage(writer: *std.io.Writer, tty_config: std.io.tty.Config,
987987 if (corresponding_span != null and corresponding_file != null) {
988988 var worth_printing_lines: bool = true;
989989 var initial_lines_err: ?anyerror = null;
990 var file_reader_buf: [max_source_line_bytes * 2]u8 = undefined;
990991 var corresponding_lines: ?CorrespondingLines = CorrespondingLines.init(
991992 cwd,
992993 err_details,
993994 source_line_for_display.line,
994995 corresponding_span.?,
995996 corresponding_file.?,
997 &file_reader_buf,
996998 ) catch |err| switch (err) {
997999 error.NotWorthPrintingLines => blk: {
9981000 worth_printing_lines = false;
......@@ -1078,10 +1080,17 @@ const CorrespondingLines = struct {
10781080 at_eof: bool = false,
10791081 span: SourceMappings.CorrespondingSpan,
10801082 file: std.fs.File,
1081 buffered_reader: std.fs.File.Reader,
1083 file_reader: std.fs.File.Reader,
10821084 code_page: SupportedCodePage,
10831085
1084 pub fn init(cwd: std.fs.Dir, err_details: ErrorDetails, line_for_comparison: []const u8, corresponding_span: SourceMappings.CorrespondingSpan, corresponding_file: []const u8) !CorrespondingLines {
1086 pub fn init(
1087 cwd: std.fs.Dir,
1088 err_details: ErrorDetails,
1089 line_for_comparison: []const u8,
1090 corresponding_span: SourceMappings.CorrespondingSpan,
1091 corresponding_file: []const u8,
1092 file_reader_buf: []u8,
1093 ) !CorrespondingLines {
10851094 // We don't do line comparison for this error, so don't print the note if the line
10861095 // number is different
10871096 if (err_details.err == .string_literal_too_long and err_details.token.line_number != corresponding_span.start_line) {
......@@ -1096,18 +1105,14 @@ const CorrespondingLines = struct {
10961105 var corresponding_lines = CorrespondingLines{
10971106 .span = corresponding_span,
10981107 .file = try utils.openFileNotDir(cwd, corresponding_file, .{}),
1099 .buffered_reader = undefined,
11001108 .code_page = err_details.code_page,
1109 .file_reader = undefined,
11011110 };
1102 corresponding_lines.buffered_reader = corresponding_lines.file.reader(&.{});
1111 corresponding_lines.file_reader = corresponding_lines.file.reader(file_reader_buf);
11031112 errdefer corresponding_lines.deinit();
11041113
1105 var fbs = std.io.fixedBufferStream(&corresponding_lines.line_buf);
1106 const writer = fbs.writer();
1107
11081114 try corresponding_lines.writeLineFromStreamVerbatim(
1109 writer,
1110 corresponding_lines.buffered_reader.interface.adaptToOldInterface(),
1115 &corresponding_lines.file_reader.interface,
11111116 corresponding_span.start_line,
11121117 );
11131118
......@@ -1145,12 +1150,8 @@ const CorrespondingLines = struct {
11451150 self.line_len = 0;
11461151 self.visual_line_len = 0;
11471152
1148 var fbs = std.io.fixedBufferStream(&self.line_buf);
1149 const writer = fbs.writer();
1150
11511153 try self.writeLineFromStreamVerbatim(
1152 writer,
1153 self.buffered_reader.interface.adaptToOldInterface(),
1154 &self.file_reader.interface,
11541155 self.line_num,
11551156 );
11561157
......@@ -1164,7 +1165,7 @@ const CorrespondingLines = struct {
11641165 return visual_line;
11651166 }
11661167
1167 fn writeLineFromStreamVerbatim(self: *CorrespondingLines, writer: anytype, input: anytype, line_num: usize) !void {
1168 fn writeLineFromStreamVerbatim(self: *CorrespondingLines, input: *std.Io.Reader, line_num: usize) !void {
11681169 while (try readByteOrEof(input)) |byte| {
11691170 switch (byte) {
11701171 '\n', '\r' => {
......@@ -1184,13 +1185,9 @@ const CorrespondingLines = struct {
11841185 }
11851186 },
11861187 else => {
1187 if (self.line_num == line_num) {
1188 if (writer.writeByte(byte)) {
1189 self.line_len += 1;
1190 } else |err| switch (err) {
1191 error.NoSpaceLeft => {},
1192 else => |e| return e,
1193 }
1188 if (self.line_num == line_num and self.line_len < self.line_buf.len) {
1189 self.line_buf[self.line_len] = byte;
1190 self.line_len += 1;
11941191 }
11951192 },
11961193 }
......@@ -1201,8 +1198,8 @@ const CorrespondingLines = struct {
12011198 self.line_num += 1;
12021199 }
12031200
1204 fn readByteOrEof(reader: anytype) !?u8 {
1205 return reader.readByte() catch |err| switch (err) {
1201 fn readByteOrEof(reader: *std.Io.Reader) !?u8 {
1202 return reader.takeByte() catch |err| switch (err) {
12061203 error.EndOfStream => return null,
12071204 else => |e| return e,
12081205 };
lib/compiler/resinator/ico.zig+43-57
......@@ -8,80 +8,66 @@ const std = @import("std");
88const builtin = @import("builtin");
99const native_endian = builtin.cpu.arch.endian();
1010
11pub const ReadError = std.mem.Allocator.Error || error{ InvalidHeader, InvalidImageType, ImpossibleDataSize, UnexpectedEOF, ReadError };
12
13pub fn read(allocator: std.mem.Allocator, reader: anytype, max_size: u64) ReadError!IconDir {
14 // Some Reader implementations have an empty ReadError error set which would
15 // cause 'unreachable else' if we tried to use an else in the switch, so we
16 // need to detect this case and not try to translate to ReadError
17 const anyerror_reader_errorset = @TypeOf(reader).Error == anyerror;
18 const empty_reader_errorset = @typeInfo(@TypeOf(reader).Error).error_set == null or @typeInfo(@TypeOf(reader).Error).error_set.?.len == 0;
19 if (empty_reader_errorset and !anyerror_reader_errorset) {
20 return readAnyError(allocator, reader, max_size) catch |err| switch (err) {
21 error.EndOfStream => error.UnexpectedEOF,
22 else => |e| return e,
23 };
24 } else {
25 return readAnyError(allocator, reader, max_size) catch |err| switch (err) {
26 error.OutOfMemory,
27 error.InvalidHeader,
28 error.InvalidImageType,
29 error.ImpossibleDataSize,
30 => |e| return e,
31 error.EndOfStream => error.UnexpectedEOF,
32 // The remaining errors are dependent on the `reader`, so
33 // we just translate them all to generic ReadError
34 else => error.ReadError,
35 };
36 }
11pub const ReadError = std.mem.Allocator.Error || error{ InvalidHeader, InvalidImageType, ImpossibleDataSize, UnexpectedEOF, ReadFailed };
12
13pub fn read(allocator: std.mem.Allocator, reader: *std.Io.Reader, max_size: u64) ReadError!IconDir {
14 return readInner(allocator, reader, max_size) catch |err| switch (err) {
15 error.OutOfMemory,
16 error.InvalidHeader,
17 error.InvalidImageType,
18 error.ImpossibleDataSize,
19 error.ReadFailed,
20 => |e| return e,
21 error.EndOfStream => error.UnexpectedEOF,
22 };
3723}
3824
3925// TODO: This seems like a somewhat strange pattern, could be a better way
4026// to do this. Maybe it makes more sense to handle the translation
4127// at the call site instead of having a helper function here.
42pub fn readAnyError(allocator: std.mem.Allocator, reader: anytype, max_size: u64) !IconDir {
43 const reserved = try reader.readInt(u16, .little);
28fn readInner(allocator: std.mem.Allocator, reader: *std.Io.Reader, max_size: u64) !IconDir {
29 const reserved = try reader.takeInt(u16, .little);
4430 if (reserved != 0) {
4531 return error.InvalidHeader;
4632 }
4733
48 const image_type = reader.readEnum(ImageType, .little) catch |err| switch (err) {
49 error.InvalidValue => return error.InvalidImageType,
34 const image_type = reader.takeEnum(ImageType, .little) catch |err| switch (err) {
35 error.InvalidEnumTag => return error.InvalidImageType,
5036 else => |e| return e,
5137 };
5238
53 const num_images = try reader.readInt(u16, .little);
39 const num_images = try reader.takeInt(u16, .little);
5440
5541 // To avoid over-allocation in the case of a file that says it has way more
5642 // entries than it actually does, we use an ArrayList with a conservatively
5743 // limited initial capacity instead of allocating the entire slice at once.
5844 const initial_capacity = @min(num_images, 8);
59 var entries = try std.array_list.Managed(Entry).initCapacity(allocator, initial_capacity);
60 errdefer entries.deinit();
45 var entries = try std.ArrayList(Entry).initCapacity(allocator, initial_capacity);
46 errdefer entries.deinit(allocator);
6147
6248 var i: usize = 0;
6349 while (i < num_images) : (i += 1) {
6450 var entry: Entry = undefined;
65 entry.width = try reader.readByte();
66 entry.height = try reader.readByte();
67 entry.num_colors = try reader.readByte();
68 entry.reserved = try reader.readByte();
51 entry.width = try reader.takeByte();
52 entry.height = try reader.takeByte();
53 entry.num_colors = try reader.takeByte();
54 entry.reserved = try reader.takeByte();
6955 switch (image_type) {
7056 .icon => {
7157 entry.type_specific_data = .{ .icon = .{
72 .color_planes = try reader.readInt(u16, .little),
73 .bits_per_pixel = try reader.readInt(u16, .little),
58 .color_planes = try reader.takeInt(u16, .little),
59 .bits_per_pixel = try reader.takeInt(u16, .little),
7460 } };
7561 },
7662 .cursor => {
7763 entry.type_specific_data = .{ .cursor = .{
78 .hotspot_x = try reader.readInt(u16, .little),
79 .hotspot_y = try reader.readInt(u16, .little),
64 .hotspot_x = try reader.takeInt(u16, .little),
65 .hotspot_y = try reader.takeInt(u16, .little),
8066 } };
8167 },
8268 }
83 entry.data_size_in_bytes = try reader.readInt(u32, .little);
84 entry.data_offset_from_start_of_file = try reader.readInt(u32, .little);
69 entry.data_size_in_bytes = try reader.takeInt(u32, .little);
70 entry.data_offset_from_start_of_file = try reader.takeInt(u32, .little);
8571 // Validate that the offset/data size is feasible
8672 if (@as(u64, entry.data_offset_from_start_of_file) + entry.data_size_in_bytes > max_size) {
8773 return error.ImpossibleDataSize;
......@@ -101,12 +87,12 @@ pub fn readAnyError(allocator: std.mem.Allocator, reader: anytype, max_size: u64
10187 if (entry.data_size_in_bytes < 16) {
10288 return error.ImpossibleDataSize;
10389 }
104 try entries.append(entry);
90 try entries.append(allocator, entry);
10591 }
10692
10793 return .{
10894 .image_type = image_type,
109 .entries = try entries.toOwnedSlice(),
95 .entries = try entries.toOwnedSlice(allocator),
11096 .allocator = allocator,
11197 };
11298}
......@@ -135,7 +121,7 @@ pub const IconDir = struct {
135121 return @intCast(IconDir.res_header_byte_len + self.entries.len * Entry.res_byte_len);
136122 }
137123
138 pub fn writeResData(self: IconDir, writer: anytype, first_image_id: u16) !void {
124 pub fn writeResData(self: IconDir, writer: *std.Io.Writer, first_image_id: u16) !void {
139125 try writer.writeInt(u16, 0, .little);
140126 try writer.writeInt(u16, @intFromEnum(self.image_type), .little);
141127 // We know that entries.len must fit into a u16
......@@ -173,7 +159,7 @@ pub const Entry = struct {
173159
174160 pub const res_byte_len = 14;
175161
176 pub fn writeResData(self: Entry, writer: anytype, id: u16) !void {
162 pub fn writeResData(self: Entry, writer: *std.Io.Writer, id: u16) !void {
177163 switch (self.type_specific_data) {
178164 .icon => |icon_data| {
179165 try writer.writeInt(u8, @as(u8, @truncate(self.width)), .little);
......@@ -198,8 +184,8 @@ pub const Entry = struct {
198184
199185test "icon" {
200186 const data = "\x00\x00\x01\x00\x01\x00\x10\x10\x00\x00\x01\x00\x10\x00\x10\x00\x00\x00\x16\x00\x00\x00" ++ [_]u8{0} ** 16;
201 var fbs = std.io.fixedBufferStream(data);
202 const icon = try read(std.testing.allocator, fbs.reader(), data.len);
187 var fbs: std.Io.Reader = .fixed(data);
188 const icon = try read(std.testing.allocator, &fbs, data.len);
203189 defer icon.deinit();
204190
205191 try std.testing.expectEqual(ImageType.icon, icon.image_type);
......@@ -211,26 +197,26 @@ test "icon too many images" {
211197 // it's not possible to hit EOF when looking for more RESDIR structures, since they are
212198 // themselves 16 bytes long, so we'll always hit ImpossibleDataSize instead.
213199 const data = "\x00\x00\x01\x00\x02\x00\x10\x10\x00\x00\x01\x00\x10\x00\x10\x00\x00\x00\x16\x00\x00\x00" ++ [_]u8{0} ** 16;
214 var fbs = std.io.fixedBufferStream(data);
215 try std.testing.expectError(error.ImpossibleDataSize, read(std.testing.allocator, fbs.reader(), data.len));
200 var fbs: std.Io.Reader = .fixed(data);
201 try std.testing.expectError(error.ImpossibleDataSize, read(std.testing.allocator, &fbs, data.len));
216202}
217203
218204test "icon data size past EOF" {
219205 const data = "\x00\x00\x01\x00\x01\x00\x10\x10\x00\x00\x01\x00\x10\x00\x10\x01\x00\x00\x16\x00\x00\x00" ++ [_]u8{0} ** 16;
220 var fbs = std.io.fixedBufferStream(data);
221 try std.testing.expectError(error.ImpossibleDataSize, read(std.testing.allocator, fbs.reader(), data.len));
206 var fbs: std.Io.Reader = .fixed(data);
207 try std.testing.expectError(error.ImpossibleDataSize, read(std.testing.allocator, &fbs, data.len));
222208}
223209
224210test "icon data offset past EOF" {
225211 const data = "\x00\x00\x01\x00\x01\x00\x10\x10\x00\x00\x01\x00\x10\x00\x10\x00\x00\x00\x17\x00\x00\x00" ++ [_]u8{0} ** 16;
226 var fbs = std.io.fixedBufferStream(data);
227 try std.testing.expectError(error.ImpossibleDataSize, read(std.testing.allocator, fbs.reader(), data.len));
212 var fbs: std.Io.Reader = .fixed(data);
213 try std.testing.expectError(error.ImpossibleDataSize, read(std.testing.allocator, &fbs, data.len));
228214}
229215
230216test "icon data size too small" {
231217 const data = "\x00\x00\x01\x00\x01\x00\x10\x10\x00\x00\x01\x00\x10\x00\x0F\x00\x00\x00\x16\x00\x00\x00";
232 var fbs = std.io.fixedBufferStream(data);
233 try std.testing.expectError(error.ImpossibleDataSize, read(std.testing.allocator, fbs.reader(), data.len));
218 var fbs: std.Io.Reader = .fixed(data);
219 try std.testing.expectError(error.ImpossibleDataSize, read(std.testing.allocator, &fbs, data.len));
234220}
235221
236222pub const ImageFormat = enum(u2) {
lib/compiler/resinator/lang.zig+6-5
......@@ -119,6 +119,7 @@ test tagToId {
119119}
120120
121121test "exhaustive tagToId" {
122 @setEvalBranchQuota(2000);
122123 inline for (@typeInfo(LanguageId).@"enum".fields) |field| {
123124 const id = tagToId(field.name) catch |err| {
124125 std.debug.print("tag: {s}\n", .{field.name});
......@@ -131,8 +132,8 @@ test "exhaustive tagToId" {
131132 }
132133 var buf: [32]u8 = undefined;
133134 inline for (valid_alternate_sorts) |parsed_sort| {
134 var fbs = std.io.fixedBufferStream(&buf);
135 const writer = fbs.writer();
135 var fbs: std.Io.Writer = .fixed(&buf);
136 const writer = &fbs;
136137 writer.writeAll(parsed_sort.language_code) catch unreachable;
137138 writer.writeAll("-") catch unreachable;
138139 writer.writeAll(parsed_sort.country_code.?) catch unreachable;
......@@ -146,12 +147,12 @@ test "exhaustive tagToId" {
146147 break :field name_buf;
147148 };
148149 const expected = @field(LanguageId, &expected_field_name);
149 const id = tagToId(fbs.getWritten()) catch |err| {
150 std.debug.print("tag: {s}\n", .{fbs.getWritten()});
150 const id = tagToId(fbs.buffered()) catch |err| {
151 std.debug.print("tag: {s}\n", .{fbs.buffered()});
151152 return err;
152153 };
153154 try std.testing.expectEqual(expected, id orelse {
154 std.debug.print("tag: {s}, expected: {}, got null\n", .{ fbs.getWritten(), expected });
155 std.debug.print("tag: {s}, expected: {}, got null\n", .{ fbs.buffered(), expected });
155156 return error.TestExpectedEqual;
156157 });
157158 }
lib/compiler/resinator/literals.zig+22-22
......@@ -469,8 +469,8 @@ pub fn parseQuotedString(
469469 const T = if (literal_type == .ascii) u8 else u16;
470470 std.debug.assert(bytes.slice.len >= 2); // must at least have 2 double quote chars
471471
472 var buf = try std.array_list.Managed(T).initCapacity(allocator, bytes.slice.len);
473 errdefer buf.deinit();
472 var buf = try std.ArrayList(T).initCapacity(allocator, bytes.slice.len);
473 errdefer buf.deinit(allocator);
474474
475475 var iterative_parser = IterativeStringParser.init(bytes, options);
476476
......@@ -480,13 +480,13 @@ pub fn parseQuotedString(
480480 .ascii => switch (options.output_code_page) {
481481 .windows1252 => {
482482 if (parsed.from_escaped_integer) {
483 try buf.append(@truncate(c));
483 try buf.append(allocator, @truncate(c));
484484 } else if (windows1252.bestFitFromCodepoint(c)) |best_fit| {
485 try buf.append(best_fit);
485 try buf.append(allocator, best_fit);
486486 } else if (c < 0x10000 or c == code_pages.Codepoint.invalid) {
487 try buf.append('?');
487 try buf.append(allocator, '?');
488488 } else {
489 try buf.appendSlice("??");
489 try buf.appendSlice(allocator, "??");
490490 }
491491 },
492492 .utf8 => {
......@@ -500,35 +500,35 @@ pub fn parseQuotedString(
500500 }
501501 var utf8_buf: [4]u8 = undefined;
502502 const utf8_len = std.unicode.utf8Encode(codepoint_to_encode, &utf8_buf) catch unreachable;
503 try buf.appendSlice(utf8_buf[0..utf8_len]);
503 try buf.appendSlice(allocator, utf8_buf[0..utf8_len]);
504504 },
505505 },
506506 .wide => {
507507 // Parsing any string type as a wide string is handled separately, see parseQuotedStringAsWideString
508508 std.debug.assert(iterative_parser.declared_string_type == .wide);
509509 if (parsed.from_escaped_integer) {
510 try buf.append(std.mem.nativeToLittle(u16, @truncate(c)));
510 try buf.append(allocator, std.mem.nativeToLittle(u16, @truncate(c)));
511511 } else if (c == code_pages.Codepoint.invalid) {
512 try buf.append(std.mem.nativeToLittle(u16, '�'));
512 try buf.append(allocator, std.mem.nativeToLittle(u16, '�'));
513513 } else if (c < 0x10000) {
514514 const short: u16 = @intCast(c);
515 try buf.append(std.mem.nativeToLittle(u16, short));
515 try buf.append(allocator, std.mem.nativeToLittle(u16, short));
516516 } else {
517517 if (!parsed.escaped_surrogate_pair) {
518518 const high = @as(u16, @intCast((c - 0x10000) >> 10)) + 0xD800;
519 try buf.append(std.mem.nativeToLittle(u16, high));
519 try buf.append(allocator, std.mem.nativeToLittle(u16, high));
520520 }
521521 const low = @as(u16, @intCast(c & 0x3FF)) + 0xDC00;
522 try buf.append(std.mem.nativeToLittle(u16, low));
522 try buf.append(allocator, std.mem.nativeToLittle(u16, low));
523523 }
524524 },
525525 }
526526 }
527527
528528 if (literal_type == .wide) {
529 return buf.toOwnedSliceSentinel(0);
529 return buf.toOwnedSliceSentinel(allocator, 0);
530530 } else {
531 return buf.toOwnedSlice();
531 return buf.toOwnedSlice(allocator);
532532 }
533533}
534534
......@@ -564,8 +564,8 @@ pub fn parseQuotedStringAsWideString(allocator: std.mem.Allocator, bytes: Source
564564 // Note: We're only handling the case of parsing an ASCII string into a wide string from here on out.
565565 // TODO: The logic below is similar to that in AcceleratorKeyCodepointTranslator, might be worth merging the two
566566
567 var buf = try std.array_list.Managed(u16).initCapacity(allocator, bytes.slice.len);
568 errdefer buf.deinit();
567 var buf = try std.ArrayList(u16).initCapacity(allocator, bytes.slice.len);
568 errdefer buf.deinit(allocator);
569569
570570 var iterative_parser = IterativeStringParser.init(bytes, options);
571571
......@@ -578,23 +578,23 @@ pub fn parseQuotedStringAsWideString(allocator: std.mem.Allocator, bytes: Source
578578 .windows1252 => windows1252.toCodepoint(byte_to_interpret),
579579 .utf8 => if (byte_to_interpret > 0x7F) '�' else byte_to_interpret,
580580 };
581 try buf.append(std.mem.nativeToLittle(u16, code_unit_to_encode));
581 try buf.append(allocator, std.mem.nativeToLittle(u16, code_unit_to_encode));
582582 } else if (c == code_pages.Codepoint.invalid) {
583 try buf.append(std.mem.nativeToLittle(u16, '�'));
583 try buf.append(allocator, std.mem.nativeToLittle(u16, '�'));
584584 } else if (c < 0x10000) {
585585 const short: u16 = @intCast(c);
586 try buf.append(std.mem.nativeToLittle(u16, short));
586 try buf.append(allocator, std.mem.nativeToLittle(u16, short));
587587 } else {
588588 if (!parsed.escaped_surrogate_pair) {
589589 const high = @as(u16, @intCast((c - 0x10000) >> 10)) + 0xD800;
590 try buf.append(std.mem.nativeToLittle(u16, high));
590 try buf.append(allocator, std.mem.nativeToLittle(u16, high));
591591 }
592592 const low = @as(u16, @intCast(c & 0x3FF)) + 0xDC00;
593 try buf.append(std.mem.nativeToLittle(u16, low));
593 try buf.append(allocator, std.mem.nativeToLittle(u16, low));
594594 }
595595 }
596596
597 return buf.toOwnedSliceSentinel(0);
597 return buf.toOwnedSliceSentinel(allocator, 0);
598598}
599599
600600test "parse quoted ascii string" {
lib/compiler/resinator/main.zig+68-62
......@@ -3,6 +3,7 @@ const builtin = @import("builtin");
33const removeComments = @import("comments.zig").removeComments;
44const parseAndRemoveLineCommands = @import("source_mapping.zig").parseAndRemoveLineCommands;
55const compile = @import("compile.zig").compile;
6const Dependencies = @import("compile.zig").Dependencies;
67const Diagnostics = @import("errors.zig").Diagnostics;
78const cli = @import("cli.zig");
89const preprocess = @import("preprocess.zig");
......@@ -13,8 +14,6 @@ const hasDisjointCodePage = @import("disjoint_code_page.zig").hasDisjointCodePag
1314const fmtResourceType = @import("res.zig").NameOrOrdinal.fmtResourceType;
1415const aro = @import("aro");
1516
16var stdout_buffer: [1024]u8 = undefined;
17
1817pub fn main() !void {
1918 var gpa: std.heap.GeneralPurposeAllocator(.{}) = .init;
2019 defer std.debug.assert(gpa.deinit() == .ok);
......@@ -43,11 +42,13 @@ pub fn main() !void {
4342 cli_args = args[3..];
4443 }
4544
46 var stdout_writer2 = std.fs.File.stdout().writer(&stdout_buffer);
45 var stdout_buffer: [1024]u8 = undefined;
46 var stdout_writer = std.fs.File.stdout().writer(&stdout_buffer);
47 const stdout = &stdout_writer.interface;
4748 var error_handler: ErrorHandler = switch (zig_integration) {
4849 true => .{
4950 .server = .{
50 .out = &stdout_writer2.interface,
51 .out = stdout,
5152 .in = undefined, // won't be receiving messages
5253 },
5354 },
......@@ -83,28 +84,23 @@ pub fn main() !void {
8384 defer options.deinit();
8485
8586 if (options.print_help_and_exit) {
86 const stdout = std.fs.File.stdout();
87 try cli.writeUsage(stdout.deprecatedWriter(), "zig rc");
87 try cli.writeUsage(stdout, "zig rc");
88 try stdout.flush();
8889 return;
8990 }
9091
9192 // Don't allow verbose when integrating with Zig via stdout
9293 options.verbose = false;
9394
94 const stdout_writer = std.fs.File.stdout().deprecatedWriter();
9595 if (options.verbose) {
96 try options.dumpVerbose(stdout_writer);
97 try stdout_writer.writeByte('\n');
96 try options.dumpVerbose(stdout);
97 try stdout.writeByte('\n');
98 try stdout.flush();
9899 }
99100
100 var dependencies_list = std.array_list.Managed([]const u8).init(allocator);
101 defer {
102 for (dependencies_list.items) |item| {
103 allocator.free(item);
104 }
105 dependencies_list.deinit();
106 }
107 const maybe_dependencies_list: ?*std.array_list.Managed([]const u8) = if (options.depfile_path != null) &dependencies_list else null;
101 var dependencies = Dependencies.init(allocator);
102 defer dependencies.deinit();
103 const maybe_dependencies: ?*Dependencies = if (options.depfile_path != null) &dependencies else null;
108104
109105 var include_paths = LazyIncludePaths{
110106 .arena = arena,
......@@ -115,7 +111,7 @@ pub fn main() !void {
115111
116112 const full_input = full_input: {
117113 if (options.input_format == .rc and options.preprocess != .no) {
118 var preprocessed_buf = std.array_list.Managed(u8).init(allocator);
114 var preprocessed_buf: std.Io.Writer.Allocating = .init(allocator);
119115 errdefer preprocessed_buf.deinit();
120116
121117 // We're going to throw away everything except the final preprocessed output anyway,
......@@ -127,26 +123,27 @@ pub fn main() !void {
127123 var comp = aro.Compilation.init(aro_arena, std.fs.cwd());
128124 defer comp.deinit();
129125
130 var argv = std.array_list.Managed([]const u8).init(comp.gpa);
131 defer argv.deinit();
126 var argv: std.ArrayList([]const u8) = .empty;
127 defer argv.deinit(aro_arena);
132128
133 try argv.append("arocc"); // dummy command name
129 try argv.append(aro_arena, "arocc"); // dummy command name
134130 const resolved_include_paths = try include_paths.get(&error_handler);
135131 try preprocess.appendAroArgs(aro_arena, &argv, options, resolved_include_paths);
136 try argv.append(switch (options.input_source) {
132 try argv.append(aro_arena, switch (options.input_source) {
137133 .stdio => "-",
138134 .filename => |filename| filename,
139135 });
140136
141137 if (options.verbose) {
142 try stdout_writer.writeAll("Preprocessor: arocc (built-in)\n");
138 try stdout.writeAll("Preprocessor: arocc (built-in)\n");
143139 for (argv.items[0 .. argv.items.len - 1]) |arg| {
144 try stdout_writer.print("{s} ", .{arg});
140 try stdout.print("{s} ", .{arg});
145141 }
146 try stdout_writer.print("{s}\n\n", .{argv.items[argv.items.len - 1]});
142 try stdout.print("{s}\n\n", .{argv.items[argv.items.len - 1]});
143 try stdout.flush();
147144 }
148145
149 preprocess.preprocess(&comp, preprocessed_buf.writer(), argv.items, maybe_dependencies_list) catch |err| switch (err) {
146 preprocess.preprocess(&comp, &preprocessed_buf.writer, argv.items, maybe_dependencies) catch |err| switch (err) {
150147 error.GeneratedSourceError => {
151148 try error_handler.emitAroDiagnostics(allocator, "failed during preprocessor setup (this is always a bug):", &comp);
152149 std.process.exit(1);
......@@ -249,14 +246,15 @@ pub fn main() !void {
249246 defer diagnostics.deinit();
250247
251248 var output_buffer: [4096]u8 = undefined;
252 var res_stream_writer = res_stream.source.writer(allocator).adaptToNewApi(&output_buffer);
253 const output_buffered_stream = &res_stream_writer.new_interface;
249 var res_stream_writer = res_stream.source.writer(allocator, &output_buffer);
250 defer res_stream_writer.deinit(&res_stream.source);
251 const output_buffered_stream = res_stream_writer.interface();
254252
255253 compile(allocator, final_input, output_buffered_stream, .{
256254 .cwd = std.fs.cwd(),
257255 .diagnostics = &diagnostics,
258256 .source_mappings = &mapping_results.mappings,
259 .dependencies_list = maybe_dependencies_list,
257 .dependencies = maybe_dependencies,
260258 .ignore_include_env_var = options.ignore_include_env_var,
261259 .extra_include_paths = options.extra_include_paths.items,
262260 .system_include_paths = try include_paths.get(&error_handler),
......@@ -303,7 +301,7 @@ pub fn main() !void {
303301 };
304302
305303 try write_stream.beginArray();
306 for (dependencies_list.items) |dep_path| {
304 for (dependencies.list.items) |dep_path| {
307305 try write_stream.write(dep_path);
308306 }
309307 try write_stream.endArray();
......@@ -342,10 +340,10 @@ pub fn main() !void {
342340 defer coff_stream.deinit(allocator);
343341
344342 var coff_output_buffer: [4096]u8 = undefined;
345 var coff_output_buffered_stream = coff_stream.source.writer(allocator).adaptToNewApi(&coff_output_buffer);
343 var coff_output_buffered_stream = coff_stream.source.writer(allocator, &coff_output_buffer);
346344
347345 var cvtres_diagnostics: cvtres.Diagnostics = .{ .none = {} };
348 cvtres.writeCoff(allocator, &coff_output_buffered_stream.new_interface, resources.list.items, options.coff_options, &cvtres_diagnostics) catch |err| {
346 cvtres.writeCoff(allocator, coff_output_buffered_stream.interface(), resources.list.items, options.coff_options, &cvtres_diagnostics) catch |err| {
349347 switch (err) {
350348 error.DuplicateResource => {
351349 const duplicate_resource = resources.list.items[cvtres_diagnostics.duplicate_resource];
......@@ -382,7 +380,7 @@ pub fn main() !void {
382380 std.process.exit(1);
383381 };
384382
385 try coff_output_buffered_stream.new_interface.flush();
383 try coff_output_buffered_stream.interface().flush();
386384}
387385
388386const IoStream = struct {
......@@ -425,7 +423,7 @@ const IoStream = struct {
425423 pub const Source = union(enum) {
426424 file: std.fs.File,
427425 stdio: std.fs.File,
428 memory: std.ArrayListUnmanaged(u8),
426 memory: std.ArrayList(u8),
429427 /// The source has been closed and any usage of the Source in this state is illegal (except deinit).
430428 closed: void,
431429
......@@ -472,26 +470,34 @@ const IoStream = struct {
472470 };
473471 }
474472
475 pub const WriterContext = struct {
476 self: *Source,
477 allocator: std.mem.Allocator,
478 };
479 pub const WriteError = std.mem.Allocator.Error || std.fs.File.WriteError;
480 pub const Writer = std.io.GenericWriter(WriterContext, WriteError, write);
481
482 pub fn write(ctx: WriterContext, bytes: []const u8) WriteError!usize {
483 switch (ctx.self.*) {
484 inline .file, .stdio => |file| return file.write(bytes),
485 .memory => |*list| {
486 try list.appendSlice(ctx.allocator, bytes);
487 return bytes.len;
488 },
489 .closed => unreachable,
473 pub const Writer = union(enum) {
474 file: std.fs.File.Writer,
475 allocating: std.Io.Writer.Allocating,
476
477 pub const Error = std.mem.Allocator.Error || std.fs.File.WriteError;
478
479 pub fn interface(this: *@This()) *std.Io.Writer {
480 return switch (this.*) {
481 .file => |*fw| &fw.interface,
482 .allocating => |*a| &a.writer,
483 };
490484 }
491 }
492485
493 pub fn writer(self: *Source, allocator: std.mem.Allocator) Writer {
494 return .{ .context = .{ .self = self, .allocator = allocator } };
486 pub fn deinit(this: *@This(), source: *Source) void {
487 switch (this.*) {
488 .file => {},
489 .allocating => |*a| source.memory = a.toArrayList(),
490 }
491 this.* = undefined;
492 }
493 };
494
495 pub fn writer(source: *Source, allocator: std.mem.Allocator, buffer: []u8) Writer {
496 return switch (source.*) {
497 .file, .stdio => |file| .{ .file = file.writer(buffer) },
498 .memory => |*list| .{ .allocating = .fromArrayList(allocator, list) },
499 .closed => unreachable,
500 };
495501 }
496502 };
497503};
......@@ -721,7 +727,7 @@ fn cliDiagnosticsToErrorBundle(
721727 });
722728
723729 var cur_err: ?ErrorBundle.ErrorMessage = null;
724 var cur_notes: std.ArrayListUnmanaged(ErrorBundle.ErrorMessage) = .empty;
730 var cur_notes: std.ArrayList(ErrorBundle.ErrorMessage) = .empty;
725731 defer cur_notes.deinit(gpa);
726732 for (diagnostics.errors.items) |err_details| {
727733 switch (err_details.type) {
......@@ -763,10 +769,10 @@ fn diagnosticsToErrorBundle(
763769 try bundle.init(gpa);
764770 errdefer bundle.deinit();
765771
766 var msg_buf: std.ArrayListUnmanaged(u8) = .empty;
767 defer msg_buf.deinit(gpa);
772 var msg_buf: std.Io.Writer.Allocating = .init(gpa);
773 defer msg_buf.deinit();
768774 var cur_err: ?ErrorBundle.ErrorMessage = null;
769 var cur_notes: std.ArrayListUnmanaged(ErrorBundle.ErrorMessage) = .empty;
775 var cur_notes: std.ArrayList(ErrorBundle.ErrorMessage) = .empty;
770776 defer cur_notes.deinit(gpa);
771777 for (diagnostics.errors.items) |err_details| {
772778 switch (err_details.type) {
......@@ -789,7 +795,7 @@ fn diagnosticsToErrorBundle(
789795 const column = err_details.token.calculateColumn(source, 1, source_line_start) + 1;
790796
791797 msg_buf.clearRetainingCapacity();
792 try err_details.render(msg_buf.writer(gpa), source, diagnostics.strings.items);
798 try err_details.render(&msg_buf.writer, source, diagnostics.strings.items);
793799
794800 const src_loc = src_loc: {
795801 var src_loc: ErrorBundle.SourceLocation = .{
......@@ -817,7 +823,7 @@ fn diagnosticsToErrorBundle(
817823 try flushErrorMessageIntoBundle(&bundle, err, cur_notes.items);
818824 }
819825 cur_err = .{
820 .msg = try bundle.addString(msg_buf.items),
826 .msg = try bundle.addString(msg_buf.written()),
821827 .src_loc = src_loc,
822828 };
823829 cur_notes.clearRetainingCapacity();
......@@ -825,7 +831,7 @@ fn diagnosticsToErrorBundle(
825831 .note => {
826832 cur_err.?.notes_len += 1;
827833 try cur_notes.append(gpa, .{
828 .msg = try bundle.addString(msg_buf.items),
834 .msg = try bundle.addString(msg_buf.written()),
829835 .src_loc = src_loc,
830836 });
831837 },
......@@ -876,7 +882,7 @@ fn aroDiagnosticsToErrorBundle(
876882 var msg_writer = MsgWriter.init(gpa);
877883 defer msg_writer.deinit();
878884 var cur_err: ?ErrorBundle.ErrorMessage = null;
879 var cur_notes: std.ArrayListUnmanaged(ErrorBundle.ErrorMessage) = .empty;
885 var cur_notes: std.ArrayList(ErrorBundle.ErrorMessage) = .empty;
880886 defer cur_notes.deinit(gpa);
881887 for (comp.diagnostics.list.items) |msg| {
882888 switch (msg.kind) {
......@@ -971,11 +977,11 @@ const MsgWriter = struct {
971977 }
972978
973979 pub fn print(m: *MsgWriter, comptime fmt: []const u8, args: anytype) void {
974 m.buf.writer().print(fmt, args) catch {};
980 m.buf.print(fmt, args) catch {};
975981 }
976982
977983 pub fn write(m: *MsgWriter, msg: []const u8) void {
978 m.buf.writer().writeAll(msg) catch {};
984 m.buf.appendSlice(msg) catch {};
979985 }
980986
981987 pub fn setColor(m: *MsgWriter, color: std.io.tty.Color) void {
lib/compiler/resinator/parse.zig+26-26
......@@ -82,8 +82,8 @@ pub const Parser = struct {
8282 }
8383
8484 fn parseRoot(self: *Self) Error!*Node {
85 var statements = std.array_list.Managed(*Node).init(self.state.allocator);
86 defer statements.deinit();
85 var statements: std.ArrayList(*Node) = .empty;
86 defer statements.deinit(self.state.allocator);
8787
8888 try self.parseStatements(&statements);
8989 try self.check(.eof);
......@@ -95,7 +95,7 @@ pub const Parser = struct {
9595 return &node.base;
9696 }
9797
98 fn parseStatements(self: *Self, statements: *std.array_list.Managed(*Node)) Error!void {
98 fn parseStatements(self: *Self, statements: *std.ArrayList(*Node)) Error!void {
9999 while (true) {
100100 try self.nextToken(.whitespace_delimiter_only);
101101 if (self.state.token.id == .eof) break;
......@@ -105,7 +105,7 @@ pub const Parser = struct {
105105 // (usually it will end up with bogus things like 'file
106106 // not found: {')
107107 const statement = try self.parseStatement();
108 try statements.append(statement);
108 try statements.append(self.state.allocator, statement);
109109 }
110110 }
111111
......@@ -115,7 +115,7 @@ pub const Parser = struct {
115115 /// current token is unchanged.
116116 /// The returned slice is allocated by the parser's arena
117117 fn parseCommonResourceAttributes(self: *Self) ![]Token {
118 var common_resource_attributes: std.ArrayListUnmanaged(Token) = .empty;
118 var common_resource_attributes: std.ArrayList(Token) = .empty;
119119 while (true) {
120120 const maybe_common_resource_attribute = try self.lookaheadToken(.normal);
121121 if (maybe_common_resource_attribute.id == .literal and rc.CommonResourceAttributes.map.has(maybe_common_resource_attribute.slice(self.lexer.buffer))) {
......@@ -135,7 +135,7 @@ pub const Parser = struct {
135135 /// current token is unchanged.
136136 /// The returned slice is allocated by the parser's arena
137137 fn parseOptionalStatements(self: *Self, resource: ResourceType) ![]*Node {
138 var optional_statements: std.ArrayListUnmanaged(*Node) = .empty;
138 var optional_statements: std.ArrayList(*Node) = .empty;
139139
140140 const num_statement_types = @typeInfo(rc.OptionalStatements).@"enum".fields.len;
141141 var statement_type_has_duplicates = [_]bool{false} ** num_statement_types;
......@@ -355,8 +355,8 @@ pub const Parser = struct {
355355 const begin_token = self.state.token;
356356 try self.check(.begin);
357357
358 var strings = std.array_list.Managed(*Node).init(self.state.allocator);
359 defer strings.deinit();
358 var strings: std.ArrayList(*Node) = .empty;
359 defer strings.deinit(self.state.allocator);
360360 while (true) {
361361 const maybe_end_token = try self.lookaheadToken(.normal);
362362 switch (maybe_end_token.id) {
......@@ -392,7 +392,7 @@ pub const Parser = struct {
392392 .maybe_comma = comma_token,
393393 .string = self.state.token,
394394 };
395 try strings.append(&string_node.base);
395 try strings.append(self.state.allocator, &string_node.base);
396396 }
397397
398398 if (strings.items.len == 0) {
......@@ -501,7 +501,7 @@ pub const Parser = struct {
501501 const begin_token = self.state.token;
502502 try self.check(.begin);
503503
504 var accelerators: std.ArrayListUnmanaged(*Node) = .empty;
504 var accelerators: std.ArrayList(*Node) = .empty;
505505
506506 while (true) {
507507 const lookahead = try self.lookaheadToken(.normal);
......@@ -519,7 +519,7 @@ pub const Parser = struct {
519519
520520 const idvalue = try self.parseExpression(.{ .allowed_types = .{ .number = true } });
521521
522 var type_and_options: std.ArrayListUnmanaged(Token) = .empty;
522 var type_and_options: std.ArrayList(Token) = .empty;
523523 while (true) {
524524 if (!(try self.parseOptionalToken(.comma))) break;
525525
......@@ -584,7 +584,7 @@ pub const Parser = struct {
584584 const begin_token = self.state.token;
585585 try self.check(.begin);
586586
587 var controls: std.ArrayListUnmanaged(*Node) = .empty;
587 var controls: std.ArrayList(*Node) = .empty;
588588 defer controls.deinit(self.state.allocator);
589589 while (try self.parseControlStatement(resource)) |control_node| {
590590 // The number of controls must fit in a u16 in order for it to
......@@ -643,7 +643,7 @@ pub const Parser = struct {
643643 const begin_token = self.state.token;
644644 try self.check(.begin);
645645
646 var buttons: std.ArrayListUnmanaged(*Node) = .empty;
646 var buttons: std.ArrayList(*Node) = .empty;
647647 defer buttons.deinit(self.state.allocator);
648648 while (try self.parseToolbarButtonStatement()) |button_node| {
649649 // The number of buttons must fit in a u16 in order for it to
......@@ -701,7 +701,7 @@ pub const Parser = struct {
701701 const begin_token = self.state.token;
702702 try self.check(.begin);
703703
704 var items: std.ArrayListUnmanaged(*Node) = .empty;
704 var items: std.ArrayList(*Node) = .empty;
705705 defer items.deinit(self.state.allocator);
706706 while (try self.parseMenuItemStatement(resource, id_token, 1)) |item_node| {
707707 try items.append(self.state.allocator, item_node);
......@@ -735,7 +735,7 @@ pub const Parser = struct {
735735 // common resource attributes must all be contiguous and come before optional-statements
736736 const common_resource_attributes = try self.parseCommonResourceAttributes();
737737
738 var fixed_info: std.ArrayListUnmanaged(*Node) = .empty;
738 var fixed_info: std.ArrayList(*Node) = .empty;
739739 while (try self.parseVersionStatement()) |version_statement| {
740740 try fixed_info.append(self.state.arena, version_statement);
741741 }
......@@ -744,7 +744,7 @@ pub const Parser = struct {
744744 const begin_token = self.state.token;
745745 try self.check(.begin);
746746
747 var block_statements: std.ArrayListUnmanaged(*Node) = .empty;
747 var block_statements: std.ArrayList(*Node) = .empty;
748748 while (try self.parseVersionBlockOrValue(id_token, 1)) |block_node| {
749749 try block_statements.append(self.state.arena, block_node);
750750 }
......@@ -852,8 +852,8 @@ pub const Parser = struct {
852852 /// Expects the current token to be a begin token.
853853 /// After return, the current token will be the end token.
854854 fn parseRawDataBlock(self: *Self) Error![]*Node {
855 var raw_data = std.array_list.Managed(*Node).init(self.state.allocator);
856 defer raw_data.deinit();
855 var raw_data: std.ArrayList(*Node) = .empty;
856 defer raw_data.deinit(self.state.allocator);
857857 while (true) {
858858 const maybe_end_token = try self.lookaheadToken(.normal);
859859 switch (maybe_end_token.id) {
......@@ -888,7 +888,7 @@ pub const Parser = struct {
888888 else => {},
889889 }
890890 const expression = try self.parseExpression(.{ .allowed_types = .{ .number = true, .string = true } });
891 try raw_data.append(expression);
891 try raw_data.append(self.state.allocator, expression);
892892
893893 if (expression.isNumberExpression()) {
894894 const maybe_close_paren = try self.lookaheadToken(.normal);
......@@ -1125,7 +1125,7 @@ pub const Parser = struct {
11251125
11261126 _ = try self.parseOptionalToken(.comma);
11271127
1128 var options: std.ArrayListUnmanaged(Token) = .empty;
1128 var options: std.ArrayList(Token) = .empty;
11291129 while (true) {
11301130 const option_token = try self.lookaheadToken(.normal);
11311131 if (!rc.MenuItem.Option.map.has(option_token.slice(self.lexer.buffer))) {
......@@ -1160,7 +1160,7 @@ pub const Parser = struct {
11601160 }
11611161 try self.skipAnyCommas();
11621162
1163 var options: std.ArrayListUnmanaged(Token) = .empty;
1163 var options: std.ArrayList(Token) = .empty;
11641164 while (true) {
11651165 const option_token = try self.lookaheadToken(.normal);
11661166 if (!rc.MenuItem.Option.map.has(option_token.slice(self.lexer.buffer))) {
......@@ -1175,7 +1175,7 @@ pub const Parser = struct {
11751175 const begin_token = self.state.token;
11761176 try self.check(.begin);
11771177
1178 var items: std.ArrayListUnmanaged(*Node) = .empty;
1178 var items: std.ArrayList(*Node) = .empty;
11791179 while (try self.parseMenuItemStatement(resource, top_level_menu_id_token, nesting_level + 1)) |item_node| {
11801180 try items.append(self.state.arena, item_node);
11811181 }
......@@ -1245,7 +1245,7 @@ pub const Parser = struct {
12451245 const begin_token = self.state.token;
12461246 try self.check(.begin);
12471247
1248 var items: std.ArrayListUnmanaged(*Node) = .empty;
1248 var items: std.ArrayList(*Node) = .empty;
12491249 while (try self.parseMenuItemStatement(resource, top_level_menu_id_token, nesting_level + 1)) |item_node| {
12501250 try items.append(self.state.arena, item_node);
12511251 }
......@@ -1322,7 +1322,7 @@ pub const Parser = struct {
13221322 switch (statement_type) {
13231323 .file_version, .product_version => {
13241324 var parts_buffer: [4]*Node = undefined;
1325 var parts = std.ArrayListUnmanaged(*Node).initBuffer(&parts_buffer);
1325 var parts = std.ArrayList(*Node).initBuffer(&parts_buffer);
13261326
13271327 while (true) {
13281328 const value = try self.parseExpression(.{ .allowed_types = .{ .number = true } });
......@@ -1402,7 +1402,7 @@ pub const Parser = struct {
14021402 const begin_token = self.state.token;
14031403 try self.check(.begin);
14041404
1405 var children: std.ArrayListUnmanaged(*Node) = .empty;
1405 var children: std.ArrayList(*Node) = .empty;
14061406 while (try self.parseVersionBlockOrValue(top_level_version_id_token, nesting_level + 1)) |value_node| {
14071407 try children.append(self.state.arena, value_node);
14081408 }
......@@ -1435,7 +1435,7 @@ pub const Parser = struct {
14351435 }
14361436
14371437 fn parseBlockValuesList(self: *Self, had_comma_before_first_value: bool) Error![]*Node {
1438 var values: std.ArrayListUnmanaged(*Node) = .empty;
1438 var values: std.ArrayList(*Node) = .empty;
14391439 var seen_number: bool = false;
14401440 var first_string_value: ?*Node = null;
14411441 while (true) {
lib/compiler/resinator/preprocess.zig+28-22
......@@ -2,28 +2,32 @@ const std = @import("std");
22const builtin = @import("builtin");
33const Allocator = std.mem.Allocator;
44const cli = @import("cli.zig");
5const Dependencies = @import("compile.zig").Dependencies;
56const aro = @import("aro");
67
78const PreprocessError = error{ ArgError, GeneratedSourceError, PreprocessError, StreamTooLong, OutOfMemory };
89
910pub fn preprocess(
1011 comp: *aro.Compilation,
11 writer: anytype,
12 writer: *std.Io.Writer,
1213 /// Expects argv[0] to be the command name
1314 argv: []const []const u8,
14 maybe_dependencies_list: ?*std.array_list.Managed([]const u8),
15 maybe_dependencies: ?*Dependencies,
1516) PreprocessError!void {
1617 try comp.addDefaultPragmaHandlers();
1718
1819 var driver: aro.Driver = .{ .comp = comp, .aro_name = "arocc" };
1920 defer driver.deinit();
2021
21 var macro_buf = std.array_list.Managed(u8).init(comp.gpa);
22 var macro_buf: std.Io.Writer.Allocating = .init(comp.gpa);
2223 defer macro_buf.deinit();
2324
24 _ = driver.parseArgs(std.io.null_writer, macro_buf.writer(), argv) catch |err| switch (err) {
25 var trash: [64]u8 = undefined;
26 var discarding: std.Io.Writer.Discarding = .init(&trash);
27 _ = driver.parseArgs(&discarding.writer, &macro_buf.writer, argv) catch |err| switch (err) {
2528 error.FatalError => return error.ArgError,
2629 error.OutOfMemory => |e| return e,
30 error.WriteFailed => return error.OutOfMemory,
2731 };
2832
2933 if (hasAnyErrors(comp)) return error.ArgError;
......@@ -33,7 +37,7 @@ pub fn preprocess(
3337 error.FatalError => return error.GeneratedSourceError,
3438 else => |e| return e,
3539 };
36 const user_macros = comp.addSourceFromBuffer("<command line>", macro_buf.items) catch |err| switch (err) {
40 const user_macros = comp.addSourceFromBuffer("<command line>", macro_buf.written()) catch |err| switch (err) {
3741 error.FatalError => return error.GeneratedSourceError,
3842 else => |e| return e,
3943 };
......@@ -59,15 +63,17 @@ pub fn preprocess(
5963
6064 if (hasAnyErrors(comp)) return error.PreprocessError;
6165
62 try pp.prettyPrintTokens(writer, .result_only);
66 pp.prettyPrintTokens(writer, .result_only) catch |err| switch (err) {
67 error.WriteFailed => return error.OutOfMemory,
68 };
6369
64 if (maybe_dependencies_list) |dependencies_list| {
70 if (maybe_dependencies) |dependencies| {
6571 for (comp.sources.values()) |comp_source| {
6672 if (comp_source.id == builtin_macros.id or comp_source.id == user_macros.id) continue;
6773 if (comp_source.id == .unused or comp_source.id == .generated) continue;
68 const duped_path = try dependencies_list.allocator.dupe(u8, comp_source.path);
69 errdefer dependencies_list.allocator.free(duped_path);
70 try dependencies_list.append(duped_path);
74 const duped_path = try dependencies.allocator.dupe(u8, comp_source.path);
75 errdefer dependencies.allocator.free(duped_path);
76 try dependencies.list.append(dependencies.allocator, duped_path);
7177 }
7278 }
7379}
......@@ -87,8 +93,8 @@ fn hasAnyErrors(comp: *aro.Compilation) bool {
8793
8894/// `arena` is used for temporary -D argument strings and the INCLUDE environment variable.
8995/// The arena should be kept alive at least as long as `argv`.
90pub fn appendAroArgs(arena: Allocator, argv: *std.array_list.Managed([]const u8), options: cli.Options, system_include_paths: []const []const u8) !void {
91 try argv.appendSlice(&.{
96pub fn appendAroArgs(arena: Allocator, argv: *std.ArrayList([]const u8), options: cli.Options, system_include_paths: []const []const u8) !void {
97 try argv.appendSlice(arena, &.{
9298 "-E",
9399 "--comments",
94100 "-fuse-line-directives",
......@@ -99,13 +105,13 @@ pub fn appendAroArgs(arena: Allocator, argv: *std.array_list.Managed([]const u8)
99105 "-D_WIN32", // undocumented, but defined by default
100106 });
101107 for (options.extra_include_paths.items) |extra_include_path| {
102 try argv.append("-I");
103 try argv.append(extra_include_path);
108 try argv.append(arena, "-I");
109 try argv.append(arena, extra_include_path);
104110 }
105111
106112 for (system_include_paths) |include_path| {
107 try argv.append("-isystem");
108 try argv.append(include_path);
113 try argv.append(arena, "-isystem");
114 try argv.append(arena, include_path);
109115 }
110116
111117 if (!options.ignore_include_env_var) {
......@@ -119,8 +125,8 @@ pub fn appendAroArgs(arena: Allocator, argv: *std.array_list.Managed([]const u8)
119125 };
120126 var it = std.mem.tokenizeScalar(u8, INCLUDE, delimiter);
121127 while (it.next()) |include_path| {
122 try argv.append("-isystem");
123 try argv.append(include_path);
128 try argv.append(arena, "-isystem");
129 try argv.append(arena, include_path);
124130 }
125131 }
126132
......@@ -128,13 +134,13 @@ pub fn appendAroArgs(arena: Allocator, argv: *std.array_list.Managed([]const u8)
128134 while (symbol_it.next()) |entry| {
129135 switch (entry.value_ptr.*) {
130136 .define => |value| {
131 try argv.append("-D");
137 try argv.append(arena, "-D");
132138 const define_arg = try std.fmt.allocPrint(arena, "{s}={s}", .{ entry.key_ptr.*, value });
133 try argv.append(define_arg);
139 try argv.append(arena, define_arg);
134140 },
135141 .undefine => {
136 try argv.append("-U");
137 try argv.append(entry.key_ptr.*);
142 try argv.append(arena, "-U");
143 try argv.append(arena, entry.key_ptr.*);
138144 },
139145 }
140146 }
lib/compiler/resinator/res.zig+11-11
......@@ -258,7 +258,7 @@ pub const NameOrOrdinal = union(enum) {
258258 }
259259 }
260260
261 pub fn write(self: NameOrOrdinal, writer: anytype) !void {
261 pub fn write(self: NameOrOrdinal, writer: *std.Io.Writer) !void {
262262 switch (self) {
263263 .name => |name| {
264264 try writer.writeAll(std.mem.sliceAsBytes(name[0 .. name.len + 1]));
......@@ -270,7 +270,7 @@ pub const NameOrOrdinal = union(enum) {
270270 }
271271 }
272272
273 pub fn writeEmpty(writer: anytype) !void {
273 pub fn writeEmpty(writer: *std.Io.Writer) !void {
274274 try writer.writeInt(u16, 0, .little);
275275 }
276276
......@@ -283,8 +283,8 @@ pub const NameOrOrdinal = union(enum) {
283283
284284 pub fn nameFromString(allocator: Allocator, bytes: SourceBytes) !NameOrOrdinal {
285285 // Names have a limit of 256 UTF-16 code units + null terminator
286 var buf = try std.array_list.Managed(u16).initCapacity(allocator, @min(257, bytes.slice.len));
287 errdefer buf.deinit();
286 var buf = try std.ArrayList(u16).initCapacity(allocator, @min(257, bytes.slice.len));
287 errdefer buf.deinit(allocator);
288288
289289 var i: usize = 0;
290290 while (bytes.code_page.codepointAt(i, bytes.slice)) |codepoint| : (i += codepoint.byte_len) {
......@@ -292,27 +292,27 @@ pub const NameOrOrdinal = union(enum) {
292292
293293 const c = codepoint.value;
294294 if (c == Codepoint.invalid) {
295 try buf.append(std.mem.nativeToLittle(u16, '�'));
295 try buf.append(allocator, std.mem.nativeToLittle(u16, '�'));
296296 } else if (c < 0x7F) {
297297 // ASCII chars in names are always converted to uppercase
298 try buf.append(std.mem.nativeToLittle(u16, std.ascii.toUpper(@intCast(c))));
298 try buf.append(allocator, std.mem.nativeToLittle(u16, std.ascii.toUpper(@intCast(c))));
299299 } else if (c < 0x10000) {
300300 const short: u16 = @intCast(c);
301 try buf.append(std.mem.nativeToLittle(u16, short));
301 try buf.append(allocator, std.mem.nativeToLittle(u16, short));
302302 } else {
303303 const high = @as(u16, @intCast((c - 0x10000) >> 10)) + 0xD800;
304 try buf.append(std.mem.nativeToLittle(u16, high));
304 try buf.append(allocator, std.mem.nativeToLittle(u16, high));
305305
306306 // Note: This can cut-off in the middle of a UTF-16 surrogate pair,
307307 // i.e. it can make the string end with an unpaired high surrogate
308308 if (buf.items.len == 256) break;
309309
310310 const low = @as(u16, @intCast(c & 0x3FF)) + 0xDC00;
311 try buf.append(std.mem.nativeToLittle(u16, low));
311 try buf.append(allocator, std.mem.nativeToLittle(u16, low));
312312 }
313313 }
314314
315 return NameOrOrdinal{ .name = try buf.toOwnedSliceSentinel(0) };
315 return NameOrOrdinal{ .name = try buf.toOwnedSliceSentinel(allocator, 0) };
316316 }
317317
318318 /// Returns `null` if the bytes do not form a valid number.
......@@ -1079,7 +1079,7 @@ pub const FixedFileInfo = struct {
10791079 }
10801080 };
10811081
1082 pub fn write(self: FixedFileInfo, writer: anytype) !void {
1082 pub fn write(self: FixedFileInfo, writer: *std.Io.Writer) !void {
10831083 try writer.writeInt(u32, signature, .little);
10841084 try writer.writeInt(u32, version, .little);
10851085 try writer.writeInt(u32, self.file_version.mostSignificantCombinedParts(), .little);
lib/compiler/resinator/source_mapping.zig+5-5
......@@ -10,7 +10,7 @@ pub const ParseLineCommandsResult = struct {
1010
1111const CurrentMapping = struct {
1212 line_num: usize = 1,
13 filename: std.ArrayListUnmanaged(u8) = .empty,
13 filename: std.ArrayList(u8) = .empty,
1414 pending: bool = true,
1515 ignore_contents: bool = false,
1616};
......@@ -574,8 +574,8 @@ fn parseFilename(allocator: Allocator, str: []const u8) error{ OutOfMemory, Inva
574574 escape_u,
575575 };
576576
577 var filename = try std.array_list.Managed(u8).initCapacity(allocator, str.len);
578 errdefer filename.deinit();
577 var filename = try std.ArrayList(u8).initCapacity(allocator, str.len);
578 errdefer filename.deinit(allocator);
579579 var state: State = .string;
580580 var index: usize = 0;
581581 var escape_len: usize = undefined;
......@@ -693,7 +693,7 @@ fn parseFilename(allocator: Allocator, str: []const u8) error{ OutOfMemory, Inva
693693 }
694694 }
695695
696 return filename.toOwnedSlice();
696 return filename.toOwnedSlice(allocator);
697697}
698698
699699fn testParseFilename(expected: []const u8, input: []const u8) !void {
......@@ -927,7 +927,7 @@ test "SourceMappings collapse" {
927927
928928/// Same thing as StringTable in Zig's src/Wasm.zig
929929pub const StringTable = struct {
930 data: std.ArrayListUnmanaged(u8) = .empty,
930 data: std.ArrayList(u8) = .empty,
931931 map: std.HashMapUnmanaged(u32, void, std.hash_map.StringIndexContext, std.hash_map.default_max_load_percentage) = .empty,
932932
933933 pub fn deinit(self: *StringTable, allocator: Allocator) void {
lib/compiler/resinator/windows1252.zig-45
......@@ -1,36 +1,5 @@
11const std = @import("std");
22
3pub fn windows1252ToUtf8Stream(writer: anytype, reader: anytype) !usize {
4 var bytes_written: usize = 0;
5 var utf8_buf: [3]u8 = undefined;
6 while (true) {
7 const c = reader.readByte() catch |err| switch (err) {
8 error.EndOfStream => return bytes_written,
9 else => |e| return e,
10 };
11 const codepoint = toCodepoint(c);
12 if (codepoint <= 0x7F) {
13 try writer.writeByte(c);
14 bytes_written += 1;
15 } else {
16 const utf8_len = std.unicode.utf8Encode(codepoint, &utf8_buf) catch unreachable;
17 try writer.writeAll(utf8_buf[0..utf8_len]);
18 bytes_written += utf8_len;
19 }
20 }
21}
22
23/// Returns the number of code units written to the writer
24pub fn windows1252ToUtf16AllocZ(allocator: std.mem.Allocator, win1252_str: []const u8) ![:0]u16 {
25 // Guaranteed to need exactly the same number of code units as Windows-1252 bytes
26 var utf16_slice = try allocator.allocSentinel(u16, win1252_str.len, 0);
27 errdefer allocator.free(utf16_slice);
28 for (win1252_str, 0..) |c, i| {
29 utf16_slice[i] = toCodepoint(c);
30 }
31 return utf16_slice;
32}
33
343/// https://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WindowsBestFit/bestfit1252.txt
354pub fn toCodepoint(c: u8) u16 {
365 return switch (c) {
......@@ -572,17 +541,3 @@ pub fn bestFitFromCodepoint(codepoint: u21) ?u8 {
572541 else => null,
573542 };
574543}
575
576test "windows-1252 to utf8" {
577 var buf = std.array_list.Managed(u8).init(std.testing.allocator);
578 defer buf.deinit();
579
580 const input_windows1252 = "\x81pqrstuvwxyz{|}~\x80\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8e\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9e\x9f\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff";
581 const expected_utf8 = "\xc2\x81pqrstuvwxyz{|}~€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ";
582
583 var fbs = std.io.fixedBufferStream(input_windows1252);
584 const bytes_written = try windows1252ToUtf8Stream(buf.writer(), fbs.reader());
585
586 try std.testing.expectEqualStrings(expected_utf8, buf.items);
587 try std.testing.expectEqual(expected_utf8.len, bytes_written);
588}
lib/docs/wasm/Decl.zig+5-4
......@@ -6,6 +6,7 @@ const gpa = std.heap.wasm_allocator;
66const assert = std.debug.assert;
77const log = std.log;
88const Oom = error{OutOfMemory};
9const ArrayList = std.ArrayList;
910
1011ast_node: Ast.Node.Index,
1112file: Walk.File.Index,
......@@ -189,7 +190,7 @@ pub fn lookup(decl: *const Decl, name: []const u8) ?Decl.Index {
189190}
190191
191192/// Appends the fully qualified name to `out`.
192pub fn fqn(decl: *const Decl, out: *std.ArrayListUnmanaged(u8)) Oom!void {
193pub fn fqn(decl: *const Decl, out: *ArrayList(u8)) Oom!void {
193194 try decl.append_path(out);
194195 if (decl.parent != .none) {
195196 try append_parent_ns(out, decl.parent);
......@@ -199,12 +200,12 @@ pub fn fqn(decl: *const Decl, out: *std.ArrayListUnmanaged(u8)) Oom!void {
199200 }
200201}
201202
202pub fn reset_with_path(decl: *const Decl, list: *std.ArrayListUnmanaged(u8)) Oom!void {
203pub fn reset_with_path(decl: *const Decl, list: *ArrayList(u8)) Oom!void {
203204 list.clearRetainingCapacity();
204205 try append_path(decl, list);
205206}
206207
207pub fn append_path(decl: *const Decl, list: *std.ArrayListUnmanaged(u8)) Oom!void {
208pub fn append_path(decl: *const Decl, list: *ArrayList(u8)) Oom!void {
208209 const start = list.items.len;
209210 // Prefer the module name alias.
210211 for (Walk.modules.keys(), Walk.modules.values()) |pkg_name, pkg_file| {
......@@ -230,7 +231,7 @@ pub fn append_path(decl: *const Decl, list: *std.ArrayListUnmanaged(u8)) Oom!voi
230231 }
231232}
232233
233pub fn append_parent_ns(list: *std.ArrayListUnmanaged(u8), parent: Decl.Index) Oom!void {
234pub fn append_parent_ns(list: *ArrayList(u8), parent: Decl.Index) Oom!void {
234235 assert(parent != .none);
235236 const decl = parent.get();
236237 if (decl.parent != .none) {
lib/docs/wasm/html_render.zig+10-8
......@@ -1,6 +1,8 @@
11const std = @import("std");
22const Ast = std.zig.Ast;
33const assert = std.debug.assert;
4const ArrayList = std.ArrayList;
5const Writer = std.Io.Writer;
46
57const Walk = @import("Walk");
68const Decl = Walk.Decl;
......@@ -30,7 +32,7 @@ pub const Annotation = struct {
3032
3133pub fn fileSourceHtml(
3234 file_index: Walk.File.Index,
33 out: *std.ArrayListUnmanaged(u8),
35 out: *ArrayList(u8),
3436 root_node: Ast.Node.Index,
3537 options: RenderSourceOptions,
3638) !void {
......@@ -38,7 +40,7 @@ pub fn fileSourceHtml(
3840 const file = file_index.get();
3941
4042 const g = struct {
41 var field_access_buffer: std.ArrayListUnmanaged(u8) = .empty;
43 var field_access_buffer: ArrayList(u8) = .empty;
4244 };
4345
4446 const start_token = ast.firstToken(root_node);
......@@ -88,7 +90,7 @@ pub fn fileSourceHtml(
8890 if (next_annotate_index >= options.source_location_annotations.len) break;
8991 const next_annotation = options.source_location_annotations[next_annotate_index];
9092 if (cursor <= next_annotation.file_byte_offset) break;
91 try out.writer(gpa).print("<span id=\"{s}{d}\"></span>", .{
93 try out.print(gpa, "<span id=\"{s}{d}\"></span>", .{
9294 options.annotation_prefix, next_annotation.dom_id,
9395 });
9496 next_annotate_index += 1;
......@@ -318,7 +320,7 @@ pub fn fileSourceHtml(
318320 }
319321}
320322
321fn appendUnindented(out: *std.ArrayListUnmanaged(u8), s: []const u8, indent: usize) !void {
323fn appendUnindented(out: *ArrayList(u8), s: []const u8, indent: usize) !void {
322324 var it = std.mem.splitScalar(u8, s, '\n');
323325 var is_first_line = true;
324326 while (it.next()) |line| {
......@@ -332,7 +334,7 @@ fn appendUnindented(out: *std.ArrayListUnmanaged(u8), s: []const u8, indent: usi
332334 }
333335}
334336
335pub fn appendEscaped(out: *std.ArrayListUnmanaged(u8), s: []const u8) !void {
337pub fn appendEscaped(out: *ArrayList(u8), s: []const u8) !void {
336338 for (s) |c| {
337339 try out.ensureUnusedCapacity(gpa, 6);
338340 switch (c) {
......@@ -347,7 +349,7 @@ pub fn appendEscaped(out: *std.ArrayListUnmanaged(u8), s: []const u8) !void {
347349
348350fn walkFieldAccesses(
349351 file_index: Walk.File.Index,
350 out: *std.ArrayListUnmanaged(u8),
352 out: *ArrayList(u8),
351353 node: Ast.Node.Index,
352354) Oom!void {
353355 const ast = file_index.get_ast();
......@@ -371,7 +373,7 @@ fn walkFieldAccesses(
371373
372374fn resolveIdentLink(
373375 file_index: Walk.File.Index,
374 out: *std.ArrayListUnmanaged(u8),
376 out: *ArrayList(u8),
375377 ident_token: Ast.TokenIndex,
376378) Oom!void {
377379 const decl_index = file_index.get().lookup_token(ident_token);
......@@ -391,7 +393,7 @@ fn unindent(s: []const u8, indent: usize) []const u8 {
391393 return s[indent_idx..];
392394}
393395
394pub fn resolveDeclLink(decl_index: Decl.Index, out: *std.ArrayListUnmanaged(u8)) Oom!void {
396pub fn resolveDeclLink(decl_index: Decl.Index, out: *ArrayList(u8)) Oom!void {
395397 const decl = decl_index.get();
396398 switch (decl.categorize()) {
397399 .alias => |alias_decl| try alias_decl.get().fqn(out),
lib/docs/wasm/main.zig+30-24
......@@ -5,6 +5,8 @@ const Ast = std.zig.Ast;
55const Walk = @import("Walk");
66const markdown = @import("markdown.zig");
77const Decl = Walk.Decl;
8const ArrayList = std.ArrayList;
9const Writer = std.Io.Writer;
810
911const fileSourceHtml = @import("html_render.zig").fileSourceHtml;
1012const appendEscaped = @import("html_render.zig").appendEscaped;
......@@ -66,8 +68,8 @@ export fn unpack(tar_ptr: [*]u8, tar_len: usize) void {
6668 };
6769}
6870
69var query_string: std.ArrayListUnmanaged(u8) = .empty;
70var query_results: std.ArrayListUnmanaged(Decl.Index) = .empty;
71var query_string: ArrayList(u8) = .empty;
72var query_results: ArrayList(Decl.Index) = .empty;
7173
7274/// Resizes the query string to be the correct length; returns the pointer to
7375/// the query string.
......@@ -99,11 +101,11 @@ fn query_exec_fallible(query: []const u8, ignore_case: bool) !void {
99101 segments: u16,
100102 };
101103 const g = struct {
102 var full_path_search_text: std.ArrayListUnmanaged(u8) = .empty;
103 var full_path_search_text_lower: std.ArrayListUnmanaged(u8) = .empty;
104 var doc_search_text: std.ArrayListUnmanaged(u8) = .empty;
104 var full_path_search_text: ArrayList(u8) = .empty;
105 var full_path_search_text_lower: ArrayList(u8) = .empty;
106 var doc_search_text: ArrayList(u8) = .empty;
105107 /// Each element matches a corresponding query_results element.
106 var scores: std.ArrayListUnmanaged(Score) = .empty;
108 var scores: ArrayList(Score) = .empty;
107109 };
108110
109111 // First element stores the size of the list.
......@@ -234,7 +236,7 @@ const ErrorIdentifier = packed struct(u64) {
234236 return ast.tokenTag(token_index - 1) == .doc_comment;
235237 }
236238
237 fn html(ei: ErrorIdentifier, base_decl: Decl.Index, out: *std.ArrayListUnmanaged(u8)) Oom!void {
239 fn html(ei: ErrorIdentifier, base_decl: Decl.Index, out: *ArrayList(u8)) Oom!void {
238240 const decl_index = ei.decl_index;
239241 const ast = decl_index.get().file.get_ast();
240242 const name = ast.tokenSlice(ei.token_index);
......@@ -260,7 +262,7 @@ const ErrorIdentifier = packed struct(u64) {
260262 }
261263};
262264
263var string_result: std.ArrayListUnmanaged(u8) = .empty;
265var string_result: ArrayList(u8) = .empty;
264266var error_set_result: std.StringArrayHashMapUnmanaged(ErrorIdentifier) = .empty;
265267
266268export fn decl_error_set(decl_index: Decl.Index) Slice(ErrorIdentifier) {
......@@ -411,7 +413,7 @@ fn decl_fields_fallible(decl_index: Decl.Index) ![]Ast.Node.Index {
411413
412414fn ast_decl_fields_fallible(ast: *Ast, ast_index: Ast.Node.Index) ![]Ast.Node.Index {
413415 const g = struct {
414 var result: std.ArrayListUnmanaged(Ast.Node.Index) = .empty;
416 var result: ArrayList(Ast.Node.Index) = .empty;
415417 };
416418 g.result.clearRetainingCapacity();
417419 var buf: [2]Ast.Node.Index = undefined;
......@@ -429,7 +431,7 @@ fn ast_decl_fields_fallible(ast: *Ast, ast_index: Ast.Node.Index) ![]Ast.Node.In
429431
430432fn decl_params_fallible(decl_index: Decl.Index) ![]Ast.Node.Index {
431433 const g = struct {
432 var result: std.ArrayListUnmanaged(Ast.Node.Index) = .empty;
434 var result: ArrayList(Ast.Node.Index) = .empty;
433435 };
434436 g.result.clearRetainingCapacity();
435437 const decl = decl_index.get();
......@@ -460,7 +462,7 @@ export fn decl_param_html(decl_index: Decl.Index, param_node: Ast.Node.Index) St
460462}
461463
462464fn decl_field_html_fallible(
463 out: *std.ArrayListUnmanaged(u8),
465 out: *ArrayList(u8),
464466 decl_index: Decl.Index,
465467 field_node: Ast.Node.Index,
466468) !void {
......@@ -480,7 +482,7 @@ fn decl_field_html_fallible(
480482}
481483
482484fn decl_param_html_fallible(
483 out: *std.ArrayListUnmanaged(u8),
485 out: *ArrayList(u8),
484486 decl_index: Decl.Index,
485487 param_node: Ast.Node.Index,
486488) !void {
......@@ -649,7 +651,7 @@ export fn decl_docs_html(decl_index: Decl.Index, short: bool) String {
649651}
650652
651653fn collect_docs(
652 list: *std.ArrayListUnmanaged(u8),
654 list: *ArrayList(u8),
653655 ast: *const Ast,
654656 first_doc_comment: Ast.TokenIndex,
655657) Oom!void {
......@@ -667,7 +669,7 @@ fn collect_docs(
667669}
668670
669671fn render_docs(
670 out: *std.ArrayListUnmanaged(u8),
672 out: *ArrayList(u8),
671673 decl_index: Decl.Index,
672674 first_doc_comment: Ast.TokenIndex,
673675 short: bool,
......@@ -691,11 +693,10 @@ fn render_docs(
691693 defer parsed_doc.deinit(gpa);
692694
693695 const g = struct {
694 var link_buffer: std.ArrayListUnmanaged(u8) = .empty;
696 var link_buffer: ArrayList(u8) = .empty;
695697 };
696698
697 const Writer = std.ArrayListUnmanaged(u8).Writer;
698 const Renderer = markdown.Renderer(Writer, Decl.Index);
699 const Renderer = markdown.Renderer(Decl.Index);
699700 const renderer: Renderer = .{
700701 .context = decl_index,
701702 .renderFn = struct {
......@@ -703,8 +704,8 @@ fn render_docs(
703704 r: Renderer,
704705 doc: markdown.Document,
705706 node: markdown.Document.Node.Index,
706 writer: Writer,
707 ) !void {
707 writer: *Writer,
708 ) Writer.Error!void {
708709 const data = doc.nodes.items(.data)[@intFromEnum(node)];
709710 switch (doc.nodes.items(.tag)[@intFromEnum(node)]) {
710711 .code_span => {
......@@ -712,7 +713,7 @@ fn render_docs(
712713 const content = doc.string(data.text.content);
713714 if (resolve_decl_path(r.context, content)) |resolved_decl_index| {
714715 g.link_buffer.clearRetainingCapacity();
715 try resolveDeclLink(resolved_decl_index, &g.link_buffer);
716 resolveDeclLink(resolved_decl_index, &g.link_buffer) catch return error.WriteFailed;
716717
717718 try writer.writeAll("<a href=\"#");
718719 _ = missing_feature_url_escape;
......@@ -730,7 +731,12 @@ fn render_docs(
730731 }
731732 }.render,
732733 };
733 try renderer.render(parsed_doc, out.writer(gpa));
734
735 var allocating = Writer.Allocating.fromArrayList(gpa, out);
736 defer out.* = allocating.toArrayList();
737 renderer.render(parsed_doc, &allocating.writer) catch |err| switch (err) {
738 error.WriteFailed => return error.OutOfMemory,
739 };
734740}
735741
736742fn resolve_decl_path(decl_index: Decl.Index, path: []const u8) ?Decl.Index {
......@@ -827,7 +833,7 @@ export fn find_module_root(pkg: Walk.ModuleIndex) Decl.Index {
827833}
828834
829835/// Set by `set_input_string`.
830var input_string: std.ArrayListUnmanaged(u8) = .empty;
836var input_string: ArrayList(u8) = .empty;
831837
832838export fn set_input_string(len: usize) [*]u8 {
833839 input_string.resize(gpa, len) catch @panic("OOM");
......@@ -849,7 +855,7 @@ export fn find_decl() Decl.Index {
849855 if (result != .none) return result;
850856
851857 const g = struct {
852 var match_fqn: std.ArrayListUnmanaged(u8) = .empty;
858 var match_fqn: ArrayList(u8) = .empty;
853859 };
854860 for (Walk.decls.items, 0..) |*decl, decl_index| {
855861 g.match_fqn.clearRetainingCapacity();
......@@ -905,7 +911,7 @@ export fn type_fn_members(parent: Decl.Index, include_private: bool) Slice(Decl.
905911
906912export fn namespace_members(parent: Decl.Index, include_private: bool) Slice(Decl.Index) {
907913 const g = struct {
908 var members: std.ArrayListUnmanaged(Decl.Index) = .empty;
914 var members: ArrayList(Decl.Index) = .empty;
909915 };
910916
911917 g.members.clearRetainingCapacity();
lib/docs/wasm/markdown/renderer.zig+15-16
......@@ -2,25 +2,26 @@ const std = @import("std");
22const Document = @import("Document.zig");
33const Node = Document.Node;
44const assert = std.debug.assert;
5const Writer = std.Io.Writer;
56
67/// A Markdown document renderer.
78///
89/// Each concrete `Renderer` type has a `renderDefault` function, with the
910/// intention that custom `renderFn` implementations can call `renderDefault`
1011/// for node types for which they require no special rendering.
11pub fn Renderer(comptime Writer: type, comptime Context: type) type {
12pub fn Renderer(comptime Context: type) type {
1213 return struct {
1314 renderFn: *const fn (
1415 r: Self,
1516 doc: Document,
1617 node: Node.Index,
17 writer: Writer,
18 writer: *Writer,
1819 ) Writer.Error!void = renderDefault,
1920 context: Context,
2021
2122 const Self = @This();
2223
23 pub fn render(r: Self, doc: Document, writer: Writer) Writer.Error!void {
24 pub fn render(r: Self, doc: Document, writer: *Writer) Writer.Error!void {
2425 try r.renderFn(r, doc, .root, writer);
2526 }
2627
......@@ -28,7 +29,7 @@ pub fn Renderer(comptime Writer: type, comptime Context: type) type {
2829 r: Self,
2930 doc: Document,
3031 node: Node.Index,
31 writer: Writer,
32 writer: *Writer,
3233 ) Writer.Error!void {
3334 const data = doc.nodes.items(.data)[@intFromEnum(node)];
3435 switch (doc.nodes.items(.tag)[@intFromEnum(node)]) {
......@@ -188,8 +189,8 @@ pub fn Renderer(comptime Writer: type, comptime Context: type) type {
188189pub fn renderInlineNodeText(
189190 doc: Document,
190191 node: Node.Index,
191 writer: anytype,
192) @TypeOf(writer).Error!void {
192 writer: *Writer,
193) Writer.Error!void {
193194 const data = doc.nodes.items(.data)[@intFromEnum(node)];
194195 switch (doc.nodes.items(.tag)[@intFromEnum(node)]) {
195196 .root,
......@@ -234,14 +235,12 @@ pub fn fmtHtml(bytes: []const u8) std.fmt.Formatter([]const u8, formatHtml) {
234235 return .{ .data = bytes };
235236}
236237
237fn formatHtml(bytes: []const u8, writer: *std.io.Writer) std.io.Writer.Error!void {
238 for (bytes) |b| {
239 switch (b) {
240 '<' => try writer.writeAll("&lt;"),
241 '>' => try writer.writeAll("&gt;"),
242 '&' => try writer.writeAll("&amp;"),
243 '"' => try writer.writeAll("&quot;"),
244 else => try writer.writeByte(b),
245 }
246 }
238fn formatHtml(bytes: []const u8, w: *Writer) Writer.Error!void {
239 for (bytes) |b| switch (b) {
240 '<' => try w.writeAll("&lt;"),
241 '>' => try w.writeAll("&gt;"),
242 '&' => try w.writeAll("&amp;"),
243 '"' => try w.writeAll("&quot;"),
244 else => try w.writeByte(b),
245 };
247246}
lib/std/Build/Step/CheckObject.zig+25-27
......@@ -257,7 +257,7 @@ const Check = struct {
257257 fn dumpSection(allocator: Allocator, name: [:0]const u8) Check {
258258 var check = Check.create(allocator, .dump_section);
259259 const off: u32 = @intCast(check.data.items.len);
260 check.data.writer().print("{s}\x00", .{name}) catch @panic("OOM");
260 check.data.print("{s}\x00", .{name}) catch @panic("OOM");
261261 check.payload = .{ .dump_section = off };
262262 return check;
263263 }
......@@ -1320,7 +1320,8 @@ const MachODumper = struct {
13201320 }
13211321 bindings.deinit();
13221322 }
1323 try ctx.parseBindInfo(data, &bindings);
1323 var data_reader: std.Io.Reader = .fixed(data);
1324 try ctx.parseBindInfo(&data_reader, &bindings);
13241325 mem.sort(Binding, bindings.items, {}, Binding.lessThan);
13251326 for (bindings.items) |binding| {
13261327 try writer.print("0x{x} [addend: {d}]", .{ binding.address, binding.addend });
......@@ -1335,11 +1336,7 @@ const MachODumper = struct {
13351336 }
13361337 }
13371338
1338 fn parseBindInfo(ctx: ObjectContext, data: []const u8, bindings: *std.array_list.Managed(Binding)) !void {
1339 var stream = std.io.fixedBufferStream(data);
1340 var creader = std.io.countingReader(stream.reader());
1341 const reader = creader.reader();
1342
1339 fn parseBindInfo(ctx: ObjectContext, reader: *std.Io.Reader, bindings: *std.array_list.Managed(Binding)) !void {
13431340 var seg_id: ?u8 = null;
13441341 var tag: Binding.Tag = .self;
13451342 var ordinal: u16 = 0;
......@@ -1350,7 +1347,7 @@ const MachODumper = struct {
13501347 defer name_buf.deinit();
13511348
13521349 while (true) {
1353 const byte = reader.readByte() catch break;
1350 const byte = reader.takeByte() catch break;
13541351 const opc = byte & macho.BIND_OPCODE_MASK;
13551352 const imm = byte & macho.BIND_IMMEDIATE_MASK;
13561353 switch (opc) {
......@@ -1371,18 +1368,17 @@ const MachODumper = struct {
13711368 },
13721369 macho.BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB => {
13731370 seg_id = imm;
1374 offset = try std.leb.readUleb128(u64, reader);
1371 offset = try reader.takeLeb128(u64);
13751372 },
13761373 macho.BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM => {
13771374 name_buf.clearRetainingCapacity();
1378 try reader.readUntilDelimiterArrayList(&name_buf, 0, std.math.maxInt(u32));
1379 try name_buf.append(0);
1375 try name_buf.appendSlice(try reader.takeDelimiterInclusive(0));
13801376 },
13811377 macho.BIND_OPCODE_SET_ADDEND_SLEB => {
1382 addend = try std.leb.readIleb128(i64, reader);
1378 addend = try reader.takeLeb128(i64);
13831379 },
13841380 macho.BIND_OPCODE_ADD_ADDR_ULEB => {
1385 const x = try std.leb.readUleb128(u64, reader);
1381 const x = try reader.takeLeb128(u64);
13861382 offset = @intCast(@as(i64, @intCast(offset)) + @as(i64, @bitCast(x)));
13871383 },
13881384 macho.BIND_OPCODE_DO_BIND,
......@@ -1397,14 +1393,14 @@ const MachODumper = struct {
13971393 switch (opc) {
13981394 macho.BIND_OPCODE_DO_BIND => {},
13991395 macho.BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB => {
1400 add_addr = try std.leb.readUleb128(u64, reader);
1396 add_addr = try reader.takeLeb128(u64);
14011397 },
14021398 macho.BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED => {
14031399 add_addr = imm * @sizeOf(u64);
14041400 },
14051401 macho.BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB => {
1406 count = try std.leb.readUleb128(u64, reader);
1407 skip = try std.leb.readUleb128(u64, reader);
1402 count = try reader.takeLeb128(u64);
1403 skip = try reader.takeLeb128(u64);
14081404 },
14091405 else => unreachable,
14101406 }
......@@ -1621,8 +1617,9 @@ const MachODumper = struct {
16211617 var ctx = ObjectContext{ .gpa = gpa, .data = bytes, .header = hdr };
16221618 try ctx.parse();
16231619
1624 var output = std.array_list.Managed(u8).init(gpa);
1625 const writer = output.writer();
1620 var output: std.Io.Writer.Allocating = .init(gpa);
1621 defer output.deinit();
1622 const writer = &output.writer;
16261623
16271624 switch (check.kind) {
16281625 .headers => {
......@@ -1787,8 +1784,9 @@ const ElfDumper = struct {
17871784 try ctx.objects.append(gpa, .{ .name = name, .off = stream.pos, .len = size });
17881785 }
17891786
1790 var output = std.array_list.Managed(u8).init(gpa);
1791 const writer = output.writer();
1787 var output: std.Io.Writer.Allocating = .init(gpa);
1788 defer output.deinit();
1789 const writer = &output.writer;
17921790
17931791 switch (check.kind) {
17941792 .archive_symtab => if (ctx.symtab.items.len > 0) {
......@@ -1944,8 +1942,9 @@ const ElfDumper = struct {
19441942 else => {},
19451943 };
19461944
1947 var output = std.array_list.Managed(u8).init(gpa);
1948 const writer = output.writer();
1945 var output: std.Io.Writer.Allocating = .init(gpa);
1946 defer output.deinit();
1947 const writer = &output.writer;
19491948
19501949 switch (check.kind) {
19511950 .headers => {
......@@ -2398,10 +2397,10 @@ const WasmDumper = struct {
23982397 return error.UnsupportedWasmVersion;
23992398 }
24002399
2401 var output = std.array_list.Managed(u8).init(gpa);
2400 var output: std.Io.Writer.Allocating = .init(gpa);
24022401 defer output.deinit();
2403 parseAndDumpInner(step, check, bytes, &fbs, &output) catch |err| switch (err) {
2404 error.EndOfStream => try output.appendSlice("\n<UnexpectedEndOfStream>"),
2402 parseAndDumpInner(step, check, bytes, &fbs, &output.writer) catch |err| switch (err) {
2403 error.EndOfStream => try output.writer.writeAll("\n<UnexpectedEndOfStream>"),
24052404 else => |e| return e,
24062405 };
24072406 return output.toOwnedSlice();
......@@ -2412,10 +2411,9 @@ const WasmDumper = struct {
24122411 check: Check,
24132412 bytes: []const u8,
24142413 fbs: *std.io.FixedBufferStream([]const u8),
2415 output: *std.array_list.Managed(u8),
2414 writer: *std.Io.Writer,
24162415 ) !void {
24172416 const reader = fbs.reader();
2418 const writer = output.writer();
24192417
24202418 switch (check.kind) {
24212419 .headers => {
lib/std/Io.zig-163
......@@ -144,61 +144,6 @@ pub fn GenericReader(
144144 return @errorCast(self.any().readAllAlloc(allocator, max_size));
145145 }
146146
147 pub inline fn readUntilDelimiterArrayList(
148 self: Self,
149 array_list: *std.array_list.Managed(u8),
150 delimiter: u8,
151 max_size: usize,
152 ) (NoEofError || Allocator.Error || error{StreamTooLong})!void {
153 return @errorCast(self.any().readUntilDelimiterArrayList(
154 array_list,
155 delimiter,
156 max_size,
157 ));
158 }
159
160 pub inline fn readUntilDelimiterAlloc(
161 self: Self,
162 allocator: Allocator,
163 delimiter: u8,
164 max_size: usize,
165 ) (NoEofError || Allocator.Error || error{StreamTooLong})![]u8 {
166 return @errorCast(self.any().readUntilDelimiterAlloc(
167 allocator,
168 delimiter,
169 max_size,
170 ));
171 }
172
173 pub inline fn readUntilDelimiter(
174 self: Self,
175 buf: []u8,
176 delimiter: u8,
177 ) (NoEofError || error{StreamTooLong})![]u8 {
178 return @errorCast(self.any().readUntilDelimiter(buf, delimiter));
179 }
180
181 pub inline fn readUntilDelimiterOrEofAlloc(
182 self: Self,
183 allocator: Allocator,
184 delimiter: u8,
185 max_size: usize,
186 ) (Error || Allocator.Error || error{StreamTooLong})!?[]u8 {
187 return @errorCast(self.any().readUntilDelimiterOrEofAlloc(
188 allocator,
189 delimiter,
190 max_size,
191 ));
192 }
193
194 pub inline fn readUntilDelimiterOrEof(
195 self: Self,
196 buf: []u8,
197 delimiter: u8,
198 ) (Error || error{StreamTooLong})!?[]u8 {
199 return @errorCast(self.any().readUntilDelimiterOrEof(buf, delimiter));
200 }
201
202147 pub inline fn streamUntilDelimiter(
203148 self: Self,
204149 writer: anytype,
......@@ -326,103 +271,8 @@ pub fn GenericReader(
326271 };
327272}
328273
329/// Deprecated in favor of `Writer`.
330pub fn GenericWriter(
331 comptime Context: type,
332 comptime WriteError: type,
333 comptime writeFn: fn (context: Context, bytes: []const u8) WriteError!usize,
334) type {
335 return struct {
336 context: Context,
337
338 const Self = @This();
339 pub const Error = WriteError;
340
341 pub inline fn write(self: Self, bytes: []const u8) Error!usize {
342 return writeFn(self.context, bytes);
343 }
344
345 pub inline fn writeAll(self: Self, bytes: []const u8) Error!void {
346 return @errorCast(self.any().writeAll(bytes));
347 }
348
349 pub inline fn print(self: Self, comptime format: []const u8, args: anytype) Error!void {
350 return @errorCast(self.any().print(format, args));
351 }
352
353 pub inline fn writeByte(self: Self, byte: u8) Error!void {
354 return @errorCast(self.any().writeByte(byte));
355 }
356
357 pub inline fn writeByteNTimes(self: Self, byte: u8, n: usize) Error!void {
358 return @errorCast(self.any().writeByteNTimes(byte, n));
359 }
360
361 pub inline fn writeBytesNTimes(self: Self, bytes: []const u8, n: usize) Error!void {
362 return @errorCast(self.any().writeBytesNTimes(bytes, n));
363 }
364
365 pub inline fn writeInt(self: Self, comptime T: type, value: T, endian: std.builtin.Endian) Error!void {
366 return @errorCast(self.any().writeInt(T, value, endian));
367 }
368
369 pub inline fn writeStruct(self: Self, value: anytype) Error!void {
370 return @errorCast(self.any().writeStruct(value));
371 }
372
373 pub inline fn writeStructEndian(self: Self, value: anytype, endian: std.builtin.Endian) Error!void {
374 return @errorCast(self.any().writeStructEndian(value, endian));
375 }
376
377 pub inline fn any(self: *const Self) AnyWriter {
378 return .{
379 .context = @ptrCast(&self.context),
380 .writeFn = typeErasedWriteFn,
381 };
382 }
383
384 fn typeErasedWriteFn(context: *const anyopaque, bytes: []const u8) anyerror!usize {
385 const ptr: *const Context = @ptrCast(@alignCast(context));
386 return writeFn(ptr.*, bytes);
387 }
388
389 /// Helper for bridging to the new `Writer` API while upgrading.
390 pub fn adaptToNewApi(self: *const Self, buffer: []u8) Adapter {
391 return .{
392 .derp_writer = self.*,
393 .new_interface = .{
394 .buffer = buffer,
395 .vtable = &.{ .drain = Adapter.drain },
396 },
397 };
398 }
399
400 pub const Adapter = struct {
401 derp_writer: Self,
402 new_interface: Writer,
403 err: ?Error = null,
404
405 fn drain(w: *std.io.Writer, data: []const []const u8, splat: usize) std.io.Writer.Error!usize {
406 _ = splat;
407 const a: *@This() = @alignCast(@fieldParentPtr("new_interface", w));
408 const buffered = w.buffered();
409 if (buffered.len != 0) return w.consume(a.derp_writer.write(buffered) catch |err| {
410 a.err = err;
411 return error.WriteFailed;
412 });
413 return a.derp_writer.write(data[0]) catch |err| {
414 a.err = err;
415 return error.WriteFailed;
416 };
417 }
418 };
419 };
420}
421
422274/// Deprecated in favor of `Reader`.
423275pub const AnyReader = @import("Io/DeprecatedReader.zig");
424/// Deprecated in favor of `Writer`.
425pub const AnyWriter = @import("Io/DeprecatedWriter.zig");
426276/// Deprecated in favor of `Reader`.
427277pub const FixedBufferStream = @import("Io/fixed_buffer_stream.zig").FixedBufferStream;
428278/// Deprecated in favor of `Reader`.
......@@ -434,19 +284,6 @@ pub const countingReader = @import("Io/counting_reader.zig").countingReader;
434284
435285pub const tty = @import("Io/tty.zig");
436286
437/// Deprecated in favor of `Writer.Discarding`.
438pub const null_writer: NullWriter = .{ .context = {} };
439/// Deprecated in favor of `Writer.Discarding`.
440pub const NullWriter = GenericWriter(void, error{}, dummyWrite);
441fn dummyWrite(context: void, data: []const u8) error{}!usize {
442 _ = context;
443 return data.len;
444}
445
446test null_writer {
447 null_writer.writeAll("yay" ** 10) catch |err| switch (err) {};
448}
449
450287pub fn poll(
451288 gpa: Allocator,
452289 comptime StreamEnum: type,
lib/std/Io/DeprecatedReader.zig-98
......@@ -93,100 +93,6 @@ pub fn readAllAlloc(self: Self, allocator: mem.Allocator, max_size: usize) anyer
9393 return try array_list.toOwnedSlice();
9494}
9595
96/// Deprecated: use `streamUntilDelimiter` with ArrayList's writer instead.
97/// Replaces the `std.array_list.Managed` contents by reading from the stream until `delimiter` is found.
98/// Does not include the delimiter in the result.
99/// If the `std.array_list.Managed` length would exceed `max_size`, `error.StreamTooLong` is returned and the
100/// `std.array_list.Managed` is populated with `max_size` bytes from the stream.
101pub fn readUntilDelimiterArrayList(
102 self: Self,
103 array_list: *std.array_list.Managed(u8),
104 delimiter: u8,
105 max_size: usize,
106) anyerror!void {
107 array_list.shrinkRetainingCapacity(0);
108 try self.streamUntilDelimiter(array_list.writer(), delimiter, max_size);
109}
110
111/// Deprecated: use `streamUntilDelimiter` with ArrayList's writer instead.
112/// Allocates enough memory to read until `delimiter`. If the allocated
113/// memory would be greater than `max_size`, returns `error.StreamTooLong`.
114/// Caller owns returned memory.
115/// If this function returns an error, the contents from the stream read so far are lost.
116pub fn readUntilDelimiterAlloc(
117 self: Self,
118 allocator: mem.Allocator,
119 delimiter: u8,
120 max_size: usize,
121) anyerror![]u8 {
122 var array_list = std.array_list.Managed(u8).init(allocator);
123 defer array_list.deinit();
124 try self.streamUntilDelimiter(array_list.writer(), delimiter, max_size);
125 return try array_list.toOwnedSlice();
126}
127
128/// Deprecated: use `streamUntilDelimiter` with FixedBufferStream's writer instead.
129/// Reads from the stream until specified byte is found. If the buffer is not
130/// large enough to hold the entire contents, `error.StreamTooLong` is returned.
131/// If end-of-stream is found, `error.EndOfStream` is returned.
132/// Returns a slice of the stream data, with ptr equal to `buf.ptr`. The
133/// delimiter byte is written to the output buffer but is not included
134/// in the returned slice.
135pub fn readUntilDelimiter(self: Self, buf: []u8, delimiter: u8) anyerror![]u8 {
136 var fbs = std.io.fixedBufferStream(buf);
137 try self.streamUntilDelimiter(fbs.writer(), delimiter, fbs.buffer.len);
138 const output = fbs.getWritten();
139 buf[output.len] = delimiter; // emulating old behaviour
140 return output;
141}
142
143/// Deprecated: use `streamUntilDelimiter` with ArrayList's (or any other's) writer instead.
144/// Allocates enough memory to read until `delimiter` or end-of-stream.
145/// If the allocated memory would be greater than `max_size`, returns
146/// `error.StreamTooLong`. If end-of-stream is found, returns the rest
147/// of the stream. If this function is called again after that, returns
148/// null.
149/// Caller owns returned memory.
150/// If this function returns an error, the contents from the stream read so far are lost.
151pub fn readUntilDelimiterOrEofAlloc(
152 self: Self,
153 allocator: mem.Allocator,
154 delimiter: u8,
155 max_size: usize,
156) anyerror!?[]u8 {
157 var array_list = std.array_list.Managed(u8).init(allocator);
158 defer array_list.deinit();
159 self.streamUntilDelimiter(array_list.writer(), delimiter, max_size) catch |err| switch (err) {
160 error.EndOfStream => if (array_list.items.len == 0) {
161 return null;
162 },
163 else => |e| return e,
164 };
165 return try array_list.toOwnedSlice();
166}
167
168/// Deprecated: use `streamUntilDelimiter` with FixedBufferStream's writer instead.
169/// Reads from the stream until specified byte is found. If the buffer is not
170/// large enough to hold the entire contents, `error.StreamTooLong` is returned.
171/// If end-of-stream is found, returns the rest of the stream. If this
172/// function is called again after that, returns null.
173/// Returns a slice of the stream data, with ptr equal to `buf.ptr`. The
174/// delimiter byte is written to the output buffer but is not included
175/// in the returned slice.
176pub fn readUntilDelimiterOrEof(self: Self, buf: []u8, delimiter: u8) anyerror!?[]u8 {
177 var fbs = std.io.fixedBufferStream(buf);
178 self.streamUntilDelimiter(fbs.writer(), delimiter, fbs.buffer.len) catch |err| switch (err) {
179 error.EndOfStream => if (fbs.getWritten().len == 0) {
180 return null;
181 },
182
183 else => |e| return e,
184 };
185 const output = fbs.getWritten();
186 buf[output.len] = delimiter; // emulating old behaviour
187 return output;
188}
189
19096/// Appends to the `writer` contents by reading from the stream until `delimiter` is found.
19197/// Does not write the delimiter itself.
19298/// If `optional_max_size` is not null and amount of written bytes exceeds `optional_max_size`,
......@@ -384,7 +290,3 @@ const mem = std.mem;
384290const testing = std.testing;
385291const native_endian = @import("builtin").target.cpu.arch.endian();
386292const Alignment = std.mem.Alignment;
387
388test {
389 _ = @import("Reader/test.zig");
390}
lib/std/Io/DeprecatedWriter.zig deleted-114
......@@ -1,114 +0,0 @@
1const std = @import("../std.zig");
2const assert = std.debug.assert;
3const mem = std.mem;
4const native_endian = @import("builtin").target.cpu.arch.endian();
5
6context: *const anyopaque,
7writeFn: *const fn (context: *const anyopaque, bytes: []const u8) anyerror!usize,
8
9const Self = @This();
10pub const Error = anyerror;
11
12pub fn write(self: Self, bytes: []const u8) anyerror!usize {
13 return self.writeFn(self.context, bytes);
14}
15
16pub fn writeAll(self: Self, bytes: []const u8) anyerror!void {
17 var index: usize = 0;
18 while (index != bytes.len) {
19 index += try self.write(bytes[index..]);
20 }
21}
22
23pub fn print(self: Self, comptime format: []const u8, args: anytype) anyerror!void {
24 return std.fmt.format(self, format, args);
25}
26
27pub fn writeByte(self: Self, byte: u8) anyerror!void {
28 const array = [1]u8{byte};
29 return self.writeAll(&array);
30}
31
32pub fn writeByteNTimes(self: Self, byte: u8, n: usize) anyerror!void {
33 var bytes: [256]u8 = undefined;
34 @memset(bytes[0..], byte);
35
36 var remaining: usize = n;
37 while (remaining > 0) {
38 const to_write = @min(remaining, bytes.len);
39 try self.writeAll(bytes[0..to_write]);
40 remaining -= to_write;
41 }
42}
43
44pub fn writeBytesNTimes(self: Self, bytes: []const u8, n: usize) anyerror!void {
45 var i: usize = 0;
46 while (i < n) : (i += 1) {
47 try self.writeAll(bytes);
48 }
49}
50
51pub inline fn writeInt(self: Self, comptime T: type, value: T, endian: std.builtin.Endian) anyerror!void {
52 var bytes: [@divExact(@typeInfo(T).int.bits, 8)]u8 = undefined;
53 mem.writeInt(std.math.ByteAlignedInt(@TypeOf(value)), &bytes, value, endian);
54 return self.writeAll(&bytes);
55}
56
57pub fn writeStruct(self: Self, value: anytype) anyerror!void {
58 // Only extern and packed structs have defined in-memory layout.
59 comptime assert(@typeInfo(@TypeOf(value)).@"struct".layout != .auto);
60 return self.writeAll(mem.asBytes(&value));
61}
62
63pub fn writeStructEndian(self: Self, value: anytype, endian: std.builtin.Endian) anyerror!void {
64 // TODO: make sure this value is not a reference type
65 if (native_endian == endian) {
66 return self.writeStruct(value);
67 } else {
68 var copy = value;
69 mem.byteSwapAllFields(@TypeOf(value), &copy);
70 return self.writeStruct(copy);
71 }
72}
73
74pub fn writeFile(self: Self, file: std.fs.File) anyerror!void {
75 // TODO: figure out how to adjust std lib abstractions so that this ends up
76 // doing sendfile or maybe even copy_file_range under the right conditions.
77 var buf: [4000]u8 = undefined;
78 while (true) {
79 const n = try file.readAll(&buf);
80 try self.writeAll(buf[0..n]);
81 if (n < buf.len) return;
82 }
83}
84
85/// Helper for bridging to the new `Writer` API while upgrading.
86pub fn adaptToNewApi(self: *const Self, buffer: []u8) Adapter {
87 return .{
88 .derp_writer = self.*,
89 .new_interface = .{
90 .buffer = buffer,
91 .vtable = &.{ .drain = Adapter.drain },
92 },
93 };
94}
95
96pub const Adapter = struct {
97 derp_writer: Self,
98 new_interface: std.io.Writer,
99 err: ?Error = null,
100
101 fn drain(w: *std.io.Writer, data: []const []const u8, splat: usize) std.io.Writer.Error!usize {
102 _ = splat;
103 const a: *@This() = @alignCast(@fieldParentPtr("new_interface", w));
104 const buffered = w.buffered();
105 if (buffered.len != 0) return w.consume(a.derp_writer.write(buffered) catch |err| {
106 a.err = err;
107 return error.WriteFailed;
108 });
109 return a.derp_writer.write(data[0]) catch |err| {
110 a.err = err;
111 return error.WriteFailed;
112 };
113 }
114};
lib/std/Io/Reader.zig+48-5
......@@ -143,8 +143,8 @@ pub const failing: Reader = .{
143143
144144/// This is generally safe to `@constCast` because it has an empty buffer, so
145145/// there is not really a way to accidentally attempt mutation of these fields.
146const ending_state: Reader = .fixed(&.{});
147pub const ending: *Reader = @constCast(&ending_state);
146pub const ending_instance: Reader = .fixed(&.{});
147pub const ending: *Reader = @constCast(&ending_instance);
148148
149149pub fn limited(r: *Reader, limit: Limit, buffer: []u8) Limited {
150150 return .init(r, limit, buffer);
......@@ -784,7 +784,7 @@ pub fn peekDelimiterInclusive(r: *Reader, delimiter: u8) DelimiterError![]u8 {
784784}
785785
786786/// Returns a slice of the next bytes of buffered data from the stream until
787/// `delimiter` is found, advancing the seek position.
787/// `delimiter` is found, advancing the seek position up to the delimiter.
788788///
789789/// Returned slice excludes the delimiter. End-of-stream is treated equivalent
790790/// to a delimiter, unless it would result in a length 0 return value, in which
......@@ -814,6 +814,37 @@ pub fn takeDelimiterExclusive(r: *Reader, delimiter: u8) DelimiterError![]u8 {
814814 return result[0 .. result.len - 1];
815815}
816816
817/// Returns a slice of the next bytes of buffered data from the stream until
818/// `delimiter` is found, advancing the seek position past the delimiter.
819///
820/// Returned slice excludes the delimiter. End-of-stream is treated equivalent
821/// to a delimiter, unless it would result in a length 0 return value, in which
822/// case `null` is returned instead.
823///
824/// If the delimiter is not found within a number of bytes matching the
825/// capacity of this `Reader`, `error.StreamTooLong` is returned. In
826/// such case, the stream state is unmodified as if this function was never
827/// called.
828///
829/// Invalidates previously returned values from `peek`.
830///
831/// See also:
832/// * `takeDelimiterInclusive`
833/// * `takeDelimiterExclusive`
834pub fn takeDelimiter(r: *Reader, delimiter: u8) error{ ReadFailed, StreamTooLong }!?[]u8 {
835 const result = r.peekDelimiterInclusive(delimiter) catch |err| switch (err) {
836 error.EndOfStream => {
837 const remaining = r.buffer[r.seek..r.end];
838 if (remaining.len == 0) return null;
839 r.toss(remaining.len);
840 return remaining;
841 },
842 else => |e| return e,
843 };
844 r.toss(result.len + 1);
845 return result[0 .. result.len - 1];
846}
847
817848/// Returns a slice of the next bytes of buffered data from the stream until
818849/// `delimiter` is found, without advancing the seek position.
819850///
......@@ -846,6 +877,8 @@ pub fn peekDelimiterExclusive(r: *Reader, delimiter: u8) DelimiterError![]u8 {
846877/// Appends to `w` contents by reading from the stream until `delimiter` is
847878/// found. Does not write the delimiter itself.
848879///
880/// Does not discard the delimiter from the `Reader`.
881///
849882/// Returns number of bytes streamed, which may be zero, or error.EndOfStream
850883/// if the delimiter was not found.
851884///
......@@ -899,6 +932,8 @@ pub const StreamDelimiterLimitError = error{
899932/// Appends to `w` contents by reading from the stream until `delimiter` is found.
900933/// Does not write the delimiter itself.
901934///
935/// Does not discard the delimiter from the `Reader`.
936///
902937/// Returns number of bytes streamed, which may be zero. End of stream can be
903938/// detected by checking if the next byte in the stream is the delimiter.
904939///
......@@ -1128,7 +1163,11 @@ pub inline fn takeStruct(r: *Reader, comptime T: type, endian: std.builtin.Endia
11281163 .@"struct" => |info| switch (info.layout) {
11291164 .auto => @compileError("ill-defined memory layout"),
11301165 .@"extern" => {
1131 var res = (try r.takeStructPointer(T)).*;
1166 // This code works around https://github.com/ziglang/zig/issues/25067
1167 // by avoiding a call to `peekStructPointer`.
1168 const struct_bytes = try r.takeArray(@sizeOf(T));
1169 var res: T = undefined;
1170 @memcpy(@as([]u8, @ptrCast(&res)), struct_bytes);
11321171 if (native_endian != endian) std.mem.byteSwapAllFields(T, &res);
11331172 return res;
11341173 },
......@@ -1153,7 +1192,11 @@ pub inline fn peekStruct(r: *Reader, comptime T: type, endian: std.builtin.Endia
11531192 .@"struct" => |info| switch (info.layout) {
11541193 .auto => @compileError("ill-defined memory layout"),
11551194 .@"extern" => {
1156 var res = (try r.peekStructPointer(T)).*;
1195 // This code works around https://github.com/ziglang/zig/issues/25067
1196 // by avoiding a call to `peekStructPointer`.
1197 const struct_bytes = try r.peekArray(@sizeOf(T));
1198 var res: T = undefined;
1199 @memcpy(@as([]u8, @ptrCast(&res)), struct_bytes);
11571200 if (native_endian != endian) std.mem.byteSwapAllFields(T, &res);
11581201 return res;
11591202 },
lib/std/Io/Reader/test.zig deleted-351
......@@ -1,351 +0,0 @@
1const builtin = @import("builtin");
2const std = @import("../../std.zig");
3const testing = std.testing;
4
5test "Reader" {
6 var buf = "a\x02".*;
7 var fis = std.io.fixedBufferStream(&buf);
8 const reader = fis.reader();
9 try testing.expect((try reader.readByte()) == 'a');
10 try testing.expect((try reader.readEnum(enum(u8) {
11 a = 0,
12 b = 99,
13 c = 2,
14 d = 3,
15 }, builtin.cpu.arch.endian())) == .c);
16 try testing.expectError(error.EndOfStream, reader.readByte());
17}
18
19test "isBytes" {
20 var fis = std.io.fixedBufferStream("foobar");
21 const reader = fis.reader();
22 try testing.expectEqual(true, try reader.isBytes("foo"));
23 try testing.expectEqual(false, try reader.isBytes("qux"));
24}
25
26test "skipBytes" {
27 var fis = std.io.fixedBufferStream("foobar");
28 const reader = fis.reader();
29 try reader.skipBytes(3, .{});
30 try testing.expect(try reader.isBytes("bar"));
31 try reader.skipBytes(0, .{});
32 try testing.expectError(error.EndOfStream, reader.skipBytes(1, .{}));
33}
34
35test "readUntilDelimiterArrayList returns ArrayLists with bytes read until the delimiter, then EndOfStream" {
36 const a = std.testing.allocator;
37 var list = std.array_list.Managed(u8).init(a);
38 defer list.deinit();
39
40 var fis = std.io.fixedBufferStream("0000\n1234\n");
41 const reader = fis.reader();
42
43 try reader.readUntilDelimiterArrayList(&list, '\n', 5);
44 try std.testing.expectEqualStrings("0000", list.items);
45 try reader.readUntilDelimiterArrayList(&list, '\n', 5);
46 try std.testing.expectEqualStrings("1234", list.items);
47 try std.testing.expectError(error.EndOfStream, reader.readUntilDelimiterArrayList(&list, '\n', 5));
48}
49
50test "readUntilDelimiterArrayList returns an empty ArrayList" {
51 const a = std.testing.allocator;
52 var list = std.array_list.Managed(u8).init(a);
53 defer list.deinit();
54
55 var fis = std.io.fixedBufferStream("\n");
56 const reader = fis.reader();
57
58 try reader.readUntilDelimiterArrayList(&list, '\n', 5);
59 try std.testing.expectEqualStrings("", list.items);
60}
61
62test "readUntilDelimiterArrayList returns StreamTooLong, then an ArrayList with bytes read until the delimiter" {
63 const a = std.testing.allocator;
64 var list = std.array_list.Managed(u8).init(a);
65 defer list.deinit();
66
67 var fis = std.io.fixedBufferStream("1234567\n");
68 const reader = fis.reader();
69
70 try std.testing.expectError(error.StreamTooLong, reader.readUntilDelimiterArrayList(&list, '\n', 5));
71 try std.testing.expectEqualStrings("12345", list.items);
72 try reader.readUntilDelimiterArrayList(&list, '\n', 5);
73 try std.testing.expectEqualStrings("67", list.items);
74}
75
76test "readUntilDelimiterArrayList returns EndOfStream" {
77 const a = std.testing.allocator;
78 var list = std.array_list.Managed(u8).init(a);
79 defer list.deinit();
80
81 var fis = std.io.fixedBufferStream("1234");
82 const reader = fis.reader();
83
84 try std.testing.expectError(error.EndOfStream, reader.readUntilDelimiterArrayList(&list, '\n', 5));
85 try std.testing.expectEqualStrings("1234", list.items);
86}
87
88test "readUntilDelimiterAlloc returns ArrayLists with bytes read until the delimiter, then EndOfStream" {
89 const a = std.testing.allocator;
90
91 var fis = std.io.fixedBufferStream("0000\n1234\n");
92 const reader = fis.reader();
93
94 {
95 const result = try reader.readUntilDelimiterAlloc(a, '\n', 5);
96 defer a.free(result);
97 try std.testing.expectEqualStrings("0000", result);
98 }
99
100 {
101 const result = try reader.readUntilDelimiterAlloc(a, '\n', 5);
102 defer a.free(result);
103 try std.testing.expectEqualStrings("1234", result);
104 }
105
106 try std.testing.expectError(error.EndOfStream, reader.readUntilDelimiterAlloc(a, '\n', 5));
107}
108
109test "readUntilDelimiterAlloc returns an empty ArrayList" {
110 const a = std.testing.allocator;
111
112 var fis = std.io.fixedBufferStream("\n");
113 const reader = fis.reader();
114
115 {
116 const result = try reader.readUntilDelimiterAlloc(a, '\n', 5);
117 defer a.free(result);
118 try std.testing.expectEqualStrings("", result);
119 }
120}
121
122test "readUntilDelimiterAlloc returns StreamTooLong, then an ArrayList with bytes read until the delimiter" {
123 const a = std.testing.allocator;
124
125 var fis = std.io.fixedBufferStream("1234567\n");
126 const reader = fis.reader();
127
128 try std.testing.expectError(error.StreamTooLong, reader.readUntilDelimiterAlloc(a, '\n', 5));
129
130 const result = try reader.readUntilDelimiterAlloc(a, '\n', 5);
131 defer a.free(result);
132 try std.testing.expectEqualStrings("67", result);
133}
134
135test "readUntilDelimiterAlloc returns EndOfStream" {
136 const a = std.testing.allocator;
137
138 var fis = std.io.fixedBufferStream("1234");
139 const reader = fis.reader();
140
141 try std.testing.expectError(error.EndOfStream, reader.readUntilDelimiterAlloc(a, '\n', 5));
142}
143
144test "readUntilDelimiter returns bytes read until the delimiter" {
145 var buf: [5]u8 = undefined;
146 var fis = std.io.fixedBufferStream("0000\n1234\n");
147 const reader = fis.reader();
148 try std.testing.expectEqualStrings("0000", try reader.readUntilDelimiter(&buf, '\n'));
149 try std.testing.expectEqualStrings("1234", try reader.readUntilDelimiter(&buf, '\n'));
150}
151
152test "readUntilDelimiter returns an empty string" {
153 var buf: [5]u8 = undefined;
154 var fis = std.io.fixedBufferStream("\n");
155 const reader = fis.reader();
156 try std.testing.expectEqualStrings("", try reader.readUntilDelimiter(&buf, '\n'));
157}
158
159test "readUntilDelimiter returns StreamTooLong, then an empty string" {
160 var buf: [5]u8 = undefined;
161 var fis = std.io.fixedBufferStream("12345\n");
162 const reader = fis.reader();
163 try std.testing.expectError(error.StreamTooLong, reader.readUntilDelimiter(&buf, '\n'));
164 try std.testing.expectEqualStrings("", try reader.readUntilDelimiter(&buf, '\n'));
165}
166
167test "readUntilDelimiter returns StreamTooLong, then bytes read until the delimiter" {
168 var buf: [5]u8 = undefined;
169 var fis = std.io.fixedBufferStream("1234567\n");
170 const reader = fis.reader();
171 try std.testing.expectError(error.StreamTooLong, reader.readUntilDelimiter(&buf, '\n'));
172 try std.testing.expectEqualStrings("67", try reader.readUntilDelimiter(&buf, '\n'));
173}
174
175test "readUntilDelimiter returns EndOfStream" {
176 {
177 var buf: [5]u8 = undefined;
178 var fis = std.io.fixedBufferStream("");
179 const reader = fis.reader();
180 try std.testing.expectError(error.EndOfStream, reader.readUntilDelimiter(&buf, '\n'));
181 }
182 {
183 var buf: [5]u8 = undefined;
184 var fis = std.io.fixedBufferStream("1234");
185 const reader = fis.reader();
186 try std.testing.expectError(error.EndOfStream, reader.readUntilDelimiter(&buf, '\n'));
187 }
188}
189
190test "readUntilDelimiter returns bytes read until delimiter, then EndOfStream" {
191 var buf: [5]u8 = undefined;
192 var fis = std.io.fixedBufferStream("1234\n");
193 const reader = fis.reader();
194 try std.testing.expectEqualStrings("1234", try reader.readUntilDelimiter(&buf, '\n'));
195 try std.testing.expectError(error.EndOfStream, reader.readUntilDelimiter(&buf, '\n'));
196}
197
198test "readUntilDelimiter returns StreamTooLong, then EndOfStream" {
199 var buf: [5]u8 = undefined;
200 var fis = std.io.fixedBufferStream("12345");
201 const reader = fis.reader();
202 try std.testing.expectError(error.StreamTooLong, reader.readUntilDelimiter(&buf, '\n'));
203 try std.testing.expectError(error.EndOfStream, reader.readUntilDelimiter(&buf, '\n'));
204}
205
206test "readUntilDelimiter writes all bytes read to the output buffer" {
207 var buf: [5]u8 = undefined;
208 var fis = std.io.fixedBufferStream("0000\n12345");
209 const reader = fis.reader();
210 _ = try reader.readUntilDelimiter(&buf, '\n');
211 try std.testing.expectEqualStrings("0000\n", &buf);
212 try std.testing.expectError(error.StreamTooLong, reader.readUntilDelimiter(&buf, '\n'));
213 try std.testing.expectEqualStrings("12345", &buf);
214}
215
216test "readUntilDelimiterOrEofAlloc returns ArrayLists with bytes read until the delimiter, then EndOfStream" {
217 const a = std.testing.allocator;
218
219 var fis = std.io.fixedBufferStream("0000\n1234\n");
220 const reader = fis.reader();
221
222 {
223 const result = (try reader.readUntilDelimiterOrEofAlloc(a, '\n', 5)).?;
224 defer a.free(result);
225 try std.testing.expectEqualStrings("0000", result);
226 }
227
228 {
229 const result = (try reader.readUntilDelimiterOrEofAlloc(a, '\n', 5)).?;
230 defer a.free(result);
231 try std.testing.expectEqualStrings("1234", result);
232 }
233
234 try std.testing.expect((try reader.readUntilDelimiterOrEofAlloc(a, '\n', 5)) == null);
235}
236
237test "readUntilDelimiterOrEofAlloc returns an empty ArrayList" {
238 const a = std.testing.allocator;
239
240 var fis = std.io.fixedBufferStream("\n");
241 const reader = fis.reader();
242
243 {
244 const result = (try reader.readUntilDelimiterOrEofAlloc(a, '\n', 5)).?;
245 defer a.free(result);
246 try std.testing.expectEqualStrings("", result);
247 }
248}
249
250test "readUntilDelimiterOrEofAlloc returns StreamTooLong, then an ArrayList with bytes read until the delimiter" {
251 const a = std.testing.allocator;
252
253 var fis = std.io.fixedBufferStream("1234567\n");
254 const reader = fis.reader();
255
256 try std.testing.expectError(error.StreamTooLong, reader.readUntilDelimiterOrEofAlloc(a, '\n', 5));
257
258 const result = (try reader.readUntilDelimiterOrEofAlloc(a, '\n', 5)).?;
259 defer a.free(result);
260 try std.testing.expectEqualStrings("67", result);
261}
262
263test "readUntilDelimiterOrEof returns bytes read until the delimiter" {
264 var buf: [5]u8 = undefined;
265 var fis = std.io.fixedBufferStream("0000\n1234\n");
266 const reader = fis.reader();
267 try std.testing.expectEqualStrings("0000", (try reader.readUntilDelimiterOrEof(&buf, '\n')).?);
268 try std.testing.expectEqualStrings("1234", (try reader.readUntilDelimiterOrEof(&buf, '\n')).?);
269}
270
271test "readUntilDelimiterOrEof returns an empty string" {
272 var buf: [5]u8 = undefined;
273 var fis = std.io.fixedBufferStream("\n");
274 const reader = fis.reader();
275 try std.testing.expectEqualStrings("", (try reader.readUntilDelimiterOrEof(&buf, '\n')).?);
276}
277
278test "readUntilDelimiterOrEof returns StreamTooLong, then an empty string" {
279 var buf: [5]u8 = undefined;
280 var fis = std.io.fixedBufferStream("12345\n");
281 const reader = fis.reader();
282 try std.testing.expectError(error.StreamTooLong, reader.readUntilDelimiterOrEof(&buf, '\n'));
283 try std.testing.expectEqualStrings("", (try reader.readUntilDelimiterOrEof(&buf, '\n')).?);
284}
285
286test "readUntilDelimiterOrEof returns StreamTooLong, then bytes read until the delimiter" {
287 var buf: [5]u8 = undefined;
288 var fis = std.io.fixedBufferStream("1234567\n");
289 const reader = fis.reader();
290 try std.testing.expectError(error.StreamTooLong, reader.readUntilDelimiterOrEof(&buf, '\n'));
291 try std.testing.expectEqualStrings("67", (try reader.readUntilDelimiterOrEof(&buf, '\n')).?);
292}
293
294test "readUntilDelimiterOrEof returns null" {
295 var buf: [5]u8 = undefined;
296 var fis = std.io.fixedBufferStream("");
297 const reader = fis.reader();
298 try std.testing.expect((try reader.readUntilDelimiterOrEof(&buf, '\n')) == null);
299}
300
301test "readUntilDelimiterOrEof returns bytes read until delimiter, then null" {
302 var buf: [5]u8 = undefined;
303 var fis = std.io.fixedBufferStream("1234\n");
304 const reader = fis.reader();
305 try std.testing.expectEqualStrings("1234", (try reader.readUntilDelimiterOrEof(&buf, '\n')).?);
306 try std.testing.expect((try reader.readUntilDelimiterOrEof(&buf, '\n')) == null);
307}
308
309test "readUntilDelimiterOrEof returns bytes read until end-of-stream" {
310 var buf: [5]u8 = undefined;
311 var fis = std.io.fixedBufferStream("1234");
312 const reader = fis.reader();
313 try std.testing.expectEqualStrings("1234", (try reader.readUntilDelimiterOrEof(&buf, '\n')).?);
314}
315
316test "readUntilDelimiterOrEof returns StreamTooLong, then bytes read until end-of-stream" {
317 var buf: [5]u8 = undefined;
318 var fis = std.io.fixedBufferStream("1234567");
319 const reader = fis.reader();
320 try std.testing.expectError(error.StreamTooLong, reader.readUntilDelimiterOrEof(&buf, '\n'));
321 try std.testing.expectEqualStrings("67", (try reader.readUntilDelimiterOrEof(&buf, '\n')).?);
322}
323
324test "readUntilDelimiterOrEof writes all bytes read to the output buffer" {
325 var buf: [5]u8 = undefined;
326 var fis = std.io.fixedBufferStream("0000\n12345");
327 const reader = fis.reader();
328 _ = try reader.readUntilDelimiterOrEof(&buf, '\n');
329 try std.testing.expectEqualStrings("0000\n", &buf);
330 try std.testing.expectError(error.StreamTooLong, reader.readUntilDelimiterOrEof(&buf, '\n'));
331 try std.testing.expectEqualStrings("12345", &buf);
332}
333
334test "streamUntilDelimiter writes all bytes without delimiter to the output" {
335 const input_string = "some_string_with_delimiter!";
336 var input_fbs = std.io.fixedBufferStream(input_string);
337 const reader = input_fbs.reader();
338
339 var output: [input_string.len]u8 = undefined;
340 var output_fbs = std.io.fixedBufferStream(&output);
341 const writer = output_fbs.writer();
342
343 try reader.streamUntilDelimiter(writer, '!', input_fbs.buffer.len);
344 try std.testing.expectEqualStrings("some_string_with_delimiter", output_fbs.getWritten());
345 try std.testing.expectError(error.EndOfStream, reader.streamUntilDelimiter(writer, '!', input_fbs.buffer.len));
346
347 input_fbs.reset();
348 output_fbs.reset();
349
350 try std.testing.expectError(error.StreamTooLong, reader.streamUntilDelimiter(writer, '!', 5));
351}
lib/std/Io/Writer.zig+29-5
......@@ -8,6 +8,7 @@ const Limit = std.Io.Limit;
88const File = std.fs.File;
99const testing = std.testing;
1010const Allocator = std.mem.Allocator;
11const ArrayList = std.ArrayList;
1112
1213vtable: *const VTable,
1314/// If this has length zero, the writer is unbuffered, and `flush` is a no-op.
......@@ -2374,6 +2375,29 @@ pub fn unreachableRebase(w: *Writer, preserve: usize, capacity: usize) Error!voi
23742375 unreachable;
23752376}
23762377
2378pub fn fromArrayList(array_list: *ArrayList(u8)) Writer {
2379 defer array_list.* = .empty;
2380 return .{
2381 .vtable = &.{
2382 .drain = fixedDrain,
2383 .flush = noopFlush,
2384 .rebase = failingRebase,
2385 },
2386 .buffer = array_list.allocatedSlice(),
2387 .end = array_list.items.len,
2388 };
2389}
2390
2391pub fn toArrayList(w: *Writer) ArrayList(u8) {
2392 const result: ArrayList(u8) = .{
2393 .items = w.buffer[0..w.end],
2394 .capacity = w.buffer.len,
2395 };
2396 w.buffer = &.{};
2397 w.end = 0;
2398 return result;
2399}
2400
23772401/// Provides a `Writer` implementation based on calling `Hasher.update`, sending
23782402/// all data also to an underlying `Writer`.
23792403///
......@@ -2546,7 +2570,7 @@ pub const Allocating = struct {
25462570 }
25472571
25482572 /// Replaces `array_list` with empty, taking ownership of the memory.
2549 pub fn fromArrayList(allocator: Allocator, array_list: *std.ArrayListUnmanaged(u8)) Allocating {
2573 pub fn fromArrayList(allocator: Allocator, array_list: *ArrayList(u8)) Allocating {
25502574 defer array_list.* = .empty;
25512575 return .{
25522576 .allocator = allocator,
......@@ -2572,9 +2596,9 @@ pub const Allocating = struct {
25722596
25732597 /// Returns an array list that takes ownership of the allocated memory.
25742598 /// Resets the `Allocating` to an empty state.
2575 pub fn toArrayList(a: *Allocating) std.ArrayListUnmanaged(u8) {
2599 pub fn toArrayList(a: *Allocating) ArrayList(u8) {
25762600 const w = &a.writer;
2577 const result: std.ArrayListUnmanaged(u8) = .{
2601 const result: ArrayList(u8) = .{
25782602 .items = w.buffer[0..w.end],
25792603 .capacity = w.buffer.len,
25802604 };
......@@ -2603,7 +2627,7 @@ pub const Allocating = struct {
26032627
26042628 pub fn toOwnedSliceSentinel(a: *Allocating, comptime sentinel: u8) error{OutOfMemory}![:sentinel]u8 {
26052629 const gpa = a.allocator;
2606 var list = toArrayList(a);
2630 var list = @This().toArrayList(a);
26072631 defer a.setArrayList(list);
26082632 return list.toOwnedSliceSentinel(gpa, sentinel);
26092633 }
......@@ -2670,7 +2694,7 @@ pub const Allocating = struct {
26702694 list.ensureUnusedCapacity(gpa, minimum_len) catch return error.WriteFailed;
26712695 }
26722696
2673 fn setArrayList(a: *Allocating, list: std.ArrayListUnmanaged(u8)) void {
2697 fn setArrayList(a: *Allocating, list: ArrayList(u8)) void {
26742698 a.writer.buffer = list.allocatedSlice();
26752699 a.writer.end = list.items.len;
26762700 }
lib/std/Io/fixed_buffer_stream.zig-69
......@@ -17,7 +17,6 @@ pub fn FixedBufferStream(comptime Buffer: type) type {
1717 pub const GetSeekPosError = error{};
1818
1919 pub const Reader = io.GenericReader(*Self, ReadError, read);
20 pub const Writer = io.GenericWriter(*Self, WriteError, write);
2120
2221 const Self = @This();
2322
......@@ -25,10 +24,6 @@ pub fn FixedBufferStream(comptime Buffer: type) type {
2524 return .{ .context = self };
2625 }
2726
28 pub fn writer(self: *Self) Writer {
29 return .{ .context = self };
30 }
31
3227 pub fn read(self: *Self, dest: []u8) ReadError!usize {
3328 const size = @min(dest.len, self.buffer.len - self.pos);
3429 const end = self.pos + size;
......@@ -39,23 +34,6 @@ pub fn FixedBufferStream(comptime Buffer: type) type {
3934 return size;
4035 }
4136
42 /// If the returned number of bytes written is less than requested, the
43 /// buffer is full. Returns `error.NoSpaceLeft` when no bytes would be written.
44 /// Note: `error.NoSpaceLeft` matches the corresponding error from
45 /// `std.fs.File.WriteError`.
46 pub fn write(self: *Self, bytes: []const u8) WriteError!usize {
47 if (bytes.len == 0) return 0;
48 if (self.pos >= self.buffer.len) return error.NoSpaceLeft;
49
50 const n = @min(self.buffer.len - self.pos, bytes.len);
51 @memcpy(self.buffer[self.pos..][0..n], bytes[0..n]);
52 self.pos += n;
53
54 if (n == 0) return error.NoSpaceLeft;
55
56 return n;
57 }
58
5937 pub fn seekTo(self: *Self, pos: u64) SeekError!void {
6038 self.pos = @min(std.math.lossyCast(usize, pos), self.buffer.len);
6139 }
......@@ -84,10 +62,6 @@ pub fn FixedBufferStream(comptime Buffer: type) type {
8462 return self.pos;
8563 }
8664
87 pub fn getWritten(self: Self) Buffer {
88 return self.buffer[0..self.pos];
89 }
90
9165 pub fn reset(self: *Self) void {
9266 self.pos = 0;
9367 }
......@@ -117,49 +91,6 @@ fn Slice(comptime T: type) type {
11791 }
11892}
11993
120test "output" {
121 var buf: [255]u8 = undefined;
122 var fbs = fixedBufferStream(&buf);
123 const stream = fbs.writer();
124
125 try stream.print("{s}{s}!", .{ "Hello", "World" });
126 try testing.expectEqualSlices(u8, "HelloWorld!", fbs.getWritten());
127}
128
129test "output at comptime" {
130 comptime {
131 var buf: [255]u8 = undefined;
132 var fbs = fixedBufferStream(&buf);
133 const stream = fbs.writer();
134
135 try stream.print("{s}{s}!", .{ "Hello", "World" });
136 try testing.expectEqualSlices(u8, "HelloWorld!", fbs.getWritten());
137 }
138}
139
140test "output 2" {
141 var buffer: [10]u8 = undefined;
142 var fbs = fixedBufferStream(&buffer);
143
144 try fbs.writer().writeAll("Hello");
145 try testing.expect(mem.eql(u8, fbs.getWritten(), "Hello"));
146
147 try fbs.writer().writeAll("world");
148 try testing.expect(mem.eql(u8, fbs.getWritten(), "Helloworld"));
149
150 try testing.expectError(error.NoSpaceLeft, fbs.writer().writeAll("!"));
151 try testing.expect(mem.eql(u8, fbs.getWritten(), "Helloworld"));
152
153 fbs.reset();
154 try testing.expect(fbs.getWritten().len == 0);
155
156 try testing.expectError(error.NoSpaceLeft, fbs.writer().writeAll("Hello world!"));
157 try testing.expect(mem.eql(u8, fbs.getWritten(), "Hello worl"));
158
159 try fbs.seekTo((try fbs.getEndPos()) + 1);
160 try testing.expectError(error.NoSpaceLeft, fbs.writer().writeAll("H"));
161}
162
16394test "input" {
16495 const bytes = [_]u8{ 1, 2, 3, 4, 5, 6, 7 };
16596 var fbs = fixedBufferStream(&bytes);
lib/std/Thread.zig+1-1
......@@ -167,7 +167,7 @@ pub fn setName(self: Thread, name: []const u8) SetNameError!void {
167167 const file = try std.fs.cwd().openFile(path, .{ .mode = .write_only });
168168 defer file.close();
169169
170 try file.deprecatedWriter().writeAll(name);
170 try file.writeAll(name);
171171 return;
172172 },
173173 .windows => {
lib/std/array_list.zig-129
......@@ -336,39 +336,6 @@ pub fn AlignedManaged(comptime T: type, comptime alignment: ?mem.Alignment) type
336336 try unmanaged.print(gpa, fmt, args);
337337 }
338338
339 pub const Writer = if (T != u8) void else std.io.GenericWriter(*Self, Allocator.Error, appendWrite);
340
341 /// Initializes a Writer which will append to the list.
342 pub fn writer(self: *Self) Writer {
343 return .{ .context = self };
344 }
345
346 /// Same as `append` except it returns the number of bytes written, which is always the same
347 /// as `m.len`. The purpose of this function existing is to match `std.io.GenericWriter` API.
348 /// Invalidates element pointers if additional memory is needed.
349 fn appendWrite(self: *Self, m: []const u8) Allocator.Error!usize {
350 try self.appendSlice(m);
351 return m.len;
352 }
353
354 pub const FixedWriter = std.io.GenericWriter(*Self, Allocator.Error, appendWriteFixed);
355
356 /// Initializes a Writer which will append to the list but will return
357 /// `error.OutOfMemory` rather than increasing capacity.
358 pub fn fixedWriter(self: *Self) FixedWriter {
359 return .{ .context = self };
360 }
361
362 /// The purpose of this function existing is to match `std.io.GenericWriter` API.
363 fn appendWriteFixed(self: *Self, m: []const u8) error{OutOfMemory}!usize {
364 const available_capacity = self.capacity - self.items.len;
365 if (m.len > available_capacity)
366 return error.OutOfMemory;
367
368 self.appendSliceAssumeCapacity(m);
369 return m.len;
370 }
371
372339 /// Append a value to the list `n` times.
373340 /// Allocates more memory as necessary.
374341 /// Invalidates element pointers if additional memory is needed.
......@@ -1083,48 +1050,6 @@ pub fn Aligned(comptime T: type, comptime alignment: ?mem.Alignment) type {
10831050 self.items.len += w.end;
10841051 }
10851052
1086 /// Deprecated in favor of `print` or `std.io.Writer.Allocating`.
1087 pub const WriterContext = struct {
1088 self: *Self,
1089 allocator: Allocator,
1090 };
1091
1092 /// Deprecated in favor of `print` or `std.io.Writer.Allocating`.
1093 pub const Writer = if (T != u8)
1094 @compileError("The Writer interface is only defined for ArrayList(u8) " ++
1095 "but the given type is ArrayList(" ++ @typeName(T) ++ ")")
1096 else
1097 std.io.GenericWriter(WriterContext, Allocator.Error, appendWrite);
1098
1099 /// Deprecated in favor of `print` or `std.io.Writer.Allocating`.
1100 pub fn writer(self: *Self, gpa: Allocator) Writer {
1101 return .{ .context = .{ .self = self, .allocator = gpa } };
1102 }
1103
1104 /// Deprecated in favor of `print` or `std.io.Writer.Allocating`.
1105 fn appendWrite(context: WriterContext, m: []const u8) Allocator.Error!usize {
1106 try context.self.appendSlice(context.allocator, m);
1107 return m.len;
1108 }
1109
1110 /// Deprecated in favor of `print` or `std.io.Writer.Allocating`.
1111 pub const FixedWriter = std.io.GenericWriter(*Self, Allocator.Error, appendWriteFixed);
1112
1113 /// Deprecated in favor of `print` or `std.io.Writer.Allocating`.
1114 pub fn fixedWriter(self: *Self) FixedWriter {
1115 return .{ .context = self };
1116 }
1117
1118 /// Deprecated in favor of `print` or `std.io.Writer.Allocating`.
1119 fn appendWriteFixed(self: *Self, m: []const u8) error{OutOfMemory}!usize {
1120 const available_capacity = self.capacity - self.items.len;
1121 if (m.len > available_capacity)
1122 return error.OutOfMemory;
1123
1124 self.appendSliceAssumeCapacity(m);
1125 return m.len;
1126 }
1127
11281053 /// Append a value to the list `n` times.
11291054 /// Allocates more memory as necessary.
11301055 /// Invalidates element pointers if additional memory is needed.
......@@ -2116,60 +2041,6 @@ test "Managed(T) of struct T" {
21162041 }
21172042}
21182043
2119test "Managed(u8) implements writer" {
2120 const a = testing.allocator;
2121
2122 {
2123 var buffer = Managed(u8).init(a);
2124 defer buffer.deinit();
2125
2126 const x: i32 = 42;
2127 const y: i32 = 1234;
2128 try buffer.writer().print("x: {}\ny: {}\n", .{ x, y });
2129
2130 try testing.expectEqualSlices(u8, "x: 42\ny: 1234\n", buffer.items);
2131 }
2132 {
2133 var list = AlignedManaged(u8, .@"2").init(a);
2134 defer list.deinit();
2135
2136 const writer = list.writer();
2137 try writer.writeAll("a");
2138 try writer.writeAll("bc");
2139 try writer.writeAll("d");
2140 try writer.writeAll("efg");
2141
2142 try testing.expectEqualSlices(u8, list.items, "abcdefg");
2143 }
2144}
2145
2146test "ArrayList(u8) implements writer" {
2147 const a = testing.allocator;
2148
2149 {
2150 var buffer: ArrayList(u8) = .empty;
2151 defer buffer.deinit(a);
2152
2153 const x: i32 = 42;
2154 const y: i32 = 1234;
2155 try buffer.writer(a).print("x: {}\ny: {}\n", .{ x, y });
2156
2157 try testing.expectEqualSlices(u8, "x: 42\ny: 1234\n", buffer.items);
2158 }
2159 {
2160 var list: Aligned(u8, .@"2") = .empty;
2161 defer list.deinit(a);
2162
2163 const writer = list.writer(a);
2164 try writer.writeAll("a");
2165 try writer.writeAll("bc");
2166 try writer.writeAll("d");
2167 try writer.writeAll("efg");
2168
2169 try testing.expectEqualSlices(u8, list.items, "abcdefg");
2170 }
2171}
2172
21732044test "shrink still sets length when resizing is disabled" {
21742045 var failing_allocator = testing.FailingAllocator.init(testing.allocator, .{ .resize_fail_index = 0 });
21752046 const a = failing_allocator.allocator();
lib/std/base64.zig+1-2
......@@ -108,8 +108,7 @@ pub const Base64Encoder = struct {
108108 }
109109 }
110110
111 // dest must be compatible with std.io.GenericWriter's writeAll interface
112 pub fn encodeWriter(encoder: *const Base64Encoder, dest: anytype, source: []const u8) !void {
111 pub fn encodeWriter(encoder: *const Base64Encoder, dest: *std.Io.Writer, source: []const u8) !void {
113112 var chunker = window(u8, source, 3, 3);
114113 while (chunker.next()) |chunk| {
115114 var temp: [5]u8 = undefined;
lib/std/crypto/aegis.zig-12
......@@ -801,18 +801,6 @@ fn AegisMac(comptime T: type) type {
801801 ctx.update(msg);
802802 ctx.final(out);
803803 }
804
805 pub const Error = error{};
806 pub const Writer = std.io.GenericWriter(*Mac, Error, write);
807
808 fn write(self: *Mac, bytes: []const u8) Error!usize {
809 self.update(bytes);
810 return bytes.len;
811 }
812
813 pub fn writer(self: *Mac) Writer {
814 return .{ .context = self };
815 }
816804 };
817805}
818806
lib/std/crypto/blake2.zig-12
......@@ -185,18 +185,6 @@ pub fn Blake2s(comptime out_bits: usize) type {
185185 r.* ^= v[i] ^ v[i + 8];
186186 }
187187 }
188
189 pub const Error = error{};
190 pub const Writer = std.io.GenericWriter(*Self, Error, write);
191
192 fn write(self: *Self, bytes: []const u8) Error!usize {
193 self.update(bytes);
194 return bytes.len;
195 }
196
197 pub fn writer(self: *Self) Writer {
198 return .{ .context = self };
199 }
200188 };
201189}
202190
lib/std/crypto/blake3.zig-12
......@@ -474,18 +474,6 @@ pub const Blake3 = struct {
474474 }
475475 output.rootOutputBytes(out_slice);
476476 }
477
478 pub const Error = error{};
479 pub const Writer = std.io.GenericWriter(*Blake3, Error, write);
480
481 fn write(self: *Blake3, bytes: []const u8) Error!usize {
482 self.update(bytes);
483 return bytes.len;
484 }
485
486 pub fn writer(self: *Blake3) Writer {
487 return .{ .context = self };
488 }
489477};
490478
491479// Use named type declarations to workaround crash with anonymous structs (issue #4373).
lib/std/crypto/codecs/asn1/der/ArrayListReverse.zig+6-11
......@@ -4,6 +4,12 @@
44//! Laid out in memory like:
55//! capacity |--------------------------|
66//! data |-------------|
7
8const std = @import("std");
9const Allocator = std.mem.Allocator;
10const assert = std.debug.assert;
11const testing = std.testing;
12
713data: []u8,
814capacity: usize,
915allocator: Allocator,
......@@ -45,12 +51,6 @@ pub fn prependSlice(self: *ArrayListReverse, data: []const u8) Error!void {
4551 self.data.ptr = begin;
4652}
4753
48pub const Writer = std.io.GenericWriter(*ArrayListReverse, Error, prependSliceSize);
49/// Warning: This writer writes backwards. `fn print` will NOT work as expected.
50pub fn writer(self: *ArrayListReverse) Writer {
51 return .{ .context = self };
52}
53
5454fn prependSliceSize(self: *ArrayListReverse, data: []const u8) Error!usize {
5555 try self.prependSlice(data);
5656 return data.len;
......@@ -77,11 +77,6 @@ pub fn toOwnedSlice(self: *ArrayListReverse) Error![]u8 {
7777 return new_memory;
7878}
7979
80const std = @import("std");
81const Allocator = std.mem.Allocator;
82const assert = std.debug.assert;
83const testing = std.testing;
84
8580test ArrayListReverse {
8681 var b = ArrayListReverse.init(testing.allocator);
8782 defer b.deinit();
lib/std/crypto/ml_kem.zig+47-45
......@@ -1721,53 +1721,55 @@ test "Test happy flow" {
17211721
17221722// Code to test NIST Known Answer Tests (KAT), see PQCgenKAT.c.
17231723
1724const sha2 = crypto.hash.sha2;
1725
1726test "NIST KAT test" {
1727 inline for (.{
1728 .{ d00.Kyber512, "e9c2bd37133fcb40772f81559f14b1f58dccd1c816701be9ba6214d43baf4547" },
1729 .{ d00.Kyber1024, "89248f2f33f7f4f7051729111f3049c409a933ec904aedadf035f30fa5646cd5" },
1730 .{ d00.Kyber768, "a1e122cad3c24bc51622e4c242d8b8acbcd3f618fee4220400605ca8f9ea02c2" },
1731 }) |modeHash| {
1732 const mode = modeHash[0];
1733 var seed: [48]u8 = undefined;
1734 for (&seed, 0..) |*s, i| {
1735 s.* = @as(u8, @intCast(i));
1736 }
1737 var f = sha2.Sha256.init(.{});
1738 const fw = f.writer();
1739 var g = NistDRBG.init(seed);
1740 try std.fmt.format(fw, "# {s}\n\n", .{mode.name});
1741 for (0..100) |i| {
1742 g.fill(&seed);
1743 try std.fmt.format(fw, "count = {}\n", .{i});
1744 try std.fmt.format(fw, "seed = {X}\n", .{&seed});
1745 var g2 = NistDRBG.init(seed);
1746
1747 // This is not equivalent to g2.fill(kseed[:]). As the reference
1748 // implementation calls randombytes twice generating the keypair,
1749 // we have to do that as well.
1750 var kseed: [64]u8 = undefined;
1751 var eseed: [32]u8 = undefined;
1752 g2.fill(kseed[0..32]);
1753 g2.fill(kseed[32..64]);
1754 g2.fill(&eseed);
1755 const kp = try mode.KeyPair.generateDeterministic(kseed);
1756 const e = kp.public_key.encaps(eseed);
1757 const ss2 = try kp.secret_key.decaps(&e.ciphertext);
1758 try testing.expectEqual(ss2, e.shared_secret);
1759 try std.fmt.format(fw, "pk = {X}\n", .{&kp.public_key.toBytes()});
1760 try std.fmt.format(fw, "sk = {X}\n", .{&kp.secret_key.toBytes()});
1761 try std.fmt.format(fw, "ct = {X}\n", .{&e.ciphertext});
1762 try std.fmt.format(fw, "ss = {X}\n\n", .{&e.shared_secret});
1763 }
1724test "NIST KAT test d00.Kyber512" {
1725 try testNistKat(d00.Kyber512, "e9c2bd37133fcb40772f81559f14b1f58dccd1c816701be9ba6214d43baf4547");
1726}
17641727
1765 var out: [32]u8 = undefined;
1766 f.final(&out);
1767 var outHex: [64]u8 = undefined;
1768 _ = try std.fmt.bufPrint(&outHex, "{x}", .{&out});
1769 try testing.expectEqual(outHex, modeHash[1].*);
1728test "NIST KAT test d00.Kyber1024" {
1729 try testNistKat(d00.Kyber1024, "89248f2f33f7f4f7051729111f3049c409a933ec904aedadf035f30fa5646cd5");
1730}
1731
1732test "NIST KAT test d00.Kyber768" {
1733 try testNistKat(d00.Kyber768, "a1e122cad3c24bc51622e4c242d8b8acbcd3f618fee4220400605ca8f9ea02c2");
1734}
1735
1736fn testNistKat(mode: type, hash: []const u8) !void {
1737 var seed: [48]u8 = undefined;
1738 for (&seed, 0..) |*s, i| {
1739 s.* = @as(u8, @intCast(i));
17701740 }
1741 var fw: std.Io.Writer.Hashing(crypto.hash.sha2.Sha256) = .init(&.{});
1742 var g = NistDRBG.init(seed);
1743 try fw.writer.print("# {s}\n\n", .{mode.name});
1744 for (0..100) |i| {
1745 g.fill(&seed);
1746 try fw.writer.print("count = {}\n", .{i});
1747 try fw.writer.print("seed = {X}\n", .{&seed});
1748 var g2 = NistDRBG.init(seed);
1749
1750 // This is not equivalent to g2.fill(kseed[:]). As the reference
1751 // implementation calls randombytes twice generating the keypair,
1752 // we have to do that as well.
1753 var kseed: [64]u8 = undefined;
1754 var eseed: [32]u8 = undefined;
1755 g2.fill(kseed[0..32]);
1756 g2.fill(kseed[32..64]);
1757 g2.fill(&eseed);
1758 const kp = try mode.KeyPair.generateDeterministic(kseed);
1759 const e = kp.public_key.encaps(eseed);
1760 const ss2 = try kp.secret_key.decaps(&e.ciphertext);
1761 try testing.expectEqual(ss2, e.shared_secret);
1762 try fw.writer.print("pk = {X}\n", .{&kp.public_key.toBytes()});
1763 try fw.writer.print("sk = {X}\n", .{&kp.secret_key.toBytes()});
1764 try fw.writer.print("ct = {X}\n", .{&e.ciphertext});
1765 try fw.writer.print("ss = {X}\n\n", .{&e.shared_secret});
1766 }
1767
1768 var out: [32]u8 = undefined;
1769 fw.hasher.final(&out);
1770 var outHex: [64]u8 = undefined;
1771 _ = try std.fmt.bufPrint(&outHex, "{x}", .{&out});
1772 try testing.expectEqualStrings(&outHex, hash);
17711773}
17721774
17731775const NistDRBG = struct {
lib/std/crypto/scrypt.zig+12-9
......@@ -304,31 +304,34 @@ const crypt_format = struct {
304304
305305 /// Serialize parameters into a string in modular crypt format.
306306 pub fn serialize(params: anytype, str: []u8) EncodingError![]const u8 {
307 var buf = io.fixedBufferStream(str);
308 try serializeTo(params, buf.writer());
309 return buf.getWritten();
307 var w: std.Io.Writer = .fixed(str);
308 serializeTo(params, &w) catch |err| switch (err) {
309 error.WriteFailed => return error.NoSpaceLeft,
310 else => |e| return e,
311 };
312 return w.buffered();
310313 }
311314
312315 /// Compute the number of bytes required to serialize `params`
313316 pub fn calcSize(params: anytype) usize {
314317 var trash: [128]u8 = undefined;
315318 var d: std.Io.Writer.Discarding = .init(&trash);
316 serializeTo(params, &d) catch unreachable;
319 serializeTo(params, &d.writer) catch unreachable;
317320 return @intCast(d.fullCount());
318321 }
319322
320 fn serializeTo(params: anytype, out: anytype) !void {
323 fn serializeTo(params: anytype, w: *std.Io.Writer) !void {
321324 var header: [14]u8 = undefined;
322325 header[0..3].* = prefix.*;
323326 Codec.intEncode(header[3..4], params.ln);
324327 Codec.intEncode(header[4..9], params.r);
325328 Codec.intEncode(header[9..14], params.p);
326 try out.writeAll(&header);
327 try out.writeAll(params.salt);
328 try out.writeAll("$");
329 try w.writeAll(&header);
330 try w.writeAll(params.salt);
331 try w.writeAll("$");
329332 var buf: [@TypeOf(params.hash).max_encoded_length]u8 = undefined;
330333 const hash_str = try params.hash.toB64(&buf);
331 try out.writeAll(hash_str);
334 try w.writeAll(hash_str);
332335 }
333336
334337 /// Custom codec that maps 6 bits into 8 like regular Base64, but uses its own alphabet,
lib/std/crypto/sha2.zig-12
......@@ -373,18 +373,6 @@ fn Sha2x32(comptime iv: Iv32, digest_bits: comptime_int) type {
373373
374374 for (&d.s, v) |*dv, vv| dv.* +%= vv;
375375 }
376
377 pub const Error = error{};
378 pub const Writer = std.io.GenericWriter(*Self, Error, write);
379
380 fn write(self: *Self, bytes: []const u8) Error!usize {
381 self.update(bytes);
382 return bytes.len;
383 }
384
385 pub fn writer(self: *Self) Writer {
386 return .{ .context = self };
387 }
388376 };
389377}
390378
lib/std/crypto/sha3.zig-60
......@@ -80,18 +80,6 @@ pub fn Keccak(comptime f: u11, comptime output_bits: u11, comptime default_delim
8080 self.st.pad();
8181 self.st.squeeze(out[0..]);
8282 }
83
84 pub const Error = error{};
85 pub const Writer = std.io.GenericWriter(*Self, Error, write);
86
87 fn write(self: *Self, bytes: []const u8) Error!usize {
88 self.update(bytes);
89 return bytes.len;
90 }
91
92 pub fn writer(self: *Self) Writer {
93 return .{ .context = self };
94 }
9583 };
9684}
9785
......@@ -191,18 +179,6 @@ fn ShakeLike(comptime security_level: u11, comptime default_delim: u8, comptime
191179 pub fn fillBlock(self: *Self) void {
192180 self.st.fillBlock();
193181 }
194
195 pub const Error = error{};
196 pub const Writer = std.io.GenericWriter(*Self, Error, write);
197
198 fn write(self: *Self, bytes: []const u8) Error!usize {
199 self.update(bytes);
200 return bytes.len;
201 }
202
203 pub fn writer(self: *Self) Writer {
204 return .{ .context = self };
205 }
206182 };
207183}
208184
......@@ -284,18 +260,6 @@ fn CShakeLike(comptime security_level: u11, comptime default_delim: u8, comptime
284260 pub fn fillBlock(self: *Self) void {
285261 self.shaker.fillBlock();
286262 }
287
288 pub const Error = error{};
289 pub const Writer = std.io.GenericWriter(*Self, Error, write);
290
291 fn write(self: *Self, bytes: []const u8) Error!usize {
292 self.update(bytes);
293 return bytes.len;
294 }
295
296 pub fn writer(self: *Self) Writer {
297 return .{ .context = self };
298 }
299263 };
300264}
301265
......@@ -390,18 +354,6 @@ fn KMacLike(comptime security_level: u11, comptime default_delim: u8, comptime r
390354 ctx.update(msg);
391355 ctx.final(out);
392356 }
393
394 pub const Error = error{};
395 pub const Writer = std.io.GenericWriter(*Self, Error, write);
396
397 fn write(self: *Self, bytes: []const u8) Error!usize {
398 self.update(bytes);
399 return bytes.len;
400 }
401
402 pub fn writer(self: *Self) Writer {
403 return .{ .context = self };
404 }
405357 };
406358}
407359
......@@ -482,18 +434,6 @@ fn TupleHashLike(comptime security_level: u11, comptime default_delim: u8, compt
482434 }
483435 self.cshaker.squeeze(out);
484436 }
485
486 pub const Error = error{};
487 pub const Writer = std.io.GenericWriter(*Self, Error, write);
488
489 fn write(self: *Self, bytes: []const u8) Error!usize {
490 self.update(bytes);
491 return bytes.len;
492 }
493
494 pub fn writer(self: *Self) Writer {
495 return .{ .context = self };
496 }
497437 };
498438}
499439
lib/std/crypto/siphash.zig-12
......@@ -238,18 +238,6 @@ fn SipHash(comptime T: type, comptime c_rounds: usize, comptime d_rounds: usize)
238238 pub fn toInt(msg: []const u8, key: *const [key_length]u8) T {
239239 return State.hash(msg, key);
240240 }
241
242 pub const Error = error{};
243 pub const Writer = std.io.GenericWriter(*Self, Error, write);
244
245 fn write(self: *Self, bytes: []const u8) Error!usize {
246 self.update(bytes);
247 return bytes.len;
248 }
249
250 pub fn writer(self: *Self) Writer {
251 return .{ .context = self };
252 }
253241 };
254242}
255243
lib/std/debug/Dwarf/expression.zig+101-100
......@@ -8,6 +8,8 @@ const OP = std.dwarf.OP;
88const abi = std.debug.Dwarf.abi;
99const mem = std.mem;
1010const assert = std.debug.assert;
11const testing = std.testing;
12const Writer = std.Io.Writer;
1113
1214/// Expressions can be evaluated in different contexts, each requiring its own set of inputs.
1315/// Callers should specify all the fields relevant to their context. If a field is required
......@@ -782,7 +784,7 @@ pub fn Builder(comptime options: Options) type {
782784
783785 return struct {
784786 /// Zero-operand instructions
785 pub fn writeOpcode(writer: anytype, comptime opcode: u8) !void {
787 pub fn writeOpcode(writer: *Writer, comptime opcode: u8) !void {
786788 if (options.call_frame_context and !comptime isOpcodeValidInCFA(opcode)) return error.InvalidCFAOpcode;
787789 switch (opcode) {
788790 OP.dup,
......@@ -823,14 +825,14 @@ pub fn Builder(comptime options: Options) type {
823825 }
824826
825827 // 2.5.1.1: Literal Encodings
826 pub fn writeLiteral(writer: anytype, literal: u8) !void {
828 pub fn writeLiteral(writer: *Writer, literal: u8) !void {
827829 switch (literal) {
828830 0...31 => |n| try writer.writeByte(n + OP.lit0),
829831 else => return error.InvalidLiteral,
830832 }
831833 }
832834
833 pub fn writeConst(writer: anytype, comptime T: type, value: T) !void {
835 pub fn writeConst(writer: *Writer, comptime T: type, value: T) !void {
834836 if (@typeInfo(T) != .int) @compileError("Constants must be integers");
835837
836838 switch (T) {
......@@ -852,7 +854,7 @@ pub fn Builder(comptime options: Options) type {
852854 else => switch (@typeInfo(T).int.signedness) {
853855 .unsigned => {
854856 try writer.writeByte(OP.constu);
855 try leb.writeUleb128(writer, value);
857 try writer.writeUleb128(value);
856858 },
857859 .signed => {
858860 try writer.writeByte(OP.consts);
......@@ -862,105 +864,105 @@ pub fn Builder(comptime options: Options) type {
862864 }
863865 }
864866
865 pub fn writeConstx(writer: anytype, debug_addr_offset: anytype) !void {
867 pub fn writeConstx(writer: *Writer, debug_addr_offset: anytype) !void {
866868 try writer.writeByte(OP.constx);
867 try leb.writeUleb128(writer, debug_addr_offset);
869 try writer.writeUleb128(debug_addr_offset);
868870 }
869871
870 pub fn writeConstType(writer: anytype, die_offset: anytype, value_bytes: []const u8) !void {
872 pub fn writeConstType(writer: *Writer, die_offset: anytype, value_bytes: []const u8) !void {
871873 if (options.call_frame_context) return error.InvalidCFAOpcode;
872874 if (value_bytes.len > 0xff) return error.InvalidTypeLength;
873875 try writer.writeByte(OP.const_type);
874 try leb.writeUleb128(writer, die_offset);
876 try writer.writeUleb128(die_offset);
875877 try writer.writeByte(@intCast(value_bytes.len));
876878 try writer.writeAll(value_bytes);
877879 }
878880
879 pub fn writeAddr(writer: anytype, value: addr_type) !void {
881 pub fn writeAddr(writer: *Writer, value: addr_type) !void {
880882 try writer.writeByte(OP.addr);
881883 try writer.writeInt(addr_type, value, options.endian);
882884 }
883885
884 pub fn writeAddrx(writer: anytype, debug_addr_offset: anytype) !void {
886 pub fn writeAddrx(writer: *Writer, debug_addr_offset: anytype) !void {
885887 if (options.call_frame_context) return error.InvalidCFAOpcode;
886888 try writer.writeByte(OP.addrx);
887 try leb.writeUleb128(writer, debug_addr_offset);
889 try writer.writeUleb128(debug_addr_offset);
888890 }
889891
890892 // 2.5.1.2: Register Values
891 pub fn writeFbreg(writer: anytype, offset: anytype) !void {
893 pub fn writeFbreg(writer: *Writer, offset: anytype) !void {
892894 try writer.writeByte(OP.fbreg);
893895 try leb.writeIleb128(writer, offset);
894896 }
895897
896 pub fn writeBreg(writer: anytype, register: u8, offset: anytype) !void {
898 pub fn writeBreg(writer: *Writer, register: u8, offset: anytype) !void {
897899 if (register > 31) return error.InvalidRegister;
898900 try writer.writeByte(OP.breg0 + register);
899901 try leb.writeIleb128(writer, offset);
900902 }
901903
902 pub fn writeBregx(writer: anytype, register: anytype, offset: anytype) !void {
904 pub fn writeBregx(writer: *Writer, register: anytype, offset: anytype) !void {
903905 try writer.writeByte(OP.bregx);
904 try leb.writeUleb128(writer, register);
906 try writer.writeUleb128(register);
905907 try leb.writeIleb128(writer, offset);
906908 }
907909
908 pub fn writeRegvalType(writer: anytype, register: anytype, offset: anytype) !void {
910 pub fn writeRegvalType(writer: *Writer, register: anytype, offset: anytype) !void {
909911 if (options.call_frame_context) return error.InvalidCFAOpcode;
910912 try writer.writeByte(OP.regval_type);
911 try leb.writeUleb128(writer, register);
912 try leb.writeUleb128(writer, offset);
913 try writer.writeUleb128(register);
914 try writer.writeUleb128(offset);
913915 }
914916
915917 // 2.5.1.3: Stack Operations
916 pub fn writePick(writer: anytype, index: u8) !void {
918 pub fn writePick(writer: *Writer, index: u8) !void {
917919 try writer.writeByte(OP.pick);
918920 try writer.writeByte(index);
919921 }
920922
921 pub fn writeDerefSize(writer: anytype, size: u8) !void {
923 pub fn writeDerefSize(writer: *Writer, size: u8) !void {
922924 try writer.writeByte(OP.deref_size);
923925 try writer.writeByte(size);
924926 }
925927
926 pub fn writeXDerefSize(writer: anytype, size: u8) !void {
928 pub fn writeXDerefSize(writer: *Writer, size: u8) !void {
927929 try writer.writeByte(OP.xderef_size);
928930 try writer.writeByte(size);
929931 }
930932
931 pub fn writeDerefType(writer: anytype, size: u8, die_offset: anytype) !void {
933 pub fn writeDerefType(writer: *Writer, size: u8, die_offset: anytype) !void {
932934 if (options.call_frame_context) return error.InvalidCFAOpcode;
933935 try writer.writeByte(OP.deref_type);
934936 try writer.writeByte(size);
935 try leb.writeUleb128(writer, die_offset);
937 try writer.writeUleb128(die_offset);
936938 }
937939
938 pub fn writeXDerefType(writer: anytype, size: u8, die_offset: anytype) !void {
940 pub fn writeXDerefType(writer: *Writer, size: u8, die_offset: anytype) !void {
939941 try writer.writeByte(OP.xderef_type);
940942 try writer.writeByte(size);
941 try leb.writeUleb128(writer, die_offset);
943 try writer.writeUleb128(die_offset);
942944 }
943945
944946 // 2.5.1.4: Arithmetic and Logical Operations
945947
946 pub fn writePlusUconst(writer: anytype, uint_value: anytype) !void {
948 pub fn writePlusUconst(writer: *Writer, uint_value: anytype) !void {
947949 try writer.writeByte(OP.plus_uconst);
948 try leb.writeUleb128(writer, uint_value);
950 try writer.writeUleb128(uint_value);
949951 }
950952
951953 // 2.5.1.5: Control Flow Operations
952954
953 pub fn writeSkip(writer: anytype, offset: i16) !void {
955 pub fn writeSkip(writer: *Writer, offset: i16) !void {
954956 try writer.writeByte(OP.skip);
955957 try writer.writeInt(i16, offset, options.endian);
956958 }
957959
958 pub fn writeBra(writer: anytype, offset: i16) !void {
960 pub fn writeBra(writer: *Writer, offset: i16) !void {
959961 try writer.writeByte(OP.bra);
960962 try writer.writeInt(i16, offset, options.endian);
961963 }
962964
963 pub fn writeCall(writer: anytype, comptime T: type, offset: T) !void {
965 pub fn writeCall(writer: *Writer, comptime T: type, offset: T) !void {
964966 if (options.call_frame_context) return error.InvalidCFAOpcode;
965967 switch (T) {
966968 u16 => try writer.writeByte(OP.call2),
......@@ -971,45 +973,45 @@ pub fn Builder(comptime options: Options) type {
971973 try writer.writeInt(T, offset, options.endian);
972974 }
973975
974 pub fn writeCallRef(writer: anytype, comptime is_64: bool, value: if (is_64) u64 else u32) !void {
976 pub fn writeCallRef(writer: *Writer, comptime is_64: bool, value: if (is_64) u64 else u32) !void {
975977 if (options.call_frame_context) return error.InvalidCFAOpcode;
976978 try writer.writeByte(OP.call_ref);
977979 try writer.writeInt(if (is_64) u64 else u32, value, options.endian);
978980 }
979981
980 pub fn writeConvert(writer: anytype, die_offset: anytype) !void {
982 pub fn writeConvert(writer: *Writer, die_offset: anytype) !void {
981983 if (options.call_frame_context) return error.InvalidCFAOpcode;
982984 try writer.writeByte(OP.convert);
983 try leb.writeUleb128(writer, die_offset);
985 try writer.writeUleb128(die_offset);
984986 }
985987
986 pub fn writeReinterpret(writer: anytype, die_offset: anytype) !void {
988 pub fn writeReinterpret(writer: *Writer, die_offset: anytype) !void {
987989 if (options.call_frame_context) return error.InvalidCFAOpcode;
988990 try writer.writeByte(OP.reinterpret);
989 try leb.writeUleb128(writer, die_offset);
991 try writer.writeUleb128(die_offset);
990992 }
991993
992994 // 2.5.1.7: Special Operations
993995
994 pub fn writeEntryValue(writer: anytype, expression: []const u8) !void {
996 pub fn writeEntryValue(writer: *Writer, expression: []const u8) !void {
995997 try writer.writeByte(OP.entry_value);
996 try leb.writeUleb128(writer, expression.len);
998 try writer.writeUleb128(expression.len);
997999 try writer.writeAll(expression);
9981000 }
9991001
10001002 // 2.6: Location Descriptions
1001 pub fn writeReg(writer: anytype, register: u8) !void {
1003 pub fn writeReg(writer: *Writer, register: u8) !void {
10021004 try writer.writeByte(OP.reg0 + register);
10031005 }
10041006
1005 pub fn writeRegx(writer: anytype, register: anytype) !void {
1007 pub fn writeRegx(writer: *Writer, register: anytype) !void {
10061008 try writer.writeByte(OP.regx);
1007 try leb.writeUleb128(writer, register);
1009 try writer.writeUleb128(register);
10081010 }
10091011
1010 pub fn writeImplicitValue(writer: anytype, value_bytes: []const u8) !void {
1012 pub fn writeImplicitValue(writer: *Writer, value_bytes: []const u8) !void {
10111013 try writer.writeByte(OP.implicit_value);
1012 try leb.writeUleb128(writer, value_bytes.len);
1014 try writer.writeUleb128(value_bytes.len);
10131015 try writer.writeAll(value_bytes);
10141016 }
10151017 };
......@@ -1042,8 +1044,7 @@ fn isOpcodeRegisterLocation(opcode: u8) bool {
10421044 };
10431045}
10441046
1045const testing = std.testing;
1046test "DWARF expressions" {
1047test "basics" {
10471048 const allocator = std.testing.allocator;
10481049
10491050 const options = Options{};
......@@ -1052,10 +1053,10 @@ test "DWARF expressions" {
10521053
10531054 const b = Builder(options);
10541055
1055 var program = std.array_list.Managed(u8).init(allocator);
1056 var program: std.Io.Writer.Allocating = .init(allocator);
10561057 defer program.deinit();
10571058
1058 const writer = program.writer();
1059 const writer = &program.writer;
10591060
10601061 // Literals
10611062 {
......@@ -1064,7 +1065,7 @@ test "DWARF expressions" {
10641065 try b.writeLiteral(writer, @intCast(i));
10651066 }
10661067
1067 _ = try stack_machine.run(program.items, allocator, context, 0);
1068 _ = try stack_machine.run(program.written(), allocator, context, 0);
10681069
10691070 for (0..32) |i| {
10701071 const expected = 31 - i;
......@@ -1108,16 +1109,16 @@ test "DWARF expressions" {
11081109 var mock_compile_unit: std.debug.Dwarf.CompileUnit = undefined;
11091110 mock_compile_unit.addr_base = 1;
11101111
1111 var mock_debug_addr = std.array_list.Managed(u8).init(allocator);
1112 var mock_debug_addr: std.Io.Writer.Allocating = .init(allocator);
11121113 defer mock_debug_addr.deinit();
11131114
1114 try mock_debug_addr.writer().writeInt(u16, 0, native_endian);
1115 try mock_debug_addr.writer().writeInt(usize, input[11], native_endian);
1116 try mock_debug_addr.writer().writeInt(usize, input[12], native_endian);
1115 try mock_debug_addr.writer.writeInt(u16, 0, native_endian);
1116 try mock_debug_addr.writer.writeInt(usize, input[11], native_endian);
1117 try mock_debug_addr.writer.writeInt(usize, input[12], native_endian);
11171118
1118 const context = Context{
1119 const context: Context = .{
11191120 .compile_unit = &mock_compile_unit,
1120 .debug_addr = mock_debug_addr.items,
1121 .debug_addr = mock_debug_addr.written(),
11211122 };
11221123
11231124 try b.writeConstx(writer, @as(usize, 1));
......@@ -1127,7 +1128,7 @@ test "DWARF expressions" {
11271128 const type_bytes: []const u8 = &.{ 1, 2, 3, 4 };
11281129 try b.writeConstType(writer, die_offset, type_bytes);
11291130
1130 _ = try stack_machine.run(program.items, allocator, context, 0);
1131 _ = try stack_machine.run(program.written(), allocator, context, 0);
11311132
11321133 const const_type = stack_machine.stack.pop().?.const_type;
11331134 try testing.expectEqual(die_offset, const_type.type_offset);
......@@ -1185,7 +1186,7 @@ test "DWARF expressions" {
11851186 try b.writeBregx(writer, abi.ipRegNum(native_arch).?, @as(usize, 300));
11861187 try b.writeRegvalType(writer, @as(u8, 0), @as(usize, 400));
11871188
1188 _ = try stack_machine.run(program.items, allocator, context, 0);
1189 _ = try stack_machine.run(program.written(), allocator, context, 0);
11891190
11901191 const regval_type = stack_machine.stack.pop().?.regval_type;
11911192 try testing.expectEqual(@as(usize, 400), regval_type.type_offset);
......@@ -1214,7 +1215,7 @@ test "DWARF expressions" {
12141215 program.clearRetainingCapacity();
12151216 try b.writeConst(writer, u8, 1);
12161217 try b.writeOpcode(writer, OP.dup);
1217 _ = try stack_machine.run(program.items, allocator, context, null);
1218 _ = try stack_machine.run(program.written(), allocator, context, null);
12181219 try testing.expectEqual(@as(usize, 1), stack_machine.stack.pop().?.generic);
12191220 try testing.expectEqual(@as(usize, 1), stack_machine.stack.pop().?.generic);
12201221
......@@ -1222,7 +1223,7 @@ test "DWARF expressions" {
12221223 program.clearRetainingCapacity();
12231224 try b.writeConst(writer, u8, 1);
12241225 try b.writeOpcode(writer, OP.drop);
1225 _ = try stack_machine.run(program.items, allocator, context, null);
1226 _ = try stack_machine.run(program.written(), allocator, context, null);
12261227 try testing.expect(stack_machine.stack.pop() == null);
12271228
12281229 stack_machine.reset();
......@@ -1231,7 +1232,7 @@ test "DWARF expressions" {
12311232 try b.writeConst(writer, u8, 5);
12321233 try b.writeConst(writer, u8, 6);
12331234 try b.writePick(writer, 2);
1234 _ = try stack_machine.run(program.items, allocator, context, null);
1235 _ = try stack_machine.run(program.written(), allocator, context, null);
12351236 try testing.expectEqual(@as(usize, 4), stack_machine.stack.pop().?.generic);
12361237
12371238 stack_machine.reset();
......@@ -1240,7 +1241,7 @@ test "DWARF expressions" {
12401241 try b.writeConst(writer, u8, 5);
12411242 try b.writeConst(writer, u8, 6);
12421243 try b.writeOpcode(writer, OP.over);
1243 _ = try stack_machine.run(program.items, allocator, context, null);
1244 _ = try stack_machine.run(program.written(), allocator, context, null);
12441245 try testing.expectEqual(@as(usize, 5), stack_machine.stack.pop().?.generic);
12451246
12461247 stack_machine.reset();
......@@ -1248,7 +1249,7 @@ test "DWARF expressions" {
12481249 try b.writeConst(writer, u8, 5);
12491250 try b.writeConst(writer, u8, 6);
12501251 try b.writeOpcode(writer, OP.swap);
1251 _ = try stack_machine.run(program.items, allocator, context, null);
1252 _ = try stack_machine.run(program.written(), allocator, context, null);
12521253 try testing.expectEqual(@as(usize, 5), stack_machine.stack.pop().?.generic);
12531254 try testing.expectEqual(@as(usize, 6), stack_machine.stack.pop().?.generic);
12541255
......@@ -1258,7 +1259,7 @@ test "DWARF expressions" {
12581259 try b.writeConst(writer, u8, 5);
12591260 try b.writeConst(writer, u8, 6);
12601261 try b.writeOpcode(writer, OP.rot);
1261 _ = try stack_machine.run(program.items, allocator, context, null);
1262 _ = try stack_machine.run(program.written(), allocator, context, null);
12621263 try testing.expectEqual(@as(usize, 5), stack_machine.stack.pop().?.generic);
12631264 try testing.expectEqual(@as(usize, 4), stack_machine.stack.pop().?.generic);
12641265 try testing.expectEqual(@as(usize, 6), stack_machine.stack.pop().?.generic);
......@@ -1269,7 +1270,7 @@ test "DWARF expressions" {
12691270 program.clearRetainingCapacity();
12701271 try b.writeAddr(writer, @intFromPtr(&deref_target));
12711272 try b.writeOpcode(writer, OP.deref);
1272 _ = try stack_machine.run(program.items, allocator, context, null);
1273 _ = try stack_machine.run(program.written(), allocator, context, null);
12731274 try testing.expectEqual(deref_target, stack_machine.stack.pop().?.generic);
12741275
12751276 stack_machine.reset();
......@@ -1277,14 +1278,14 @@ test "DWARF expressions" {
12771278 try b.writeLiteral(writer, 0);
12781279 try b.writeAddr(writer, @intFromPtr(&deref_target));
12791280 try b.writeOpcode(writer, OP.xderef);
1280 _ = try stack_machine.run(program.items, allocator, context, null);
1281 _ = try stack_machine.run(program.written(), allocator, context, null);
12811282 try testing.expectEqual(deref_target, stack_machine.stack.pop().?.generic);
12821283
12831284 stack_machine.reset();
12841285 program.clearRetainingCapacity();
12851286 try b.writeAddr(writer, @intFromPtr(&deref_target));
12861287 try b.writeDerefSize(writer, 1);
1287 _ = try stack_machine.run(program.items, allocator, context, null);
1288 _ = try stack_machine.run(program.written(), allocator, context, null);
12881289 try testing.expectEqual(@as(usize, @as(*const u8, @ptrCast(&deref_target)).*), stack_machine.stack.pop().?.generic);
12891290
12901291 stack_machine.reset();
......@@ -1292,7 +1293,7 @@ test "DWARF expressions" {
12921293 try b.writeLiteral(writer, 0);
12931294 try b.writeAddr(writer, @intFromPtr(&deref_target));
12941295 try b.writeXDerefSize(writer, 1);
1295 _ = try stack_machine.run(program.items, allocator, context, null);
1296 _ = try stack_machine.run(program.written(), allocator, context, null);
12961297 try testing.expectEqual(@as(usize, @as(*const u8, @ptrCast(&deref_target)).*), stack_machine.stack.pop().?.generic);
12971298
12981299 const type_offset: usize = @truncate(0xaabbaabb_aabbaabb);
......@@ -1301,7 +1302,7 @@ test "DWARF expressions" {
13011302 program.clearRetainingCapacity();
13021303 try b.writeAddr(writer, @intFromPtr(&deref_target));
13031304 try b.writeDerefType(writer, 1, type_offset);
1304 _ = try stack_machine.run(program.items, allocator, context, null);
1305 _ = try stack_machine.run(program.written(), allocator, context, null);
13051306 const deref_type = stack_machine.stack.pop().?.regval_type;
13061307 try testing.expectEqual(type_offset, deref_type.type_offset);
13071308 try testing.expectEqual(@as(u8, 1), deref_type.type_size);
......@@ -1312,7 +1313,7 @@ test "DWARF expressions" {
13121313 try b.writeLiteral(writer, 0);
13131314 try b.writeAddr(writer, @intFromPtr(&deref_target));
13141315 try b.writeXDerefType(writer, 1, type_offset);
1315 _ = try stack_machine.run(program.items, allocator, context, null);
1316 _ = try stack_machine.run(program.written(), allocator, context, null);
13161317 const xderef_type = stack_machine.stack.pop().?.regval_type;
13171318 try testing.expectEqual(type_offset, xderef_type.type_offset);
13181319 try testing.expectEqual(@as(u8, 1), xderef_type.type_size);
......@@ -1323,7 +1324,7 @@ test "DWARF expressions" {
13231324 stack_machine.reset();
13241325 program.clearRetainingCapacity();
13251326 try b.writeOpcode(writer, OP.push_object_address);
1326 _ = try stack_machine.run(program.items, allocator, context, null);
1327 _ = try stack_machine.run(program.written(), allocator, context, null);
13271328 try testing.expectEqual(@as(usize, @intFromPtr(context.object_address.?)), stack_machine.stack.pop().?.generic);
13281329
13291330 // TODO: Test OP.form_tls_address
......@@ -1333,7 +1334,7 @@ test "DWARF expressions" {
13331334 stack_machine.reset();
13341335 program.clearRetainingCapacity();
13351336 try b.writeOpcode(writer, OP.call_frame_cfa);
1336 _ = try stack_machine.run(program.items, allocator, context, null);
1337 _ = try stack_machine.run(program.written(), allocator, context, null);
13371338 try testing.expectEqual(context.cfa.?, stack_machine.stack.pop().?.generic);
13381339 }
13391340
......@@ -1345,7 +1346,7 @@ test "DWARF expressions" {
13451346 program.clearRetainingCapacity();
13461347 try b.writeConst(writer, i16, -4096);
13471348 try b.writeOpcode(writer, OP.abs);
1348 _ = try stack_machine.run(program.items, allocator, context, null);
1349 _ = try stack_machine.run(program.written(), allocator, context, null);
13491350 try testing.expectEqual(@as(usize, 4096), stack_machine.stack.pop().?.generic);
13501351
13511352 stack_machine.reset();
......@@ -1353,7 +1354,7 @@ test "DWARF expressions" {
13531354 try b.writeConst(writer, u16, 0xff0f);
13541355 try b.writeConst(writer, u16, 0xf0ff);
13551356 try b.writeOpcode(writer, OP.@"and");
1356 _ = try stack_machine.run(program.items, allocator, context, null);
1357 _ = try stack_machine.run(program.written(), allocator, context, null);
13571358 try testing.expectEqual(@as(usize, 0xf00f), stack_machine.stack.pop().?.generic);
13581359
13591360 stack_machine.reset();
......@@ -1361,7 +1362,7 @@ test "DWARF expressions" {
13611362 try b.writeConst(writer, i16, -404);
13621363 try b.writeConst(writer, i16, 100);
13631364 try b.writeOpcode(writer, OP.div);
1364 _ = try stack_machine.run(program.items, allocator, context, null);
1365 _ = try stack_machine.run(program.written(), allocator, context, null);
13651366 try testing.expectEqual(@as(isize, -404 / 100), @as(isize, @bitCast(stack_machine.stack.pop().?.generic)));
13661367
13671368 stack_machine.reset();
......@@ -1369,7 +1370,7 @@ test "DWARF expressions" {
13691370 try b.writeConst(writer, u16, 200);
13701371 try b.writeConst(writer, u16, 50);
13711372 try b.writeOpcode(writer, OP.minus);
1372 _ = try stack_machine.run(program.items, allocator, context, null);
1373 _ = try stack_machine.run(program.written(), allocator, context, null);
13731374 try testing.expectEqual(@as(usize, 150), stack_machine.stack.pop().?.generic);
13741375
13751376 stack_machine.reset();
......@@ -1377,7 +1378,7 @@ test "DWARF expressions" {
13771378 try b.writeConst(writer, u16, 123);
13781379 try b.writeConst(writer, u16, 100);
13791380 try b.writeOpcode(writer, OP.mod);
1380 _ = try stack_machine.run(program.items, allocator, context, null);
1381 _ = try stack_machine.run(program.written(), allocator, context, null);
13811382 try testing.expectEqual(@as(usize, 23), stack_machine.stack.pop().?.generic);
13821383
13831384 stack_machine.reset();
......@@ -1385,7 +1386,7 @@ test "DWARF expressions" {
13851386 try b.writeConst(writer, u16, 0xff);
13861387 try b.writeConst(writer, u16, 0xee);
13871388 try b.writeOpcode(writer, OP.mul);
1388 _ = try stack_machine.run(program.items, allocator, context, null);
1389 _ = try stack_machine.run(program.written(), allocator, context, null);
13891390 try testing.expectEqual(@as(usize, 0xed12), stack_machine.stack.pop().?.generic);
13901391
13911392 stack_machine.reset();
......@@ -1394,7 +1395,7 @@ test "DWARF expressions" {
13941395 try b.writeOpcode(writer, OP.neg);
13951396 try b.writeConst(writer, i16, -6);
13961397 try b.writeOpcode(writer, OP.neg);
1397 _ = try stack_machine.run(program.items, allocator, context, null);
1398 _ = try stack_machine.run(program.written(), allocator, context, null);
13981399 try testing.expectEqual(@as(usize, 6), stack_machine.stack.pop().?.generic);
13991400 try testing.expectEqual(@as(isize, -5), @as(isize, @bitCast(stack_machine.stack.pop().?.generic)));
14001401
......@@ -1402,7 +1403,7 @@ test "DWARF expressions" {
14021403 program.clearRetainingCapacity();
14031404 try b.writeConst(writer, u16, 0xff0f);
14041405 try b.writeOpcode(writer, OP.not);
1405 _ = try stack_machine.run(program.items, allocator, context, null);
1406 _ = try stack_machine.run(program.written(), allocator, context, null);
14061407 try testing.expectEqual(~@as(usize, 0xff0f), stack_machine.stack.pop().?.generic);
14071408
14081409 stack_machine.reset();
......@@ -1410,7 +1411,7 @@ test "DWARF expressions" {
14101411 try b.writeConst(writer, u16, 0xff0f);
14111412 try b.writeConst(writer, u16, 0xf0ff);
14121413 try b.writeOpcode(writer, OP.@"or");
1413 _ = try stack_machine.run(program.items, allocator, context, null);
1414 _ = try stack_machine.run(program.written(), allocator, context, null);
14141415 try testing.expectEqual(@as(usize, 0xffff), stack_machine.stack.pop().?.generic);
14151416
14161417 stack_machine.reset();
......@@ -1418,14 +1419,14 @@ test "DWARF expressions" {
14181419 try b.writeConst(writer, i16, 402);
14191420 try b.writeConst(writer, i16, 100);
14201421 try b.writeOpcode(writer, OP.plus);
1421 _ = try stack_machine.run(program.items, allocator, context, null);
1422 _ = try stack_machine.run(program.written(), allocator, context, null);
14221423 try testing.expectEqual(@as(usize, 502), stack_machine.stack.pop().?.generic);
14231424
14241425 stack_machine.reset();
14251426 program.clearRetainingCapacity();
14261427 try b.writeConst(writer, u16, 4096);
14271428 try b.writePlusUconst(writer, @as(usize, 8192));
1428 _ = try stack_machine.run(program.items, allocator, context, null);
1429 _ = try stack_machine.run(program.written(), allocator, context, null);
14291430 try testing.expectEqual(@as(usize, 4096 + 8192), stack_machine.stack.pop().?.generic);
14301431
14311432 stack_machine.reset();
......@@ -1433,7 +1434,7 @@ test "DWARF expressions" {
14331434 try b.writeConst(writer, u16, 0xfff);
14341435 try b.writeConst(writer, u16, 1);
14351436 try b.writeOpcode(writer, OP.shl);
1436 _ = try stack_machine.run(program.items, allocator, context, null);
1437 _ = try stack_machine.run(program.written(), allocator, context, null);
14371438 try testing.expectEqual(@as(usize, 0xfff << 1), stack_machine.stack.pop().?.generic);
14381439
14391440 stack_machine.reset();
......@@ -1441,7 +1442,7 @@ test "DWARF expressions" {
14411442 try b.writeConst(writer, u16, 0xfff);
14421443 try b.writeConst(writer, u16, 1);
14431444 try b.writeOpcode(writer, OP.shr);
1444 _ = try stack_machine.run(program.items, allocator, context, null);
1445 _ = try stack_machine.run(program.written(), allocator, context, null);
14451446 try testing.expectEqual(@as(usize, 0xfff >> 1), stack_machine.stack.pop().?.generic);
14461447
14471448 stack_machine.reset();
......@@ -1449,7 +1450,7 @@ test "DWARF expressions" {
14491450 try b.writeConst(writer, u16, 0xfff);
14501451 try b.writeConst(writer, u16, 1);
14511452 try b.writeOpcode(writer, OP.shr);
1452 _ = try stack_machine.run(program.items, allocator, context, null);
1453 _ = try stack_machine.run(program.written(), allocator, context, null);
14531454 try testing.expectEqual(@as(usize, @bitCast(@as(isize, 0xfff) >> 1)), stack_machine.stack.pop().?.generic);
14541455
14551456 stack_machine.reset();
......@@ -1457,7 +1458,7 @@ test "DWARF expressions" {
14571458 try b.writeConst(writer, u16, 0xf0ff);
14581459 try b.writeConst(writer, u16, 0xff0f);
14591460 try b.writeOpcode(writer, OP.xor);
1460 _ = try stack_machine.run(program.items, allocator, context, null);
1461 _ = try stack_machine.run(program.written(), allocator, context, null);
14611462 try testing.expectEqual(@as(usize, 0x0ff0), stack_machine.stack.pop().?.generic);
14621463 }
14631464
......@@ -1486,7 +1487,7 @@ test "DWARF expressions" {
14861487 try b.writeConst(writer, u16, 1);
14871488 try b.writeConst(writer, u16, 0);
14881489 try b.writeOpcode(writer, e[0]);
1489 _ = try stack_machine.run(program.items, allocator, context, null);
1490 _ = try stack_machine.run(program.written(), allocator, context, null);
14901491 try testing.expectEqual(@as(usize, e[3]), stack_machine.stack.pop().?.generic);
14911492 try testing.expectEqual(@as(usize, e[2]), stack_machine.stack.pop().?.generic);
14921493 try testing.expectEqual(@as(usize, e[1]), stack_machine.stack.pop().?.generic);
......@@ -1497,7 +1498,7 @@ test "DWARF expressions" {
14971498 try b.writeLiteral(writer, 2);
14981499 try b.writeSkip(writer, 1);
14991500 try b.writeLiteral(writer, 3);
1500 _ = try stack_machine.run(program.items, allocator, context, null);
1501 _ = try stack_machine.run(program.written(), allocator, context, null);
15011502 try testing.expectEqual(@as(usize, 2), stack_machine.stack.pop().?.generic);
15021503
15031504 stack_machine.reset();
......@@ -1509,7 +1510,7 @@ test "DWARF expressions" {
15091510 try b.writeBra(writer, 1);
15101511 try b.writeLiteral(writer, 4);
15111512 try b.writeLiteral(writer, 5);
1512 _ = try stack_machine.run(program.items, allocator, context, null);
1513 _ = try stack_machine.run(program.written(), allocator, context, null);
15131514 try testing.expectEqual(@as(usize, 5), stack_machine.stack.pop().?.generic);
15141515 try testing.expectEqual(@as(usize, 4), stack_machine.stack.pop().?.generic);
15151516 try testing.expect(stack_machine.stack.pop() == null);
......@@ -1535,7 +1536,7 @@ test "DWARF expressions" {
15351536 program.clearRetainingCapacity();
15361537 try b.writeConstType(writer, @as(usize, 0), &value_bytes);
15371538 try b.writeConvert(writer, @as(usize, 0));
1538 _ = try stack_machine.run(program.items, allocator, context, null);
1539 _ = try stack_machine.run(program.written(), allocator, context, null);
15391540 try testing.expectEqual(value, stack_machine.stack.pop().?.generic);
15401541
15411542 // Reinterpret to generic type
......@@ -1543,7 +1544,7 @@ test "DWARF expressions" {
15431544 program.clearRetainingCapacity();
15441545 try b.writeConstType(writer, @as(usize, 0), &value_bytes);
15451546 try b.writeReinterpret(writer, @as(usize, 0));
1546 _ = try stack_machine.run(program.items, allocator, context, null);
1547 _ = try stack_machine.run(program.written(), allocator, context, null);
15471548 try testing.expectEqual(value, stack_machine.stack.pop().?.generic);
15481549
15491550 // Reinterpret to new type
......@@ -1553,7 +1554,7 @@ test "DWARF expressions" {
15531554 program.clearRetainingCapacity();
15541555 try b.writeConstType(writer, @as(usize, 0), &value_bytes);
15551556 try b.writeReinterpret(writer, die_offset);
1556 _ = try stack_machine.run(program.items, allocator, context, null);
1557 _ = try stack_machine.run(program.written(), allocator, context, null);
15571558 const const_type = stack_machine.stack.pop().?.const_type;
15581559 try testing.expectEqual(die_offset, const_type.type_offset);
15591560
......@@ -1561,7 +1562,7 @@ test "DWARF expressions" {
15611562 program.clearRetainingCapacity();
15621563 try b.writeLiteral(writer, 0);
15631564 try b.writeReinterpret(writer, die_offset);
1564 _ = try stack_machine.run(program.items, allocator, context, null);
1565 _ = try stack_machine.run(program.written(), allocator, context, null);
15651566 const regval_type = stack_machine.stack.pop().?.regval_type;
15661567 try testing.expectEqual(die_offset, regval_type.type_offset);
15671568 }
......@@ -1573,20 +1574,20 @@ test "DWARF expressions" {
15731574 stack_machine.reset();
15741575 program.clearRetainingCapacity();
15751576 try b.writeOpcode(writer, OP.nop);
1576 _ = try stack_machine.run(program.items, allocator, context, null);
1577 _ = try stack_machine.run(program.written(), allocator, context, null);
15771578 try testing.expect(stack_machine.stack.pop() == null);
15781579
15791580 // Sub-expression
15801581 {
1581 var sub_program = std.array_list.Managed(u8).init(allocator);
1582 var sub_program: std.Io.Writer.Allocating = .init(allocator);
15821583 defer sub_program.deinit();
1583 const sub_writer = sub_program.writer();
1584 const sub_writer = &sub_program.writer;
15841585 try b.writeLiteral(sub_writer, 3);
15851586
15861587 stack_machine.reset();
15871588 program.clearRetainingCapacity();
1588 try b.writeEntryValue(writer, sub_program.items);
1589 _ = try stack_machine.run(program.items, allocator, context, null);
1589 try b.writeEntryValue(writer, sub_program.written());
1590 _ = try stack_machine.run(program.written(), allocator, context, null);
15901591 try testing.expectEqual(@as(usize, 3), stack_machine.stack.pop().?.generic);
15911592 }
15921593
......@@ -1605,15 +1606,15 @@ test "DWARF expressions" {
16051606 if (abi.regBytes(&thread_context, 0, reg_context)) |reg_bytes| {
16061607 mem.writeInt(usize, reg_bytes[0..@sizeOf(usize)], 0xee, native_endian);
16071608
1608 var sub_program = std.array_list.Managed(u8).init(allocator);
1609 var sub_program: std.Io.Writer.Allocating = .init(allocator);
16091610 defer sub_program.deinit();
1610 const sub_writer = sub_program.writer();
1611 const sub_writer = &sub_program.writer;
16111612 try b.writeReg(sub_writer, 0);
16121613
16131614 stack_machine.reset();
16141615 program.clearRetainingCapacity();
1615 try b.writeEntryValue(writer, sub_program.items);
1616 _ = try stack_machine.run(program.items, allocator, context, null);
1616 try b.writeEntryValue(writer, sub_program.written());
1617 _ = try stack_machine.run(program.written(), allocator, context, null);
16171618 try testing.expectEqual(@as(usize, 0xee), stack_machine.stack.pop().?.generic);
16181619 } else |err| {
16191620 switch (err) {
lib/std/debug/Pdb.zig+185-158
......@@ -2,10 +2,11 @@ const std = @import("../std.zig");
22const File = std.fs.File;
33const Allocator = std.mem.Allocator;
44const pdb = std.pdb;
5const assert = std.debug.assert;
56
67const Pdb = @This();
78
8in_file: File,
9file_reader: *File.Reader,
910msf: Msf,
1011allocator: Allocator,
1112string_table: ?*MsfStream,
......@@ -35,39 +36,38 @@ pub const Module = struct {
3536 }
3637};
3738
38pub fn init(allocator: Allocator, path: []const u8) !Pdb {
39 const file = try std.fs.cwd().openFile(path, .{});
40 errdefer file.close();
41
39pub fn init(gpa: Allocator, file_reader: *File.Reader) !Pdb {
4240 return .{
43 .in_file = file,
44 .allocator = allocator,
41 .file_reader = file_reader,
42 .allocator = gpa,
4543 .string_table = null,
4644 .dbi = null,
47 .msf = try Msf.init(allocator, file),
48 .modules = &[_]Module{},
49 .sect_contribs = &[_]pdb.SectionContribEntry{},
45 .msf = try Msf.init(gpa, file_reader),
46 .modules = &.{},
47 .sect_contribs = &.{},
5048 .guid = undefined,
5149 .age = undefined,
5250 };
5351}
5452
5553pub fn deinit(self: *Pdb) void {
56 self.in_file.close();
57 self.msf.deinit(self.allocator);
54 const gpa = self.allocator;
55 self.msf.deinit(gpa);
5856 for (self.modules) |*module| {
59 module.deinit(self.allocator);
57 module.deinit(gpa);
6058 }
61 self.allocator.free(self.modules);
62 self.allocator.free(self.sect_contribs);
59 gpa.free(self.modules);
60 gpa.free(self.sect_contribs);
6361}
6462
6563pub fn parseDbiStream(self: *Pdb) !void {
6664 var stream = self.getStream(pdb.StreamType.dbi) orelse
6765 return error.InvalidDebugInfo;
68 const reader = stream.reader();
6966
70 const header = try reader.readStruct(std.pdb.DbiStreamHeader);
67 const gpa = self.allocator;
68 const reader = &stream.interface;
69
70 const header = try reader.takeStruct(std.pdb.DbiStreamHeader, .little);
7171 if (header.version_header != 19990903) // V70, only value observed by LLVM team
7272 return error.UnknownPDBVersion;
7373 // if (header.Age != age)
......@@ -76,22 +76,28 @@ pub fn parseDbiStream(self: *Pdb) !void {
7676 const mod_info_size = header.mod_info_size;
7777 const section_contrib_size = header.section_contribution_size;
7878
79 var modules = std.array_list.Managed(Module).init(self.allocator);
79 var modules = std.array_list.Managed(Module).init(gpa);
8080 errdefer modules.deinit();
8181
8282 // Module Info Substream
8383 var mod_info_offset: usize = 0;
8484 while (mod_info_offset != mod_info_size) {
85 const mod_info = try reader.readStruct(pdb.ModInfo);
85 const mod_info = try reader.takeStruct(pdb.ModInfo, .little);
8686 var this_record_len: usize = @sizeOf(pdb.ModInfo);
8787
88 const module_name = try reader.readUntilDelimiterAlloc(self.allocator, 0, 1024);
89 errdefer self.allocator.free(module_name);
90 this_record_len += module_name.len + 1;
88 var module_name: std.Io.Writer.Allocating = .init(gpa);
89 defer module_name.deinit();
90 this_record_len += try reader.streamDelimiterLimit(&module_name.writer, 0, .limited(1024));
91 assert(reader.buffered()[0] == 0); // TODO change streamDelimiterLimit API
92 reader.toss(1);
93 this_record_len += 1;
9194
92 const obj_file_name = try reader.readUntilDelimiterAlloc(self.allocator, 0, 1024);
93 errdefer self.allocator.free(obj_file_name);
94 this_record_len += obj_file_name.len + 1;
95 var obj_file_name: std.Io.Writer.Allocating = .init(gpa);
96 defer obj_file_name.deinit();
97 this_record_len += try reader.streamDelimiterLimit(&obj_file_name.writer, 0, .limited(1024));
98 assert(reader.buffered()[0] == 0); // TODO change streamDelimiterLimit API
99 reader.toss(1);
100 this_record_len += 1;
95101
96102 if (this_record_len % 4 != 0) {
97103 const round_to_next_4 = (this_record_len | 0x3) + 1;
......@@ -100,10 +106,10 @@ pub fn parseDbiStream(self: *Pdb) !void {
100106 this_record_len += march_forward_bytes;
101107 }
102108
103 try modules.append(Module{
109 try modules.append(.{
104110 .mod_info = mod_info,
105 .module_name = module_name,
106 .obj_file_name = obj_file_name,
111 .module_name = try module_name.toOwnedSlice(),
112 .obj_file_name = try obj_file_name.toOwnedSlice(),
107113
108114 .populated = false,
109115 .symbols = undefined,
......@@ -117,21 +123,21 @@ pub fn parseDbiStream(self: *Pdb) !void {
117123 }
118124
119125 // Section Contribution Substream
120 var sect_contribs = std.array_list.Managed(pdb.SectionContribEntry).init(self.allocator);
126 var sect_contribs = std.array_list.Managed(pdb.SectionContribEntry).init(gpa);
121127 errdefer sect_contribs.deinit();
122128
123129 var sect_cont_offset: usize = 0;
124130 if (section_contrib_size != 0) {
125 const version = reader.readEnum(std.pdb.SectionContrSubstreamVersion, .little) catch |err| switch (err) {
126 error.InvalidValue => return error.InvalidDebugInfo,
127 else => |e| return e,
131 const version = reader.takeEnum(std.pdb.SectionContrSubstreamVersion, .little) catch |err| switch (err) {
132 error.InvalidEnumTag, error.EndOfStream => return error.InvalidDebugInfo,
133 error.ReadFailed => return error.ReadFailed,
128134 };
129135 _ = version;
130136 sect_cont_offset += @sizeOf(u32);
131137 }
132138 while (sect_cont_offset != section_contrib_size) {
133139 const entry = try sect_contribs.addOne();
134 entry.* = try reader.readStruct(pdb.SectionContribEntry);
140 entry.* = try reader.takeStruct(pdb.SectionContribEntry, .little);
135141 sect_cont_offset += @sizeOf(pdb.SectionContribEntry);
136142
137143 if (sect_cont_offset > section_contrib_size)
......@@ -143,29 +149,28 @@ pub fn parseDbiStream(self: *Pdb) !void {
143149}
144150
145151pub fn parseInfoStream(self: *Pdb) !void {
146 var stream = self.getStream(pdb.StreamType.pdb) orelse
147 return error.InvalidDebugInfo;
148 const reader = stream.reader();
152 var stream = self.getStream(pdb.StreamType.pdb) orelse return error.InvalidDebugInfo;
153 const reader = &stream.interface;
149154
150155 // Parse the InfoStreamHeader.
151 const version = try reader.readInt(u32, .little);
152 const signature = try reader.readInt(u32, .little);
156 const version = try reader.takeInt(u32, .little);
157 const signature = try reader.takeInt(u32, .little);
153158 _ = signature;
154 const age = try reader.readInt(u32, .little);
155 const guid = try reader.readBytesNoEof(16);
159 const age = try reader.takeInt(u32, .little);
160 const guid = try reader.takeArray(16);
156161
157162 if (version != 20000404) // VC70, only value observed by LLVM team
158163 return error.UnknownPDBVersion;
159164
160 self.guid = guid;
165 self.guid = guid.*;
161166 self.age = age;
162167
168 const gpa = self.allocator;
169
163170 // Find the string table.
164171 const string_table_index = str_tab_index: {
165 const name_bytes_len = try reader.readInt(u32, .little);
166 const name_bytes = try self.allocator.alloc(u8, name_bytes_len);
167 defer self.allocator.free(name_bytes);
168 try reader.readNoEof(name_bytes);
172 const name_bytes_len = try reader.takeInt(u32, .little);
173 const name_bytes = try reader.readAlloc(gpa, name_bytes_len);
169174
170175 const HashTableHeader = extern struct {
171176 size: u32,
......@@ -175,23 +180,23 @@ pub fn parseInfoStream(self: *Pdb) !void {
175180 return cap * 2 / 3 + 1;
176181 }
177182 };
178 const hash_tbl_hdr = try reader.readStruct(HashTableHeader);
183 const hash_tbl_hdr = try reader.takeStruct(HashTableHeader, .little);
179184 if (hash_tbl_hdr.capacity == 0)
180185 return error.InvalidDebugInfo;
181186
182187 if (hash_tbl_hdr.size > HashTableHeader.maxLoad(hash_tbl_hdr.capacity))
183188 return error.InvalidDebugInfo;
184189
185 const present = try readSparseBitVector(&reader, self.allocator);
186 defer self.allocator.free(present);
190 const present = try readSparseBitVector(reader, gpa);
191 defer gpa.free(present);
187192 if (present.len != hash_tbl_hdr.size)
188193 return error.InvalidDebugInfo;
189 const deleted = try readSparseBitVector(&reader, self.allocator);
190 defer self.allocator.free(deleted);
194 const deleted = try readSparseBitVector(reader, gpa);
195 defer gpa.free(deleted);
191196
192197 for (present) |_| {
193 const name_offset = try reader.readInt(u32, .little);
194 const name_index = try reader.readInt(u32, .little);
198 const name_offset = try reader.takeInt(u32, .little);
199 const name_index = try reader.takeInt(u32, .little);
195200 if (name_offset > name_bytes.len)
196201 return error.InvalidDebugInfo;
197202 const name = std.mem.sliceTo(name_bytes[name_offset..], 0);
......@@ -233,6 +238,7 @@ pub fn getSymbolName(self: *Pdb, module: *Module, address: u64) ?[]const u8 {
233238pub fn getLineNumberInfo(self: *Pdb, module: *Module, address: u64) !std.debug.SourceLocation {
234239 std.debug.assert(module.populated);
235240 const subsect_info = module.subsect_info;
241 const gpa = self.allocator;
236242
237243 var sect_offset: usize = 0;
238244 var skip_len: usize = undefined;
......@@ -287,7 +293,16 @@ pub fn getLineNumberInfo(self: *Pdb, module: *Module, address: u64) !std.debug.S
287293 const chksum_hdr: *align(1) pdb.FileChecksumEntryHeader = @ptrCast(&module.subsect_info[subsect_index]);
288294 const strtab_offset = @sizeOf(pdb.StringTableHeader) + chksum_hdr.file_name_offset;
289295 try self.string_table.?.seekTo(strtab_offset);
290 const source_file_name = try self.string_table.?.reader().readUntilDelimiterAlloc(self.allocator, 0, 1024);
296 const source_file_name = s: {
297 const string_reader = &self.string_table.?.interface;
298 var source_file_name: std.Io.Writer.Allocating = .init(gpa);
299 defer source_file_name.deinit();
300 _ = try string_reader.streamDelimiterLimit(&source_file_name.writer, 0, .limited(1024));
301 assert(string_reader.buffered()[0] == 0); // TODO change streamDelimiterLimit API
302 string_reader.toss(1);
303 break :s try source_file_name.toOwnedSlice();
304 };
305 errdefer gpa.free(source_file_name);
291306
292307 const line_entry_idx = line_i - 1;
293308
......@@ -341,19 +356,16 @@ pub fn getModule(self: *Pdb, index: usize) !?*Module {
341356
342357 const stream = self.getStreamById(mod.mod_info.module_sym_stream) orelse
343358 return error.MissingDebugInfo;
344 const reader = stream.reader();
359 const reader = &stream.interface;
345360
346 const signature = try reader.readInt(u32, .little);
361 const signature = try reader.takeInt(u32, .little);
347362 if (signature != 4)
348363 return error.InvalidDebugInfo;
349364
350 mod.symbols = try self.allocator.alloc(u8, mod.mod_info.sym_byte_size - 4);
351 errdefer self.allocator.free(mod.symbols);
352 try reader.readNoEof(mod.symbols);
365 const gpa = self.allocator;
353366
354 mod.subsect_info = try self.allocator.alloc(u8, mod.mod_info.c13_byte_size);
355 errdefer self.allocator.free(mod.subsect_info);
356 try reader.readNoEof(mod.subsect_info);
367 mod.symbols = try reader.readAlloc(gpa, mod.mod_info.sym_byte_size - 4);
368 mod.subsect_info = try reader.readAlloc(gpa, mod.mod_info.c13_byte_size);
357369
358370 var sect_offset: usize = 0;
359371 var skip_len: usize = undefined;
......@@ -379,8 +391,7 @@ pub fn getModule(self: *Pdb, index: usize) !?*Module {
379391}
380392
381393pub fn getStreamById(self: *Pdb, id: u32) ?*MsfStream {
382 if (id >= self.msf.streams.len)
383 return null;
394 if (id >= self.msf.streams.len) return null;
384395 return &self.msf.streams[id];
385396}
386397
......@@ -394,17 +405,14 @@ const Msf = struct {
394405 directory: MsfStream,
395406 streams: []MsfStream,
396407
397 fn init(allocator: Allocator, file: File) !Msf {
398 const in = file.deprecatedReader();
399
400 const superblock = try in.readStruct(pdb.SuperBlock);
408 fn init(gpa: Allocator, file_reader: *File.Reader) !Msf {
409 const superblock = try file_reader.interface.takeStruct(pdb.SuperBlock, .little);
401410
402 // Sanity checks
403411 if (!std.mem.eql(u8, &superblock.file_magic, pdb.SuperBlock.expect_magic))
404412 return error.InvalidDebugInfo;
405413 if (superblock.free_block_map_block != 1 and superblock.free_block_map_block != 2)
406414 return error.InvalidDebugInfo;
407 const file_len = try file.getEndPos();
415 const file_len = try file_reader.getSize();
408416 if (superblock.num_blocks * superblock.block_size != file_len)
409417 return error.InvalidDebugInfo;
410418 switch (superblock.block_size) {
......@@ -417,163 +425,182 @@ const Msf = struct {
417425 if (dir_block_count > superblock.block_size / @sizeOf(u32))
418426 return error.UnhandledBigDirectoryStream; // cf. BlockMapAddr comment.
419427
420 try file.seekTo(superblock.block_size * superblock.block_map_addr);
421 const dir_blocks = try allocator.alloc(u32, dir_block_count);
428 try file_reader.seekTo(superblock.block_size * superblock.block_map_addr);
429 const dir_blocks = try gpa.alloc(u32, dir_block_count);
422430 for (dir_blocks) |*b| {
423 b.* = try in.readInt(u32, .little);
431 b.* = try file_reader.interface.takeInt(u32, .little);
424432 }
425 var directory = MsfStream.init(
426 superblock.block_size,
427 file,
428 dir_blocks,
429 );
433 var directory_buffer: [64]u8 = undefined;
434 var directory = MsfStream.init(superblock.block_size, file_reader, dir_blocks, &directory_buffer);
430435
431 const begin = directory.pos;
432 const stream_count = try directory.reader().readInt(u32, .little);
433 const stream_sizes = try allocator.alloc(u32, stream_count);
434 defer allocator.free(stream_sizes);
436 const begin = directory.logicalPos();
437 const stream_count = try directory.interface.takeInt(u32, .little);
438 const stream_sizes = try gpa.alloc(u32, stream_count);
439 defer gpa.free(stream_sizes);
435440
436441 // Microsoft's implementation uses @as(u32, -1) for inexistent streams.
437442 // These streams are not used, but still participate in the file
438443 // and must be taken into account when resolving stream indices.
439 const Nil = 0xFFFFFFFF;
444 const nil_size = 0xFFFFFFFF;
440445 for (stream_sizes) |*s| {
441 const size = try directory.reader().readInt(u32, .little);
442 s.* = if (size == Nil) 0 else blockCountFromSize(size, superblock.block_size);
446 const size = try directory.interface.takeInt(u32, .little);
447 s.* = if (size == nil_size) 0 else blockCountFromSize(size, superblock.block_size);
443448 }
444449
445 const streams = try allocator.alloc(MsfStream, stream_count);
450 const streams = try gpa.alloc(MsfStream, stream_count);
451 errdefer gpa.free(streams);
452
446453 for (streams, 0..) |*stream, i| {
447454 const size = stream_sizes[i];
448455 if (size == 0) {
449 stream.* = MsfStream{
450 .blocks = &[_]u32{},
451 };
456 stream.* = .empty;
452457 } else {
453 var blocks = try allocator.alloc(u32, size);
454 var j: u32 = 0;
455 while (j < size) : (j += 1) {
456 const block_id = try directory.reader().readInt(u32, .little);
458 const blocks = try gpa.alloc(u32, size);
459 errdefer gpa.free(blocks);
460 for (blocks) |*block| {
461 const block_id = try directory.interface.takeInt(u32, .little);
457462 const n = (block_id % superblock.block_size);
458463 // 0 is for pdb.SuperBlock, 1 and 2 for FPMs.
459464 if (block_id == 0 or n == 1 or n == 2 or block_id * superblock.block_size > file_len)
460465 return error.InvalidBlockIndex;
461 blocks[j] = block_id;
466 block.* = block_id;
462467 }
463
464 stream.* = MsfStream.init(
465 superblock.block_size,
466 file,
467 blocks,
468 );
468 const buffer = try gpa.alloc(u8, 64);
469 errdefer gpa.free(buffer);
470 stream.* = .init(superblock.block_size, file_reader, blocks, buffer);
469471 }
470472 }
471473
472 const end = directory.pos;
474 const end = directory.logicalPos();
473475 if (end - begin != superblock.num_directory_bytes)
474476 return error.InvalidStreamDirectory;
475477
476 return Msf{
478 return .{
477479 .directory = directory,
478480 .streams = streams,
479481 };
480482 }
481483
482 fn deinit(self: *Msf, allocator: Allocator) void {
483 allocator.free(self.directory.blocks);
484 fn deinit(self: *Msf, gpa: Allocator) void {
485 gpa.free(self.directory.blocks);
484486 for (self.streams) |*stream| {
485 allocator.free(stream.blocks);
487 gpa.free(stream.interface.buffer);
488 gpa.free(stream.blocks);
486489 }
487 allocator.free(self.streams);
490 gpa.free(self.streams);
488491 }
489492};
490493
491494const MsfStream = struct {
492 in_file: File = undefined,
493 pos: u64 = undefined,
494 blocks: []u32 = undefined,
495 block_size: u32 = undefined,
496
497 pub const Error = @typeInfo(@typeInfo(@TypeOf(read)).@"fn".return_type.?).error_union.error_set;
495 file_reader: *File.Reader,
496 next_read_pos: u64,
497 blocks: []u32,
498 block_size: u32,
499 interface: std.Io.Reader,
500 err: ?Error,
501
502 const Error = File.Reader.SeekError;
503
504 const empty: MsfStream = .{
505 .file_reader = undefined,
506 .next_read_pos = 0,
507 .blocks = &.{},
508 .block_size = undefined,
509 .interface = .ending_instance,
510 .err = null,
511 };
498512
499 fn init(block_size: u32, file: File, blocks: []u32) MsfStream {
500 const stream = MsfStream{
501 .in_file = file,
502 .pos = 0,
513 fn init(block_size: u32, file_reader: *File.Reader, blocks: []u32, buffer: []u8) MsfStream {
514 return .{
515 .file_reader = file_reader,
516 .next_read_pos = 0,
503517 .blocks = blocks,
504518 .block_size = block_size,
519 .interface = .{
520 .vtable = &.{ .stream = stream },
521 .buffer = buffer,
522 .seek = 0,
523 .end = 0,
524 },
525 .err = null,
505526 };
506
507 return stream;
508527 }
509528
510 fn read(self: *MsfStream, buffer: []u8) !usize {
511 var block_id = @as(usize, @intCast(self.pos / self.block_size));
512 if (block_id >= self.blocks.len) return 0; // End of Stream
513 var block = self.blocks[block_id];
514 var offset = self.pos % self.block_size;
529 fn stream(r: *std.Io.Reader, w: *std.Io.Writer, limit: std.Io.Limit) std.Io.Reader.StreamError!usize {
530 const ms: *MsfStream = @alignCast(@fieldParentPtr("interface", r));
515531
516 try self.in_file.seekTo(block * self.block_size + offset);
517 const in = self.in_file.deprecatedReader();
532 var block_id: usize = @intCast(ms.next_read_pos / ms.block_size);
533 if (block_id >= ms.blocks.len) return error.EndOfStream;
534 var block = ms.blocks[block_id];
535 var offset = ms.next_read_pos % ms.block_size;
518536
519 var size: usize = 0;
520 var rem_buffer = buffer;
521 while (size < buffer.len) {
522 const size_to_read = @min(self.block_size - offset, rem_buffer.len);
523 size += try in.read(rem_buffer[0..size_to_read]);
524 rem_buffer = buffer[size..];
525 offset += size_to_read;
537 ms.file_reader.seekTo(block * ms.block_size + offset) catch |err| {
538 ms.err = err;
539 return error.ReadFailed;
540 };
541
542 var remaining = @intFromEnum(limit);
543 while (remaining != 0) {
544 const stream_len: usize = @min(remaining, ms.block_size - offset);
545 const n = try ms.file_reader.interface.stream(w, .limited(stream_len));
546 remaining -= n;
547 offset += n;
526548
527549 // If we're at the end of a block, go to the next one.
528 if (offset == self.block_size) {
550 if (offset == ms.block_size) {
529551 offset = 0;
530552 block_id += 1;
531 if (block_id >= self.blocks.len) break; // End of Stream
532 block = self.blocks[block_id];
533 try self.in_file.seekTo(block * self.block_size);
553 if (block_id >= ms.blocks.len) break; // End of Stream
554 block = ms.blocks[block_id];
555 ms.file_reader.seekTo(block * ms.block_size) catch |err| {
556 ms.err = err;
557 return error.ReadFailed;
558 };
534559 }
535560 }
536561
537 self.pos += buffer.len;
538 return buffer.len;
562 const total = @intFromEnum(limit) - remaining;
563 ms.next_read_pos += total;
564 return total;
539565 }
540566
541 pub fn seekBy(self: *MsfStream, len: i64) !void {
542 self.pos = @as(u64, @intCast(@as(i64, @intCast(self.pos)) + len));
543 if (self.pos >= self.blocks.len * self.block_size)
544 return error.EOF;
567 pub fn logicalPos(ms: *const MsfStream) u64 {
568 return ms.next_read_pos - ms.interface.bufferedLen();
545569 }
546570
547 pub fn seekTo(self: *MsfStream, len: u64) !void {
548 self.pos = len;
549 if (self.pos >= self.blocks.len * self.block_size)
550 return error.EOF;
571 pub fn seekBy(ms: *MsfStream, len: i64) !void {
572 ms.next_read_pos = @as(u64, @intCast(@as(i64, @intCast(ms.logicalPos())) + len));
573 if (ms.next_read_pos >= ms.blocks.len * ms.block_size) return error.EOF;
574 ms.interface.tossBuffered();
551575 }
552576
553 fn getSize(self: *const MsfStream) u64 {
554 return self.blocks.len * self.block_size;
577 pub fn seekTo(ms: *MsfStream, len: u64) !void {
578 ms.next_read_pos = len;
579 if (ms.next_read_pos >= ms.blocks.len * ms.block_size) return error.EOF;
580 ms.interface.tossBuffered();
555581 }
556582
557 fn getFilePos(self: MsfStream) u64 {
558 const block_id = self.pos / self.block_size;
559 const block = self.blocks[block_id];
560 const offset = self.pos % self.block_size;
561
562 return block * self.block_size + offset;
583 fn getSize(ms: *const MsfStream) u64 {
584 return ms.blocks.len * ms.block_size;
563585 }
564586
565 pub fn reader(self: *MsfStream) std.io.GenericReader(*MsfStream, Error, read) {
566 return .{ .context = self };
587 fn getFilePos(ms: *const MsfStream) u64 {
588 const pos = ms.logicalPos();
589 const block_id = pos / ms.block_size;
590 const block = ms.blocks[block_id];
591 const offset = pos % ms.block_size;
592
593 return block * ms.block_size + offset;
567594 }
568595};
569596
570fn readSparseBitVector(stream: anytype, allocator: Allocator) ![]u32 {
571 const num_words = try stream.readInt(u32, .little);
597fn readSparseBitVector(reader: *std.Io.Reader, allocator: Allocator) ![]u32 {
598 const num_words = try reader.takeInt(u32, .little);
572599 var list = std.array_list.Managed(u32).init(allocator);
573600 errdefer list.deinit();
574601 var word_i: u32 = 0;
575602 while (word_i != num_words) : (word_i += 1) {
576 const word = try stream.readInt(u32, .little);
603 const word = try reader.takeInt(u32, .little);
577604 var bit_i: u5 = 0;
578605 while (true) : (bit_i += 1) {
579606 if (word & (@as(u32, 1) << bit_i) != 0) {
lib/std/debug/SelfInfo.zig+34-17
......@@ -713,22 +713,26 @@ pub const Module = switch (native_os) {
713713 },
714714 .uefi, .windows => struct {
715715 base_address: usize,
716 pdb: ?Pdb = null,
717 dwarf: ?Dwarf = null,
716 pdb: ?Pdb,
717 dwarf: ?Dwarf,
718718 coff_image_base: u64,
719719
720720 /// Only used if pdb is non-null
721721 coff_section_headers: []coff.SectionHeader,
722722
723 pub fn deinit(self: *@This(), allocator: Allocator) void {
723 pub fn deinit(self: *@This(), gpa: Allocator) void {
724724 if (self.dwarf) |*dwarf| {
725 dwarf.deinit(allocator);
725 dwarf.deinit(gpa);
726726 }
727727
728728 if (self.pdb) |*p| {
729 gpa.free(p.file_reader.interface.buffer);
730 gpa.destroy(p.file_reader);
729731 p.deinit();
730 allocator.free(self.coff_section_headers);
732 gpa.free(self.coff_section_headers);
731733 }
734
735 self.* = undefined;
732736 }
733737
734738 fn getSymbolFromPdb(self: *@This(), relocated_address: usize) !?std.debug.Symbol {
......@@ -970,23 +974,25 @@ fn readMachODebugInfo(allocator: Allocator, macho_file: File) !Module {
970974 };
971975}
972976
973fn readCoffDebugInfo(allocator: Allocator, coff_obj: *coff.Coff) !Module {
977fn readCoffDebugInfo(gpa: Allocator, coff_obj: *coff.Coff) !Module {
974978 nosuspend {
975979 var di: Module = .{
976980 .base_address = undefined,
977981 .coff_image_base = coff_obj.getImageBase(),
978982 .coff_section_headers = undefined,
983 .pdb = null,
984 .dwarf = null,
979985 };
980986
981987 if (coff_obj.getSectionByName(".debug_info")) |_| {
982988 // This coff file has embedded DWARF debug info
983989 var sections: Dwarf.SectionArray = Dwarf.null_section_array;
984 errdefer for (sections) |section| if (section) |s| if (s.owned) allocator.free(s.data);
990 errdefer for (sections) |section| if (section) |s| if (s.owned) gpa.free(s.data);
985991
986992 inline for (@typeInfo(Dwarf.Section.Id).@"enum".fields, 0..) |section, i| {
987993 sections[i] = if (coff_obj.getSectionByName("." ++ section.name)) |section_header| blk: {
988994 break :blk .{
989 .data = try coff_obj.getSectionDataAlloc(section_header, allocator),
995 .data = try coff_obj.getSectionDataAlloc(section_header, gpa),
990996 .virtual_address = section_header.virtual_address,
991997 .owned = true,
992998 };
......@@ -999,7 +1005,7 @@ fn readCoffDebugInfo(allocator: Allocator, coff_obj: *coff.Coff) !Module {
9991005 .is_macho = false,
10001006 };
10011007
1002 try Dwarf.open(&dwarf, allocator);
1008 try Dwarf.open(&dwarf, gpa);
10031009 di.dwarf = dwarf;
10041010 }
10051011
......@@ -1008,20 +1014,31 @@ fn readCoffDebugInfo(allocator: Allocator, coff_obj: *coff.Coff) !Module {
10081014 if (fs.path.isAbsolute(raw_path)) {
10091015 break :blk raw_path;
10101016 } else {
1011 const self_dir = try fs.selfExeDirPathAlloc(allocator);
1012 defer allocator.free(self_dir);
1013 break :blk try fs.path.join(allocator, &.{ self_dir, raw_path });
1017 const self_dir = try fs.selfExeDirPathAlloc(gpa);
1018 defer gpa.free(self_dir);
1019 break :blk try fs.path.join(gpa, &.{ self_dir, raw_path });
10141020 }
10151021 };
1016 defer if (path.ptr != raw_path.ptr) allocator.free(path);
1022 defer if (path.ptr != raw_path.ptr) gpa.free(path);
10171023
1018 di.pdb = Pdb.init(allocator, path) catch |err| switch (err) {
1024 const pdb_file = std.fs.cwd().openFile(path, .{}) catch |err| switch (err) {
10191025 error.FileNotFound, error.IsDir => {
10201026 if (di.dwarf == null) return error.MissingDebugInfo;
10211027 return di;
10221028 },
1023 else => return err,
1029 else => |e| return e,
10241030 };
1031 errdefer pdb_file.close();
1032
1033 const pdb_file_reader_buffer = try gpa.alloc(u8, 4096);
1034 errdefer gpa.free(pdb_file_reader_buffer);
1035
1036 const pdb_file_reader = try gpa.create(File.Reader);
1037 errdefer gpa.destroy(pdb_file_reader);
1038
1039 pdb_file_reader.* = pdb_file.reader(pdb_file_reader_buffer);
1040
1041 di.pdb = try Pdb.init(gpa, pdb_file_reader);
10251042 try di.pdb.?.parseInfoStream();
10261043 try di.pdb.?.parseDbiStream();
10271044
......@@ -1029,8 +1046,8 @@ fn readCoffDebugInfo(allocator: Allocator, coff_obj: *coff.Coff) !Module {
10291046 return error.InvalidDebugInfo;
10301047
10311048 // Only used by the pdb path
1032 di.coff_section_headers = try coff_obj.getSectionHeadersAlloc(allocator);
1033 errdefer allocator.free(di.coff_section_headers);
1049 di.coff_section_headers = try coff_obj.getSectionHeadersAlloc(gpa);
1050 errdefer gpa.free(di.coff_section_headers);
10341051
10351052 return di;
10361053 }
lib/std/fs/File.zig-8
......@@ -1097,14 +1097,6 @@ pub fn deprecatedReader(file: File) DeprecatedReader {
10971097 return .{ .context = file };
10981098}
10991099
1100/// Deprecated in favor of `Writer`.
1101pub const DeprecatedWriter = io.GenericWriter(File, WriteError, write);
1102
1103/// Deprecated in favor of `Writer`.
1104pub fn deprecatedWriter(file: File) DeprecatedWriter {
1105 return .{ .context = file };
1106}
1107
11081100/// Memoizes key information about a file handle such as:
11091101/// * The size from calling stat, or the error that occurred therein.
11101102/// * The current seek position.
lib/std/json.zig+1-1
......@@ -6,7 +6,7 @@
66//! The high-level `parseFromSlice` and `parseFromTokenSource` deserialize a JSON document into a Zig type.
77//! Parse into a dynamically-typed `Value` to load any JSON value for runtime inspection.
88//!
9//! The low-level `writeStream` emits syntax-conformant JSON tokens to a `std.io.GenericWriter`.
9//! The low-level `writeStream` emits syntax-conformant JSON tokens to a `std.Io.Writer`.
1010//! The high-level `stringify` serializes a Zig or `Value` type into JSON.
1111
1212const builtin = @import("builtin");
lib/std/leb128.zig-103
......@@ -33,28 +33,6 @@ pub fn readUleb128(comptime T: type, reader: anytype) !T {
3333 return @as(T, @truncate(value));
3434}
3535
36/// Write a single unsigned integer as unsigned LEB128 to the given writer.
37pub fn writeUleb128(writer: anytype, arg: anytype) !void {
38 const Arg = @TypeOf(arg);
39 const Int = switch (Arg) {
40 comptime_int => std.math.IntFittingRange(arg, arg),
41 else => Arg,
42 };
43 const Value = if (@typeInfo(Int).int.bits < 8) u8 else Int;
44 var value: Value = arg;
45
46 while (true) {
47 const byte: u8 = @truncate(value & 0x7f);
48 value >>= 7;
49 if (value == 0) {
50 try writer.writeByte(byte);
51 break;
52 } else {
53 try writer.writeByte(byte | 0x80);
54 }
55 }
56}
57
5836/// Read a single signed LEB128 value from the given reader as type T,
5937/// or error.Overflow if the value cannot fit.
6038pub fn readIleb128(comptime T: type, reader: anytype) !T {
......@@ -374,84 +352,3 @@ test "deserialize unsigned LEB128" {
374352 // Decode sequence of ULEB128 values
375353 try test_read_uleb128_seq(u64, 4, "\x81\x01\x3f\x80\x7f\x80\x80\x80\x00");
376354}
377
378fn test_write_leb128(value: anytype) !void {
379 const T = @TypeOf(value);
380 const signedness = @typeInfo(T).int.signedness;
381 const t_signed = signedness == .signed;
382
383 const writeStream = if (t_signed) writeIleb128 else writeUleb128;
384 const readStream = if (t_signed) readIleb128 else readUleb128;
385
386 // decode to a larger bit size too, to ensure sign extension
387 // is working as expected
388 const larger_type_bits = ((@typeInfo(T).int.bits + 8) / 8) * 8;
389 const B = std.meta.Int(signedness, larger_type_bits);
390
391 const bytes_needed = bn: {
392 if (@typeInfo(T).int.bits <= 7) break :bn @as(u16, 1);
393
394 const unused_bits = if (value < 0) @clz(~value) else @clz(value);
395 const used_bits: u16 = (@typeInfo(T).int.bits - unused_bits) + @intFromBool(t_signed);
396 if (used_bits <= 7) break :bn @as(u16, 1);
397 break :bn ((used_bits + 6) / 7);
398 };
399
400 const max_groups = if (@typeInfo(T).int.bits == 0) 1 else (@typeInfo(T).int.bits + 6) / 7;
401
402 var buf: [max_groups]u8 = undefined;
403 var fbs = std.io.fixedBufferStream(&buf);
404
405 // stream write
406 try writeStream(fbs.writer(), value);
407 const w1_pos = fbs.pos;
408 try testing.expect(w1_pos == bytes_needed);
409
410 // stream read
411 fbs.pos = 0;
412 const sr = try readStream(T, fbs.reader());
413 try testing.expect(fbs.pos == w1_pos);
414 try testing.expect(sr == value);
415
416 // bigger type stream read
417 fbs.pos = 0;
418 const bsr = try readStream(B, fbs.reader());
419 try testing.expect(fbs.pos == w1_pos);
420 try testing.expect(bsr == value);
421}
422
423test "serialize unsigned LEB128" {
424 if (builtin.cpu.arch == .x86 and builtin.abi == .musl and builtin.link_mode == .dynamic) return error.SkipZigTest;
425
426 const max_bits = 18;
427
428 comptime var t = 0;
429 inline while (t <= max_bits) : (t += 1) {
430 const T = std.meta.Int(.unsigned, t);
431 const min = std.math.minInt(T);
432 const max = std.math.maxInt(T);
433 var i = @as(std.meta.Int(.unsigned, @typeInfo(T).int.bits + 1), min);
434
435 while (i <= max) : (i += 1) try test_write_leb128(@as(T, @intCast(i)));
436 }
437}
438
439test "serialize signed LEB128" {
440 if (builtin.cpu.arch == .x86 and builtin.abi == .musl and builtin.link_mode == .dynamic) return error.SkipZigTest;
441
442 // explicitly test i0 because starting `t` at 0
443 // will break the while loop
444 try test_write_leb128(@as(i0, 0));
445
446 const max_bits = 18;
447
448 comptime var t = 1;
449 inline while (t <= max_bits) : (t += 1) {
450 const T = std.meta.Int(.signed, t);
451 const min = std.math.minInt(T);
452 const max = std.math.maxInt(T);
453 var i = @as(std.meta.Int(.signed, @typeInfo(T).int.bits + 1), min);
454
455 while (i <= max) : (i += 1) try test_write_leb128(@as(T, @intCast(i)));
456 }
457}
lib/std/macho.zig-2
......@@ -1883,10 +1883,8 @@ pub const GenericBlob = extern struct {
18831883pub const data_in_code_entry = extern struct {
18841884 /// From mach_header to start of data range.
18851885 offset: u32,
1886
18871886 /// Number of bytes in data range.
18881887 length: u16,
1889
18901888 /// A DICE_KIND value.
18911889 kind: u16,
18921890};
lib/std/posix/test.zig+2-2
......@@ -683,11 +683,11 @@ test "mmap" {
683683 const file = try tmp.dir.createFile(test_out_file, .{});
684684 defer file.close();
685685
686 const stream = file.deprecatedWriter();
686 var stream = file.writer(&.{});
687687
688688 var i: u32 = 0;
689689 while (i < alloc_size / @sizeOf(u32)) : (i += 1) {
690 try stream.writeInt(u32, i, .little);
690 try stream.interface.writeInt(u32, i, .little);
691691 }
692692 }
693693
lib/std/tz.zig+45-44
......@@ -1,6 +1,12 @@
1const std = @import("std.zig");
1//! The Time Zone Information Format (TZif)
2//! https://datatracker.ietf.org/doc/html/rfc8536
3
24const builtin = @import("builtin");
35
6const std = @import("std.zig");
7const Reader = std.Io.Reader;
8const Allocator = std.mem.Allocator;
9
410pub const Transition = struct {
511 ts: i64,
612 timetype: *Timetype,
......@@ -34,7 +40,7 @@ pub const Leapsecond = struct {
3440};
3541
3642pub const Tz = struct {
37 allocator: std.mem.Allocator,
43 allocator: Allocator,
3844 transitions: []const Transition,
3945 timetypes: []const Timetype,
4046 leapseconds: []const Leapsecond,
......@@ -54,34 +60,30 @@ pub const Tz = struct {
5460 },
5561 };
5662
57 pub fn parse(allocator: std.mem.Allocator, reader: anytype) !Tz {
58 var legacy_header = try reader.readStruct(Header);
63 pub fn parse(allocator: Allocator, reader: *Reader) !Tz {
64 const legacy_header = try reader.takeStruct(Header, .big);
5965 if (!std.mem.eql(u8, &legacy_header.magic, "TZif")) return error.BadHeader;
60 if (legacy_header.version != 0 and legacy_header.version != '2' and legacy_header.version != '3') return error.BadVersion;
61
62 if (builtin.target.cpu.arch.endian() != std.builtin.Endian.big) {
63 std.mem.byteSwapAllFields(@TypeOf(legacy_header.counts), &legacy_header.counts);
64 }
66 if (legacy_header.version != 0 and legacy_header.version != '2' and legacy_header.version != '3')
67 return error.BadVersion;
6568
66 if (legacy_header.version == 0) {
69 if (legacy_header.version == 0)
6770 return parseBlock(allocator, reader, legacy_header, true);
68 } else {
69 // If the format is modern, just skip over the legacy data
70 const skipv = legacy_header.counts.timecnt * 5 + legacy_header.counts.typecnt * 6 + legacy_header.counts.charcnt + legacy_header.counts.leapcnt * 8 + legacy_header.counts.isstdcnt + legacy_header.counts.isutcnt;
71 try reader.skipBytes(skipv, .{});
72
73 var header = try reader.readStruct(Header);
74 if (!std.mem.eql(u8, &header.magic, "TZif")) return error.BadHeader;
75 if (header.version != '2' and header.version != '3') return error.BadVersion;
76 if (builtin.target.cpu.arch.endian() != std.builtin.Endian.big) {
77 std.mem.byteSwapAllFields(@TypeOf(header.counts), &header.counts);
78 }
7971
80 return parseBlock(allocator, reader, header, false);
81 }
72 // If the format is modern, just skip over the legacy data
73 const skip_n = legacy_header.counts.timecnt * 5 +
74 legacy_header.counts.typecnt * 6 +
75 legacy_header.counts.charcnt + legacy_header.counts.leapcnt * 8 +
76 legacy_header.counts.isstdcnt + legacy_header.counts.isutcnt;
77 try reader.discardAll(skip_n);
78
79 var header = try reader.takeStruct(Header, .big);
80 if (!std.mem.eql(u8, &header.magic, "TZif")) return error.BadHeader;
81 if (header.version != '2' and header.version != '3') return error.BadVersion;
82
83 return parseBlock(allocator, reader, header, false);
8284 }
8385
84 fn parseBlock(allocator: std.mem.Allocator, reader: anytype, header: Header, legacy: bool) !Tz {
86 fn parseBlock(allocator: Allocator, reader: *Reader, header: Header, legacy: bool) !Tz {
8587 if (header.counts.isstdcnt != 0 and header.counts.isstdcnt != header.counts.typecnt) return error.Malformed; // rfc8536: isstdcnt [...] MUST either be zero or equal to "typecnt"
8688 if (header.counts.isutcnt != 0 and header.counts.isutcnt != header.counts.typecnt) return error.Malformed; // rfc8536: isutcnt [...] MUST either be zero or equal to "typecnt"
8789 if (header.counts.typecnt == 0) return error.Malformed; // rfc8536: typecnt [...] MUST NOT be zero
......@@ -98,12 +100,12 @@ pub const Tz = struct {
98100 // Parse transition types
99101 var i: usize = 0;
100102 while (i < header.counts.timecnt) : (i += 1) {
101 transitions[i].ts = if (legacy) try reader.readInt(i32, .big) else try reader.readInt(i64, .big);
103 transitions[i].ts = if (legacy) try reader.takeInt(i32, .big) else try reader.takeInt(i64, .big);
102104 }
103105
104106 i = 0;
105107 while (i < header.counts.timecnt) : (i += 1) {
106 const tt = try reader.readByte();
108 const tt = try reader.takeByte();
107109 if (tt >= timetypes.len) return error.Malformed; // rfc8536: Each type index MUST be in the range [0, "typecnt" - 1]
108110 transitions[i].timetype = &timetypes[tt];
109111 }
......@@ -111,11 +113,11 @@ pub const Tz = struct {
111113 // Parse time types
112114 i = 0;
113115 while (i < header.counts.typecnt) : (i += 1) {
114 const offset = try reader.readInt(i32, .big);
116 const offset = try reader.takeInt(i32, .big);
115117 if (offset < -2147483648) return error.Malformed; // rfc8536: utoff [...] MUST NOT be -2**31
116 const dst = try reader.readByte();
118 const dst = try reader.takeByte();
117119 if (dst != 0 and dst != 1) return error.Malformed; // rfc8536: (is)dst [...] The value MUST be 0 or 1.
118 const idx = try reader.readByte();
120 const idx = try reader.takeByte();
119121 if (idx > header.counts.charcnt - 1) return error.Malformed; // rfc8536: (desig)idx [...] Each index MUST be in the range [0, "charcnt" - 1]
120122 timetypes[i] = .{
121123 .offset = offset,
......@@ -128,7 +130,7 @@ pub const Tz = struct {
128130 }
129131
130132 var designators_data: [256 + 6]u8 = undefined;
131 try reader.readNoEof(designators_data[0..header.counts.charcnt]);
133 try reader.readSliceAll(designators_data[0..header.counts.charcnt]);
132134 const designators = designators_data[0..header.counts.charcnt];
133135 if (designators[designators.len - 1] != 0) return error.Malformed; // rfc8536: charcnt [...] includes the trailing NUL (0x00) octet
134136
......@@ -144,12 +146,12 @@ pub const Tz = struct {
144146 // Parse leap seconds
145147 i = 0;
146148 while (i < header.counts.leapcnt) : (i += 1) {
147 const occur: i64 = if (legacy) try reader.readInt(i32, .big) else try reader.readInt(i64, .big);
149 const occur: i64 = if (legacy) try reader.takeInt(i32, .big) else try reader.takeInt(i64, .big);
148150 if (occur < 0) return error.Malformed; // rfc8536: occur [...] MUST be nonnegative
149151 if (i > 0 and leapseconds[i - 1].occurrence + 2419199 > occur) return error.Malformed; // rfc8536: occur [...] each later value MUST be at least 2419199 greater than the previous value
150152 if (occur > std.math.maxInt(i48)) return error.Malformed; // Unreasonably far into the future
151153
152 const corr = try reader.readInt(i32, .big);
154 const corr = try reader.takeInt(i32, .big);
153155 if (i == 0 and corr != -1 and corr != 1) return error.Malformed; // rfc8536: The correction value in the first leap-second record, if present, MUST be either one (1) or minus one (-1)
154156 if (i > 0 and leapseconds[i - 1].correction != corr + 1 and leapseconds[i - 1].correction != corr - 1) return error.Malformed; // rfc8536: The correction values in adjacent leap-second records MUST differ by exactly one (1)
155157 if (corr > std.math.maxInt(i16)) return error.Malformed; // Unreasonably large correction
......@@ -163,7 +165,7 @@ pub const Tz = struct {
163165 // Parse standard/wall indicators
164166 i = 0;
165167 while (i < header.counts.isstdcnt) : (i += 1) {
166 const stdtime = try reader.readByte();
168 const stdtime = try reader.takeByte();
167169 if (stdtime == 1) {
168170 timetypes[i].flags |= 0x02;
169171 }
......@@ -172,7 +174,7 @@ pub const Tz = struct {
172174 // Parse UT/local indicators
173175 i = 0;
174176 while (i < header.counts.isutcnt) : (i += 1) {
175 const ut = try reader.readByte();
177 const ut = try reader.takeByte();
176178 if (ut == 1) {
177179 timetypes[i].flags |= 0x04;
178180 if (!timetypes[i].standardTimeIndicator()) return error.Malformed; // rfc8536: standard/wall value MUST be one (1) if the UT/local value is one (1)
......@@ -182,9 +184,8 @@ pub const Tz = struct {
182184 // Footer
183185 var footer: ?[]u8 = null;
184186 if (!legacy) {
185 if ((try reader.readByte()) != '\n') return error.Malformed; // An rfc8536 footer must start with a newline
186 var footerdata_buf: [128]u8 = undefined;
187 const footer_mem = reader.readUntilDelimiter(&footerdata_buf, '\n') catch |err| switch (err) {
187 if ((try reader.takeByte()) != '\n') return error.Malformed; // An rfc8536 footer must start with a newline
188 const footer_mem = reader.takeSentinel('\n') catch |err| switch (err) {
188189 error.StreamTooLong => return error.OverlargeFooter, // Read more than 128 bytes, much larger than any reasonable POSIX TZ string
189190 else => return err,
190191 };
......@@ -194,7 +195,7 @@ pub const Tz = struct {
194195 }
195196 errdefer if (footer) |ft| allocator.free(ft);
196197
197 return Tz{
198 return .{
198199 .allocator = allocator,
199200 .transitions = transitions,
200201 .timetypes = timetypes,
......@@ -215,9 +216,9 @@ pub const Tz = struct {
215216
216217test "slim" {
217218 const data = @embedFile("tz/asia_tokyo.tzif");
218 var in_stream = std.io.fixedBufferStream(data);
219 var in_stream: Reader = .fixed(data);
219220
220 var tz = try std.Tz.parse(std.testing.allocator, in_stream.reader());
221 var tz = try std.Tz.parse(std.testing.allocator, &in_stream);
221222 defer tz.deinit();
222223
223224 try std.testing.expectEqual(tz.transitions.len, 9);
......@@ -228,9 +229,9 @@ test "slim" {
228229
229230test "fat" {
230231 const data = @embedFile("tz/antarctica_davis.tzif");
231 var in_stream = std.io.fixedBufferStream(data);
232 var in_stream: Reader = .fixed(data);
232233
233 var tz = try std.Tz.parse(std.testing.allocator, in_stream.reader());
234 var tz = try std.Tz.parse(std.testing.allocator, &in_stream);
234235 defer tz.deinit();
235236
236237 try std.testing.expectEqual(tz.transitions.len, 8);
......@@ -241,9 +242,9 @@ test "fat" {
241242test "legacy" {
242243 // Taken from Slackware 8.0, from 2001
243244 const data = @embedFile("tz/europe_vatican.tzif");
244 var in_stream = std.io.fixedBufferStream(data);
245 var in_stream: Reader = .fixed(data);
245246
246 var tz = try std.Tz.parse(std.testing.allocator, in_stream.reader());
247 var tz = try std.Tz.parse(std.testing.allocator, &in_stream);
247248 defer tz.deinit();
248249
249250 try std.testing.expectEqual(tz.transitions.len, 170);
src/Compilation.zig+10-9
......@@ -5893,15 +5893,16 @@ fn buildGlibcCrtFile(comp: *Compilation, crt_file: glibc.CrtFile, prog_node: std
58935893
58945894fn buildGlibcSharedObjects(comp: *Compilation, prog_node: std.Progress.Node) void {
58955895 defer comp.link_task_queue.finishPrelinkItem(comp);
5896 if (glibc.buildSharedObjects(comp, prog_node)) |_| {
5897 // The job should no longer be queued up since it succeeded.
5898 comp.queued_jobs.glibc_shared_objects = false;
5899 } else |err| switch (err) {
5900 error.AlreadyReported => return,
5901 else => comp.lockAndSetMiscFailure(.glibc_shared_objects, "unable to build glibc shared objects: {s}", .{
5902 @errorName(err),
5903 }),
5904 }
5896 glibc.buildSharedObjects(comp, prog_node) catch unreachable;
5897 //if (glibc.buildSharedObjects(comp, prog_node)) |_| {
5898 // // The job should no longer be queued up since it succeeded.
5899 // comp.queued_jobs.glibc_shared_objects = false;
5900 //} else |err| switch (err) {
5901 // error.AlreadyReported => return,
5902 // else => comp.lockAndSetMiscFailure(.glibc_shared_objects, "unable to build glibc shared objects: {s}", .{
5903 // @errorName(err),
5904 // }),
5905 //}
59055906}
59065907
59075908fn buildFreeBSDCrtFile(comp: *Compilation, crt_file: freebsd.CrtFile, prog_node: std.Progress.Node) void {
src/IncrementalDebugServer.zig+4-4
......@@ -76,7 +76,9 @@ fn runThread(ids: *IncrementalDebugServer) void {
7676 ids.mutex.lock();
7777 }
7878 defer ids.mutex.unlock();
79 handleCommand(ids.zcu, &text_out, cmd, arg) catch @panic("IncrementalDebugServer: out of memory");
79 var allocating: std.Io.Writer.Allocating = .fromArrayList(gpa, &text_out);
80 defer text_out = allocating.toArrayList();
81 handleCommand(ids.zcu, &allocating.writer, cmd, arg) catch @panic("IncrementalDebugServer: out of memory");
8082 }
8183 text_out.append(gpa, '\n') catch @panic("IncrementalDebugServer: out of memory");
8284 conn.stream.writeAll(text_out.items) catch @panic("IncrementalDebugServer: failed to write");
......@@ -119,10 +121,8 @@ const help_str: []const u8 =
119121 \\
120122;
121123
122fn handleCommand(zcu: *Zcu, output: *std.ArrayListUnmanaged(u8), cmd_str: []const u8, arg_str: []const u8) Allocator.Error!void {
124fn handleCommand(zcu: *Zcu, w: *std.Io.Writer, cmd_str: []const u8, arg_str: []const u8) error{ WriteFailed, OutOfMemory }!void {
123125 const ip = &zcu.intern_pool;
124 const gpa = zcu.gpa;
125 const w = output.writer(gpa);
126126 if (std.mem.eql(u8, cmd_str, "help")) {
127127 try w.writeAll(help_str);
128128 } else if (std.mem.eql(u8, cmd_str, "summary")) {
src/Package/Fetch.zig+5-5
......@@ -200,7 +200,7 @@ pub const JobQueue = struct {
200200
201201 const hash_slice = hash.toSlice();
202202
203 try buf.writer().print(
203 try buf.print(
204204 \\ pub const {f} = struct {{
205205 \\
206206 , .{std.zig.fmtId(hash_slice)});
......@@ -226,13 +226,13 @@ pub const JobQueue = struct {
226226 }
227227 }
228228
229 try buf.writer().print(
229 try buf.print(
230230 \\ pub const build_root = "{f}";
231231 \\
232232 , .{std.fmt.alt(fetch.package_root, .formatEscapeString)});
233233
234234 if (fetch.has_build_zig) {
235 try buf.writer().print(
235 try buf.print(
236236 \\ pub const build_zig = @import("{f}");
237237 \\
238238 , .{std.zig.fmtString(hash_slice)});
......@@ -245,7 +245,7 @@ pub const JobQueue = struct {
245245 );
246246 for (manifest.dependencies.keys(), manifest.dependencies.values()) |name, dep| {
247247 const h = depDigest(fetch.package_root, jq.global_cache, dep) orelse continue;
248 try buf.writer().print(
248 try buf.print(
249249 " .{{ \"{f}\", \"{f}\" }},\n",
250250 .{ std.zig.fmtString(name), std.zig.fmtString(h.toSlice()) },
251251 );
......@@ -277,7 +277,7 @@ pub const JobQueue = struct {
277277
278278 for (root_manifest.dependencies.keys(), root_manifest.dependencies.values()) |name, dep| {
279279 const h = depDigest(root_fetch.package_root, jq.global_cache, dep) orelse continue;
280 try buf.writer().print(
280 try buf.print(
281281 " .{{ \"{f}\", \"{f}\" }},\n",
282282 .{ std.zig.fmtString(name), std.zig.fmtString(h.toSlice()) },
283283 );
src/arch/riscv64/Emit.zig+1-1
......@@ -31,7 +31,7 @@ pub fn emitMir(emit: *Emit) Error!void {
3131 var lowered_relocs = lowered.relocs;
3232 for (lowered.insts, 0..) |lowered_inst, lowered_index| {
3333 const start_offset: u32 = @intCast(emit.code.items.len);
34 try lowered_inst.encode(emit.code.writer(gpa));
34 std.mem.writeInt(u32, try emit.code.addManyAsArray(gpa, 4), lowered_inst.toU32(), .little);
3535
3636 while (lowered_relocs.len > 0 and
3737 lowered_relocs[0].lowered_inst_index == lowered_index) : ({
src/arch/riscv64/encoding.zig+1-1
......@@ -518,7 +518,7 @@ pub const Instruction = union(Lir.Format) {
518518 };
519519 }
520520
521 pub fn encode(inst: Instruction, writer: anytype) !void {
521 pub fn encode(inst: Instruction, writer: *std.Io.Writer) !void {
522522 try writer.writeInt(u32, inst.toU32(), .little);
523523 }
524524
src/arch/wasm/Emit.zig+46-34
......@@ -3,7 +3,7 @@ const Emit = @This();
33const std = @import("std");
44const assert = std.debug.assert;
55const Allocator = std.mem.Allocator;
6const leb = std.leb;
6const ArrayList = std.ArrayList;
77
88const Wasm = link.File.Wasm;
99const Mir = @import("Mir.zig");
......@@ -15,7 +15,7 @@ const codegen = @import("../../codegen.zig");
1515mir: Mir,
1616wasm: *Wasm,
1717/// The binary representation that will be emitted by this module.
18code: *std.ArrayListUnmanaged(u8),
18code: *ArrayList(u8),
1919
2020pub const Error = error{
2121 OutOfMemory,
......@@ -85,7 +85,7 @@ pub fn lowerToCode(emit: *Emit) Error!void {
8585 if (is_obj) {
8686 @panic("TODO");
8787 } else {
88 leb.writeUleb128(code.fixedWriter(), 1 + @intFromEnum(indirect_func_idx)) catch unreachable;
88 writeUleb128(code, 1 + @intFromEnum(indirect_func_idx));
8989 }
9090 inst += 1;
9191 continue :loop tags[inst];
......@@ -99,7 +99,7 @@ pub fn lowerToCode(emit: *Emit) Error!void {
9999 code.appendAssumeCapacity(@intFromEnum(std.wasm.Opcode.i32_const));
100100 // MIR is lowered during flush, so there is indeed only one thread at this time.
101101 const errors_len = 1 + comp.zcu.?.intern_pool.global_error_set.getNamesFromMainThread().len;
102 leb.writeIleb128(code.fixedWriter(), errors_len) catch unreachable;
102 writeSleb128(code, errors_len);
103103
104104 inst += 1;
105105 continue :loop tags[inst];
......@@ -122,7 +122,7 @@ pub fn lowerToCode(emit: *Emit) Error!void {
122122 continue :loop tags[inst];
123123 } else {
124124 const addr: u32 = wasm.errorNameTableAddr();
125 leb.writeIleb128(code.fixedWriter(), addr) catch unreachable;
125 writeSleb128(code, addr);
126126
127127 inst += 1;
128128 continue :loop tags[inst];
......@@ -131,7 +131,7 @@ pub fn lowerToCode(emit: *Emit) Error!void {
131131 .br_if, .br, .memory_grow, .memory_size => {
132132 try code.ensureUnusedCapacity(gpa, 11);
133133 code.appendAssumeCapacity(@intFromEnum(tags[inst]));
134 leb.writeUleb128(code.fixedWriter(), datas[inst].label) catch unreachable;
134 writeUleb128(code, datas[inst].label);
135135
136136 inst += 1;
137137 continue :loop tags[inst];
......@@ -140,7 +140,7 @@ pub fn lowerToCode(emit: *Emit) Error!void {
140140 .local_get, .local_set, .local_tee => {
141141 try code.ensureUnusedCapacity(gpa, 11);
142142 code.appendAssumeCapacity(@intFromEnum(tags[inst]));
143 leb.writeUleb128(code.fixedWriter(), datas[inst].local) catch unreachable;
143 writeUleb128(code, datas[inst].local);
144144
145145 inst += 1;
146146 continue :loop tags[inst];
......@@ -153,8 +153,8 @@ pub fn lowerToCode(emit: *Emit) Error!void {
153153 try code.ensureUnusedCapacity(gpa, 11 + 10 * labels.len);
154154 code.appendAssumeCapacity(@intFromEnum(std.wasm.Opcode.br_table));
155155 // -1 because default label is not part of length/depth.
156 leb.writeUleb128(code.fixedWriter(), extra.data.length - 1) catch unreachable;
157 for (labels) |label| leb.writeUleb128(code.fixedWriter(), label) catch unreachable;
156 writeUleb128(code, extra.data.length - 1);
157 for (labels) |label| writeUleb128(code, label);
158158
159159 inst += 1;
160160 continue :loop tags[inst];
......@@ -199,9 +199,9 @@ pub fn lowerToCode(emit: *Emit) Error!void {
199199 code.appendNTimesAssumeCapacity(0, 5);
200200 } else {
201201 const index: Wasm.Flush.FuncTypeIndex = .fromTypeIndex(func_ty_index, &wasm.flush_buffer);
202 leb.writeUleb128(code.fixedWriter(), @intFromEnum(index)) catch unreachable;
202 writeUleb128(code, @intFromEnum(index));
203203 }
204 leb.writeUleb128(code.fixedWriter(), @as(u32, 0)) catch unreachable; // table index
204 writeUleb128(code, @as(u32, 0)); // table index
205205
206206 inst += 1;
207207 continue :loop tags[inst];
......@@ -263,7 +263,7 @@ pub fn lowerToCode(emit: *Emit) Error!void {
263263 code.appendNTimesAssumeCapacity(0, 5);
264264 } else {
265265 const sp_global: Wasm.GlobalIndex = .stack_pointer;
266 std.leb.writeUleb128(code.fixedWriter(), @intFromEnum(sp_global)) catch unreachable;
266 writeUleb128(code, @intFromEnum(sp_global));
267267 }
268268
269269 inst += 1;
......@@ -291,7 +291,7 @@ pub fn lowerToCode(emit: *Emit) Error!void {
291291 .i32_const => {
292292 try code.ensureUnusedCapacity(gpa, 6);
293293 code.appendAssumeCapacity(@intFromEnum(std.wasm.Opcode.i32_const));
294 leb.writeIleb128(code.fixedWriter(), datas[inst].imm32) catch unreachable;
294 writeSleb128(code, datas[inst].imm32);
295295
296296 inst += 1;
297297 continue :loop tags[inst];
......@@ -300,7 +300,7 @@ pub fn lowerToCode(emit: *Emit) Error!void {
300300 try code.ensureUnusedCapacity(gpa, 11);
301301 code.appendAssumeCapacity(@intFromEnum(std.wasm.Opcode.i64_const));
302302 const int64: i64 = @bitCast(mir.extraData(Mir.Imm64, datas[inst].payload).data.toInt());
303 leb.writeIleb128(code.fixedWriter(), int64) catch unreachable;
303 writeSleb128(code, int64);
304304
305305 inst += 1;
306306 continue :loop tags[inst];
......@@ -476,33 +476,33 @@ pub fn lowerToCode(emit: *Emit) Error!void {
476476 const extra_index = datas[inst].payload;
477477 const opcode = mir.extra[extra_index];
478478 code.appendAssumeCapacity(@intFromEnum(std.wasm.Opcode.misc_prefix));
479 leb.writeUleb128(code.fixedWriter(), opcode) catch unreachable;
479 writeUleb128(code, opcode);
480480 switch (@as(std.wasm.MiscOpcode, @enumFromInt(opcode))) {
481481 // bulk-memory opcodes
482482 .data_drop => {
483483 const segment = mir.extra[extra_index + 1];
484 leb.writeUleb128(code.fixedWriter(), segment) catch unreachable;
484 writeUleb128(code, segment);
485485
486486 inst += 1;
487487 continue :loop tags[inst];
488488 },
489489 .memory_init => {
490490 const segment = mir.extra[extra_index + 1];
491 leb.writeUleb128(code.fixedWriter(), segment) catch unreachable;
492 leb.writeUleb128(code.fixedWriter(), @as(u32, 0)) catch unreachable; // memory index
491 writeUleb128(code, segment);
492 writeUleb128(code, @as(u32, 0)); // memory index
493493
494494 inst += 1;
495495 continue :loop tags[inst];
496496 },
497497 .memory_fill => {
498 leb.writeUleb128(code.fixedWriter(), @as(u32, 0)) catch unreachable; // memory index
498 writeUleb128(code, @as(u32, 0)); // memory index
499499
500500 inst += 1;
501501 continue :loop tags[inst];
502502 },
503503 .memory_copy => {
504 leb.writeUleb128(code.fixedWriter(), @as(u32, 0)) catch unreachable; // dst memory index
505 leb.writeUleb128(code.fixedWriter(), @as(u32, 0)) catch unreachable; // src memory index
504 writeUleb128(code, @as(u32, 0)); // dst memory index
505 writeUleb128(code, @as(u32, 0)); // src memory index
506506
507507 inst += 1;
508508 continue :loop tags[inst];
......@@ -538,7 +538,7 @@ pub fn lowerToCode(emit: *Emit) Error!void {
538538 const extra_index = datas[inst].payload;
539539 const opcode = mir.extra[extra_index];
540540 code.appendAssumeCapacity(@intFromEnum(std.wasm.Opcode.simd_prefix));
541 leb.writeUleb128(code.fixedWriter(), opcode) catch unreachable;
541 writeUleb128(code, opcode);
542542 switch (@as(std.wasm.SimdOpcode, @enumFromInt(opcode))) {
543543 .v128_store,
544544 .v128_load,
......@@ -824,7 +824,7 @@ pub fn lowerToCode(emit: *Emit) Error!void {
824824 const extra_index = datas[inst].payload;
825825 const opcode = mir.extra[extra_index];
826826 code.appendAssumeCapacity(@intFromEnum(std.wasm.Opcode.atomics_prefix));
827 leb.writeUleb128(code.fixedWriter(), opcode) catch unreachable;
827 writeUleb128(code, opcode);
828828 switch (@as(std.wasm.AtomicsOpcode, @enumFromInt(opcode))) {
829829 .i32_atomic_load,
830830 .i64_atomic_load,
......@@ -900,7 +900,7 @@ pub fn lowerToCode(emit: *Emit) Error!void {
900900 // Hard-codes memory index 0 since multi-memory proposal is
901901 // not yet accepted nor implemented.
902902 const memory_index: u32 = 0;
903 leb.writeUleb128(code.fixedWriter(), memory_index) catch unreachable;
903 writeUleb128(code, memory_index);
904904 inst += 1;
905905 continue :loop tags[inst];
906906 },
......@@ -915,15 +915,15 @@ pub fn lowerToCode(emit: *Emit) Error!void {
915915}
916916
917917/// Asserts 20 unused capacity.
918fn encodeMemArg(code: *std.ArrayListUnmanaged(u8), mem_arg: Mir.MemArg) void {
918fn encodeMemArg(code: *ArrayList(u8), mem_arg: Mir.MemArg) void {
919919 assert(code.unusedCapacitySlice().len >= 20);
920920 // Wasm encodes alignment as power of 2, rather than natural alignment.
921921 const encoded_alignment = @ctz(mem_arg.alignment);
922 leb.writeUleb128(code.fixedWriter(), encoded_alignment) catch unreachable;
923 leb.writeUleb128(code.fixedWriter(), mem_arg.offset) catch unreachable;
922 writeUleb128(code, encoded_alignment);
923 writeUleb128(code, mem_arg.offset);
924924}
925925
926fn uavRefObj(wasm: *Wasm, code: *std.ArrayListUnmanaged(u8), value: InternPool.Index, offset: i32, is_wasm32: bool) !void {
926fn uavRefObj(wasm: *Wasm, code: *ArrayList(u8), value: InternPool.Index, offset: i32, is_wasm32: bool) !void {
927927 const comp = wasm.base.comp;
928928 const gpa = comp.gpa;
929929 const opcode: std.wasm.Opcode = if (is_wasm32) .i32_const else .i64_const;
......@@ -940,7 +940,7 @@ fn uavRefObj(wasm: *Wasm, code: *std.ArrayListUnmanaged(u8), value: InternPool.I
940940 code.appendNTimesAssumeCapacity(0, if (is_wasm32) 5 else 10);
941941}
942942
943fn uavRefExe(wasm: *Wasm, code: *std.ArrayListUnmanaged(u8), value: InternPool.Index, offset: i32, is_wasm32: bool) !void {
943fn uavRefExe(wasm: *Wasm, code: *ArrayList(u8), value: InternPool.Index, offset: i32, is_wasm32: bool) !void {
944944 const comp = wasm.base.comp;
945945 const gpa = comp.gpa;
946946 const opcode: std.wasm.Opcode = if (is_wasm32) .i32_const else .i64_const;
......@@ -949,10 +949,10 @@ fn uavRefExe(wasm: *Wasm, code: *std.ArrayListUnmanaged(u8), value: InternPool.I
949949 code.appendAssumeCapacity(@intFromEnum(opcode));
950950
951951 const addr = wasm.uavAddr(value);
952 leb.writeUleb128(code.fixedWriter(), @as(u32, @intCast(@as(i64, addr) + offset))) catch unreachable;
952 writeUleb128(code, @as(u32, @intCast(@as(i64, addr) + offset)));
953953}
954954
955fn navRefOff(wasm: *Wasm, code: *std.ArrayListUnmanaged(u8), data: Mir.NavRefOff, is_wasm32: bool) !void {
955fn navRefOff(wasm: *Wasm, code: *ArrayList(u8), data: Mir.NavRefOff, is_wasm32: bool) !void {
956956 const comp = wasm.base.comp;
957957 const zcu = comp.zcu.?;
958958 const ip = &zcu.intern_pool;
......@@ -975,10 +975,22 @@ fn navRefOff(wasm: *Wasm, code: *std.ArrayListUnmanaged(u8), data: Mir.NavRefOff
975975 code.appendNTimesAssumeCapacity(0, if (is_wasm32) 5 else 10);
976976 } else {
977977 const addr = wasm.navAddr(data.nav_index);
978 leb.writeUleb128(code.fixedWriter(), @as(u32, @intCast(@as(i64, addr) + data.offset))) catch unreachable;
978 writeUleb128(code, @as(u32, @intCast(@as(i64, addr) + data.offset)));
979979 }
980980}
981981
982fn appendOutputFunctionIndex(code: *std.ArrayListUnmanaged(u8), i: Wasm.OutputFunctionIndex) void {
983 leb.writeUleb128(code.fixedWriter(), @intFromEnum(i)) catch unreachable;
982fn appendOutputFunctionIndex(code: *ArrayList(u8), i: Wasm.OutputFunctionIndex) void {
983 writeUleb128(code, @intFromEnum(i));
984}
985
986fn writeUleb128(code: *ArrayList(u8), arg: anytype) void {
987 var w: std.Io.Writer = .fixed(code.unusedCapacitySlice());
988 w.writeUleb128(arg) catch unreachable;
989 code.items.len += w.end;
990}
991
992fn writeSleb128(code: *ArrayList(u8), arg: anytype) void {
993 var w: std.Io.Writer = .fixed(code.unusedCapacitySlice());
994 w.writeSleb128(arg) catch unreachable;
995 code.items.len += w.end;
984996}
src/arch/wasm/Mir.zig+22-17
......@@ -675,10 +675,13 @@ pub fn lower(mir: *const Mir, wasm: *Wasm, code: *std.ArrayListUnmanaged(u8)) st
675675 // Write the locals in the prologue of the function body.
676676 try code.ensureUnusedCapacity(gpa, 5 + mir.locals.len * 6 + 38);
677677
678 std.leb.writeUleb128(code.fixedWriter(), @as(u32, @intCast(mir.locals.len))) catch unreachable;
678 var w: std.Io.Writer = .fixed(code.unusedCapacitySlice());
679
680 w.writeLeb128(@as(u32, @intCast(mir.locals.len))) catch unreachable;
681
679682 for (mir.locals) |local| {
680 std.leb.writeUleb128(code.fixedWriter(), @as(u32, 1)) catch unreachable;
681 code.appendAssumeCapacity(@intFromEnum(local));
683 w.writeLeb128(@as(u32, 1)) catch unreachable;
684 w.writeByte(@intFromEnum(local)) catch unreachable;
682685 }
683686
684687 // Stack management section of function prologue.
......@@ -686,33 +689,35 @@ pub fn lower(mir: *const Mir, wasm: *Wasm, code: *std.ArrayListUnmanaged(u8)) st
686689 if (stack_alignment.toByteUnits()) |align_bytes| {
687690 const sp_global: Wasm.GlobalIndex = .stack_pointer;
688691 // load stack pointer
689 code.appendAssumeCapacity(@intFromEnum(std.wasm.Opcode.global_get));
690 std.leb.writeUleb128(code.fixedWriter(), @intFromEnum(sp_global)) catch unreachable;
692 w.writeByte(@intFromEnum(std.wasm.Opcode.global_get)) catch unreachable;
693 w.writeUleb128(@intFromEnum(sp_global)) catch unreachable;
691694 // store stack pointer so we can restore it when we return from the function
692 code.appendAssumeCapacity(@intFromEnum(std.wasm.Opcode.local_tee));
693 leb.writeUleb128(code.fixedWriter(), mir.prologue.sp_local) catch unreachable;
695 w.writeByte(@intFromEnum(std.wasm.Opcode.local_tee)) catch unreachable;
696 w.writeUleb128(mir.prologue.sp_local) catch unreachable;
694697 // get the total stack size
695698 const aligned_stack: i32 = @intCast(stack_alignment.forward(mir.prologue.stack_size));
696 code.appendAssumeCapacity(@intFromEnum(std.wasm.Opcode.i32_const));
697 leb.writeIleb128(code.fixedWriter(), aligned_stack) catch unreachable;
699 w.writeByte(@intFromEnum(std.wasm.Opcode.i32_const)) catch unreachable;
700 w.writeSleb128(aligned_stack) catch unreachable;
698701 // subtract it from the current stack pointer
699 code.appendAssumeCapacity(@intFromEnum(std.wasm.Opcode.i32_sub));
702 w.writeByte(@intFromEnum(std.wasm.Opcode.i32_sub)) catch unreachable;
700703 // Get negative stack alignment
701704 const neg_stack_align = @as(i32, @intCast(align_bytes)) * -1;
702 code.appendAssumeCapacity(@intFromEnum(std.wasm.Opcode.i32_const));
703 leb.writeIleb128(code.fixedWriter(), neg_stack_align) catch unreachable;
705 w.writeByte(@intFromEnum(std.wasm.Opcode.i32_const)) catch unreachable;
706 w.writeSleb128(neg_stack_align) catch unreachable;
704707 // Bitwise-and the value to get the new stack pointer to ensure the
705708 // pointers are aligned with the abi alignment.
706 code.appendAssumeCapacity(@intFromEnum(std.wasm.Opcode.i32_and));
709 w.writeByte(@intFromEnum(std.wasm.Opcode.i32_and)) catch unreachable;
707710 // The bottom will be used to calculate all stack pointer offsets.
708 code.appendAssumeCapacity(@intFromEnum(std.wasm.Opcode.local_tee));
709 leb.writeUleb128(code.fixedWriter(), mir.prologue.bottom_stack_local) catch unreachable;
711 w.writeByte(@intFromEnum(std.wasm.Opcode.local_tee)) catch unreachable;
712 w.writeUleb128(mir.prologue.bottom_stack_local) catch unreachable;
710713 // Store the current stack pointer value into the global stack pointer so other function calls will
711714 // start from this value instead and not overwrite the current stack.
712 code.appendAssumeCapacity(@intFromEnum(std.wasm.Opcode.global_set));
713 std.leb.writeUleb128(code.fixedWriter(), @intFromEnum(sp_global)) catch unreachable;
715 w.writeByte(@intFromEnum(std.wasm.Opcode.global_set)) catch unreachable;
716 w.writeUleb128(@intFromEnum(sp_global)) catch unreachable;
714717 }
715718
719 code.items.len += w.end;
720
716721 var emit: Emit = .{
717722 .mir = mir.*,
718723 .wasm = wasm,
src/codegen.zig+13-12
......@@ -6,6 +6,7 @@ const link = @import("link.zig");
66const log = std.log.scoped(.codegen);
77const mem = std.mem;
88const math = std.math;
9const ArrayList = std.ArrayList;
910const target_util = @import("target.zig");
1011const trace = @import("tracy.zig").trace;
1112
......@@ -179,7 +180,7 @@ pub fn emitFunction(
179180 src_loc: Zcu.LazySrcLoc,
180181 func_index: InternPool.Index,
181182 any_mir: *const AnyMir,
182 code: *std.ArrayListUnmanaged(u8),
183 code: *ArrayList(u8),
183184 debug_output: link.File.DebugInfoOutput,
184185) CodeGenError!void {
185186 const zcu = pt.zcu;
......@@ -204,7 +205,7 @@ pub fn generateLazyFunction(
204205 pt: Zcu.PerThread,
205206 src_loc: Zcu.LazySrcLoc,
206207 lazy_sym: link.File.LazySymbol,
207 code: *std.ArrayListUnmanaged(u8),
208 code: *ArrayList(u8),
208209 debug_output: link.File.DebugInfoOutput,
209210) CodeGenError!void {
210211 const zcu = pt.zcu;
......@@ -236,7 +237,7 @@ pub fn generateLazySymbol(
236237 lazy_sym: link.File.LazySymbol,
237238 // TODO don't use an "out" parameter like this; put it in the result instead
238239 alignment: *Alignment,
239 code: *std.ArrayListUnmanaged(u8),
240 code: *ArrayList(u8),
240241 debug_output: link.File.DebugInfoOutput,
241242 reloc_parent: link.File.RelocInfo.Parent,
242243) CodeGenError!void {
......@@ -311,7 +312,7 @@ pub fn generateSymbol(
311312 pt: Zcu.PerThread,
312313 src_loc: Zcu.LazySrcLoc,
313314 val: Value,
314 code: *std.ArrayListUnmanaged(u8),
315 code: *ArrayList(u8),
315316 reloc_parent: link.File.RelocInfo.Parent,
316317) GenerateSymbolError!void {
317318 const tracy = trace(@src());
......@@ -379,7 +380,7 @@ pub fn generateSymbol(
379380 },
380381 .err => |err| {
381382 const int = try pt.getErrorValue(err.name);
382 try code.writer(gpa).writeInt(u16, @intCast(int), endian);
383 mem.writeInt(u16, try code.addManyAsArray(gpa, 2), @intCast(int), endian);
383384 },
384385 .error_union => |error_union| {
385386 const payload_ty = ty.errorUnionPayload(zcu);
......@@ -389,7 +390,7 @@ pub fn generateSymbol(
389390 };
390391
391392 if (!payload_ty.hasRuntimeBitsIgnoreComptime(zcu)) {
392 try code.writer(gpa).writeInt(u16, err_val, endian);
393 mem.writeInt(u16, try code.addManyAsArray(gpa, 2), err_val, endian);
393394 return;
394395 }
395396
......@@ -399,7 +400,7 @@ pub fn generateSymbol(
399400
400401 // error value first when its type is larger than the error union's payload
401402 if (error_align.order(payload_align) == .gt) {
402 try code.writer(gpa).writeInt(u16, err_val, endian);
403 mem.writeInt(u16, try code.addManyAsArray(gpa, 2), err_val, endian);
403404 }
404405
405406 // emit payload part of the error union
......@@ -421,7 +422,7 @@ pub fn generateSymbol(
421422 // Payload size is larger than error set, so emit our error set last
422423 if (error_align.compare(.lte, payload_align)) {
423424 const begin = code.items.len;
424 try code.writer(gpa).writeInt(u16, err_val, endian);
425 mem.writeInt(u16, try code.addManyAsArray(gpa, 2), err_val, endian);
425426 const unpadded_end = code.items.len - begin;
426427 const padded_end = abi_align.forward(unpadded_end);
427428 const padding = math.cast(usize, padded_end - unpadded_end) orelse return error.Overflow;
......@@ -476,7 +477,7 @@ pub fn generateSymbol(
476477 }));
477478 try generateSymbol(bin_file, pt, src_loc, value, code, reloc_parent);
478479 }
479 try code.writer(gpa).writeByte(@intFromBool(payload_val != null));
480 try code.append(gpa, @intFromBool(payload_val != null));
480481 try code.appendNTimes(gpa, 0, padding);
481482 }
482483 },
......@@ -721,7 +722,7 @@ fn lowerPtr(
721722 pt: Zcu.PerThread,
722723 src_loc: Zcu.LazySrcLoc,
723724 ptr_val: InternPool.Index,
724 code: *std.ArrayListUnmanaged(u8),
725 code: *ArrayList(u8),
725726 reloc_parent: link.File.RelocInfo.Parent,
726727 prev_offset: u64,
727728) GenerateSymbolError!void {
......@@ -774,7 +775,7 @@ fn lowerUavRef(
774775 pt: Zcu.PerThread,
775776 src_loc: Zcu.LazySrcLoc,
776777 uav: InternPool.Key.Ptr.BaseAddr.Uav,
777 code: *std.ArrayListUnmanaged(u8),
778 code: *ArrayList(u8),
778779 reloc_parent: link.File.RelocInfo.Parent,
779780 offset: u64,
780781) GenerateSymbolError!void {
......@@ -834,7 +835,7 @@ fn lowerNavRef(
834835 lf: *link.File,
835836 pt: Zcu.PerThread,
836837 nav_index: InternPool.Nav.Index,
837 code: *std.ArrayListUnmanaged(u8),
838 code: *ArrayList(u8),
838839 reloc_parent: link.File.RelocInfo.Parent,
839840 offset: u64,
840841) GenerateSymbolError!void {
src/libs/freebsd.zig+42-39
......@@ -512,7 +512,7 @@ pub fn buildSharedObjects(comp: *Compilation, prog_node: std.Progress.Node) anye
512512 {
513513 var map_contents = std.array_list.Managed(u8).init(arena);
514514 for (metadata.all_versions[0 .. target_ver_index + 1]) |ver| {
515 try map_contents.writer().print("FBSD_{d}.{d} {{ }};\n", .{ ver.major, ver.minor });
515 try map_contents.print("FBSD_{d}.{d} {{ }};\n", .{ ver.major, ver.minor });
516516 }
517517 try o_directory.handle.writeFile(.{ .sub_path = all_map_basename, .data = map_contents.items });
518518 map_contents.deinit();
......@@ -524,20 +524,17 @@ pub fn buildSharedObjects(comp: *Compilation, prog_node: std.Progress.Node) anye
524524 for (libs, 0..) |lib, lib_i| {
525525 stubs_asm.shrinkRetainingCapacity(0);
526526
527 const stubs_writer = stubs_asm.writer();
528
529 try stubs_writer.writeAll(".text\n");
527 try stubs_asm.appendSlice(".text\n");
530528
531529 var sym_i: usize = 0;
532 var sym_name_buf = std.array_list.Managed(u8).init(arena);
530 var sym_name_buf: std.Io.Writer.Allocating = .init(arena);
533531 var opt_symbol_name: ?[]const u8 = null;
534532 var versions = try std.DynamicBitSetUnmanaged.initEmpty(arena, metadata.all_versions.len);
535533 var weak_linkages = try std.DynamicBitSetUnmanaged.initEmpty(arena, metadata.all_versions.len);
536534
537 var inc_fbs = std.io.fixedBufferStream(metadata.inclusions);
538 var inc_reader = inc_fbs.reader();
535 var inc_reader: std.Io.Reader = .fixed(metadata.inclusions);
539536
540 const fn_inclusions_len = try inc_reader.readInt(u16, .little);
537 const fn_inclusions_len = try inc_reader.takeInt(u16, .little);
541538
542539 // Pick the default symbol version:
543540 // - If there are no versions, don't emit it
......@@ -550,19 +547,21 @@ pub fn buildSharedObjects(comp: *Compilation, prog_node: std.Progress.Node) anye
550547 while (sym_i < fn_inclusions_len) : (sym_i += 1) {
551548 const sym_name = opt_symbol_name orelse n: {
552549 sym_name_buf.clearRetainingCapacity();
553 try inc_reader.streamUntilDelimiter(sym_name_buf.writer(), 0, null);
550 _ = try inc_reader.streamDelimiter(&sym_name_buf.writer, 0);
551 assert(inc_reader.buffered()[0] == 0); // TODO change streamDelimiter API
552 inc_reader.toss(1);
554553
555 opt_symbol_name = sym_name_buf.items;
554 opt_symbol_name = sym_name_buf.written();
556555 versions.unsetAll();
557556 weak_linkages.unsetAll();
558557 chosen_def_ver_index = 255;
559558 chosen_unversioned_ver_index = 255;
560559
561 break :n sym_name_buf.items;
560 break :n sym_name_buf.written();
562561 };
563562 {
564 const targets = try std.leb.readUleb128(u64, inc_reader);
565 var lib_index = try inc_reader.readByte();
563 const targets = try inc_reader.takeLeb128(u64);
564 var lib_index = try inc_reader.takeByte();
566565
567566 const is_unversioned = (lib_index & (1 << 5)) != 0;
568567 const is_weak = (lib_index & (1 << 6)) != 0;
......@@ -576,7 +575,7 @@ pub fn buildSharedObjects(comp: *Compilation, prog_node: std.Progress.Node) anye
576575 ((targets & (@as(u64, 1) << @as(u6, @intCast(target_targ_index)))) != 0);
577576
578577 while (true) {
579 const byte = try inc_reader.readByte();
578 const byte = try inc_reader.takeByte();
580579 const last = (byte & 0b1000_0000) != 0;
581580 const ver_i = @as(u7, @truncate(byte));
582581 if (ok_lib_and_target and ver_i <= target_ver_index) {
......@@ -608,7 +607,7 @@ pub fn buildSharedObjects(comp: *Compilation, prog_node: std.Progress.Node) anye
608607 // .globl _Exit
609608 // .type _Exit, %function
610609 // _Exit: .long 0
611 try stubs_writer.print(
610 try stubs_asm.print(
612611 \\.balign {d}
613612 \\.{s} {s}
614613 \\.type {s}, %function
......@@ -640,7 +639,7 @@ pub fn buildSharedObjects(comp: *Compilation, prog_node: std.Progress.Node) anye
640639 .{ sym_name, ver.major, ver.minor },
641640 );
642641
643 try stubs_writer.print(
642 try stubs_asm.print(
644643 \\.balign {d}
645644 \\.{s} {s}
646645 \\.type {s}, %function
......@@ -665,14 +664,14 @@ pub fn buildSharedObjects(comp: *Compilation, prog_node: std.Progress.Node) anye
665664 }
666665 }
667666
668 try stubs_writer.writeAll(".data\n");
667 try stubs_asm.appendSlice(".data\n");
669668
670669 // FreeBSD's `libc.so.7` contains strong references to `__progname` and `environ` which are
671670 // defined in the statically-linked startup code. Those references cause the linker to put
672671 // the symbols in the dynamic symbol table. We need to create dummy references to them here
673672 // to get the same effect.
674673 if (std.mem.eql(u8, lib.name, "c")) {
675 try stubs_writer.print(
674 try stubs_asm.print(
676675 \\.balign {d}
677676 \\.globl __progname
678677 \\.globl environ
......@@ -686,7 +685,7 @@ pub fn buildSharedObjects(comp: *Compilation, prog_node: std.Progress.Node) anye
686685 });
687686 }
688687
689 const obj_inclusions_len = try inc_reader.readInt(u16, .little);
688 const obj_inclusions_len = try inc_reader.takeInt(u16, .little);
690689
691690 var sizes = try arena.alloc(u16, metadata.all_versions.len);
692691
......@@ -696,21 +695,23 @@ pub fn buildSharedObjects(comp: *Compilation, prog_node: std.Progress.Node) anye
696695 while (sym_i < obj_inclusions_len) : (sym_i += 1) {
697696 const sym_name = opt_symbol_name orelse n: {
698697 sym_name_buf.clearRetainingCapacity();
699 try inc_reader.streamUntilDelimiter(sym_name_buf.writer(), 0, null);
698 _ = try inc_reader.streamDelimiter(&sym_name_buf.writer, 0);
699 assert(inc_reader.buffered()[0] == 0); // TODO change streamDelimiter API
700 inc_reader.toss(1);
700701
701 opt_symbol_name = sym_name_buf.items;
702 opt_symbol_name = sym_name_buf.written();
702703 versions.unsetAll();
703704 weak_linkages.unsetAll();
704705 chosen_def_ver_index = 255;
705706 chosen_unversioned_ver_index = 255;
706707
707 break :n sym_name_buf.items;
708 break :n sym_name_buf.written();
708709 };
709710
710711 {
711 const targets = try std.leb.readUleb128(u64, inc_reader);
712 const size = try std.leb.readUleb128(u16, inc_reader);
713 var lib_index = try inc_reader.readByte();
712 const targets = try inc_reader.takeLeb128(u64);
713 const size = try inc_reader.takeLeb128(u16);
714 var lib_index = try inc_reader.takeByte();
714715
715716 const is_unversioned = (lib_index & (1 << 5)) != 0;
716717 const is_weak = (lib_index & (1 << 6)) != 0;
......@@ -724,7 +725,7 @@ pub fn buildSharedObjects(comp: *Compilation, prog_node: std.Progress.Node) anye
724725 ((targets & (@as(u64, 1) << @as(u6, @intCast(target_targ_index)))) != 0);
725726
726727 while (true) {
727 const byte = try inc_reader.readByte();
728 const byte = try inc_reader.takeByte();
728729 const last = (byte & 0b1000_0000) != 0;
729730 const ver_i = @as(u7, @truncate(byte));
730731 if (ok_lib_and_target and ver_i <= target_ver_index) {
......@@ -758,7 +759,7 @@ pub fn buildSharedObjects(comp: *Compilation, prog_node: std.Progress.Node) anye
758759 // .type malloc_conf, %object
759760 // .size malloc_conf, 4
760761 // malloc_conf: .fill 4, 1, 0
761 try stubs_writer.print(
762 try stubs_asm.print(
762763 \\.balign {d}
763764 \\.{s} {s}
764765 \\.type {s}, %object
......@@ -794,7 +795,7 @@ pub fn buildSharedObjects(comp: *Compilation, prog_node: std.Progress.Node) anye
794795 .{ sym_name, ver.major, ver.minor },
795796 );
796797
797 try stubs_asm.writer().print(
798 try stubs_asm.print(
798799 \\.balign {d}
799800 \\.{s} {s}
800801 \\.type {s}, %object
......@@ -822,9 +823,9 @@ pub fn buildSharedObjects(comp: *Compilation, prog_node: std.Progress.Node) anye
822823 }
823824 }
824825
825 try stubs_writer.writeAll(".tdata\n");
826 try stubs_asm.appendSlice(".tdata\n");
826827
827 const tls_inclusions_len = try inc_reader.readInt(u16, .little);
828 const tls_inclusions_len = try inc_reader.takeInt(u16, .little);
828829
829830 sym_i = 0;
830831 opt_symbol_name = null;
......@@ -832,21 +833,23 @@ pub fn buildSharedObjects(comp: *Compilation, prog_node: std.Progress.Node) anye
832833 while (sym_i < tls_inclusions_len) : (sym_i += 1) {
833834 const sym_name = opt_symbol_name orelse n: {
834835 sym_name_buf.clearRetainingCapacity();
835 try inc_reader.streamUntilDelimiter(sym_name_buf.writer(), 0, null);
836 _ = try inc_reader.streamDelimiter(&sym_name_buf.writer, 0);
837 assert(inc_reader.buffered()[0] == 0); // TODO change streamDelimiter API
838 inc_reader.toss(1);
836839
837 opt_symbol_name = sym_name_buf.items;
840 opt_symbol_name = sym_name_buf.written();
838841 versions.unsetAll();
839842 weak_linkages.unsetAll();
840843 chosen_def_ver_index = 255;
841844 chosen_unversioned_ver_index = 255;
842845
843 break :n sym_name_buf.items;
846 break :n sym_name_buf.written();
844847 };
845848
846849 {
847 const targets = try std.leb.readUleb128(u64, inc_reader);
848 const size = try std.leb.readUleb128(u16, inc_reader);
849 var lib_index = try inc_reader.readByte();
850 const targets = try inc_reader.takeLeb128(u64);
851 const size = try inc_reader.takeLeb128(u16);
852 var lib_index = try inc_reader.takeByte();
850853
851854 const is_unversioned = (lib_index & (1 << 5)) != 0;
852855 const is_weak = (lib_index & (1 << 6)) != 0;
......@@ -860,7 +863,7 @@ pub fn buildSharedObjects(comp: *Compilation, prog_node: std.Progress.Node) anye
860863 ((targets & (@as(u64, 1) << @as(u6, @intCast(target_targ_index)))) != 0);
861864
862865 while (true) {
863 const byte = try inc_reader.readByte();
866 const byte = try inc_reader.takeByte();
864867 const last = (byte & 0b1000_0000) != 0;
865868 const ver_i = @as(u7, @truncate(byte));
866869 if (ok_lib_and_target and ver_i <= target_ver_index) {
......@@ -894,7 +897,7 @@ pub fn buildSharedObjects(comp: *Compilation, prog_node: std.Progress.Node) anye
894897 // .type _ThreadRuneLocale, %object
895898 // .size _ThreadRuneLocale, 4
896899 // _ThreadRuneLocale: .fill 4, 1, 0
897 try stubs_writer.print(
900 try stubs_asm.print(
898901 \\.balign {d}
899902 \\.{s} {s}
900903 \\.type {s}, %tls_object
......@@ -930,7 +933,7 @@ pub fn buildSharedObjects(comp: *Compilation, prog_node: std.Progress.Node) anye
930933 .{ sym_name, ver.major, ver.minor },
931934 );
932935
933 try stubs_writer.print(
936 try stubs_asm.print(
934937 \\.balign {d}
935938 \\.{s} {s}
936939 \\.type {s}, %tls_object
src/libs/glibc.zig+28-25
......@@ -752,9 +752,9 @@ pub fn buildSharedObjects(comp: *Compilation, prog_node: std.Progress.Node) anye
752752 var map_contents = std.array_list.Managed(u8).init(arena);
753753 for (metadata.all_versions[0 .. target_ver_index + 1]) |ver| {
754754 if (ver.patch == 0) {
755 try map_contents.writer().print("GLIBC_{d}.{d} {{ }};\n", .{ ver.major, ver.minor });
755 try map_contents.print("GLIBC_{d}.{d} {{ }};\n", .{ ver.major, ver.minor });
756756 } else {
757 try map_contents.writer().print("GLIBC_{d}.{d}.{d} {{ }};\n", .{ ver.major, ver.minor, ver.patch });
757 try map_contents.print("GLIBC_{d}.{d}.{d} {{ }};\n", .{ ver.major, ver.minor, ver.patch });
758758 }
759759 }
760760 try o_directory.handle.writeFile(.{ .sub_path = all_map_basename, .data = map_contents.items });
......@@ -773,7 +773,7 @@ pub fn buildSharedObjects(comp: *Compilation, prog_node: std.Progress.Node) anye
773773 try stubs_asm.appendSlice(".text\n");
774774
775775 var sym_i: usize = 0;
776 var sym_name_buf = std.array_list.Managed(u8).init(arena);
776 var sym_name_buf: std.Io.Writer.Allocating = .init(arena);
777777 var opt_symbol_name: ?[]const u8 = null;
778778 var versions_buffer: [32]u8 = undefined;
779779 var versions_len: usize = undefined;
......@@ -794,24 +794,25 @@ pub fn buildSharedObjects(comp: *Compilation, prog_node: std.Progress.Node) anye
794794 // twice, which causes a "duplicate symbol" assembler error.
795795 var versions_written = std.AutoArrayHashMap(Version, void).init(arena);
796796
797 var inc_fbs = std.io.fixedBufferStream(metadata.inclusions);
798 var inc_reader = inc_fbs.reader();
797 var inc_reader: std.Io.Reader = .fixed(metadata.inclusions);
799798
800 const fn_inclusions_len = try inc_reader.readInt(u16, .little);
799 const fn_inclusions_len = try inc_reader.takeInt(u16, .little);
801800
802801 while (sym_i < fn_inclusions_len) : (sym_i += 1) {
803802 const sym_name = opt_symbol_name orelse n: {
804803 sym_name_buf.clearRetainingCapacity();
805 try inc_reader.streamUntilDelimiter(sym_name_buf.writer(), 0, null);
804 _ = try inc_reader.streamDelimiter(&sym_name_buf.writer, 0);
805 assert(inc_reader.buffered()[0] == 0); // TODO change streamDelimiter API
806 inc_reader.toss(1);
806807
807 opt_symbol_name = sym_name_buf.items;
808 opt_symbol_name = sym_name_buf.written();
808809 versions_buffer = undefined;
809810 versions_len = 0;
810811
811 break :n sym_name_buf.items;
812 break :n sym_name_buf.written();
812813 };
813 const targets = try std.leb.readUleb128(u64, inc_reader);
814 var lib_index = try inc_reader.readByte();
814 const targets = try inc_reader.takeLeb128(u64);
815 var lib_index = try inc_reader.takeByte();
815816
816817 const is_terminal = (lib_index & (1 << 7)) != 0;
817818 if (is_terminal) {
......@@ -825,7 +826,7 @@ pub fn buildSharedObjects(comp: *Compilation, prog_node: std.Progress.Node) anye
825826 ((targets & (@as(u64, 1) << @as(u6, @intCast(target_targ_index)))) != 0);
826827
827828 while (true) {
828 const byte = try inc_reader.readByte();
829 const byte = try inc_reader.takeByte();
829830 const last = (byte & 0b1000_0000) != 0;
830831 const ver_i = @as(u7, @truncate(byte));
831832 if (ok_lib_and_target and ver_i <= target_ver_index) {
......@@ -880,7 +881,7 @@ pub fn buildSharedObjects(comp: *Compilation, prog_node: std.Progress.Node) anye
880881 "{s}_{d}_{d}",
881882 .{ sym_name, ver.major, ver.minor },
882883 );
883 try stubs_asm.writer().print(
884 try stubs_asm.print(
884885 \\.balign {d}
885886 \\.globl {s}
886887 \\.type {s}, %function
......@@ -905,7 +906,7 @@ pub fn buildSharedObjects(comp: *Compilation, prog_node: std.Progress.Node) anye
905906 "{s}_{d}_{d}_{d}",
906907 .{ sym_name, ver.major, ver.minor, ver.patch },
907908 );
908 try stubs_asm.writer().print(
909 try stubs_asm.print(
909910 \\.balign {d}
910911 \\.globl {s}
911912 \\.type {s}, %function
......@@ -950,7 +951,7 @@ pub fn buildSharedObjects(comp: *Compilation, prog_node: std.Progress.Node) anye
950951 // versions where the symbol didn't exist. We only care about modern glibc versions, so use
951952 // a strong reference.
952953 if (std.mem.eql(u8, lib.name, "c")) {
953 try stubs_asm.writer().print(
954 try stubs_asm.print(
954955 \\.balign {d}
955956 \\.globl _IO_stdin_used
956957 \\{s} _IO_stdin_used
......@@ -963,7 +964,7 @@ pub fn buildSharedObjects(comp: *Compilation, prog_node: std.Progress.Node) anye
963964
964965 try stubs_asm.appendSlice(".data\n");
965966
966 const obj_inclusions_len = try inc_reader.readInt(u16, .little);
967 const obj_inclusions_len = try inc_reader.takeInt(u16, .little);
967968
968969 var sizes = try arena.alloc(u16, metadata.all_versions.len);
969970
......@@ -974,17 +975,19 @@ pub fn buildSharedObjects(comp: *Compilation, prog_node: std.Progress.Node) anye
974975 while (sym_i < obj_inclusions_len) : (sym_i += 1) {
975976 const sym_name = opt_symbol_name orelse n: {
976977 sym_name_buf.clearRetainingCapacity();
977 try inc_reader.streamUntilDelimiter(sym_name_buf.writer(), 0, null);
978 _ = try inc_reader.streamDelimiter(&sym_name_buf.writer, 0);
979 assert(inc_reader.buffered()[0] == 0); // TODO change streamDelimiter API
980 inc_reader.toss(1);
978981
979 opt_symbol_name = sym_name_buf.items;
982 opt_symbol_name = sym_name_buf.written();
980983 versions_buffer = undefined;
981984 versions_len = 0;
982985
983 break :n sym_name_buf.items;
986 break :n sym_name_buf.written();
984987 };
985 const targets = try std.leb.readUleb128(u64, inc_reader);
986 const size = try std.leb.readUleb128(u16, inc_reader);
987 var lib_index = try inc_reader.readByte();
988 const targets = try inc_reader.takeLeb128(u64);
989 const size = try inc_reader.takeLeb128(u16);
990 var lib_index = try inc_reader.takeByte();
988991
989992 const is_terminal = (lib_index & (1 << 7)) != 0;
990993 if (is_terminal) {
......@@ -998,7 +1001,7 @@ pub fn buildSharedObjects(comp: *Compilation, prog_node: std.Progress.Node) anye
9981001 ((targets & (@as(u64, 1) << @as(u6, @intCast(target_targ_index)))) != 0);
9991002
10001003 while (true) {
1001 const byte = try inc_reader.readByte();
1004 const byte = try inc_reader.takeByte();
10021005 const last = (byte & 0b1000_0000) != 0;
10031006 const ver_i = @as(u7, @truncate(byte));
10041007 if (ok_lib_and_target and ver_i <= target_ver_index) {
......@@ -1055,7 +1058,7 @@ pub fn buildSharedObjects(comp: *Compilation, prog_node: std.Progress.Node) anye
10551058 "{s}_{d}_{d}",
10561059 .{ sym_name, ver.major, ver.minor },
10571060 );
1058 try stubs_asm.writer().print(
1061 try stubs_asm.print(
10591062 \\.balign {d}
10601063 \\.globl {s}
10611064 \\.type {s}, %object
......@@ -1083,7 +1086,7 @@ pub fn buildSharedObjects(comp: *Compilation, prog_node: std.Progress.Node) anye
10831086 "{s}_{d}_{d}_{d}",
10841087 .{ sym_name, ver.major, ver.minor, ver.patch },
10851088 );
1086 try stubs_asm.writer().print(
1089 try stubs_asm.print(
10871090 \\.balign {d}
10881091 \\.globl {s}
10891092 \\.type {s}, %object
src/libs/mingw.zig+12-10
......@@ -304,9 +304,8 @@ pub fn buildImportLib(comp: *Compilation, lib_name: []const u8) !void {
304304 const include_dir = try comp.dirs.zig_lib.join(arena, &.{ "libc", "mingw", "def-include" });
305305
306306 if (comp.verbose_cc) print: {
307 std.debug.lockStdErr();
308 defer std.debug.unlockStdErr();
309 const stderr = std.fs.File.stderr().deprecatedWriter();
307 var stderr = std.debug.lockStderrWriter(&.{});
308 defer std.debug.unlockStderrWriter();
310309 nosuspend stderr.print("def file: {s}\n", .{def_file_path}) catch break :print;
311310 nosuspend stderr.print("include dir: {s}\n", .{include_dir}) catch break :print;
312311 nosuspend stderr.print("output path: {s}\n", .{def_final_path}) catch break :print;
......@@ -335,7 +334,10 @@ pub fn buildImportLib(comp: *Compilation, lib_name: []const u8) !void {
335334 // new scope to ensure definition file is written before passing the path to WriteImportLibrary
336335 const def_final_file = try o_dir.createFile(final_def_basename, .{ .truncate = true });
337336 defer def_final_file.close();
338 try pp.prettyPrintTokens(def_final_file.deprecatedWriter(), .result_only);
337 var buffer: [1024]u8 = undefined;
338 var def_final_file_writer = def_final_file.writer(&buffer);
339 try pp.prettyPrintTokens(&def_final_file_writer.interface, .result_only);
340 try def_final_file_writer.interface.flush();
339341 }
340342
341343 const lib_final_path = try std.fs.path.join(gpa, &.{ "o", &digest, final_lib_basename });
......@@ -410,9 +412,9 @@ fn findDef(
410412 // Try the archtecture-specific path first.
411413 const fmt_path = "libc" ++ s ++ "mingw" ++ s ++ "{s}" ++ s ++ "{s}.def";
412414 if (zig_lib_directory.path) |p| {
413 try override_path.writer().print("{s}" ++ s ++ fmt_path, .{ p, lib_path, lib_name });
415 try override_path.print("{s}" ++ s ++ fmt_path, .{ p, lib_path, lib_name });
414416 } else {
415 try override_path.writer().print(fmt_path, .{ lib_path, lib_name });
417 try override_path.print(fmt_path, .{ lib_path, lib_name });
416418 }
417419 if (std.fs.cwd().access(override_path.items, .{})) |_| {
418420 return override_path.toOwnedSlice();
......@@ -427,9 +429,9 @@ fn findDef(
427429 override_path.shrinkRetainingCapacity(0);
428430 const fmt_path = "libc" ++ s ++ "mingw" ++ s ++ "lib-common" ++ s ++ "{s}.def";
429431 if (zig_lib_directory.path) |p| {
430 try override_path.writer().print("{s}" ++ s ++ fmt_path, .{ p, lib_name });
432 try override_path.print("{s}" ++ s ++ fmt_path, .{ p, lib_name });
431433 } else {
432 try override_path.writer().print(fmt_path, .{lib_name});
434 try override_path.print(fmt_path, .{lib_name});
433435 }
434436 if (std.fs.cwd().access(override_path.items, .{})) |_| {
435437 return override_path.toOwnedSlice();
......@@ -444,9 +446,9 @@ fn findDef(
444446 override_path.shrinkRetainingCapacity(0);
445447 const fmt_path = "libc" ++ s ++ "mingw" ++ s ++ "lib-common" ++ s ++ "{s}.def.in";
446448 if (zig_lib_directory.path) |p| {
447 try override_path.writer().print("{s}" ++ s ++ fmt_path, .{ p, lib_name });
449 try override_path.print("{s}" ++ s ++ fmt_path, .{ p, lib_name });
448450 } else {
449 try override_path.writer().print(fmt_path, .{lib_name});
451 try override_path.print(fmt_path, .{lib_name});
450452 }
451453 if (std.fs.cwd().access(override_path.items, .{})) |_| {
452454 return override_path.toOwnedSlice();
src/libs/musl.zig+3-3
......@@ -140,21 +140,21 @@ pub fn buildCrtFile(comp: *Compilation, in_crt_file: CrtFile, prog_node: std.Pro
140140 if (!is_arch_specific) {
141141 // Look for an arch specific override.
142142 override_path.shrinkRetainingCapacity(0);
143 try override_path.writer().print("{s}" ++ s ++ "{s}" ++ s ++ "{s}.s", .{
143 try override_path.print("{s}" ++ s ++ "{s}" ++ s ++ "{s}.s", .{
144144 dirname, arch_name, noextbasename,
145145 });
146146 if (source_table.contains(override_path.items))
147147 continue;
148148
149149 override_path.shrinkRetainingCapacity(0);
150 try override_path.writer().print("{s}" ++ s ++ "{s}" ++ s ++ "{s}.S", .{
150 try override_path.print("{s}" ++ s ++ "{s}" ++ s ++ "{s}.S", .{
151151 dirname, arch_name, noextbasename,
152152 });
153153 if (source_table.contains(override_path.items))
154154 continue;
155155
156156 override_path.shrinkRetainingCapacity(0);
157 try override_path.writer().print("{s}" ++ s ++ "{s}" ++ s ++ "{s}.c", .{
157 try override_path.print("{s}" ++ s ++ "{s}" ++ s ++ "{s}.c", .{
158158 dirname, arch_name, noextbasename,
159159 });
160160 if (source_table.contains(override_path.items))
src/libs/netbsd.zig+25-24
......@@ -460,18 +460,15 @@ pub fn buildSharedObjects(comp: *Compilation, prog_node: std.Progress.Node) anye
460460 for (libs, 0..) |lib, lib_i| {
461461 stubs_asm.shrinkRetainingCapacity(0);
462462
463 const stubs_writer = stubs_asm.writer();
464
465 try stubs_writer.writeAll(".text\n");
463 try stubs_asm.appendSlice(".text\n");
466464
467465 var sym_i: usize = 0;
468 var sym_name_buf = std.array_list.Managed(u8).init(arena);
466 var sym_name_buf: std.Io.Writer.Allocating = .init(arena);
469467 var opt_symbol_name: ?[]const u8 = null;
470468
471 var inc_fbs = std.io.fixedBufferStream(metadata.inclusions);
472 var inc_reader = inc_fbs.reader();
469 var inc_reader: std.Io.Reader = .fixed(metadata.inclusions);
473470
474 const fn_inclusions_len = try inc_reader.readInt(u16, .little);
471 const fn_inclusions_len = try inc_reader.takeInt(u16, .little);
475472
476473 var chosen_ver_index: usize = 255;
477474 var chosen_is_weak: bool = undefined;
......@@ -479,17 +476,19 @@ pub fn buildSharedObjects(comp: *Compilation, prog_node: std.Progress.Node) anye
479476 while (sym_i < fn_inclusions_len) : (sym_i += 1) {
480477 const sym_name = opt_symbol_name orelse n: {
481478 sym_name_buf.clearRetainingCapacity();
482 try inc_reader.streamUntilDelimiter(sym_name_buf.writer(), 0, null);
479 _ = try inc_reader.streamDelimiter(&sym_name_buf.writer, 0);
480 assert(inc_reader.buffered()[0] == 0); // TODO change streamDelimiter API
481 inc_reader.toss(1);
483482
484 opt_symbol_name = sym_name_buf.items;
483 opt_symbol_name = sym_name_buf.written();
485484 chosen_ver_index = 255;
486485
487 break :n sym_name_buf.items;
486 break :n sym_name_buf.written();
488487 };
489488
490489 {
491 const targets = try std.leb.readUleb128(u64, inc_reader);
492 var lib_index = try inc_reader.readByte();
490 const targets = try inc_reader.takeLeb128(u64);
491 var lib_index = try inc_reader.takeByte();
493492
494493 const is_weak = (lib_index & (1 << 6)) != 0;
495494 const is_terminal = (lib_index & (1 << 7)) != 0;
......@@ -502,7 +501,7 @@ pub fn buildSharedObjects(comp: *Compilation, prog_node: std.Progress.Node) anye
502501 ((targets & (@as(u64, 1) << @as(u6, @intCast(target_targ_index)))) != 0);
503502
504503 while (true) {
505 const byte = try inc_reader.readByte();
504 const byte = try inc_reader.takeByte();
506505 const last = (byte & 0b1000_0000) != 0;
507506 const ver_i = @as(u7, @truncate(byte));
508507 if (ok_lib_and_target and ver_i <= target_ver_index and
......@@ -525,7 +524,7 @@ pub fn buildSharedObjects(comp: *Compilation, prog_node: std.Progress.Node) anye
525524 // .globl _Exit
526525 // .type _Exit, %function
527526 // _Exit: .long 0
528 try stubs_writer.print(
527 try stubs_asm.print(
529528 \\.balign {d}
530529 \\.{s} {s}
531530 \\.type {s}, %function
......@@ -542,9 +541,9 @@ pub fn buildSharedObjects(comp: *Compilation, prog_node: std.Progress.Node) anye
542541 }
543542 }
544543
545 try stubs_writer.writeAll(".data\n");
544 try stubs_asm.appendSlice(".data\n");
546545
547 const obj_inclusions_len = try inc_reader.readInt(u16, .little);
546 const obj_inclusions_len = try inc_reader.takeInt(u16, .little);
548547
549548 sym_i = 0;
550549 opt_symbol_name = null;
......@@ -554,18 +553,20 @@ pub fn buildSharedObjects(comp: *Compilation, prog_node: std.Progress.Node) anye
554553 while (sym_i < obj_inclusions_len) : (sym_i += 1) {
555554 const sym_name = opt_symbol_name orelse n: {
556555 sym_name_buf.clearRetainingCapacity();
557 try inc_reader.streamUntilDelimiter(sym_name_buf.writer(), 0, null);
556 _ = try inc_reader.streamDelimiter(&sym_name_buf.writer, 0);
557 assert(inc_reader.buffered()[0] == 0); // TODO change streamDelimiter API
558 inc_reader.toss(1);
558559
559 opt_symbol_name = sym_name_buf.items;
560 opt_symbol_name = sym_name_buf.written();
560561 chosen_ver_index = 255;
561562
562 break :n sym_name_buf.items;
563 break :n sym_name_buf.written();
563564 };
564565
565566 {
566 const targets = try std.leb.readUleb128(u64, inc_reader);
567 const size = try std.leb.readUleb128(u16, inc_reader);
568 var lib_index = try inc_reader.readByte();
567 const targets = try inc_reader.takeLeb128(u64);
568 const size = try inc_reader.takeLeb128(u16);
569 var lib_index = try inc_reader.takeByte();
569570
570571 const is_weak = (lib_index & (1 << 6)) != 0;
571572 const is_terminal = (lib_index & (1 << 7)) != 0;
......@@ -578,7 +579,7 @@ pub fn buildSharedObjects(comp: *Compilation, prog_node: std.Progress.Node) anye
578579 ((targets & (@as(u64, 1) << @as(u6, @intCast(target_targ_index)))) != 0);
579580
580581 while (true) {
581 const byte = try inc_reader.readByte();
582 const byte = try inc_reader.takeByte();
582583 const last = (byte & 0b1000_0000) != 0;
583584 const ver_i = @as(u7, @truncate(byte));
584585 if (ok_lib_and_target and ver_i <= target_ver_index and
......@@ -603,7 +604,7 @@ pub fn buildSharedObjects(comp: *Compilation, prog_node: std.Progress.Node) anye
603604 // .type malloc_conf, %object
604605 // .size malloc_conf, 4
605606 // malloc_conf: .fill 4, 1, 0
606 try stubs_writer.print(
607 try stubs_asm.print(
607608 \\.balign {d}
608609 \\.{s} {s}
609610 \\.type {s}, %object
src/link.zig+4-4
......@@ -1976,7 +1976,7 @@ fn resolveLibInput(
19761976 .root_dir = lib_directory,
19771977 .sub_path = try std.fmt.allocPrint(arena, "lib{s}.tbd", .{lib_name}),
19781978 };
1979 try checked_paths.writer(gpa).print("\n {f}", .{test_path});
1979 try checked_paths.print(gpa, "\n {f}", .{test_path});
19801980 var file = test_path.root_dir.handle.openFile(test_path.sub_path, .{}) catch |err| switch (err) {
19811981 error.FileNotFound => break :tbd,
19821982 else => |e| fatal("unable to search for tbd library '{f}': {s}", .{ test_path, @errorName(e) }),
......@@ -1995,7 +1995,7 @@ fn resolveLibInput(
19951995 },
19961996 }),
19971997 };
1998 try checked_paths.writer(gpa).print("\n {f}", .{test_path});
1998 try checked_paths.print(gpa, "\n {f}", .{test_path});
19991999 switch (try resolvePathInputLib(gpa, arena, unresolved_inputs, resolved_inputs, ld_script_bytes, target, .{
20002000 .path = test_path,
20012001 .query = name_query.query,
......@@ -2012,7 +2012,7 @@ fn resolveLibInput(
20122012 .root_dir = lib_directory,
20132013 .sub_path = try std.fmt.allocPrint(arena, "lib{s}.so", .{lib_name}),
20142014 };
2015 try checked_paths.writer(gpa).print("\n {f}", .{test_path});
2015 try checked_paths.print(gpa, "\n {f}", .{test_path});
20162016 var file = test_path.root_dir.handle.openFile(test_path.sub_path, .{}) catch |err| switch (err) {
20172017 error.FileNotFound => break :so,
20182018 else => |e| fatal("unable to search for so library '{f}': {s}", .{
......@@ -2030,7 +2030,7 @@ fn resolveLibInput(
20302030 .root_dir = lib_directory,
20312031 .sub_path = try std.fmt.allocPrint(arena, "lib{s}.a", .{lib_name}),
20322032 };
2033 try checked_paths.writer(gpa).print("\n {f}", .{test_path});
2033 try checked_paths.print(gpa, "\n {f}", .{test_path});
20342034 var file = test_path.root_dir.handle.openFile(test_path.sub_path, .{}) catch |err| switch (err) {
20352035 error.FileNotFound => break :mingw,
20362036 else => |e| fatal("unable to search for static library '{f}': {s}", .{ test_path, @errorName(e) }),
src/link/Coff.zig+4-4
......@@ -2179,13 +2179,13 @@ fn writeDataDirectoriesHeaders(coff: *Coff) !void {
21792179fn writeHeader(coff: *Coff) !void {
21802180 const target = &coff.base.comp.root_mod.resolved_target.result;
21812181 const gpa = coff.base.comp.gpa;
2182 var buffer = std.array_list.Managed(u8).init(gpa);
2182 var buffer: std.Io.Writer.Allocating = .init(gpa);
21832183 defer buffer.deinit();
2184 const writer = buffer.writer();
2184 const writer = &buffer.writer;
21852185
21862186 try buffer.ensureTotalCapacity(coff.getSizeOfHeaders());
21872187 writer.writeAll(&msdos_stub) catch unreachable;
2188 mem.writeInt(u32, buffer.items[0x3c..][0..4], msdos_stub.len, .little);
2188 mem.writeInt(u32, buffer.writer.buffer[0x3c..][0..4], msdos_stub.len, .little);
21892189
21902190 writer.writeAll("PE\x00\x00") catch unreachable;
21912191 var flags = coff_util.CoffHeaderFlags{
......@@ -2313,7 +2313,7 @@ fn writeHeader(coff: *Coff) !void {
23132313 },
23142314 }
23152315
2316 try coff.pwriteAll(buffer.items, 0);
2316 try coff.pwriteAll(buffer.written(), 0);
23172317}
23182318
23192319pub fn padToIdeal(actual_size: anytype) @TypeOf(actual_size) {
src/link/Elf.zig+34-38
......@@ -811,10 +811,6 @@ fn flushInner(self: *Elf, arena: Allocator, tid: Zcu.PerThread.Id) !void {
811811
812812 if (self.base.gc_sections) {
813813 try gc.gcAtoms(self);
814
815 if (self.base.print_gc_sections) {
816 try gc.dumpPrunedAtoms(self);
817 }
818814 }
819815
820816 self.checkDuplicates() catch |err| switch (err) {
......@@ -3005,7 +3001,7 @@ fn writeAtoms(self: *Elf) !void {
30053001 undefs.deinit();
30063002 }
30073003
3008 var buffer = std.array_list.Managed(u8).init(gpa);
3004 var buffer: std.Io.Writer.Allocating = .init(gpa);
30093005 defer buffer.deinit();
30103006
30113007 const slice = self.sections.slice();
......@@ -3032,9 +3028,9 @@ fn writeAtoms(self: *Elf) !void {
30323028 try buffer.ensureUnusedCapacity(thunk_size);
30333029 const shdr = slice.items(.shdr)[th.output_section_index];
30343030 const offset = @as(u64, @intCast(th.value)) + shdr.sh_offset;
3035 try th.write(self, buffer.writer());
3036 assert(buffer.items.len == thunk_size);
3037 try self.pwriteAll(buffer.items, offset);
3031 try th.write(self, &buffer.writer);
3032 assert(buffer.written().len == thunk_size);
3033 try self.pwriteAll(buffer.written(), offset);
30383034 buffer.clearRetainingCapacity();
30393035 }
30403036 }
......@@ -3166,26 +3162,26 @@ fn writeSyntheticSections(self: *Elf) !void {
31663162
31673163 if (self.section_indexes.verneed) |shndx| {
31683164 const shdr = slice.items(.shdr)[shndx];
3169 var buffer = try std.array_list.Managed(u8).initCapacity(gpa, self.verneed.size());
3165 var buffer = try std.Io.Writer.Allocating.initCapacity(gpa, self.verneed.size());
31703166 defer buffer.deinit();
3171 try self.verneed.write(buffer.writer());
3172 try self.pwriteAll(buffer.items, shdr.sh_offset);
3167 try self.verneed.write(&buffer.writer);
3168 try self.pwriteAll(buffer.written(), shdr.sh_offset);
31733169 }
31743170
31753171 if (self.section_indexes.dynamic) |shndx| {
31763172 const shdr = slice.items(.shdr)[shndx];
3177 var buffer = try std.array_list.Managed(u8).initCapacity(gpa, self.dynamic.size(self));
3173 var buffer = try std.Io.Writer.Allocating.initCapacity(gpa, self.dynamic.size(self));
31783174 defer buffer.deinit();
3179 try self.dynamic.write(self, buffer.writer());
3180 try self.pwriteAll(buffer.items, shdr.sh_offset);
3175 try self.dynamic.write(self, &buffer.writer);
3176 try self.pwriteAll(buffer.written(), shdr.sh_offset);
31813177 }
31823178
31833179 if (self.section_indexes.dynsymtab) |shndx| {
31843180 const shdr = slice.items(.shdr)[shndx];
3185 var buffer = try std.array_list.Managed(u8).initCapacity(gpa, self.dynsym.size());
3181 var buffer = try std.Io.Writer.Allocating.initCapacity(gpa, self.dynsym.size());
31863182 defer buffer.deinit();
3187 try self.dynsym.write(self, buffer.writer());
3188 try self.pwriteAll(buffer.items, shdr.sh_offset);
3183 try self.dynsym.write(self, &buffer.writer);
3184 try self.pwriteAll(buffer.written(), shdr.sh_offset);
31893185 }
31903186
31913187 if (self.section_indexes.dynstrtab) |shndx| {
......@@ -3201,28 +3197,28 @@ fn writeSyntheticSections(self: *Elf) !void {
32013197 };
32023198 const shdr = slice.items(.shdr)[shndx];
32033199 const sh_size = try self.cast(usize, shdr.sh_size);
3204 var buffer = try std.array_list.Managed(u8).initCapacity(gpa, @intCast(sh_size - existing_size));
3200 var buffer = try std.Io.Writer.Allocating.initCapacity(gpa, @intCast(sh_size - existing_size));
32053201 defer buffer.deinit();
3206 try eh_frame.writeEhFrame(self, buffer.writer());
3207 assert(buffer.items.len == sh_size - existing_size);
3208 try self.pwriteAll(buffer.items, shdr.sh_offset + existing_size);
3202 try eh_frame.writeEhFrame(self, &buffer.writer);
3203 assert(buffer.written().len == sh_size - existing_size);
3204 try self.pwriteAll(buffer.written(), shdr.sh_offset + existing_size);
32093205 }
32103206
32113207 if (self.section_indexes.eh_frame_hdr) |shndx| {
32123208 const shdr = slice.items(.shdr)[shndx];
32133209 const sh_size = try self.cast(usize, shdr.sh_size);
3214 var buffer = try std.array_list.Managed(u8).initCapacity(gpa, sh_size);
3210 var buffer = try std.Io.Writer.Allocating.initCapacity(gpa, sh_size);
32153211 defer buffer.deinit();
3216 try eh_frame.writeEhFrameHdr(self, buffer.writer());
3217 try self.pwriteAll(buffer.items, shdr.sh_offset);
3212 try eh_frame.writeEhFrameHdr(self, &buffer.writer);
3213 try self.pwriteAll(buffer.written(), shdr.sh_offset);
32183214 }
32193215
32203216 if (self.section_indexes.got) |index| {
32213217 const shdr = slice.items(.shdr)[index];
3222 var buffer = try std.array_list.Managed(u8).initCapacity(gpa, self.got.size(self));
3218 var buffer = try std.Io.Writer.Allocating.initCapacity(gpa, self.got.size(self));
32233219 defer buffer.deinit();
3224 try self.got.write(self, buffer.writer());
3225 try self.pwriteAll(buffer.items, shdr.sh_offset);
3220 try self.got.write(self, &buffer.writer);
3221 try self.pwriteAll(buffer.written(), shdr.sh_offset);
32263222 }
32273223
32283224 if (self.section_indexes.rela_dyn) |shndx| {
......@@ -3235,26 +3231,26 @@ fn writeSyntheticSections(self: *Elf) !void {
32353231
32363232 if (self.section_indexes.plt) |shndx| {
32373233 const shdr = slice.items(.shdr)[shndx];
3238 var buffer = try std.array_list.Managed(u8).initCapacity(gpa, self.plt.size(self));
3234 var buffer = try std.Io.Writer.Allocating.initCapacity(gpa, self.plt.size(self));
32393235 defer buffer.deinit();
3240 try self.plt.write(self, buffer.writer());
3241 try self.pwriteAll(buffer.items, shdr.sh_offset);
3236 try self.plt.write(self, &buffer.writer);
3237 try self.pwriteAll(buffer.written(), shdr.sh_offset);
32423238 }
32433239
32443240 if (self.section_indexes.got_plt) |shndx| {
32453241 const shdr = slice.items(.shdr)[shndx];
3246 var buffer = try std.array_list.Managed(u8).initCapacity(gpa, self.got_plt.size(self));
3242 var buffer = try std.Io.Writer.Allocating.initCapacity(gpa, self.got_plt.size(self));
32473243 defer buffer.deinit();
3248 try self.got_plt.write(self, buffer.writer());
3249 try self.pwriteAll(buffer.items, shdr.sh_offset);
3244 try self.got_plt.write(self, &buffer.writer);
3245 try self.pwriteAll(buffer.written(), shdr.sh_offset);
32503246 }
32513247
32523248 if (self.section_indexes.plt_got) |shndx| {
32533249 const shdr = slice.items(.shdr)[shndx];
3254 var buffer = try std.array_list.Managed(u8).initCapacity(gpa, self.plt_got.size(self));
3250 var buffer = try std.Io.Writer.Allocating.initCapacity(gpa, self.plt_got.size(self));
32553251 defer buffer.deinit();
3256 try self.plt_got.write(self, buffer.writer());
3257 try self.pwriteAll(buffer.items, shdr.sh_offset);
3252 try self.plt_got.write(self, &buffer.writer);
3253 try self.pwriteAll(buffer.written(), shdr.sh_offset);
32583254 }
32593255
32603256 if (self.section_indexes.rela_plt) |shndx| {
......@@ -3757,7 +3753,7 @@ pub fn insertShString(self: *Elf, name: [:0]const u8) error{OutOfMemory}!u32 {
37573753 const gpa = self.base.comp.gpa;
37583754 const off = @as(u32, @intCast(self.shstrtab.items.len));
37593755 try self.shstrtab.ensureUnusedCapacity(gpa, name.len + 1);
3760 self.shstrtab.writer(gpa).print("{s}\x00", .{name}) catch unreachable;
3756 self.shstrtab.print(gpa, "{s}\x00", .{name}) catch unreachable;
37613757 return off;
37623758}
37633759
......@@ -3770,7 +3766,7 @@ pub fn insertDynString(self: *Elf, name: []const u8) error{OutOfMemory}!u32 {
37703766 const gpa = self.base.comp.gpa;
37713767 const off = @as(u32, @intCast(self.dynstrtab.items.len));
37723768 try self.dynstrtab.ensureUnusedCapacity(gpa, name.len + 1);
3773 self.dynstrtab.writer(gpa).print("{s}\x00", .{name}) catch unreachable;
3769 self.dynstrtab.print(gpa, "{s}\x00", .{name}) catch unreachable;
37743770 return off;
37753771}
37763772
src/link/Elf/Archive.zig+4-5
......@@ -123,8 +123,7 @@ pub fn setArHdr(opts: struct {
123123 @memcpy(&hdr.ar_fmag, elf.ARFMAG);
124124
125125 {
126 var stream = std.io.fixedBufferStream(&hdr.ar_name);
127 const writer = stream.writer();
126 var writer: std.Io.Writer = .fixed(&hdr.ar_name);
128127 switch (opts.name) {
129128 .symtab => writer.print("{s}", .{elf.SYM64NAME}) catch unreachable,
130129 .strtab => writer.print("//", .{}) catch unreachable,
......@@ -133,8 +132,8 @@ pub fn setArHdr(opts: struct {
133132 }
134133 }
135134 {
136 var stream = std.io.fixedBufferStream(&hdr.ar_size);
137 stream.writer().print("{d}", .{opts.size}) catch unreachable;
135 var writer: std.Io.Writer = .fixed(&hdr.ar_size);
136 writer.print("{d}", .{opts.size}) catch unreachable;
138137 }
139138
140139 return hdr;
......@@ -246,7 +245,7 @@ pub const ArStrtab = struct {
246245
247246 pub fn insert(ar: *ArStrtab, allocator: Allocator, name: []const u8) error{OutOfMemory}!u32 {
248247 const off = @as(u32, @intCast(ar.buffer.items.len));
249 try ar.buffer.writer(allocator).print("{s}/{c}", .{ name, strtab_delimiter });
248 try ar.buffer.print(allocator, "{s}/{c}", .{ name, strtab_delimiter });
250249 return off;
251250 }
252251
src/link/Elf/Atom.zig+113-142
......@@ -621,7 +621,6 @@ pub fn resolveRelocsAlloc(self: Atom, elf_file: *Elf, code: []u8) RelocError!voi
621621
622622 const cpu_arch = elf_file.getTarget().cpu.arch;
623623 const file_ptr = self.file(elf_file).?;
624 var stream = std.io.fixedBufferStream(code);
625624
626625 const rels = self.relocs(elf_file);
627626 var it = RelocsIterator{ .relocs = rels };
......@@ -661,20 +660,16 @@ pub fn resolveRelocsAlloc(self: Atom, elf_file: *Elf, code: []u8) RelocError!voi
661660 target.name(elf_file),
662661 });
663662
664 try stream.seekTo(r_offset);
665
666663 const args = ResolveArgs{ P, A, S, GOT, G, TP, DTP };
667664
668665 switch (cpu_arch) {
669 .x86_64 => x86_64.resolveRelocAlloc(self, elf_file, rel, target, args, &it, code, &stream) catch |err| switch (err) {
666 .x86_64 => x86_64.resolveRelocAlloc(self, elf_file, rel, target, args, &it, code) catch |err| switch (err) {
670667 error.RelocFailure,
671668 error.RelaxFailure,
672 error.InvalidInstruction,
673 error.CannotEncode,
674669 => has_reloc_errors = true,
675670 else => |e| return e,
676671 },
677 .aarch64, .aarch64_be => aarch64.resolveRelocAlloc(self, elf_file, rel, target, args, &it, code, &stream) catch |err| switch (err) {
672 .aarch64, .aarch64_be => aarch64.resolveRelocAlloc(self, elf_file, rel, target, args, &it, code) catch |err| switch (err) {
678673 error.RelocFailure,
679674 error.RelaxFailure,
680675 error.UnexpectedRemainder,
......@@ -682,7 +677,7 @@ pub fn resolveRelocsAlloc(self: Atom, elf_file: *Elf, code: []u8) RelocError!voi
682677 => has_reloc_errors = true,
683678 else => |e| return e,
684679 },
685 .riscv64, .riscv64be => riscv.resolveRelocAlloc(self, elf_file, rel, target, args, &it, code, &stream) catch |err| switch (err) {
680 .riscv64, .riscv64be => riscv.resolveRelocAlloc(self, elf_file, rel, target, args, &it, code) catch |err| switch (err) {
686681 error.RelocFailure,
687682 error.RelaxFailure,
688683 => has_reloc_errors = true,
......@@ -701,7 +696,8 @@ fn resolveDynAbsReloc(
701696 rel: elf.Elf64_Rela,
702697 action: RelocAction,
703698 elf_file: *Elf,
704 writer: anytype,
699 code: []u8,
700 r_offset: usize,
705701) !void {
706702 const comp = elf_file.base.comp;
707703 const gpa = comp.gpa;
......@@ -726,7 +722,7 @@ fn resolveDynAbsReloc(
726722 .copyrel,
727723 .cplt,
728724 .none,
729 => try writer.writeInt(i64, S + A, .little),
725 => mem.writeInt(i64, code[r_offset..][0..8], S + A, .little),
730726
731727 .dyn_copyrel => {
732728 if (is_writeable or elf_file.z_nocopyreloc) {
......@@ -737,9 +733,9 @@ fn resolveDynAbsReloc(
737733 .addend = A,
738734 .target = target,
739735 });
740 try applyDynamicReloc(A, elf_file, writer);
736 applyDynamicReloc(A, code, r_offset);
741737 } else {
742 try writer.writeInt(i64, S + A, .little);
738 mem.writeInt(i64, code[r_offset..][0..8], S + A, .little);
743739 }
744740 },
745741
......@@ -752,9 +748,9 @@ fn resolveDynAbsReloc(
752748 .addend = A,
753749 .target = target,
754750 });
755 try applyDynamicReloc(A, elf_file, writer);
751 applyDynamicReloc(A, code, r_offset);
756752 } else {
757 try writer.writeInt(i64, S + A, .little);
753 mem.writeInt(i64, code[r_offset..][0..8], S + A, .little);
758754 }
759755 },
760756
......@@ -766,7 +762,7 @@ fn resolveDynAbsReloc(
766762 .addend = A,
767763 .target = target,
768764 });
769 try applyDynamicReloc(A, elf_file, writer);
765 applyDynamicReloc(A, code, r_offset);
770766 },
771767
772768 .baserel => {
......@@ -776,7 +772,7 @@ fn resolveDynAbsReloc(
776772 .addend = S + A,
777773 .target = target,
778774 });
779 try applyDynamicReloc(S + A, elf_file, writer);
775 applyDynamicReloc(S + A, code, r_offset);
780776 },
781777
782778 .ifunc => {
......@@ -787,16 +783,13 @@ fn resolveDynAbsReloc(
787783 .addend = S_ + A,
788784 .target = target,
789785 });
790 try applyDynamicReloc(S_ + A, elf_file, writer);
786 applyDynamicReloc(S_ + A, code, r_offset);
791787 },
792788 }
793789}
794790
795fn applyDynamicReloc(value: i64, elf_file: *Elf, writer: anytype) !void {
796 _ = elf_file;
797 // if (elf_file.options.apply_dynamic_relocs) {
798 try writer.writeInt(i64, value, .little);
799 // }
791fn applyDynamicReloc(value: i64, code: []u8, r_offset: usize) void {
792 mem.writeInt(i64, code[r_offset..][0..8], value, .little);
800793}
801794
802795pub fn resolveRelocsNonAlloc(self: Atom, elf_file: *Elf, code: []u8, undefs: anytype) !void {
......@@ -804,7 +797,6 @@ pub fn resolveRelocsNonAlloc(self: Atom, elf_file: *Elf, code: []u8, undefs: any
804797
805798 const cpu_arch = elf_file.getTarget().cpu.arch;
806799 const file_ptr = self.file(elf_file).?;
807 var stream = std.io.fixedBufferStream(code);
808800
809801 const rels = self.relocs(elf_file);
810802 var has_reloc_errors = false;
......@@ -863,18 +855,16 @@ pub fn resolveRelocsNonAlloc(self: Atom, elf_file: *Elf, code: []u8, undefs: any
863855 target.name(elf_file),
864856 });
865857
866 try stream.seekTo(r_offset);
867
868858 switch (cpu_arch) {
869 .x86_64 => x86_64.resolveRelocNonAlloc(self, elf_file, rel, target, args, &it, code, &stream) catch |err| switch (err) {
859 .x86_64 => x86_64.resolveRelocNonAlloc(self, elf_file, rel, target, args, code[r_offset..]) catch |err| switch (err) {
870860 error.RelocFailure => has_reloc_errors = true,
871861 else => |e| return e,
872862 },
873 .aarch64, .aarch64_be => aarch64.resolveRelocNonAlloc(self, elf_file, rel, target, args, &it, code, &stream) catch |err| switch (err) {
863 .aarch64, .aarch64_be => aarch64.resolveRelocNonAlloc(self, elf_file, rel, target, args, code[r_offset..]) catch |err| switch (err) {
874864 error.RelocFailure => has_reloc_errors = true,
875865 else => |e| return e,
876866 },
877 .riscv64, .riscv64be => riscv.resolveRelocNonAlloc(self, elf_file, rel, target, args, &it, code, &stream) catch |err| switch (err) {
867 .riscv64, .riscv64be => riscv.resolveRelocNonAlloc(self, elf_file, rel, target, args, code[r_offset..]) catch |err| switch (err) {
878868 error.RelocFailure => has_reloc_errors = true,
879869 else => |e| return e,
880870 },
......@@ -915,7 +905,7 @@ const Format = struct {
915905 atom: Atom,
916906 elf_file: *Elf,
917907
918 fn default(f: Format, w: *std.io.Writer) std.io.Writer.Error!void {
908 fn default(f: Format, w: *Writer) Writer.Error!void {
919909 const atom = f.atom;
920910 const elf_file = f.elf_file;
921911 try w.print("atom({d}) : {s} : @{x} : shdr({d}) : align({x}) : size({x}) : prev({f}) : next({f})", .{
......@@ -1068,16 +1058,13 @@ const x86_64 = struct {
10681058 args: ResolveArgs,
10691059 it: *RelocsIterator,
10701060 code: []u8,
1071 stream: anytype,
1072 ) (error{ InvalidInstruction, CannotEncode } || RelocError)!void {
1061 ) !void {
10731062 dev.check(.x86_64_backend);
10741063 const t = &elf_file.base.comp.root_mod.resolved_target.result;
10751064 const diags = &elf_file.base.comp.link_diags;
10761065 const r_type: elf.R_X86_64 = @enumFromInt(rel.r_type());
10771066 const r_offset = std.math.cast(usize, rel.r_offset) orelse return error.Overflow;
10781067
1079 const cwriter = stream.writer();
1080
10811068 const P, const A, const S, const GOT, const G, const TP, const DTP = args;
10821069
10831070 switch (r_type) {
......@@ -1089,58 +1076,60 @@ const x86_64 = struct {
10891076 rel,
10901077 dynAbsRelocAction(target, elf_file),
10911078 elf_file,
1092 cwriter,
1079 code,
1080 r_offset,
10931081 );
10941082 },
10951083
1096 .PLT32 => try cwriter.writeInt(i32, @as(i32, @intCast(S + A - P)), .little),
1097 .PC32 => try cwriter.writeInt(i32, @as(i32, @intCast(S + A - P)), .little),
1084 .PLT32 => mem.writeInt(i32, code[r_offset..][0..4], @as(i32, @intCast(S + A - P)), .little),
1085 .PC32 => mem.writeInt(i32, code[r_offset..][0..4], @as(i32, @intCast(S + A - P)), .little),
10981086
1099 .GOTPCREL => try cwriter.writeInt(i32, @as(i32, @intCast(G + GOT + A - P)), .little),
1100 .GOTPC32 => try cwriter.writeInt(i32, @as(i32, @intCast(GOT + A - P)), .little),
1101 .GOTPC64 => try cwriter.writeInt(i64, GOT + A - P, .little),
1087 .GOTPCREL => mem.writeInt(i32, code[r_offset..][0..4], @as(i32, @intCast(G + GOT + A - P)), .little),
1088 .GOTPC32 => mem.writeInt(i32, code[r_offset..][0..4], @as(i32, @intCast(GOT + A - P)), .little),
1089 .GOTPC64 => mem.writeInt(i64, code[r_offset..][0..8], GOT + A - P, .little),
11021090
11031091 .GOTPCRELX => {
11041092 if (!target.flags.import and !target.isIFunc(elf_file) and !target.isAbs(elf_file)) blk: {
11051093 x86_64.relaxGotpcrelx(code[r_offset - 2 ..], t) catch break :blk;
1106 try cwriter.writeInt(i32, @as(i32, @intCast(S + A - P)), .little);
1094 mem.writeInt(i32, code[r_offset..][0..4], @as(i32, @intCast(S + A - P)), .little);
11071095 return;
11081096 }
1109 try cwriter.writeInt(i32, @as(i32, @intCast(G + GOT + A - P)), .little);
1097 mem.writeInt(i32, code[r_offset..][0..4], @as(i32, @intCast(G + GOT + A - P)), .little);
11101098 },
11111099
11121100 .REX_GOTPCRELX => {
11131101 if (!target.flags.import and !target.isIFunc(elf_file) and !target.isAbs(elf_file)) blk: {
11141102 x86_64.relaxRexGotpcrelx(code[r_offset - 3 ..], t) catch break :blk;
1115 try cwriter.writeInt(i32, @as(i32, @intCast(S + A - P)), .little);
1103 mem.writeInt(i32, code[r_offset..][0..4], @as(i32, @intCast(S + A - P)), .little);
11161104 return;
11171105 }
1118 try cwriter.writeInt(i32, @as(i32, @intCast(G + GOT + A - P)), .little);
1106 mem.writeInt(i32, code[r_offset..][0..4], @as(i32, @intCast(G + GOT + A - P)), .little);
11191107 },
11201108
1121 .@"32" => try cwriter.writeInt(u32, @as(u32, @truncate(@as(u64, @intCast(S + A)))), .little),
1122 .@"32S" => try cwriter.writeInt(i32, @as(i32, @truncate(S + A)), .little),
1109 .@"32" => mem.writeInt(u32, code[r_offset..][0..4], @as(u32, @truncate(@as(u64, @intCast(S + A)))), .little),
1110 .@"32S" => mem.writeInt(i32, code[r_offset..][0..4], @as(i32, @truncate(S + A)), .little),
11231111
1124 .TPOFF32 => try cwriter.writeInt(i32, @as(i32, @truncate(S + A - TP)), .little),
1125 .TPOFF64 => try cwriter.writeInt(i64, S + A - TP, .little),
1112 .TPOFF32 => mem.writeInt(i32, code[r_offset..][0..4], @as(i32, @truncate(S + A - TP)), .little),
1113 .TPOFF64 => mem.writeInt(i64, code[r_offset..][0..8], S + A - TP, .little),
11261114
1127 .DTPOFF32 => try cwriter.writeInt(i32, @as(i32, @truncate(S + A - DTP)), .little),
1128 .DTPOFF64 => try cwriter.writeInt(i64, S + A - DTP, .little),
1115 .DTPOFF32 => mem.writeInt(i32, code[r_offset..][0..4], @as(i32, @truncate(S + A - DTP)), .little),
1116 .DTPOFF64 => mem.writeInt(i64, code[r_offset..][0..8], S + A - DTP, .little),
11291117
11301118 .TLSGD => {
11311119 if (target.flags.has_tlsgd) {
11321120 const S_ = target.tlsGdAddress(elf_file);
1133 try cwriter.writeInt(i32, @as(i32, @intCast(S_ + A - P)), .little);
1121 mem.writeInt(i32, code[r_offset..][0..4], @as(i32, @intCast(S_ + A - P)), .little);
11341122 } else if (target.flags.has_gottp) {
11351123 const S_ = target.gotTpAddress(elf_file);
1136 try x86_64.relaxTlsGdToIe(atom, &.{ rel, it.next().? }, @intCast(S_ - P), elf_file, stream);
1124 try x86_64.relaxTlsGdToIe(atom, &.{ rel, it.next().? }, @intCast(S_ - P), elf_file, code, r_offset);
11371125 } else {
11381126 try x86_64.relaxTlsGdToLe(
11391127 atom,
11401128 &.{ rel, it.next().? },
11411129 @as(i32, @intCast(S - TP)),
11421130 elf_file,
1143 stream,
1131 code,
1132 r_offset,
11441133 );
11451134 }
11461135 },
......@@ -1149,14 +1138,15 @@ const x86_64 = struct {
11491138 if (elf_file.got.tlsld_index) |entry_index| {
11501139 const tlsld_entry = elf_file.got.entries.items[entry_index];
11511140 const S_ = tlsld_entry.address(elf_file);
1152 try cwriter.writeInt(i32, @as(i32, @intCast(S_ + A - P)), .little);
1141 mem.writeInt(i32, code[r_offset..][0..4], @as(i32, @intCast(S_ + A - P)), .little);
11531142 } else {
11541143 try x86_64.relaxTlsLdToLe(
11551144 atom,
11561145 &.{ rel, it.next().? },
11571146 @as(i32, @intCast(TP - elf_file.tlsAddress())),
11581147 elf_file,
1159 stream,
1148 code,
1149 r_offset,
11601150 );
11611151 }
11621152 },
......@@ -1164,7 +1154,7 @@ const x86_64 = struct {
11641154 .GOTPC32_TLSDESC => {
11651155 if (target.flags.has_tlsdesc) {
11661156 const S_ = target.tlsDescAddress(elf_file);
1167 try cwriter.writeInt(i32, @as(i32, @intCast(S_ + A - P)), .little);
1157 mem.writeInt(i32, code[r_offset..][0..4], @as(i32, @intCast(S_ + A - P)), .little);
11681158 } else {
11691159 x86_64.relaxGotPcTlsDesc(code[r_offset - 3 ..], t) catch {
11701160 var err = try diags.addErrorWithNotes(1);
......@@ -1176,26 +1166,26 @@ const x86_64 = struct {
11761166 });
11771167 return error.RelaxFailure;
11781168 };
1179 try cwriter.writeInt(i32, @as(i32, @intCast(S - TP)), .little);
1169 mem.writeInt(i32, code[r_offset..][0..4], @as(i32, @intCast(S - TP)), .little);
11801170 }
11811171 },
11821172
11831173 .TLSDESC_CALL => if (!target.flags.has_tlsdesc) {
11841174 // call -> nop
1185 try cwriter.writeAll(&.{ 0x66, 0x90 });
1175 code[r_offset..][0..2].* = .{ 0x66, 0x90 };
11861176 },
11871177
11881178 .GOTTPOFF => {
11891179 if (target.flags.has_gottp) {
11901180 const S_ = target.gotTpAddress(elf_file);
1191 try cwriter.writeInt(i32, @as(i32, @intCast(S_ + A - P)), .little);
1181 mem.writeInt(i32, code[r_offset..][0..4], @as(i32, @intCast(S_ + A - P)), .little);
11921182 } else {
11931183 x86_64.relaxGotTpOff(code[r_offset - 3 ..], t);
1194 try cwriter.writeInt(i32, @as(i32, @intCast(S - TP)), .little);
1184 mem.writeInt(i32, code[r_offset..][0..4], @as(i32, @intCast(S - TP)), .little);
11951185 }
11961186 },
11971187
1198 .GOT32 => try cwriter.writeInt(i32, @as(i32, @intCast(G + A)), .little),
1188 .GOT32 => mem.writeInt(i32, code[r_offset..][0..4], @as(i32, @intCast(G + A)), .little),
11991189
12001190 else => try atom.reportUnhandledRelocError(rel, elf_file),
12011191 }
......@@ -1207,45 +1197,42 @@ const x86_64 = struct {
12071197 rel: elf.Elf64_Rela,
12081198 target: *const Symbol,
12091199 args: ResolveArgs,
1210 it: *RelocsIterator,
12111200 code: []u8,
1212 stream: anytype,
12131201 ) !void {
12141202 dev.check(.x86_64_backend);
1215 _ = code;
1216 _ = it;
12171203 const r_type: elf.R_X86_64 = @enumFromInt(rel.r_type());
1218 const cwriter = stream.writer();
12191204
12201205 _, const A, const S, const GOT, _, _, const DTP = args;
12211206
1207 var writer: Writer = .fixed(code);
1208
12221209 switch (r_type) {
12231210 .NONE => unreachable,
1224 .@"8" => try cwriter.writeInt(u8, @as(u8, @bitCast(@as(i8, @intCast(S + A)))), .little),
1225 .@"16" => try cwriter.writeInt(u16, @as(u16, @bitCast(@as(i16, @intCast(S + A)))), .little),
1226 .@"32" => try cwriter.writeInt(u32, @as(u32, @bitCast(@as(i32, @intCast(S + A)))), .little),
1227 .@"32S" => try cwriter.writeInt(i32, @as(i32, @intCast(S + A)), .little),
1211 .@"8" => try writer.writeInt(u8, @as(u8, @bitCast(@as(i8, @intCast(S + A)))), .little),
1212 .@"16" => try writer.writeInt(u16, @as(u16, @bitCast(@as(i16, @intCast(S + A)))), .little),
1213 .@"32" => try writer.writeInt(u32, @as(u32, @bitCast(@as(i32, @intCast(S + A)))), .little),
1214 .@"32S" => try writer.writeInt(i32, @as(i32, @intCast(S + A)), .little),
12281215 .@"64" => if (atom.debugTombstoneValue(target.*, elf_file)) |value|
1229 try cwriter.writeInt(u64, value, .little)
1216 try writer.writeInt(u64, value, .little)
12301217 else
1231 try cwriter.writeInt(i64, S + A, .little),
1218 try writer.writeInt(i64, S + A, .little),
12321219 .DTPOFF32 => if (atom.debugTombstoneValue(target.*, elf_file)) |value|
1233 try cwriter.writeInt(u64, value, .little)
1220 try writer.writeInt(u64, value, .little)
12341221 else
1235 try cwriter.writeInt(i32, @as(i32, @intCast(S + A - DTP)), .little),
1222 try writer.writeInt(i32, @as(i32, @intCast(S + A - DTP)), .little),
12361223 .DTPOFF64 => if (atom.debugTombstoneValue(target.*, elf_file)) |value|
1237 try cwriter.writeInt(u64, value, .little)
1224 try writer.writeInt(u64, value, .little)
12381225 else
1239 try cwriter.writeInt(i64, S + A - DTP, .little),
1240 .GOTOFF64 => try cwriter.writeInt(i64, S + A - GOT, .little),
1241 .GOTPC64 => try cwriter.writeInt(i64, GOT + A, .little),
1226 try writer.writeInt(i64, S + A - DTP, .little),
1227 .GOTOFF64 => try writer.writeInt(i64, S + A - GOT, .little),
1228 .GOTPC64 => try writer.writeInt(i64, GOT + A, .little),
12421229 .SIZE32 => {
12431230 const size = @as(i64, @intCast(target.elfSym(elf_file).st_size));
1244 try cwriter.writeInt(u32, @bitCast(@as(i32, @intCast(size + A))), .little);
1231 try writer.writeInt(u32, @bitCast(@as(i32, @intCast(size + A))), .little);
12451232 },
12461233 .SIZE64 => {
12471234 const size = @as(i64, @intCast(target.elfSym(elf_file).st_size));
1248 try cwriter.writeInt(i64, @intCast(size + A), .little);
1235 try writer.writeInt(i64, @intCast(size + A), .little);
12491236 },
12501237 else => try atom.reportUnhandledRelocError(rel, elf_file),
12511238 }
......@@ -1288,12 +1275,12 @@ const x86_64 = struct {
12881275 rels: []const elf.Elf64_Rela,
12891276 value: i32,
12901277 elf_file: *Elf,
1291 stream: anytype,
1278 code: []u8,
1279 r_offset: usize,
12921280 ) !void {
12931281 dev.check(.x86_64_backend);
12941282 assert(rels.len == 2);
12951283 const diags = &elf_file.base.comp.link_diags;
1296 const writer = stream.writer();
12971284 const rel: elf.R_X86_64 = @enumFromInt(rels[1].r_type());
12981285 switch (rel) {
12991286 .PC32,
......@@ -1304,8 +1291,7 @@ const x86_64 = struct {
13041291 0x48, 0x03, 0x05, 0, 0, 0, 0, // add foo@gottpoff(%rip), %rax
13051292 };
13061293 std.mem.writeInt(i32, insts[12..][0..4], value - 12, .little);
1307 try stream.seekBy(-4);
1308 try writer.writeAll(&insts);
1294 @memcpy(code[r_offset - 4 ..][0..insts.len], &insts);
13091295 },
13101296
13111297 else => {
......@@ -1329,12 +1315,12 @@ const x86_64 = struct {
13291315 rels: []const elf.Elf64_Rela,
13301316 value: i32,
13311317 elf_file: *Elf,
1332 stream: anytype,
1318 code: []u8,
1319 r_offset: usize,
13331320 ) !void {
13341321 dev.check(.x86_64_backend);
13351322 assert(rels.len == 2);
13361323 const diags = &elf_file.base.comp.link_diags;
1337 const writer = stream.writer();
13381324 const rel: elf.R_X86_64 = @enumFromInt(rels[1].r_type());
13391325 switch (rel) {
13401326 .PC32,
......@@ -1346,8 +1332,7 @@ const x86_64 = struct {
13461332 0x48, 0x2d, 0, 0, 0, 0, // sub $tls_size, %rax
13471333 };
13481334 std.mem.writeInt(i32, insts[8..][0..4], value, .little);
1349 try stream.seekBy(-3);
1350 try writer.writeAll(&insts);
1335 @memcpy(code[r_offset - 3 ..][0..insts.len], &insts);
13511336 },
13521337
13531338 .GOTPCREL,
......@@ -1360,8 +1345,7 @@ const x86_64 = struct {
13601345 0x90, // nop
13611346 };
13621347 std.mem.writeInt(i32, insts[8..][0..4], value, .little);
1363 try stream.seekBy(-3);
1364 try writer.writeAll(&insts);
1348 @memcpy(code[r_offset - 3 ..][0..insts.len], &insts);
13651349 },
13661350
13671351 else => {
......@@ -1390,7 +1374,7 @@ const x86_64 = struct {
13901374 // TODO: hack to force imm32s in the assembler
13911375 .{ .imm = .s(-129) },
13921376 }, t) catch return false;
1393 var trash: std.io.Writer.Discarding = .init(&.{});
1377 var trash: Writer.Discarding = .init(&.{});
13941378 inst.encode(&trash.writer, .{}) catch return false;
13951379 return true;
13961380 },
......@@ -1437,12 +1421,12 @@ const x86_64 = struct {
14371421 rels: []const elf.Elf64_Rela,
14381422 value: i32,
14391423 elf_file: *Elf,
1440 stream: anytype,
1424 code: []u8,
1425 r_offset: usize,
14411426 ) !void {
14421427 dev.check(.x86_64_backend);
14431428 assert(rels.len == 2);
14441429 const diags = &elf_file.base.comp.link_diags;
1445 const writer = stream.writer();
14461430 const rel: elf.R_X86_64 = @enumFromInt(rels[1].r_type());
14471431 switch (rel) {
14481432 .PC32,
......@@ -1455,8 +1439,7 @@ const x86_64 = struct {
14551439 0x48, 0x81, 0xc0, 0, 0, 0, 0, // add $tp_offset, %rax
14561440 };
14571441 std.mem.writeInt(i32, insts[12..][0..4], value, .little);
1458 try stream.seekBy(-4);
1459 try writer.writeAll(&insts);
1442 @memcpy(code[r_offset - 4 ..][0..insts.len], &insts);
14601443 relocs_log.debug(" relaxing {f} and {f}", .{
14611444 relocation.fmtRelocType(rels[0].r_type(), .x86_64),
14621445 relocation.fmtRelocType(rels[1].r_type(), .x86_64),
......@@ -1486,8 +1469,8 @@ const x86_64 = struct {
14861469 }
14871470
14881471 fn encode(insts: []const Instruction, code: []u8) !void {
1489 var stream: std.io.Writer = .fixed(code);
1490 for (insts) |inst| try inst.encode(&stream, .{});
1472 var writer: Writer = .fixed(code);
1473 for (insts) |inst| try inst.encode(&writer, .{});
14911474 }
14921475
14931476 const bits = @import("../../arch/x86_64/bits.zig");
......@@ -1592,14 +1575,12 @@ const aarch64 = struct {
15921575 args: ResolveArgs,
15931576 it: *RelocsIterator,
15941577 code_buffer: []u8,
1595 stream: anytype,
15961578 ) (error{ UnexpectedRemainder, DivisionByZero } || RelocError)!void {
15971579 _ = it;
15981580
15991581 const diags = &elf_file.base.comp.link_diags;
16001582 const r_type: elf.R_AARCH64 = @enumFromInt(rel.r_type());
16011583 const r_offset = std.math.cast(usize, rel.r_offset) orelse return error.Overflow;
1602 const cwriter = stream.writer();
16031584 const code = code_buffer[r_offset..][0..4];
16041585 const file_ptr = atom.file(elf_file).?;
16051586
......@@ -1614,7 +1595,8 @@ const aarch64 = struct {
16141595 rel,
16151596 dynAbsRelocAction(target, elf_file),
16161597 elf_file,
1617 cwriter,
1598 code_buffer,
1599 r_offset,
16181600 );
16191601 },
16201602
......@@ -1782,25 +1764,20 @@ const aarch64 = struct {
17821764 rel: elf.Elf64_Rela,
17831765 target: *const Symbol,
17841766 args: ResolveArgs,
1785 it: *RelocsIterator,
17861767 code: []u8,
1787 stream: anytype,
17881768 ) !void {
1789 _ = it;
1790 _ = code;
1791
17921769 const r_type: elf.R_AARCH64 = @enumFromInt(rel.r_type());
1793 const cwriter = stream.writer();
17941770
17951771 _, const A, const S, _, _, _, _ = args;
17961772
1773 var writer: Writer = .fixed(code);
17971774 switch (r_type) {
17981775 .NONE => unreachable,
1799 .ABS32 => try cwriter.writeInt(i32, @as(i32, @intCast(S + A)), .little),
1776 .ABS32 => try writer.writeInt(i32, @as(i32, @intCast(S + A)), .little),
18001777 .ABS64 => if (atom.debugTombstoneValue(target.*, elf_file)) |value|
1801 try cwriter.writeInt(u64, value, .little)
1778 try writer.writeInt(u64, value, .little)
18021779 else
1803 try cwriter.writeInt(i64, S + A, .little),
1780 try writer.writeInt(i64, S + A, .little),
18041781 else => try atom.reportUnhandledRelocError(rel, elf_file),
18051782 }
18061783 }
......@@ -1861,12 +1838,10 @@ const riscv = struct {
18611838 args: ResolveArgs,
18621839 it: *RelocsIterator,
18631840 code: []u8,
1864 stream: anytype,
18651841 ) !void {
18661842 const diags = &elf_file.base.comp.link_diags;
18671843 const r_type: elf.R_RISCV = @enumFromInt(rel.r_type());
18681844 const r_offset = std.math.cast(usize, rel.r_offset) orelse return error.Overflow;
1869 const cwriter = stream.writer();
18701845
18711846 const P, const A, const S, const GOT, const G, const TP, const DTP = args;
18721847 _ = TP;
......@@ -1875,7 +1850,7 @@ const riscv = struct {
18751850 switch (r_type) {
18761851 .NONE => unreachable,
18771852
1878 .@"32" => try cwriter.writeInt(u32, @as(u32, @truncate(@as(u64, @intCast(S + A)))), .little),
1853 .@"32" => mem.writeInt(u32, code[r_offset..][0..4], @as(u32, @truncate(@as(u64, @intCast(S + A)))), .little),
18791854
18801855 .@"64" => {
18811856 try atom.resolveDynAbsReloc(
......@@ -1883,7 +1858,8 @@ const riscv = struct {
18831858 rel,
18841859 dynAbsRelocAction(target, elf_file),
18851860 elf_file,
1886 cwriter,
1861 code,
1862 r_offset,
18871863 );
18881864 },
18891865
......@@ -1997,15 +1973,9 @@ const riscv = struct {
19971973 rel: elf.Elf64_Rela,
19981974 target: *const Symbol,
19991975 args: ResolveArgs,
2000 it: *RelocsIterator,
20011976 code: []u8,
2002 stream: anytype,
20031977 ) !void {
2004 _ = it;
2005
20061978 const r_type: elf.R_RISCV = @enumFromInt(rel.r_type());
2007 const r_offset = std.math.cast(usize, rel.r_offset) orelse return error.Overflow;
2008 const cwriter = stream.writer();
20091979
20101980 _, const A, const S, const GOT, _, _, const DTP = args;
20111981 _ = GOT;
......@@ -2014,30 +1984,29 @@ const riscv = struct {
20141984 switch (r_type) {
20151985 .NONE => unreachable,
20161986
2017 .@"32" => try cwriter.writeInt(i32, @as(i32, @intCast(S + A)), .little),
1987 .@"32" => mem.writeInt(i32, code[0..4], @intCast(S + A), .little),
20181988 .@"64" => if (atom.debugTombstoneValue(target.*, elf_file)) |value|
2019 try cwriter.writeInt(u64, value, .little)
1989 mem.writeInt(u64, code[0..8], value, .little)
20201990 else
2021 try cwriter.writeInt(i64, S + A, .little),
2022
2023 .ADD8 => riscv_util.writeAddend(i8, .add, code[r_offset..][0..1], S + A),
2024 .SUB8 => riscv_util.writeAddend(i8, .sub, code[r_offset..][0..1], S + A),
2025 .ADD16 => riscv_util.writeAddend(i16, .add, code[r_offset..][0..2], S + A),
2026 .SUB16 => riscv_util.writeAddend(i16, .sub, code[r_offset..][0..2], S + A),
2027 .ADD32 => riscv_util.writeAddend(i32, .add, code[r_offset..][0..4], S + A),
2028 .SUB32 => riscv_util.writeAddend(i32, .sub, code[r_offset..][0..4], S + A),
2029 .ADD64 => riscv_util.writeAddend(i64, .add, code[r_offset..][0..8], S + A),
2030 .SUB64 => riscv_util.writeAddend(i64, .sub, code[r_offset..][0..8], S + A),
2031
2032 .SET8 => mem.writeInt(i8, code[r_offset..][0..1], @as(i8, @truncate(S + A)), .little),
2033 .SET16 => mem.writeInt(i16, code[r_offset..][0..2], @as(i16, @truncate(S + A)), .little),
2034 .SET32 => mem.writeInt(i32, code[r_offset..][0..4], @as(i32, @truncate(S + A)), .little),
2035
2036 .SET6 => riscv_util.writeSetSub6(.set, code[r_offset..][0..1], S + A),
2037 .SUB6 => riscv_util.writeSetSub6(.sub, code[r_offset..][0..1], S + A),
2038
2039 .SET_ULEB128 => try riscv_util.writeSetSubUleb(.set, stream, S + A),
2040 .SUB_ULEB128 => try riscv_util.writeSetSubUleb(.sub, stream, S - A),
1991 mem.writeInt(i64, code[0..8], S + A, .little),
1992 .ADD8 => riscv_util.writeAddend(i8, .add, code[0..1], S + A),
1993 .SUB8 => riscv_util.writeAddend(i8, .sub, code[0..1], S + A),
1994 .ADD16 => riscv_util.writeAddend(i16, .add, code[0..2], S + A),
1995 .SUB16 => riscv_util.writeAddend(i16, .sub, code[0..2], S + A),
1996 .ADD32 => riscv_util.writeAddend(i32, .add, code[0..4], S + A),
1997 .SUB32 => riscv_util.writeAddend(i32, .sub, code[0..4], S + A),
1998 .ADD64 => riscv_util.writeAddend(i64, .add, code[0..8], S + A),
1999 .SUB64 => riscv_util.writeAddend(i64, .sub, code[0..8], S + A),
2000
2001 .SET8 => mem.writeInt(i8, code[0..1], @as(i8, @truncate(S + A)), .little),
2002 .SET16 => mem.writeInt(i16, code[0..2], @as(i16, @truncate(S + A)), .little),
2003 .SET32 => mem.writeInt(i32, code[0..4], @as(i32, @truncate(S + A)), .little),
2004
2005 .SET6 => riscv_util.writeSetSub6(.set, code[0..1], S + A),
2006 .SUB6 => riscv_util.writeSetSub6(.sub, code[0..1], S + A),
2007
2008 .SET_ULEB128 => riscv_util.writeSetUleb(code, S + A),
2009 .SUB_ULEB128 => riscv_util.writeSubUleb(code, S - A),
20412010
20422011 else => try atom.reportUnhandledRelocError(rel, elf_file),
20432012 }
......@@ -2108,14 +2077,16 @@ pub const Extra = struct {
21082077const std = @import("std");
21092078const assert = std.debug.assert;
21102079const elf = std.elf;
2111const eh_frame = @import("eh_frame.zig");
21122080const log = std.log.scoped(.link);
21132081const math = std.math;
21142082const mem = std.mem;
21152083const relocs_log = std.log.scoped(.link_relocs);
2084const Allocator = mem.Allocator;
2085const Writer = std.Io.Writer;
2086
2087const eh_frame = @import("eh_frame.zig");
21162088const relocation = @import("relocation.zig");
21172089
2118const Allocator = mem.Allocator;
21192090const Atom = @This();
21202091const Elf = @import("../Elf.zig");
21212092const Fde = eh_frame.Fde;
src/link/Elf/AtomList.zig+4-5
......@@ -89,7 +89,7 @@ pub fn allocate(list: *AtomList, elf_file: *Elf) !void {
8989 list.dirty = false;
9090}
9191
92pub fn write(list: AtomList, buffer: *std.array_list.Managed(u8), undefs: anytype, elf_file: *Elf) !void {
92pub fn write(list: AtomList, buffer: *std.Io.Writer.Allocating, undefs: anytype, elf_file: *Elf) !void {
9393 const gpa = elf_file.base.comp.gpa;
9494 const osec = elf_file.sections.items(.shdr)[list.output_section_index];
9595 assert(osec.sh_type != elf.SHT_NOBITS);
......@@ -98,8 +98,7 @@ pub fn write(list: AtomList, buffer: *std.array_list.Managed(u8), undefs: anytyp
9898 log.debug("writing atoms in section '{s}'", .{elf_file.getShString(osec.sh_name)});
9999
100100 const list_size = math.cast(usize, list.size) orelse return error.Overflow;
101 try buffer.ensureUnusedCapacity(list_size);
102 buffer.appendNTimesAssumeCapacity(0, list_size);
101 try buffer.writer.splatByteAll(0, list_size);
103102
104103 for (list.atoms.keys()) |ref| {
105104 const atom_ptr = elf_file.atom(ref).?;
......@@ -113,7 +112,7 @@ pub fn write(list: AtomList, buffer: *std.array_list.Managed(u8), undefs: anytyp
113112 const object = atom_ptr.file(elf_file).?.object;
114113 const code = try object.codeDecompressAlloc(elf_file, ref.index);
115114 defer gpa.free(code);
116 const out_code = buffer.items[off..][0..size];
115 const out_code = buffer.written()[off..][0..size];
117116 @memcpy(out_code, code);
118117
119118 if (osec.sh_flags & elf.SHF_ALLOC == 0)
......@@ -122,7 +121,7 @@ pub fn write(list: AtomList, buffer: *std.array_list.Managed(u8), undefs: anytyp
122121 try atom_ptr.resolveRelocsAlloc(elf_file, out_code);
123122 }
124123
125 try elf_file.base.file.?.pwriteAll(buffer.items, list.offset(elf_file));
124 try elf_file.base.file.?.pwriteAll(buffer.written(), list.offset(elf_file));
126125 buffer.clearRetainingCapacity();
127126}
128127
src/link/Elf/Object.zig+1-1
......@@ -952,7 +952,7 @@ pub fn convertCommonSymbols(self: *Object, elf_file: *Elf) !void {
952952 const is_tls = sym.type(elf_file) == elf.STT_TLS;
953953 const name = if (is_tls) ".tls_common" else ".common";
954954 const name_offset = @as(u32, @intCast(self.strtab.items.len));
955 try self.strtab.writer(gpa).print("{s}\x00", .{name});
955 try self.strtab.print(gpa, "{s}\x00", .{name});
956956
957957 var sh_flags: u32 = elf.SHF_ALLOC | elf.SHF_WRITE;
958958 if (is_tls) sh_flags |= elf.SHF_TLS;
src/link/Elf/gc.zig-16
......@@ -162,22 +162,6 @@ fn prune(elf_file: *Elf) void {
162162 }
163163}
164164
165pub fn dumpPrunedAtoms(elf_file: *Elf) !void {
166 const stderr = std.fs.File.stderr().deprecatedWriter();
167 for (elf_file.objects.items) |index| {
168 const file = elf_file.file(index).?;
169 for (file.atoms()) |atom_index| {
170 const atom = file.atom(atom_index) orelse continue;
171 if (!atom.alive)
172 // TODO should we simply print to stderr?
173 try stderr.print("link: removing unused section '{s}' in file '{f}'\n", .{
174 atom.name(elf_file),
175 atom.file(elf_file).?.fmtPath(),
176 });
177 }
178 }
179}
180
181165const Level = struct {
182166 value: usize = 0,
183167
src/link/Elf/relocatable.zig+24-21
......@@ -100,32 +100,33 @@ pub fn flushStaticLib(elf_file: *Elf, comp: *Compilation) !void {
100100 state_log.debug("ar_strtab\n{f}\n", .{ar_strtab});
101101 }
102102
103 var buffer = std.array_list.Managed(u8).init(gpa);
104 defer buffer.deinit();
105 try buffer.ensureTotalCapacityPrecise(total_size);
103 const buffer = try gpa.alloc(u8, total_size);
104 defer gpa.free(buffer);
105
106 var writer: std.Io.Writer = .fixed(buffer);
106107
107108 // Write magic
108 try buffer.writer().writeAll(elf.ARMAG);
109 try writer.writeAll(elf.ARMAG);
109110
110111 // Write symtab
111 try ar_symtab.write(.p64, elf_file, buffer.writer());
112 try ar_symtab.write(.p64, elf_file, &writer);
112113
113114 // Write strtab
114115 if (ar_strtab.size() > 0) {
115 if (!mem.isAligned(buffer.items.len, 2)) try buffer.writer().writeByte(0);
116 try ar_strtab.write(buffer.writer());
116 if (!mem.isAligned(writer.end, 2)) try writer.writeByte(0);
117 try ar_strtab.write(&writer);
117118 }
118119
119120 // Write object files
120121 for (files.items) |index| {
121 if (!mem.isAligned(buffer.items.len, 2)) try buffer.writer().writeByte(0);
122 try elf_file.file(index).?.writeAr(elf_file, buffer.writer());
122 if (!mem.isAligned(writer.end, 2)) try writer.writeByte(0);
123 try elf_file.file(index).?.writeAr(elf_file, &writer);
123124 }
124125
125 assert(buffer.items.len == total_size);
126 assert(writer.buffered().len == total_size);
126127
127128 try elf_file.base.file.?.setEndPos(total_size);
128 try elf_file.base.file.?.pwriteAll(buffer.items, 0);
129 try elf_file.base.file.?.pwriteAll(writer.buffered(), 0);
129130
130131 if (diags.hasErrors()) return error.LinkFailure;
131132}
......@@ -407,15 +408,16 @@ fn writeSyntheticSections(elf_file: *Elf) !void {
407408 };
408409 const shdr = slice.items(.shdr)[shndx];
409410 const sh_size = math.cast(usize, shdr.sh_size) orelse return error.Overflow;
410 var buffer = try std.array_list.Managed(u8).initCapacity(gpa, @intCast(sh_size - existing_size));
411 defer buffer.deinit();
412 try eh_frame.writeEhFrameRelocatable(elf_file, buffer.writer());
411 const buffer = try gpa.alloc(u8, @intCast(sh_size - existing_size));
412 defer gpa.free(buffer);
413 var writer: std.Io.Writer = .fixed(buffer);
414 try eh_frame.writeEhFrameRelocatable(elf_file, &writer);
413415 log.debug("writing .eh_frame from 0x{x} to 0x{x}", .{
414416 shdr.sh_offset + existing_size,
415417 shdr.sh_offset + sh_size,
416418 });
417 assert(buffer.items.len == sh_size - existing_size);
418 try elf_file.base.file.?.pwriteAll(buffer.items, shdr.sh_offset + existing_size);
419 assert(writer.buffered().len == sh_size - existing_size);
420 try elf_file.base.file.?.pwriteAll(writer.buffered(), shdr.sh_offset + existing_size);
419421 }
420422 if (elf_file.section_indexes.eh_frame_rela) |shndx| {
421423 const shdr = slice.items(.shdr)[shndx];
......@@ -446,15 +448,16 @@ fn writeGroups(elf_file: *Elf) !void {
446448 for (elf_file.group_sections.items) |cgs| {
447449 const shdr = elf_file.sections.items(.shdr)[cgs.shndx];
448450 const sh_size = math.cast(usize, shdr.sh_size) orelse return error.Overflow;
449 var buffer = try std.array_list.Managed(u8).initCapacity(gpa, sh_size);
450 defer buffer.deinit();
451 try cgs.write(elf_file, buffer.writer());
452 assert(buffer.items.len == sh_size);
451 const buffer = try gpa.alloc(u8, sh_size);
452 defer gpa.free(buffer);
453 var writer: std.Io.Writer = .fixed(buffer);
454 try cgs.write(elf_file, &writer);
455 assert(writer.buffered().len == sh_size);
453456 log.debug("writing group from 0x{x} to 0x{x}", .{
454457 shdr.sh_offset,
455458 shdr.sh_offset + shdr.sh_size,
456459 });
457 try elf_file.base.file.?.pwriteAll(buffer.items, shdr.sh_offset);
460 try elf_file.base.file.?.pwriteAll(writer.buffered(), shdr.sh_offset);
458461 }
459462}
460463
src/link/Elf/synthetic_sections.zig+53-51
......@@ -94,134 +94,134 @@ pub const DynamicSection = struct {
9494 return nentries * @sizeOf(elf.Elf64_Dyn);
9595 }
9696
97 pub fn write(dt: DynamicSection, elf_file: *Elf, writer: anytype) !void {
97 pub fn write(dt: DynamicSection, elf_file: *Elf, writer: *std.Io.Writer) !void {
9898 const shdrs = elf_file.sections.items(.shdr);
9999
100100 // NEEDED
101101 for (dt.needed.items) |off| {
102 try writer.writeStruct(elf.Elf64_Dyn{ .d_tag = elf.DT_NEEDED, .d_val = off });
102 try writer.writeStruct(@as(elf.Elf64_Dyn, .{ .d_tag = elf.DT_NEEDED, .d_val = off }), .little);
103103 }
104104
105105 if (dt.soname) |off| {
106 try writer.writeStruct(elf.Elf64_Dyn{ .d_tag = elf.DT_SONAME, .d_val = off });
106 try writer.writeStruct(@as(elf.Elf64_Dyn, .{ .d_tag = elf.DT_SONAME, .d_val = off }), .little);
107107 }
108108
109109 // RUNPATH
110110 // TODO add option in Options to revert to old RPATH tag
111111 if (dt.rpath > 0) {
112 try writer.writeStruct(elf.Elf64_Dyn{ .d_tag = elf.DT_RUNPATH, .d_val = dt.rpath });
112 try writer.writeStruct(@as(elf.Elf64_Dyn, .{ .d_tag = elf.DT_RUNPATH, .d_val = dt.rpath }), .little);
113113 }
114114
115115 // INIT
116116 if (elf_file.sectionByName(".init")) |shndx| {
117117 const addr = shdrs[shndx].sh_addr;
118 try writer.writeStruct(elf.Elf64_Dyn{ .d_tag = elf.DT_INIT, .d_val = addr });
118 try writer.writeStruct(@as(elf.Elf64_Dyn, .{ .d_tag = elf.DT_INIT, .d_val = addr }), .little);
119119 }
120120
121121 // FINI
122122 if (elf_file.sectionByName(".fini")) |shndx| {
123123 const addr = shdrs[shndx].sh_addr;
124 try writer.writeStruct(elf.Elf64_Dyn{ .d_tag = elf.DT_FINI, .d_val = addr });
124 try writer.writeStruct(@as(elf.Elf64_Dyn, .{ .d_tag = elf.DT_FINI, .d_val = addr }), .little);
125125 }
126126
127127 // INIT_ARRAY
128128 if (elf_file.sectionByName(".init_array")) |shndx| {
129129 const shdr = shdrs[shndx];
130 try writer.writeStruct(elf.Elf64_Dyn{ .d_tag = elf.DT_INIT_ARRAY, .d_val = shdr.sh_addr });
131 try writer.writeStruct(elf.Elf64_Dyn{ .d_tag = elf.DT_INIT_ARRAYSZ, .d_val = shdr.sh_size });
130 try writer.writeStruct(@as(elf.Elf64_Dyn, .{ .d_tag = elf.DT_INIT_ARRAY, .d_val = shdr.sh_addr }), .little);
131 try writer.writeStruct(@as(elf.Elf64_Dyn, .{ .d_tag = elf.DT_INIT_ARRAYSZ, .d_val = shdr.sh_size }), .little);
132132 }
133133
134134 // FINI_ARRAY
135135 if (elf_file.sectionByName(".fini_array")) |shndx| {
136136 const shdr = shdrs[shndx];
137 try writer.writeStruct(elf.Elf64_Dyn{ .d_tag = elf.DT_FINI_ARRAY, .d_val = shdr.sh_addr });
138 try writer.writeStruct(elf.Elf64_Dyn{ .d_tag = elf.DT_FINI_ARRAYSZ, .d_val = shdr.sh_size });
137 try writer.writeStruct(@as(elf.Elf64_Dyn, .{ .d_tag = elf.DT_FINI_ARRAY, .d_val = shdr.sh_addr }), .little);
138 try writer.writeStruct(@as(elf.Elf64_Dyn, .{ .d_tag = elf.DT_FINI_ARRAYSZ, .d_val = shdr.sh_size }), .little);
139139 }
140140
141141 // RELA
142142 if (elf_file.section_indexes.rela_dyn) |shndx| {
143143 const shdr = shdrs[shndx];
144 try writer.writeStruct(elf.Elf64_Dyn{ .d_tag = elf.DT_RELA, .d_val = shdr.sh_addr });
145 try writer.writeStruct(elf.Elf64_Dyn{ .d_tag = elf.DT_RELASZ, .d_val = shdr.sh_size });
146 try writer.writeStruct(elf.Elf64_Dyn{ .d_tag = elf.DT_RELAENT, .d_val = shdr.sh_entsize });
144 try writer.writeStruct(@as(elf.Elf64_Dyn, .{ .d_tag = elf.DT_RELA, .d_val = shdr.sh_addr }), .little);
145 try writer.writeStruct(@as(elf.Elf64_Dyn, .{ .d_tag = elf.DT_RELASZ, .d_val = shdr.sh_size }), .little);
146 try writer.writeStruct(@as(elf.Elf64_Dyn, .{ .d_tag = elf.DT_RELAENT, .d_val = shdr.sh_entsize }), .little);
147147 }
148148
149149 // JMPREL
150150 if (elf_file.section_indexes.rela_plt) |shndx| {
151151 const shdr = shdrs[shndx];
152 try writer.writeStruct(elf.Elf64_Dyn{ .d_tag = elf.DT_JMPREL, .d_val = shdr.sh_addr });
153 try writer.writeStruct(elf.Elf64_Dyn{ .d_tag = elf.DT_PLTRELSZ, .d_val = shdr.sh_size });
154 try writer.writeStruct(elf.Elf64_Dyn{ .d_tag = elf.DT_PLTREL, .d_val = elf.DT_RELA });
152 try writer.writeStruct(@as(elf.Elf64_Dyn, .{ .d_tag = elf.DT_JMPREL, .d_val = shdr.sh_addr }), .little);
153 try writer.writeStruct(@as(elf.Elf64_Dyn, .{ .d_tag = elf.DT_PLTRELSZ, .d_val = shdr.sh_size }), .little);
154 try writer.writeStruct(@as(elf.Elf64_Dyn, .{ .d_tag = elf.DT_PLTREL, .d_val = elf.DT_RELA }), .little);
155155 }
156156
157157 // PLTGOT
158158 if (elf_file.section_indexes.got_plt) |shndx| {
159159 const addr = shdrs[shndx].sh_addr;
160 try writer.writeStruct(elf.Elf64_Dyn{ .d_tag = elf.DT_PLTGOT, .d_val = addr });
160 try writer.writeStruct(@as(elf.Elf64_Dyn, .{ .d_tag = elf.DT_PLTGOT, .d_val = addr }), .little);
161161 }
162162
163163 {
164164 assert(elf_file.section_indexes.hash != null);
165165 const addr = shdrs[elf_file.section_indexes.hash.?].sh_addr;
166 try writer.writeStruct(elf.Elf64_Dyn{ .d_tag = elf.DT_HASH, .d_val = addr });
166 try writer.writeStruct(@as(elf.Elf64_Dyn, .{ .d_tag = elf.DT_HASH, .d_val = addr }), .little);
167167 }
168168
169169 if (elf_file.section_indexes.gnu_hash) |shndx| {
170170 const addr = shdrs[shndx].sh_addr;
171 try writer.writeStruct(elf.Elf64_Dyn{ .d_tag = elf.DT_GNU_HASH, .d_val = addr });
171 try writer.writeStruct(@as(elf.Elf64_Dyn, .{ .d_tag = elf.DT_GNU_HASH, .d_val = addr }), .little);
172172 }
173173
174174 // TEXTREL
175175 if (elf_file.has_text_reloc) {
176 try writer.writeStruct(elf.Elf64_Dyn{ .d_tag = elf.DT_TEXTREL, .d_val = 0 });
176 try writer.writeStruct(@as(elf.Elf64_Dyn, .{ .d_tag = elf.DT_TEXTREL, .d_val = 0 }), .little);
177177 }
178178
179179 // SYMTAB + SYMENT
180180 {
181181 assert(elf_file.section_indexes.dynsymtab != null);
182182 const shdr = shdrs[elf_file.section_indexes.dynsymtab.?];
183 try writer.writeStruct(elf.Elf64_Dyn{ .d_tag = elf.DT_SYMTAB, .d_val = shdr.sh_addr });
184 try writer.writeStruct(elf.Elf64_Dyn{ .d_tag = elf.DT_SYMENT, .d_val = shdr.sh_entsize });
183 try writer.writeStruct(@as(elf.Elf64_Dyn, .{ .d_tag = elf.DT_SYMTAB, .d_val = shdr.sh_addr }), .little);
184 try writer.writeStruct(@as(elf.Elf64_Dyn, .{ .d_tag = elf.DT_SYMENT, .d_val = shdr.sh_entsize }), .little);
185185 }
186186
187187 // STRTAB + STRSZ
188188 {
189189 assert(elf_file.section_indexes.dynstrtab != null);
190190 const shdr = shdrs[elf_file.section_indexes.dynstrtab.?];
191 try writer.writeStruct(elf.Elf64_Dyn{ .d_tag = elf.DT_STRTAB, .d_val = shdr.sh_addr });
192 try writer.writeStruct(elf.Elf64_Dyn{ .d_tag = elf.DT_STRSZ, .d_val = shdr.sh_size });
191 try writer.writeStruct(@as(elf.Elf64_Dyn, .{ .d_tag = elf.DT_STRTAB, .d_val = shdr.sh_addr }), .little);
192 try writer.writeStruct(@as(elf.Elf64_Dyn, .{ .d_tag = elf.DT_STRSZ, .d_val = shdr.sh_size }), .little);
193193 }
194194
195195 // VERSYM
196196 if (elf_file.section_indexes.versym) |shndx| {
197197 const addr = shdrs[shndx].sh_addr;
198 try writer.writeStruct(elf.Elf64_Dyn{ .d_tag = elf.DT_VERSYM, .d_val = addr });
198 try writer.writeStruct(@as(elf.Elf64_Dyn, .{ .d_tag = elf.DT_VERSYM, .d_val = addr }), .little);
199199 }
200200
201201 // VERNEED + VERNEEDNUM
202202 if (elf_file.section_indexes.verneed) |shndx| {
203203 const addr = shdrs[shndx].sh_addr;
204 try writer.writeStruct(elf.Elf64_Dyn{ .d_tag = elf.DT_VERNEED, .d_val = addr });
205 try writer.writeStruct(elf.Elf64_Dyn{
204 try writer.writeStruct(@as(elf.Elf64_Dyn, .{ .d_tag = elf.DT_VERNEED, .d_val = addr }), .little);
205 try writer.writeStruct(@as(elf.Elf64_Dyn, .{
206206 .d_tag = elf.DT_VERNEEDNUM,
207207 .d_val = elf_file.verneed.verneed.items.len,
208 });
208 }), .little);
209209 }
210210
211211 // FLAGS
212212 if (dt.getFlags(elf_file)) |flags| {
213 try writer.writeStruct(elf.Elf64_Dyn{ .d_tag = elf.DT_FLAGS, .d_val = flags });
213 try writer.writeStruct(@as(elf.Elf64_Dyn, .{ .d_tag = elf.DT_FLAGS, .d_val = flags }), .little);
214214 }
215215 // FLAGS_1
216216 if (dt.getFlags1(elf_file)) |flags_1| {
217 try writer.writeStruct(elf.Elf64_Dyn{ .d_tag = elf.DT_FLAGS_1, .d_val = flags_1 });
217 try writer.writeStruct(@as(elf.Elf64_Dyn, .{ .d_tag = elf.DT_FLAGS_1, .d_val = flags_1 }), .little);
218218 }
219219
220220 // DEBUG
221 if (!elf_file.isEffectivelyDynLib()) try writer.writeStruct(elf.Elf64_Dyn{ .d_tag = elf.DT_DEBUG, .d_val = 0 });
221 if (!elf_file.isEffectivelyDynLib()) try writer.writeStruct(@as(elf.Elf64_Dyn, .{ .d_tag = elf.DT_DEBUG, .d_val = 0 }), .little);
222222
223223 // NULL
224 try writer.writeStruct(elf.Elf64_Dyn{ .d_tag = elf.DT_NULL, .d_val = 0 });
224 try writer.writeStruct(@as(elf.Elf64_Dyn, .{ .d_tag = elf.DT_NULL, .d_val = 0 }), .little);
225225 }
226226};
227227
......@@ -360,7 +360,7 @@ pub const GotSection = struct {
360360 return s;
361361 }
362362
363 pub fn write(got: GotSection, elf_file: *Elf, writer: anytype) !void {
363 pub fn write(got: GotSection, elf_file: *Elf, writer: *std.Io.Writer) !void {
364364 const comp = elf_file.base.comp;
365365 const is_dyn_lib = elf_file.isEffectivelyDynLib();
366366 const apply_relocs = true; // TODO add user option for this
......@@ -666,7 +666,7 @@ pub const PltSection = struct {
666666 };
667667 }
668668
669 pub fn write(plt: PltSection, elf_file: *Elf, writer: anytype) !void {
669 pub fn write(plt: PltSection, elf_file: *Elf, writer: *std.Io.Writer) !void {
670670 const cpu_arch = elf_file.getTarget().cpu.arch;
671671 switch (cpu_arch) {
672672 .x86_64 => try x86_64.write(plt, elf_file, writer),
......@@ -763,7 +763,7 @@ pub const PltSection = struct {
763763 }
764764
765765 const x86_64 = struct {
766 fn write(plt: PltSection, elf_file: *Elf, writer: anytype) !void {
766 fn write(plt: PltSection, elf_file: *Elf, writer: *std.Io.Writer) !void {
767767 const shdrs = elf_file.sections.items(.shdr);
768768 const plt_addr = shdrs[elf_file.section_indexes.plt.?].sh_addr;
769769 const got_plt_addr = shdrs[elf_file.section_indexes.got_plt.?].sh_addr;
......@@ -778,7 +778,7 @@ pub const PltSection = struct {
778778 disp = @as(i64, @intCast(got_plt_addr + 16)) - @as(i64, @intCast(plt_addr + 14)) - 4;
779779 mem.writeInt(i32, preamble[14..][0..4], @as(i32, @intCast(disp)), .little);
780780 try writer.writeAll(&preamble);
781 try writer.writeByteNTimes(0xcc, preambleSize(.x86_64) - preamble.len);
781 try writer.splatByteAll(0xcc, preambleSize(.x86_64) - preamble.len);
782782
783783 for (plt.symbols.items, 0..) |ref, i| {
784784 const sym = elf_file.symbol(ref).?;
......@@ -798,7 +798,7 @@ pub const PltSection = struct {
798798 };
799799
800800 const aarch64 = struct {
801 fn write(plt: PltSection, elf_file: *Elf, writer: anytype) !void {
801 fn write(plt: PltSection, elf_file: *Elf, writer: *std.Io.Writer) !void {
802802 {
803803 const shdrs = elf_file.sections.items(.shdr);
804804 const plt_addr: i64 = @intCast(shdrs[elf_file.section_indexes.plt.?].sh_addr);
......@@ -853,7 +853,7 @@ pub const GotPltSection = struct {
853853 return preamble_size + elf_file.plt.symbols.items.len * 8;
854854 }
855855
856 pub fn write(got_plt: GotPltSection, elf_file: *Elf, writer: anytype) !void {
856 pub fn write(got_plt: GotPltSection, elf_file: *Elf, writer: *std.Io.Writer) !void {
857857 _ = got_plt;
858858 {
859859 // [0]: _DYNAMIC
......@@ -904,7 +904,7 @@ pub const PltGotSection = struct {
904904 };
905905 }
906906
907 pub fn write(plt_got: PltGotSection, elf_file: *Elf, writer: anytype) !void {
907 pub fn write(plt_got: PltGotSection, elf_file: *Elf, writer: *std.Io.Writer) !void {
908908 const cpu_arch = elf_file.getTarget().cpu.arch;
909909 switch (cpu_arch) {
910910 .x86_64 => try x86_64.write(plt_got, elf_file, writer),
......@@ -940,7 +940,7 @@ pub const PltGotSection = struct {
940940 }
941941
942942 const x86_64 = struct {
943 pub fn write(plt_got: PltGotSection, elf_file: *Elf, writer: anytype) !void {
943 pub fn write(plt_got: PltGotSection, elf_file: *Elf, writer: *std.Io.Writer) !void {
944944 for (plt_got.symbols.items) |ref| {
945945 const sym = elf_file.symbol(ref).?;
946946 const target_addr = sym.gotAddress(elf_file);
......@@ -958,7 +958,7 @@ pub const PltGotSection = struct {
958958 };
959959
960960 const aarch64 = struct {
961 fn write(plt_got: PltGotSection, elf_file: *Elf, writer: anytype) !void {
961 fn write(plt_got: PltGotSection, elf_file: *Elf, writer: *std.Io.Writer) !void {
962962 for (plt_got.symbols.items) |ref| {
963963 const sym = elf_file.symbol(ref).?;
964964 const target_addr = sym.gotAddress(elf_file);
......@@ -1133,14 +1133,14 @@ pub const DynsymSection = struct {
11331133 return @as(u32, @intCast(dynsym.entries.items.len + 1));
11341134 }
11351135
1136 pub fn write(dynsym: DynsymSection, elf_file: *Elf, writer: anytype) !void {
1137 try writer.writeStruct(Elf.null_sym);
1136 pub fn write(dynsym: DynsymSection, elf_file: *Elf, writer: *std.Io.Writer) !void {
1137 try writer.writeStruct(Elf.null_sym, .little);
11381138 for (dynsym.entries.items) |entry| {
11391139 const sym = elf_file.symbol(entry.ref).?;
11401140 var out_sym: elf.Elf64_Sym = Elf.null_sym;
11411141 sym.setOutputSym(elf_file, &out_sym);
11421142 out_sym.st_name = entry.off;
1143 try writer.writeStruct(out_sym);
1143 try writer.writeStruct(out_sym, .little);
11441144 }
11451145 }
11461146};
......@@ -1175,10 +1175,12 @@ pub const HashSection = struct {
11751175 }
11761176
11771177 try hs.buffer.ensureTotalCapacityPrecise(gpa, (2 + nsyms * 2) * 4);
1178 hs.buffer.writer(gpa).writeInt(u32, @as(u32, @intCast(nsyms)), .little) catch unreachable;
1179 hs.buffer.writer(gpa).writeInt(u32, @as(u32, @intCast(nsyms)), .little) catch unreachable;
1180 hs.buffer.writer(gpa).writeAll(mem.sliceAsBytes(buckets)) catch unreachable;
1181 hs.buffer.writer(gpa).writeAll(mem.sliceAsBytes(chains)) catch unreachable;
1178 var w: std.Io.Writer = .fixed(hs.buffer.unusedCapacitySlice());
1179 w.writeInt(u32, @as(u32, @intCast(nsyms)), .little) catch unreachable;
1180 w.writeInt(u32, @as(u32, @intCast(nsyms)), .little) catch unreachable;
1181 w.writeAll(@ptrCast(buckets)) catch unreachable;
1182 w.writeAll(@ptrCast(chains)) catch unreachable;
1183 hs.buffer.items.len += w.end;
11821184 }
11831185
11841186 pub inline fn size(hs: HashSection) usize {
......@@ -1439,7 +1441,7 @@ pub const VerneedSection = struct {
14391441 return vern.verneed.items.len * @sizeOf(elf.Elf64_Verneed) + vern.vernaux.items.len * @sizeOf(elf.Vernaux);
14401442 }
14411443
1442 pub fn write(vern: VerneedSection, writer: anytype) !void {
1444 pub fn write(vern: VerneedSection, writer: *std.Io.Writer) !void {
14431445 try writer.writeAll(mem.sliceAsBytes(vern.verneed.items));
14441446 try writer.writeAll(mem.sliceAsBytes(vern.vernaux.items));
14451447 }
......@@ -1467,7 +1469,7 @@ pub const GroupSection = struct {
14671469 return (members.len + 1) * @sizeOf(u32);
14681470 }
14691471
1470 pub fn write(cgs: GroupSection, elf_file: *Elf, writer: anytype) !void {
1472 pub fn write(cgs: GroupSection, elf_file: *Elf, writer: *std.Io.Writer) !void {
14711473 const cg = cgs.group(elf_file);
14721474 const object = cg.file(elf_file).object;
14731475 const members = cg.members(elf_file);
......@@ -1495,7 +1497,7 @@ pub const GroupSection = struct {
14951497 }
14961498};
14971499
1498fn writeInt(value: anytype, elf_file: *Elf, writer: anytype) !void {
1500fn writeInt(value: anytype, elf_file: *Elf, writer: *std.Io.Writer) !void {
14991501 const entry_size = elf_file.archPtrWidthBytes();
15001502 const target = elf_file.getTarget();
15011503 const endian = target.cpu.arch.endian();
src/link/MachO.zig+71-65
......@@ -589,7 +589,7 @@ pub fn flush(
589589 );
590590
591591 const ncmds, const sizeofcmds, const uuid_cmd_offset = self.writeLoadCommands() catch |err| switch (err) {
592 error.NoSpaceLeft => unreachable,
592 error.WriteFailed => unreachable,
593593 error.OutOfMemory => return error.OutOfMemory,
594594 error.LinkFailure => return error.LinkFailure,
595595 };
......@@ -1074,7 +1074,7 @@ fn accessLibPath(
10741074
10751075 for (&[_][]const u8{ ".tbd", ".dylib", "" }) |ext| {
10761076 test_path.clearRetainingCapacity();
1077 try test_path.writer().print("{s}" ++ sep ++ "lib{s}{s}", .{ search_dir, name, ext });
1077 try test_path.print("{s}" ++ sep ++ "lib{s}{s}", .{ search_dir, name, ext });
10781078 try checked_paths.append(try arena.dupe(u8, test_path.items));
10791079 fs.cwd().access(test_path.items, .{}) catch |err| switch (err) {
10801080 error.FileNotFound => continue,
......@@ -1097,7 +1097,7 @@ fn accessFrameworkPath(
10971097
10981098 for (&[_][]const u8{ ".tbd", ".dylib", "" }) |ext| {
10991099 test_path.clearRetainingCapacity();
1100 try test_path.writer().print("{s}" ++ sep ++ "{s}.framework" ++ sep ++ "{s}{s}", .{
1100 try test_path.print("{s}" ++ sep ++ "{s}.framework" ++ sep ++ "{s}{s}", .{
11011101 search_dir,
11021102 name,
11031103 name,
......@@ -1178,9 +1178,9 @@ fn parseDependentDylibs(self: *MachO) !void {
11781178 for (&[_][]const u8{ ".tbd", ".dylib", "" }) |ext| {
11791179 test_path.clearRetainingCapacity();
11801180 if (self.base.comp.sysroot) |root| {
1181 try test_path.writer().print("{s}" ++ fs.path.sep_str ++ "{s}{s}", .{ root, path, ext });
1181 try test_path.print("{s}" ++ fs.path.sep_str ++ "{s}{s}", .{ root, path, ext });
11821182 } else {
1183 try test_path.writer().print("{s}{s}", .{ path, ext });
1183 try test_path.print("{s}{s}", .{ path, ext });
11841184 }
11851185 try checked_paths.append(try arena.dupe(u8, test_path.items));
11861186 fs.cwd().access(test_path.items, .{}) catch |err| switch (err) {
......@@ -2528,8 +2528,8 @@ fn writeThunkWorker(self: *MachO, thunk: Thunk) void {
25282528 fn doWork(th: Thunk, buffer: []u8, macho_file: *MachO) !void {
25292529 const off = try macho_file.cast(usize, th.value);
25302530 const size = th.size();
2531 var stream = std.io.fixedBufferStream(buffer[off..][0..size]);
2532 try th.write(macho_file, stream.writer());
2531 var stream: Writer = .fixed(buffer[off..][0..size]);
2532 try th.write(macho_file, &stream);
25332533 }
25342534 }.doWork;
25352535 const out = self.sections.items(.out)[thunk.out_n_sect].items;
......@@ -2556,15 +2556,15 @@ fn writeSyntheticSectionWorker(self: *MachO, sect_id: u8, out: []u8) void {
25562556
25572557 const doWork = struct {
25582558 fn doWork(macho_file: *MachO, tag: Tag, buffer: []u8) !void {
2559 var stream = std.io.fixedBufferStream(buffer);
2559 var stream: Writer = .fixed(buffer);
25602560 switch (tag) {
25612561 .eh_frame => eh_frame.write(macho_file, buffer),
25622562 .unwind_info => try macho_file.unwind_info.write(macho_file, buffer),
2563 .got => try macho_file.got.write(macho_file, stream.writer()),
2564 .stubs => try macho_file.stubs.write(macho_file, stream.writer()),
2565 .la_symbol_ptr => try macho_file.la_symbol_ptr.write(macho_file, stream.writer()),
2566 .tlv_ptr => try macho_file.tlv_ptr.write(macho_file, stream.writer()),
2567 .objc_stubs => try macho_file.objc_stubs.write(macho_file, stream.writer()),
2563 .got => try macho_file.got.write(macho_file, &stream),
2564 .stubs => try macho_file.stubs.write(macho_file, &stream),
2565 .la_symbol_ptr => try macho_file.la_symbol_ptr.write(macho_file, &stream),
2566 .tlv_ptr => try macho_file.tlv_ptr.write(macho_file, &stream),
2567 .objc_stubs => try macho_file.objc_stubs.write(macho_file, &stream),
25682568 }
25692569 }
25702570 }.doWork;
......@@ -2605,8 +2605,8 @@ fn updateLazyBindSizeWorker(self: *MachO) void {
26052605 try macho_file.lazy_bind_section.updateSize(macho_file);
26062606 const sect_id = macho_file.stubs_helper_sect_index.?;
26072607 const out = &macho_file.sections.items(.out)[sect_id];
2608 var stream = std.io.fixedBufferStream(out.items);
2609 try macho_file.stubs_helper.write(macho_file, stream.writer());
2608 var stream: Writer = .fixed(out.items);
2609 try macho_file.stubs_helper.write(macho_file, &stream);
26102610 }
26112611 }.doWork;
26122612 doWork(self) catch |err|
......@@ -2669,18 +2669,17 @@ fn writeDyldInfo(self: *MachO) !void {
26692669 defer gpa.free(buffer);
26702670 @memset(buffer, 0);
26712671
2672 var stream = std.io.fixedBufferStream(buffer);
2673 const writer = stream.writer();
2674
2675 try self.rebase_section.write(writer);
2676 try stream.seekTo(cmd.bind_off - base_off);
2677 try self.bind_section.write(writer);
2678 try stream.seekTo(cmd.weak_bind_off - base_off);
2679 try self.weak_bind_section.write(writer);
2680 try stream.seekTo(cmd.lazy_bind_off - base_off);
2681 try self.lazy_bind_section.write(writer);
2682 try stream.seekTo(cmd.export_off - base_off);
2683 try self.export_trie.write(writer);
2672 var writer: Writer = .fixed(buffer);
2673
2674 try self.rebase_section.write(&writer);
2675 writer.end = @intCast(cmd.bind_off - base_off);
2676 try self.bind_section.write(&writer);
2677 writer.end = @intCast(cmd.weak_bind_off - base_off);
2678 try self.weak_bind_section.write(&writer);
2679 writer.end = @intCast(cmd.lazy_bind_off - base_off);
2680 try self.lazy_bind_section.write(&writer);
2681 writer.end = @intCast(cmd.export_off - base_off);
2682 try self.export_trie.write(&writer);
26842683 try self.pwriteAll(buffer, cmd.rebase_off);
26852684}
26862685
......@@ -2689,10 +2688,10 @@ pub fn writeDataInCode(self: *MachO) !void {
26892688 defer tracy.end();
26902689 const gpa = self.base.comp.gpa;
26912690 const cmd = self.data_in_code_cmd;
2692 var buffer = try std.array_list.Managed(u8).initCapacity(gpa, self.data_in_code.size());
2691 var buffer = try std.Io.Writer.Allocating.initCapacity(gpa, self.data_in_code.size());
26932692 defer buffer.deinit();
2694 try self.data_in_code.write(self, buffer.writer());
2695 try self.pwriteAll(buffer.items, cmd.dataoff);
2693 self.data_in_code.write(self, &buffer.writer) catch return error.OutOfMemory;
2694 try self.pwriteAll(buffer.written(), cmd.dataoff);
26962695}
26972696
26982697fn writeIndsymtab(self: *MachO) !void {
......@@ -2701,10 +2700,11 @@ fn writeIndsymtab(self: *MachO) !void {
27012700 const gpa = self.base.comp.gpa;
27022701 const cmd = self.dysymtab_cmd;
27032702 const needed_size = cmd.nindirectsyms * @sizeOf(u32);
2704 var buffer = try std.array_list.Managed(u8).initCapacity(gpa, needed_size);
2705 defer buffer.deinit();
2706 try self.indsymtab.write(self, buffer.writer());
2707 try self.pwriteAll(buffer.items, cmd.indirectsymoff);
2703 const buffer = try gpa.alloc(u8, needed_size);
2704 defer gpa.free(buffer);
2705 var writer: Writer = .fixed(buffer);
2706 try self.indsymtab.write(self, &writer);
2707 try self.pwriteAll(buffer, cmd.indirectsymoff);
27082708}
27092709
27102710pub fn writeSymtabToFile(self: *MachO) !void {
......@@ -2821,8 +2821,7 @@ fn writeLoadCommands(self: *MachO) !struct { usize, usize, u64 } {
28212821 const buffer = try gpa.alloc(u8, needed_size);
28222822 defer gpa.free(buffer);
28232823
2824 var stream = std.io.fixedBufferStream(buffer);
2825 const writer = stream.writer();
2824 var writer: Writer = .fixed(buffer);
28262825
28272826 var ncmds: usize = 0;
28282827
......@@ -2831,26 +2830,26 @@ fn writeLoadCommands(self: *MachO) !struct { usize, usize, u64 } {
28312830 const slice = self.sections.slice();
28322831 var sect_id: usize = 0;
28332832 for (self.segments.items) |seg| {
2834 try writer.writeStruct(seg);
2833 try writer.writeStruct(seg, .little);
28352834 for (slice.items(.header)[sect_id..][0..seg.nsects]) |header| {
2836 try writer.writeStruct(header);
2835 try writer.writeStruct(header, .little);
28372836 }
28382837 sect_id += seg.nsects;
28392838 }
28402839 ncmds += self.segments.items.len;
28412840 }
28422841
2843 try writer.writeStruct(self.dyld_info_cmd);
2842 try writer.writeStruct(self.dyld_info_cmd, .little);
28442843 ncmds += 1;
2845 try writer.writeStruct(self.function_starts_cmd);
2844 try writer.writeStruct(self.function_starts_cmd, .little);
28462845 ncmds += 1;
2847 try writer.writeStruct(self.data_in_code_cmd);
2846 try writer.writeStruct(self.data_in_code_cmd, .little);
28482847 ncmds += 1;
2849 try writer.writeStruct(self.symtab_cmd);
2848 try writer.writeStruct(self.symtab_cmd, .little);
28502849 ncmds += 1;
2851 try writer.writeStruct(self.dysymtab_cmd);
2850 try writer.writeStruct(self.dysymtab_cmd, .little);
28522851 ncmds += 1;
2853 try load_commands.writeDylinkerLC(writer);
2852 try load_commands.writeDylinkerLC(&writer);
28542853 ncmds += 1;
28552854
28562855 if (self.getInternalObject()) |obj| {
......@@ -2861,44 +2860,44 @@ fn writeLoadCommands(self: *MachO) !struct { usize, usize, u64 } {
28612860 0
28622861 else
28632862 @as(u32, @intCast(sym.getAddress(.{ .stubs = true }, self) - seg.vmaddr));
2864 try writer.writeStruct(macho.entry_point_command{
2863 try writer.writeStruct(@as(macho.entry_point_command, .{
28652864 .entryoff = entryoff,
28662865 .stacksize = self.base.stack_size,
2867 });
2866 }), .little);
28682867 ncmds += 1;
28692868 }
28702869 }
28712870
28722871 if (self.base.isDynLib()) {
2873 try load_commands.writeDylibIdLC(self, writer);
2872 try load_commands.writeDylibIdLC(self, &writer);
28742873 ncmds += 1;
28752874 }
28762875
28772876 for (self.rpath_list) |rpath| {
2878 try load_commands.writeRpathLC(rpath, writer);
2877 try load_commands.writeRpathLC(rpath, &writer);
28792878 ncmds += 1;
28802879 }
28812880 if (comp.config.any_sanitize_thread) {
28822881 const path = try comp.tsan_lib.?.full_object_path.toString(gpa);
28832882 defer gpa.free(path);
28842883 const rpath = std.fs.path.dirname(path) orelse ".";
2885 try load_commands.writeRpathLC(rpath, writer);
2884 try load_commands.writeRpathLC(rpath, &writer);
28862885 ncmds += 1;
28872886 }
28882887
2889 try writer.writeStruct(macho.source_version_command{ .version = 0 });
2888 try writer.writeStruct(@as(macho.source_version_command, .{ .version = 0 }), .little);
28902889 ncmds += 1;
28912890
28922891 if (self.platform.isBuildVersionCompatible()) {
2893 try load_commands.writeBuildVersionLC(self.platform, self.sdk_version, writer);
2892 try load_commands.writeBuildVersionLC(self.platform, self.sdk_version, &writer);
28942893 ncmds += 1;
28952894 } else {
2896 try load_commands.writeVersionMinLC(self.platform, self.sdk_version, writer);
2895 try load_commands.writeVersionMinLC(self.platform, self.sdk_version, &writer);
28972896 ncmds += 1;
28982897 }
28992898
2900 const uuid_cmd_offset = @sizeOf(macho.mach_header_64) + stream.pos;
2901 try writer.writeStruct(self.uuid_cmd);
2899 const uuid_cmd_offset = @sizeOf(macho.mach_header_64) + writer.end;
2900 try writer.writeStruct(self.uuid_cmd, .little);
29022901 ncmds += 1;
29032902
29042903 for (self.dylibs.items) |index| {
......@@ -2916,16 +2915,16 @@ fn writeLoadCommands(self: *MachO) !struct { usize, usize, u64 } {
29162915 .timestamp = dylib_id.timestamp,
29172916 .current_version = dylib_id.current_version,
29182917 .compatibility_version = dylib_id.compatibility_version,
2919 }, writer);
2918 }, &writer);
29202919 ncmds += 1;
29212920 }
29222921
29232922 if (self.requiresCodeSig()) {
2924 try writer.writeStruct(self.codesig_cmd);
2923 try writer.writeStruct(self.codesig_cmd, .little);
29252924 ncmds += 1;
29262925 }
29272926
2928 assert(stream.pos == needed_size);
2927 assert(writer.end == needed_size);
29292928
29302929 try self.pwriteAll(buffer, @sizeOf(macho.mach_header_64));
29312930
......@@ -3014,25 +3013,32 @@ pub fn writeCodeSignaturePadding(self: *MachO, code_sig: *CodeSignature) !void {
30143013pub fn writeCodeSignature(self: *MachO, code_sig: *CodeSignature) !void {
30153014 const seg = self.getTextSegment();
30163015 const offset = self.codesig_cmd.dataoff;
3016 const gpa = self.base.comp.gpa;
30173017
3018 var buffer = std.array_list.Managed(u8).init(self.base.comp.gpa);
3018 var buffer: std.Io.Writer.Allocating = .init(gpa);
30193019 defer buffer.deinit();
3020 try buffer.ensureTotalCapacityPrecise(code_sig.size());
3021 try code_sig.writeAdhocSignature(self, .{
3020 // The writeAdhocSignature function internally changes code_sig.size()
3021 // during the execution.
3022 try buffer.ensureUnusedCapacity(code_sig.size());
3023
3024 code_sig.writeAdhocSignature(self, .{
30223025 .file = self.base.file.?,
30233026 .exec_seg_base = seg.fileoff,
30243027 .exec_seg_limit = seg.filesize,
30253028 .file_size = offset,
30263029 .dylib = self.base.isDynLib(),
3027 }, buffer.writer());
3028 assert(buffer.items.len == code_sig.size());
3030 }, &buffer.writer) catch |err| switch (err) {
3031 error.WriteFailed => return error.OutOfMemory,
3032 else => |e| return e,
3033 };
3034 assert(buffer.written().len == code_sig.size());
30293035
30303036 log.debug("writing code signature from 0x{x} to 0x{x}", .{
30313037 offset,
3032 offset + buffer.items.len,
3038 offset + buffer.written().len,
30333039 });
30343040
3035 try self.pwriteAll(buffer.items, offset);
3041 try self.pwriteAll(buffer.written(), offset);
30363042}
30373043
30383044pub fn updateFunc(
......@@ -5372,7 +5378,7 @@ const macho = std.macho;
53725378const math = std.math;
53735379const mem = std.mem;
53745380const meta = std.meta;
5375const Writer = std.io.Writer;
5381const Writer = std.Io.Writer;
53765382
53775383const aarch64 = codegen.aarch64.encoding;
53785384const bind = @import("MachO/dyld_info/bind.zig");
src/link/MachO/Archive.zig+18-38
......@@ -81,34 +81,20 @@ pub fn writeHeader(
8181 object_name: []const u8,
8282 object_size: usize,
8383 format: Format,
84 writer: anytype,
84 writer: *Writer,
8585) !void {
86 var hdr: ar_hdr = .{
87 .ar_name = undefined,
88 .ar_date = undefined,
89 .ar_uid = undefined,
90 .ar_gid = undefined,
91 .ar_mode = undefined,
92 .ar_size = undefined,
93 .ar_fmag = undefined,
94 };
95 @memset(mem.asBytes(&hdr), 0x20);
96 inline for (@typeInfo(ar_hdr).@"struct".fields) |field| {
97 var stream = std.io.fixedBufferStream(&@field(hdr, field.name));
98 stream.writer().print("0", .{}) catch unreachable;
99 }
100 @memcpy(&hdr.ar_fmag, ARFMAG);
86 var hdr: ar_hdr = .{};
10187
10288 const object_name_len = mem.alignForward(usize, object_name.len + 1, ptrWidth(format));
10389 const total_object_size = object_size + object_name_len;
10490
10591 {
106 var stream = std.io.fixedBufferStream(&hdr.ar_name);
107 stream.writer().print("#1/{d}", .{object_name_len}) catch unreachable;
92 var stream: Writer = .fixed(&hdr.ar_name);
93 stream.print("#1/{d}", .{object_name_len}) catch unreachable;
10894 }
10995 {
110 var stream = std.io.fixedBufferStream(&hdr.ar_size);
111 stream.writer().print("{d}", .{total_object_size}) catch unreachable;
96 var stream: Writer = .fixed(&hdr.ar_size);
97 stream.print("{d}", .{total_object_size}) catch unreachable;
11298 }
11399
114100 try writer.writeAll(mem.asBytes(&hdr));
......@@ -116,7 +102,7 @@ pub fn writeHeader(
116102
117103 const padding = object_name_len - object_name.len - 1;
118104 if (padding > 0) {
119 try writer.writeByteNTimes(0, padding);
105 try writer.splatByteAll(0, padding);
120106 }
121107}
122108
......@@ -138,25 +124,19 @@ pub const SYMDEF64_SORTED = "__.SYMDEF_64 SORTED";
138124
139125pub const ar_hdr = extern struct {
140126 /// Member file name, sometimes / terminated.
141 ar_name: [16]u8,
142
127 ar_name: [16]u8 = "0\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20".*,
143128 /// File date, decimal seconds since Epoch.
144 ar_date: [12]u8,
145
129 ar_date: [12]u8 = "0\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20".*,
146130 /// User ID, in ASCII format.
147 ar_uid: [6]u8,
148
131 ar_uid: [6]u8 = "0\x20\x20\x20\x20\x20".*,
149132 /// Group ID, in ASCII format.
150 ar_gid: [6]u8,
151
133 ar_gid: [6]u8 = "0\x20\x20\x20\x20\x20".*,
152134 /// File mode, in ASCII octal.
153 ar_mode: [8]u8,
154
135 ar_mode: [8]u8 = "0\x20\x20\x20\x20\x20\x20\x20".*,
155136 /// File size, in ASCII decimal.
156 ar_size: [10]u8,
157
137 ar_size: [10]u8 = "0\x20\x20\x20\x20\x20\x20\x20\x20\x20".*,
158138 /// Always contains ARFMAG.
159 ar_fmag: [2]u8,
139 ar_fmag: [2]u8 = ARFMAG.*,
160140
161141 fn date(self: ar_hdr) !u64 {
162142 const value = mem.trimEnd(u8, &self.ar_date, &[_]u8{@as(u8, 0x20)});
......@@ -201,7 +181,7 @@ pub const ArSymtab = struct {
201181 return ptr_width + ar.entries.items.len * 2 * ptr_width + ptr_width + mem.alignForward(usize, ar.strtab.buffer.items.len, ptr_width);
202182 }
203183
204 pub fn write(ar: ArSymtab, format: Format, macho_file: *MachO, writer: anytype) !void {
184 pub fn write(ar: ArSymtab, format: Format, macho_file: *MachO, writer: *Writer) !void {
205185 const ptr_width = ptrWidth(format);
206186 // Header
207187 try writeHeader(SYMDEF, ar.size(format), format, writer);
......@@ -226,7 +206,7 @@ pub const ArSymtab = struct {
226206 // Strtab
227207 try writer.writeAll(ar.strtab.buffer.items);
228208 if (padding > 0) {
229 try writer.writeByteNTimes(0, padding);
209 try writer.splatByteAll(0, padding);
230210 }
231211 }
232212
......@@ -275,7 +255,7 @@ pub fn ptrWidth(format: Format) usize {
275255 };
276256}
277257
278pub fn writeInt(format: Format, value: u64, writer: anytype) !void {
258pub fn writeInt(format: Format, value: u64, writer: *Writer) !void {
279259 switch (format) {
280260 .p32 => try writer.writeInt(u32, std.math.cast(u32, value) orelse return error.Overflow, .little),
281261 .p64 => try writer.writeInt(u64, value, .little),
......@@ -299,7 +279,7 @@ const mem = std.mem;
299279const std = @import("std");
300280const Allocator = std.mem.Allocator;
301281const Path = std.Build.Cache.Path;
302const Writer = std.io.Writer;
282const Writer = std.Io.Writer;
303283
304284const Archive = @This();
305285const File = @import("file.zig").File;
src/link/MachO/Atom.zig+7-6
......@@ -581,19 +581,19 @@ pub fn resolveRelocs(self: Atom, macho_file: *MachO, buffer: []u8) !void {
581581 relocs_log.debug("{x}: {s}", .{ self.value, name });
582582
583583 var has_error = false;
584 var stream = std.io.fixedBufferStream(buffer);
584 var stream: Writer = .fixed(buffer);
585585 var i: usize = 0;
586586 while (i < relocs.len) : (i += 1) {
587587 const rel = relocs[i];
588 const rel_offset = rel.offset - self.off;
588 const rel_offset: usize = @intCast(rel.offset - self.off);
589589 const subtractor = if (rel.meta.has_subtractor) relocs[i - 1] else null;
590590
591591 if (rel.tag == .@"extern") {
592592 if (rel.getTargetSymbol(self, macho_file).getFile(macho_file) == null) continue;
593593 }
594594
595 try stream.seekTo(rel_offset);
596 self.resolveRelocInner(rel, subtractor, buffer, macho_file, stream.writer()) catch |err| {
595 stream.end = rel_offset;
596 self.resolveRelocInner(rel, subtractor, buffer, macho_file, &stream) catch |err| {
597597 switch (err) {
598598 error.RelaxFail => {
599599 const target = switch (rel.tag) {
......@@ -630,6 +630,7 @@ const ResolveError = error{
630630 UnexpectedRemainder,
631631 Overflow,
632632 OutOfMemory,
633 WriteFailed,
633634};
634635
635636fn resolveRelocInner(
......@@ -638,7 +639,7 @@ fn resolveRelocInner(
638639 subtractor: ?Relocation,
639640 code: []u8,
640641 macho_file: *MachO,
641 writer: anytype,
642 writer: *Writer,
642643) ResolveError!void {
643644 const t = &macho_file.base.comp.root_mod.resolved_target.result;
644645 const cpu_arch = t.cpu.arch;
......@@ -1147,7 +1148,7 @@ const math = std.math;
11471148const mem = std.mem;
11481149const log = std.log.scoped(.link);
11491150const relocs_log = std.log.scoped(.link_relocs);
1150const Writer = std.io.Writer;
1151const Writer = std.Io.Writer;
11511152const Allocator = mem.Allocator;
11521153const AtomicBool = std.atomic.Value(bool);
11531154
src/link/MachO/CodeSignature.zig+9-9
......@@ -263,7 +263,7 @@ pub fn writeAdhocSignature(
263263 self: *CodeSignature,
264264 macho_file: *MachO,
265265 opts: WriteOpts,
266 writer: anytype,
266 writer: *std.Io.Writer,
267267) !void {
268268 const tracy = trace(@src());
269269 defer tracy.end();
......@@ -304,10 +304,10 @@ pub fn writeAdhocSignature(
304304 var hash: [hash_size]u8 = undefined;
305305
306306 if (self.requirements) |*req| {
307 var buf = std.array_list.Managed(u8).init(allocator);
308 defer buf.deinit();
309 try req.write(buf.writer());
310 Sha256.hash(buf.items, &hash, .{});
307 var a: std.Io.Writer.Allocating = .init(allocator);
308 defer a.deinit();
309 try req.write(&a.writer);
310 Sha256.hash(a.written(), &hash, .{});
311311 self.code_directory.addSpecialHash(req.slotType(), hash);
312312
313313 try blobs.append(.{ .requirements = req });
......@@ -316,10 +316,10 @@ pub fn writeAdhocSignature(
316316 }
317317
318318 if (self.entitlements) |*ents| {
319 var buf = std.array_list.Managed(u8).init(allocator);
320 defer buf.deinit();
321 try ents.write(buf.writer());
322 Sha256.hash(buf.items, &hash, .{});
319 var a: std.Io.Writer.Allocating = .init(allocator);
320 defer a.deinit();
321 try ents.write(&a.writer);
322 Sha256.hash(a.written(), &hash, .{});
323323 self.code_directory.addSpecialHash(ents.slotType(), hash);
324324
325325 try blobs.append(.{ .entitlements = ents });
src/link/MachO/DebugSymbols.zig+9-10
......@@ -273,14 +273,13 @@ fn writeLoadCommands(self: *DebugSymbols, macho_file: *MachO) !struct { usize, u
273273 const buffer = try gpa.alloc(u8, needed_size);
274274 defer gpa.free(buffer);
275275
276 var stream = std.io.fixedBufferStream(buffer);
277 const writer = stream.writer();
276 var writer: Writer = .fixed(buffer);
278277
279278 var ncmds: usize = 0;
280279
281280 // UUID comes first presumably to speed up lookup by the consumer like lldb.
282281 @memcpy(&self.uuid_cmd.uuid, &macho_file.uuid_cmd.uuid);
283 try writer.writeStruct(self.uuid_cmd);
282 try writer.writeStruct(self.uuid_cmd, .little);
284283 ncmds += 1;
285284
286285 // Segment and section load commands
......@@ -293,11 +292,11 @@ fn writeLoadCommands(self: *DebugSymbols, macho_file: *MachO) !struct { usize, u
293292 var out_seg = seg;
294293 out_seg.fileoff = 0;
295294 out_seg.filesize = 0;
296 try writer.writeStruct(out_seg);
295 try writer.writeStruct(out_seg, .little);
297296 for (slice.items(.header)[sect_id..][0..seg.nsects]) |header| {
298297 var out_header = header;
299298 out_header.offset = 0;
300 try writer.writeStruct(out_header);
299 try writer.writeStruct(out_header, .little);
301300 }
302301 sect_id += seg.nsects;
303302 }
......@@ -306,19 +305,19 @@ fn writeLoadCommands(self: *DebugSymbols, macho_file: *MachO) !struct { usize, u
306305 // Next, commit DSYM's __LINKEDIT and __DWARF segments headers.
307306 sect_id = 0;
308307 for (self.segments.items) |seg| {
309 try writer.writeStruct(seg);
308 try writer.writeStruct(seg, .little);
310309 for (self.sections.items[sect_id..][0..seg.nsects]) |header| {
311 try writer.writeStruct(header);
310 try writer.writeStruct(header, .little);
312311 }
313312 sect_id += seg.nsects;
314313 }
315314 ncmds += self.segments.items.len;
316315 }
317316
318 try writer.writeStruct(self.symtab_cmd);
317 try writer.writeStruct(self.symtab_cmd, .little);
319318 ncmds += 1;
320319
321 assert(stream.pos == needed_size);
320 assert(writer.end == needed_size);
322321
323322 try self.file.?.pwriteAll(buffer, @sizeOf(macho.mach_header_64));
324323
......@@ -460,7 +459,7 @@ const math = std.math;
460459const mem = std.mem;
461460const padToIdeal = MachO.padToIdeal;
462461const trace = @import("../../tracy.zig").trace;
463const Writer = std.io.Writer;
462const Writer = std.Io.Writer;
464463
465464const Allocator = mem.Allocator;
466465const MachO = @import("../MachO.zig");
src/link/MachO/InternalObject.zig+1-1
......@@ -261,7 +261,7 @@ fn addObjcMethnameSection(self: *InternalObject, methname: []const u8, macho_fil
261261
262262 sect.offset = @intCast(self.objc_methnames.items.len);
263263 try self.objc_methnames.ensureUnusedCapacity(gpa, methname.len + 1);
264 self.objc_methnames.writer(gpa).print("{s}\x00", .{methname}) catch unreachable;
264 self.objc_methnames.print(gpa, "{s}\x00", .{methname}) catch unreachable;
265265
266266 const name_str = try self.addString(gpa, "ltmp");
267267 const sym_index = try self.addSymbol(gpa);
src/link/MachO/UnwindInfo.zig+23-24
......@@ -293,8 +293,7 @@ pub fn write(info: UnwindInfo, macho_file: *MachO, buffer: []u8) !void {
293293 const seg = macho_file.getTextSegment();
294294 const header = macho_file.sections.items(.header)[macho_file.unwind_info_sect_index.?];
295295
296 var stream = std.io.fixedBufferStream(buffer);
297 const writer = stream.writer();
296 var writer: Writer = .fixed(buffer);
298297
299298 const common_encodings_offset: u32 = @sizeOf(macho.unwind_info_section_header);
300299 const common_encodings_count: u32 = info.common_encodings_count;
......@@ -303,14 +302,14 @@ pub fn write(info: UnwindInfo, macho_file: *MachO, buffer: []u8) !void {
303302 const indexes_offset: u32 = personalities_offset + personalities_count * @sizeOf(u32);
304303 const indexes_count: u32 = @as(u32, @intCast(info.pages.items.len + 1));
305304
306 try writer.writeStruct(macho.unwind_info_section_header{
305 try writer.writeStruct(@as(macho.unwind_info_section_header, .{
307306 .commonEncodingsArraySectionOffset = common_encodings_offset,
308307 .commonEncodingsArrayCount = common_encodings_count,
309308 .personalityArraySectionOffset = personalities_offset,
310309 .personalityArrayCount = personalities_count,
311310 .indexSectionOffset = indexes_offset,
312311 .indexCount = indexes_count,
313 });
312 }), .little);
314313
315314 try writer.writeAll(mem.sliceAsBytes(info.common_encodings[0..info.common_encodings_count]));
316315
......@@ -325,42 +324,42 @@ pub fn write(info: UnwindInfo, macho_file: *MachO, buffer: []u8) !void {
325324 for (info.pages.items, 0..) |page, i| {
326325 assert(page.count > 0);
327326 const rec = info.records.items[page.start].getUnwindRecord(macho_file);
328 try writer.writeStruct(macho.unwind_info_section_header_index_entry{
327 try writer.writeStruct(@as(macho.unwind_info_section_header_index_entry, .{
329328 .functionOffset = @as(u32, @intCast(rec.getAtomAddress(macho_file) - seg.vmaddr)),
330329 .secondLevelPagesSectionOffset = @as(u32, @intCast(pages_base_offset + i * second_level_page_bytes)),
331330 .lsdaIndexArraySectionOffset = lsda_base_offset +
332331 info.lsdas_lookup.items[page.start] * @sizeOf(macho.unwind_info_section_header_lsda_index_entry),
333 });
332 }), .little);
334333 }
335334
336335 const last_rec = info.records.items[info.records.items.len - 1].getUnwindRecord(macho_file);
337336 const sentinel_address = @as(u32, @intCast(last_rec.getAtomAddress(macho_file) + last_rec.length - seg.vmaddr));
338 try writer.writeStruct(macho.unwind_info_section_header_index_entry{
337 try writer.writeStruct(@as(macho.unwind_info_section_header_index_entry, .{
339338 .functionOffset = sentinel_address,
340339 .secondLevelPagesSectionOffset = 0,
341340 .lsdaIndexArraySectionOffset = lsda_base_offset +
342341 @as(u32, @intCast(info.lsdas.items.len)) * @sizeOf(macho.unwind_info_section_header_lsda_index_entry),
343 });
342 }), .little);
344343
345344 for (info.lsdas.items) |index| {
346345 const rec = info.records.items[index].getUnwindRecord(macho_file);
347 try writer.writeStruct(macho.unwind_info_section_header_lsda_index_entry{
346 try writer.writeStruct(@as(macho.unwind_info_section_header_lsda_index_entry, .{
348347 .functionOffset = @as(u32, @intCast(rec.getAtomAddress(macho_file) - seg.vmaddr)),
349348 .lsdaOffset = @as(u32, @intCast(rec.getLsdaAddress(macho_file) - seg.vmaddr)),
350 });
349 }), .little);
351350 }
352351
353352 for (info.pages.items) |page| {
354 const start = stream.pos;
355 try page.write(info, macho_file, writer);
356 const nwritten = stream.pos - start;
353 const start = writer.end;
354 try page.write(info, macho_file, &writer);
355 const nwritten = writer.end - start;
357356 if (nwritten < second_level_page_bytes) {
358357 const padding = math.cast(usize, second_level_page_bytes - nwritten) orelse return error.Overflow;
359 try writer.writeByteNTimes(0, padding);
358 try writer.splatByteAll(0, padding);
360359 }
361360 }
362361
363 @memset(buffer[stream.pos..], 0);
362 @memset(buffer[writer.end..], 0);
364363}
365364
366365fn getOrPutPersonalityFunction(info: *UnwindInfo, ref: MachO.Ref) error{TooManyPersonalities}!u2 {
......@@ -611,33 +610,33 @@ const Page = struct {
611610 } };
612611 }
613612
614 fn write(page: Page, info: UnwindInfo, macho_file: *MachO, writer: anytype) !void {
613 fn write(page: Page, info: UnwindInfo, macho_file: *MachO, writer: *Writer) !void {
615614 const seg = macho_file.getTextSegment();
616615
617616 switch (page.kind) {
618617 .regular => {
619 try writer.writeStruct(macho.unwind_info_regular_second_level_page_header{
618 try writer.writeStruct(@as(macho.unwind_info_regular_second_level_page_header, .{
620619 .entryPageOffset = @sizeOf(macho.unwind_info_regular_second_level_page_header),
621620 .entryCount = page.count,
622 });
621 }), .little);
623622
624623 for (info.records.items[page.start..][0..page.count]) |ref| {
625624 const rec = ref.getUnwindRecord(macho_file);
626 try writer.writeStruct(macho.unwind_info_regular_second_level_entry{
625 try writer.writeStruct(@as(macho.unwind_info_regular_second_level_entry, .{
627626 .functionOffset = @as(u32, @intCast(rec.getAtomAddress(macho_file) - seg.vmaddr)),
628627 .encoding = rec.enc.enc,
629 });
628 }), .little);
630629 }
631630 },
632631 .compressed => {
633632 const entry_offset = @sizeOf(macho.unwind_info_compressed_second_level_page_header) +
634633 @as(u16, @intCast(page.page_encodings_count)) * @sizeOf(u32);
635 try writer.writeStruct(macho.unwind_info_compressed_second_level_page_header{
634 try writer.writeStruct(@as(macho.unwind_info_compressed_second_level_page_header, .{
636635 .entryPageOffset = entry_offset,
637636 .entryCount = page.count,
638637 .encodingsPageOffset = @sizeOf(macho.unwind_info_compressed_second_level_page_header),
639638 .encodingsCount = page.page_encodings_count,
640 });
639 }), .little);
641640
642641 for (page.page_encodings[0..page.page_encodings_count]) |enc| {
643642 try writer.writeInt(u32, enc.enc, .little);
......@@ -656,7 +655,7 @@ const Page = struct {
656655 .funcOffset = @as(u24, @intCast(rec.getAtomAddress(macho_file) - first_rec.getAtomAddress(macho_file))),
657656 .encodingIndex = @as(u8, @intCast(enc_index)),
658657 };
659 try writer.writeStruct(compressed);
658 try writer.writeStruct(compressed, .little);
660659 }
661660 },
662661 }
......@@ -673,7 +672,7 @@ const macho = std.macho;
673672const math = std.math;
674673const mem = std.mem;
675674const trace = @import("../../tracy.zig").trace;
676const Writer = std.io.Writer;
675const Writer = std.Io.Writer;
677676
678677const Allocator = mem.Allocator;
679678const Atom = @import("Atom.zig");
src/link/MachO/dyld_info/Rebase.zig+10-9
......@@ -110,12 +110,14 @@ pub fn updateSize(rebase: *Rebase, macho_file: *MachO) !void {
110110fn finalize(rebase: *Rebase, gpa: Allocator) !void {
111111 if (rebase.entries.items.len == 0) return;
112112
113 const writer = rebase.buffer.writer(gpa);
114
115113 log.debug("rebase opcodes", .{});
116114
117115 std.mem.sort(Entry, rebase.entries.items, {}, Entry.lessThan);
118116
117 var allocating: std.Io.Writer.Allocating = .fromArrayList(gpa, &rebase.buffer);
118 defer rebase.buffer = allocating.toArrayList();
119 const writer = &allocating.writer;
120
119121 try setTypePointer(writer);
120122
121123 var start: usize = 0;
......@@ -226,13 +228,13 @@ fn setTypePointer(writer: anytype) !void {
226228fn setSegmentOffset(segment_id: u8, offset: u64, writer: anytype) !void {
227229 log.debug(">>> set segment: {d} and offset: {x}", .{ segment_id, offset });
228230 try writer.writeByte(macho.REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB | @as(u4, @truncate(segment_id)));
229 try std.leb.writeUleb128(writer, offset);
231 try writer.writeUleb128(offset);
230232}
231233
232234fn rebaseAddAddr(addr: u64, writer: anytype) !void {
233235 log.debug(">>> rebase with add: {x}", .{addr});
234236 try writer.writeByte(macho.REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB);
235 try std.leb.writeUleb128(writer, addr);
237 try writer.writeUleb128(addr);
236238}
237239
238240fn rebaseTimes(count: usize, writer: anytype) !void {
......@@ -241,15 +243,15 @@ fn rebaseTimes(count: usize, writer: anytype) !void {
241243 try writer.writeByte(macho.REBASE_OPCODE_DO_REBASE_IMM_TIMES | @as(u4, @truncate(count)));
242244 } else {
243245 try writer.writeByte(macho.REBASE_OPCODE_DO_REBASE_ULEB_TIMES);
244 try std.leb.writeUleb128(writer, count);
246 try writer.writeUleb128(count);
245247 }
246248}
247249
248250fn rebaseTimesSkip(count: usize, skip: u64, writer: anytype) !void {
249251 log.debug(">>> rebase with count: {d} and skip: {x}", .{ count, skip });
250252 try writer.writeByte(macho.REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB);
251 try std.leb.writeUleb128(writer, count);
252 try std.leb.writeUleb128(writer, skip);
253 try writer.writeUleb128(count);
254 try writer.writeUleb128(skip);
253255}
254256
255257fn addAddr(addr: u64, writer: anytype) !void {
......@@ -262,7 +264,7 @@ fn addAddr(addr: u64, writer: anytype) !void {
262264 }
263265 }
264266 try writer.writeByte(macho.REBASE_OPCODE_ADD_ADDR_ULEB);
265 try std.leb.writeUleb128(writer, addr);
267 try writer.writeUleb128(addr);
266268}
267269
268270fn done(writer: anytype) !void {
......@@ -649,7 +651,6 @@ test "rebase - composite" {
649651
650652const std = @import("std");
651653const assert = std.debug.assert;
652const leb = std.leb;
653654const log = std.log.scoped(.link_dyld_info);
654655const macho = std.macho;
655656const mem = std.mem;
src/link/MachO/dyld_info/Trie.zig+16-12
......@@ -170,8 +170,13 @@ fn finalize(self: *Trie, allocator: Allocator) !void {
170170 }
171171
172172 try self.buffer.ensureTotalCapacityPrecise(allocator, size);
173
174 var allocating: std.Io.Writer.Allocating = .fromArrayList(allocator, &self.buffer);
175 defer self.buffer = allocating.toArrayList();
176 const writer = &allocating.writer;
177
173178 for (ordered_nodes.items) |node_index| {
174 try self.writeNode(node_index, self.buffer.writer(allocator));
179 try self.writeNode(node_index, writer);
175180 }
176181}
177182
......@@ -232,7 +237,7 @@ pub fn deinit(self: *Trie, allocator: Allocator) void {
232237 self.buffer.deinit(allocator);
233238}
234239
235pub fn write(self: Trie, writer: anytype) !void {
240pub fn write(self: Trie, writer: *std.Io.Writer) !void {
236241 if (self.buffer.items.len == 0) return;
237242 try writer.writeAll(self.buffer.items);
238243}
......@@ -243,7 +248,7 @@ pub fn write(self: Trie, writer: anytype) !void {
243248/// iterate over `Trie.ordered_nodes` and call this method on each node.
244249/// This is one of the requirements of the MachO.
245250/// Panics if `finalize` was not called before calling this method.
246fn writeNode(self: *Trie, node_index: Node.Index, writer: anytype) !void {
251fn writeNode(self: *Trie, node_index: Node.Index, writer: *std.Io.Writer) !void {
247252 const slice = self.nodes.slice();
248253 const edges = slice.items(.edges)[node_index];
249254 const is_terminal = slice.items(.is_terminal)[node_index];
......@@ -253,21 +258,21 @@ fn writeNode(self: *Trie, node_index: Node.Index, writer: anytype) !void {
253258 if (is_terminal) {
254259 // Terminal node info: encode export flags and vmaddr offset of this symbol.
255260 var info_buf: [@sizeOf(u64) * 2]u8 = undefined;
256 var info_stream = std.io.fixedBufferStream(&info_buf);
261 var info_stream: std.Io.Writer = .fixed(&info_buf);
257262 // TODO Implement for special flags.
258263 assert(export_flags & macho.EXPORT_SYMBOL_FLAGS_REEXPORT == 0 and
259264 export_flags & macho.EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER == 0);
260 try leb.writeUleb128(info_stream.writer(), export_flags);
261 try leb.writeUleb128(info_stream.writer(), vmaddr_offset);
265 try info_stream.writeUleb128(export_flags);
266 try info_stream.writeUleb128(vmaddr_offset);
262267
263268 // Encode the size of the terminal node info.
264269 var size_buf: [@sizeOf(u64)]u8 = undefined;
265 var size_stream = std.io.fixedBufferStream(&size_buf);
266 try leb.writeUleb128(size_stream.writer(), info_stream.pos);
270 var size_stream: std.Io.Writer = .fixed(&size_buf);
271 try size_stream.writeUleb128(info_stream.end);
267272
268273 // Now, write them to the output stream.
269 try writer.writeAll(size_buf[0..size_stream.pos]);
270 try writer.writeAll(info_buf[0..info_stream.pos]);
274 try writer.writeAll(size_buf[0..size_stream.end]);
275 try writer.writeAll(info_buf[0..info_stream.end]);
271276 } else {
272277 // Non-terminal node is delimited by 0 byte.
273278 try writer.writeByte(0);
......@@ -280,7 +285,7 @@ fn writeNode(self: *Trie, node_index: Node.Index, writer: anytype) !void {
280285 // Write edge label and offset to next node in trie.
281286 try writer.writeAll(edge.label);
282287 try writer.writeByte(0);
283 try leb.writeUleb128(writer, slice.items(.trie_offset)[edge.node]);
288 try writer.writeUleb128(slice.items(.trie_offset)[edge.node]);
284289 }
285290}
286291
......@@ -414,7 +419,6 @@ test "ordering bug" {
414419}
415420
416421const assert = std.debug.assert;
417const leb = std.leb;
418422const log = std.log.scoped(.macho);
419423const macho = std.macho;
420424const mem = std.mem;
src/link/MachO/dyld_info/bind.zig+32-28
......@@ -132,12 +132,14 @@ pub const Bind = struct {
132132 fn finalize(self: *Self, gpa: Allocator, ctx: *MachO) !void {
133133 if (self.entries.items.len == 0) return;
134134
135 const writer = self.buffer.writer(gpa);
136
137135 log.debug("bind opcodes", .{});
138136
139137 std.mem.sort(Entry, self.entries.items, ctx, Entry.lessThan);
140138
139 var allocating: std.Io.Writer.Allocating = .fromArrayList(gpa, &self.buffer);
140 defer self.buffer = allocating.toArrayList();
141 const writer = &allocating.writer;
142
141143 var start: usize = 0;
142144 var seg_id: ?u8 = null;
143145 for (self.entries.items, 0..) |entry, i| {
......@@ -151,7 +153,7 @@ pub const Bind = struct {
151153 try done(writer);
152154 }
153155
154 fn finalizeSegment(entries: []const Entry, ctx: *MachO, writer: anytype) !void {
156 fn finalizeSegment(entries: []const Entry, ctx: *MachO, writer: *std.Io.Writer) !void {
155157 if (entries.len == 0) return;
156158
157159 const seg_id = entries[0].segment_id;
......@@ -263,7 +265,7 @@ pub const Bind = struct {
263265 }
264266 }
265267
266 pub fn write(self: Self, writer: anytype) !void {
268 pub fn write(self: Self, writer: *std.Io.Writer) !void {
267269 try writer.writeAll(self.buffer.items);
268270 }
269271};
......@@ -385,12 +387,14 @@ pub const WeakBind = struct {
385387 fn finalize(self: *Self, gpa: Allocator, ctx: *MachO) !void {
386388 if (self.entries.items.len == 0) return;
387389
388 const writer = self.buffer.writer(gpa);
389
390390 log.debug("weak bind opcodes", .{});
391391
392392 std.mem.sort(Entry, self.entries.items, ctx, Entry.lessThan);
393393
394 var allocating: std.Io.Writer.Allocating = .fromArrayList(gpa, &self.buffer);
395 defer self.buffer = allocating.toArrayList();
396 const writer = &allocating.writer;
397
394398 var start: usize = 0;
395399 var seg_id: ?u8 = null;
396400 for (self.entries.items, 0..) |entry, i| {
......@@ -404,7 +408,7 @@ pub const WeakBind = struct {
404408 try done(writer);
405409 }
406410
407 fn finalizeSegment(entries: []const Entry, ctx: *MachO, writer: anytype) !void {
411 fn finalizeSegment(entries: []const Entry, ctx: *MachO, writer: *std.Io.Writer) !void {
408412 if (entries.len == 0) return;
409413
410414 const seg_id = entries[0].segment_id;
......@@ -505,7 +509,7 @@ pub const WeakBind = struct {
505509 }
506510 }
507511
508 pub fn write(self: Self, writer: anytype) !void {
512 pub fn write(self: Self, writer: *std.Io.Writer) !void {
509513 try writer.writeAll(self.buffer.items);
510514 }
511515};
......@@ -555,8 +559,6 @@ pub const LazyBind = struct {
555559 fn finalize(self: *Self, gpa: Allocator, ctx: *MachO) !void {
556560 try self.offsets.ensureTotalCapacityPrecise(gpa, self.entries.items.len);
557561
558 const writer = self.buffer.writer(gpa);
559
560562 log.debug("lazy bind opcodes", .{});
561563
562564 var addend: i64 = 0;
......@@ -578,6 +580,9 @@ pub const LazyBind = struct {
578580 break :ord macho.BIND_SPECIAL_DYLIB_SELF;
579581 };
580582
583 var allocating: std.Io.Writer.Allocating = .fromArrayList(gpa, &self.buffer);
584 defer self.buffer = allocating.toArrayList();
585 const writer = &allocating.writer;
581586 try setSegmentOffset(entry.segment_id, entry.offset, writer);
582587 try setSymbol(name, flags, writer);
583588 try setDylibOrdinal(ordinal, writer);
......@@ -592,30 +597,30 @@ pub const LazyBind = struct {
592597 }
593598 }
594599
595 pub fn write(self: Self, writer: anytype) !void {
600 pub fn write(self: Self, writer: *std.Io.Writer) !void {
596601 try writer.writeAll(self.buffer.items);
597602 }
598603};
599604
600fn setSegmentOffset(segment_id: u8, offset: u64, writer: anytype) !void {
605fn setSegmentOffset(segment_id: u8, offset: u64, writer: *std.Io.Writer) !void {
601606 log.debug(">>> set segment: {d} and offset: {x}", .{ segment_id, offset });
602607 try writer.writeByte(macho.BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB | @as(u4, @truncate(segment_id)));
603 try std.leb.writeUleb128(writer, offset);
608 try writer.writeUleb128(offset);
604609}
605610
606fn setSymbol(name: []const u8, flags: u8, writer: anytype) !void {
611fn setSymbol(name: []const u8, flags: u8, writer: *std.Io.Writer) !void {
607612 log.debug(">>> set symbol: {s} with flags: {x}", .{ name, flags });
608613 try writer.writeByte(macho.BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM | @as(u4, @truncate(flags)));
609614 try writer.writeAll(name);
610615 try writer.writeByte(0);
611616}
612617
613fn setTypePointer(writer: anytype) !void {
618fn setTypePointer(writer: *std.Io.Writer) !void {
614619 log.debug(">>> set type: {d}", .{macho.BIND_TYPE_POINTER});
615620 try writer.writeByte(macho.BIND_OPCODE_SET_TYPE_IMM | @as(u4, @truncate(macho.BIND_TYPE_POINTER)));
616621}
617622
618fn setDylibOrdinal(ordinal: i16, writer: anytype) !void {
623fn setDylibOrdinal(ordinal: i16, writer: *std.Io.Writer) !void {
619624 if (ordinal <= 0) {
620625 switch (ordinal) {
621626 macho.BIND_SPECIAL_DYLIB_SELF,
......@@ -634,23 +639,23 @@ fn setDylibOrdinal(ordinal: i16, writer: anytype) !void {
634639 try writer.writeByte(macho.BIND_OPCODE_SET_DYLIB_ORDINAL_IMM | @as(u4, @truncate(cast)));
635640 } else {
636641 try writer.writeByte(macho.BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB);
637 try std.leb.writeUleb128(writer, cast);
642 try writer.writeUleb128(cast);
638643 }
639644 }
640645}
641646
642fn setAddend(addend: i64, writer: anytype) !void {
647fn setAddend(addend: i64, writer: *std.Io.Writer) !void {
643648 log.debug(">>> set addend: {x}", .{addend});
644649 try writer.writeByte(macho.BIND_OPCODE_SET_ADDEND_SLEB);
645650 try std.leb.writeIleb128(writer, addend);
646651}
647652
648fn doBind(writer: anytype) !void {
653fn doBind(writer: *std.Io.Writer) !void {
649654 log.debug(">>> bind", .{});
650655 try writer.writeByte(macho.BIND_OPCODE_DO_BIND);
651656}
652657
653fn doBindAddAddr(addr: u64, writer: anytype) !void {
658fn doBindAddAddr(addr: u64, writer: *std.Io.Writer) !void {
654659 log.debug(">>> bind with add: {x}", .{addr});
655660 if (std.mem.isAlignedGeneric(u64, addr, @sizeOf(u64))) {
656661 const imm = @divExact(addr, @sizeOf(u64));
......@@ -662,29 +667,28 @@ fn doBindAddAddr(addr: u64, writer: anytype) !void {
662667 }
663668 }
664669 try writer.writeByte(macho.BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB);
665 try std.leb.writeUleb128(writer, addr);
670 try writer.writeUleb128(addr);
666671}
667672
668fn doBindTimesSkip(count: usize, skip: u64, writer: anytype) !void {
673fn doBindTimesSkip(count: usize, skip: u64, writer: *std.Io.Writer) !void {
669674 log.debug(">>> bind with count: {d} and skip: {x}", .{ count, skip });
670675 try writer.writeByte(macho.BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB);
671 try std.leb.writeUleb128(writer, count);
672 try std.leb.writeUleb128(writer, skip);
676 try writer.writeUleb128(count);
677 try writer.writeUleb128(skip);
673678}
674679
675fn addAddr(addr: u64, writer: anytype) !void {
680fn addAddr(addr: u64, writer: *std.Io.Writer) !void {
676681 log.debug(">>> add: {x}", .{addr});
677682 try writer.writeByte(macho.BIND_OPCODE_ADD_ADDR_ULEB);
678 try std.leb.writeUleb128(writer, addr);
683 try writer.writeUleb128(addr);
679684}
680685
681fn done(writer: anytype) !void {
686fn done(writer: *std.Io.Writer) !void {
682687 log.debug(">>> done", .{});
683688 try writer.writeByte(macho.BIND_OPCODE_DONE);
684689}
685690
686691const assert = std.debug.assert;
687const leb = std.leb;
688692const log = std.log.scoped(.link_dyld_info);
689693const macho = std.macho;
690694const mem = std.mem;
src/link/MachO/load_commands.zig+19-19
......@@ -3,9 +3,9 @@ const assert = std.debug.assert;
33const log = std.log.scoped(.link);
44const macho = std.macho;
55const mem = std.mem;
6const Writer = std.io.Writer;
6const Writer = std.Io.Writer;
7const Allocator = std.mem.Allocator;
78
8const Allocator = mem.Allocator;
99const DebugSymbols = @import("DebugSymbols.zig");
1010const Dylib = @import("Dylib.zig");
1111const MachO = @import("../MachO.zig");
......@@ -181,22 +181,22 @@ pub fn calcMinHeaderPadSize(macho_file: *MachO) !u32 {
181181 return offset;
182182}
183183
184pub fn writeDylinkerLC(writer: anytype) !void {
184pub fn writeDylinkerLC(writer: *Writer) !void {
185185 const name_len = mem.sliceTo(default_dyld_path, 0).len;
186186 const cmdsize = @as(u32, @intCast(mem.alignForward(
187187 u64,
188188 @sizeOf(macho.dylinker_command) + name_len,
189189 @sizeOf(u64),
190190 )));
191 try writer.writeStruct(macho.dylinker_command{
191 try writer.writeStruct(@as(macho.dylinker_command, .{
192192 .cmd = .LOAD_DYLINKER,
193193 .cmdsize = cmdsize,
194194 .name = @sizeOf(macho.dylinker_command),
195 });
195 }), .little);
196196 try writer.writeAll(mem.sliceTo(default_dyld_path, 0));
197197 const padding = cmdsize - @sizeOf(macho.dylinker_command) - name_len;
198198 if (padding > 0) {
199 try writer.writeByteNTimes(0, padding);
199 try writer.splatByteAll(0, padding);
200200 }
201201}
202202
......@@ -208,14 +208,14 @@ const WriteDylibLCCtx = struct {
208208 compatibility_version: u32 = 0x10000,
209209};
210210
211pub fn writeDylibLC(ctx: WriteDylibLCCtx, writer: anytype) !void {
211pub fn writeDylibLC(ctx: WriteDylibLCCtx, writer: *Writer) !void {
212212 const name_len = ctx.name.len + 1;
213213 const cmdsize = @as(u32, @intCast(mem.alignForward(
214214 u64,
215215 @sizeOf(macho.dylib_command) + name_len,
216216 @sizeOf(u64),
217217 )));
218 try writer.writeStruct(macho.dylib_command{
218 try writer.writeStruct(@as(macho.dylib_command, .{
219219 .cmd = ctx.cmd,
220220 .cmdsize = cmdsize,
221221 .dylib = .{
......@@ -224,16 +224,16 @@ pub fn writeDylibLC(ctx: WriteDylibLCCtx, writer: anytype) !void {
224224 .current_version = ctx.current_version,
225225 .compatibility_version = ctx.compatibility_version,
226226 },
227 });
227 }), .little);
228228 try writer.writeAll(ctx.name);
229229 try writer.writeByte(0);
230230 const padding = cmdsize - @sizeOf(macho.dylib_command) - name_len;
231231 if (padding > 0) {
232 try writer.writeByteNTimes(0, padding);
232 try writer.splatByteAll(0, padding);
233233 }
234234}
235235
236pub fn writeDylibIdLC(macho_file: *MachO, writer: anytype) !void {
236pub fn writeDylibIdLC(macho_file: *MachO, writer: *Writer) !void {
237237 const comp = macho_file.base.comp;
238238 const gpa = comp.gpa;
239239 assert(comp.config.output_mode == .Lib and comp.config.link_mode == .dynamic);
......@@ -259,26 +259,26 @@ pub fn writeDylibIdLC(macho_file: *MachO, writer: anytype) !void {
259259 }, writer);
260260}
261261
262pub fn writeRpathLC(rpath: []const u8, writer: anytype) !void {
262pub fn writeRpathLC(rpath: []const u8, writer: *Writer) !void {
263263 const rpath_len = rpath.len + 1;
264264 const cmdsize = @as(u32, @intCast(mem.alignForward(
265265 u64,
266266 @sizeOf(macho.rpath_command) + rpath_len,
267267 @sizeOf(u64),
268268 )));
269 try writer.writeStruct(macho.rpath_command{
269 try writer.writeStruct(@as(macho.rpath_command, .{
270270 .cmdsize = cmdsize,
271271 .path = @sizeOf(macho.rpath_command),
272 });
272 }), .little);
273273 try writer.writeAll(rpath);
274274 try writer.writeByte(0);
275275 const padding = cmdsize - @sizeOf(macho.rpath_command) - rpath_len;
276276 if (padding > 0) {
277 try writer.writeByteNTimes(0, padding);
277 try writer.splatByteAll(0, padding);
278278 }
279279}
280280
281pub fn writeVersionMinLC(platform: MachO.Platform, sdk_version: ?std.SemanticVersion, writer: anytype) !void {
281pub fn writeVersionMinLC(platform: MachO.Platform, sdk_version: ?std.SemanticVersion, writer: *Writer) !void {
282282 const cmd: macho.LC = switch (platform.os_tag) {
283283 .macos => .VERSION_MIN_MACOSX,
284284 .ios => .VERSION_MIN_IPHONEOS,
......@@ -296,9 +296,9 @@ pub fn writeVersionMinLC(platform: MachO.Platform, sdk_version: ?std.SemanticVer
296296 }));
297297}
298298
299pub fn writeBuildVersionLC(platform: MachO.Platform, sdk_version: ?std.SemanticVersion, writer: anytype) !void {
299pub fn writeBuildVersionLC(platform: MachO.Platform, sdk_version: ?std.SemanticVersion, writer: *Writer) !void {
300300 const cmdsize = @sizeOf(macho.build_version_command) + @sizeOf(macho.build_tool_version);
301 try writer.writeStruct(macho.build_version_command{
301 try writer.writeStruct(@as(macho.build_version_command, .{
302302 .cmdsize = cmdsize,
303303 .platform = platform.toApplePlatform(),
304304 .minos = platform.toAppleVersion(),
......@@ -307,7 +307,7 @@ pub fn writeBuildVersionLC(platform: MachO.Platform, sdk_version: ?std.SemanticV
307307 else
308308 platform.toAppleVersion(),
309309 .ntools = 1,
310 });
310 }), .little);
311311 try writer.writeAll(mem.asBytes(&macho.build_tool_version{
312312 .tool = .ZIG,
313313 .version = 0x0,
src/link/MachO/relocatable.zig+29-33
......@@ -205,35 +205,32 @@ pub fn flushStaticLib(macho_file: *MachO, comp: *Compilation, module_obj_path: ?
205205 state_log.debug("ar_symtab\n{f}\n", .{ar_symtab.fmt(macho_file)});
206206 }
207207
208 var buffer = std.array_list.Managed(u8).init(gpa);
209 defer buffer.deinit();
210 try buffer.ensureTotalCapacityPrecise(total_size);
211 const writer = buffer.writer();
208 const buffer = try gpa.alloc(u8, total_size);
209 defer gpa.free(buffer);
210 var writer: Writer = .fixed(buffer);
212211
213212 // Write magic
214 try writer.writeAll(Archive.ARMAG);
213 writer.writeAll(Archive.ARMAG) catch unreachable;
215214
216215 // Write symtab
217 ar_symtab.write(format, macho_file, writer) catch |err| switch (err) {
218 error.OutOfMemory => return error.OutOfMemory,
219 else => |e| return diags.fail("failed to write archive symbol table: {s}", .{@errorName(e)}),
220 };
216 ar_symtab.write(format, macho_file, &writer) catch |err|
217 return diags.fail("failed to write archive symbol table: {t}", .{err});
221218
222219 // Write object files
223220 for (files.items) |index| {
224 const aligned = mem.alignForward(usize, buffer.items.len, 2);
225 const padding = aligned - buffer.items.len;
221 const aligned = mem.alignForward(usize, writer.end, 2);
222 const padding = aligned - writer.end;
226223 if (padding > 0) {
227 try writer.writeByteNTimes(0, padding);
224 writer.splatByteAll(0, padding) catch unreachable;
228225 }
229 macho_file.getFile(index).?.writeAr(format, macho_file, writer) catch |err|
230 return diags.fail("failed to write archive: {s}", .{@errorName(err)});
226 macho_file.getFile(index).?.writeAr(format, macho_file, &writer) catch |err|
227 return diags.fail("failed to write archive: {t}", .{err});
231228 }
232229
233 assert(buffer.items.len == total_size);
230 assert(writer.end == total_size);
234231
235232 try macho_file.setEndPos(total_size);
236 try macho_file.pwriteAll(buffer.items, 0);
233 try macho_file.pwriteAll(writer.buffered(), 0);
237234
238235 if (diags.hasErrors()) return error.LinkFailure;
239236}
......@@ -693,8 +690,7 @@ fn writeLoadCommands(macho_file: *MachO) error{ LinkFailure, OutOfMemory }!struc
693690 const buffer = try gpa.alloc(u8, needed_size);
694691 defer gpa.free(buffer);
695692
696 var stream = std.io.fixedBufferStream(buffer);
697 const writer = stream.writer();
693 var writer: Writer = .fixed(buffer);
698694
699695 var ncmds: usize = 0;
700696
......@@ -702,43 +698,43 @@ fn writeLoadCommands(macho_file: *MachO) error{ LinkFailure, OutOfMemory }!struc
702698 {
703699 assert(macho_file.segments.items.len == 1);
704700 const seg = macho_file.segments.items[0];
705 writer.writeStruct(seg) catch |err| switch (err) {
706 error.NoSpaceLeft => unreachable,
701 writer.writeStruct(seg, .little) catch |err| switch (err) {
702 error.WriteFailed => unreachable,
707703 };
708704 for (macho_file.sections.items(.header)) |header| {
709 writer.writeStruct(header) catch |err| switch (err) {
710 error.NoSpaceLeft => unreachable,
705 writer.writeStruct(header, .little) catch |err| switch (err) {
706 error.WriteFailed => unreachable,
711707 };
712708 }
713709 ncmds += 1;
714710 }
715711
716 writer.writeStruct(macho_file.data_in_code_cmd) catch |err| switch (err) {
717 error.NoSpaceLeft => unreachable,
712 writer.writeStruct(macho_file.data_in_code_cmd, .little) catch |err| switch (err) {
713 error.WriteFailed => unreachable,
718714 };
719715 ncmds += 1;
720 writer.writeStruct(macho_file.symtab_cmd) catch |err| switch (err) {
721 error.NoSpaceLeft => unreachable,
716 writer.writeStruct(macho_file.symtab_cmd, .little) catch |err| switch (err) {
717 error.WriteFailed => unreachable,
722718 };
723719 ncmds += 1;
724 writer.writeStruct(macho_file.dysymtab_cmd) catch |err| switch (err) {
725 error.NoSpaceLeft => unreachable,
720 writer.writeStruct(macho_file.dysymtab_cmd, .little) catch |err| switch (err) {
721 error.WriteFailed => unreachable,
726722 };
727723 ncmds += 1;
728724
729725 if (macho_file.platform.isBuildVersionCompatible()) {
730 load_commands.writeBuildVersionLC(macho_file.platform, macho_file.sdk_version, writer) catch |err| switch (err) {
731 error.NoSpaceLeft => unreachable,
726 load_commands.writeBuildVersionLC(macho_file.platform, macho_file.sdk_version, &writer) catch |err| switch (err) {
727 error.WriteFailed => unreachable,
732728 };
733729 ncmds += 1;
734730 } else {
735 load_commands.writeVersionMinLC(macho_file.platform, macho_file.sdk_version, writer) catch |err| switch (err) {
736 error.NoSpaceLeft => unreachable,
731 load_commands.writeVersionMinLC(macho_file.platform, macho_file.sdk_version, &writer) catch |err| switch (err) {
732 error.WriteFailed => unreachable,
737733 };
738734 ncmds += 1;
739735 }
740736
741 assert(stream.pos == needed_size);
737 assert(writer.end == needed_size);
742738
743739 try macho_file.pwriteAll(buffer, @sizeOf(macho.mach_header_64));
744740
src/link/MachO/synthetic.zig+12-12
......@@ -27,7 +27,7 @@ pub const GotSection = struct {
2727 return got.symbols.items.len * @sizeOf(u64);
2828 }
2929
30 pub fn write(got: GotSection, macho_file: *MachO, writer: anytype) !void {
30 pub fn write(got: GotSection, macho_file: *MachO, writer: *Writer) !void {
3131 const tracy = trace(@src());
3232 defer tracy.end();
3333 for (got.symbols.items) |ref| {
......@@ -89,7 +89,7 @@ pub const StubsSection = struct {
8989 return stubs.symbols.items.len * header.reserved2;
9090 }
9191
92 pub fn write(stubs: StubsSection, macho_file: *MachO, writer: anytype) !void {
92 pub fn write(stubs: StubsSection, macho_file: *MachO, writer: *Writer) !void {
9393 const tracy = trace(@src());
9494 defer tracy.end();
9595 const cpu_arch = macho_file.getTarget().cpu.arch;
......@@ -174,7 +174,7 @@ pub const StubsHelperSection = struct {
174174 return s;
175175 }
176176
177 pub fn write(stubs_helper: StubsHelperSection, macho_file: *MachO, writer: anytype) !void {
177 pub fn write(stubs_helper: StubsHelperSection, macho_file: *MachO, writer: *Writer) !void {
178178 const tracy = trace(@src());
179179 defer tracy.end();
180180
......@@ -217,7 +217,7 @@ pub const StubsHelperSection = struct {
217217 }
218218 }
219219
220 fn writePreamble(stubs_helper: StubsHelperSection, macho_file: *MachO, writer: anytype) !void {
220 fn writePreamble(stubs_helper: StubsHelperSection, macho_file: *MachO, writer: *Writer) !void {
221221 _ = stubs_helper;
222222 const obj = macho_file.getInternalObject().?;
223223 const cpu_arch = macho_file.getTarget().cpu.arch;
......@@ -273,7 +273,7 @@ pub const LaSymbolPtrSection = struct {
273273 return macho_file.stubs.symbols.items.len * @sizeOf(u64);
274274 }
275275
276 pub fn write(laptr: LaSymbolPtrSection, macho_file: *MachO, writer: anytype) !void {
276 pub fn write(laptr: LaSymbolPtrSection, macho_file: *MachO, writer: *Writer) !void {
277277 const tracy = trace(@src());
278278 defer tracy.end();
279279 _ = laptr;
......@@ -323,7 +323,7 @@ pub const TlvPtrSection = struct {
323323 return tlv.symbols.items.len * @sizeOf(u64);
324324 }
325325
326 pub fn write(tlv: TlvPtrSection, macho_file: *MachO, writer: anytype) !void {
326 pub fn write(tlv: TlvPtrSection, macho_file: *MachO, writer: *Writer) !void {
327327 const tracy = trace(@src());
328328 defer tracy.end();
329329
......@@ -394,7 +394,7 @@ pub const ObjcStubsSection = struct {
394394 return objc.symbols.items.len * entrySize(macho_file.getTarget().cpu.arch);
395395 }
396396
397 pub fn write(objc: ObjcStubsSection, macho_file: *MachO, writer: anytype) !void {
397 pub fn write(objc: ObjcStubsSection, macho_file: *MachO, writer: *Writer) !void {
398398 const tracy = trace(@src());
399399 defer tracy.end();
400400
......@@ -487,7 +487,7 @@ pub const Indsymtab = struct {
487487 macho_file.dysymtab_cmd.nindirectsyms = ind.nsyms(macho_file);
488488 }
489489
490 pub fn write(ind: Indsymtab, macho_file: *MachO, writer: anytype) !void {
490 pub fn write(ind: Indsymtab, macho_file: *MachO, writer: *Writer) !void {
491491 const tracy = trace(@src());
492492 defer tracy.end();
493493
......@@ -564,7 +564,7 @@ pub const DataInCode = struct {
564564 macho_file.data_in_code_cmd.datasize = math.cast(u32, dice.size()) orelse return error.Overflow;
565565 }
566566
567 pub fn write(dice: DataInCode, macho_file: *MachO, writer: anytype) !void {
567 pub fn write(dice: DataInCode, macho_file: *MachO, writer: *Writer) !void {
568568 const base_address = if (!macho_file.base.isRelocatable())
569569 macho_file.getTextSegment().vmaddr
570570 else
......@@ -572,11 +572,11 @@ pub const DataInCode = struct {
572572 for (dice.entries.items) |entry| {
573573 const atom_address = entry.atom_ref.getAtom(macho_file).?.getAddress(macho_file);
574574 const offset = atom_address + entry.offset - base_address;
575 try writer.writeStruct(macho.data_in_code_entry{
575 try writer.writeStruct(@as(macho.data_in_code_entry, .{
576576 .offset = @intCast(offset),
577577 .length = entry.length,
578578 .kind = entry.kind,
579 });
579 }), .little);
580580 }
581581 }
582582
......@@ -594,7 +594,7 @@ const assert = std.debug.assert;
594594const macho = std.macho;
595595const math = std.math;
596596const Allocator = std.mem.Allocator;
597const Writer = std.io.Writer;
597const Writer = std.Io.Writer;
598598
599599const trace = @import("../../tracy.zig").trace;
600600const MachO = @import("../MachO.zig");
src/link/Wasm/Flush.zig+176-149
......@@ -19,6 +19,7 @@ const mem = std.mem;
1919const leb = std.leb;
2020const log = std.log.scoped(.link);
2121const assert = std.debug.assert;
22const ArrayList = std.ArrayList;
2223
2324/// Ordered list of data segments that will appear in the final binary.
2425/// When sorted, to-be-merged segments will be made adjacent.
......@@ -27,9 +28,9 @@ data_segments: std.AutoArrayHashMapUnmanaged(Wasm.DataSegmentId, u32) = .empty,
2728/// Each time a `data_segment` offset equals zero it indicates a new group, and
2829/// the next element in this array will contain the total merged segment size.
2930/// Value is the virtual memory address of the end of the segment.
30data_segment_groups: std.ArrayListUnmanaged(DataSegmentGroup) = .empty,
31data_segment_groups: ArrayList(DataSegmentGroup) = .empty,
3132
32binary_bytes: std.ArrayListUnmanaged(u8) = .empty,
33binary_bytes: ArrayList(u8) = .empty,
3334missing_exports: std.AutoArrayHashMapUnmanaged(String, void) = .empty,
3435function_imports: std.AutoArrayHashMapUnmanaged(String, Wasm.FunctionImportId) = .empty,
3536global_imports: std.AutoArrayHashMapUnmanaged(String, Wasm.GlobalImportId) = .empty,
......@@ -563,8 +564,6 @@ pub fn finish(f: *Flush, wasm: *Wasm) !void {
563564 try binary_bytes.appendSlice(gpa, &std.wasm.magic ++ &std.wasm.version);
564565 assert(binary_bytes.items.len == 8);
565566
566 const binary_writer = binary_bytes.writer(gpa);
567
568567 // Type section.
569568 for (f.function_imports.values()) |id| {
570569 try f.func_types.put(gpa, id.functionType(wasm), {});
......@@ -576,16 +575,16 @@ pub fn finish(f: *Flush, wasm: *Wasm) !void {
576575 const header_offset = try reserveVecSectionHeader(gpa, binary_bytes);
577576 for (f.func_types.keys()) |func_type_index| {
578577 const func_type = func_type_index.ptr(wasm);
579 try leb.writeUleb128(binary_writer, std.wasm.function_type);
578 try appendLeb128(gpa, binary_bytes, std.wasm.function_type);
580579 const params = func_type.params.slice(wasm);
581 try leb.writeUleb128(binary_writer, @as(u32, @intCast(params.len)));
580 try appendLeb128(gpa, binary_bytes, @as(u32, @intCast(params.len)));
582581 for (params) |param_ty| {
583 try leb.writeUleb128(binary_writer, @intFromEnum(param_ty));
582 try appendLeb128(gpa, binary_bytes, @intFromEnum(param_ty));
584583 }
585584 const returns = func_type.returns.slice(wasm);
586 try leb.writeUleb128(binary_writer, @as(u32, @intCast(returns.len)));
585 try appendLeb128(gpa, binary_bytes, @as(u32, @intCast(returns.len)));
587586 for (returns) |ret_ty| {
588 try leb.writeUleb128(binary_writer, @intFromEnum(ret_ty));
587 try appendLeb128(gpa, binary_bytes, @intFromEnum(ret_ty));
589588 }
590589 }
591590 replaceVecSectionHeader(binary_bytes, header_offset, .type, @intCast(f.func_types.entries.len));
......@@ -605,31 +604,31 @@ pub fn finish(f: *Flush, wasm: *Wasm) !void {
605604
606605 for (f.function_imports.values()) |id| {
607606 const module_name = id.moduleName(wasm).slice(wasm).?;
608 try leb.writeUleb128(binary_writer, @as(u32, @intCast(module_name.len)));
609 try binary_writer.writeAll(module_name);
607 try appendLeb128(gpa, binary_bytes, @as(u32, @intCast(module_name.len)));
608 try binary_bytes.appendSlice(gpa, module_name);
610609
611610 const name = id.importName(wasm).slice(wasm);
612 try leb.writeUleb128(binary_writer, @as(u32, @intCast(name.len)));
613 try binary_writer.writeAll(name);
611 try appendLeb128(gpa, binary_bytes, @as(u32, @intCast(name.len)));
612 try binary_bytes.appendSlice(gpa, name);
614613
615 try binary_writer.writeByte(@intFromEnum(std.wasm.ExternalKind.function));
614 try binary_bytes.append(gpa, @intFromEnum(std.wasm.ExternalKind.function));
616615 const type_index: FuncTypeIndex = .fromTypeIndex(id.functionType(wasm), f);
617 try leb.writeUleb128(binary_writer, @intFromEnum(type_index));
616 try appendLeb128(gpa, binary_bytes, @intFromEnum(type_index));
618617 }
619618 total_imports += f.function_imports.entries.len;
620619
621620 for (wasm.table_imports.values()) |id| {
622621 const table_import = id.value(wasm);
623622 const module_name = table_import.module_name.slice(wasm);
624 try leb.writeUleb128(binary_writer, @as(u32, @intCast(module_name.len)));
625 try binary_writer.writeAll(module_name);
623 try appendLeb128(gpa, binary_bytes, @as(u32, @intCast(module_name.len)));
624 try binary_bytes.appendSlice(gpa, module_name);
626625
627626 const name = table_import.name.slice(wasm);
628 try leb.writeUleb128(binary_writer, @as(u32, @intCast(name.len)));
629 try binary_writer.writeAll(name);
627 try appendLeb128(gpa, binary_bytes, @as(u32, @intCast(name.len)));
628 try binary_bytes.appendSlice(gpa, name);
630629
631 try binary_writer.writeByte(@intFromEnum(std.wasm.ExternalKind.table));
632 try leb.writeUleb128(binary_writer, @intFromEnum(@as(std.wasm.RefType, table_import.flags.ref_type.to())));
630 try binary_bytes.append(gpa, @intFromEnum(std.wasm.ExternalKind.table));
631 try appendLeb128(gpa, binary_bytes, @intFromEnum(@as(std.wasm.RefType, table_import.flags.ref_type.to())));
633632 try emitLimits(gpa, binary_bytes, table_import.limits());
634633 }
635634 total_imports += wasm.table_imports.entries.len;
......@@ -650,17 +649,17 @@ pub fn finish(f: *Flush, wasm: *Wasm) !void {
650649
651650 for (f.global_imports.values()) |id| {
652651 const module_name = id.moduleName(wasm).slice(wasm).?;
653 try leb.writeUleb128(binary_writer, @as(u32, @intCast(module_name.len)));
654 try binary_writer.writeAll(module_name);
652 try appendLeb128(gpa, binary_bytes, @as(u32, @intCast(module_name.len)));
653 try binary_bytes.appendSlice(gpa, module_name);
655654
656655 const name = id.importName(wasm).slice(wasm);
657 try leb.writeUleb128(binary_writer, @as(u32, @intCast(name.len)));
658 try binary_writer.writeAll(name);
656 try appendLeb128(gpa, binary_bytes, @as(u32, @intCast(name.len)));
657 try binary_bytes.appendSlice(gpa, name);
659658
660 try binary_writer.writeByte(@intFromEnum(std.wasm.ExternalKind.global));
659 try binary_bytes.append(gpa, @intFromEnum(std.wasm.ExternalKind.global));
661660 const global_type = id.globalType(wasm);
662 try leb.writeUleb128(binary_writer, @intFromEnum(@as(std.wasm.Valtype, global_type.valtype)));
663 try binary_writer.writeByte(@intFromBool(global_type.mutable));
661 try appendLeb128(gpa, binary_bytes, @intFromEnum(@as(std.wasm.Valtype, global_type.valtype)));
662 try binary_bytes.append(gpa, @intFromBool(global_type.mutable));
664663 }
665664 total_imports += f.global_imports.entries.len;
666665
......@@ -677,7 +676,7 @@ pub fn finish(f: *Flush, wasm: *Wasm) !void {
677676 const header_offset = try reserveVecSectionHeader(gpa, binary_bytes);
678677 for (wasm.functions.keys()) |function| {
679678 const index: FuncTypeIndex = .fromTypeIndex(function.typeIndex(wasm), f);
680 try leb.writeUleb128(binary_writer, @intFromEnum(index));
679 try appendLeb128(gpa, binary_bytes, @intFromEnum(index));
681680 }
682681
683682 replaceVecSectionHeader(binary_bytes, header_offset, .function, @intCast(wasm.functions.count()));
......@@ -689,7 +688,7 @@ pub fn finish(f: *Flush, wasm: *Wasm) !void {
689688 const header_offset = try reserveVecSectionHeader(gpa, binary_bytes);
690689
691690 for (wasm.tables.keys()) |table| {
692 try leb.writeUleb128(binary_writer, @intFromEnum(@as(std.wasm.RefType, table.refType(wasm))));
691 try appendLeb128(gpa, binary_bytes, @intFromEnum(@as(std.wasm.RefType, table.refType(wasm))));
693692 try emitLimits(gpa, binary_bytes, table.limits(wasm));
694693 }
695694
......@@ -743,39 +742,39 @@ pub fn finish(f: *Flush, wasm: *Wasm) !void {
743742
744743 for (wasm.function_exports.keys(), wasm.function_exports.values()) |exp_name, function_index| {
745744 const name = exp_name.slice(wasm);
746 try leb.writeUleb128(binary_writer, @as(u32, @intCast(name.len)));
745 try appendLeb128(gpa, binary_bytes, @as(u32, @intCast(name.len)));
747746 try binary_bytes.appendSlice(gpa, name);
748747 try binary_bytes.append(gpa, @intFromEnum(std.wasm.ExternalKind.function));
749748 const func_index = Wasm.OutputFunctionIndex.fromFunctionIndex(wasm, function_index);
750 try leb.writeUleb128(binary_writer, @intFromEnum(func_index));
749 try appendLeb128(gpa, binary_bytes, @intFromEnum(func_index));
751750 }
752751 exports_len += wasm.function_exports.entries.len;
753752
754753 if (wasm.export_table and f.indirect_function_table.entries.len > 0) {
755754 const name = "__indirect_function_table";
756755 const index: u32 = @intCast(wasm.tables.getIndex(.__indirect_function_table).?);
757 try leb.writeUleb128(binary_writer, @as(u32, @intCast(name.len)));
756 try appendLeb128(gpa, binary_bytes, @as(u32, @intCast(name.len)));
758757 try binary_bytes.appendSlice(gpa, name);
759758 try binary_bytes.append(gpa, @intFromEnum(std.wasm.ExternalKind.table));
760 try leb.writeUleb128(binary_writer, index);
759 try appendLeb128(gpa, binary_bytes, index);
761760 exports_len += 1;
762761 }
763762
764763 if (export_memory) {
765764 const name = "memory";
766 try leb.writeUleb128(binary_writer, @as(u32, @intCast(name.len)));
765 try appendLeb128(gpa, binary_bytes, @as(u32, @intCast(name.len)));
767766 try binary_bytes.appendSlice(gpa, name);
768767 try binary_bytes.append(gpa, @intFromEnum(std.wasm.ExternalKind.memory));
769 try leb.writeUleb128(binary_writer, @as(u32, 0));
768 try appendLeb128(gpa, binary_bytes, @as(u32, 0));
770769 exports_len += 1;
771770 }
772771
773772 for (wasm.global_exports.items) |exp| {
774773 const name = exp.name.slice(wasm);
775 try leb.writeUleb128(binary_writer, @as(u32, @intCast(name.len)));
774 try appendLeb128(gpa, binary_bytes, @as(u32, @intCast(name.len)));
776775 try binary_bytes.appendSlice(gpa, name);
777776 try binary_bytes.append(gpa, @intFromEnum(std.wasm.ExternalKind.global));
778 try leb.writeUleb128(binary_writer, @intFromEnum(exp.global_index));
777 try appendLeb128(gpa, binary_bytes, @intFromEnum(exp.global_index));
779778 }
780779 exports_len += wasm.global_exports.items.len;
781780
......@@ -802,18 +801,22 @@ pub fn finish(f: *Flush, wasm: *Wasm) !void {
802801 const table_index: u32 = @intCast(wasm.tables.getIndex(.__indirect_function_table).?);
803802 // passive with implicit 0-index table or set table index manually
804803 const flags: u32 = if (table_index == 0) 0x0 else 0x02;
805 try leb.writeUleb128(binary_writer, flags);
804 try appendLeb128(gpa, binary_bytes, flags);
806805 if (flags == 0x02) {
807 try leb.writeUleb128(binary_writer, table_index);
806 try appendLeb128(gpa, binary_bytes, table_index);
808807 }
809808 // We start at index 1, so unresolved function pointers are invalid
810 try emitInit(binary_writer, .{ .i32_const = 1 });
809 {
810 var aw: std.Io.Writer.Allocating = .fromArrayList(gpa, binary_bytes);
811 defer binary_bytes.* = aw.toArrayList();
812 try emitInit(&aw.writer, .{ .i32_const = 1 });
813 }
811814 if (flags == 0x02) {
812 try leb.writeUleb128(binary_writer, @as(u8, 0)); // represents funcref
815 try appendLeb128(gpa, binary_bytes, @as(u8, 0)); // represents funcref
813816 }
814 try leb.writeUleb128(binary_writer, @as(u32, @intCast(f.indirect_function_table.entries.len)));
817 try appendLeb128(gpa, binary_bytes, @as(u32, @intCast(f.indirect_function_table.entries.len)));
815818 for (f.indirect_function_table.keys()) |func_index| {
816 try leb.writeUleb128(binary_writer, @intFromEnum(func_index));
819 try appendLeb128(gpa, binary_bytes, @intFromEnum(func_index));
817820 }
818821
819822 replaceVecSectionHeader(binary_bytes, header_offset, .element, 1);
......@@ -851,7 +854,7 @@ pub fn finish(f: *Flush, wasm: *Wasm) !void {
851854 .object_function => |i| {
852855 const ptr = i.ptr(wasm);
853856 const code = ptr.code.slice(wasm);
854 try leb.writeUleb128(binary_writer, code.len);
857 try appendLeb128(gpa, binary_bytes, code.len);
855858 const code_start = binary_bytes.items.len;
856859 try binary_bytes.appendSlice(gpa, code);
857860 if (!is_obj) applyRelocs(binary_bytes.items[code_start..], ptr.offset, ptr.relocations(wasm), wasm);
......@@ -946,12 +949,14 @@ pub fn finish(f: *Flush, wasm: *Wasm) !void {
946949 const group_size = group_end_addr - group_start_addr;
947950 log.debug("emit data section group, {d} bytes", .{group_size});
948951 const flags: Object.DataSegmentFlags = if (segment_id.isPassive(wasm)) .passive else .active;
949 try leb.writeUleb128(binary_writer, @intFromEnum(flags));
952 try appendLeb128(gpa, binary_bytes, @intFromEnum(flags));
950953 // Passive segments are initialized at runtime.
951954 if (flags != .passive) {
952 try emitInit(binary_writer, .{ .i32_const = @as(i32, @bitCast(group_start_addr)) });
955 var aw: std.Io.Writer.Allocating = .fromArrayList(gpa, binary_bytes);
956 defer binary_bytes.* = aw.toArrayList();
957 try emitInit(&aw.writer, .{ .i32_const = @as(i32, @bitCast(group_start_addr)) });
953958 }
954 try leb.writeUleb128(binary_writer, group_size);
959 try appendLeb128(gpa, binary_bytes, group_size);
955960 }
956961 if (segment_id.isEmpty(wasm)) {
957962 // It counted for virtual memory but it does not go into the binary.
......@@ -1077,7 +1082,7 @@ const VirtualAddrs = struct {
10771082fn emitNameSection(
10781083 wasm: *Wasm,
10791084 data_segment_groups: []const DataSegmentGroup,
1080 binary_bytes: *std.ArrayListUnmanaged(u8),
1085 binary_bytes: *ArrayList(u8),
10811086) !void {
10821087 const f = &wasm.flush_buffer;
10831088 const comp = wasm.base.comp;
......@@ -1087,7 +1092,7 @@ fn emitNameSection(
10871092 defer writeCustomSectionHeader(binary_bytes, header_offset);
10881093
10891094 const name_name = "name";
1090 try leb.writeUleb128(binary_bytes.writer(gpa), @as(u32, name_name.len));
1095 try appendLeb128(gpa, binary_bytes, @as(u32, name_name.len));
10911096 try binary_bytes.appendSlice(gpa, name_name);
10921097
10931098 {
......@@ -1095,18 +1100,18 @@ fn emitNameSection(
10951100 defer replaceHeader(binary_bytes, sub_offset, @intFromEnum(std.wasm.NameSubsection.function));
10961101
10971102 const total_functions: u32 = @intCast(f.function_imports.entries.len + wasm.functions.entries.len);
1098 try leb.writeUleb128(binary_bytes.writer(gpa), total_functions);
1103 try appendLeb128(gpa, binary_bytes, total_functions);
10991104
11001105 for (f.function_imports.keys(), 0..) |name_index, function_index| {
11011106 const name = name_index.slice(wasm);
1102 try leb.writeUleb128(binary_bytes.writer(gpa), @as(u32, @intCast(function_index)));
1103 try leb.writeUleb128(binary_bytes.writer(gpa), @as(u32, @intCast(name.len)));
1107 try appendLeb128(gpa, binary_bytes, @as(u32, @intCast(function_index)));
1108 try appendLeb128(gpa, binary_bytes, @as(u32, @intCast(name.len)));
11041109 try binary_bytes.appendSlice(gpa, name);
11051110 }
11061111 for (wasm.functions.keys(), f.function_imports.entries.len..) |resolution, function_index| {
11071112 const name = resolution.name(wasm).?;
1108 try leb.writeUleb128(binary_bytes.writer(gpa), @as(u32, @intCast(function_index)));
1109 try leb.writeUleb128(binary_bytes.writer(gpa), @as(u32, @intCast(name.len)));
1113 try appendLeb128(gpa, binary_bytes, @as(u32, @intCast(function_index)));
1114 try appendLeb128(gpa, binary_bytes, @as(u32, @intCast(name.len)));
11101115 try binary_bytes.appendSlice(gpa, name);
11111116 }
11121117 }
......@@ -1116,18 +1121,18 @@ fn emitNameSection(
11161121 defer replaceHeader(binary_bytes, sub_offset, @intFromEnum(std.wasm.NameSubsection.global));
11171122
11181123 const total_globals: u32 = @intCast(f.global_imports.entries.len + wasm.globals.entries.len);
1119 try leb.writeUleb128(binary_bytes.writer(gpa), total_globals);
1124 try appendLeb128(gpa, binary_bytes, total_globals);
11201125
11211126 for (f.global_imports.keys(), 0..) |name_index, global_index| {
11221127 const name = name_index.slice(wasm);
1123 try leb.writeUleb128(binary_bytes.writer(gpa), @as(u32, @intCast(global_index)));
1124 try leb.writeUleb128(binary_bytes.writer(gpa), @as(u32, @intCast(name.len)));
1128 try appendLeb128(gpa, binary_bytes, @as(u32, @intCast(global_index)));
1129 try appendLeb128(gpa, binary_bytes, @as(u32, @intCast(name.len)));
11251130 try binary_bytes.appendSlice(gpa, name);
11261131 }
11271132 for (wasm.globals.keys(), f.global_imports.entries.len..) |resolution, global_index| {
11281133 const name = resolution.name(wasm).?;
1129 try leb.writeUleb128(binary_bytes.writer(gpa), @as(u32, @intCast(global_index)));
1130 try leb.writeUleb128(binary_bytes.writer(gpa), @as(u32, @intCast(name.len)));
1134 try appendLeb128(gpa, binary_bytes, @as(u32, @intCast(global_index)));
1135 try appendLeb128(gpa, binary_bytes, @as(u32, @intCast(name.len)));
11311136 try binary_bytes.appendSlice(gpa, name);
11321137 }
11331138 }
......@@ -1137,12 +1142,12 @@ fn emitNameSection(
11371142 defer replaceHeader(binary_bytes, sub_offset, @intFromEnum(std.wasm.NameSubsection.data_segment));
11381143
11391144 const total_data_segments: u32 = @intCast(data_segment_groups.len);
1140 try leb.writeUleb128(binary_bytes.writer(gpa), total_data_segments);
1145 try appendLeb128(gpa, binary_bytes, total_data_segments);
11411146
11421147 for (data_segment_groups, 0..) |group, i| {
11431148 const name, _ = splitSegmentName(group.first_segment.name(wasm));
1144 try leb.writeUleb128(binary_bytes.writer(gpa), @as(u32, @intCast(i)));
1145 try leb.writeUleb128(binary_bytes.writer(gpa), @as(u32, @intCast(name.len)));
1149 try appendLeb128(gpa, binary_bytes, @as(u32, @intCast(i)));
1150 try appendLeb128(gpa, binary_bytes, @as(u32, @intCast(name.len)));
11461151 try binary_bytes.appendSlice(gpa, name);
11471152 }
11481153 }
......@@ -1150,7 +1155,7 @@ fn emitNameSection(
11501155
11511156fn emitFeaturesSection(
11521157 gpa: Allocator,
1153 binary_bytes: *std.ArrayListUnmanaged(u8),
1158 binary_bytes: *ArrayList(u8),
11541159 target: *const std.Target,
11551160) Allocator.Error!void {
11561161 const feature_count = target.cpu.features.count();
......@@ -1159,87 +1164,84 @@ fn emitFeaturesSection(
11591164 const header_offset = try reserveCustomSectionHeader(gpa, binary_bytes);
11601165 defer writeCustomSectionHeader(binary_bytes, header_offset);
11611166
1162 const writer = binary_bytes.writer(gpa);
11631167 const target_features = "target_features";
1164 try leb.writeUleb128(writer, @as(u32, @intCast(target_features.len)));
1165 try writer.writeAll(target_features);
1168 try appendLeb128(gpa, binary_bytes, @as(u32, @intCast(target_features.len)));
1169 try binary_bytes.appendSlice(gpa, target_features);
11661170
1167 try leb.writeUleb128(writer, @as(u32, @intCast(feature_count)));
1171 try appendLeb128(gpa, binary_bytes, @as(u32, @intCast(feature_count)));
11681172
11691173 var safety_count = feature_count;
11701174 for (target.cpu.arch.allFeaturesList(), 0..) |*feature, i| {
11711175 if (!target.cpu.has(.wasm, @as(std.Target.wasm.Feature, @enumFromInt(i)))) continue;
11721176 safety_count -= 1;
11731177
1174 try leb.writeUleb128(writer, @as(u32, '+'));
1178 try appendLeb128(gpa, binary_bytes, @as(u32, '+'));
11751179 // Depends on llvm_name for the hyphenated version that matches wasm tooling conventions.
11761180 const name = feature.llvm_name.?;
1177 try leb.writeUleb128(writer, @as(u32, @intCast(name.len)));
1178 try writer.writeAll(name);
1181 try appendLeb128(gpa, binary_bytes, @as(u32, @intCast(name.len)));
1182 try binary_bytes.appendSlice(gpa, name);
11791183 }
11801184 assert(safety_count == 0);
11811185}
11821186
1183fn emitBuildIdSection(gpa: Allocator, binary_bytes: *std.ArrayListUnmanaged(u8), build_id: []const u8) !void {
1187fn emitBuildIdSection(gpa: Allocator, binary_bytes: *ArrayList(u8), build_id: []const u8) !void {
11841188 const header_offset = try reserveCustomSectionHeader(gpa, binary_bytes);
11851189 defer writeCustomSectionHeader(binary_bytes, header_offset);
11861190
1187 const writer = binary_bytes.writer(gpa);
11881191 const hdr_build_id = "build_id";
1189 try leb.writeUleb128(writer, @as(u32, @intCast(hdr_build_id.len)));
1190 try writer.writeAll(hdr_build_id);
1192 try appendLeb128(gpa, binary_bytes, @as(u32, @intCast(hdr_build_id.len)));
1193 try binary_bytes.appendSlice(gpa, hdr_build_id);
11911194
1192 try leb.writeUleb128(writer, @as(u32, 1));
1193 try leb.writeUleb128(writer, @as(u32, @intCast(build_id.len)));
1194 try writer.writeAll(build_id);
1195 try appendLeb128(gpa, binary_bytes, @as(u32, 1));
1196 try appendLeb128(gpa, binary_bytes, @as(u32, @intCast(build_id.len)));
1197 try binary_bytes.appendSlice(gpa, build_id);
11951198}
11961199
1197fn emitProducerSection(gpa: Allocator, binary_bytes: *std.ArrayListUnmanaged(u8)) !void {
1200fn emitProducerSection(gpa: Allocator, binary_bytes: *ArrayList(u8)) !void {
11981201 const header_offset = try reserveCustomSectionHeader(gpa, binary_bytes);
11991202 defer writeCustomSectionHeader(binary_bytes, header_offset);
12001203
1201 const writer = binary_bytes.writer(gpa);
12021204 const producers = "producers";
1203 try leb.writeUleb128(writer, @as(u32, @intCast(producers.len)));
1204 try writer.writeAll(producers);
1205 try appendLeb128(gpa, binary_bytes, @as(u32, @intCast(producers.len)));
1206 try binary_bytes.appendSlice(gpa, producers);
12051207
1206 try leb.writeUleb128(writer, @as(u32, 2)); // 2 fields: Language + processed-by
1208 try appendLeb128(gpa, binary_bytes, @as(u32, 2)); // 2 fields: Language + processed-by
12071209
12081210 // language field
12091211 {
12101212 const language = "language";
1211 try leb.writeUleb128(writer, @as(u32, @intCast(language.len)));
1212 try writer.writeAll(language);
1213 try appendLeb128(gpa, binary_bytes, @as(u32, @intCast(language.len)));
1214 try binary_bytes.appendSlice(gpa, language);
12131215
12141216 // field_value_count (TODO: Parse object files for producer sections to detect their language)
1215 try leb.writeUleb128(writer, @as(u32, 1));
1217 try appendLeb128(gpa, binary_bytes, @as(u32, 1));
12161218
12171219 // versioned name
12181220 {
1219 try leb.writeUleb128(writer, @as(u32, 3)); // len of "Zig"
1220 try writer.writeAll("Zig");
1221 try appendLeb128(gpa, binary_bytes, @as(u32, 3)); // len of "Zig"
1222 try binary_bytes.appendSlice(gpa, "Zig");
12211223
1222 try leb.writeUleb128(writer, @as(u32, @intCast(build_options.version.len)));
1223 try writer.writeAll(build_options.version);
1224 try appendLeb128(gpa, binary_bytes, @as(u32, @intCast(build_options.version.len)));
1225 try binary_bytes.appendSlice(gpa, build_options.version);
12241226 }
12251227 }
12261228
12271229 // processed-by field
12281230 {
12291231 const processed_by = "processed-by";
1230 try leb.writeUleb128(writer, @as(u32, @intCast(processed_by.len)));
1231 try writer.writeAll(processed_by);
1232 try appendLeb128(gpa, binary_bytes, @as(u32, @intCast(processed_by.len)));
1233 try binary_bytes.appendSlice(gpa, processed_by);
12321234
12331235 // field_value_count (TODO: Parse object files for producer sections to detect other used tools)
1234 try leb.writeUleb128(writer, @as(u32, 1));
1236 try appendLeb128(gpa, binary_bytes, @as(u32, 1));
12351237
12361238 // versioned name
12371239 {
1238 try leb.writeUleb128(writer, @as(u32, 3)); // len of "Zig"
1239 try writer.writeAll("Zig");
1240 try appendLeb128(gpa, binary_bytes, @as(u32, 3)); // len of "Zig"
1241 try binary_bytes.appendSlice(gpa, "Zig");
12401242
1241 try leb.writeUleb128(writer, @as(u32, @intCast(build_options.version.len)));
1242 try writer.writeAll(build_options.version);
1243 try appendLeb128(gpa, binary_bytes, @as(u32, @intCast(build_options.version.len)));
1244 try binary_bytes.appendSlice(gpa, build_options.version);
12431245 }
12441246 }
12451247}
......@@ -1280,99 +1282,97 @@ fn wantSegmentMerge(
12801282const section_header_reserve_size = 1 + 5 + 5;
12811283const section_header_size = 5 + 1;
12821284
1283fn reserveVecSectionHeader(gpa: Allocator, bytes: *std.ArrayListUnmanaged(u8)) Allocator.Error!u32 {
1285fn reserveVecSectionHeader(gpa: Allocator, bytes: *ArrayList(u8)) Allocator.Error!u32 {
12841286 try bytes.appendNTimes(gpa, 0, section_header_reserve_size);
12851287 return @intCast(bytes.items.len - section_header_reserve_size);
12861288}
12871289
12881290fn replaceVecSectionHeader(
1289 bytes: *std.ArrayListUnmanaged(u8),
1291 bytes: *ArrayList(u8),
12901292 offset: u32,
12911293 section: std.wasm.Section,
12921294 n_items: u32,
12931295) void {
12941296 const size: u32 = @intCast(bytes.items.len - offset - section_header_reserve_size + uleb128size(n_items));
12951297 var buf: [section_header_reserve_size]u8 = undefined;
1296 var fbw = std.io.fixedBufferStream(&buf);
1297 const w = fbw.writer();
1298 var w: std.Io.Writer = .fixed(&buf);
12981299 w.writeByte(@intFromEnum(section)) catch unreachable;
1299 leb.writeUleb128(w, size) catch unreachable;
1300 leb.writeUleb128(w, n_items) catch unreachable;
1301 bytes.replaceRangeAssumeCapacity(offset, section_header_reserve_size, fbw.getWritten());
1300 w.writeUleb128(size) catch unreachable;
1301 w.writeUleb128(n_items) catch unreachable;
1302 bytes.replaceRangeAssumeCapacity(offset, section_header_reserve_size, w.buffered());
13021303}
13031304
1304fn reserveCustomSectionHeader(gpa: Allocator, bytes: *std.ArrayListUnmanaged(u8)) Allocator.Error!u32 {
1305fn reserveCustomSectionHeader(gpa: Allocator, bytes: *ArrayList(u8)) Allocator.Error!u32 {
13051306 try bytes.appendNTimes(gpa, 0, section_header_size);
13061307 return @intCast(bytes.items.len - section_header_size);
13071308}
13081309
1309fn writeCustomSectionHeader(bytes: *std.ArrayListUnmanaged(u8), offset: u32) void {
1310fn writeCustomSectionHeader(bytes: *ArrayList(u8), offset: u32) void {
13101311 return replaceHeader(bytes, offset, 0); // 0 = 'custom' section
13111312}
13121313
1313fn replaceHeader(bytes: *std.ArrayListUnmanaged(u8), offset: u32, tag: u8) void {
1314fn replaceHeader(bytes: *ArrayList(u8), offset: u32, tag: u8) void {
13141315 const size: u32 = @intCast(bytes.items.len - offset - section_header_size);
13151316 var buf: [section_header_size]u8 = undefined;
1316 var fbw = std.io.fixedBufferStream(&buf);
1317 const w = fbw.writer();
1317 var w: std.Io.Writer = .fixed(&buf);
13181318 w.writeByte(tag) catch unreachable;
1319 leb.writeUleb128(w, size) catch unreachable;
1320 bytes.replaceRangeAssumeCapacity(offset, section_header_size, fbw.getWritten());
1319 w.writeUleb128(size) catch unreachable;
1320 bytes.replaceRangeAssumeCapacity(offset, section_header_size, w.buffered());
13211321}
13221322
13231323const max_size_encoding = 5;
13241324
1325fn reserveSize(gpa: Allocator, bytes: *std.ArrayListUnmanaged(u8)) Allocator.Error!u32 {
1325fn reserveSize(gpa: Allocator, bytes: *ArrayList(u8)) Allocator.Error!u32 {
13261326 try bytes.appendNTimes(gpa, 0, max_size_encoding);
13271327 return @intCast(bytes.items.len - max_size_encoding);
13281328}
13291329
1330fn replaceSize(bytes: *std.ArrayListUnmanaged(u8), offset: u32) void {
1330fn replaceSize(bytes: *ArrayList(u8), offset: u32) void {
13311331 const size: u32 = @intCast(bytes.items.len - offset - max_size_encoding);
13321332 var buf: [max_size_encoding]u8 = undefined;
1333 var fbw = std.io.fixedBufferStream(&buf);
1334 leb.writeUleb128(fbw.writer(), size) catch unreachable;
1335 bytes.replaceRangeAssumeCapacity(offset, max_size_encoding, fbw.getWritten());
1333 var w: std.Io.Writer = .fixed(&buf);
1334 w.writeUleb128(size) catch unreachable;
1335 bytes.replaceRangeAssumeCapacity(offset, max_size_encoding, w.buffered());
13361336}
13371337
13381338fn emitLimits(
13391339 gpa: Allocator,
1340 binary_bytes: *std.ArrayListUnmanaged(u8),
1340 binary_bytes: *ArrayList(u8),
13411341 limits: std.wasm.Limits,
13421342) Allocator.Error!void {
13431343 try binary_bytes.append(gpa, @bitCast(limits.flags));
1344 try leb.writeUleb128(binary_bytes.writer(gpa), limits.min);
1345 if (limits.flags.has_max) try leb.writeUleb128(binary_bytes.writer(gpa), limits.max);
1344 try appendLeb128(gpa, binary_bytes, limits.min);
1345 if (limits.flags.has_max) try appendLeb128(gpa, binary_bytes, limits.max);
13461346}
13471347
13481348fn emitMemoryImport(
13491349 wasm: *Wasm,
1350 binary_bytes: *std.ArrayListUnmanaged(u8),
1350 binary_bytes: *ArrayList(u8),
13511351 name_index: String,
13521352 memory_import: *const Wasm.MemoryImport,
13531353) Allocator.Error!void {
13541354 const gpa = wasm.base.comp.gpa;
13551355 const module_name = memory_import.module_name.slice(wasm);
1356 try leb.writeUleb128(binary_bytes.writer(gpa), @as(u32, @intCast(module_name.len)));
1356 try appendLeb128(gpa, binary_bytes, @as(u32, @intCast(module_name.len)));
13571357 try binary_bytes.appendSlice(gpa, module_name);
13581358
13591359 const name = name_index.slice(wasm);
1360 try leb.writeUleb128(binary_bytes.writer(gpa), @as(u32, @intCast(name.len)));
1360 try appendLeb128(gpa, binary_bytes, @as(u32, @intCast(name.len)));
13611361 try binary_bytes.appendSlice(gpa, name);
13621362
13631363 try binary_bytes.append(gpa, @intFromEnum(std.wasm.ExternalKind.memory));
13641364 try emitLimits(gpa, binary_bytes, memory_import.limits());
13651365}
13661366
1367pub fn emitInit(writer: anytype, init_expr: std.wasm.InitExpression) !void {
1367fn emitInit(writer: *std.Io.Writer, init_expr: std.wasm.InitExpression) !void {
13681368 switch (init_expr) {
13691369 .i32_const => |val| {
13701370 try writer.writeByte(@intFromEnum(std.wasm.Opcode.i32_const));
1371 try leb.writeIleb128(writer, val);
1371 try writer.writeSleb128(val);
13721372 },
13731373 .i64_const => |val| {
13741374 try writer.writeByte(@intFromEnum(std.wasm.Opcode.i64_const));
1375 try leb.writeIleb128(writer, val);
1375 try writer.writeSleb128(val);
13761376 },
13771377 .f32_const => |val| {
13781378 try writer.writeByte(@intFromEnum(std.wasm.Opcode.f32_const));
......@@ -1384,13 +1384,13 @@ pub fn emitInit(writer: anytype, init_expr: std.wasm.InitExpression) !void {
13841384 },
13851385 .global_get => |val| {
13861386 try writer.writeByte(@intFromEnum(std.wasm.Opcode.global_get));
1387 try leb.writeUleb128(writer, val);
1387 try writer.writeUleb128(val);
13881388 },
13891389 }
13901390 try writer.writeByte(@intFromEnum(std.wasm.Opcode.end));
13911391}
13921392
1393pub fn emitExpr(wasm: *const Wasm, binary_bytes: *std.ArrayListUnmanaged(u8), expr: Wasm.Expr) Allocator.Error!void {
1393pub fn emitExpr(wasm: *const Wasm, binary_bytes: *ArrayList(u8), expr: Wasm.Expr) Allocator.Error!void {
13941394 const gpa = wasm.base.comp.gpa;
13951395 const slice = expr.slice(wasm);
13961396 try binary_bytes.appendSlice(gpa, slice[0 .. slice.len + 1]); // +1 to include end opcode
......@@ -1398,21 +1398,20 @@ pub fn emitExpr(wasm: *const Wasm, binary_bytes: *std.ArrayListUnmanaged(u8), ex
13981398
13991399fn emitSegmentInfo(wasm: *Wasm, binary_bytes: *std.array_list.Managed(u8)) !void {
14001400 const gpa = wasm.base.comp.gpa;
1401 const writer = binary_bytes.writer(gpa);
1402 try leb.writeUleb128(writer, @intFromEnum(Wasm.SubsectionType.segment_info));
1401 try appendLeb128(gpa, binary_bytes, @intFromEnum(Wasm.SubsectionType.segment_info));
14031402 const segment_offset = binary_bytes.items.len;
14041403
1405 try leb.writeUleb128(writer, @as(u32, @intCast(wasm.segment_info.count())));
1404 try appendLeb128(gpa, binary_bytes, @as(u32, @intCast(wasm.segment_info.count())));
14061405 for (wasm.segment_info.values()) |segment_info| {
14071406 log.debug("Emit segment: {s} align({d}) flags({b})", .{
14081407 segment_info.name,
14091408 segment_info.alignment,
14101409 segment_info.flags,
14111410 });
1412 try leb.writeUleb128(writer, @as(u32, @intCast(segment_info.name.len)));
1413 try writer.writeAll(segment_info.name);
1414 try leb.writeUleb128(writer, segment_info.alignment.toLog2Units());
1415 try leb.writeUleb128(writer, segment_info.flags);
1411 try appendLeb128(gpa, binary_bytes, @as(u32, @intCast(segment_info.name.len)));
1412 try binary_bytes.appendSlice(gpa, segment_info.name);
1413 try appendLeb128(gpa, binary_bytes, segment_info.alignment.toLog2Units());
1414 try appendLeb128(gpa, binary_bytes, segment_info.flags);
14161415 }
14171416
14181417 var buf: [5]u8 = undefined;
......@@ -1429,7 +1428,7 @@ fn uleb128size(x: u32) u32 {
14291428
14301429fn emitTagNameTable(
14311430 gpa: Allocator,
1432 code: *std.ArrayListUnmanaged(u8),
1431 code: *ArrayList(u8),
14331432 tag_name_offs: []const u32,
14341433 tag_name_bytes: []const u8,
14351434 base: u32,
......@@ -1604,7 +1603,7 @@ fn reloc_leb_type(code: []u8, index: FuncTypeIndex) void {
16041603 leb.writeUnsignedFixed(5, code[0..5], @intFromEnum(index));
16051604}
16061605
1607fn emitCallCtorsFunction(wasm: *const Wasm, binary_bytes: *std.ArrayListUnmanaged(u8)) Allocator.Error!void {
1606fn emitCallCtorsFunction(wasm: *const Wasm, binary_bytes: *ArrayList(u8)) Allocator.Error!void {
16081607 const gpa = wasm.base.comp.gpa;
16091608
16101609 try binary_bytes.ensureUnusedCapacity(gpa, 5 + 1);
......@@ -1631,7 +1630,7 @@ fn emitCallCtorsFunction(wasm: *const Wasm, binary_bytes: *std.ArrayListUnmanage
16311630
16321631fn emitInitMemoryFunction(
16331632 wasm: *const Wasm,
1634 binary_bytes: *std.ArrayListUnmanaged(u8),
1633 binary_bytes: *ArrayList(u8),
16351634 virtual_addrs: *const VirtualAddrs,
16361635) Allocator.Error!void {
16371636 const comp = wasm.base.comp;
......@@ -1734,7 +1733,7 @@ fn emitInitMemoryFunction(
17341733 // notify any waiters for segment initialization completion
17351734 appendReservedI32Const(binary_bytes, flag_address);
17361735 binary_bytes.appendAssumeCapacity(@intFromEnum(std.wasm.Opcode.i32_const));
1737 leb.writeIleb128(binary_bytes.fixedWriter(), @as(i32, -1)) catch unreachable; // number of waiters
1736 appendReservedLeb128(binary_bytes, @as(i32, -1)); // number of waiters
17381737 binary_bytes.appendAssumeCapacity(@intFromEnum(std.wasm.Opcode.atomics_prefix));
17391738 appendReservedUleb32(binary_bytes, @intFromEnum(std.wasm.AtomicsOpcode.memory_atomic_notify));
17401739 appendReservedUleb32(binary_bytes, @as(u32, 2)); // alignment
......@@ -1750,7 +1749,7 @@ fn emitInitMemoryFunction(
17501749 appendReservedI32Const(binary_bytes, flag_address);
17511750 appendReservedI32Const(binary_bytes, 1); // expected flag value
17521751 binary_bytes.appendAssumeCapacity(@intFromEnum(std.wasm.Opcode.i64_const));
1753 leb.writeIleb128(binary_bytes.fixedWriter(), @as(i64, -1)) catch unreachable; // timeout
1752 appendReservedLeb128(binary_bytes, @as(i64, -1)); // timeout
17541753 binary_bytes.appendAssumeCapacity(@intFromEnum(std.wasm.Opcode.atomics_prefix));
17551754 appendReservedUleb32(binary_bytes, @intFromEnum(std.wasm.AtomicsOpcode.memory_atomic_wait32));
17561755 appendReservedUleb32(binary_bytes, @as(u32, 2)); // alignment
......@@ -1779,7 +1778,7 @@ fn emitInitMemoryFunction(
17791778 binary_bytes.appendAssumeCapacity(@intFromEnum(std.wasm.Opcode.end));
17801779}
17811780
1782fn emitInitTlsFunction(wasm: *const Wasm, bytes: *std.ArrayListUnmanaged(u8)) Allocator.Error!void {
1781fn emitInitTlsFunction(wasm: *const Wasm, bytes: *ArrayList(u8)) Allocator.Error!void {
17831782 const comp = wasm.base.comp;
17841783 const gpa = comp.gpa;
17851784
......@@ -1840,14 +1839,14 @@ fn emitInitTlsFunction(wasm: *const Wasm, bytes: *std.ArrayListUnmanaged(u8)) Al
18401839 bytes.appendAssumeCapacity(@intFromEnum(std.wasm.Opcode.end));
18411840}
18421841
1843fn emitStartSection(gpa: Allocator, bytes: *std.ArrayListUnmanaged(u8), i: Wasm.OutputFunctionIndex) !void {
1842fn emitStartSection(gpa: Allocator, bytes: *ArrayList(u8), i: Wasm.OutputFunctionIndex) !void {
18441843 const header_offset = try reserveVecSectionHeader(gpa, bytes);
18451844 replaceVecSectionHeader(bytes, header_offset, .start, @intFromEnum(i));
18461845}
18471846
18481847fn emitTagNameFunction(
18491848 wasm: *Wasm,
1850 code: *std.ArrayListUnmanaged(u8),
1849 code: *ArrayList(u8),
18511850 table_base_addr: u32,
18521851 table_index: u32,
18531852 enum_type_ip: InternPool.Index,
......@@ -1959,22 +1958,34 @@ fn emitTagNameFunction(
19591958}
19601959
19611960/// Writes an unsigned 32-bit integer as a LEB128-encoded 'i32.const' value.
1962fn appendReservedI32Const(bytes: *std.ArrayListUnmanaged(u8), val: u32) void {
1961fn appendReservedI32Const(bytes: *ArrayList(u8), val: u32) void {
19631962 bytes.appendAssumeCapacity(@intFromEnum(std.wasm.Opcode.i32_const));
1964 leb.writeIleb128(bytes.fixedWriter(), @as(i32, @bitCast(val))) catch unreachable;
1963 var w: std.Io.Writer = .fromArrayList(bytes);
1964 defer bytes.* = w.toArrayList();
1965 return w.writeSleb128(val) catch |err| switch (err) {
1966 error.WriteFailed => unreachable,
1967 };
19651968}
19661969
19671970/// Writes an unsigned 64-bit integer as a LEB128-encoded 'i64.const' value.
1968fn appendReservedI64Const(bytes: *std.ArrayListUnmanaged(u8), val: u64) void {
1971fn appendReservedI64Const(bytes: *ArrayList(u8), val: u64) void {
19691972 bytes.appendAssumeCapacity(@intFromEnum(std.wasm.Opcode.i64_const));
1970 leb.writeIleb128(bytes.fixedWriter(), @as(i64, @bitCast(val))) catch unreachable;
1973 var w: std.Io.Writer = .fromArrayList(bytes);
1974 defer bytes.* = w.toArrayList();
1975 return w.writeSleb128(val) catch |err| switch (err) {
1976 error.WriteFailed => unreachable,
1977 };
19711978}
19721979
1973fn appendReservedUleb32(bytes: *std.ArrayListUnmanaged(u8), val: u32) void {
1974 leb.writeUleb128(bytes.fixedWriter(), val) catch unreachable;
1980fn appendReservedUleb32(bytes: *ArrayList(u8), val: u32) void {
1981 var w: std.Io.Writer = .fromArrayList(bytes);
1982 defer bytes.* = w.toArrayList();
1983 return w.writeUleb128(val) catch |err| switch (err) {
1984 error.WriteFailed => unreachable,
1985 };
19751986}
19761987
1977fn appendGlobal(gpa: Allocator, bytes: *std.ArrayListUnmanaged(u8), mutable: u8, val: u32) Allocator.Error!void {
1988fn appendGlobal(gpa: Allocator, bytes: *ArrayList(u8), mutable: u8, val: u32) Allocator.Error!void {
19781989 try bytes.ensureUnusedCapacity(gpa, 9);
19791990 bytes.appendAssumeCapacity(@intFromEnum(std.wasm.Valtype.i32));
19801991 bytes.appendAssumeCapacity(mutable);
......@@ -1982,3 +1993,19 @@ fn appendGlobal(gpa: Allocator, bytes: *std.ArrayListUnmanaged(u8), mutable: u8,
19821993 appendReservedUleb32(bytes, val);
19831994 bytes.appendAssumeCapacity(@intFromEnum(std.wasm.Opcode.end));
19841995}
1996
1997fn appendLeb128(gpa: Allocator, bytes: *ArrayList(u8), value: anytype) Allocator.Error!void {
1998 var aw: std.Io.Writer.Allocating = .fromArrayList(gpa, bytes);
1999 defer bytes.* = aw.toArrayList();
2000 return aw.writer.writeLeb128(value) catch |err| switch (err) {
2001 error.WriteFailed => return error.OutOfMemory,
2002 };
2003}
2004
2005fn appendReservedLeb128(bytes: *ArrayList(u8), value: anytype) void {
2006 var w: std.Io.Writer = .fromArrayList(bytes);
2007 defer bytes.* = w.toArrayList();
2008 return w.writeLeb128(value) catch |err| switch (err) {
2009 error.WriteFailed => unreachable,
2010 };
2011}
src/link/riscv.zig+14-15
......@@ -9,29 +9,28 @@ pub fn writeSetSub6(comptime op: enum { set, sub }, code: *[1]u8, addend: anytyp
99 mem.writeInt(u8, code, value, .little);
1010}
1111
12pub fn writeSetSubUleb(comptime op: enum { set, sub }, stream: *std.io.FixedBufferStream([]u8), addend: i64) !void {
13 switch (op) {
14 .set => try overwriteUleb(stream, @intCast(addend)),
15 .sub => {
16 const position = try stream.getPos();
17 const value: u64 = try std.leb.readUleb128(u64, stream.reader());
18 try stream.seekTo(position);
19 try overwriteUleb(stream, value -% @as(u64, @intCast(addend)));
20 },
21 }
12pub fn writeSubUleb(code: []u8, addend: i64) void {
13 var reader: std.Io.Reader = .fixed(code);
14 const value = reader.takeLeb128(u64) catch unreachable;
15 overwriteUleb(code, value -% @as(u64, @intCast(addend)));
16}
17
18pub fn writeSetUleb(code: []u8, addend: i64) void {
19 overwriteUleb(code, @intCast(addend));
2220}
2321
24fn overwriteUleb(stream: *std.io.FixedBufferStream([]u8), addend: u64) !void {
22fn overwriteUleb(code: []u8, addend: u64) void {
2523 var value: u64 = addend;
26 const writer = stream.writer();
24 var i: usize = 0;
2725
2826 while (true) {
29 const byte = stream.buffer[stream.pos];
27 const byte = code[i];
3028 if (byte & 0x80 == 0) break;
31 try writer.writeByte(0x80 | @as(u8, @truncate(value & 0x7f)));
29 code[i] = 0x80 | @as(u8, @truncate(value & 0x7f));
30 i += 1;
3231 value >>= 7;
3332 }
34 stream.buffer[stream.pos] = @truncate(value & 0x7f);
33 code[i] = @truncate(value & 0x7f);
3534}
3635
3736pub fn writeAddend(
src/main.zig+2-2
......@@ -4230,7 +4230,7 @@ fn serveUpdateResults(s: *Server, comp: *Compilation) !void {
42304230 const decl_name = zir.nullTerminatedString(zir.getDeclaration(resolved.inst).name);
42314231
42324232 const gop = try files.getOrPut(gpa, resolved.file);
4233 if (!gop.found_existing) try file_name_bytes.writer(gpa).print("{f}\x00", .{file.path.fmt(comp)});
4233 if (!gop.found_existing) try file_name_bytes.print(gpa, "{f}\x00", .{file.path.fmt(comp)});
42344234
42354235 const codegen_ns = tr.decl_codegen_ns.get(tracked_inst) orelse 0;
42364236 const link_ns = tr.decl_link_ns.get(tracked_inst) orelse 0;
......@@ -7451,7 +7451,7 @@ const Templates = struct {
74517451 i += "_NAME".len;
74527452 continue;
74537453 } else if (std.mem.startsWith(u8, contents[i + 1 ..], "FINGERPRINT")) {
7454 try templates.buffer.writer().print("0x{x}", .{fingerprint.int()});
7454 try templates.buffer.print("0x{x}", .{fingerprint.int()});
74557455 i += "_FINGERPRINT".len;
74567456 continue;
74577457 } else if (std.mem.startsWith(u8, contents[i + 1 ..], "ZIGVER")) {
test/behavior/packed-struct.zig-11
......@@ -1075,17 +1075,6 @@ test "assigning packed struct inside another packed struct" {
10751075 try expect(S.mem.padding == 0);
10761076}
10771077
1078test "packed struct used as part of anon decl name" {
1079 if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO
1080 if (builtin.zig_backend == .stage2_sparc64) return error.SkipZigTest; // TODO
1081 if (builtin.zig_backend == .stage2_spirv) return error.SkipZigTest;
1082
1083 const S = packed struct { a: u0 = 0 };
1084 var a: u8 = 0;
1085 _ = &a;
1086 try std.io.null_writer.print("\n{} {}\n", .{ a, S{} });
1087}
1088
10891078test "packed struct acts as a namespace" {
10901079 if (builtin.zig_backend == .stage2_sparc64) return error.SkipZigTest; // TODO
10911080
test/behavior/var_args.zig+21-14
......@@ -200,35 +200,42 @@ test "variadic functions" {
200200 if (builtin.cpu.arch.isSPARC() and builtin.zig_backend == .stage2_llvm) return error.SkipZigTest; // https://github.com/ziglang/zig/issues/23718
201201
202202 const S = struct {
203 fn printf(list_ptr: *std.array_list.Managed(u8), format: [*:0]const u8, ...) callconv(.c) void {
203 fn printf(buffer: [*]u8, format: [*:0]const u8, ...) callconv(.c) void {
204204 var ap = @cVaStart();
205205 defer @cVaEnd(&ap);
206 vprintf(list_ptr, format, &ap);
206 vprintf(buffer, format, &ap);
207207 }
208208
209 fn vprintf(
210 list: *std.array_list.Managed(u8),
211 format: [*:0]const u8,
212 ap: *std.builtin.VaList,
213 ) callconv(.c) void {
214 for (std.mem.span(format)) |c| switch (c) {
209 fn vprintf(buffer: [*]u8, format: [*:0]const u8, ap: *std.builtin.VaList) callconv(.c) void {
210 var i: usize = 0;
211 for (format[0..3]) |byte| switch (byte) {
215212 's' => {
216213 const arg = @cVaArg(ap, [*:0]const u8);
217 list.writer().print("{s}", .{arg}) catch return;
214 buffer[i..][0..5].* = arg[0..5].*;
215 i += 5;
218216 },
219217 'd' => {
220218 const arg = @cVaArg(ap, c_int);
221 list.writer().print("{d}", .{arg}) catch return;
219 switch (arg) {
220 1 => {
221 buffer[i] = '1';
222 i += 1;
223 },
224 5 => {
225 buffer[i] = '5';
226 i += 1;
227 },
228 else => unreachable,
229 }
222230 },
223231 else => unreachable,
224232 };
225233 }
226234 };
227235
228 var list = std.array_list.Managed(u8).init(std.testing.allocator);
229 defer list.deinit();
230 S.printf(&list, "dsd", @as(c_int, 1), @as([*:0]const u8, "hello"), @as(c_int, 5));
231 try std.testing.expectEqualStrings("1hello5", list.items);
236 var buffer: [7]u8 = undefined;
237 S.printf(&buffer, "dsd", @as(c_int, 1), @as([*:0]const u8, "hello"), @as(c_int, 5));
238 try expect(std.mem.eql(u8, &buffer, "1hello5"));
232239}
233240
234241test "copy VaList" {
test/standalone/run_output_paths/create_file.zig+2-1
......@@ -10,7 +10,8 @@ pub fn main() !void {
1010 dir_name, .{});
1111 const file_name = args.next().?;
1212 const file = try dir.createFile(file_name, .{});
13 try file.deprecatedWriter().print(
13 var file_writer = file.writer(&.{});
14 try file_writer.interface.print(
1415 \\{s}
1516 \\{s}
1617 \\Hello, world!
tools/docgen.zig+21-21
......@@ -1,6 +1,5 @@
11const std = @import("std");
22const builtin = @import("builtin");
3const io = std.io;
43const fs = std.fs;
54const process = std.process;
65const Progress = std.Progress;
......@@ -8,8 +7,10 @@ const print = std.debug.print;
87const mem = std.mem;
98const testing = std.testing;
109const Allocator = std.mem.Allocator;
10const ArrayList = std.ArrayList;
1111const getExternalExecutor = std.zig.system.getExternalExecutor;
1212const fatal = std.process.fatal;
13const Writer = std.Io.Writer;
1314
1415const max_doc_file_size = 10 * 1024 * 1024;
1516
......@@ -344,10 +345,10 @@ fn genToc(allocator: Allocator, tokenizer: *Tokenizer) !Toc {
344345 var last_action: Action = .open;
345346 var last_columns: ?u8 = null;
346347
347 var toc_buf = std.array_list.Managed(u8).init(allocator);
348 var toc_buf: Writer.Allocating = .init(allocator);
348349 defer toc_buf.deinit();
349350
350 var toc = toc_buf.writer();
351 const toc = &toc_buf.writer;
351352
352353 var nodes = std.array_list.Managed(Node).init(allocator);
353354 defer nodes.deinit();
......@@ -422,7 +423,7 @@ fn genToc(allocator: Allocator, tokenizer: *Tokenizer) !Toc {
422423 }
423424 if (last_action == .open) {
424425 try toc.writeByte('\n');
425 try toc.writeByteNTimes(' ', header_stack_size * 4);
426 try toc.splatByteAll(' ', header_stack_size * 4);
426427 if (last_columns) |n| {
427428 try toc.print("<ul style=\"columns: {d}\">\n", .{n});
428429 } else {
......@@ -432,7 +433,7 @@ fn genToc(allocator: Allocator, tokenizer: *Tokenizer) !Toc {
432433 last_action = .open;
433434 }
434435 last_columns = columns;
435 try toc.writeByteNTimes(' ', 4 + header_stack_size * 4);
436 try toc.splatByteAll(' ', 4 + header_stack_size * 4);
436437 try toc.print("<li><a id=\"toc-{s}\" href=\"#{s}\">{s}</a>", .{ urlized, urlized, content });
437438 } else if (mem.eql(u8, tag_name, "header_close")) {
438439 if (header_stack_size == 0) {
......@@ -442,7 +443,7 @@ fn genToc(allocator: Allocator, tokenizer: *Tokenizer) !Toc {
442443 _ = try eatToken(tokenizer, .bracket_close);
443444
444445 if (last_action == .close) {
445 try toc.writeByteNTimes(' ', 8 + header_stack_size * 4);
446 try toc.splatByteAll(' ', 8 + header_stack_size * 4);
446447 try toc.writeAll("</ul></li>\n");
447448 } else {
448449 try toc.writeAll("</li>\n");
......@@ -591,30 +592,29 @@ fn genToc(allocator: Allocator, tokenizer: *Tokenizer) !Toc {
591592 }
592593 }
593594
594 return Toc{
595 return .{
595596 .nodes = try nodes.toOwnedSlice(),
596597 .toc = try toc_buf.toOwnedSlice(),
597598 .urls = urls,
598599 };
599600}
600601
601fn urlize(allocator: Allocator, input: []const u8) ![]u8 {
602 var buf = std.array_list.Managed(u8).init(allocator);
603 defer buf.deinit();
602fn urlize(gpa: Allocator, input: []const u8) ![]u8 {
603 var buf: ArrayList(u8) = .empty;
604 defer buf.deinit(gpa);
604605
605 const out = buf.writer();
606606 for (input) |c| {
607607 switch (c) {
608608 'a'...'z', 'A'...'Z', '_', '-', '0'...'9' => {
609 try out.writeByte(c);
609 try buf.append(gpa, c);
610610 },
611611 ' ' => {
612 try out.writeByte('-');
612 try buf.append(gpa, '-');
613613 },
614614 else => {},
615615 }
616616 }
617 return try buf.toOwnedSlice();
617 return try buf.toOwnedSlice(gpa);
618618}
619619
620620fn escapeHtml(allocator: Allocator, input: []const u8) ![]u8 {
......@@ -626,7 +626,7 @@ fn escapeHtml(allocator: Allocator, input: []const u8) ![]u8 {
626626 return try buf.toOwnedSlice();
627627}
628628
629fn writeEscaped(out: anytype, input: []const u8) !void {
629fn writeEscaped(out: *Writer, input: []const u8) !void {
630630 for (input) |c| {
631631 try switch (c) {
632632 '&' => out.writeAll("&amp;"),
......@@ -662,14 +662,14 @@ fn isType(name: []const u8) bool {
662662 return false;
663663}
664664
665fn writeEscapedLines(out: anytype, text: []const u8) !void {
665fn writeEscapedLines(out: *Writer, text: []const u8) !void {
666666 return writeEscaped(out, text);
667667}
668668
669669fn tokenizeAndPrintRaw(
670670 allocator: Allocator,
671671 docgen_tokenizer: *Tokenizer,
672 out: anytype,
672 out: *Writer,
673673 source_token: Token,
674674 raw_src: []const u8,
675675) !void {
......@@ -907,14 +907,14 @@ fn tokenizeAndPrintRaw(
907907fn tokenizeAndPrint(
908908 allocator: Allocator,
909909 docgen_tokenizer: *Tokenizer,
910 out: anytype,
910 out: *Writer,
911911 source_token: Token,
912912) !void {
913913 const raw_src = docgen_tokenizer.buffer[source_token.start..source_token.end];
914914 return tokenizeAndPrintRaw(allocator, docgen_tokenizer, out, source_token, raw_src);
915915}
916916
917fn printSourceBlock(allocator: Allocator, docgen_tokenizer: *Tokenizer, out: anytype, syntax_block: SyntaxBlock) !void {
917fn printSourceBlock(allocator: Allocator, docgen_tokenizer: *Tokenizer, out: *Writer, syntax_block: SyntaxBlock) !void {
918918 const source_type = @tagName(syntax_block.source_type);
919919
920920 try out.print("<figure><figcaption class=\"{s}-cap\"><cite class=\"file\">{s}</cite></figcaption><pre>", .{ source_type, syntax_block.name });
......@@ -932,7 +932,7 @@ fn printSourceBlock(allocator: Allocator, docgen_tokenizer: *Tokenizer, out: any
932932 try out.writeAll("</pre></figure>");
933933}
934934
935fn printShell(out: anytype, shell_content: []const u8, escape: bool) !void {
935fn printShell(out: *Writer, shell_content: []const u8, escape: bool) !void {
936936 const trimmed_shell_content = mem.trim(u8, shell_content, " \r\n");
937937 try out.writeAll("<figure><figcaption class=\"shell-cap\">Shell</figcaption><pre><samp>");
938938 var cmd_cont: bool = false;
......@@ -984,7 +984,7 @@ fn genHtml(
984984 tokenizer: *Tokenizer,
985985 toc: *Toc,
986986 code_dir: std.fs.Dir,
987 out: anytype,
987 out: *Writer,
988988) !void {
989989 for (toc.nodes) |node| {
990990 switch (node) {
tools/doctest.zig+60-64
......@@ -7,6 +7,7 @@ const process = std.process;
77const Allocator = std.mem.Allocator;
88const testing = std.testing;
99const getExternalExecutor = std.zig.system.getExternalExecutor;
10const Writer = std.Io.Writer;
1011
1112const max_doc_file_size = 10 * 1024 * 1024;
1213
......@@ -108,7 +109,7 @@ pub fn main() !void {
108109
109110fn printOutput(
110111 arena: Allocator,
111 out: anytype,
112 out: *Writer,
112113 code: Code,
113114 /// Relative to this process' cwd.
114115 tmp_dir_path: []const u8,
......@@ -126,9 +127,9 @@ fn printOutput(
126127 const obj_ext = builtin.object_format.fileExt(builtin.cpu.arch);
127128 const print = std.debug.print;
128129
129 var shell_buffer = std.array_list.Managed(u8).init(arena);
130 var shell_buffer: std.Io.Writer.Allocating = .init(arena);
130131 defer shell_buffer.deinit();
131 var shell_out = shell_buffer.writer();
132 const shell_out = &shell_buffer.writer;
132133
133134 const code_name = std.fs.path.stem(input_path);
134135
......@@ -599,7 +600,7 @@ fn printOutput(
599600 }
600601
601602 if (!code.just_check_syntax) {
602 try printShell(out, shell_buffer.items, false);
603 try printShell(out, shell_buffer.written(), false);
603604 }
604605}
605606
......@@ -610,7 +611,7 @@ fn dumpArgs(args: []const []const u8) void {
610611 std.debug.print("\n", .{});
611612}
612613
613fn printSourceBlock(arena: Allocator, out: anytype, source_bytes: []const u8, name: []const u8) !void {
614fn printSourceBlock(arena: Allocator, out: *Writer, source_bytes: []const u8, name: []const u8) !void {
614615 try out.print("<figure><figcaption class=\"{s}-cap\"><cite class=\"file\">{s}</cite></figcaption><pre>", .{
615616 "zig", name,
616617 });
......@@ -618,7 +619,7 @@ fn printSourceBlock(arena: Allocator, out: anytype, source_bytes: []const u8, na
618619 try out.writeAll("</pre></figure>");
619620}
620621
621fn tokenizeAndPrint(arena: Allocator, out: anytype, raw_src: []const u8) !void {
622fn tokenizeAndPrint(arena: Allocator, out: *Writer, raw_src: []const u8) !void {
622623 const src_non_terminated = mem.trim(u8, raw_src, " \r\n");
623624 const src = try arena.dupeZ(u8, src_non_terminated);
624625
......@@ -846,7 +847,7 @@ fn tokenizeAndPrint(arena: Allocator, out: anytype, raw_src: []const u8) !void {
846847 try out.writeAll("</code>");
847848}
848849
849fn writeEscapedLines(out: anytype, text: []const u8) !void {
850fn writeEscapedLines(out: *Writer, text: []const u8) !void {
850851 return writeEscaped(out, text);
851852}
852853
......@@ -974,25 +975,21 @@ fn skipPrefix(line: []const u8) []const u8 {
974975 return line[3..];
975976}
976977
977fn escapeHtml(allocator: Allocator, input: []const u8) ![]u8 {
978 var buf = std.array_list.Managed(u8).init(allocator);
979 defer buf.deinit();
980
981 const out = buf.writer();
982 try writeEscaped(out, input);
983 return try buf.toOwnedSlice();
978fn escapeHtml(gpa: Allocator, input: []const u8) ![]u8 {
979 var allocating: Writer.Allocating = .init(gpa);
980 defer allocating.deinit();
981 try writeEscaped(&allocating.writer, input);
982 return allocating.toOwnedSlice();
984983}
985984
986fn writeEscaped(out: anytype, input: []const u8) !void {
987 for (input) |c| {
988 try switch (c) {
989 '&' => out.writeAll("&amp;"),
990 '<' => out.writeAll("&lt;"),
991 '>' => out.writeAll("&gt;"),
992 '"' => out.writeAll("&quot;"),
993 else => out.writeByte(c),
994 };
995 }
985fn writeEscaped(w: *Writer, input: []const u8) !void {
986 for (input) |c| try switch (c) {
987 '&' => w.writeAll("&amp;"),
988 '<' => w.writeAll("&lt;"),
989 '>' => w.writeAll("&gt;"),
990 '"' => w.writeAll("&quot;"),
991 else => w.writeByte(c),
992 };
996993}
997994
998995fn termColor(allocator: Allocator, input: []const u8) ![]u8 {
......@@ -1014,7 +1011,6 @@ fn termColor(allocator: Allocator, input: []const u8) ![]u8 {
10141011 var buf = std.array_list.Managed(u8).init(allocator);
10151012 defer buf.deinit();
10161013
1017 var out = buf.writer();
10181014 var sgr_param_start_index: usize = undefined;
10191015 var sgr_num: u8 = undefined;
10201016 var sgr_color: u8 = undefined;
......@@ -1037,10 +1033,10 @@ fn termColor(allocator: Allocator, input: []const u8) ![]u8 {
10371033 .start => switch (c) {
10381034 '\x1b' => state = .escape,
10391035 '\n' => {
1040 try out.writeByte(c);
1036 try buf.append(c);
10411037 last_new_line = buf.items.len;
10421038 },
1043 else => try out.writeByte(c),
1039 else => try buf.append(c),
10441040 },
10451041 .escape => switch (c) {
10461042 '[' => state = .lbracket,
......@@ -1101,16 +1097,16 @@ fn termColor(allocator: Allocator, input: []const u8) ![]u8 {
11011097 'm' => {
11021098 state = .start;
11031099 while (open_span_count != 0) : (open_span_count -= 1) {
1104 try out.writeAll("</span>");
1100 try buf.appendSlice("</span>");
11051101 }
11061102 if (sgr_num == 0) {
11071103 if (sgr_color != 0) return error.UnsupportedColor;
11081104 continue;
11091105 }
11101106 if (sgr_color != 0) {
1111 try out.print("<span class=\"sgr-{d}_{d}m\">", .{ sgr_color, sgr_num });
1107 try buf.print("<span class=\"sgr-{d}_{d}m\">", .{ sgr_color, sgr_num });
11121108 } else {
1113 try out.print("<span class=\"sgr-{d}m\">", .{sgr_num});
1109 try buf.print("<span class=\"sgr-{d}m\">", .{sgr_num});
11141110 }
11151111 open_span_count += 1;
11161112 },
......@@ -1156,7 +1152,7 @@ fn run(
11561152 return result;
11571153}
11581154
1159fn printShell(out: anytype, shell_content: []const u8, escape: bool) !void {
1155fn printShell(out: *Writer, shell_content: []const u8, escape: bool) !void {
11601156 const trimmed_shell_content = mem.trim(u8, shell_content, " \r\n");
11611157 try out.writeAll("<figure><figcaption class=\"shell-cap\">Shell</figcaption><pre><samp>");
11621158 var cmd_cont: bool = false;
......@@ -1401,11 +1397,11 @@ test "printShell" {
14011397 \\</samp></pre></figure>
14021398 ;
14031399
1404 var buffer = std.array_list.Managed(u8).init(test_allocator);
1400 var buffer: std.Io.Writer.Allocating = .init(test_allocator);
14051401 defer buffer.deinit();
14061402
1407 try printShell(buffer.writer(), shell_out, false);
1408 try testing.expectEqualSlices(u8, expected, buffer.items);
1403 try printShell(&buffer.writer, shell_out, false);
1404 try testing.expectEqualSlices(u8, expected, buffer.written());
14091405 }
14101406 {
14111407 const shell_out =
......@@ -1418,11 +1414,11 @@ test "printShell" {
14181414 \\</samp></pre></figure>
14191415 ;
14201416
1421 var buffer = std.array_list.Managed(u8).init(test_allocator);
1417 var buffer: std.Io.Writer.Allocating = .init(test_allocator);
14221418 defer buffer.deinit();
14231419
1424 try printShell(buffer.writer(), shell_out, false);
1425 try testing.expectEqualSlices(u8, expected, buffer.items);
1420 try printShell(&buffer.writer, shell_out, false);
1421 try testing.expectEqualSlices(u8, expected, buffer.written());
14261422 }
14271423 {
14281424 const shell_out = "$ zig build test.zig\r\nbuild output\r\n";
......@@ -1432,11 +1428,11 @@ test "printShell" {
14321428 \\</samp></pre></figure>
14331429 ;
14341430
1435 var buffer = std.array_list.Managed(u8).init(test_allocator);
1431 var buffer: std.Io.Writer.Allocating = .init(test_allocator);
14361432 defer buffer.deinit();
14371433
1438 try printShell(buffer.writer(), shell_out, false);
1439 try testing.expectEqualSlices(u8, expected, buffer.items);
1434 try printShell(&buffer.writer, shell_out, false);
1435 try testing.expectEqualSlices(u8, expected, buffer.written());
14401436 }
14411437 {
14421438 const shell_out =
......@@ -1451,11 +1447,11 @@ test "printShell" {
14511447 \\</samp></pre></figure>
14521448 ;
14531449
1454 var buffer = std.array_list.Managed(u8).init(test_allocator);
1450 var buffer: std.Io.Writer.Allocating = .init(test_allocator);
14551451 defer buffer.deinit();
14561452
1457 try printShell(buffer.writer(), shell_out, false);
1458 try testing.expectEqualSlices(u8, expected, buffer.items);
1453 try printShell(&buffer.writer, shell_out, false);
1454 try testing.expectEqualSlices(u8, expected, buffer.written());
14591455 }
14601456 {
14611457 const shell_out =
......@@ -1472,11 +1468,11 @@ test "printShell" {
14721468 \\</samp></pre></figure>
14731469 ;
14741470
1475 var buffer = std.array_list.Managed(u8).init(test_allocator);
1471 var buffer: std.Io.Writer.Allocating = .init(test_allocator);
14761472 defer buffer.deinit();
14771473
1478 try printShell(buffer.writer(), shell_out, false);
1479 try testing.expectEqualSlices(u8, expected, buffer.items);
1474 try printShell(&buffer.writer, shell_out, false);
1475 try testing.expectEqualSlices(u8, expected, buffer.written());
14801476 }
14811477 {
14821478 const shell_out =
......@@ -1491,11 +1487,11 @@ test "printShell" {
14911487 \\</samp></pre></figure>
14921488 ;
14931489
1494 var buffer = std.array_list.Managed(u8).init(test_allocator);
1490 var buffer: std.Io.Writer.Allocating = .init(test_allocator);
14951491 defer buffer.deinit();
14961492
1497 try printShell(buffer.writer(), shell_out, false);
1498 try testing.expectEqualSlices(u8, expected, buffer.items);
1493 try printShell(&buffer.writer, shell_out, false);
1494 try testing.expectEqualSlices(u8, expected, buffer.written());
14991495 }
15001496 {
15011497 const shell_out =
......@@ -1514,11 +1510,11 @@ test "printShell" {
15141510 \\</samp></pre></figure>
15151511 ;
15161512
1517 var buffer = std.array_list.Managed(u8).init(test_allocator);
1513 var buffer: std.Io.Writer.Allocating = .init(test_allocator);
15181514 defer buffer.deinit();
15191515
1520 try printShell(buffer.writer(), shell_out, false);
1521 try testing.expectEqualSlices(u8, expected, buffer.items);
1516 try printShell(&buffer.writer, shell_out, false);
1517 try testing.expectEqualSlices(u8, expected, buffer.written());
15221518 }
15231519 {
15241520 // intentional space after "--build-option1 \"
......@@ -1536,11 +1532,11 @@ test "printShell" {
15361532 \\</samp></pre></figure>
15371533 ;
15381534
1539 var buffer = std.array_list.Managed(u8).init(test_allocator);
1535 var buffer: std.Io.Writer.Allocating = .init(test_allocator);
15401536 defer buffer.deinit();
15411537
1542 try printShell(buffer.writer(), shell_out, false);
1543 try testing.expectEqualSlices(u8, expected, buffer.items);
1538 try printShell(&buffer.writer, shell_out, false);
1539 try testing.expectEqualSlices(u8, expected, buffer.written());
15441540 }
15451541 {
15461542 const shell_out =
......@@ -1553,11 +1549,11 @@ test "printShell" {
15531549 \\</samp></pre></figure>
15541550 ;
15551551
1556 var buffer = std.array_list.Managed(u8).init(test_allocator);
1552 var buffer: std.Io.Writer.Allocating = .init(test_allocator);
15571553 defer buffer.deinit();
15581554
1559 try printShell(buffer.writer(), shell_out, false);
1560 try testing.expectEqualSlices(u8, expected, buffer.items);
1555 try printShell(&buffer.writer, shell_out, false);
1556 try testing.expectEqualSlices(u8, expected, buffer.written());
15611557 }
15621558 {
15631559 const shell_out =
......@@ -1572,11 +1568,11 @@ test "printShell" {
15721568 \\</samp></pre></figure>
15731569 ;
15741570
1575 var buffer = std.array_list.Managed(u8).init(test_allocator);
1571 var buffer: std.Io.Writer.Allocating = .init(test_allocator);
15761572 defer buffer.deinit();
15771573
1578 try printShell(buffer.writer(), shell_out, false);
1579 try testing.expectEqualSlices(u8, expected, buffer.items);
1574 try printShell(&buffer.writer, shell_out, false);
1575 try testing.expectEqualSlices(u8, expected, buffer.written());
15801576 }
15811577 {
15821578 const shell_out =
......@@ -1587,10 +1583,10 @@ test "printShell" {
15871583 \\</samp></pre></figure>
15881584 ;
15891585
1590 var buffer = std.array_list.Managed(u8).init(test_allocator);
1586 var buffer: std.Io.Writer.Allocating = .init(test_allocator);
15911587 defer buffer.deinit();
15921588
1593 try printShell(buffer.writer(), shell_out, false);
1594 try testing.expectEqualSlices(u8, expected, buffer.items);
1589 try printShell(&buffer.writer, shell_out, false);
1590 try testing.expectEqualSlices(u8, expected, buffer.written());
15951591 }
15961592}
tools/gen_outline_atomics.zig+1-1
......@@ -49,7 +49,7 @@ pub fn main() !void {
4949 @tagName(op), n.toBytes(), @tagName(order),
5050 });
5151 try writeFunction(arena, w, name, op, n, order);
52 try footer.writer().print(" @export(&{s}, .{{ .name = \"{s}\", .linkage = common.linkage, .visibility = common.visibility }});\n", .{
52 try footer.print(" @export(&{s}, .{{ .name = \"{s}\", .linkage = common.linkage, .visibility = common.visibility }});\n", .{
5353 name, name,
5454 });
5555 }
tools/gen_spirv_spec.zig+8-11
......@@ -82,13 +82,11 @@ pub fn main() !void {
8282
8383 try readExtRegistry(&exts, std.fs.cwd(), args[2]);
8484
85 const output_buf = try allocator.alloc(u8, 1024 * 1024);
86 var fbs = std.io.fixedBufferStream(output_buf);
87 var adapter = fbs.writer().adaptToNewApi(&.{});
88 const w = &adapter.new_interface;
89 try render(w, core_spec, exts.items);
90 var output: [:0]u8 = @ptrCast(fbs.getWritten());
91 output[output.len] = 0;
85 var allocating: std.Io.Writer.Allocating = .init(allocator);
86 defer allocating.deinit();
87 try render(&allocating.writer, core_spec, exts.items);
88 try allocating.writer.writeByte(0);
89 const output = allocating.written()[0 .. allocating.written().len - 1 :0];
9290
9391 var tree = try std.zig.Ast.parse(allocator, output, .zig);
9492 var color: std.zig.Color = .on;
......@@ -429,10 +427,9 @@ fn renderClass(writer: *std.io.Writer, instructions: []const Instruction) !void
429427const Formatter = struct {
430428 data: []const u8,
431429
432 fn format(f: Formatter, writer: *std.io.Writer) std.io.Writer.Error!void {
430 fn format(f: Formatter, writer: *std.Io.Writer) std.io.Writer.Error!void {
433431 var id_buf: [128]u8 = undefined;
434 var fbs = std.io.fixedBufferStream(&id_buf);
435 const fw = fbs.writer();
432 var fw: std.Io.Writer = .fixed(&id_buf);
436433 for (f.data, 0..) |c, i| {
437434 switch (c) {
438435 '-', '_', '.', '~', ' ' => fw.writeByte('_') catch return error.WriteFailed,
......@@ -452,7 +449,7 @@ const Formatter = struct {
452449 }
453450
454451 // make sure that this won't clobber with zig keywords
455 try writer.print("{f}", .{std.zig.fmtId(fbs.getWritten())});
452 try writer.print("{f}", .{std.zig.fmtId(fw.buffered())});
456453 }
457454};
458455
tools/migrate_langref.zig+22-18
......@@ -382,46 +382,50 @@ fn walk(arena: Allocator, tokenizer: *Tokenizer, out_dir: std.fs.Dir, w: anytype
382382 fatal("unable to create file '{s}': {s}", .{ name, @errorName(err) });
383383 };
384384 defer file.close();
385 var file_buffer: [1024]u8 = undefined;
386 var file_writer = file.writer(&file_buffer);
387 const code = &file_writer.interface;
385388
386389 const source = tokenizer.buffer[source_token.start..source_token.end];
387 try file.writeAll(std.mem.trim(u8, source[1..], " \t\r\n"));
388 try file.writeAll("\n\n");
390 try code.writeAll(std.mem.trim(u8, source[1..], " \t\r\n"));
391 try code.writeAll("\n\n");
389392
390393 if (just_check_syntax) {
391 try file.deprecatedWriter().print("// syntax\n", .{});
394 try code.print("// syntax\n", .{});
392395 } else switch (code_kind_id) {
393 .@"test" => try file.deprecatedWriter().print("// test\n", .{}),
394 .lib => try file.deprecatedWriter().print("// lib\n", .{}),
395 .test_error => |s| try file.deprecatedWriter().print("// test_error={s}\n", .{s}),
396 .test_safety => |s| try file.deprecatedWriter().print("// test_safety={s}\n", .{s}),
397 .exe => |s| try file.deprecatedWriter().print("// exe={s}\n", .{@tagName(s)}),
396 .@"test" => try code.print("// test\n", .{}),
397 .lib => try code.print("// lib\n", .{}),
398 .test_error => |s| try code.print("// test_error={s}\n", .{s}),
399 .test_safety => |s| try code.print("// test_safety={s}\n", .{s}),
400 .exe => |s| try code.print("// exe={s}\n", .{@tagName(s)}),
398401 .obj => |opt| if (opt) |s| {
399 try file.deprecatedWriter().print("// obj={s}\n", .{s});
402 try code.print("// obj={s}\n", .{s});
400403 } else {
401 try file.deprecatedWriter().print("// obj\n", .{});
404 try code.print("// obj\n", .{});
402405 },
403406 }
404407
405408 if (mode != .Debug)
406 try file.deprecatedWriter().print("// optimize={s}\n", .{@tagName(mode)});
409 try code.print("// optimize={s}\n", .{@tagName(mode)});
407410
408411 for (link_objects.items) |link_object| {
409 try file.deprecatedWriter().print("// link_object={s}\n", .{link_object});
412 try code.print("// link_object={s}\n", .{link_object});
410413 }
411414
412415 if (target_str) |s|
413 try file.deprecatedWriter().print("// target={s}\n", .{s});
416 try code.print("// target={s}\n", .{s});
414417
415 if (link_libc) try file.deprecatedWriter().print("// link_libc\n", .{});
416 if (disable_cache) try file.deprecatedWriter().print("// disable_cache\n", .{});
417 if (verbose_cimport) try file.deprecatedWriter().print("// verbose_cimport\n", .{});
418 if (link_libc) try code.print("// link_libc\n", .{});
419 if (disable_cache) try code.print("// disable_cache\n", .{});
420 if (verbose_cimport) try code.print("// verbose_cimport\n", .{});
418421
419422 if (link_mode) |m|
420 try file.deprecatedWriter().print("// link_mode={s}\n", .{@tagName(m)});
423 try code.print("// link_mode={s}\n", .{@tagName(m)});
421424
422425 for (additional_options.items) |o| {
423 try file.deprecatedWriter().print("// additional_option={s}\n", .{o});
426 try code.print("// additional_option={s}\n", .{o});
424427 }
428 try code.flush();
425429 try w.print("{{#code|{s}#}}\n", .{basename});
426430 } else {
427431 const close_bracket = while (true) {
tools/update_crc_catalog.zig+2-3
......@@ -88,10 +88,9 @@ pub fn main() anyerror!void {
8888 \\
8989 );
9090
91 var stream = std.io.fixedBufferStream(catalog_txt);
92 const reader = stream.reader();
91 var reader: std.Io.Reader = .fixed(catalog_txt);
9392
94 while (try reader.readUntilDelimiterOrEofAlloc(arena, '\n', std.math.maxInt(usize))) |line| {
93 while (try reader.takeDelimiter('\n')) |line| {
9594 if (line.len == 0 or line[0] == '#')
9695 continue;
9796