跳转到内容

std.zig.ErrorBundle

标准库Zig 0.17.1官方原文
源码std/zig/ErrorBundle.zig

第 1 行

为支持增量编译,错误存储在不同位置, 以便适时创建和销毁。此结构体 用于将不同位置的全部错误收集到 一个方便 API 用户使用的位置。

此数据结构具有一种特殊编码:如果两个数组均 为空,则表示没有错误。该编码的目的在于 使无错误这一常见情况无需堆分配。

字段

string_bytes: []const u8
extra: []const u32

此数组的首项为 ErrorMessageList。

std.zig.ErrorBundle.Allocator

别名

第 14 行

别名目标 std.mem.Allocator

std.zig.ErrorBundle.assert

别名

第 15 行

别名目标 std.debug.assert

std.zig.ErrorBundle.deinit

函数

第 89 行

pub fn deinit(eb: *ErrorBundle, gpa: Allocator) void

参数

std.zig.ErrorBundle.empty

常量

第 27 行

没有错误时使用的特殊编码。

ErrorBundle

std.zig.ErrorBundle.ErrorBundle

别名

第 9 行

别名目标 std.zig.ErrorBundle

std.zig.ErrorBundle.ErrorMessage

容器

第 70 行

尾随数据:

  • 对每个 notes_len 项存储一个 MessageIndex。

字段

msg: String
count: u32 = 1

通常为一,但冗余消息会使其增加。

src_loc: SourceLocationIndex = .none
notes_len: u32 = 0

std.zig.ErrorBundle.errorMessageCount

函数

第 95 行

pub fn errorMessageCount(eb: ErrorBundle) u32

参数

std.zig.ErrorBundle.ErrorMessageList

容器

第 44 行

每个长度值在起始处都有一个 MessageIndex。

字段

len: u32
start: u32
compile_log_text: OptionalString

空终止字符串索引。0 表示没有编译日志文本。

std.zig.ErrorBundle.extraData

类型函数

第 130 行

返回请求的数据,以及位于该对象尾部数据起点的 新索引。

fn extraData(eb: ErrorBundle, comptime T: type, index: usize) struct { data: T, end: usize }

参数

eb: ErrorBundle
T: type
index: usize

std.zig.ErrorBundle.getCompileLogOutput

函数

第 124 行

pub fn getCompileLogOutput(eb: ErrorBundle) [:0]const u8

参数

std.zig.ErrorBundle.getErrorMessage

函数

第 109 行

pub fn getErrorMessage(eb: ErrorBundle, index: MessageIndex) ErrorMessage

参数

std.zig.ErrorBundle.getErrorMessageList

函数

第 100 行

pub fn getErrorMessageList(eb: ErrorBundle) ErrorMessageList

参数

std.zig.ErrorBundle.getMessages

函数

第 104 行

pub fn getMessages(eb: ErrorBundle) []const MessageIndex

参数

std.zig.ErrorBundle.getNotes

函数

第 118 行

pub fn getNotes(eb: ErrorBundle, index: MessageIndex) []const MessageIndex

参数

std.zig.ErrorBundle.getSourceLocation

函数

第 113 行

pub fn getSourceLocation(eb: ErrorBundle, index: SourceLocationIndex) SourceLocation

参数

std.zig.ErrorBundle.Io

别名

第 12 行

别名目标 std.Io

std.zig.ErrorBundle.MessageIndex

容器

第 33 行

字段

_

std.zig.ErrorBundle.nullTerminatedString

函数

第 151 行

给定 string_bytes 中的索引,返回其中找到的空终止字符串。

pub fn nullTerminatedString(eb: ErrorBundle, index: String) [:0]const u8

参数

eb: ErrorBundle
index: String

std.zig.ErrorBundle.OptionalString

类型

第 24 行

string_bytes 中的索引,或 null。

std.zig.ErrorBundle.readAlloc

函数

第 200 行

pub fn readAlloc( r: *Io.Reader, gpa: Allocator, extra_len: u32, string_bytes_len: u32, ) Io.Reader.ReadAllocError!ErrorBundle

参数

r: *Io.Reader
gpa: Allocator
extra_len: u32
string_bytes_len: u32

错误

EndOfStream Error
OutOfMemory Error
ReadFailed Error

详细诊断参见 Reader 的实现。

std.zig.ErrorBundle.ReferenceTrace

容器

第 78 行

字段

decl_name: String

以 null 结尾的字符串索引。 但哨兵 ReferenceTrace 元素例外,此时:

  • 0 表示剩余引用被隐藏
  • 0 表示隐藏了 N 个引用

src_loc: SourceLocationIndex

SourceLocation 在 extra 中的索引 若为 0,则是哨兵 ReferenceTrace 元素。

std.zig.ErrorBundle.renderErrorMessage

函数

第 218 行

fn renderErrorMessage( eb: ErrorBundle, options: RenderOptions, err_msg_index: MessageIndex, t: Io.Terminal, kind: []const u8, color: Io.Terminal.Color, indent: usize, ) Io.Terminal.SetColorError!void

参数

eb: ErrorBundle
options: RenderOptions
err_msg_index: MessageIndex
t: Io.Terminal
kind: []const u8
color: Io.Terminal.Color
indent: usize

错误

Canceled Cancelable

调用方请求停止异步操作。

Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

WriteFailed Error

详细诊断信息见 Writer 实现。

std.zig.ErrorBundle.RenderOptions

容器

第 160 行

字段

include_reference_trace: bool = true
include_source_line: bool = true
include_log_text: bool = true

std.zig.ErrorBundle.renderToStderr

函数

第 168 行

pub fn renderToStderr(eb: ErrorBundle, io: Io, options: RenderOptions, color: std.zig.Color) RenderToStderrError!void

参数

eb: ErrorBundle
io: Io
options: RenderOptions
color: std.zig.Color

错误

AccessDenied Error

文件描述符没有写入所需的权限。

BrokenPipe Error

文件为未连接的套接字,或其读取端已关闭。

Canceled Cancelable

调用方请求停止异步操作。

DeviceBusy Error
DiskQuota Error
FileBusy Error
FileTooBig Error
InputOutput Error
LockViolation Error

进程无法访问文件,因为另一进程已锁定 文件的一部分。仅限 Windows。

NoDevice Error

写入设备期间,若设备在刷新之前或刷新途中断开,就会发生此错误:errno(6),没有此设备或地址。

NoSpaceLeft Error
NotOpenForWriting Error
PermissionDenied Error
SystemResources Error

内核内存不足,无法从 in_fd 读取。

Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

WouldBlock Error

已启用非阻塞模式,而此操作将阻塞。

std.zig.ErrorBundle.RenderToStderrError

错误集合

第 166 行

错误

AccessDenied Error

文件描述符没有写入所需的权限。

BrokenPipe Error

文件为未连接的套接字,或其读取端已关闭。

Canceled Cancelable

调用方请求停止异步操作。

DeviceBusy Error
DiskQuota Error
FileBusy Error
FileTooBig Error
InputOutput Error
LockViolation Error

进程无法访问文件,因为另一进程已锁定 文件的一部分。仅限 Windows。

NoDevice Error

写入设备期间,若设备在刷新之前或刷新途中断开,就会发生此错误:errno(6),没有此设备或地址。

NoSpaceLeft Error
NotOpenForWriting Error
PermissionDenied Error
SystemResources Error

内核内存不足,无法从 in_fd 读取。

Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

WouldBlock Error

已启用非阻塞模式,而此操作将阻塞。

std.zig.ErrorBundle.renderToTerminal

函数

第 185 行

pub fn renderToTerminal(eb: ErrorBundle, options: RenderOptions, t: Io.Terminal) Io.Terminal.SetColorError!void

参数

错误

Canceled Cancelable

调用方请求停止异步操作。

Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

WriteFailed Error

详细诊断信息见 Writer 实现。

std.zig.ErrorBundle.renderToWriter

函数

第 178 行

pub fn renderToWriter(eb: ErrorBundle, options: RenderOptions, w: *Writer) Writer.Error!void

参数

eb: ErrorBundle
options: RenderOptions
w: *Writer

错误

WriteFailed

详细诊断信息见 Writer 实现。

std.zig.ErrorBundle.SourceLocation

容器

第 53 行

尾随数据:

  • 对每个 reference_trace_len 的 ReferenceTrace

字段

src_path: String
line: u32
column: u32
span_start: u32

起始词法标记的字节偏移

span_main: u32

主要错误位置的字节偏移

span_end: u32

最后一个词法标记结束处的字节偏移量

source_line: OptionalString = 0

不包含末尾换行符。

reference_trace_len: u32 = 0

std.zig.ErrorBundle.SourceLocationIndex

容器

第 38 行

字段

none = 0
_

std.zig.ErrorBundle.std

别名

第 11 行

别名目标 std

std.zig.ErrorBundle.String

类型

第 22 行

string_bytes 中的索引。

std.zig.ErrorBundle.Wip

容器

第 356 行

字段

gpa: Allocator
string_bytes: std.ArrayList(u8)
extra: std.ArrayList(u32)

此数组的首项为 ErrorMessageList。

root_list: std.ArrayList(MessageIndex)

std.zig.ErrorBundle.Wip.addBundleAsNotes

函数

第 489 行

pub fn addBundleAsNotes(wip: *Wip, other: ErrorBundle) Allocator.Error!void

参数

wip: *Wip
other: ErrorBundle

错误

OutOfMemory

std.zig.ErrorBundle.Wip.addBundleAsRoots

函数

第 506 行

pub fn addBundleAsRoots(wip: *Wip, other: ErrorBundle) !void

参数

wip: *Wip
other: ErrorBundle

用法示例

test addBundleAsRoots {
    var bundle = bundle: {
        var wip: ErrorBundle.Wip = undefined;
        try wip.init(std.testing.allocator);
        errdefer wip.deinit();

        var ref_traces: [3]ReferenceTrace = undefined;
        for (&ref_traces, 0..) |*ref_trace, i| {
            if (i == ref_traces.len - 1) {
                // 哨兵引用跟踪
                ref_trace.* = .{
                    .decl_name = 3, // 表示 3 个隐藏引用
                    .src_loc = .none,
                };
            } else {
                ref_trace.* = .{
                    .decl_name = try wip.addString("foo"),
                    .src_loc = try wip.addSourceLocation(.{
                        .src_path = try wip.addString("foo"),
                        .line = 1,
                        .column = 2,
                        .span_start = 3,
                        .span_main = 4,
                        .span_end = 5,
                        .source_line = 0,
                    }),
                };
            }
        }

        const src_loc = try wip.addSourceLocation(.{
            .src_path = try wip.addString("foo"),
            .line = 1,
            .column = 2,
            .span_start = 3,
            .span_main = 4,
            .span_end = 5,
            .source_line = try wip.addString("some source code"),
            .reference_trace_len = ref_traces.len,
        });
        for (&ref_traces) |ref_trace| {
            try wip.addReferenceTrace(ref_trace);
        }

        try wip.addRootErrorMessage(ErrorMessage{
            .msg = try wip.addString("hello world"),
            .src_loc = src_loc,
            .notes_len = 1,
        });
        const i = try wip.reserveNotes(1);
        const note_index = @backingInt(wip.addErrorMessageAssumeCapacity(.{
            .msg = try wip.addString("this is a note"),
            .src_loc = try wip.addSourceLocation(.{
                .src_path = try wip.addString("bar"),
                .line = 1,
                .column = 2,
                .span_start = 3,
                .span_main = 4,
                .span_end = 5,
                .source_line = try wip.addString("another line of source"),
            }),
        }));
        wip.extra.items[i] = note_index;

        break :bundle try wip.toOwnedBundle("");
    };
    defer bundle.deinit(std.testing.allocator);

    var bundle_buf: Writer.Allocating = .init(std.testing.allocator);
    const bundle_bw = &bundle_buf.interface;
    defer bundle_buf.deinit();
    try bundle.renderToWriter(bundle_bw);

    var copy = copy: {
        var wip: ErrorBundle.Wip = undefined;
        try wip.init(std.testing.allocator);
        errdefer wip.deinit();

        try wip.addBundleAsRoots(bundle);

        break :copy try wip.toOwnedBundle("");
    };
    defer copy.deinit(std.testing.allocator);

    var copy_buf: Writer.Allocating = .init(std.testing.allocator);
    const copy_bw = &copy_buf.interface;
    defer copy_buf.deinit();
    try copy.renderToWriter(copy_bw);

    try std.testing.expectEqualStrings(bundle_bw.written(), copy_bw.written());
}

std.zig.ErrorBundle.Wip.addErrorMessage

函数

第 473 行

pub fn addErrorMessage(wip: *Wip, em: ErrorMessage) Allocator.Error!MessageIndex

参数

wip: *Wip
em: ErrorMessage

错误

OutOfMemory

std.zig.ErrorBundle.Wip.addErrorMessageAssumeCapacity

函数

第 477 行

pub fn addErrorMessageAssumeCapacity(wip: *Wip, em: ErrorMessage) MessageIndex

参数

wip: *Wip
em: ErrorMessage

std.zig.ErrorBundle.Wip.addExtra

函数

第 754 行

fn addExtra(wip: *Wip, extra: anytype) Allocator.Error!u32

参数

wip: *Wip

错误

OutOfMemory

std.zig.ErrorBundle.Wip.addExtraAssumeCapacity

函数

第 761 行

fn addExtraAssumeCapacity(wip: *Wip, extra: anytype) u32

参数

wip: *Wip

std.zig.ErrorBundle.Wip.addOtherMessage

函数

第 687 行

fn addOtherMessage(wip: *Wip, other: ErrorBundle, msg_index: MessageIndex) !MessageIndex

参数

wip: *Wip
other: ErrorBundle
msg_index: MessageIndex

std.zig.ErrorBundle.Wip.addOtherSourceLocation

函数

第 703 行

fn addOtherSourceLocation( wip: *Wip, other: ErrorBundle, index: SourceLocationIndex, ) !SourceLocationIndex

参数

wip: *Wip
other: ErrorBundle
index: SourceLocationIndex

std.zig.ErrorBundle.Wip.addReferenceTrace

函数

第 485 行

pub fn addReferenceTrace(wip: *Wip, rt: ReferenceTrace) Allocator.Error!void

参数

wip: *Wip
rt: ReferenceTrace

错误

OutOfMemory

std.zig.ErrorBundle.Wip.addRootErrorMessage

函数

第 456 行

pub fn addRootErrorMessage(wip: *Wip, em: ErrorMessage) Allocator.Error!void

参数

wip: *Wip
em: ErrorMessage

错误

OutOfMemory

std.zig.ErrorBundle.Wip.addRootErrorMessageWithNotes

函数

第 461 行

pub fn addRootErrorMessageWithNotes( wip: *Wip, msg: ErrorMessage, notes: []const ErrorMessage, ) !void

参数

wip: *Wip
msg: ErrorMessage
notes: []const ErrorMessage

std.zig.ErrorBundle.Wip.addSourceLocation

函数

第 481 行

pub fn addSourceLocation(wip: *Wip, sl: SourceLocation) Allocator.Error!SourceLocationIndex

参数

wip: *Wip
sl: SourceLocation

错误

OutOfMemory

std.zig.ErrorBundle.Wip.addString

函数

第 439 行

pub fn addString(wip: *Wip, s: []const u8) Allocator.Error!String

参数

wip: *Wip
s: []const u8

错误

OutOfMemory

std.zig.ErrorBundle.Wip.addZirErrorMessages

函数

第 528 行

pub fn addZirErrorMessages( eb: *ErrorBundle.Wip, zir: std.zig.Zir, tree: std.zig.Ast, source: [:0]const u8, src_path: []const u8, ) !void

参数

eb: *ErrorBundle.Wip
zir: std.zig.Zir
tree: std.zig.Ast
source: [:0]const u8
src_path: []const u8

std.zig.ErrorBundle.Wip.addZoirErrorMessages

函数

第 614 行

pub fn addZoirErrorMessages( eb: *ErrorBundle.Wip, zoir: std.zig.Zoir, tree: std.zig.Ast, source: [:0]const u8, src_path: []const u8, ) !void

参数

eb: *ErrorBundle.Wip
zoir: std.zig.Zoir
tree: std.zig.Ast
source: [:0]const u8
src_path: []const u8

std.zig.ErrorBundle.Wip.deinit

函数

第 384 行

pub fn deinit(wip: *Wip) void

参数

wip: *Wip

std.zig.ErrorBundle.Wip.init

函数

第 363 行

pub fn init(gpa: Allocator) !Wip

参数

gpa: Allocator

std.zig.ErrorBundle.Wip.printString

函数

第 448 行

pub fn printString(wip: *Wip, comptime fmt: []const u8, args: anytype) Allocator.Error!String

参数

wip: *Wip
fmt: []const u8

错误

OutOfMemory

std.zig.ErrorBundle.Wip.reserveNotes

函数

第 521 行

pub fn reserveNotes(wip: *Wip, notes_len: u32) !u32

参数

wip: *Wip
notes_len: u32

std.zig.ErrorBundle.Wip.setExtra

函数

第 769 行

fn setExtra(wip: *Wip, index: usize, extra: anytype) void

参数

wip: *Wip
index: usize

std.zig.ErrorBundle.Wip.tmpBundle

函数

第 432 行

pub fn tmpBundle(wip: Wip) ErrorBundle

参数

wip: Wip

std.zig.ErrorBundle.Wip.toOwnedBundle

函数

第 392 行

pub fn toOwnedBundle(wip: *Wip, compile_log_text: []const u8) !ErrorBundle

参数

wip: *Wip
compile_log_text: []const u8

std.zig.ErrorBundle.writeMsg

函数

第 346 行

将错误消息拆分为各行,以便正确缩进, 支持较长且格式清晰的错误消息。

例如,用于拆分 @compileError("hello\nworld") 中的消息。

fn writeMsg(eb: ErrorBundle, err_msg: ErrorMessage, w: *Writer, indent: usize) !void

参数

eb: ErrorBundle
err_msg: ErrorMessage
w: *Writer
indent: usize

std.zig.ErrorBundle.Writer

别名

第 13 行

别名目标 std.Io.Writer

源码

std/zig/ErrorBundle.zig

//! 为支持增量编译,错误存储在不同位置,
//! 以便适时创建和销毁。此结构体
//! 用于将不同位置的全部错误收集到
//! 一个方便 API 用户使用的位置。
//!
//! 此数据结构具有一种特殊编码:如果两个数组均
//! 为空,则表示没有错误。该编码的目的在于
//! 使无错误这一常见情况无需堆分配。
const ErrorBundle = @This();

const std = @import("std");
const Io = std.Io;
const Writer = std.Io.Writer;
const Allocator = std.mem.Allocator;
const assert = std.debug.assert;

string_bytes: []const u8,
/// 此数组的首项为 `ErrorMessageList`。
extra: []const u32,

/// `string_bytes` 中的索引。
pub const String = u32;
/// `string_bytes` 中的索引,或 null。
pub const OptionalString = u32;

/// 没有错误时使用的特殊编码。
pub const empty: ErrorBundle = .{
    .string_bytes = &.{},
    .extra = &.{},
};

// `extra` 中指向 `ErrorMessage` 的索引。
pub const MessageIndex = enum(u32) {
    _,
};

// `extra` 中指向 `SourceLocation` 的索引。
pub const SourceLocationIndex = enum(u32) {
    none = 0,
    _,
};

/// 每个长度值在起始处都有一个 MessageIndex。
pub const ErrorMessageList = struct {
    len: u32,
    start: u32,
    /// 空终止字符串索引。0 表示没有编译日志文本。
    compile_log_text: OptionalString,
};

/// 尾随数据:
/// * 对每个 reference_trace_len 的 ReferenceTrace
pub const SourceLocation = struct {
    src_path: String,
    line: u32,
    column: u32,
    /// 起始词法标记的字节偏移
    span_start: u32,
    /// 主要错误位置的字节偏移
    span_main: u32,
    /// 最后一个词法标记结束处的字节偏移量
    span_end: u32,
    /// 不包含末尾换行符。
    source_line: OptionalString = 0,
    reference_trace_len: u32 = 0,
};

/// 尾随数据:
/// * 对每个 notes_len 项存储一个 MessageIndex。
pub const ErrorMessage = struct {
    msg: String,
    /// 通常为一,但冗余消息会使其增加。
    count: u32 = 1,
    src_loc: SourceLocationIndex = .none,
    notes_len: u32 = 0,
};

pub const ReferenceTrace = struct {
    /// 以 null 结尾的字符串索引。
    /// 但哨兵 ReferenceTrace 元素例外,此时:
    /// * 0 表示剩余引用被隐藏
    /// * >0 表示隐藏了 N 个引用
    decl_name: String,
    /// SourceLocation 在 extra 中的索引
    /// 若为 0,则是哨兵 ReferenceTrace 元素。
    src_loc: SourceLocationIndex,
};

pub fn deinit(eb: *ErrorBundle, gpa: Allocator) void {
    gpa.free(eb.string_bytes);
    gpa.free(eb.extra);
    eb.* = undefined;
}

pub fn errorMessageCount(eb: ErrorBundle) u32 {
    if (eb.extra.len == 0) return 0;
    return eb.getErrorMessageList().len;
}

pub fn getErrorMessageList(eb: ErrorBundle) ErrorMessageList {
    return eb.extraData(ErrorMessageList, 0).data;
}

pub fn getMessages(eb: ErrorBundle) []const MessageIndex {
    const list = eb.getErrorMessageList();
    return @as([]const MessageIndex, @ptrCast(eb.extra[list.start..][0..list.len]));
}

pub fn getErrorMessage(eb: ErrorBundle, index: MessageIndex) ErrorMessage {
    return eb.extraData(ErrorMessage, @backingInt(index)).data;
}

pub fn getSourceLocation(eb: ErrorBundle, index: SourceLocationIndex) SourceLocation {
    assert(index != .none);
    return eb.extraData(SourceLocation, @backingInt(index)).data;
}

pub fn getNotes(eb: ErrorBundle, index: MessageIndex) []const MessageIndex {
    const notes_len = eb.getErrorMessage(index).notes_len;
    const start = @backingInt(index) + @typeInfo(ErrorMessage).@"struct".field_names.len;
    return @as([]const MessageIndex, @ptrCast(eb.extra[start..][0..notes_len]));
}

pub fn getCompileLogOutput(eb: ErrorBundle) [:0]const u8 {
    return nullTerminatedString(eb, getErrorMessageList(eb).compile_log_text);
}

/// 返回请求的数据,以及位于该对象尾部数据起点的
/// 新索引。
fn extraData(eb: ErrorBundle, comptime T: type, index: usize) struct { data: T, end: usize } {
    const field_names = @typeInfo(T).@"struct".field_names;
    const field_types = @typeInfo(T).@"struct".field_types;
    var i: usize = index;
    var result: T = undefined;
    inline for (field_names, field_types) |field_name, field_type| {
        @field(result, field_name) = switch (field_type) {
            u32 => eb.extra[i],
            MessageIndex => @as(MessageIndex, @fromBackingInt(@intCast(eb.extra[i]))),
            SourceLocationIndex => @as(SourceLocationIndex, @fromBackingInt(@intCast(eb.extra[i]))),
            else => @compileError("bad field type"),
        };
        i += 1;
    }
    return .{
        .data = result,
        .end = i,
    };
}

/// 给定 `string_bytes` 中的索引,返回其中找到的空终止字符串。
pub fn nullTerminatedString(eb: ErrorBundle, index: String) [:0]const u8 {
    const string_bytes = eb.string_bytes;
    var end: usize = index;
    while (string_bytes[end] != 0) {
        end += 1;
    }
    return string_bytes[index..end :0];
}

pub const RenderOptions = struct {
    include_reference_trace: bool = true,
    include_source_line: bool = true,
    include_log_text: bool = true,
};

pub const RenderToStderrError = Io.Cancelable || Io.File.Writer.Error;

pub fn renderToStderr(eb: ErrorBundle, io: Io, options: RenderOptions, color: std.zig.Color) RenderToStderrError!void {
    var buffer: [256]u8 = undefined;
    const stderr = try io.lockStderr(&buffer, color.terminalMode());
    defer io.unlockStderr();
    renderToTerminal(eb, options, stderr.terminal()) catch |err| switch (err) {
        error.WriteFailed => return stderr.file_writer.err.?,
        else => |e| return e,
    };
}

pub fn renderToWriter(eb: ErrorBundle, options: RenderOptions, w: *Writer) Writer.Error!void {
    return renderToTerminal(eb, options, .{ .writer = w, .mode = .no_color }) catch |err| switch (err) {
        error.WriteFailed => |e| return e,
        else => unreachable,
    };
}

pub fn renderToTerminal(eb: ErrorBundle, options: RenderOptions, t: Io.Terminal) Io.Terminal.SetColorError!void {
    if (eb.extra.len == 0) return;
    for (eb.getMessages()) |err_msg| {
        try renderErrorMessage(eb, options, err_msg, t, "error", .red, 0);
    }

    if (options.include_log_text) {
        const log_text = eb.getCompileLogOutput();
        if (log_text.len != 0) {
            try t.writer.writeAll("\nCompile Log Output:\n");
            try t.writer.writeAll(log_text);
        }
    }
}

pub fn readAlloc(
    r: *Io.Reader,
    gpa: Allocator,
    extra_len: u32,
    string_bytes_len: u32,
) Io.Reader.ReadAllocError!ErrorBundle {
    const extra = try r.readSliceEndianAlloc(gpa, u32, extra_len, .little);
    errdefer gpa.free(extra);

    const string_bytes = try r.readAlloc(gpa, string_bytes_len);
    errdefer gpa.free(string_bytes);

    return .{
        .extra = extra,
        .string_bytes = string_bytes,
    };
}

fn renderErrorMessage(
    eb: ErrorBundle,
    options: RenderOptions,
    err_msg_index: MessageIndex,
    t: Io.Terminal,
    kind: []const u8,
    color: Io.Terminal.Color,
    indent: usize,
) Io.Terminal.SetColorError!void {
    const w = t.writer;
    const err_msg = eb.getErrorMessage(err_msg_index);
    if (err_msg.src_loc != .none) {
        const src = eb.extraData(SourceLocation, @backingInt(err_msg.src_loc));
        var prefix: Writer.Discarding = .init(&.{});
        try w.splatByteAll(' ', indent);
        prefix.count += indent;
        try t.setColor(.bold);
        try w.print("{s}:{d}:{d}: ", .{
            eb.nullTerminatedString(src.data.src_path),
            src.data.line + 1,
            src.data.column + 1,
        });
        try prefix.writer.print("{s}:{d}:{d}: ", .{
            eb.nullTerminatedString(src.data.src_path),
            src.data.line + 1,
            src.data.column + 1,
        });
        try t.setColor(color);
        try w.writeAll(kind);
        prefix.count += kind.len;
        try w.writeAll(": ");
        prefix.count += 2;
        // 这是错误消息前缀部分的长度:
        // 例如 "file.zig:4:5: error: "。
        const prefix_len: usize = @intCast(prefix.count);
        try t.setColor(.reset);
        try t.setColor(.bold);
        if (err_msg.count == 1) {
            try writeMsg(eb, err_msg, w, prefix_len);
            try w.writeByte('\n');
        } else {
            try writeMsg(eb, err_msg, w, prefix_len);
            try t.setColor(.dim);
            try w.print(" ({d} times)\n", .{err_msg.count});
        }
        try t.setColor(.reset);
        if (src.data.source_line != 0 and options.include_source_line) {
            try w.splatByteAll(' ', indent);
            const line = eb.nullTerminatedString(src.data.source_line);
            for (line) |b| switch (b) {
                '\t' => try w.writeByte(' '),
                else => try w.writeByte(b),
            };
            try w.writeByte('\n');
            try w.splatByteAll(' ', indent);
            // TODO 基本 unicode 码点的等宽显示宽度
            const before_caret = src.data.span_main - src.data.span_start;
            // 减 1,因为 span.main 包含插入符号
            const after_caret = src.data.span_end -| src.data.span_main -| 1;
            try w.splatByteAll(' ', src.data.column - before_caret);
            try t.setColor(.green);
            try w.splatByteAll('~', before_caret);
            try w.writeByte('^');
            try w.splatByteAll('~', after_caret);
            try w.writeByte('\n');
            try t.setColor(.reset);
        }
        for (eb.getNotes(err_msg_index)) |note| {
            try renderErrorMessage(eb, options, note, t, "note", .cyan, indent);
        }
        if (src.data.reference_trace_len > 0 and options.include_reference_trace) {
            try t.setColor(.reset);
            try t.setColor(.dim);
            try w.splatByteAll(' ', indent);
            try w.print("referenced by:\n", .{});
            var ref_index = src.end;
            for (0..src.data.reference_trace_len) |_| {
                const ref_trace = eb.extraData(ReferenceTrace, ref_index);
                ref_index = ref_trace.end;
                try w.splatByteAll(' ', indent);
                if (ref_trace.data.src_loc != .none) {
                    const ref_src = eb.getSourceLocation(ref_trace.data.src_loc);
                    try w.print("    {s}: {s}:{d}:{d}\n", .{
                        eb.nullTerminatedString(ref_trace.data.decl_name),
                        eb.nullTerminatedString(ref_src.src_path),
                        ref_src.line + 1,
                        ref_src.column + 1,
                    });
                } else if (ref_trace.data.decl_name != 0) {
                    const count = ref_trace.data.decl_name;
                    try w.print(
                        "    {d} reference(s) hidden; use '-freference-trace={d}' to see all references\n",
                        .{ count, count + src.data.reference_trace_len - 1 },
                    );
                } else {
                    try w.print(
                        "    remaining reference traces hidden; use '-freference-trace' to see all reference traces\n",
                        .{},
                    );
                }
            }
            try t.setColor(.reset);
        }
    } else {
        try t.setColor(color);
        try w.splatByteAll(' ', indent);
        try w.writeAll(kind);
        try w.writeAll(": ");
        try t.setColor(.reset);
        const msg = eb.nullTerminatedString(err_msg.msg);
        if (err_msg.count == 1) {
            try w.print("{s}\n", .{msg});
        } else {
            try w.print("{s}", .{msg});
            try t.setColor(.dim);
            try w.print(" ({d} times)\n", .{err_msg.count});
        }
        try t.setColor(.reset);
        for (eb.getNotes(err_msg_index)) |note| {
            try renderErrorMessage(eb, options, note, t, "note", .cyan, indent + 4);
        }
    }
}

/// 将错误消息拆分为各行,以便正确缩进,
/// 支持较长且格式清晰的错误消息。
///
/// 例如,用于拆分 `@compileError("hello\nworld")` 中的消息。
fn writeMsg(eb: ErrorBundle, err_msg: ErrorMessage, w: *Writer, indent: usize) !void {
    var lines = std.mem.splitScalar(u8, eb.nullTerminatedString(err_msg.msg), '\n');
    while (lines.next()) |line| {
        try w.writeAll(line);
        if (lines.index == null) break;
        try w.writeByte('\n');
        try w.splatByteAll(' ', indent);
    }
}

pub const Wip = struct {
    gpa: Allocator,
    string_bytes: std.ArrayList(u8),
    /// 此数组的首项为 ErrorMessageList。
    extra: std.ArrayList(u32),
    root_list: std.ArrayList(MessageIndex),

    pub fn init(gpa: Allocator) !Wip {
        var wip: Wip = .{
            .gpa = gpa,
            .string_bytes = .empty,
            .extra = .empty,
            .root_list = .empty,
        };
        errdefer wip.deinit();

        // 以便用 0 表示空字符串引用。
        try wip.string_bytes.append(gpa, 0);

        assert(0 == try wip.addExtra(ErrorMessageList{
            .len = 0,
            .start = 0,
            .compile_log_text = 0,
        }));

        return wip;
    }

    pub fn deinit(wip: *Wip) void {
        const gpa = wip.gpa;
        wip.root_list.deinit(gpa);
        wip.string_bytes.deinit(gpa);
        wip.extra.deinit(gpa);
        wip.* = undefined;
    }

    pub fn toOwnedBundle(wip: *Wip, compile_log_text: []const u8) !ErrorBundle {
        const gpa = wip.gpa;
        if (wip.root_list.items.len == 0) {
            assert(compile_log_text.len == 0);
            // 没有错误时使用的特殊编码。
            wip.deinit();
            wip.* = .{
                .gpa = gpa,
                .string_bytes = .empty,
                .extra = .empty,
                .root_list = .empty,
            };
            return empty;
        }

        const compile_log_str_index = if (compile_log_text.len == 0) 0 else str: {
            const str: u32 = @intCast(wip.string_bytes.items.len);
            try wip.string_bytes.ensureUnusedCapacity(gpa, compile_log_text.len + 1);
            wip.string_bytes.appendSliceAssumeCapacity(compile_log_text);
            wip.string_bytes.appendAssumeCapacity(0);
            break :str str;
        };

        wip.setExtra(0, ErrorMessageList{
            .len = @intCast(wip.root_list.items.len),
            .start = @intCast(wip.extra.items.len),
            .compile_log_text = compile_log_str_index,
        });
        try wip.extra.appendSlice(gpa, @as([]const u32, @ptrCast(wip.root_list.items)));
        wip.root_list.clearAndFree(gpa);

        try wip.string_bytes.shrinkToLen(gpa);
        try wip.extra.shrinkToLen(gpa);

        return .{
            .string_bytes = wip.string_bytes.toOwnedSliceAssert(),
            .extra = wip.extra.toOwnedSliceAssert(),
        };
    }

    pub fn tmpBundle(wip: Wip) ErrorBundle {
        return .{
            .string_bytes = wip.string_bytes.items,
            .extra = wip.extra.items,
        };
    }

    pub fn addString(wip: *Wip, s: []const u8) Allocator.Error!String {
        const gpa = wip.gpa;
        const index: String = @intCast(wip.string_bytes.items.len);
        try wip.string_bytes.ensureUnusedCapacity(gpa, s.len + 1);
        wip.string_bytes.appendSliceAssumeCapacity(s);
        wip.string_bytes.appendAssumeCapacity(0);
        return index;
    }

    pub fn printString(wip: *Wip, comptime fmt: []const u8, args: anytype) Allocator.Error!String {
        const gpa = wip.gpa;
        const index: String = @intCast(wip.string_bytes.items.len);
        try wip.string_bytes.print(gpa, fmt, args);
        try wip.string_bytes.append(gpa, 0);
        return index;
    }

    pub fn addRootErrorMessage(wip: *Wip, em: ErrorMessage) Allocator.Error!void {
        try wip.root_list.ensureUnusedCapacity(wip.gpa, 1);
        wip.root_list.appendAssumeCapacity(try addErrorMessage(wip, em));
    }

    pub fn addRootErrorMessageWithNotes(
        wip: *Wip,
        msg: ErrorMessage,
        notes: []const ErrorMessage,
    ) !void {
        try wip.addRootErrorMessage(msg);
        const notes_start = try wip.reserveNotes(@intCast(notes.len));
        for (notes_start.., notes) |i, note| {
            wip.extra.items[i] = @backingInt(wip.addErrorMessageAssumeCapacity(note));
        }
    }

    pub fn addErrorMessage(wip: *Wip, em: ErrorMessage) Allocator.Error!MessageIndex {
        return @fromBackingInt(@intCast(try addExtra(wip, em)));
    }

    pub fn addErrorMessageAssumeCapacity(wip: *Wip, em: ErrorMessage) MessageIndex {
        return @fromBackingInt(@intCast(addExtraAssumeCapacity(wip, em)));
    }

    pub fn addSourceLocation(wip: *Wip, sl: SourceLocation) Allocator.Error!SourceLocationIndex {
        return @fromBackingInt(@intCast(try addExtra(wip, sl)));
    }

    pub fn addReferenceTrace(wip: *Wip, rt: ReferenceTrace) Allocator.Error!void {
        _ = try addExtra(wip, rt);
    }

    pub fn addBundleAsNotes(wip: *Wip, other: ErrorBundle) Allocator.Error!void {
        const gpa = wip.gpa;

        try wip.string_bytes.ensureUnusedCapacity(gpa, other.string_bytes.len);
        try wip.extra.ensureUnusedCapacity(gpa, other.extra.len);

        const other_list = other.getMessages();

        // 上方的 ensureUnusedCapacity 调用保证这一点。
        const notes_start = wip.reserveNotes(@intCast(other_list.len)) catch unreachable;
        for (notes_start.., other_list) |note, message| {
            // 此行可能导致 `wip.extra.items` 调整大小。
            const note_index = @backingInt(wip.addOtherMessage(other, message) catch unreachable);
            wip.extra.items[note] = note_index;
        }
    }

    pub fn addBundleAsRoots(wip: *Wip, other: ErrorBundle) !void {
        const gpa = wip.gpa;

        try wip.string_bytes.ensureUnusedCapacity(gpa, other.string_bytes.len);
        try wip.extra.ensureUnusedCapacity(gpa, other.extra.len);

        const other_list = other.getMessages();

        try wip.root_list.ensureUnusedCapacity(gpa, other_list.len);
        for (other_list) |other_msg| {
            // 上方的 ensureUnusedCapacity 调用保证了这一点。
            wip.root_list.appendAssumeCapacity(wip.addOtherMessage(other, other_msg) catch unreachable);
        }
    }

    pub fn reserveNotes(wip: *Wip, notes_len: u32) !u32 {
        try wip.extra.ensureUnusedCapacity(wip.gpa, notes_len +
            notes_len * @typeInfo(ErrorBundle.ErrorMessage).@"struct".field_names.len);
        wip.extra.items.len += notes_len;
        return @intCast(wip.extra.items.len - notes_len);
    }

    pub fn addZirErrorMessages(
        eb: *ErrorBundle.Wip,
        zir: std.zig.Zir,
        tree: std.zig.Ast,
        source: [:0]const u8,
        src_path: []const u8,
    ) !void {
        const Zir = std.zig.Zir;
        const payload_index = zir.extra[@backingInt(Zir.ExtraIndex.compile_errors)];
        assert(payload_index != 0);

        const header = zir.extraData(Zir.Inst.CompileErrors, payload_index);
        const items_len = header.data.items_len;
        var extra_index = header.end;
        for (0..items_len) |_| {
            const item = zir.extraData(Zir.Inst.CompileErrors.Item, extra_index);
            extra_index = item.end;
            const err_span = blk: {
                if (item.data.node.unwrap()) |node| {
                    break :blk tree.nodeToSpan(node);
                } else if (item.data.token.unwrap()) |token| {
                    const start = tree.tokenStart(token) + item.data.byte_offset;
                    const end = start + @as(u32, @intCast(tree.tokenSlice(token).len)) - item.data.byte_offset;
                    break :blk std.zig.Ast.Span{ .start = start, .end = end, .main = start };
                } else unreachable;
            };
            const err_loc = std.zig.findLineColumn(source, err_span.main);

            {
                const msg = zir.nullTerminatedString(item.data.msg);
                try eb.addRootErrorMessage(.{
                    .msg = try eb.addString(msg),
                    .src_loc = try eb.addSourceLocation(.{
                        .src_path = try eb.addString(src_path),
                        .span_start = err_span.start,
                        .span_main = err_span.main,
                        .span_end = err_span.end,
                        .line = @intCast(err_loc.line),
                        .column = @intCast(err_loc.column),
                        .source_line = try eb.addString(err_loc.source_line),
                    }),
                    .notes_len = item.data.notesLen(zir),
                });
            }

            if (item.data.notes != 0) {
                const notes_start = try eb.reserveNotes(item.data.notesLen(zir));
                const block = zir.extraData(Zir.Inst.Block, item.data.notes);
                const body = zir.extra[block.end..][0..block.data.body_len];
                for (notes_start.., body) |note_i, body_elem| {
                    const note_item = zir.extraData(Zir.Inst.CompileErrors.Item, body_elem);
                    const msg = zir.nullTerminatedString(note_item.data.msg);
                    const span = blk: {
                        if (note_item.data.node.unwrap()) |node| {
                            break :blk tree.nodeToSpan(node);
                        } else if (note_item.data.token.unwrap()) |token| {
                            const start = tree.tokenStart(token) + note_item.data.byte_offset;
                            const end = start + @as(u32, @intCast(tree.tokenSlice(token).len)) - item.data.byte_offset;
                            break :blk std.zig.Ast.Span{ .start = start, .end = end, .main = start };
                        } else unreachable;
                    };
                    const loc = std.zig.findLineColumn(source, span.main);

                    // 此行可能导致 `wip.extra.items` 调整大小。
                    const note_index = @backingInt(try eb.addErrorMessage(.{
                        .msg = try eb.addString(msg),
                        .src_loc = try eb.addSourceLocation(.{
                            .src_path = try eb.addString(src_path),
                            .span_start = span.start,
                            .span_main = span.main,
                            .span_end = span.end,
                            .line = @intCast(loc.line),
                            .column = @intCast(loc.column),
                            .source_line = if (loc.eql(err_loc))
                                0
                            else
                                try eb.addString(loc.source_line),
                        }),
                        .notes_len = 0, // TODO 将此函数改写为递归形式
                    }));
                    eb.extra.items[note_i] = note_index;
                }
            }
        }
    }

    pub fn addZoirErrorMessages(
        eb: *ErrorBundle.Wip,
        zoir: std.zig.Zoir,
        tree: std.zig.Ast,
        source: [:0]const u8,
        src_path: []const u8,
    ) !void {
        assert(zoir.hasCompileErrors());

        for (zoir.compile_errors) |err| {
            const err_span: std.zig.Ast.Span = span: {
                if (err.token.unwrap()) |token| {
                    const token_start = tree.tokenStart(token);
                    const start = token_start + err.node_or_offset;
                    const end = token_start + @as(u32, @intCast(tree.tokenSlice(token).len));
                    break :span .{ .start = start, .end = end, .main = start };
                } else {
                    break :span tree.nodeToSpan(@fromBackingInt(@intCast(err.node_or_offset)));
                }
            };
            const err_loc = std.zig.findLineColumn(source, err_span.main);

            try eb.addRootErrorMessage(.{
                .msg = try eb.addString(err.msg.get(&zoir)),
                .src_loc = try eb.addSourceLocation(.{
                    .src_path = try eb.addString(src_path),
                    .span_start = err_span.start,
                    .span_main = err_span.main,
                    .span_end = err_span.end,
                    .line = @intCast(err_loc.line),
                    .column = @intCast(err_loc.column),
                    .source_line = try eb.addString(err_loc.source_line),
                }),
                .notes_len = err.note_count,
            });

            const notes_start = try eb.reserveNotes(err.note_count);
            for (notes_start.., err.first_note.., 0..err.note_count) |eb_note_idx, zoir_note_idx, _| {
                const note = zoir.error_notes[zoir_note_idx];
                const note_span: std.zig.Ast.Span = span: {
                    if (note.token.unwrap()) |token| {
                        const token_start = tree.tokenStart(token);
                        const start = token_start + note.node_or_offset;
                        const end = token_start + @as(u32, @intCast(tree.tokenSlice(token).len));
                        break :span .{ .start = start, .end = end, .main = start };
                    } else {
                        break :span tree.nodeToSpan(@fromBackingInt(@intCast(note.node_or_offset)));
                    }
                };
                const note_loc = std.zig.findLineColumn(source, note_span.main);

                // 此行可能导致 `wip.extra.items` 调整大小。
                const note_index = @backingInt(try eb.addErrorMessage(.{
                    .msg = try eb.addString(note.msg.get(&zoir)),
                    .src_loc = try eb.addSourceLocation(.{
                        .src_path = try eb.addString(src_path),
                        .span_start = note_span.start,
                        .span_main = note_span.main,
                        .span_end = note_span.end,
                        .line = @intCast(note_loc.line),
                        .column = @intCast(note_loc.column),
                        .source_line = if (note_loc.eql(err_loc))
                            0
                        else
                            try eb.addString(note_loc.source_line),
                    }),
                    .notes_len = 0,
                }));
                eb.extra.items[eb_note_idx] = note_index;
            }
        }
    }

    fn addOtherMessage(wip: *Wip, other: ErrorBundle, msg_index: MessageIndex) !MessageIndex {
        const other_msg = other.getErrorMessage(msg_index);
        const src_loc = try wip.addOtherSourceLocation(other, other_msg.src_loc);
        const msg = try wip.addErrorMessage(.{
            .msg = try wip.addString(other.nullTerminatedString(other_msg.msg)),
            .count = other_msg.count,
            .src_loc = src_loc,
            .notes_len = other_msg.notes_len,
        });
        const notes_start = try wip.reserveNotes(other_msg.notes_len);
        for (notes_start.., other.getNotes(msg_index)) |note, other_note| {
            wip.extra.items[note] = @backingInt(try wip.addOtherMessage(other, other_note));
        }
        return msg;
    }

    fn addOtherSourceLocation(
        wip: *Wip,
        other: ErrorBundle,
        index: SourceLocationIndex,
    ) !SourceLocationIndex {
        if (index == .none) return .none;
        const other_sl = other.getSourceLocation(index);

        var ref_traces: std.ArrayList(ReferenceTrace) = .empty;
        defer ref_traces.deinit(wip.gpa);

        if (other_sl.reference_trace_len > 0) {
            var ref_index = other.extraData(SourceLocation, @backingInt(index)).end;
            for (0..other_sl.reference_trace_len) |_| {
                const other_ref_trace_ed = other.extraData(ReferenceTrace, ref_index);
                const other_ref_trace = other_ref_trace_ed.data;
                ref_index = other_ref_trace_ed.end;

                const ref_trace: ReferenceTrace = if (other_ref_trace.src_loc == .none) .{
                    // 哨兵 ReferenceTrace 不在 decl_name 中存储字符串索引
                    .decl_name = other_ref_trace.decl_name,
                    .src_loc = .none,
                } else .{
                    .decl_name = try wip.addString(other.nullTerminatedString(other_ref_trace.decl_name)),
                    .src_loc = try wip.addOtherSourceLocation(other, other_ref_trace.src_loc),
                };
                try ref_traces.append(wip.gpa, ref_trace);
            }
        }

        const src_loc = try wip.addSourceLocation(.{
            .src_path = try wip.addString(other.nullTerminatedString(other_sl.src_path)),
            .line = other_sl.line,
            .column = other_sl.column,
            .span_start = other_sl.span_start,
            .span_main = other_sl.span_main,
            .span_end = other_sl.span_end,
            .source_line = if (other_sl.source_line != 0)
                try wip.addString(other.nullTerminatedString(other_sl.source_line))
            else
                0,
            .reference_trace_len = other_sl.reference_trace_len,
        });

        for (ref_traces.items) |ref_trace| {
            try wip.addReferenceTrace(ref_trace);
        }

        return src_loc;
    }

    fn addExtra(wip: *Wip, extra: anytype) Allocator.Error!u32 {
        const gpa = wip.gpa;
        const fields = @typeInfo(@TypeOf(extra)).@"struct".field_names;
        try wip.extra.ensureUnusedCapacity(gpa, fields.len);
        return addExtraAssumeCapacity(wip, extra);
    }

    fn addExtraAssumeCapacity(wip: *Wip, extra: anytype) u32 {
        const fields = @typeInfo(@TypeOf(extra)).@"struct".field_names;
        const result: u32 = @intCast(wip.extra.items.len);
        wip.extra.items.len += fields.len;
        setExtra(wip, result, extra);
        return result;
    }

    fn setExtra(wip: *Wip, index: usize, extra: anytype) void {
        const extra_info = @typeInfo(@TypeOf(extra)).@"struct";
        const field_names = extra_info.field_names;
        const field_types = extra_info.field_types;
        var i = index;
        inline for (field_names, field_types) |field_name, field_type| {
            wip.extra.items[i] = switch (field_type) {
                u32 => @field(extra, field_name),
                MessageIndex => @backingInt(@field(extra, field_name)),
                SourceLocationIndex => @backingInt(@field(extra, field_name)),
                else => @compileError("bad field type: " ++ @typeName(field_type)),
            };
            i += 1;
        }
    }

    test addBundleAsRoots {
        var bundle = bundle: {
            var wip: ErrorBundle.Wip = undefined;
            try wip.init(std.testing.allocator);
            errdefer wip.deinit();

            var ref_traces: [3]ReferenceTrace = undefined;
            for (&ref_traces, 0..) |*ref_trace, i| {
                if (i == ref_traces.len - 1) {
                    // 哨兵引用跟踪
                    ref_trace.* = .{
                        .decl_name = 3, // 表示 3 个隐藏引用
                        .src_loc = .none,
                    };
                } else {
                    ref_trace.* = .{
                        .decl_name = try wip.addString("foo"),
                        .src_loc = try wip.addSourceLocation(.{
                            .src_path = try wip.addString("foo"),
                            .line = 1,
                            .column = 2,
                            .span_start = 3,
                            .span_main = 4,
                            .span_end = 5,
                            .source_line = 0,
                        }),
                    };
                }
            }

            const src_loc = try wip.addSourceLocation(.{
                .src_path = try wip.addString("foo"),
                .line = 1,
                .column = 2,
                .span_start = 3,
                .span_main = 4,
                .span_end = 5,
                .source_line = try wip.addString("some source code"),
                .reference_trace_len = ref_traces.len,
            });
            for (&ref_traces) |ref_trace| {
                try wip.addReferenceTrace(ref_trace);
            }

            try wip.addRootErrorMessage(ErrorMessage{
                .msg = try wip.addString("hello world"),
                .src_loc = src_loc,
                .notes_len = 1,
            });
            const i = try wip.reserveNotes(1);
            const note_index = @backingInt(wip.addErrorMessageAssumeCapacity(.{
                .msg = try wip.addString("this is a note"),
                .src_loc = try wip.addSourceLocation(.{
                    .src_path = try wip.addString("bar"),
                    .line = 1,
                    .column = 2,
                    .span_start = 3,
                    .span_main = 4,
                    .span_end = 5,
                    .source_line = try wip.addString("another line of source"),
                }),
            }));
            wip.extra.items[i] = note_index;

            break :bundle try wip.toOwnedBundle("");
        };
        defer bundle.deinit(std.testing.allocator);

        var bundle_buf: Writer.Allocating = .init(std.testing.allocator);
        const bundle_bw = &bundle_buf.interface;
        defer bundle_buf.deinit();
        try bundle.renderToWriter(bundle_bw);

        var copy = copy: {
            var wip: ErrorBundle.Wip = undefined;
            try wip.init(std.testing.allocator);
            errdefer wip.deinit();

            try wip.addBundleAsRoots(bundle);

            break :copy try wip.toOwnedBundle("");
        };
        defer copy.deinit(std.testing.allocator);

        var copy_buf: Writer.Allocating = .init(std.testing.allocator);
        const copy_bw = &copy_buf.interface;
        defer copy_buf.deinit();
        try copy.renderToWriter(copy_bw);

        try std.testing.expectEqualStrings(bundle_bw.written(), copy_bw.written());
    }
};