跳转到内容

std.zig.AstGen

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

第 1 行

接收抽象语法树并生成 ZIR 代码。

字段

gpa: Allocator
tree: *const Ast
nodes_need_rl: *const AstRlAnnotate.RlNeededSet

在存在选择时,必须向子表达式暴露结果指针的节点集合。详情见 AstRlAnnotate。

instructions: std.MultiArrayList(Zir.Inst) = .{}
extra: ArrayList(u32) = .empty
string_bytes: ArrayList(u8) = .empty
source_offset: u32 = 0

跟踪源码文件中的当前字节偏移量。 用于填充 ZIR 中的行号差值。AstGen 在 整个 AST 降低过程中维护此“游标”, 避免为每个声明重新扫描行列, 否则复杂度将为 O(N^2)。

source_line: u32 = 0

跟踪 source_offset 对应的行。 此值为绝对值。

source_column: u32 = 0

跟踪 source_offset 对应的列。 此值为绝对值。

arena: Allocator

用于临时分配;AstGen 完成后释放。 生成的 ZIR 代码不会引用此区域中的任何内容。

string_table: std.HashMapUnmanaged(u32, void, StringIndexContext, std.hash_map.default_max_load_percentage) = .empty
compile_errors: ArrayList(Zir.Inst.CompileErrors.Item) = .empty
fn_block: ?*GenZir = null

当前函数的最顶层块。

fn_var_args: bool = false
within_fn: bool = false

当前是否位于函数内部。若为 true,任何容器声明都可能是泛型,因此必须通过闭包传递。

fn_ret_ty: Zir.Inst.Ref = .none

当前函数的返回类型。它可能是简单的 Ref, 否则引用一个 ret_type 指令。

imports: std.array_hash_map.Auto(Zir.NullTerminatedString, Ast.TokenIndex) = .empty

将字符串表索引映射到首个将该字符串 用作操作数的 @import ZIR 指令。

scratch: std.ArrayList(u32) = .empty

构造载荷时用作临时存储。

ref_table: std.AutoHashMapUnmanaged(Zir.Inst.Index, Zir.Inst.Index) = .empty

需要 ref 指令时,先创建并保存在此 表中,而不立即追加到当前块体。 随后,将指令加入父块时,通常是在 setBlockBody 中,若其存在 ref_table 条目,就在 该位置加入 ref 指令。这样可确保两个性质:

  1. 指向同一局部变量的所有指针均返回相同地址, 这是符合语言规范所必需的。
  2. ref 指令支配其全部使用位置,这是 ZIR 要求的性质。 键为 ref 操作数,值为 ref 指令。
src_hasher: std.zig.SrcHasher

任何应触发增量编译数据失效的信息, 均应用于更新此哈希器。最终结果为 外层声明等对象的最终源码哈希。

std.zig.AstGen.addEnsureResult

函数

第 2664 行

fn addEnsureResult(gz: *GenZir, maybe_unused_result: Zir.Inst.Ref, statement: Ast.Node.Index) InnerError!Ast.Node.OptionalIndex

参数

gz: *GenZir
maybe_unused_result: Zir.Inst.Ref
statement: Ast.Node.Index

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.addExtra

函数

第 76 行

fn addExtra(astgen: *AstGen, extra: anytype) Allocator.Error!u32

参数

astgen: *AstGen

错误

OutOfMemory

std.zig.AstGen.addExtraAssumeCapacity

函数

第 82 行

fn addExtraAssumeCapacity(astgen: *AstGen, extra: anytype) u32

参数

astgen: *AstGen

std.zig.AstGen.addFailedDeclaration

函数

第 13463 行

fn addFailedDeclaration( wip_decls: *WipDecls, gz: *GenZir, kind: Zir.Inst.Declaration.Unwrapped.Kind, name: Zir.NullTerminatedString, src_node: Ast.Node.Index, is_pub: bool, ) !void

参数

wip_decls: *WipDecls
gz: *GenZir
kind: Zir.Inst.Declaration.Unwrapped.Kind
name: Zir.NullTerminatedString
src_node: Ast.Node.Index
is_pub: bool

std.zig.AstGen.addFieldAccess

函数

第 6035 行

fn addFieldAccess( tag: Zir.Inst.Tag, gz: *GenZir, scope: *Scope, lhs_ri: ResultInfo, node: Ast.Node.Index, ) InnerError!Zir.Inst.Ref

参数

tag: Zir.Inst.Tag
gz: *GenZir
scope: *Scope
lhs_ri: ResultInfo
node: Ast.Node.Index

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.advanceSourceCursor

函数

第 12928 行

将源码游标推进至文件中的绝对字节偏移 end。

fn advanceSourceCursor(astgen: *AstGen, end: usize) void

参数

astgen: *AstGen
end: usize

std.zig.AstGen.advanceSourceCursorToNode

函数

第 12921 行

将源码游标推进到 node 的起点。

fn advanceSourceCursorToNode(astgen: *AstGen, node: Ast.Node.Index) void

参数

astgen: *AstGen
node: Ast.Node.Index

std.zig.AstGen.Allocator

别名

第 7 行

别名目标 std.mem.Allocator

std.zig.AstGen.anyErrdefers

函数

第 2983 行

fn anyErrdefers(outer_scope: *Scope, inner_scope: *Scope) bool

参数

outer_scope: *Scope
inner_scope: *Scope

std.zig.AstGen.appendBodyWithFixups

函数

第 13269 行

假定已为消息体增加容量。计入修正项后所需的 容量可通过 countBodyLenAfterFixups 获得。

fn appendBodyWithFixups(astgen: *AstGen, body: []const Zir.Inst.Index) void

参数

astgen: *AstGen
body: []const Zir.Inst.Index

std.zig.AstGen.appendBodyWithFixupsArrayList

函数

第 13273 行

fn appendBodyWithFixupsArrayList( astgen: *AstGen, list: *std.ArrayList(u32), body: []const Zir.Inst.Index, ) void

参数

astgen: *AstGen
list: *std.ArrayList(u32)
body: []const Zir.Inst.Index

std.zig.AstGen.appendBodyWithFixupsExtraRefsArrayList

函数

第 13281 行

fn appendBodyWithFixupsExtraRefsArrayList( astgen: *AstGen, list: *std.ArrayList(u32), body: []const Zir.Inst.Index, extra_refs: []const Zir.Inst.Index, ) void

参数

astgen: *AstGen
list: *std.ArrayList(u32)
body: []const Zir.Inst.Index
extra_refs: []const Zir.Inst.Index

std.zig.AstGen.appendErrorNode

函数

第 10853 行

fn appendErrorNode( astgen: *AstGen, node: Ast.Node.Index, comptime format: []const u8, args: anytype, ) Allocator.Error!void

参数

astgen: *AstGen
node: Ast.Node.Index
format: []const u8

错误

OutOfMemory

std.zig.AstGen.appendErrorNodeNotes

函数

第 10862 行

fn appendErrorNodeNotes( astgen: *AstGen, node: Ast.Node.Index, comptime format: []const u8, args: anytype, notes: []const u32, ) Allocator.Error!void

参数

astgen: *AstGen
node: Ast.Node.Index
format: []const u8
notes: []const u32

错误

OutOfMemory

std.zig.AstGen.appendErrorTok

函数

第 10910 行

fn appendErrorTok( astgen: *AstGen, token: Ast.TokenIndex, comptime format: []const u8, args: anytype, ) !void

参数

astgen: *AstGen
token: Ast.TokenIndex
format: []const u8

std.zig.AstGen.appendErrorTokNotes

函数

第 10930 行

fn appendErrorTokNotes( astgen: *AstGen, token: Ast.TokenIndex, comptime format: []const u8, args: anytype, notes: []const u32, ) !void

参数

astgen: *AstGen
token: Ast.TokenIndex
format: []const u8
notes: []const u32

std.zig.AstGen.appendErrorTokNotesOff

函数

第 10953 行

fn appendErrorTokNotesOff( astgen: *AstGen, token: Ast.TokenIndex, byte_offset: u32, comptime format: []const u8, args: anytype, notes: []const u32, ) !void

参数

astgen: *AstGen
token: Ast.TokenIndex
byte_offset: u32
format: []const u8
notes: []const u32

std.zig.AstGen.appendIdentStr

函数

第 10789 行

给定标识符词法标记,获取其字符串;若使用 @"" 语法,可能需要将其作为 字符串字面量解析。将所得字符串追加到 buf。 另见 identifierTokenString 和 parseStrLit。

fn appendIdentStr( astgen: *AstGen, token: Ast.TokenIndex, buf: *ArrayList(u8), ) InnerError!void

参数

astgen: *AstGen
token: Ast.TokenIndex
buf: *ArrayList(u8)

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.appendPlaceholder

函数

第 13254 行

fn appendPlaceholder(astgen: *AstGen) Allocator.Error!Zir.Inst.Index

参数

astgen: *AstGen

错误

OutOfMemory

std.zig.AstGen.appendPossiblyRefdBodyInst

函数

第 13297 行

fn appendPossiblyRefdBodyInst( astgen: *AstGen, list: *std.ArrayList(u32), body_inst: Zir.Inst.Index, ) void

参数

astgen: *AstGen
list: *std.ArrayList(u32)
body_inst: Zir.Inst.Index

std.zig.AstGen.appendRefs

函数

第 135 行

fn appendRefs(astgen: *AstGen, refs: []const Zir.Inst.Ref) !void

参数

astgen: *AstGen
refs: []const Zir.Inst.Ref

std.zig.AstGen.appendRefsAssumeCapacity

函数

第 139 行

fn appendRefsAssumeCapacity(astgen: *AstGen, refs: []const Zir.Inst.Ref) void

参数

astgen: *AstGen
refs: []const Zir.Inst.Ref

std.zig.AstGen.arrayAccess

函数

第 6058 行

fn arrayAccess( gz: *GenZir, scope: *Scope, ri: ResultInfo, node: Ast.Node.Index, ) InnerError!Zir.Inst.Ref

参数

gz: *GenZir
scope: *Scope
ri: ResultInfo
node: Ast.Node.Index

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.arrayInitExpr

函数

第 1444 行

fn arrayInitExpr( gz: *GenZir, scope: *Scope, ri: ResultInfo, node: Ast.Node.Index, array_init: Ast.full.ArrayInit, ) InnerError!Zir.Inst.Ref

参数

gz: *GenZir
scope: *Scope
ri: ResultInfo
node: Ast.Node.Index
array_init: Ast.full.ArrayInit

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.arrayInitExprAnon

函数

第 1591 行

使用 array_init_anon 指令的数组初始化表达式。

fn arrayInitExprAnon( gz: *GenZir, scope: *Scope, node: Ast.Node.Index, elements: []const Ast.Node.Index, ) InnerError!Zir.Inst.Ref

参数

gz: *GenZir
scope: *Scope
node: Ast.Node.Index
elements: []const Ast.Node.Index

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.arrayInitExprPtr

函数

第 1660 行

使用元素指针的数组初始化表达式。

fn arrayInitExprPtr( gz: *GenZir, scope: *Scope, node: Ast.Node.Index, elements: []const Ast.Node.Index, ptr_inst: Zir.Inst.Ref, ) InnerError!void

参数

gz: *GenZir
scope: *Scope
node: Ast.Node.Index
elements: []const Ast.Node.Index
ptr_inst: Zir.Inst.Ref

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.arrayInitExprTyped

函数

第 1613 行

使用 array_init 或 array_init_ref 指令的数组初始化表达式。

fn arrayInitExprTyped( gz: *GenZir, scope: *Scope, node: Ast.Node.Index, elements: []const Ast.Node.Index, ty_inst: Zir.Inst.Ref, maybe_elem_ty_inst: Zir.Inst.Ref, is_ref: bool, ) InnerError!Zir.Inst.Ref

参数

gz: *GenZir
scope: *Scope
node: Ast.Node.Index
elements: []const Ast.Node.Index
ty_inst: Zir.Inst.Ref
maybe_elem_ty_inst: Zir.Inst.Ref
is_ref: bool

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.ArrayList

别名

第 9 行

别名目标 std.ArrayList

std.zig.AstGen.arrayType

函数

第 3875 行

fn arrayType(gz: *GenZir, scope: *Scope, ri: ResultInfo, node: Ast.Node.Index) !Zir.Inst.Ref

参数

gz: *GenZir
scope: *Scope
ri: ResultInfo
node: Ast.Node.Index

std.zig.AstGen.arrayTypeSentinel

函数

第 3895 行

fn arrayTypeSentinel(gz: *GenZir, scope: *Scope, ri: ResultInfo, node: Ast.Node.Index) !Zir.Inst.Ref

参数

gz: *GenZir
scope: *Scope
ri: ResultInfo
node: Ast.Node.Index

std.zig.AstGen.as

函数

第 8756 行

fn as( gz: *GenZir, scope: *Scope, ri: ResultInfo, node: Ast.Node.Index, lhs: Ast.Node.Index, rhs: Ast.Node.Index, ) InnerError!Zir.Inst.Ref

参数

gz: *GenZir
scope: *Scope
ri: ResultInfo
node: Ast.Node.Index
lhs: Ast.Node.Index
rhs: Ast.Node.Index

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.asmExpr

函数

第 8638 行

fn asmExpr( gz: *GenZir, scope: *Scope, ri: ResultInfo, node: Ast.Node.Index, full: Ast.full.Asm, ) InnerError!Zir.Inst.Ref

参数

gz: *GenZir
scope: *Scope
ri: ResultInfo
node: Ast.Node.Index
full: Ast.full.Asm

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.assert

别名

第 8 行

别名目标 std.debug.assert

std.zig.AstGen.assign

函数

第 3355 行

fn assign(gz: *GenZir, scope: *Scope, infix_node: Ast.Node.Index) InnerError!void

参数

gz: *GenZir
scope: *Scope
infix_node: Ast.Node.Index

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.assignDestructure

函数

第 3377 行

处理左侧均不为 const 或 var 声明的解构赋值。

fn assignDestructure(gz: *GenZir, scope: *Scope, node: Ast.Node.Index) InnerError!void

参数

gz: *GenZir
scope: *Scope
node: Ast.Node.Index

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.assignDestructureMaybeDecls

函数

第 3428 行

处理左侧可能包含 const 或 var 声明的解构赋值。

fn assignDestructureMaybeDecls( gz: *GenZir, scope: *Scope, node: Ast.Node.Index, block_arena: Allocator, ) InnerError!*Scope

参数

gz: *GenZir
scope: *Scope
node: Ast.Node.Index
block_arena: Allocator

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.assignOp

函数

第 3658 行

fn assignOp( gz: *GenZir, scope: *Scope, infix_node: Ast.Node.Index, op_inst_tag: Zir.Inst.Tag, ) InnerError!void

参数

gz: *GenZir
scope: *Scope
infix_node: Ast.Node.Index
op_inst_tag: Zir.Inst.Tag

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.assignShift

函数

第 3713 行

fn assignShift( gz: *GenZir, scope: *Scope, infix_node: Ast.Node.Index, op_inst_tag: Zir.Inst.Tag, ) InnerError!void

参数

gz: *GenZir
scope: *Scope
infix_node: Ast.Node.Index
op_inst_tag: Zir.Inst.Tag

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.assignShiftSat

函数

第 3739 行

fn assignShiftSat(gz: *GenZir, scope: *Scope, infix_node: Ast.Node.Index) InnerError!void

参数

gz: *GenZir
scope: *Scope
infix_node: Ast.Node.Index

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.Ast

别名

第 5 行

别名目标 std.zig.Ast

std.zig.AstGen.AstGen

别名

第 2 行

别名目标 std.zig.AstGen

std.zig.AstGen.AstRlAnnotate

别名

第 17 行

别名目标 std.zig.AstRlAnnotate

std.zig.AstGen.bitBuiltin

函数

第 9935 行

fn bitBuiltin( gz: *GenZir, scope: *Scope, ri: ResultInfo, node: Ast.Node.Index, operand_node: Ast.Node.Index, tag: Zir.Inst.Tag, ) InnerError!Zir.Inst.Ref

参数

gz: *GenZir
scope: *Scope
ri: ResultInfo
node: Ast.Node.Index
operand_node: Ast.Node.Index
tag: Zir.Inst.Tag

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.bitCast

函数

第 8791 行

fn bitCast( gz: *GenZir, scope: *Scope, ri: ResultInfo, node: Ast.Node.Index, operand_node: Ast.Node.Index, ) InnerError!Zir.Inst.Ref

参数

gz: *GenZir
scope: *Scope
ri: ResultInfo
node: Ast.Node.Index
operand_node: Ast.Node.Index

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.blockExpr

函数

第 2408 行

fn blockExpr( gz: *GenZir, scope: *Scope, ri: ResultInfo, block_node: Ast.Node.Index, statements: []const Ast.Node.Index, kind: BlockKind, ) InnerError!Zir.Inst.Ref

参数

gz: *GenZir
scope: *Scope
ri: ResultInfo
block_node: Ast.Node.Index
statements: []const Ast.Node.Index
kind: BlockKind

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.blockExprStmts

函数

第 2553 行

fn blockExprStmts(gz: *GenZir, parent_scope: *Scope, statements: []const Ast.Node.Index, block_kind: BlockKind) !void

参数

gz: *GenZir
parent_scope: *Scope
statements: []const Ast.Node.Index
block_kind: BlockKind

std.zig.AstGen.BlockKind

容器

第 2406 行

字段

normal
allow_branch_hint

std.zig.AstGen.boolBinOp

函数

第 6151 行

fn boolBinOp( gz: *GenZir, scope: *Scope, ri: ResultInfo, node: Ast.Node.Index, zir_tag: Zir.Inst.Tag, ) InnerError!Zir.Inst.Ref

参数

gz: *GenZir
scope: *Scope
ri: ResultInfo
node: Ast.Node.Index
zir_tag: Zir.Inst.Tag

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.breakExpr

函数

第 2170 行

fn breakExpr(parent_gz: *GenZir, parent_scope: *Scope, node: Ast.Node.Index) InnerError!Zir.Inst.Ref

参数

parent_gz: *GenZir
parent_scope: *Scope
node: Ast.Node.Index

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.builtinCall

函数

第 9040 行

fn builtinCall( gz: *GenZir, scope: *Scope, ri: ResultInfo, node: Ast.Node.Index, params: []const Ast.Node.Index, allow_branch_hint: bool, reify_name_strat: Zir.Inst.NameStrategy, ) InnerError!Zir.Inst.Ref

参数

gz: *GenZir
scope: *Scope
ri: ResultInfo
node: Ast.Node.Index
params: []const Ast.Node.Index
allow_branch_hint: bool
reify_name_strat: Zir.Inst.NameStrategy

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.BuiltinFn

别名

第 16 行

别名目标 std.zig.BuiltinFn

std.zig.AstGen.Callee

容器

第 10147 行

字段

field: struct {
    /// 指向所获取字段所属对象的*指针*,以便在第一个参数需要时,
    /// 能够将左值提升为地址。
    obj_ptr: Zir.Inst.Ref,
    /// `string_bytes` 中的偏移。
    field_name_start: Zir.NullTerminatedString,
}
direct: Zir.Inst.Ref

std.zig.AstGen.calleeExpr

函数

第 10163 行

calleeExpr 生成调用表达式的函数部分,即 f(x) 中的 f,而不是 @call() 内置函数的被调用方参数。 其目的是区分普通调用与方法调用语法 a.b()。因此,若左侧是字段访问,则使用 field 联合体字段返回;否则使用 direct 联合体字段。

fn calleeExpr( gz: *GenZir, scope: *Scope, call_rl: ResultInfo.Loc, override_decl_literal_type: Zir.Inst.Ref, node: Ast.Node.Index, ) InnerError!Callee

参数

gz: *GenZir
scope: *Scope
call_rl: ResultInfo.Loc
override_decl_literal_type: Zir.Inst.Ref

若此值不是 .none,且调用采用声明字面量形式(.foo(...)),则将此 类型作为声明字面量的结果类型,而非 call_rl 中的结果类型。

node: Ast.Node.Index

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.callExpr

函数

第 10033 行

fn callExpr( gz: *GenZir, scope: *Scope, ri: ResultInfo, override_decl_literal_type: Zir.Inst.Ref, node: Ast.Node.Index, call: Ast.full.Call, ) InnerError!Zir.Inst.Ref

参数

gz: *GenZir
scope: *Scope
ri: ResultInfo
override_decl_literal_type: Zir.Inst.Ref

若此项不为 .none,且调用采用声明字面量形式(.foo(...)),则使用 此类型作为声明字面量的结果类型,而非 ri.rl 中的结果类型。

node: Ast.Node.Index
call: Ast.full.Call

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.charLiteral

函数

第 8509 行

fn charLiteral(gz: *GenZir, ri: ResultInfo, node: Ast.Node.Index) InnerError!Zir.Inst.Ref

参数

gz: *GenZir
ri: ResultInfo
node: Ast.Node.Index

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.checkLabelRedefinition

函数

第 2454 行

fn checkLabelRedefinition(astgen: *AstGen, parent_scope: *Scope, label: Ast.TokenIndex) !void

参数

astgen: *AstGen
parent_scope: *Scope
label: Ast.TokenIndex

std.zig.AstGen.checkUsed

函数

第 3030 行

fn checkUsed(gz: *GenZir, outer_scope: *Scope, inner_scope: *Scope) InnerError!void

参数

gz: *GenZir
outer_scope: *Scope
inner_scope: *Scope

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.cmpxchg

函数

第 9912 行

fn cmpxchg( gz: *GenZir, scope: *Scope, ri: ResultInfo, node: Ast.Node.Index, params: []const Ast.Node.Index, small: u16, ) InnerError!Zir.Inst.Ref

参数

gz: *GenZir
scope: *Scope
ri: ResultInfo
node: Ast.Node.Index
params: []const Ast.Node.Index
small: u16

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.coerced_align_ri

常量

第 396 行

ResultInfo

std.zig.AstGen.coerced_bool_ri

常量

第 399 行

ResultInfo

std.zig.AstGen.coerced_linksection_ri

常量

第 397 行

ResultInfo

std.zig.AstGen.coerced_type_ri

常量

第 398 行

ResultInfo

std.zig.AstGen.ComptimeBlockInfo

容器

第 8119 行

字段

std.zig.AstGen.comptimeDecl

函数

第 4557 行

fn comptimeDecl( astgen: *AstGen, gz: *GenZir, scope: *Scope, wip_decls: *WipDecls, node: Ast.Node.Index, ) InnerError!void

参数

astgen: *AstGen
gz: *GenZir
scope: *Scope
wip_decls: *WipDecls
node: Ast.Node.Index

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.comptimeExpr

函数

第 1990 行

必要时通过包装 block_comptime,在编译期作用域中显式求值 expr。 需要强制在编译期求值某个内容,例如类型时, 都应使用此函数。 与 comptime 表达式语法对应的函数是 comptimeExprAst。

fn comptimeExpr( gz: *GenZir, scope: *Scope, ri: ResultInfo, node: Ast.Node.Index, reason: std.zig.SimpleComptimeReason, ) InnerError!Zir.Inst.Ref

参数

gz: *GenZir
scope: *Scope
ri: ResultInfo
node: Ast.Node.Index
reason: std.zig.SimpleComptimeReason

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.comptimeExpr2

函数

第 2002 行

类似 comptimeExpr,但区分要在编译期求值的 node 表达式, 以及要附加到 block_comptime 的 src_node 节点。

fn comptimeExpr2( gz: *GenZir, scope: *Scope, ri: ResultInfo, node: Ast.Node.Index, src_node: Ast.Node.Index, reason: std.zig.SimpleComptimeReason, ) InnerError!Zir.Inst.Ref

参数

gz: *GenZir
scope: *Scope
ri: ResultInfo
node: Ast.Node.Index
src_node: Ast.Node.Index
reason: std.zig.SimpleComptimeReason

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.comptimeExprAst

函数

第 2124 行

此项用于实际的 comptime 语法;若已知作用域在编译时求值, 则生成编译错误。 用于在编译时作用域中调用 expr 的辅助函数见 comptimeExpr。

fn comptimeExprAst( gz: *GenZir, scope: *Scope, ri: ResultInfo, node: Ast.Node.Index, ) InnerError!Zir.Inst.Ref

参数

gz: *GenZir
scope: *Scope
ri: ResultInfo
node: Ast.Node.Index

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.containerDecl

函数

第 5363 行

fn containerDecl( gz: *GenZir, scope: *Scope, ri: ResultInfo, node: Ast.Node.Index, container_decl: Ast.full.ContainerDecl, name_strat: Zir.Inst.NameStrategy, ) InnerError!Zir.Inst.Ref

参数

gz: *GenZir
scope: *Scope
ri: ResultInfo
node: Ast.Node.Index
container_decl: Ast.full.ContainerDecl
name_strat: Zir.Inst.NameStrategy

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.containerMember

函数

第 5635 行

fn containerMember( gz: *GenZir, scope: *Scope, wip_decls: *WipDecls, member_node: Ast.Node.Index, ) InnerError!ContainerMemberResult

参数

gz: *GenZir
scope: *Scope
wip_decls: *WipDecls
member_node: Ast.Node.Index

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.ContainerMemberResult

容器

第 5633 行

字段

decl
field: Ast.full.ContainerField

std.zig.AstGen.continueExpr

函数

第 2263 行

fn continueExpr(parent_gz: *GenZir, parent_scope: *Scope, node: Ast.Node.Index) InnerError!Zir.Inst.Ref

参数

parent_gz: *GenZir
parent_scope: *Scope
node: Ast.Node.Index

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.countBodyLenAfterFixups

函数

第 13308 行

fn countBodyLenAfterFixups(astgen: *AstGen, body: []const Zir.Inst.Index) u32

参数

astgen: *AstGen
body: []const Zir.Inst.Index

std.zig.AstGen.countBodyLenAfterFixupsExtraRefs

函数

第 13316 行

返回 body 中的指令数量,包含前置的 ref 指令,这些指令来自 ref_table。 除 body 中的全部指令外,还会前置 ref,对应于 extra_refs 中的任意指令。 例如,若某个索引已为子块保留特殊含义,必须将其传入 extra_refs,以确保正确添加该索引的 ref。

fn countBodyLenAfterFixupsExtraRefs(astgen: *AstGen, body: []const Zir.Inst.Index, extra_refs: []const Zir.Inst.Index) u32

参数

astgen: *AstGen
body: []const Zir.Inst.Index
extra_refs: []const Zir.Inst.Index

std.zig.AstGen.DeclarationName

容器

第 13455 行

字段

named: Ast.TokenIndex
named_test: Ast.TokenIndex
decltest: Ast.TokenIndex
unnamed_test
@"comptime"

std.zig.AstGen.deferStmt

函数

第 3071 行

fn deferStmt( gz: *GenZir, scope: *Scope, node: Ast.Node.Index, block_arena: Allocator, scope_tag: Scope.Tag, ) InnerError!*Scope

参数

gz: *GenZir
scope: *Scope
node: Ast.Node.Index
block_arena: Allocator
scope_tag: Scope.Tag

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.deinit

函数

第 256 行

fn deinit(astgen: *AstGen, gpa: Allocator) void

参数

astgen: *AstGen
gpa: Allocator

std.zig.AstGen.detectLocalShadowing

函数

第 12806 行

局部变量遮蔽检测,包括函数参数。

fn detectLocalShadowing( astgen: *AstGen, scope: *Scope, ident_name: Zir.NullTerminatedString, name_token: Ast.TokenIndex, ident_name_raw: []const u8, id_cat: Scope.IdCat, ) !void

参数

astgen: *AstGen
scope: *Scope
ident_name: Zir.NullTerminatedString
name_token: Ast.TokenIndex
ident_name_raw: []const u8
id_cat: Scope.IdCat

std.zig.AstGen.divBuiltin

函数

第 9948 行

fn divBuiltin( gz: *GenZir, scope: *Scope, ri: ResultInfo, node: Ast.Node.Index, lhs_node: Ast.Node.Index, rhs_node: Ast.Node.Index, tag: Zir.Inst.Tag, ) InnerError!Zir.Inst.Ref

参数

gz: *GenZir
scope: *Scope
ri: ResultInfo
node: Ast.Node.Index
lhs_node: Ast.Node.Index
rhs_node: Ast.Node.Index
tag: Zir.Inst.Tag

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.emitDbgNode

函数

第 3343 行

fn emitDbgNode(gz: *GenZir, node: Ast.Node.Index) !void

参数

gz: *GenZir
node: Ast.Node.Index

std.zig.AstGen.emitDbgStmt

函数

第 13335 行

fn emitDbgStmt(gz: *GenZir, lc: LineColumn) !void

参数

gz: *GenZir
lc: LineColumn

std.zig.AstGen.emitDbgStmtForceCurrentIndex

函数

第 13361 行

某些情况下,Sema 要求在紧挨下一条指令之前的指令 索引处生成 dbg_stmt(例如调用位于 %10 时, 期望 %9 处为 dbg_stmt)。TODO: 此逻辑可能产生冗余的 dbg_stmt 指令;应修正 Sema,使此逻辑不再必要!

fn emitDbgStmtForceCurrentIndex(gz: *GenZir, lc: LineColumn) !void

参数

gz: *GenZir
lc: LineColumn

std.zig.AstGen.errNoteNode

函数

第 11011 行

fn errNoteNode( astgen: *AstGen, node: Ast.Node.Index, comptime format: []const u8, args: anytype, ) Allocator.Error!u32

参数

astgen: *AstGen
node: Ast.Node.Index
format: []const u8

错误

OutOfMemory

std.zig.AstGen.errNoteTok

函数

第 10982 行

fn errNoteTok( astgen: *AstGen, token: Ast.TokenIndex, comptime format: []const u8, args: anytype, ) Allocator.Error!u32

参数

astgen: *AstGen
token: Ast.TokenIndex
format: []const u8

错误

OutOfMemory

std.zig.AstGen.errNoteTokOff

函数

第 10991 行

fn errNoteTokOff( astgen: *AstGen, token: Ast.TokenIndex, byte_offset: u32, comptime format: []const u8, args: anytype, ) Allocator.Error!u32

参数

astgen: *AstGen
token: Ast.TokenIndex
byte_offset: u32
format: []const u8

错误

OutOfMemory

std.zig.AstGen.errorSetDecl

函数

第 5745 行

fn errorSetDecl(gz: *GenZir, ri: ResultInfo, node: Ast.Node.Index) InnerError!Zir.Inst.Ref

参数

gz: *GenZir
ri: ResultInfo
node: Ast.Node.Index

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.expr

函数

第 639 行

将 Zig AST 转换为无类型 ZIR 指令。 当 rl 为 discard、ptr、inferred_ptr 或 inferred_ptr 时, 结果指令仅能用于检查是否为 isNoReturn(), 不得作任何其他用途。

fn expr(gz: *GenZir, scope: *Scope, ri: ResultInfo, node: Ast.Node.Index) InnerError!Zir.Inst.Ref

参数

gz: *GenZir
scope: *Scope
ri: ResultInfo
node: Ast.Node.Index

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.failNode

函数

第 10844 行

fn failNode( astgen: *AstGen, node: Ast.Node.Index, comptime format: []const u8, args: anytype, ) InnerError

参数

astgen: *AstGen
node: Ast.Node.Index
format: []const u8

std.zig.AstGen.failNodeNotes

函数

第 10890 行

fn failNodeNotes( astgen: *AstGen, node: Ast.Node.Index, comptime format: []const u8, args: anytype, notes: []const u32, ) InnerError

参数

astgen: *AstGen
node: Ast.Node.Index
format: []const u8
notes: []const u32

std.zig.AstGen.failOff

函数

第 10942 行

与 fail 相同,但会传入一个标记,以及相对于其起始字节偏移的偏移量。

fn failOff( astgen: *AstGen, token: Ast.TokenIndex, byte_offset: u32, comptime format: []const u8, args: anytype, ) InnerError

参数

astgen: *AstGen
token: Ast.TokenIndex
byte_offset: u32
format: []const u8

std.zig.AstGen.failTok

函数

第 10901 行

fn failTok( astgen: *AstGen, token: Ast.TokenIndex, comptime format: []const u8, args: anytype, ) InnerError

参数

astgen: *AstGen
token: Ast.TokenIndex
format: []const u8

std.zig.AstGen.failTokNotes

函数

第 10919 行

fn failTokNotes( astgen: *AstGen, token: Ast.TokenIndex, comptime format: []const u8, args: anytype, notes: []const u32, ) InnerError

参数

astgen: *AstGen
token: Ast.TokenIndex
format: []const u8
notes: []const u32

std.zig.AstGen.failWithNumberError

函数

第 8606 行

fn failWithNumberError(astgen: *AstGen, err: std.zig.number_literal.Error, token: Ast.TokenIndex, bytes: []const u8) InnerError

参数

astgen: *AstGen
err: std.zig.number_literal.Error
token: Ast.TokenIndex
bytes: []const u8

std.zig.AstGen.failWithStrLitError

函数

第 10833 行

fn failWithStrLitError( astgen: *AstGen, err: std.zig.string_literal.Error, token: Ast.TokenIndex, bytes: []const u8, offset: u32, ) InnerError

参数

astgen: *AstGen
err: std.zig.string_literal.Error
token: Ast.TokenIndex
bytes: []const u8
offset: u32

std.zig.AstGen.fetchRemoveRefEntries

函数

第 13688 行

给定指令列表,返回对其中任一原始指令执行 ref 的全部指令列表,来源为 astgen.ref_table,不递归搜索。条目会从 astgen.ref_table 移除,返回的切片随后可作为独立主体,将 ref 指令追加到不同于其通常所属主体的其他主体中。

这用于函数降级。极少数情况下,调用约定表达式、对齐表达式等可能通过 &param 引用函数参数;此时必须在调用约定、对齐等表达式主体中降级为 ref 指令,而不是放在声明主体中。然而,不会立即将这些主体追加到 extra,而是等到所有主体都求值到一个大型 GenZir 栈中之后才执行追加。因此,使用此函数提取每个主体中必须输出的 ref 指令。

fn fetchRemoveRefEntries(astgen: *AstGen, param_insts: []const Zir.Inst.Index) ![]Zir.Inst.Index

参数

astgen: *AstGen
param_insts: []const Zir.Inst.Index

std.zig.AstGen.fieldAccess

函数

第 6019 行

fn fieldAccess( gz: *GenZir, scope: *Scope, ri: ResultInfo, node: Ast.Node.Index, ) InnerError!Zir.Inst.Ref

参数

gz: *GenZir
scope: *Scope
ri: ResultInfo
node: Ast.Node.Index

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.floatRoundOp

函数

第 9834 行

fn floatRoundOp( gz: *GenZir, scope: *Scope, ri: ResultInfo, node: Ast.Node.Index, operand_node: Ast.Node.Index, float_tag: Zir.Inst.Tag, ) InnerError!Zir.Inst.Ref

参数

gz: *GenZir
scope: *Scope
ri: ResultInfo
node: Ast.Node.Index
operand_node: Ast.Node.Index
float_tag: Zir.Inst.Tag

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.floatUnOp

函数

第 9871 行

fn floatUnOp( gz: *GenZir, scope: *Scope, ri: ResultInfo, node: Ast.Node.Index, operand_node: Ast.Node.Index, tag: Zir.Inst.Tag, ) InnerError!Zir.Inst.Ref

参数

gz: *GenZir
scope: *Scope
ri: ResultInfo
node: Ast.Node.Index
operand_node: Ast.Node.Index
tag: Zir.Inst.Tag

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.fnDecl

函数

第 3985 行

fn fnDecl( astgen: *AstGen, gz: *GenZir, scope: *Scope, wip_decls: *WipDecls, decl_node: Ast.Node.Index, body_node: Ast.Node.OptionalIndex, fn_proto: Ast.full.FnProto, ) InnerError!void

参数

astgen: *AstGen
gz: *GenZir
scope: *Scope
wip_decls: *WipDecls
decl_node: Ast.Node.Index
body_node: Ast.Node.OptionalIndex
fn_proto: Ast.full.FnProto

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.fnDeclInner

函数

第 4144 行

fn fnDeclInner( astgen: *AstGen, decl_gz: *GenZir, scope: *Scope, decl_inst: Zir.Inst.Index, decl_node: Ast.Node.Index, body_node: Ast.Node.Index, fn_proto: Ast.full.FnProto, ) InnerError!void

参数

astgen: *AstGen
decl_gz: *GenZir
scope: *Scope
decl_inst: Zir.Inst.Index
decl_node: Ast.Node.Index
body_node: Ast.Node.Index
fn_proto: Ast.full.FnProto

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.fnProtoExpr

函数

第 1284 行

fn fnProtoExpr( gz: *GenZir, scope: *Scope, ri: ResultInfo, node: Ast.Node.Index, fn_proto: Ast.full.FnProto, ) InnerError!Zir.Inst.Ref

参数

gz: *GenZir
scope: *Scope
ri: ResultInfo
node: Ast.Node.Index
fn_proto: Ast.full.FnProto

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.fnProtoExprInner

函数

第 1326 行

fn fnProtoExprInner( gz: *GenZir, scope: *Scope, ri: ResultInfo, node: Ast.Node.Index, fn_proto: Ast.full.FnProto, implicit_ccc: bool, ) InnerError!Zir.Inst.Ref

参数

gz: *GenZir
scope: *Scope
ri: ResultInfo
node: Ast.Node.Index
fn_proto: Ast.full.FnProto
implicit_ccc: bool

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.forExpr

函数

第 6724 行

fn forExpr( parent_gz: *GenZir, scope: *Scope, ri: ResultInfo, node: Ast.Node.Index, for_full: Ast.full.For, is_statement: bool, ) InnerError!Zir.Inst.Ref

参数

parent_gz: *GenZir
scope: *Scope
ri: ResultInfo
node: Ast.Node.Index
for_full: Ast.full.For
is_statement: bool

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.fullBodyExpr

函数

第 2378 行

类似 expr,但用于 gz 对应的指令体 仅包含此节点代码的情况。与 expr 不同,如果 根表达式是无标签块,则不生成实际的块。 而是将块内容直接生成到 gz。

fn fullBodyExpr( gz: *GenZir, scope: *Scope, ri: ResultInfo, node: Ast.Node.Index, block_kind: BlockKind, ) InnerError!Zir.Inst.Ref

参数

gz: *GenZir
scope: *Scope
ri: ResultInfo
node: Ast.Node.Index
block_kind: BlockKind

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.genDefers

函数

第 2999 行

fn genDefers( gz: *GenZir, outer_scope: *Scope, inner_scope: *Scope, which_ones: enum { normal_only, normal_and_error }, ) InnerError!void

参数

gz: *GenZir
outer_scope: *Scope
inner_scope: *Scope
which_ones: enum { normal_only, normal_and_error }

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.generate

函数

第 143 行

pub fn generate(gpa: Allocator, tree: Ast) Allocator.Error!Zir

参数

gpa: Allocator
tree: Ast

错误

OutOfMemory

std.zig.AstGen.GenZir

容器

第 11291 行

这是临时结构;对其引用仅在构造 Zir 期间有效。

字段

base: Scope = Scope{ .tag = base_tag }
is_comptime: bool

是否已位于已知为编译时的作用域中。 只要知道 Sema 将以 is_comptime 分析当前块,就设置此值, 例如位于 struct_decl 或 block_comptime 内部时。

is_typeof: bool = false

当前是否位于 @TypeOf 操作数内的表达式中。此时允许捕获运行期变量,而通常情况下不允许。

is_inline: bool = false

对 block_inline 的 GenZir 将此值设为 true,表示 退出此块时应使用 break_inline,而非 break。

src_baseline: Ast.Node.Index

包含该声明的 AST 节点。

decl_line: u32

包含该声明的行索引,使用绝对索引。

parent: *Scope

父级可以为 LocalVal、LocalPtr、GenZir、Defer 或 Namespace。

astgen: *AstGen

同一 ZIR 的所有 GenZir 作用域共用此项。

instructions: *ArrayList(Zir.Inst.Index)

跟踪此作用域中的指令列表。可能被共享。 索引指向 astgen 中的指令。

instructions_top: usize

若使用严格嵌套,子块可与包含它的 GenZir 共享指令 ArrayList。 此处保存列表先前的大小,以便退出嵌套时恢复。

label: ?Label = null
allow_unlabeled_control_flow: bool = false

为 true 时,无标签的 break 和 continue 表达式可以指向此 GenZir。

break_target: Zir.Inst.Index = undefined

若 label 为 null 且 unlabeled_control_flow_target 为 false, 则此字段不使用,可为 undefined。 否则,当 break 指向此 GenZir 时, 此字段就是该 break 指令的目标。

continue_target: union(enum) {
    /// `continue` 不能指向此 `GenZir`;报告错误。
    none,
    /// 生成以此块为目标的 `break` 指令。
    @"break": Zir.Inst.Index,
    /// 输出指向此 `switch_block` 的 `switch_continue` 指令。
    switch_continue: Zir.Inst.Index,
} = undefined

若 label 为 null 且 unlabeled_control_flow_target 为 false, 则此字段未使用,可为 undefined。

break_result_info: AstGen.ResultInfo = undefined

仅在调用 setBreakResultInfo 时有效。

continue_result_info: AstGen.ResultInfo = undefined

若 continue_target 不是 switch_continue,则此项未使用,并可能为 undefined。

suspend_node: Ast.Node.OptionalIndex = .none
nosuspend_node: Ast.Node.OptionalIndex = .none
cur_defer_node: Ast.Node.OptionalIndex = .none

若此 GenZir 为延迟执行语句,则置位。

any_defer_node: Ast.Node.OptionalIndex = .none

std.zig.AstGen.GenZir.add

函数

第 12753 行

fn add(gz: *GenZir, inst: Zir.Inst) !Zir.Inst.Ref

参数

gz: *GenZir
inst: Zir.Inst

std.zig.AstGen.GenZir.addAllocExtended

函数

第 12310 行

fn addAllocExtended( gz: *GenZir, args: struct { node: Ast.Node.Index, type_inst: Zir.Inst.Ref, align_inst: Zir.Inst.Ref, is_const: bool, is_comptime: bool, }, ) !Zir.Inst.Ref

参数

gz: *GenZir
args: struct {
    /// 绝对节点索引。此函数将其转换为相对于 Decl 的偏移。
    node: Ast.Node.Index,
    type_inst: Zir.Inst.Ref,
    align_inst: Zir.Inst.Ref,
    is_const: bool,
    is_comptime: bool,
}

std.zig.AstGen.GenZir.addAsIndex

函数

第 12757 行

fn addAsIndex(gz: *GenZir, inst: Zir.Inst) !Zir.Inst.Index

参数

gz: *GenZir
inst: Zir.Inst

std.zig.AstGen.GenZir.addAsm

函数

第 12361 行

fn addAsm( gz: *GenZir, args: struct { tag: Zir.Inst.Extended, node: Ast.Node.Index, asm_source: Zir.NullTerminatedString, output_type_bits: u32, is_volatile: bool, outputs: []const Zir.Inst.Asm.Output, inputs: []const Zir.Inst.Asm.Input, clobbers: Zir.Inst.Ref, }, ) !Zir.Inst.Ref

参数

gz: *GenZir
args: struct {
    tag: Zir.Inst.Extended,
    /// 绝对节点索引。此函数将其转换为相对于 Decl 的偏移。
    node: Ast.Node.Index,
    asm_source: Zir.NullTerminatedString,
    output_type_bits: u32,
    is_volatile: bool,
    outputs: []const Zir.Inst.Asm.Output,
    inputs: []const Zir.Inst.Asm.Input,
    clobbers: Zir.Inst.Ref,
}

std.zig.AstGen.GenZir.addBin

函数

第 12224 行

fn addBin( gz: *GenZir, tag: Zir.Inst.Tag, lhs: Zir.Inst.Ref, rhs: Zir.Inst.Ref, ) !Zir.Inst.Ref

参数

gz: *GenZir
tag: Zir.Inst.Tag
lhs: Zir.Inst.Ref
rhs: Zir.Inst.Ref

std.zig.AstGen.GenZir.addBreak

函数

第 12148 行

fn addBreak( gz: *GenZir, tag: Zir.Inst.Tag, block_inst: Zir.Inst.Index, operand: Zir.Inst.Ref, ) !Zir.Inst.Index

参数

gz: *GenZir
tag: Zir.Inst.Tag
block_inst: Zir.Inst.Index
operand: Zir.Inst.Ref

std.zig.AstGen.GenZir.addBreakWithSrcNode

函数

第 12171 行

fn addBreakWithSrcNode( gz: *GenZir, tag: Zir.Inst.Tag, block_inst: Zir.Inst.Index, operand: Zir.Inst.Ref, operand_src_node: Ast.Node.Index, ) !Zir.Inst.Index

参数

gz: *GenZir
tag: Zir.Inst.Tag
block_inst: Zir.Inst.Index
operand: Zir.Inst.Ref
operand_src_node: Ast.Node.Index

std.zig.AstGen.GenZir.addCondBr

函数

第 12449 行

注意,返回的是 Zir.Inst.Index,而非引用。 使 payload_index 字段保持未定义。

fn addCondBr(gz: *GenZir, tag: Zir.Inst.Tag, node: Ast.Node.Index) !Zir.Inst.Index

参数

gz: *GenZir
tag: Zir.Inst.Tag
node: Ast.Node.Index

std.zig.AstGen.GenZir.addDbgVar

函数

第 12787 行

fn addDbgVar(gz: *GenZir, tag: Zir.Inst.Tag, name: Zir.NullTerminatedString, inst: Zir.Inst.Ref) !void

参数

std.zig.AstGen.GenZir.addDecl

函数

第 12251 行

fn addDecl( gz: *GenZir, tag: Zir.Inst.Tag, decl_index: u32, src_node: Ast.Node.Index, ) !Zir.Inst.Ref

参数

gz: *GenZir
tag: Zir.Inst.Tag
decl_index: u32
src_node: Ast.Node.Index

std.zig.AstGen.GenZir.addDefer

函数

第 12241 行

fn addDefer(gz: *GenZir, index: u32, len: u32) !void

参数

gz: *GenZir
index: u32
len: u32

std.zig.AstGen.GenZir.addExtendedMultiOp

函数

第 11951 行

fn addExtendedMultiOp( gz: *GenZir, opcode: Zir.Inst.Extended, node: Ast.Node.Index, operands: []const Zir.Inst.Ref, ) !Zir.Inst.Ref

参数

gz: *GenZir
opcode: Zir.Inst.Extended
node: Ast.Node.Index
operands: []const Zir.Inst.Ref

std.zig.AstGen.GenZir.addExtendedMultiOpPayloadIndex

函数

第 11984 行

fn addExtendedMultiOpPayloadIndex( gz: *GenZir, opcode: Zir.Inst.Extended, payload_index: u32, trailing_len: usize, ) !Zir.Inst.Ref

参数

gz: *GenZir
opcode: Zir.Inst.Extended
payload_index: u32
trailing_len: usize

std.zig.AstGen.GenZir.addExtendedNodeSmall

函数

第 12008 行

fn addExtendedNodeSmall( gz: *GenZir, opcode: Zir.Inst.Extended, src_node: Ast.Node.Index, small: u16, ) !Zir.Inst.Ref

参数

gz: *GenZir
opcode: Zir.Inst.Extended
src_node: Ast.Node.Index
small: u16

std.zig.AstGen.GenZir.addExtendedPayload

函数

第 11922 行

fn addExtendedPayload(gz: *GenZir, opcode: Zir.Inst.Extended, extra: anytype) !Zir.Inst.Ref

参数

gz: *GenZir
opcode: Zir.Inst.Extended

std.zig.AstGen.GenZir.addExtendedPayloadSmall

函数

第 11926 行

fn addExtendedPayloadSmall( gz: *GenZir, opcode: Zir.Inst.Extended, small: u16, extra: anytype, ) !Zir.Inst.Ref

参数

gz: *GenZir
opcode: Zir.Inst.Extended
small: u16

std.zig.AstGen.GenZir.addFloat

函数

第 11794 行

fn addFloat(gz: *GenZir, number: f64) !Zir.Inst.Ref

参数

gz: *GenZir
number: f64

std.zig.AstGen.GenZir.addFunc

函数

第 11552 行

调用时栈须按以下顺序设置:

  • gz(栈底)
  • cc_gz
  • ret_gz
  • body_gz(栈顶) 除 gz 外,所有这些项都会出栈。
fn addFunc( gz: *GenZir, args: struct { src_node: Ast.Node.Index, lbrace_line: u32 = 0, lbrace_column: u32 = 0, param_block: Zir.Inst.Index, ret_gz: ?*GenZir, body_gz: ?*GenZir, cc_gz: ?*GenZir, ret_param_refs: []Zir.Inst.Index, param_insts: []Zir.Inst.Index,ret_ty_is_generic: bool, cc_ref: Zir.Inst.Ref, ret_ref: Zir.Inst.Ref, noalias_bits: u32, is_var_args: bool, is_inferred_error: bool, is_noinline: bool, proto_hash: std.zig.SrcHash, }, ) !Zir.Inst.Ref

参数

gz: *GenZir
args: struct {
    src_node: Ast.Node.Index,
    lbrace_line: u32 = 0,
    lbrace_column: u32 = 0,
    param_block: Zir.Inst.Index,

    ret_gz: ?*GenZir,
    body_gz: ?*GenZir,
    cc_gz: ?*GenZir,

    ret_param_refs: []Zir.Inst.Index,
    param_insts: []Zir.Inst.Index, // `body_gz` 中对参数的引用仍应位于 `astgen.ref_table` 中
    ret_ty_is_generic: bool,

    cc_ref: Zir.Inst.Ref,
    ret_ref: Zir.Inst.Ref,

    noalias_bits: u32,
    is_var_args: bool,
    is_inferred_error: bool,
    is_noinline: bool,

    /// `body_gz == null` 时忽略。
    proto_hash: std.zig.SrcHash,
}

std.zig.AstGen.GenZir.addInstNode

函数

第 12278 行

fn addInstNode( gz: *GenZir, tag: Zir.Inst.Tag, inst: Zir.Inst.Index, src_node: Ast.Node.Index, ) !Zir.Inst.Ref

参数

gz: *GenZir
tag: Zir.Inst.Tag
inst: Zir.Inst.Index
src_node: Ast.Node.Index

绝对节点索引。此函数将其转换为相对于 Decl 的偏移。

std.zig.AstGen.GenZir.addInt

函数

第 11767 行

fn addInt(gz: *GenZir, integer: u64) !Zir.Inst.Ref

参数

gz: *GenZir
integer: u64

std.zig.AstGen.GenZir.addIntBig

函数

第 11774 行

fn addIntBig(gz: *GenZir, limbs: []const std.math.big.Limb) !Zir.Inst.Ref

参数

gz: *GenZir
limbs: []const std.math.big.Limb

std.zig.AstGen.GenZir.addNode

函数

第 12266 行

fn addNode( gz: *GenZir, tag: Zir.Inst.Tag, src_node: Ast.Node.Index, ) !Zir.Inst.Ref

参数

gz: *GenZir
tag: Zir.Inst.Tag
src_node: Ast.Node.Index

绝对节点索引。此函数将其转换为相对于 Decl 的偏移。

std.zig.AstGen.GenZir.addNodeExtended

函数

第 12294 行

fn addNodeExtended( gz: *GenZir, opcode: Zir.Inst.Extended, src_node: Ast.Node.Index, ) !Zir.Inst.Ref

参数

gz: *GenZir
opcode: Zir.Inst.Extended
src_node: Ast.Node.Index

绝对节点索引。此函数将其转换为相对于 Decl 的偏移。

std.zig.AstGen.GenZir.addParam

函数

第 11878 行

支持将 param_gz 叠加在 gz 上。假定 param_gz 上未叠加任何内容。弹出 param_gz。

fn addParam( gz: *GenZir, param_gz: *GenZir, prev_param_insts: []const Zir.Inst.Index, ty_is_generic: bool, tag: Zir.Inst.Tag, abs_tok_index: Ast.TokenIndex, name: Zir.NullTerminatedString, ) !Zir.Inst.Index

参数

gz: *GenZir
param_gz: *GenZir
prev_param_insts: []const Zir.Inst.Index

此前的参数,可能在 param_gz(新参数类型)中被引用。 这些指令的 ref 会放入此参数的类型体,并从 AstGen.ref_table 中移除。

ty_is_generic: bool
tag: Zir.Inst.Tag
abs_tok_index: Ast.TokenIndex

绝对词法标记索引。此函数负责转换为 Decl 偏移量。

name: Zir.NullTerminatedString

std.zig.AstGen.GenZir.addPlNode

函数

第 11837 行

fn addPlNode( gz: *GenZir, tag: Zir.Inst.Tag, src_node: Ast.Node.Index, extra: anytype, ) !Zir.Inst.Ref

参数

gz: *GenZir
tag: Zir.Inst.Tag
src_node: Ast.Node.Index

绝对节点索引。此函数将其转换为相对于 Decl 的偏移。

std.zig.AstGen.GenZir.addPlNodePayloadIndex

函数

第 11861 行

fn addPlNodePayloadIndex( gz: *GenZir, tag: Zir.Inst.Tag, src_node: Ast.Node.Index, payload_index: u32, ) !Zir.Inst.Ref

参数

gz: *GenZir
tag: Zir.Inst.Tag
src_node: Ast.Node.Index

绝对节点索引。此函数将其转换为相对于 Decl 的偏移。

payload_index: u32

std.zig.AstGen.GenZir.addRestoreErrRetIndex

函数

第 12108 行

fn addRestoreErrRetIndex( gz: *GenZir, bt: BranchTarget, cond: union(enum) { always: void, if_non_error: Zir.Inst.Ref, }, src_node: Ast.Node.Index, ) !Zir.Inst.Index

参数

gz: *GenZir
bt: BranchTarget
cond: union(enum) {
    always: void,
    if_non_error: Zir.Inst.Ref,
}
src_node: Ast.Node.Index

std.zig.AstGen.GenZir.addRet

函数

第 12779 行

fn addRet(gz: *GenZir, ri: ResultInfo, operand: Zir.Inst.Ref, node: Ast.Node.Index) !void

参数

gz: *GenZir
ri: ResultInfo
operand: Zir.Inst.Ref
node: Ast.Node.Index

std.zig.AstGen.GenZir.addSaveErrRetIndex

函数

第 12085 行

fn addSaveErrRetIndex( gz: *GenZir, cond: union(enum) { always: void, if_of_error_type: Zir.Inst.Ref, }, ) !Zir.Inst.Index

参数

gz: *GenZir
cond: union(enum) {
    always: void,
    if_of_error_type: Zir.Inst.Ref,
}

std.zig.AstGen.GenZir.addStdLangValue

函数

第 11918 行

fn addStdLangValue(gz: *GenZir, src_node: Ast.Node.Index, val: Zir.Inst.StdLangValue) !Zir.Inst.Ref

参数

gz: *GenZir
src_node: Ast.Node.Index
val: Zir.Inst.StdLangValue

std.zig.AstGen.GenZir.addStrTok

函数

第 12069 行

fn addStrTok( gz: *GenZir, tag: Zir.Inst.Tag, str_index: Zir.NullTerminatedString, abs_tok_index: Ast.TokenIndex, ) !Zir.Inst.Ref

参数

gz: *GenZir
tag: Zir.Inst.Tag
str_index: Zir.NullTerminatedString
abs_tok_index: Ast.TokenIndex

绝对词法标记索引。此函数负责转换为 Decl 偏移量。

std.zig.AstGen.GenZir.addUnNode

函数

第 11801 行

fn addUnNode( gz: *GenZir, tag: Zir.Inst.Tag, operand: Zir.Inst.Ref, src_node: Ast.Node.Index, ) !Zir.Inst.Ref

参数

gz: *GenZir
tag: Zir.Inst.Tag
operand: Zir.Inst.Ref
src_node: Ast.Node.Index

绝对节点索引。此函数将其转换为相对于 Decl 的偏移。

std.zig.AstGen.GenZir.addUnTok

函数

第 12032 行

fn addUnTok( gz: *GenZir, tag: Zir.Inst.Tag, operand: Zir.Inst.Ref, abs_tok_index: Ast.TokenIndex, ) !Zir.Inst.Ref

参数

gz: *GenZir
tag: Zir.Inst.Tag
operand: Zir.Inst.Ref
abs_tok_index: Ast.TokenIndex

绝对词法标记索引。此函数负责转换为 Decl 偏移量。

std.zig.AstGen.GenZir.base_tag

常量

第 11292 行

Scope.Tag

std.zig.AstGen.GenZir.BranchTarget

容器

第 12103 行

字段

ret
block: Zir.Inst.Index

std.zig.AstGen.GenZir.endsWithNoReturn

函数

第 11410 行

假定 gz 上方没有其他堆叠项。

fn endsWithNoReturn(gz: GenZir) bool

参数

gz: GenZir

std.zig.AstGen.GenZir.fancyFnExprExtraLen

函数

第 11760 行

fn fancyFnExprExtraLen(astgen: *AstGen, param_refs_body: []const Zir.Inst.Index, main_body: []const Zir.Inst.Index, ref: Zir.Inst.Ref) u32

参数

astgen: *AstGen
param_refs_body: []const Zir.Inst.Index
main_body: []const Zir.Inst.Index
ref: Zir.Inst.Ref

std.zig.AstGen.GenZir.instructionsSlice

函数

第 11363 行

fn instructionsSlice(self: *const GenZir) []Zir.Inst.Index

参数

self: *const GenZir

std.zig.AstGen.GenZir.instructionsSliceUpto

函数

第 11370 行

fn instructionsSliceUpto(self: *const GenZir, stacked_gz: *GenZir) []Zir.Inst.Index

参数

self: *const GenZir
stacked_gz: *GenZir

std.zig.AstGen.GenZir.instructionsSliceUptoOpt

函数

第 11379 行

fn instructionsSliceUptoOpt(gz: *const GenZir, maybe_stacked_gz: ?*GenZir) []Zir.Inst.Index

参数

gz: *const GenZir
maybe_stacked_gz: ?*GenZir

std.zig.AstGen.GenZir.isEmpty

函数

第 11358 行

fn isEmpty(self: *const GenZir) bool

参数

self: *const GenZir

std.zig.AstGen.GenZir.Label

容器

第 11403 行

字段

token: Ast.TokenIndex
used: bool = false
used_for_continue: bool = false

std.zig.AstGen.GenZir.makeBlockInst

函数

第 12419 行

注意,返回的是 Zir.Inst.Index,而非引用。 不会将块指令追加到作用域。 使 payload_index 字段保持未定义。

fn makeBlockInst(gz: *GenZir, tag: Zir.Inst.Tag, node: Ast.Node.Index) !Zir.Inst.Index

参数

gz: *GenZir
tag: Zir.Inst.Tag
node: Ast.Node.Index

std.zig.AstGen.GenZir.makeBreak

函数

第 12162 行

fn makeBreak( gz: *GenZir, tag: Zir.Inst.Tag, block_inst: Zir.Inst.Index, operand: Zir.Inst.Ref, ) !Zir.Inst.Index

参数

gz: *GenZir
tag: Zir.Inst.Tag
block_inst: Zir.Inst.Index
operand: Zir.Inst.Ref

std.zig.AstGen.GenZir.makeBreakCommon

函数

第 12196 行

fn makeBreakCommon( gz: *GenZir, tag: Zir.Inst.Tag, block_inst: Zir.Inst.Index, operand: Zir.Inst.Ref, operand_src_node: ?Ast.Node.Index, ) !Zir.Inst.Index

参数

gz: *GenZir
tag: Zir.Inst.Tag
block_inst: Zir.Inst.Index
operand: Zir.Inst.Ref
operand_src_node: ?Ast.Node.Index

std.zig.AstGen.GenZir.makeBreakWithSrcNode

函数

第 12186 行

fn makeBreakWithSrcNode( gz: *GenZir, tag: Zir.Inst.Tag, block_inst: Zir.Inst.Index, operand: Zir.Inst.Ref, operand_src_node: Ast.Node.Index, ) !Zir.Inst.Index

参数

gz: *GenZir
tag: Zir.Inst.Tag
block_inst: Zir.Inst.Index
operand: Zir.Inst.Ref
operand_src_node: Ast.Node.Index

std.zig.AstGen.GenZir.makeDeclaration

函数

第 12435 行

注意,此处返回 Zir.Inst.Index,而非 ref。 不会将块指令追加到作用域。 将 payload_index 字段保持为未定义。用 setDeclaration 完成设置。

fn makeDeclaration(gz: *GenZir, node: Ast.Node.Index) !Zir.Inst.Index

参数

gz: *GenZir
node: Ast.Node.Index

std.zig.AstGen.GenZir.makeSubBlock

函数

第 11387 行

fn makeSubBlock(gz: *GenZir, scope: *Scope) GenZir

参数

gz: *GenZir
scope: *Scope

std.zig.AstGen.GenZir.makeUnNode

函数

第 11818 行

fn makeUnNode( gz: *GenZir, tag: Zir.Inst.Tag, operand: Zir.Inst.Ref, src_node: Ast.Node.Index, ) !Zir.Inst.Index

参数

gz: *GenZir
tag: Zir.Inst.Tag
operand: Zir.Inst.Ref
src_node: Ast.Node.Index

绝对节点索引。此函数将其转换为相对于 Decl 的偏移。

std.zig.AstGen.GenZir.makeUnTok

函数

第 12049 行

fn makeUnTok( gz: *GenZir, tag: Zir.Inst.Tag, operand: Zir.Inst.Ref, abs_tok_index: Ast.TokenIndex, ) !Zir.Inst.Index

参数

gz: *GenZir
tag: Zir.Inst.Tag
operand: Zir.Inst.Ref
abs_tok_index: Ast.TokenIndex

绝对词法标记索引。此函数负责转换为 Decl 偏移量。

std.zig.AstGen.GenZir.nodeIndexToRelative

函数

第 11426 行

fn nodeIndexToRelative(gz: GenZir, node_index: Ast.Node.Index) Ast.Node.Offset

参数

gz: GenZir
node_index: Ast.Node.Index

std.zig.AstGen.GenZir.refIsNoReturn

函数

第 11418 行

TODO: 此项的所有用法均应替换为 endsWithNoReturn。

fn refIsNoReturn(gz: GenZir, inst_ref: Zir.Inst.Ref) bool

参数

gz: GenZir
inst_ref: Zir.Inst.Ref

std.zig.AstGen.GenZir.reserveInstructionIndex

函数

第 12768 行

fn reserveInstructionIndex(gz: *GenZir) !Zir.Inst.Index

参数

gz: *GenZir

std.zig.AstGen.GenZir.setBlockBody

函数

第 11478 行

假定 gz 上未叠加任何内容。弹出 gz。 断言 inst 不是 block_comptime。

fn setBlockBody(gz: *GenZir, inst: Zir.Inst.Index) !void

参数

gz: *GenZir
inst: Zir.Inst.Index

std.zig.AstGen.GenZir.setBlockComptimeBody

函数

第 11501 行

假定 gz 上没有压入任何内容。弹出 gz。 断言 inst 是 block_comptime。

fn setBlockComptimeBody(gz: *GenZir, inst: Zir.Inst.Index, comptime_reason: std.zig.SimpleComptimeReason) !void

参数

gz: *GenZir
inst: Zir.Inst.Index
comptime_reason: std.zig.SimpleComptimeReason

std.zig.AstGen.GenZir.setBoolBrBody

函数

第 11458 行

假定 gz 上没有压入任何内容。弹出 gz。

fn setBoolBrBody(gz: *GenZir, bool_br: Zir.Inst.Index, bool_br_lhs: Zir.Inst.Ref) !void

参数

gz: *GenZir
bool_br: Zir.Inst.Index
bool_br_lhs: Zir.Inst.Ref

std.zig.AstGen.GenZir.setBreakResultInfo

函数

第 11434 行

fn setBreakResultInfo(gz: *GenZir, parent_ri: AstGen.ResultInfo) void

参数

gz: *GenZir
parent_ri: AstGen.ResultInfo

std.zig.AstGen.GenZir.setEnum

函数

第 12628 行

fn setEnum(gz: *GenZir, inst: Zir.Inst.Index, args: struct { src_line: u32, src_column: u32, src_node: Ast.Node.Index, name_strat: Zir.Inst.NameStrategy, arg_baseline_src_node: Ast.Node.OptionalIndex, fields_baseline_src_node: Ast.Node.OptionalIndex, tag_type_body_len: ?u32, nonexhaustive: bool, decls_len: u32, fields_len: u32, any_field_values: bool, fields_hash: std.zig.SrcHash, captures: []const Zir.Inst.Capture, capture_names: []const Zir.NullTerminatedString, remaining: []const u32, }) !void

参数

gz: *GenZir
inst: Zir.Inst.Index
args: struct {
    src_line: u32,
    src_column: u32,
    src_node: Ast.Node.Index,
    name_strat: Zir.Inst.NameStrategy,
    arg_baseline_src_node: Ast.Node.OptionalIndex,
    fields_baseline_src_node: Ast.Node.OptionalIndex,
    tag_type_body_len: ?u32,
    nonexhaustive: bool,
    decls_len: u32,
    fields_len: u32,
    any_field_values: bool,
    fields_hash: std.zig.SrcHash,
    captures: []const Zir.Inst.Capture,
    capture_names: []const Zir.NullTerminatedString,
    /// 尾随的声明列表、字段信息及体指令。
    remaining: []const u32,
}

std.zig.AstGen.GenZir.setOpaque

函数

第 12705 行

fn setOpaque(gz: *GenZir, inst: Zir.Inst.Index, args: struct { src_line: u32, src_column: u32, src_node: Ast.Node.Index, name_strat: Zir.Inst.NameStrategy, decls_len: u32, captures: []const Zir.Inst.Capture, capture_names: []const Zir.NullTerminatedString, decls: []const Zir.Inst.Index, }) !void

参数

gz: *GenZir
inst: Zir.Inst.Index
args: struct {
    src_line: u32,
    src_column: u32,
    src_node: Ast.Node.Index,
    name_strat: Zir.Inst.NameStrategy,
    decls_len: u32,
    captures: []const Zir.Inst.Capture,
    capture_names: []const Zir.NullTerminatedString,
    decls: []const Zir.Inst.Index,
}

std.zig.AstGen.GenZir.setStruct

函数

第 12464 行

fn setStruct(gz: *GenZir, inst: Zir.Inst.Index, args: struct { src_line: u32, src_column: u32, src_node: Ast.Node.Index, name_strat: Zir.Inst.NameStrategy, arg_baseline_src_node: Ast.Node.OptionalIndex, fields_baseline_src_node: Ast.Node.OptionalIndex, layout: std.lang.Type.ContainerLayout, backing_int_type_body_len: ?u32, decls_len: u32, fields_len: u32, any_field_aligns: bool, any_field_defaults: bool, any_comptime_fields: bool, fields_hash: std.zig.SrcHash, captures: []const Zir.Inst.Capture, capture_names: []const Zir.NullTerminatedString, remaining: []const u32, }) !void

参数

gz: *GenZir
inst: Zir.Inst.Index
args: struct {
    src_line: u32,
    src_column: u32,
    src_node: Ast.Node.Index,
    name_strat: Zir.Inst.NameStrategy,
    arg_baseline_src_node: Ast.Node.OptionalIndex,
    fields_baseline_src_node: Ast.Node.OptionalIndex,
    layout: std.lang.Type.ContainerLayout,
    backing_int_type_body_len: ?u32,
    decls_len: u32,
    fields_len: u32,
    any_field_aligns: bool,
    any_field_defaults: bool,
    any_comptime_fields: bool,
    fields_hash: std.zig.SrcHash,
    captures: []const Zir.Inst.Capture,
    capture_names: []const Zir.NullTerminatedString,
    /// 尾随的声明列表、字段信息及体指令。
    remaining: []const u32,
}

std.zig.AstGen.GenZir.setTryBody

函数

第 11526 行

假定 gz 上没有压入任何内容。弹出 gz。

fn setTryBody(gz: *GenZir, inst: Zir.Inst.Index, operand: Zir.Inst.Ref) !void

参数

gz: *GenZir
inst: Zir.Inst.Index
operand: Zir.Inst.Ref

std.zig.AstGen.GenZir.setUnion

函数

第 12546 行

fn setUnion(gz: *GenZir, inst: Zir.Inst.Index, args: struct { src_line: u32, src_column: u32, src_node: Ast.Node.Index, name_strat: Zir.Inst.NameStrategy, arg_baseline_src_node: Ast.Node.OptionalIndex, fields_baseline_src_node: Ast.Node.OptionalIndex, kind: Zir.Inst.UnionDecl.Kind, arg_type_body_len: ?u32, decls_len: u32, fields_len: u32, any_field_aligns: bool, any_field_values: bool, fields_hash: std.zig.SrcHash, captures: []const Zir.Inst.Capture, capture_names: []const Zir.NullTerminatedString, remaining: []const u32, }) !void

参数

gz: *GenZir
inst: Zir.Inst.Index
args: struct {
    src_line: u32,
    src_column: u32,
    src_node: Ast.Node.Index,
    name_strat: Zir.Inst.NameStrategy,
    arg_baseline_src_node: Ast.Node.OptionalIndex,
    fields_baseline_src_node: Ast.Node.OptionalIndex,
    kind: Zir.Inst.UnionDecl.Kind,
    arg_type_body_len: ?u32,
    decls_len: u32,
    fields_len: u32,
    any_field_aligns: bool,
    any_field_values: bool,
    fields_hash: std.zig.SrcHash,
    captures: []const Zir.Inst.Capture,
    capture_names: []const Zir.NullTerminatedString,
    /// 尾随的声明列表、字段信息及体指令。
    remaining: []const u32,
}

std.zig.AstGen.GenZir.tokenIndexToRelative

函数

第 11430 行

fn tokenIndexToRelative(gz: GenZir, token: Ast.TokenIndex) Ast.TokenOffset

参数

gz: GenZir
token: Ast.TokenIndex

std.zig.AstGen.GenZir.unstack

函数

第 11351 行

向所属 GenZir 添加任何新指令之前,先调用 unstack。

fn unstack(self: *GenZir) void

参数

self: *GenZir

std.zig.AstGen.GenZir.unstacked_top

常量

第 11349 行

std.zig.AstGen.globalVarDecl

函数

第 4410 行

fn globalVarDecl( astgen: *AstGen, gz: *GenZir, scope: *Scope, wip_decls: *WipDecls, node: Ast.Node.Index, var_decl: Ast.full.VarDecl, ) InnerError!void

参数

astgen: *AstGen
gz: *GenZir
scope: *Scope
wip_decls: *WipDecls
node: Ast.Node.Index
var_decl: Ast.full.VarDecl

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.hasDeclOrField

函数

第 9754 行

fn hasDeclOrField( gz: *GenZir, scope: *Scope, ri: ResultInfo, node: Ast.Node.Index, lhs_node: Ast.Node.Index, rhs_node: Ast.Node.Index, tag: Zir.Inst.Tag, ) InnerError!Zir.Inst.Ref

参数

gz: *GenZir
scope: *Scope
ri: ResultInfo
node: Ast.Node.Index
lhs_node: Ast.Node.Index
rhs_node: Ast.Node.Index
tag: Zir.Inst.Tag

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.identAsString

函数

第 11030 行

fn identAsString(astgen: *AstGen, ident_token: Ast.TokenIndex) !Zir.NullTerminatedString

参数

astgen: *AstGen
ident_token: Ast.TokenIndex

std.zig.AstGen.identifier

函数

第 8124 行

fn identifier( gz: *GenZir, scope: *Scope, ri: ResultInfo, ident: Ast.Node.Index, force_comptime: ?ComptimeBlockInfo, ) InnerError!Zir.Inst.Ref

参数

gz: *GenZir
scope: *Scope
ri: ResultInfo
ident: Ast.Node.Index
force_comptime: ?ComptimeBlockInfo

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.identifierTokenString

函数

第 10767 行

给定标识符词法单元,获取对应字符串。 若词法单元使用 @"" 语法,则按字符串解析,必要时报告错误,并在 astgen.arena 中分配结果。 否则直接返回对源码字节的引用。 另见 appendIdentStr 和 parseStrLit。

fn identifierTokenString(astgen: *AstGen, token: Ast.TokenIndex) InnerError![]const u8

参数

astgen: *AstGen
token: Ast.TokenIndex

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.ifExpr

函数

第 6177 行

fn ifExpr( parent_gz: *GenZir, scope: *Scope, ri: ResultInfo, node: Ast.Node.Index, if_full: Ast.full.If, ) InnerError!Zir.Inst.Ref

参数

parent_gz: *GenZir
scope: *Scope
ri: ResultInfo
node: Ast.Node.Index
if_full: Ast.full.If

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.IndexSlice

容器

第 11051 行

字段

index: Zir.NullTerminatedString
len: u32

std.zig.AstGen.InnerError

错误集合

第 74 行

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.isPrimitive

别名

第 13 行

别名目标 std.zig.primitives.isPrimitive

std.zig.AstGen.labeledBlockExpr

函数

第 2482 行

fn labeledBlockExpr( gz: *GenZir, parent_scope: *Scope, ri: ResultInfo, block_node: Ast.Node.Index, statements: []const Ast.Node.Index, force_comptime: bool, block_kind: BlockKind, ) InnerError!Zir.Inst.Ref

参数

gz: *GenZir
parent_scope: *Scope
ri: ResultInfo
block_node: Ast.Node.Index
statements: []const Ast.Node.Index
force_comptime: bool
block_kind: BlockKind

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.LineColumn

容器

第 12906 行

字段

u32
u32

std.zig.AstGen.localVarRef

函数

第 8212 行

fn localVarRef( gz: *GenZir, scope: *Scope, ri: ResultInfo, ident: Ast.Node.Index, ident_token: Ast.TokenIndex, ) InnerError!Zir.Inst.Ref

参数

gz: *GenZir
scope: *Scope
ri: ResultInfo
ident: Ast.Node.Index
ident_token: Ast.TokenIndex

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.lowerAstErrors

函数

第 13384 行

fn lowerAstErrors(astgen: *AstGen) error{OutOfMemory}!void

参数

astgen: *AstGen

错误

OutOfMemory

std.zig.AstGen.lvalExpr

函数

第 447 行

fn lvalExpr(gz: *GenZir, scope: *Scope, node: Ast.Node.Index) InnerError!Zir.Inst.Ref

参数

gz: *GenZir
scope: *Scope
node: Ast.Node.Index

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.maybeAdvanceSourceCursorToMainToken

函数

第 12910 行

若不在编译期作用域中,将源码游标推进到 node 的主标记。 通常与 emitDbgStmt 配合使用。

fn maybeAdvanceSourceCursorToMainToken(gz: *GenZir, node: Ast.Node.Index) LineColumn

参数

gz: *GenZir
node: Ast.Node.Index

std.zig.AstGen.mem

别名

第 6 行

别名目标 std.mem

std.zig.AstGen.minMax

函数

第 8998 行

fn minMax( gz: *GenZir, scope: *Scope, ri: ResultInfo, node: Ast.Node.Index, args: []const Ast.Node.Index, comptime op: enum { min, max }, ) InnerError!Zir.Inst.Ref

参数

gz: *GenZir
scope: *Scope
ri: ResultInfo
node: Ast.Node.Index
args: []const Ast.Node.Index
op: enum { min, max }

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.multilineStringLiteral

函数

第 8492 行

fn multilineStringLiteral( gz: *GenZir, ri: ResultInfo, node: Ast.Node.Index, ) InnerError!Zir.Inst.Ref

参数

gz: *GenZir
ri: ResultInfo
node: Ast.Node.Index

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.nameStratExpr

函数

第 1167 行

存在 .anon 之外的命名策略时,例如分析变量声明的初始化表达式, 应先尝试此函数,再使用 expr、comptimeExpr 等,以便必要时应用该命名 策略。若返回 null,表示 node 不消耗命名 策略,应改用 expr 等普通求值函数。否则,node 确实消耗命名策略:表达式已按 expr 的方式求值,但使用了给定 命名策略。

fn nameStratExpr( gz: *GenZir, scope: *Scope, ri: ResultInfo, node: Ast.Node.Index, name_strat: Zir.Inst.NameStrategy, ) InnerError!?Zir.Inst.Ref

参数

gz: *GenZir
scope: *Scope
ri: ResultInfo
node: Ast.Node.Index
name_strat: Zir.Inst.NameStrategy

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.negation

函数

第 9891 行

fn negation( gz: *GenZir, scope: *Scope, ri: ResultInfo, node: Ast.Node.Index, ) InnerError!Zir.Inst.Ref

参数

gz: *GenZir
scope: *Scope
ri: ResultInfo
node: Ast.Node.Index

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.nodeIsTriviallyZero

函数

第 10279 行

fn nodeIsTriviallyZero(tree: *const Ast, node: Ast.Node.Index) bool

参数

tree: *const Ast
node: Ast.Node.Index

std.zig.AstGen.nodeMayAppendToErrorTrace

函数

第 10295 行

fn nodeMayAppendToErrorTrace(tree: *const Ast, start_node: Ast.Node.Index) bool

参数

tree: *const Ast
start_node: Ast.Node.Index

std.zig.AstGen.nodeMayEvalToError

函数

第 10320 行

fn nodeMayEvalToError(tree: *const Ast, start_node: Ast.Node.Index) BuiltinFn.EvalToError

参数

tree: *const Ast
start_node: Ast.Node.Index

std.zig.AstGen.nosuspendExpr

函数

第 1214 行

fn nosuspendExpr( gz: *GenZir, scope: *Scope, ri: ResultInfo, node: Ast.Node.Index, ) InnerError!Zir.Inst.Ref

参数

gz: *GenZir
scope: *Scope
ri: ResultInfo
node: Ast.Node.Index

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.nullTerminatedString

函数

第 12801 行

这只能用于短期引用; 添加另一个字符串时,该内存即失效。

fn nullTerminatedString(astgen: AstGen, index: Zir.NullTerminatedString) [*:0]const u8

参数

std.zig.AstGen.numberLiteral

函数

第 8526 行

fn numberLiteral(gz: *GenZir, ri: ResultInfo, node: Ast.Node.Index, source_node: Ast.Node.Index, sign: Sign) InnerError!Zir.Inst.Ref

参数

gz: *GenZir
ri: ResultInfo
node: Ast.Node.Index
source_node: Ast.Node.Index
sign: Sign

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.offsetOf

函数

第 9966 行

fn offsetOf( gz: *GenZir, scope: *Scope, ri: ResultInfo, node: Ast.Node.Index, lhs_node: Ast.Node.Index, rhs_node: Ast.Node.Index, tag: Zir.Inst.Tag, ) InnerError!Zir.Inst.Ref

参数

gz: *GenZir
scope: *Scope
ri: ResultInfo
node: Ast.Node.Index
lhs_node: Ast.Node.Index
rhs_node: Ast.Node.Index
tag: Zir.Inst.Tag

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.orelseCatchExpr

函数

第 5872 行

fn orelseCatchExpr( parent_gz: *GenZir, scope: *Scope, ri: ResultInfo, node: Ast.Node.Index, cond_op: Zir.Inst.Tag, unwrap_op: Zir.Inst.Tag, unwrap_code_op: Zir.Inst.Tag, payload_token: ?Ast.TokenIndex, ) InnerError!Zir.Inst.Ref

参数

parent_gz: *GenZir
scope: *Scope
ri: ResultInfo
node: Ast.Node.Index
cond_op: Zir.Inst.Tag
unwrap_op: Zir.Inst.Tag
unwrap_code_op: Zir.Inst.Tag
payload_token: ?Ast.TokenIndex

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.overflowArithmetic

函数

第 10015 行

fn overflowArithmetic( gz: *GenZir, scope: *Scope, ri: ResultInfo, node: Ast.Node.Index, params: []const Ast.Node.Index, tag: Zir.Inst.Extended, ) InnerError!Zir.Inst.Ref

参数

gz: *GenZir
scope: *Scope
ri: ResultInfo
node: Ast.Node.Index
params: []const Ast.Node.Index
tag: Zir.Inst.Extended

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.parseBitCount

函数

第 8101 行

将字符串 buf 解析为 u16 类型的十进制整数。

与 std.fmt.parseInt 不同,不允许 buf 中存在“_”字符。

fn parseBitCount(buf: []const u8) std.fmt.ParseIntError!u16

参数

buf: []const u8

错误

InvalidCharacter

输入为空或包含无效字符。

Overflow

结果无法由指定类型容纳。

std.zig.AstGen.parseStrLit

函数

第 10812 行

将结果追加至 buf。

fn parseStrLit( astgen: *AstGen, token: Ast.TokenIndex, buf: *ArrayList(u8), bytes: []const u8, offset: u32, ) InnerError!void

参数

astgen: *AstGen
token: Ast.TokenIndex
buf: *ArrayList(u8)
bytes: []const u8
offset: u32

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.primitive_instrs

常量

第 10214 行

std.zig.AstGen.ptrCast

函数

第 8819 行

处理一个或多个嵌套的指针转换内置函数:

  • @ptrCast
  • @alignCast
  • @addrSpaceCast
  • @constCast
  • @volatileCast 这些内置函数的任意序列均视为单个操作。这样, 即使中间结果类型未知,@ptrCast(@alignCast(ptr)) 等序列也能正确工作。
fn ptrCast( gz: *GenZir, scope: *Scope, ri: ResultInfo, root_node: Ast.Node.Index, ) InnerError!Zir.Inst.Ref

参数

gz: *GenZir
scope: *Scope
ri: ResultInfo
root_node: Ast.Node.Index

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.ptrType

函数

第 3760 行

fn ptrType( gz: *GenZir, scope: *Scope, ri: ResultInfo, node: Ast.Node.Index, ptr_info: Ast.full.PtrType, ) InnerError!Zir.Inst.Ref

参数

gz: *GenZir
scope: *Scope
ri: ResultInfo
node: Ast.Node.Index
ptr_info: Ast.full.PtrType

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.reachableExpr

函数

第 415 行

与 expr 相同,但如果结果类型为 noreturn,则以编译错误失败。

fn reachableExpr( gz: *GenZir, scope: *Scope, ri: ResultInfo, node: Ast.Node.Index, reachable_node: Ast.Node.Index, ) InnerError!Zir.Inst.Ref

参数

gz: *GenZir
scope: *Scope
ri: ResultInfo
node: Ast.Node.Index
reachable_node: Ast.Node.Index

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.reachableExprComptime

函数

第 425 行

fn reachableExprComptime( gz: *GenZir, scope: *Scope, ri: ResultInfo, node: Ast.Node.Index, reachable_node: Ast.Node.Index, comptime_reason: ?std.zig.SimpleComptimeReason, ) InnerError!Zir.Inst.Ref

参数

gz: *GenZir
scope: *Scope
ri: ResultInfo
node: Ast.Node.Index
reachable_node: Ast.Node.Index
comptime_reason: ?std.zig.SimpleComptimeReason

若为 null,则表达式不在编译期上下文中求值。

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.reachableTypeExpr

函数

第 405 行

fn reachableTypeExpr( gz: *GenZir, scope: *Scope, type_node: Ast.Node.Index, reachable_node: Ast.Node.Index, ) InnerError!Zir.Inst.Ref

参数

gz: *GenZir
scope: *Scope
type_node: Ast.Node.Index
reachable_node: Ast.Node.Index

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.reserveExtra

函数

第 129 行

fn reserveExtra(astgen: *AstGen, size: usize) Allocator.Error!u32

参数

astgen: *AstGen
size: usize

错误

OutOfMemory

std.zig.AstGen.restoreErrRetIndex

函数

第 2141 行

恢复错误返回追踪索引。仅当结果不是错误,或结果位置不是错误处理表达式时执行恢复。

fn restoreErrRetIndex( gz: *GenZir, bt: GenZir.BranchTarget, ri: ResultInfo, node: Ast.Node.Index, result: Zir.Inst.Ref, ) !void

参数

gz: *GenZir
bt: GenZir.BranchTarget
ri: ResultInfo
node: Ast.Node.Index
result: Zir.Inst.Ref

std.zig.AstGen.restoreSourceCursor

函数

第 12962 行

fn restoreSourceCursor(astgen: *AstGen, cursor: SourceCursor) void

参数

astgen: *AstGen
cursor: SourceCursor

std.zig.AstGen.ResultInfo

容器

第 267 行

字段

rl: Loc

结果位置所需的语义

ctx: Context = .none

使用结果位置的“运算符”

std.zig.AstGen.ResultInfo.br

函数

第 276 行

将 coerced_ty 转回 ty。应在 if、switch 表达式 等分支点调用。

fn br(ri: ResultInfo) ResultInfo

参数

std.zig.AstGen.ResultInfo.Context

容器

第 376 行

字段

@"return"

此表达式是 return 表达式的操作数。

error_handling_expr

此表达式是错误处理运算符(if-else、try 或 catch)的输入。

shift_op

该表达式是移位操作的右侧操作数。

fn_arg

此表达式是函数调用中的参数。

const_init

此表达式是 const 变量初始化器的右侧表达式。

assignment

表达式是赋值表达式的右侧操作数。

none

没有特定运算符。

return_addrof

该表达式是取地址操作数,而取地址表达式又是 return 表达式的操作数。

std.zig.AstGen.ResultInfo.Loc

容器

第 296 行

字段

discard

表达式是赋值给 _ 的右值。只应生成表达式的副作用。 必须忽略表达式产生的结果指令。

none

表达式的类型为推断类型,并将按右值求值。

ty: Zir.Inst.Ref

表达式将强制转换为此类型,但会作为右值求值。

coerced_ty: Zir.Inst.Ref

与 ty 相同,但保证 Sema 还会执行强制转换,因此无需输出 as 指令。

ref

表达式必须生成指针,而非值。例如, 赋值的左侧使用此类结果位置。

ref_coerced_ty: Zir.Inst.Ref

表达式必须生成指针而非值,其他代码会将该指针强制转换为此类型; 先前指令已保证此类型为指针类型。

ref_const

类似于 ref,但永远不会通过该指针存储,因此不应将局部变量 标记为可能被修改。

ptr: PtrResultLoc

表达式必须将结果存入此有类型指针。 必须忽略表达式的结果指令。

inferred_ptr: Zir.Inst.Ref

表达式必须将结果存入此分配块,其类型由推导确定。 必须忽略表达式的结果指令。 始终为标签是 alloc_inferred 的指令。

destructure: struct {
    /// 解构操作本身的 AST 节点。
    src_node: Ast.Node.Index,
    /// 用于存储结果的指针。
    components: []const DestructureComponent,
}

由于解构操作,此表达式有一组用于存储结果的指针。 每个指针的类型可能需要推导,也可能不需要。

std.zig.AstGen.ResultInfo.Loc.DestructureComponent

容器

第 333 行

字段

typed_ptr: PtrResultLoc
inferred_ptr: Zir.Inst.Ref
discard

std.zig.AstGen.ResultInfo.Loc.PtrResultLoc

容器

第 339 行

字段

inst: Zir.Inst.Ref
src_node: ?Ast.Node.Index = null

std.zig.AstGen.ResultInfo.Loc.resultType

函数

第 346 行

根据结果位置查找转换内置函数的结果类型。 若位置没有已知结果类型,则返回 null。

fn resultType(rl: Loc, gz: *GenZir, node: Ast.Node.Index) !?Zir.Inst.Ref

参数

rl: Loc
gz: *GenZir
node: Ast.Node.Index

std.zig.AstGen.ResultInfo.Loc.resultTypeForCast

函数

第 361 行

根据结果位置查找转换内置函数的结果类型。 若该位置没有已知结果类型,则在给定节点上报错。

fn resultTypeForCast(rl: Loc, gz: *GenZir, node: Ast.Node.Index, builtin_name: []const u8) !Zir.Inst.Ref

参数

rl: Loc
gz: *GenZir
node: Ast.Node.Index
builtin_name: []const u8

std.zig.AstGen.ResultInfo.zirTag

函数

第 286 行

fn zirTag(ri: ResultInfo) Zir.Inst.Tag

参数

std.zig.AstGen.resumeExpr

函数

第 1270 行

fn resumeExpr( gz: *GenZir, scope: *Scope, ri: ResultInfo, node: Ast.Node.Index, ) InnerError!Zir.Inst.Ref

参数

gz: *GenZir
scope: *Scope
ri: ResultInfo
node: Ast.Node.Index

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.ret

函数

第 7974 行

fn ret(gz: *GenZir, scope: *Scope, node: Ast.Node.Index) InnerError!Zir.Inst.Ref

参数

gz: *GenZir
scope: *Scope
node: Ast.Node.Index

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.rvalue

函数

第 10529 行

将 rl 语义应用于 result。不自行处理结果位置 的表达式,必须对结果调用此函数。 例如,若 ri.rl 为 .ptr,则将结果写入该指针。 若 ri.rl 为 .ty,则将结果强制转换为该类型。 假定 gz 上没有堆叠的内容。

fn rvalue( gz: *GenZir, ri: ResultInfo, raw_result: Zir.Inst.Ref, src_node: Ast.Node.Index, ) InnerError!Zir.Inst.Ref

参数

gz: *GenZir
ri: ResultInfo
raw_result: Zir.Inst.Ref
src_node: Ast.Node.Index

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.rvalueInner

函数

第 10551 行

fn rvalueInner( gz: *GenZir, ri: ResultInfo, raw_result: Zir.Inst.Ref, src_node: Ast.Node.Index, allow_coerce_pre_ref: bool, ) InnerError!Zir.Inst.Ref

参数

gz: *GenZir
ri: ResultInfo
raw_result: Zir.Inst.Ref
src_node: Ast.Node.Index
allow_coerce_pre_ref: bool

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.rvalueNoCoercePreRef

函数

第 10542 行

类似 rvalue,但对于 ref_coerced_ty 结果类型, 拒绝在取得引用前进行强制转换。用于没有 alloc 的局部变量,因为希望变量具有稳定地址, 即表现为左值。

fn rvalueNoCoercePreRef( gz: *GenZir, ri: ResultInfo, raw_result: Zir.Inst.Ref, src_node: Ast.Node.Index, ) InnerError!Zir.Inst.Ref

参数

gz: *GenZir
ri: ResultInfo
raw_result: Zir.Inst.Ref
src_node: Ast.Node.Index

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.saveSourceCursor

函数

第 12955 行

获取当前源码游标,稍后可通过 restoreSourceCursor 恢复。 适用于乱序分析源码。

fn saveSourceCursor(astgen: *const AstGen) SourceCursor

参数

astgen: *const AstGen

std.zig.AstGen.scanContainer

函数

第 12980 行

检测声明和字段的名称冲突,并将所有具名声明填入 namespace.decls。

fn scanContainer( astgen: *AstGen, namespace: *Scope.Namespace, members: []const Ast.Node.Index, container_kind: enum { @"struct", @"union", @"enum", @"opaque" }, ) !ScanContainerResult

参数

astgen: *AstGen
namespace: *Scope.Namespace
members: []const Ast.Node.Index
container_kind: enum { @"struct", @"union", @"enum", @"opaque" }

std.zig.AstGen.ScanContainerResult

容器

第 12968 行

字段

decls_len: u32

包含未命名声明(例如 comptime 声明)

fields_len: u32
any_field_aligns: bool
any_field_values: bool
any_comptime_fields: bool
has_underscore_field: bool

是否存在名为 _ 的字段(表示非穷尽枚举)

std.zig.AstGen.Scope

容器

第 11121 行

字段

tag: Tag

std.zig.AstGen.Scope.cast

函数

第 11124 行

fn cast(base: *Scope, comptime T: type) ?*T

参数

base: *Scope
T: type

std.zig.AstGen.Scope.Defer

容器

第 11246 行

字段

base: Scope
parent: *Scope

父级可以为 LocalVal、LocalPtr、GenZir、Defer 或 Namespace。

index: u32
len: u32

std.zig.AstGen.Scope.IdCat

容器

第 11185 行

标识符类别。这些标签名称会在编译错误中向用户显示。

字段

@"function parameter"
@"local constant"
@"local variable"
@"switch tag capture"
capture

std.zig.AstGen.Scope.LocalPtr

容器

第 11220 行

可能为 const 或 var 局部变量。持有指针而非值。 此结构的生存期与包含该变量的 Block 节点的 AST 生成过程相同。

字段

base: Scope = Scope{ .tag = base_tag }
parent: *Scope

父级可以为 LocalVal、LocalPtr、GenZir、Defer 或 Namespace。

gen_zir: *GenZir
ptr: Zir.Inst.Ref
token_src: Ast.TokenIndex

对应变量声明的源码位置。

used: Ast.OptionalTokenIndex = .none

跟踪标识符首次被引用的位置。 .none 表示从未引用。

discarded: Ast.OptionalTokenIndex = .none

跟踪标识符被丢弃的位置,例如 _ = foo;。 .none 表示从未丢弃。

used_as_lvalue: bool = false

此值在初始化后是否用作左值。 若不是,则可确定其能够为 const,因此若声明为 var 则产生编译错误。

name: Zir.NullTerminatedString

字符串表索引。

id_cat: IdCat
maybe_comptime: bool

true 表示在 Sema 阶段确定该值是否为编译期值。 false 表示在 AstGen 阶段已知该值仅在运行时确定。

std.zig.AstGen.Scope.LocalPtr.base_tag

常量

第 11221 行

Tag

std.zig.AstGen.Scope.LocalVal

容器

第 11196 行

这始终是 const 局部变量,且 inst 是值类型,而非指针。 此结构体的生命周期与包含该变量的 Block 节点的 AST 生成过程相同。

字段

base: Scope = Scope{ .tag = base_tag }
parent: *Scope

父级可以为 LocalVal、LocalPtr、GenZir、Defer 或 Namespace。

gen_zir: *GenZir
inst: Zir.Inst.Ref
token_src: Ast.TokenIndex

对应变量声明的源码位置。

used: Ast.OptionalTokenIndex = .none

跟踪标识符首次被引用的位置。 .none 表示从未引用。

discarded: Ast.OptionalTokenIndex = .none

跟踪标识符被丢弃的位置,例如 _ = foo;。 .none 表示从未丢弃。

is_used_or_discarded: ?*bool = null
name: Zir.NullTerminatedString

字符串表索引。

id_cat: IdCat

std.zig.AstGen.Scope.LocalVal.base_tag

常量

第 11197 行

Tag

std.zig.AstGen.Scope.Namespace

容器

第 11256 行

表示可包含任意数量声明的全局作用域。 每个声明均以其为父作用域。

字段

base: Scope = Scope{ .tag = base_tag }
parent: *Scope

父级可以为 LocalVal、LocalPtr、GenZir、Defer 或 Namespace。

decls: std.AutoHashMapUnmanaged(Zir.NullTerminatedString, Ast.Node.Index) = .empty

将字符串表索引映射到声明源码位置,用于报告名称遮蔽编译错误。

node: Ast.Node.Index
inst: Zir.Inst.Index
maybe_generic: bool
declaring_gz: ?*GenZir

包含此命名空间的 astgen 作用域。 仅在 astgen 期间有效。

captures: std.array_hash_map.Auto(Zir.Inst.Capture, Zir.NullTerminatedString) = .empty

此命名空间使用的捕获集合。

std.zig.AstGen.Scope.Namespace.base_tag

常量

第 11257 行

Tag

std.zig.AstGen.Scope.Namespace.deinit

函数

第 11276 行

fn deinit(self: *Namespace, gpa: Allocator) void

参数

self: *Namespace
gpa: Allocator

std.zig.AstGen.Scope.parent

函数

第 11143 行

fn parent(base: *Scope) ?*Scope

参数

base: *Scope

std.zig.AstGen.Scope.Tag

容器

第 11174 行

字段

gen_zir
local_val
local_ptr
defer_normal
defer_error
namespace
top

std.zig.AstGen.Scope.Top

容器

第 11283 行

字段

base: Scope = Scope{ .tag = base_tag }

std.zig.AstGen.Scope.Top.base_tag

常量

第 11284 行

Scope.Tag

std.zig.AstGen.Scope.unwrap

函数

第 11154 行

fn unwrap(base: *Scope) Unwrapped

参数

base: *Scope

std.zig.AstGen.Scope.Unwrapped

容器

第 11164 行

字段

gen_zir: *GenZir
local_val: *LocalVal
local_ptr: *LocalPtr
defer_normal: *Defer
defer_error: *Defer
namespace: *Namespace
top: *Top

std.zig.AstGen.Scratch

容器

第 3921 行

字段

astgen: *AstGen
scratch_top: u32

std.zig.AstGen.Scratch.addOptionalSlice

函数

第 3939 行

fn addOptionalSlice(s: *Scratch, present: bool, len: u32) Allocator.Error!?Slice

参数

s: *Scratch
present: bool
len: u32

错误

OutOfMemory

std.zig.AstGen.Scratch.addSlice

函数

第 3934 行

fn addSlice(s: *Scratch, len: u32) Allocator.Error!Slice

参数

s: *Scratch
len: u32

错误

OutOfMemory

std.zig.AstGen.Scratch.all

函数

第 3950 行

返回包含添加到此 Scratch 的全部数据的切片。

fn all(s: *Scratch) Slice

参数

s: *Scratch

std.zig.AstGen.Scratch.appendBodyWithFixups

函数

第 3943 行

fn appendBodyWithFixups(s: *Scratch, body: []const Zir.Inst.Index) Allocator.Error!u32

参数

s: *Scratch
body: []const Zir.Inst.Index

错误

OutOfMemory

std.zig.AstGen.Scratch.init

函数

第 3924 行

fn init(astgen: *AstGen) Scratch

参数

astgen: *AstGen

std.zig.AstGen.Scratch.reset

函数

第 3930 行

fn reset(s: *Scratch) void

参数

s: *Scratch

std.zig.AstGen.Scratch.Slice

容器

第 3954 行

字段

start: u32
len: u32

std.zig.AstGen.Scratch.Slice.get

函数

第 3957 行

fn get(s: Slice, astgen: *AstGen) []u32

参数

s: Slice
astgen: *AstGen

std.zig.AstGen.setCondBrPayload

函数

第 6397 行

支持 else_scope 叠加于 then_scope。先退出 else_scope,再退出 then_scope。

fn setCondBrPayload( condbr: Zir.Inst.Index, cond: Zir.Inst.Ref, then_scope: *GenZir, else_scope: *GenZir, ) !void

参数

condbr: Zir.Inst.Index
cond: Zir.Inst.Ref
then_scope: *GenZir
else_scope: *GenZir

std.zig.AstGen.setDeclaration

函数

第 13505 行

设置 declaration 指令的全部额外数据。 弹出 type_gz、align_gz、linksection_gz、addrspace_gz 和 value_gz。

fn setDeclaration( decl_inst: Zir.Inst.Index, args: struct { src_hash: std.zig.SrcHash, src_line: u32, src_column: u32, kind: Zir.Inst.Declaration.Unwrapped.Kind, name: Zir.NullTerminatedString, is_pub: bool, is_threadlocal: bool, linkage: Zir.Inst.Declaration.Unwrapped.Linkage, lib_name: Zir.NullTerminatedString = .empty, type_gz: *GenZir, align_gz: *GenZir, addrspace_gz: *GenZir, linksection_gz: *GenZir, value_gz: *GenZir, }, ) !void

参数

decl_inst: Zir.Inst.Index
args: struct {
    src_hash: std.zig.SrcHash,
    src_line: u32,
    src_column: u32,

    kind: Zir.Inst.Declaration.Unwrapped.Kind,
    name: Zir.NullTerminatedString,
    is_pub: bool,
    is_threadlocal: bool,
    linkage: Zir.Inst.Declaration.Unwrapped.Linkage,
    lib_name: Zir.NullTerminatedString = .empty,

    type_gz: *GenZir,
    /// 必须叠加在 `type_gz` 上。
    align_gz: *GenZir,
    /// 必须堆叠在 `align_gz` 之上。
    addrspace_gz: *GenZir,
    /// 必须叠放在 `addrspace_gz` 之上。
    linksection_gz: *GenZir,
    /// 必须叠放在 `linksection_gz` 之上,且其上方不得有其他项。
    value_gz: *GenZir,
}

std.zig.AstGen.setExtra

函数

第 90 行

fn setExtra(astgen: *AstGen, index: usize, extra: anytype) void

参数

astgen: *AstGen
index: usize

std.zig.AstGen.shiftOp

函数

第 9984 行

fn shiftOp( gz: *GenZir, scope: *Scope, ri: ResultInfo, node: Ast.Node.Index, lhs_node: Ast.Node.Index, rhs_node: Ast.Node.Index, tag: Zir.Inst.Tag, ) InnerError!Zir.Inst.Ref

参数

gz: *GenZir
scope: *Scope
ri: ResultInfo
node: Ast.Node.Index
lhs_node: Ast.Node.Index
rhs_node: Ast.Node.Index
tag: Zir.Inst.Tag

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.Sign

容器

第 8524 行

字段

negative
positive

std.zig.AstGen.simpleBinOp

函数

第 6102 行

fn simpleBinOp( gz: *GenZir, scope: *Scope, ri: ResultInfo, node: Ast.Node.Index, op_inst_tag: Zir.Inst.Tag, ) InnerError!Zir.Inst.Ref

参数

gz: *GenZir
scope: *Scope
ri: ResultInfo
node: Ast.Node.Index
op_inst_tag: Zir.Inst.Tag

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.simpleStrTok

函数

第 6138 行

fn simpleStrTok( gz: *GenZir, ri: ResultInfo, ident_token: Ast.TokenIndex, node: Ast.Node.Index, op_inst_tag: Zir.Inst.Tag, ) InnerError!Zir.Inst.Ref

参数

gz: *GenZir
ri: ResultInfo
ident_token: Ast.TokenIndex
node: Ast.Node.Index
op_inst_tag: Zir.Inst.Tag

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.simpleUnOp

函数

第 9812 行

fn simpleUnOp( gz: *GenZir, scope: *Scope, ri: ResultInfo, node: Ast.Node.Index, operand_ri: ResultInfo, operand_node: Ast.Node.Index, tag: Zir.Inst.Tag, ) InnerError!Zir.Inst.Ref

参数

gz: *GenZir
scope: *Scope
ri: ResultInfo
node: Ast.Node.Index
operand_ri: ResultInfo
operand_node: Ast.Node.Index
tag: Zir.Inst.Tag

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.simpleUnOpType

函数

第 9799 行

fn simpleUnOpType( gz: *GenZir, scope: *Scope, ri: ResultInfo, node: Ast.Node.Index, operand_node: Ast.Node.Index, tag: Zir.Inst.Tag, ) InnerError!Zir.Inst.Ref

参数

gz: *GenZir
scope: *Scope
ri: ResultInfo
node: Ast.Node.Index
operand_node: Ast.Node.Index
tag: Zir.Inst.Tag

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.SourceCursor

容器

第 12947 行

字段

offset: u32
line: u32
column: u32

std.zig.AstGen.std

别名

第 4 行

别名目标 std

std.zig.AstGen.StringIndexAdapter

别名

第 10 行

别名目标 std.hash_map.StringIndexAdapter

std.zig.AstGen.StringIndexContext

别名

第 11 行

别名目标 std.hash_map.StringIndexContext

std.zig.AstGen.stringLiteral

函数

第 8473 行

fn stringLiteral( gz: *GenZir, ri: ResultInfo, node: Ast.Node.Index, ) InnerError!Zir.Inst.Ref

参数

gz: *GenZir
ri: ResultInfo
node: Ast.Node.Index

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.strLitAsString

函数

第 11053 行

fn strLitAsString(astgen: *AstGen, str_lit_token: Ast.TokenIndex) !IndexSlice

参数

astgen: *AstGen
str_lit_token: Ast.TokenIndex

std.zig.AstGen.strLitNodeAsString

函数

第 11088 行

fn strLitNodeAsString(astgen: *AstGen, node: Ast.Node.Index) !IndexSlice

参数

astgen: *AstGen
node: Ast.Node.Index

std.zig.AstGen.structDeclInner

函数

第 4834 行

fn structDeclInner( gz: *GenZir, scope: *Scope, node: Ast.Node.Index, container_decl: Ast.full.ContainerDecl, layout: std.lang.Type.ContainerLayout, maybe_backing_int_node: Ast.Node.OptionalIndex, name_strat: Zir.Inst.NameStrategy, ) InnerError!Zir.Inst.Ref

参数

gz: *GenZir
scope: *Scope
node: Ast.Node.Index
container_decl: Ast.full.ContainerDecl
layout: std.lang.Type.ContainerLayout
maybe_backing_int_node: Ast.Node.OptionalIndex
name_strat: Zir.Inst.NameStrategy

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.structInitExpr

函数

第 1689 行

fn structInitExpr( gz: *GenZir, scope: *Scope, ri: ResultInfo, node: Ast.Node.Index, struct_init: Ast.full.StructInit, ) InnerError!Zir.Inst.Ref

参数

gz: *GenZir
scope: *Scope
ri: ResultInfo
node: Ast.Node.Index
struct_init: Ast.full.StructInit

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.structInitExprAnon

函数

第 1883 行

使用 struct_init_anon 指令的结构体初始化表达式。

fn structInitExprAnon( gz: *GenZir, scope: *Scope, node: Ast.Node.Index, struct_init: Ast.full.StructInit, ) InnerError!Zir.Inst.Ref

参数

gz: *GenZir
scope: *Scope
node: Ast.Node.Index
struct_init: Ast.full.StructInit

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.structInitExprPtr

函数

第 1954 行

使用字段指针的结构体初始化表达式。

fn structInitExprPtr( gz: *GenZir, scope: *Scope, node: Ast.Node.Index, struct_init: Ast.full.StructInit, ptr_inst: Zir.Inst.Ref, ) InnerError!void

参数

gz: *GenZir
scope: *Scope
node: Ast.Node.Index
struct_init: Ast.full.StructInit
ptr_inst: Zir.Inst.Ref

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.structInitExprTyped

函数

第 1915 行

使用 struct_init 或 struct_init_ref 指令的结构体初始化表达式。

fn structInitExprTyped( gz: *GenZir, scope: *Scope, node: Ast.Node.Index, struct_init: Ast.full.StructInit, ty_inst: Zir.Inst.Ref, is_ref: bool, ) InnerError!Zir.Inst.Ref

参数

gz: *GenZir
scope: *Scope
node: Ast.Node.Index
struct_init: Ast.full.StructInit
ty_inst: Zir.Inst.Ref
is_ref: bool

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.suspendExpr

函数

第 1233 行

fn suspendExpr( gz: *GenZir, scope: *Scope, node: Ast.Node.Index, ) InnerError!Zir.Inst.Ref

参数

gz: *GenZir
scope: *Scope
node: Ast.Node.Index

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.switchExpr

函数

第 7073 行

fn switchExpr( parent_gz: *GenZir, scope: *Scope, ri: ResultInfo, node: Ast.Node.Index, switch_full: Ast.full.Switch, non_err: SwitchNonErr, ) InnerError!Zir.Inst.Ref

参数

parent_gz: *GenZir
scope: *Scope
ri: ResultInfo
node: Ast.Node.Index
switch_full: Ast.full.Switch
non_err: SwitchNonErr

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.SwitchNonErr

容器

第 7044 行

字段

none

常规 switch 表达式。 生成 switch_block[_ref]。

@"catch"

eu catch |err| switch (err) { ... }

switch 不得带标签。 生成 switch_block_err_union。

@"if": Ast.full.If

if (eu) |payload| { ... } else |err| switch (err) { ... }

switch 不得带标签。 输出 switch_block_err_union。

peer_break_target: struct {
    /// 引用整个基于错误值执行 switch 的表达式的外层块。
    block_inst: Zir.Inst.Index,
    /// 属于 `block_inst`。
    block_ri: ResultInfo,
}

eu catch |err| label: switch (err) { ... } if (eu) |payload| { ... } else |err| label: switch (err) { ... }

switch 必须带有标签。 为非错误分支体生成 condbr,并生成普通 switch;但非错误 分支与所有 switch 分支中的 break 均参与同级类型解析。 此指令用于避免 switch_block_err_union 中相当复杂的特殊情况。

std.zig.AstGen.testDecl

函数

第 4620 行

fn testDecl( astgen: *AstGen, gz: *GenZir, scope: *Scope, wip_decls: *WipDecls, node: Ast.Node.Index, ) InnerError!void

参数

astgen: *AstGen
gz: *GenZir
scope: *Scope
wip_decls: *WipDecls
node: Ast.Node.Index

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.tokenIdentEql

函数

第 6013 行

返回两个词法标记的标识符名称是否相等。不分配内存即可解析 @"" 形式的标记。 确切地说,理论上可以不分配内存;此实现 在使用 @"" 形式时会进行分配。

fn tokenIdentEql(astgen: *AstGen, token1: Ast.TokenIndex, token2: Ast.TokenIndex) !bool

参数

astgen: *AstGen
token1: Ast.TokenIndex
token2: Ast.TokenIndex

std.zig.AstGen.tryExpr

函数

第 5797 行

fn tryExpr( parent_gz: *GenZir, scope: *Scope, ri: ResultInfo, node: Ast.Node.Index, operand_node: Ast.Node.Index, ) InnerError!Zir.Inst.Ref

参数

parent_gz: *GenZir
scope: *Scope
ri: ResultInfo
node: Ast.Node.Index
operand_node: Ast.Node.Index

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.tunnelThroughClosure

函数

第 8372 行

通过闭包访问 ZIR 指令。可以穿透任意 数量的命名空间,并按需添加闭包捕获。 返回加入 gz 的 closure_get 指令索引。

fn tunnelThroughClosure( gz: *GenZir, inner_ref_node: Ast.Node.Index, num_tunnels: u32, value: union(enum) { ref: Zir.Inst.Ref, ref_load: Zir.Inst.Ref, decl_val: Zir.NullTerminatedString, decl_ref: Zir.NullTerminatedString, }, decl_src: union(enum) { token: Ast.TokenIndex, node: Ast.Node.Index, }, name_str_index: Zir.NullTerminatedString, ) !Zir.Inst.Ref

参数

gz: *GenZir
inner_ref_node: Ast.Node.Index

引用待捕获值的节点。

num_tunnels: u32

穿过的命名空间数量。至少为 1。

value: union(enum) {
    ref: Zir.Inst.Ref,
    ref_load: Zir.Inst.Ref,
    decl_val: Zir.NullTerminatedString,
    decl_ref: Zir.NullTerminatedString,
}

被捕获的值。

decl_src: union(enum) {
    token: Ast.TokenIndex,
    node: Ast.Node.Index,
}

值的声明位置。

name_str_index: Zir.NullTerminatedString

std.zig.AstGen.tupleDecl

函数

第 5059 行

fn tupleDecl( gz: *GenZir, scope: *Scope, node: Ast.Node.Index, container_decl: Ast.full.ContainerDecl, layout: std.lang.Type.ContainerLayout, backing_int_node: Ast.Node.OptionalIndex, ) InnerError!Zir.Inst.Ref

参数

gz: *GenZir
scope: *Scope
node: Ast.Node.Index
container_decl: Ast.full.ContainerDecl
layout: std.lang.Type.ContainerLayout
backing_int_node: Ast.Node.OptionalIndex

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.typeCast

函数

第 9778 行

fn typeCast( gz: *GenZir, scope: *Scope, ri: ResultInfo, node: Ast.Node.Index, operand_node: Ast.Node.Index, tag: Zir.Inst.Tag, builtin_name: []const u8, ) InnerError!Zir.Inst.Ref

参数

gz: *GenZir
scope: *Scope
ri: ResultInfo
node: Ast.Node.Index
operand_node: Ast.Node.Index
tag: Zir.Inst.Tag
builtin_name: []const u8

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.typeExpr

函数

第 401 行

fn typeExpr(gz: *GenZir, scope: *Scope, type_node: Ast.Node.Index) InnerError!Zir.Inst.Ref

参数

gz: *GenZir
scope: *Scope
type_node: Ast.Node.Index

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.typeOf

函数

第 8939 行

fn typeOf( gz: *GenZir, scope: *Scope, ri: ResultInfo, node: Ast.Node.Index, args: []const Ast.Node.Index, ) InnerError!Zir.Inst.Ref

参数

gz: *GenZir
scope: *Scope
ri: ResultInfo
node: Ast.Node.Index
args: []const Ast.Node.Index

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.unionDeclInner

函数

第 5156 行

fn unionDeclInner( gz: *GenZir, scope: *Scope, node: Ast.Node.Index, members: []const Ast.Node.Index, layout: std.lang.Type.ContainerLayout, opt_arg_node: Ast.Node.OptionalIndex, auto_enum_tok: ?Ast.TokenIndex, name_strat: Zir.Inst.NameStrategy, ) InnerError!Zir.Inst.Ref

参数

gz: *GenZir
scope: *Scope
node: Ast.Node.Index
members: []const Ast.Node.Index
layout: std.lang.Type.ContainerLayout
opt_arg_node: Ast.Node.OptionalIndex
auto_enum_tok: ?Ast.TokenIndex
name_strat: Zir.Inst.NameStrategy

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.unionInit

函数

第 8769 行

fn unionInit( gz: *GenZir, scope: *Scope, ri: ResultInfo, node: Ast.Node.Index, params: []const Ast.Node.Index, ) InnerError!Zir.Inst.Ref

参数

gz: *GenZir
scope: *Scope
ri: ResultInfo
node: Ast.Node.Index
params: []const Ast.Node.Index

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.unusedResultExpr

函数

第 2656 行

若语句确定为 noreturn,返回其中 noreturn 部分的 AST 源节点。 否则返回 .none。

fn unusedResultExpr(gz: *GenZir, scope: *Scope, statement: Ast.Node.Index) InnerError!Ast.Node.OptionalIndex

参数

gz: *GenZir
scope: *Scope
statement: Ast.Node.Index

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.varDecl

函数

第 3107 行

fn varDecl( gz: *GenZir, scope: *Scope, node: Ast.Node.Index, block_arena: Allocator, var_decl: Ast.full.VarDecl, ) InnerError!*Scope

参数

gz: *GenZir
scope: *Scope
node: Ast.Node.Index
block_arena: Allocator
var_decl: Ast.full.VarDecl

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.whileExpr

函数

第 6425 行

fn whileExpr( parent_gz: *GenZir, scope: *Scope, ri: ResultInfo, node: Ast.Node.Index, while_full: Ast.full.While, is_statement: bool, ) InnerError!Zir.Inst.Ref

参数

parent_gz: *GenZir
scope: *Scope
ri: ResultInfo
node: Ast.Node.Index
while_full: Ast.full.While
is_statement: bool

错误

AnalysisFail
OutOfMemory

std.zig.AstGen.WipDecls

容器

第 3963 行

字段

astgen: *AstGen
slice: Scratch.Slice
index: u32

std.zig.AstGen.WipDecls.finish

函数

第 3975 行

fn finish(wip: *WipDecls) void

参数

wip: *WipDecls

std.zig.AstGen.WipDecls.init

函数

第 3968 行

fn init(scratch: *Scratch, decls_len: u32) Allocator.Error!WipDecls

参数

scratch: *Scratch
decls_len: u32

错误

OutOfMemory

std.zig.AstGen.WipDecls.nextDecl

函数

第 3979 行

fn nextDecl(wip: *WipDecls, decl_inst: Zir.Inst.Index) void

参数

wip: *WipDecls
decl_inst: Zir.Inst.Index

std.zig.AstGen.Zir

别名

第 15 行

别名目标 std.zig.Zir

源码

std/zig/AstGen.zig

//! 接收抽象语法树并生成 ZIR 代码。
const AstGen = @This();

const std = @import("std");
const Ast = std.zig.Ast;
const mem = std.mem;
const Allocator = std.mem.Allocator;
const assert = std.debug.assert;
const ArrayList = std.ArrayList;
const StringIndexAdapter = std.hash_map.StringIndexAdapter;
const StringIndexContext = std.hash_map.StringIndexContext;

const isPrimitive = std.zig.primitives.isPrimitive;

const Zir = std.zig.Zir;
const BuiltinFn = std.zig.BuiltinFn;
const AstRlAnnotate = std.zig.AstRlAnnotate;

gpa: Allocator,
tree: *const Ast,
/// 在存在选择时,必须向子表达式暴露结果指针的节点集合。详情见 `AstRlAnnotate`。
///
nodes_need_rl: *const AstRlAnnotate.RlNeededSet,
instructions: std.MultiArrayList(Zir.Inst) = .{},
extra: ArrayList(u32) = .empty,
string_bytes: ArrayList(u8) = .empty,
/// 跟踪源码文件中的当前字节偏移量。
/// 用于填充 ZIR 中的行号差值。AstGen 在
/// 整个 AST 降低过程中维护此“游标”,
/// 避免为每个声明重新扫描行列,
/// 否则复杂度将为 O(N^2)。
source_offset: u32 = 0,
/// 跟踪 `source_offset` 对应的行。
/// 此值为绝对值。
source_line: u32 = 0,
/// 跟踪 `source_offset` 对应的列。
/// 此值为绝对值。
source_column: u32 = 0,
/// 用于临时分配;AstGen 完成后释放。
/// 生成的 ZIR 代码不会引用此区域中的任何内容。
arena: Allocator,
string_table: std.HashMapUnmanaged(u32, void, StringIndexContext, std.hash_map.default_max_load_percentage) = .empty,
compile_errors: ArrayList(Zir.Inst.CompileErrors.Item) = .empty,
/// 当前函数的最顶层块。
fn_block: ?*GenZir = null,
fn_var_args: bool = false,
/// 当前是否位于函数内部。若为 `true`,任何容器声明都可能是泛型,因此必须通过闭包传递。
///
within_fn: bool = false,
/// 当前函数的返回类型。它可能是简单的 `Ref`,
/// 否则引用一个 `ret_type` 指令。
fn_ret_ty: Zir.Inst.Ref = .none,
/// 将字符串表索引映射到首个将该字符串
/// 用作操作数的 `@import` ZIR 指令。
imports: std.array_hash_map.Auto(Zir.NullTerminatedString, Ast.TokenIndex) = .empty,
/// 构造载荷时用作临时存储。
scratch: std.ArrayList(u32) = .empty,
/// 需要 `ref` 指令时,先创建并保存在此
/// 表中,而不立即追加到当前块体。
/// 随后,将指令加入父块时,通常是在
/// setBlockBody 中,若其存在 ref_table 条目,就在
/// 该位置加入 ref 指令。这样可确保两个性质:
/// 1. 指向同一局部变量的所有指针均返回相同地址,
///    这是符合语言规范所必需的。
/// 2. `ref` 指令支配其全部使用位置,这是 ZIR
///    要求的性质。
/// 键为 ref 操作数,值为 ref 指令。
ref_table: std.AutoHashMapUnmanaged(Zir.Inst.Index, Zir.Inst.Index) = .empty,
/// 任何应触发增量编译数据失效的信息,
/// 均应用于更新此哈希器。最终结果为
/// 外层声明等对象的最终源码哈希。
src_hasher: std.zig.SrcHasher,

const InnerError = error{ OutOfMemory, AnalysisFail };

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

fn addExtraAssumeCapacity(astgen: *AstGen, extra: anytype) u32 {
    const field_count = @typeInfo(@TypeOf(extra)).@"struct".field_names.len;
    const extra_index: u32 = @intCast(astgen.extra.items.len);
    astgen.extra.items.len += field_count;
    setExtra(astgen, extra_index, extra);
    return extra_index;
}

fn setExtra(astgen: *AstGen, index: usize, extra: anytype) void {
    const info = @typeInfo(@TypeOf(extra)).@"struct";
    var i = index;
    inline for (info.field_names, info.field_types) |field_name, field_type| {
        astgen.extra.items[i] = switch (field_type) {
            u32 => @field(extra, field_name),

            Zir.Inst.Ref,
            Zir.Inst.Index,
            Zir.Inst.Declaration.Name,
            std.zig.SimpleComptimeReason,
            Zir.NullTerminatedString,
            // Ast.TokenIndex 因为是 u32 而被省略。
            Ast.OptionalTokenIndex,
            Ast.Node.Index,
            Ast.Node.OptionalIndex,
            => @backingInt(@field(extra, field_name)),

            Ast.TokenOffset,
            Ast.OptionalTokenOffset,
            Ast.Node.Offset,
            Ast.Node.OptionalOffset,
            => @bitCast(@backingInt(@field(extra, field_name))),

            i32,
            Zir.Inst.Call.Flags,
            Zir.Inst.BuiltinCall.Flags,
            Zir.Inst.SwitchBlock.Bits,
            Zir.Inst.FuncFancy.Bits,
            Zir.Inst.Param.Type,
            Zir.Inst.Func.RetTy,
            => @bitCast(@field(extra, field_name)),

            else => @compileError("bad field type"),
        };
        i += 1;
    }
}

fn reserveExtra(astgen: *AstGen, size: usize) Allocator.Error!u32 {
    const extra_index: u32 = @intCast(astgen.extra.items.len);
    try astgen.extra.resize(astgen.gpa, extra_index + size);
    return extra_index;
}

fn appendRefs(astgen: *AstGen, refs: []const Zir.Inst.Ref) !void {
    return astgen.extra.appendSlice(astgen.gpa, @ptrCast(refs));
}

fn appendRefsAssumeCapacity(astgen: *AstGen, refs: []const Zir.Inst.Ref) void {
    astgen.extra.appendSliceAssumeCapacity(@ptrCast(refs));
}

pub fn generate(gpa: Allocator, tree: Ast) Allocator.Error!Zir {
    assert(tree.mode == .zig);

    var arena = std.heap.ArenaAllocator.init(gpa);
    defer arena.deinit();

    var nodes_need_rl = try AstRlAnnotate.annotate(gpa, arena.allocator(), tree);
    defer nodes_need_rl.deinit(gpa);

    var astgen: AstGen = .{
        .gpa = gpa,
        .arena = arena.allocator(),
        .tree = &tree,
        .nodes_need_rl = &nodes_need_rl,
        .src_hasher = undefined, // 根结构体的 `structDeclInner` 会设置此项
    };
    defer astgen.deinit(gpa);

    // 字符串表索引 0 保留给 `NullTerminatedString.empty`。
    try astgen.string_bytes.append(gpa, 0);

    // 预期 ZIR 指令数和额外数据项数至少与 AST 节点数相同。
    //
    try astgen.instructions.ensureTotalCapacity(gpa, tree.nodes.len);

    // extra 的前几个索引被保留,并在最后设置。
    const reserved_count = @typeInfo(Zir.ExtraIndex).@"enum".field_names.len;
    try astgen.extra.ensureTotalCapacity(gpa, tree.nodes.len + reserved_count);
    astgen.extra.items.len += reserved_count;

    var top_scope: Scope.Top = .{};

    var gz_instructions: std.ArrayList(Zir.Inst.Index) = .empty;
    var gen_scope: GenZir = .{
        .is_comptime = true,
        .parent = &top_scope.base,
        .src_baseline = .root,
        .decl_line = 0,
        .astgen = &astgen,
        .instructions = &gz_instructions,
        .instructions_top = 0,
    };
    defer gz_instructions.deinit(gpa);

    // AST -> ZIR 降低过程假定 AST 不含任何解析错误。
    // 解析错误或根结构体中的 AstGen 错误被视为“致命”错误,因此不生成任何 ZIR。
    const fatal = if (tree.errors.len == 0) fatal: {
        if (AstGen.structDeclInner(
            &gen_scope,
            &gen_scope.base,
            .root,
            tree.containerDeclRoot(),
            .auto,
            .none,
            .parent,
        )) |struct_decl_ref| {
            assert(struct_decl_ref.toIndex().? == .main_struct_inst);
            break :fatal false;
        } else |err| switch (err) {
            error.OutOfMemory => |e| return e,
            error.AnalysisFail => break :fatal true, // 通过下方的 compile_errors 处理。
        }
    } else fatal: {
        try lowerAstErrors(&astgen);
        break :fatal true;
    };

    const err_index = @backingInt(Zir.ExtraIndex.compile_errors);
    if (astgen.compile_errors.items.len == 0) {
        astgen.extra.items[err_index] = 0;
    } else {
        try astgen.extra.ensureUnusedCapacity(gpa, 1 + astgen.compile_errors.items.len *
            @typeInfo(Zir.Inst.CompileErrors.Item).@"struct".field_names.len);

        astgen.extra.items[err_index] = astgen.addExtraAssumeCapacity(Zir.Inst.CompileErrors{
            .items_len = @intCast(astgen.compile_errors.items.len),
        });

        for (astgen.compile_errors.items) |item| {
            _ = astgen.addExtraAssumeCapacity(item);
        }
    }

    const imports_index = @backingInt(Zir.ExtraIndex.imports);
    if (astgen.imports.count() == 0) {
        astgen.extra.items[imports_index] = 0;
    } else {
        try astgen.extra.ensureUnusedCapacity(gpa, @typeInfo(Zir.Inst.Imports).@"struct".field_names.len +
            astgen.imports.count() * @typeInfo(Zir.Inst.Imports.Item).@"struct".field_names.len);

        astgen.extra.items[imports_index] = astgen.addExtraAssumeCapacity(Zir.Inst.Imports{
            .imports_len = @intCast(astgen.imports.count()),
        });

        var it = astgen.imports.iterator();
        while (it.next()) |entry| {
            _ = astgen.addExtraAssumeCapacity(Zir.Inst.Imports.Item{
                .name = entry.key_ptr.*,
                .token = entry.value_ptr.*,
            });
        }
    }

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

    return .{
        .instructions = if (fatal) .empty else astgen.instructions.toOwnedSlice(),
        .string_bytes = astgen.string_bytes.toOwnedSliceAssert(),
        .extra = astgen.extra.toOwnedSliceAssert(),
    };
}

fn deinit(astgen: *AstGen, gpa: Allocator) void {
    astgen.instructions.deinit(gpa);
    astgen.extra.deinit(gpa);
    astgen.string_table.deinit(gpa);
    astgen.string_bytes.deinit(gpa);
    astgen.compile_errors.deinit(gpa);
    astgen.imports.deinit(gpa);
    astgen.scratch.deinit(gpa);
    astgen.ref_table.deinit(gpa);
}

const ResultInfo = struct {
    /// 结果位置所需的语义
    rl: Loc,

    /// 使用结果位置的“运算符”
    ctx: Context = .none,

    /// 将 `coerced_ty` 转回 `ty`。应在 if、switch 表达式
    /// 等分支点调用。
    fn br(ri: ResultInfo) ResultInfo {
        return switch (ri.rl) {
            .coerced_ty => |ty| .{
                .rl = .{ .ty = ty },
                .ctx = ri.ctx,
            },
            else => ri,
        };
    }

    fn zirTag(ri: ResultInfo) Zir.Inst.Tag {
        switch (ri.rl) {
            .ty => return switch (ri.ctx) {
                .shift_op => .as_shift_operand,
                else => .as_node,
            },
            else => unreachable,
        }
    }

    const Loc = union(enum) {
        /// 表达式是赋值给 `_` 的右值。只应生成表达式的副作用。
        /// 必须忽略表达式产生的结果指令。
        ///
        discard,
        /// 表达式的类型为推断类型,并将按右值求值。
        none,
        /// 表达式将强制转换为此类型,但会作为右值求值。
        ty: Zir.Inst.Ref,
        /// 与 `ty` 相同,但保证 Sema 还会执行强制转换,因此无需输出 `as` 指令。
        ///
        coerced_ty: Zir.Inst.Ref,
        /// 表达式必须生成指针,而非值。例如,
        /// 赋值的左侧使用此类结果位置。
        ref,
        /// 表达式必须生成指针而非值,其他代码会将该指针强制转换为此类型;
        /// 先前指令已保证此类型为指针类型。
        ref_coerced_ty: Zir.Inst.Ref,
        /// 类似于 `ref`,但永远不会通过该指针存储,因此不应将局部变量
        /// 标记为可能被修改。
        ref_const,
        /// 表达式必须将结果存入此有类型指针。
        /// 必须忽略表达式的结果指令。
        ptr: PtrResultLoc,
        /// 表达式必须将结果存入此分配块,其类型由推导确定。
        /// 必须忽略表达式的结果指令。
        /// 始终为标签是 `alloc_inferred` 的指令。
        inferred_ptr: Zir.Inst.Ref,
        /// 由于解构操作,此表达式有一组用于存储结果的指针。
        /// 每个指针的类型可能需要推导,也可能不需要。
        destructure: struct {
            /// 解构操作本身的 AST 节点。
            src_node: Ast.Node.Index,
            /// 用于存储结果的指针。
            components: []const DestructureComponent,
        },

        const DestructureComponent = union(enum) {
            typed_ptr: PtrResultLoc,
            inferred_ptr: Zir.Inst.Ref,
            discard,
        };

        const PtrResultLoc = struct {
            inst: Zir.Inst.Ref,
            src_node: ?Ast.Node.Index = null,
        };

        /// 根据结果位置查找转换内置函数的结果类型。
        /// 若位置没有已知结果类型,则返回 `null`。
        fn resultType(rl: Loc, gz: *GenZir, node: Ast.Node.Index) !?Zir.Inst.Ref {
            return switch (rl) {
                .discard, .none, .ref, .ref_const, .inferred_ptr, .destructure => null,
                .ty, .coerced_ty => |ty_ref| ty_ref,
                .ref_coerced_ty => |ptr_ty| try gz.addUnNode(.elem_type, ptr_ty, node),
                .ptr => |ptr| {
                    const ptr_ty = try gz.addUnNode(.typeof, ptr.inst, node);
                    return try gz.addUnNode(.elem_type, ptr_ty, node);
                },
            };
        }

        /// 根据结果位置查找转换内置函数的结果类型。
        /// 若该位置没有已知结果类型,则在给定节点上报错。
        ///
        fn resultTypeForCast(rl: Loc, gz: *GenZir, node: Ast.Node.Index, builtin_name: []const u8) !Zir.Inst.Ref {
            const astgen = gz.astgen;
            if (try rl.resultType(gz, node)) |ty| return ty;
            switch (rl) {
                .destructure => |destructure| return astgen.failNodeNotes(node, "{s} must have a known result type", .{builtin_name}, &.{
                    try astgen.errNoteNode(destructure.src_node, "destructure expressions do not provide a single result type", .{}),
                    try astgen.errNoteNode(node, "use @as to provide explicit result type", .{}),
                }),
                else => return astgen.failNodeNotes(node, "{s} must have a known result type", .{builtin_name}, &.{
                    try astgen.errNoteNode(node, "use @as to provide explicit result type", .{}),
                }),
            }
        }
    };

    const Context = enum {
        /// 此表达式是 return 表达式的操作数。
        @"return",
        /// 此表达式是错误处理运算符(if-else、try 或 catch)的输入。
        error_handling_expr,
        /// 该表达式是移位操作的右侧操作数。
        shift_op,
        /// 此表达式是函数调用中的参数。
        fn_arg,
        /// 此表达式是 `const` 变量初始化器的右侧表达式。
        const_init,
        /// 表达式是赋值表达式的右侧操作数。
        assignment,
        /// 没有特定运算符。
        none,
        /// 该表达式是取地址操作数,而取地址表达式又是 return 表达式的操作数。
        return_addrof,
    };
};

const coerced_align_ri: ResultInfo = .{ .rl = .{ .coerced_ty = .u29_type } };
const coerced_linksection_ri: ResultInfo = .{ .rl = .{ .coerced_ty = .slice_const_u8_type } };
const coerced_type_ri: ResultInfo = .{ .rl = .{ .coerced_ty = .type_type } };
const coerced_bool_ri: ResultInfo = .{ .rl = .{ .coerced_ty = .bool_type } };

fn typeExpr(gz: *GenZir, scope: *Scope, type_node: Ast.Node.Index) InnerError!Zir.Inst.Ref {
    return comptimeExpr(gz, scope, coerced_type_ri, type_node, .type);
}

fn reachableTypeExpr(
    gz: *GenZir,
    scope: *Scope,
    type_node: Ast.Node.Index,
    reachable_node: Ast.Node.Index,
) InnerError!Zir.Inst.Ref {
    return reachableExprComptime(gz, scope, coerced_type_ri, type_node, reachable_node, .type);
}

/// 与 `expr` 相同,但如果结果类型为 `noreturn`,则以编译错误失败。
fn reachableExpr(
    gz: *GenZir,
    scope: *Scope,
    ri: ResultInfo,
    node: Ast.Node.Index,
    reachable_node: Ast.Node.Index,
) InnerError!Zir.Inst.Ref {
    return reachableExprComptime(gz, scope, ri, node, reachable_node, null);
}

fn reachableExprComptime(
    gz: *GenZir,
    scope: *Scope,
    ri: ResultInfo,
    node: Ast.Node.Index,
    reachable_node: Ast.Node.Index,
    /// 若为 `null`,则表达式不在编译期上下文中求值。
    comptime_reason: ?std.zig.SimpleComptimeReason,
) InnerError!Zir.Inst.Ref {
    const result_inst = if (comptime_reason) |r|
        try comptimeExpr(gz, scope, ri, node, r)
    else
        try expr(gz, scope, ri, node);

    if (gz.refIsNoReturn(result_inst)) {
        try gz.astgen.appendErrorNodeNotes(reachable_node, "unreachable code", .{}, &[_]u32{
            try gz.astgen.errNoteNode(node, "control flow is diverted here", .{}),
        });
    }
    return result_inst;
}

fn lvalExpr(gz: *GenZir, scope: *Scope, node: Ast.Node.Index) InnerError!Zir.Inst.Ref {
    const astgen = gz.astgen;
    const tree = astgen.tree;
    switch (tree.nodeTag(node)) {
        .root => unreachable,
        .test_decl => unreachable,
        .global_var_decl => unreachable,
        .local_var_decl => unreachable,
        .simple_var_decl => unreachable,
        .aligned_var_decl => unreachable,
        .switch_case => unreachable,
        .switch_case_inline => unreachable,
        .switch_case_one => unreachable,
        .switch_case_inline_one => unreachable,
        .container_field_init => unreachable,
        .container_field_align => unreachable,
        .container_field => unreachable,
        .asm_output => unreachable,
        .asm_input => unreachable,

        .assign,
        .assign_destructure,
        .assign_bit_and,
        .assign_bit_or,
        .assign_shl,
        .assign_shl_sat,
        .assign_shr,
        .assign_bit_xor,
        .assign_div,
        .assign_sub,
        .assign_sub_wrap,
        .assign_sub_sat,
        .assign_mod,
        .assign_add,
        .assign_add_wrap,
        .assign_add_sat,
        .assign_mul,
        .assign_mul_wrap,
        .assign_mul_sat,
        .add,
        .add_wrap,
        .add_sat,
        .sub,
        .sub_wrap,
        .sub_sat,
        .mul,
        .mul_wrap,
        .mul_sat,
        .div,
        .mod,
        .bit_and,
        .bit_or,
        .shl,
        .shl_sat,
        .shr,
        .bit_xor,
        .bang_equal,
        .equal_equal,
        .greater_than,
        .greater_or_equal,
        .less_than,
        .less_or_equal,
        .array_cat,
        .bool_and,
        .bool_or,
        .@"asm",
        .asm_simple,
        .string_literal,
        .number_literal,
        .call,
        .call_comma,
        .call_one,
        .call_one_comma,
        .unreachable_literal,
        .@"return",
        .@"if",
        .if_simple,
        .@"while",
        .while_simple,
        .while_cont,
        .bool_not,
        .address_of,
        .optional_type,
        .block,
        .block_semicolon,
        .block_two,
        .block_two_semicolon,
        .@"break",
        .ptr_type_aligned,
        .ptr_type_sentinel,
        .ptr_type,
        .ptr_type_bit_range,
        .array_type,
        .array_type_sentinel,
        .enum_literal,
        .multiline_string_literal,
        .char_literal,
        .@"defer",
        .@"errdefer",
        .@"catch",
        .error_union,
        .merge_error_sets,
        .switch_range,
        .for_range,
        .bit_not,
        .negation,
        .negation_wrap,
        .@"resume",
        .@"try",
        .slice,
        .slice_open,
        .slice_sentinel,
        .array_init_one,
        .array_init_one_comma,
        .array_init_dot_two,
        .array_init_dot_two_comma,
        .array_init_dot,
        .array_init_dot_comma,
        .array_init,
        .array_init_comma,
        .struct_init_one,
        .struct_init_one_comma,
        .struct_init_dot_two,
        .struct_init_dot_two_comma,
        .struct_init_dot,
        .struct_init_dot_comma,
        .struct_init,
        .struct_init_comma,
        .@"switch",
        .switch_comma,
        .@"for",
        .for_simple,
        .@"suspend",
        .@"continue",
        .fn_proto_simple,
        .fn_proto_multi,
        .fn_proto_one,
        .fn_proto,
        .fn_decl,
        .anyframe_type,
        .anyframe_literal,
        .error_set_decl,
        .container_decl,
        .container_decl_trailing,
        .container_decl_two,
        .container_decl_two_trailing,
        .container_decl_arg,
        .container_decl_arg_trailing,
        .tagged_union,
        .tagged_union_trailing,
        .tagged_union_two,
        .tagged_union_two_trailing,
        .tagged_union_enum_tag,
        .tagged_union_enum_tag_trailing,
        .@"comptime",
        .@"nosuspend",
        .error_value,
        => return astgen.failNode(node, "invalid left-hand side to assignment", .{}),

        .builtin_call,
        .builtin_call_comma,
        .builtin_call_two,
        .builtin_call_two_comma,
        => {
            const builtin_token = tree.nodeMainToken(node);
            const builtin_name = tree.tokenSlice(builtin_token);
            // 若内置函数名称无效,此处不报错,而是允许通过,稍后再报告“invalid builtin function”。
            //
            if (BuiltinFn.list.get(builtin_name)) |info| {
                if (!info.allows_lvalue) {
                    return astgen.failNode(node, "invalid left-hand side to assignment", .{});
                }
            }
        },

        // 这些项可以被赋值。
        .unwrap_optional,
        .deref,
        .field_access,
        .array_access,
        .identifier,
        .grouped_expression,
        .@"orelse",
        => {},
    }
    return expr(gz, scope, .{ .rl = .ref }, node);
}

/// 将 Zig AST 转换为无类型 ZIR 指令。
/// 当 `rl` 为 discard、ptr、inferred_ptr 或 inferred_ptr 时,
/// 结果指令仅能用于检查是否为 isNoReturn(),
/// 不得作任何其他用途。
fn expr(gz: *GenZir, scope: *Scope, ri: ResultInfo, node: Ast.Node.Index) InnerError!Zir.Inst.Ref {
    const astgen = gz.astgen;
    const tree = astgen.tree;

    switch (tree.nodeTag(node)) {
        .root => unreachable, // 顶层声明。
        .test_decl => unreachable, // 顶层声明。
        .container_field_init => unreachable, // 顶层声明。
        .container_field_align => unreachable, // 顶层声明。
        .container_field => unreachable, // 顶层声明。
        .fn_decl => unreachable, // 顶层声明。

        .global_var_decl => unreachable, // 在 `blockExpr` 中处理。
        .local_var_decl => unreachable, // 在 `blockExpr` 中处理。
        .simple_var_decl => unreachable, // 在 `blockExpr` 中处理。
        .aligned_var_decl => unreachable, // 在 `blockExpr` 中处理。
        .@"defer" => unreachable, // 在 `blockExpr` 中处理。
        .@"errdefer" => unreachable, // 在 `blockExpr` 中处理。

        .switch_case => unreachable, // 在 `switchExpr` 中处理。
        .switch_case_inline => unreachable, // 在 `switchExpr` 中处理。
        .switch_case_one => unreachable, // 在 `switchExpr` 中处理。
        .switch_case_inline_one => unreachable, // 在 `switchExpr` 中处理。
        .switch_range => unreachable, // 在 `switchExpr` 中处理。

        .asm_output => unreachable, // 由 `asmExpr` 处理。
        .asm_input => unreachable, // 由 `asmExpr` 处理。

        .for_range => unreachable, // 在 `forExpr` 中处理。

        .assign => {
            try assign(gz, scope, node);
            return rvalue(gz, ri, .void_value, node);
        },

        .assign_destructure => {
            // 注意,此变体不声明任何新的 var/const;
            // 声明它们的变体由 `blockExprStmts` 处理。
            try assignDestructure(gz, scope, node);
            return rvalue(gz, ri, .void_value, node);
        },

        .assign_shl => {
            try assignShift(gz, scope, node, .shl);
            return rvalue(gz, ri, .void_value, node);
        },
        .assign_shl_sat => {
            try assignShiftSat(gz, scope, node);
            return rvalue(gz, ri, .void_value, node);
        },
        .assign_shr => {
            try assignShift(gz, scope, node, .shr);
            return rvalue(gz, ri, .void_value, node);
        },

        .assign_bit_and => {
            try assignOp(gz, scope, node, .bit_and);
            return rvalue(gz, ri, .void_value, node);
        },
        .assign_bit_or => {
            try assignOp(gz, scope, node, .bit_or);
            return rvalue(gz, ri, .void_value, node);
        },
        .assign_bit_xor => {
            try assignOp(gz, scope, node, .xor);
            return rvalue(gz, ri, .void_value, node);
        },
        .assign_div => {
            try assignOp(gz, scope, node, .div);
            return rvalue(gz, ri, .void_value, node);
        },
        .assign_sub => {
            try assignOp(gz, scope, node, .sub);
            return rvalue(gz, ri, .void_value, node);
        },
        .assign_sub_wrap => {
            try assignOp(gz, scope, node, .subwrap);
            return rvalue(gz, ri, .void_value, node);
        },
        .assign_sub_sat => {
            try assignOp(gz, scope, node, .sub_sat);
            return rvalue(gz, ri, .void_value, node);
        },
        .assign_mod => {
            try assignOp(gz, scope, node, .mod_rem);
            return rvalue(gz, ri, .void_value, node);
        },
        .assign_add => {
            try assignOp(gz, scope, node, .add);
            return rvalue(gz, ri, .void_value, node);
        },
        .assign_add_wrap => {
            try assignOp(gz, scope, node, .addwrap);
            return rvalue(gz, ri, .void_value, node);
        },
        .assign_add_sat => {
            try assignOp(gz, scope, node, .add_sat);
            return rvalue(gz, ri, .void_value, node);
        },
        .assign_mul => {
            try assignOp(gz, scope, node, .mul);
            return rvalue(gz, ri, .void_value, node);
        },
        .assign_mul_wrap => {
            try assignOp(gz, scope, node, .mulwrap);
            return rvalue(gz, ri, .void_value, node);
        },
        .assign_mul_sat => {
            try assignOp(gz, scope, node, .mul_sat);
            return rvalue(gz, ri, .void_value, node);
        },

        // zig fmt: off
        .shl => return shiftOp(gz, scope, ri, node, tree.nodeData(node).node_and_node[0], tree.nodeData(node).node_and_node[1], .shl),
        .shr => return shiftOp(gz, scope, ri, node, tree.nodeData(node).node_and_node[0], tree.nodeData(node).node_and_node[1], .shr),

        .add      => return simpleBinOp(gz, scope, ri, node, .add),
        .add_wrap => return simpleBinOp(gz, scope, ri, node, .addwrap),
        .add_sat  => return simpleBinOp(gz, scope, ri, node, .add_sat),
        .sub      => return simpleBinOp(gz, scope, ri, node, .sub),
        .sub_wrap => return simpleBinOp(gz, scope, ri, node, .subwrap),
        .sub_sat  => return simpleBinOp(gz, scope, ri, node, .sub_sat),
        .mul      => return simpleBinOp(gz, scope, ri, node, .mul),
        .mul_wrap => return simpleBinOp(gz, scope, ri, node, .mulwrap),
        .mul_sat  => return simpleBinOp(gz, scope, ri, node, .mul_sat),
        .div      => return simpleBinOp(gz, scope, ri, node, .div),
        .mod      => return simpleBinOp(gz, scope, ri, node, .mod_rem),
        .shl_sat  => return simpleBinOp(gz, scope, ri, node, .shl_sat),

        .bit_and          => return simpleBinOp(gz, scope, ri, node, .bit_and),
        .bit_or           => return simpleBinOp(gz, scope, ri, node, .bit_or),
        .bit_xor          => return simpleBinOp(gz, scope, ri, node, .xor),
        .bang_equal       => return simpleBinOp(gz, scope, ri, node, .cmp_neq),
        .equal_equal      => return simpleBinOp(gz, scope, ri, node, .cmp_eq),
        .greater_than     => return simpleBinOp(gz, scope, ri, node, .cmp_gt),
        .greater_or_equal => return simpleBinOp(gz, scope, ri, node, .cmp_gte),
        .less_than        => return simpleBinOp(gz, scope, ri, node, .cmp_lt),
        .less_or_equal    => return simpleBinOp(gz, scope, ri, node, .cmp_lte),
        .array_cat        => return simpleBinOp(gz, scope, ri, node, .array_cat),

        .error_union, .merge_error_sets => |tag| {
            const inst_tag: Zir.Inst.Tag = switch (tag) {
                .error_union => .error_union_type,
                .merge_error_sets => .merge_error_sets,
                else => unreachable,
            };
            const lhs_node, const rhs_node = tree.nodeData(node).node_and_node;
            const lhs = try reachableTypeExpr(gz, scope, lhs_node, node);
            const rhs = try reachableTypeExpr(gz, scope, rhs_node, node);
            const result = try gz.addPlNode(inst_tag, node, Zir.Inst.Bin{ .lhs = lhs, .rhs = rhs });
            return rvalue(gz, ri, result, node);
        },

        .bool_and => return boolBinOp(gz, scope, ri, node, .bool_br_and),
        .bool_or  => return boolBinOp(gz, scope, ri, node, .bool_br_or),

        .bool_not => return simpleUnOp(gz, scope, ri, node, .{ .rl = .none }, tree.nodeData(node).node, .bool_not),
        .bit_not  => return simpleUnOp(gz, scope, ri, node, .{ .rl = .none }, tree.nodeData(node).node, .bit_not),

        .negation      => return   negation(gz, scope, ri, node),
        .negation_wrap => return simpleUnOp(gz, scope, ri, node, .{ .rl = .none }, tree.nodeData(node).node, .negate_wrap),

        .identifier => return identifier(gz, scope, ri, node, null),

        .asm_simple,
        .@"asm",
        => return asmExpr(gz, scope, ri, node, tree.fullAsm(node).?),

        .string_literal           => return stringLiteral(gz, ri, node),
        .multiline_string_literal => return multilineStringLiteral(gz, ri, node),

        .number_literal => return numberLiteral(gz, ri, node, node, .positive),
        // zig fmt: on

        .builtin_call_two,
        .builtin_call_two_comma,
        .builtin_call,
        .builtin_call_comma,
        => {
            var buf: [2]Ast.Node.Index = undefined;
            const params = tree.builtinCallParams(&buf, node).?;
            return builtinCall(gz, scope, ri, node, params, false, .anon);
        },

        .call_one,
        .call_one_comma,
        .call,
        .call_comma,
        => {
            var buf: [1]Ast.Node.Index = undefined;
            return callExpr(gz, scope, ri, .none, node, tree.fullCall(&buf, node).?);
        },

        .unreachable_literal => {
            try emitDbgNode(gz, node);
            _ = try gz.addAsIndex(.{
                .tag = .@"unreachable",
                .data = .{ .@"unreachable" = .{
                    .src_node = gz.nodeIndexToRelative(node),
                } },
            });
            return Zir.Inst.Ref.unreachable_value;
        },
        .@"return" => return ret(gz, scope, node),
        .field_access => return fieldAccess(gz, scope, ri, node),

        .if_simple,
        .@"if",
        => {
            const if_full = tree.fullIf(node).?;
            no_switch_on_err: {
                const error_token = if_full.error_token orelse break :no_switch_on_err;
                const else_node = if_full.ast.else_expr.unwrap() orelse break :no_switch_on_err;
                const switch_full = tree.fullSwitch(else_node) orelse break :no_switch_on_err;
                if (switch_full.label_token != null) break :no_switch_on_err; // 在 `ifExpr` 中处理
                if (tree.nodeTag(switch_full.ast.condition) != .identifier) break :no_switch_on_err;
                if (!try astgen.tokenIdentEql(error_token, tree.nodeMainToken(switch_full.ast.condition))) break :no_switch_on_err;
                return switchExpr(gz, scope, ri.br(), node, switch_full, .{ .@"if" = if_full });
            }
            return ifExpr(gz, scope, ri.br(), node, if_full);
        },

        .while_simple,
        .while_cont,
        .@"while",
        => return whileExpr(gz, scope, ri.br(), node, tree.fullWhile(node).?, false),

        .for_simple, .@"for" => return forExpr(gz, scope, ri.br(), node, tree.fullFor(node).?, false),

        .slice_open,
        .slice,
        .slice_sentinel,
        => {
            const full = tree.fullSlice(node).?;
            if (full.ast.end != .none and
                tree.nodeTag(full.ast.sliced) == .slice_open and
                nodeIsTriviallyZero(tree, full.ast.start))
            {
                const lhs_extra = tree.sliceOpen(full.ast.sliced).ast;

                const lhs = try expr(gz, scope, .{ .rl = .ref }, lhs_extra.sliced);
                const start = try expr(gz, scope, .{ .rl = .{ .coerced_ty = .usize_type } }, lhs_extra.start);
                const cursor = maybeAdvanceSourceCursorToMainToken(gz, node);
                const len = try expr(gz, scope, .{ .rl = .{ .coerced_ty = .usize_type } }, full.ast.end.unwrap().?);
                const sentinel = if (full.ast.sentinel.unwrap()) |sentinel| s: {
                    const sentinel_ty = try gz.addUnNode(.slice_sentinel_ty, lhs, node);
                    break :s try expr(gz, scope, .{ .rl = .{ .coerced_ty = sentinel_ty } }, sentinel);
                } else .none;
                try emitDbgStmt(gz, cursor);
                const result = try gz.addPlNode(.slice_length, node, Zir.Inst.SliceLength{
                    .lhs = lhs,
                    .start = start,
                    .len = len,
                    .start_src_node_offset = gz.nodeIndexToRelative(full.ast.sliced),
                    .sentinel = sentinel,
                });
                return rvalue(gz, ri, result, node);
            }
            const lhs = try expr(gz, scope, .{ .rl = .ref }, full.ast.sliced);

            const cursor = maybeAdvanceSourceCursorToMainToken(gz, node);
            const start = try expr(gz, scope, .{ .rl = .{ .coerced_ty = .usize_type } }, full.ast.start);
            const end = if (full.ast.end.unwrap()) |end| try expr(gz, scope, .{ .rl = .{ .coerced_ty = .usize_type } }, end) else .none;
            const sentinel = if (full.ast.sentinel.unwrap()) |sentinel| s: {
                const sentinel_ty = try gz.addUnNode(.slice_sentinel_ty, lhs, node);
                break :s try expr(gz, scope, .{ .rl = .{ .coerced_ty = sentinel_ty } }, sentinel);
            } else .none;
            try emitDbgStmt(gz, cursor);
            if (sentinel != .none) {
                const result = try gz.addPlNode(.slice_sentinel, node, Zir.Inst.SliceSentinel{
                    .lhs = lhs,
                    .start = start,
                    .end = end,
                    .sentinel = sentinel,
                });
                return rvalue(gz, ri, result, node);
            } else if (end != .none) {
                const result = try gz.addPlNode(.slice_end, node, Zir.Inst.SliceEnd{
                    .lhs = lhs,
                    .start = start,
                    .end = end,
                });
                return rvalue(gz, ri, result, node);
            } else {
                const result = try gz.addPlNode(.slice_start, node, Zir.Inst.SliceStart{
                    .lhs = lhs,
                    .start = start,
                });
                return rvalue(gz, ri, result, node);
            }
        },

        .deref => {
            const lhs = try expr(gz, scope, .{ .rl = .none }, tree.nodeData(node).node);
            switch (ri.rl) {
                .ref,
                .ref_coerced_ty,
                .ref_const,
                => return gz.addUnNode(.ref_deref, lhs, node),

                else => {
                    const result = try gz.addUnNode(.deref, lhs, node);
                    return rvalue(gz, ri, result, node);
                },
            }
        },
        .address_of => {
            const operand_rl: ResultInfo.Loc = if (try ri.rl.resultType(gz, node)) |res_ty_inst| rl: {
                _ = try gz.addUnTok(.validate_ref_ty, res_ty_inst, tree.firstToken(node));
                break :rl .{ .ref_coerced_ty = res_ty_inst };
            } else .ref;
            const operand_node = tree.nodeData(node).node;
            const result = try expr(gz, scope, .{
                .rl = operand_rl,
                .ctx = switch (ri.ctx) {
                    .@"return" => .return_addrof,
                    else => .none,
                },
            }, operand_node);
            return rvalue(gz, ri, result, node);
        },
        .optional_type => {
            const operand = try typeExpr(gz, scope, tree.nodeData(node).node);
            const result = try gz.addUnNode(.optional_type, operand, node);
            return rvalue(gz, ri, result, node);
        },
        .unwrap_optional => switch (ri.rl) {
            .ref, .ref_coerced_ty => {
                const lhs = try expr(gz, scope, .{ .rl = .ref }, tree.nodeData(node).node_and_token[0]);

                const cursor = maybeAdvanceSourceCursorToMainToken(gz, node);
                try emitDbgStmt(gz, cursor);

                return gz.addUnNode(.optional_payload_safe_ptr, lhs, node);
            },
            .ref_const => {
                const lhs = try expr(gz, scope, .{ .rl = .ref_const }, tree.nodeData(node).node_and_token[0]);

                const cursor = maybeAdvanceSourceCursorToMainToken(gz, node);
                try emitDbgStmt(gz, cursor);

                return gz.addUnNode(.optional_payload_safe_ptr, lhs, node);
            },
            else => {
                const lhs = try expr(gz, scope, .{ .rl = .none }, tree.nodeData(node).node_and_token[0]);

                const cursor = maybeAdvanceSourceCursorToMainToken(gz, node);
                try emitDbgStmt(gz, cursor);

                return rvalue(gz, ri, try gz.addUnNode(.optional_payload_safe, lhs, node), node);
            },
        },
        .block_two,
        .block_two_semicolon,
        .block,
        .block_semicolon,
        => {
            var buf: [2]Ast.Node.Index = undefined;
            const statements = tree.blockStatements(&buf, node).?;
            return blockExpr(gz, scope, ri, node, statements, .normal);
        },
        .enum_literal => if (try ri.rl.resultType(gz, node)) |res_ty| {
            const str_index = try astgen.identAsString(tree.nodeMainToken(node));
            const res = try gz.addPlNode(.decl_literal, node, Zir.Inst.Field{
                .lhs = res_ty,
                .field_name_start = str_index,
            });
            switch (ri.rl) {
                .discard, .none, .ref, .ref_const, .inferred_ptr, .destructure => unreachable, // 无结果类型
                .ty, .coerced_ty => return res, // `decl_literal` 会代为执行强制转换
                .ref_coerced_ty, .ptr => return rvalue(gz, ri, res, node),
            }
        } else return simpleStrTok(gz, ri, tree.nodeMainToken(node), node, .enum_literal),
        .error_value => return simpleStrTok(gz, ri, tree.nodeMainToken(node) + 2, node, .error_value),
        // TODO 实现 https://github.com/ziglang/zig/issues/6025 时恢复此处
        // .anyframe_literal => return rvalue(gz, ri, .anyframe_type, node),
        .anyframe_literal => {
            const result = try gz.addUnNode(.anyframe_type, .void_type, node);
            return rvalue(gz, ri, result, node);
        },
        .anyframe_type => {
            const return_type = try typeExpr(gz, scope, tree.nodeData(node).token_and_node[1]);
            const result = try gz.addUnNode(.anyframe_type, return_type, node);
            return rvalue(gz, ri, result, node);
        },
        .@"catch" => {
            const catch_token = tree.nodeMainToken(node);
            const payload_token: ?Ast.TokenIndex = if (tree.tokenTag(catch_token + 1) == .pipe)
                catch_token + 2
            else
                null;
            no_switch_on_err: {
                const capture_token = payload_token orelse break :no_switch_on_err;
                const switch_full = tree.fullSwitch(tree.nodeData(node).node_and_node[1]) orelse break :no_switch_on_err;
                if (switch_full.label_token != null) break :no_switch_on_err; // 由 `orelseCatchExpr` 处理
                if (tree.nodeTag(switch_full.ast.condition) != .identifier) break :no_switch_on_err;
                if (!try astgen.tokenIdentEql(capture_token, tree.nodeMainToken(switch_full.ast.condition))) break :no_switch_on_err;
                return switchExpr(gz, scope, ri.br(), node, switch_full, .@"catch");
            }
            switch (ri.rl) {
                .ref, .ref_const, .ref_coerced_ty => return orelseCatchExpr(
                    gz,
                    scope,
                    ri,
                    node,
                    .is_non_err_ptr,
                    .err_union_payload_unsafe_ptr,
                    .err_union_code_ptr,
                    payload_token,
                ),
                else => return orelseCatchExpr(
                    gz,
                    scope,
                    ri,
                    node,
                    .is_non_err,
                    .err_union_payload_unsafe,
                    .err_union_code,
                    payload_token,
                ),
            }
        },
        .@"orelse" => switch (ri.rl) {
            .ref, .ref_const, .ref_coerced_ty => return orelseCatchExpr(
                gz,
                scope,
                ri,
                node,
                .is_non_null_ptr,
                .optional_payload_unsafe_ptr,
                undefined,
                null,
            ),
            else => return orelseCatchExpr(
                gz,
                scope,
                ri,
                node,
                .is_non_null,
                .optional_payload_unsafe,
                undefined,
                null,
            ),
        },

        .ptr_type_aligned,
        .ptr_type_sentinel,
        .ptr_type,
        .ptr_type_bit_range,
        => return ptrType(gz, scope, ri, node, tree.fullPtrType(node).?),

        .container_decl,
        .container_decl_trailing,
        .container_decl_arg,
        .container_decl_arg_trailing,
        .container_decl_two,
        .container_decl_two_trailing,
        .tagged_union,
        .tagged_union_trailing,
        .tagged_union_enum_tag,
        .tagged_union_enum_tag_trailing,
        .tagged_union_two,
        .tagged_union_two_trailing,
        => {
            var buf: [2]Ast.Node.Index = undefined;
            return containerDecl(gz, scope, ri, node, tree.fullContainerDecl(&buf, node).?, .anon);
        },

        .@"break" => return breakExpr(gz, scope, node),
        .@"continue" => return continueExpr(gz, scope, node),
        .grouped_expression => return expr(gz, scope, ri, tree.nodeData(node).node_and_token[0]),
        .array_type => return arrayType(gz, scope, ri, node),
        .array_type_sentinel => return arrayTypeSentinel(gz, scope, ri, node),
        .char_literal => return charLiteral(gz, ri, node),
        .error_set_decl => return errorSetDecl(gz, ri, node),
        .array_access => return arrayAccess(gz, scope, ri, node),
        .@"comptime" => return comptimeExprAst(gz, scope, ri, node),
        .@"switch", .switch_comma => return switchExpr(gz, scope, ri.br(), node, tree.fullSwitch(node).?, .none),

        .@"nosuspend" => return nosuspendExpr(gz, scope, ri, node),
        .@"suspend" => return suspendExpr(gz, scope, node),
        .@"resume" => return resumeExpr(gz, scope, ri, node),

        .@"try" => return tryExpr(gz, scope, ri, node, tree.nodeData(node).node),

        .array_init_one,
        .array_init_one_comma,
        .array_init_dot_two,
        .array_init_dot_two_comma,
        .array_init_dot,
        .array_init_dot_comma,
        .array_init,
        .array_init_comma,
        => {
            var buf: [2]Ast.Node.Index = undefined;
            return arrayInitExpr(gz, scope, ri, node, tree.fullArrayInit(&buf, node).?);
        },

        .struct_init_one,
        .struct_init_one_comma,
        .struct_init_dot_two,
        .struct_init_dot_two_comma,
        .struct_init_dot,
        .struct_init_dot_comma,
        .struct_init,
        .struct_init_comma,
        => {
            var buf: [2]Ast.Node.Index = undefined;
            return structInitExpr(gz, scope, ri, node, tree.fullStructInit(&buf, node).?);
        },

        .fn_proto_simple,
        .fn_proto_multi,
        .fn_proto_one,
        .fn_proto,
        => {
            var buf: [1]Ast.Node.Index = undefined;
            return fnProtoExpr(gz, scope, ri, node, tree.fullFnProto(&buf, node).?);
        },
    }
}

/// 存在 `.anon` 之外的命名策略时,例如分析变量声明的初始化表达式,
/// 应先尝试此函数,再使用 `expr`、`comptimeExpr` 等,以便必要时应用该命名
/// 策略。若返回 `null`,表示 `node` 不消耗命名
/// 策略,应改用 `expr` 等普通求值函数。否则,`node`
/// 确实消耗命名策略:表达式已按 `expr` 的方式求值,但使用了给定
/// 命名策略。
fn nameStratExpr(
    gz: *GenZir,
    scope: *Scope,
    ri: ResultInfo,
    node: Ast.Node.Index,
    name_strat: Zir.Inst.NameStrategy,
) InnerError!?Zir.Inst.Ref {
    const astgen = gz.astgen;
    const tree = astgen.tree;
    switch (tree.nodeTag(node)) {
        .container_decl,
        .container_decl_trailing,
        .container_decl_two,
        .container_decl_two_trailing,
        .container_decl_arg,
        .container_decl_arg_trailing,
        .tagged_union,
        .tagged_union_trailing,
        .tagged_union_two,
        .tagged_union_two_trailing,
        .tagged_union_enum_tag,
        .tagged_union_enum_tag_trailing,
        => {
            var buf: [2]Ast.Node.Index = undefined;
            return try containerDecl(gz, scope, ri, node, tree.fullContainerDecl(&buf, node).?, name_strat);
        },
        .builtin_call_two,
        .builtin_call_two_comma,
        .builtin_call,
        .builtin_call_comma,
        => {
            const builtin_token = tree.nodeMainToken(node);
            const builtin_name = tree.tokenSlice(builtin_token);
            const info = BuiltinFn.list.get(builtin_name) orelse return null;
            switch (info.tag) {
                .Enum, .Struct, .Union => {
                    var buf: [2]Ast.Node.Index = undefined;
                    const params = tree.builtinCallParams(&buf, node).?;
                    return try builtinCall(gz, scope, ri, node, params, false, name_strat);
                },
                else => return null,
            }
        },
        else => return null,
    }
}

fn nosuspendExpr(
    gz: *GenZir,
    scope: *Scope,
    ri: ResultInfo,
    node: Ast.Node.Index,
) InnerError!Zir.Inst.Ref {
    const astgen = gz.astgen;
    const tree = astgen.tree;
    const body_node = tree.nodeData(node).node;
    if (gz.nosuspend_node.unwrap()) |nosuspend_node| {
        try astgen.appendErrorNodeNotes(node, "redundant nosuspend block", .{}, &[_]u32{
            try astgen.errNoteNode(nosuspend_node, "other nosuspend block here", .{}),
        });
    }
    gz.nosuspend_node = node.toOptional();
    defer gz.nosuspend_node = .none;
    return expr(gz, scope, ri, body_node);
}

fn suspendExpr(
    gz: *GenZir,
    scope: *Scope,
    node: Ast.Node.Index,
) InnerError!Zir.Inst.Ref {
    const astgen = gz.astgen;
    const gpa = astgen.gpa;
    const tree = astgen.tree;
    const body_node = tree.nodeData(node).node;

    if (gz.nosuspend_node.unwrap()) |nosuspend_node| {
        return astgen.failNodeNotes(node, "suspend inside nosuspend block", .{}, &[_]u32{
            try astgen.errNoteNode(nosuspend_node, "nosuspend block here", .{}),
        });
    }
    if (gz.suspend_node.unwrap()) |suspend_node| {
        return astgen.failNodeNotes(node, "cannot suspend inside suspend block", .{}, &[_]u32{
            try astgen.errNoteNode(suspend_node, "other suspend block here", .{}),
        });
    }

    const suspend_inst = try gz.makeBlockInst(.suspend_block, node);
    try gz.instructions.append(gpa, suspend_inst);

    var suspend_scope = gz.makeSubBlock(scope);
    suspend_scope.suspend_node = node.toOptional();
    defer suspend_scope.unstack();

    const body_result = try fullBodyExpr(&suspend_scope, &suspend_scope.base, .{ .rl = .none }, body_node, .normal);
    if (!gz.refIsNoReturn(body_result)) {
        _ = try suspend_scope.addBreak(.break_inline, suspend_inst, .void_value);
    }
    try suspend_scope.setBlockBody(suspend_inst);

    return suspend_inst.toRef();
}

fn resumeExpr(
    gz: *GenZir,
    scope: *Scope,
    ri: ResultInfo,
    node: Ast.Node.Index,
) InnerError!Zir.Inst.Ref {
    const astgen = gz.astgen;
    const tree = astgen.tree;
    const rhs_node = tree.nodeData(node).node;
    const operand = try expr(gz, scope, .{ .rl = .ref }, rhs_node);
    const result = try gz.addUnNode(.@"resume", operand, node);
    return rvalue(gz, ri, result, node);
}

fn fnProtoExpr(
    gz: *GenZir,
    scope: *Scope,
    ri: ResultInfo,
    node: Ast.Node.Index,
    fn_proto: Ast.full.FnProto,
) InnerError!Zir.Inst.Ref {
    const astgen = gz.astgen;
    const tree = astgen.tree;

    if (fn_proto.name_token) |some| {
        return astgen.failTok(some, "function type cannot have a name", .{});
    }

    if (fn_proto.ast.align_expr.unwrap()) |align_expr| {
        return astgen.failNode(align_expr, "function type cannot have an alignment", .{});
    }

    if (fn_proto.ast.addrspace_expr.unwrap()) |addrspace_expr| {
        return astgen.failNode(addrspace_expr, "function type cannot have an addrspace", .{});
    }

    if (fn_proto.ast.section_expr.unwrap()) |section_expr| {
        return astgen.failNode(section_expr, "function type cannot have a linksection", .{});
    }

    const return_type = fn_proto.ast.return_type.unwrap().?;
    const maybe_bang = tree.firstToken(return_type) - 1;
    const is_inferred_error = tree.tokenTag(maybe_bang) == .bang;
    if (is_inferred_error) {
        return astgen.failTok(maybe_bang, "function type cannot have an inferred error set", .{});
    }

    const is_extern = blk: {
        const maybe_extern_token = fn_proto.extern_export_inline_token orelse break :blk false;
        break :blk tree.tokenTag(maybe_extern_token) == .keyword_extern;
    };
    assert(!is_extern);

    return fnProtoExprInner(gz, scope, ri, node, fn_proto, false);
}

fn fnProtoExprInner(
    gz: *GenZir,
    scope: *Scope,
    ri: ResultInfo,
    node: Ast.Node.Index,
    fn_proto: Ast.full.FnProto,
    implicit_ccc: bool,
) InnerError!Zir.Inst.Ref {
    const astgen = gz.astgen;
    const tree = astgen.tree;

    var block_scope = gz.makeSubBlock(scope);
    defer block_scope.unstack();

    const block_inst = try gz.makeBlockInst(.block_inline, node);

    var noalias_bits: u32 = 0;
    const is_var_args = is_var_args: {
        var param_type_i: usize = 0;
        var it = fn_proto.iterate(tree);
        while (it.next()) |param| : (param_type_i += 1) {
            const is_comptime = if (param.comptime_noalias) |token| switch (tree.tokenTag(token)) {
                .keyword_noalias => is_comptime: {
                    noalias_bits |= @as(u32, 1) << (std.math.cast(u5, param_type_i) orelse
                        return astgen.failTok(token, "this compiler implementation only supports 'noalias' on the first 32 parameters", .{}));
                    break :is_comptime false;
                },
                .keyword_comptime => true,
                else => false,
            } else false;

            const is_anytype = if (param.anytype_ellipsis3) |token| blk: {
                switch (tree.tokenTag(token)) {
                    .keyword_anytype => break :blk true,
                    .ellipsis3 => break :is_var_args true,
                    else => unreachable,
                }
            } else false;

            const param_name = if (param.name_token) |name_token| blk: {
                if (mem.eql(u8, "_", tree.tokenSlice(name_token)))
                    break :blk .empty;

                break :blk try astgen.identAsString(name_token);
            } else .empty;

            if (is_anytype) {
                const name_token = param.name_token orelse param.anytype_ellipsis3.?;

                const tag: Zir.Inst.Tag = if (is_comptime)
                    .param_anytype_comptime
                else
                    .param_anytype;
                _ = try block_scope.addStrTok(tag, param_name, name_token);
            } else {
                const param_type_node = param.type_expr.?;
                var param_gz = block_scope.makeSubBlock(scope);
                defer param_gz.unstack();
                param_gz.is_comptime = true;
                const param_type = try fullBodyExpr(&param_gz, scope, coerced_type_ri, param_type_node, .normal);
                const param_inst_expected: Zir.Inst.Index = @fromBackingInt(@intCast(astgen.instructions.len + 1));
                _ = try param_gz.addBreakWithSrcNode(.break_inline, param_inst_expected, param_type, param_type_node);
                const name_token = param.name_token orelse tree.nodeMainToken(param_type_node);
                const tag: Zir.Inst.Tag = if (is_comptime) .param_comptime else .param;
                // 此处将 `prev_param_insts` 传为 `&.{}`,因为函数原型不能引用先前参数(此处尚未设置作用域)。
                //
                const param_inst = try block_scope.addParam(&param_gz, &.{}, false, tag, name_token, param_name);
                assert(param_inst_expected == param_inst);
            }
        }
        break :is_var_args false;
    };

    const cc: Zir.Inst.Ref = if (fn_proto.ast.callconv_expr.unwrap()) |callconv_expr|
        try comptimeExpr(
            &block_scope,
            scope,
            .{ .rl = .{ .coerced_ty = try block_scope.addStdLangValue(callconv_expr, .calling_convention) } },
            callconv_expr,
            .@"callconv",
        )
    else if (implicit_ccc)
        try block_scope.addStdLangValue(node, .calling_convention_c)
    else
        .none;

    const ret_ty_node = fn_proto.ast.return_type.unwrap().?;
    const ret_ty = try comptimeExpr(&block_scope, scope, coerced_type_ri, ret_ty_node, .fn_ret_ty);

    const result = try block_scope.addFunc(.{
        .src_node = fn_proto.ast.proto_node,

        .cc_ref = cc,
        .cc_gz = null,
        .ret_ref = ret_ty,
        .ret_gz = null,

        .ret_param_refs = &.{},
        .param_insts = &.{},
        .ret_ty_is_generic = false,

        .param_block = block_inst,
        .body_gz = null,
        .is_var_args = is_var_args,
        .is_inferred_error = false,
        .is_noinline = false,
        .noalias_bits = noalias_bits,

        .proto_hash = undefined, // 当 `body_gz == null` 时忽略
    });

    _ = try block_scope.addBreak(.break_inline, block_inst, result);
    try block_scope.setBlockBody(block_inst);
    try gz.instructions.append(astgen.gpa, block_inst);

    return rvalue(gz, ri, block_inst.toRef(), fn_proto.ast.proto_node);
}

fn arrayInitExpr(
    gz: *GenZir,
    scope: *Scope,
    ri: ResultInfo,
    node: Ast.Node.Index,
    array_init: Ast.full.ArrayInit,
) InnerError!Zir.Inst.Ref {
    const astgen = gz.astgen;
    const tree = astgen.tree;

    assert(array_init.ast.elements.len != 0); // 否则将是结构体初始化。

    const array_ty: Zir.Inst.Ref, const elem_ty: Zir.Inst.Ref = inst: {
        const type_expr = array_init.ast.type_expr.unwrap() orelse break :inst .{ .none, .none };

        infer: {
            const array_type: Ast.full.ArrayType = tree.fullArrayType(type_expr) orelse break :infer;
            // 此处有意不支持 `@"_"` 语法。
            if (tree.nodeTag(array_type.ast.elem_count) == .identifier and
                mem.eql(u8, tree.tokenSlice(tree.nodeMainToken(array_type.ast.elem_count)), "_"))
            {
                const len_inst = try gz.addInt(array_init.ast.elements.len);
                const saved_cursor = astgen.saveSourceCursor();
                const elem_type = try typeExpr(gz, scope, array_type.ast.elem_type);
                if (array_type.ast.sentinel == .none) {
                    const array_type_inst = try gz.addPlNode(.array_type, type_expr, Zir.Inst.Bin{
                        .lhs = len_inst,
                        .rhs = elem_type,
                    });
                    break :inst .{ array_type_inst, elem_type };
                } else {
                    astgen.restoreSourceCursor(saved_cursor);
                    const sentinel_node = array_type.ast.sentinel.unwrap().?;
                    const sentinel = try comptimeExpr(gz, scope, .{ .rl = .{ .ty = elem_type } }, sentinel_node, .array_sentinel);
                    const array_type_inst = try gz.addPlNode(
                        .array_type_sentinel,
                        type_expr,
                        Zir.Inst.ArrayTypeSentinel{
                            .len = len_inst,
                            .elem_type = elem_type,
                            .sentinel = sentinel,
                        },
                    );
                    break :inst .{ array_type_inst, elem_type };
                }
            }
        }
        const array_type_inst = try typeExpr(gz, scope, type_expr);
        _ = try gz.addPlNode(.validate_array_init_ty, node, Zir.Inst.ArrayInit{
            .ty = array_type_inst,
            .init_count = @intCast(array_init.ast.elements.len),
        });
        break :inst .{ array_type_inst, .none };
    };

    if (array_ty != .none) {
        // 为简化语言,带类型初始化不使用 RLS。
        switch (ri.rl) {
            .discard => {
                if (elem_ty != .none) {
                    const elem_ri: ResultInfo = .{ .rl = .{ .ty = elem_ty } };
                    for (array_init.ast.elements) |elem_init| {
                        _ = try expr(gz, scope, elem_ri, elem_init);
                    }
                } else {
                    for (array_init.ast.elements, 0..) |elem_init, i| {
                        const this_elem_ty = try gz.add(.{
                            .tag = .array_init_elem_type,
                            .data = .{ .bin = .{
                                .lhs = array_ty,
                                .rhs = @fromBackingInt(@intCast(i)),
                            } },
                        });
                        _ = try expr(gz, scope, .{ .rl = .{ .ty = this_elem_ty } }, elem_init);
                    }
                }
                return .void_value;
            },
            .ref, .ref_const => return arrayInitExprTyped(gz, scope, node, array_init.ast.elements, array_ty, elem_ty, true),
            else => {
                const array_inst = try arrayInitExprTyped(gz, scope, node, array_init.ast.elements, array_ty, elem_ty, false);
                return rvalue(gz, ri, array_inst, node);
            },
        }
    }

    switch (ri.rl) {
        .none => return arrayInitExprAnon(gz, scope, node, array_init.ast.elements),
        .discard => {
            for (array_init.ast.elements) |elem_init| {
                _ = try expr(gz, scope, .{ .rl = .discard }, elem_init);
            }
            return Zir.Inst.Ref.void_value;
        },
        .ref, .ref_const => {
            const result = try arrayInitExprAnon(gz, scope, node, array_init.ast.elements);
            return gz.addUnTok(.ref, result, tree.firstToken(node));
        },
        .ref_coerced_ty => |ptr_ty_inst| {
            const dest_arr_ty_inst = try gz.addPlNode(.validate_array_init_ref_ty, node, Zir.Inst.ArrayInitRefTy{
                .ptr_ty = ptr_ty_inst,
                .elem_count = @intCast(array_init.ast.elements.len),
            });
            return arrayInitExprTyped(gz, scope, node, array_init.ast.elements, dest_arr_ty_inst, .none, true);
        },
        .ty, .coerced_ty => |result_ty_inst| {
            _ = try gz.addPlNode(.validate_array_init_result_ty, node, Zir.Inst.ArrayInit{
                .ty = result_ty_inst,
                .init_count = @intCast(array_init.ast.elements.len),
            });
            return arrayInitExprTyped(gz, scope, node, array_init.ast.elements, result_ty_inst, .none, false);
        },
        .ptr => |ptr| {
            try arrayInitExprPtr(gz, scope, node, array_init.ast.elements, ptr.inst);
            return .void_value;
        },
        .inferred_ptr => {
            // 无法获取无类型推导分配块的元素指针,因此必须执行
            // 标准匿名初始化,再存储右值。
            // 参见 structInitExpr 中对应的逻辑。
            const result = try arrayInitExprAnon(gz, scope, node, array_init.ast.elements);
            return rvalue(gz, ri, result, node);
        },
        .destructure => |destructure| {
            // 无类型初始化:直接解构到结果指针
            if (array_init.ast.elements.len != destructure.components.len) {
                return astgen.failNodeNotes(node, "expected {} elements for destructure, found {}", .{
                    destructure.components.len,
                    array_init.ast.elements.len,
                }, &.{
                    try astgen.errNoteNode(destructure.src_node, "result destructured here", .{}),
                });
            }
            for (array_init.ast.elements, destructure.components) |elem_init, ds_comp| {
                const elem_ri: ResultInfo = .{ .rl = switch (ds_comp) {
                    .typed_ptr => |ptr_rl| .{ .ptr = ptr_rl },
                    .inferred_ptr => |ptr_inst| .{ .inferred_ptr = ptr_inst },
                    .discard => .discard,
                } };
                _ = try expr(gz, scope, elem_ri, elem_init);
            }
            return .void_value;
        },
    }
}

/// 使用 `array_init_anon` 指令的数组初始化表达式。
fn arrayInitExprAnon(
    gz: *GenZir,
    scope: *Scope,
    node: Ast.Node.Index,
    elements: []const Ast.Node.Index,
) InnerError!Zir.Inst.Ref {
    const astgen = gz.astgen;

    const payload_index = try addExtra(astgen, Zir.Inst.MultiOp{
        .operands_len = @intCast(elements.len),
    });
    var extra_index = try reserveExtra(astgen, elements.len);

    for (elements) |elem_init| {
        const elem_ref = try expr(gz, scope, .{ .rl = .none }, elem_init);
        astgen.extra.items[extra_index] = @backingInt(elem_ref);
        extra_index += 1;
    }
    return try gz.addPlNodePayloadIndex(.array_init_anon, node, payload_index);
}

/// 使用 `array_init` 或 `array_init_ref` 指令的数组初始化表达式。
fn arrayInitExprTyped(
    gz: *GenZir,
    scope: *Scope,
    node: Ast.Node.Index,
    elements: []const Ast.Node.Index,
    ty_inst: Zir.Inst.Ref,
    maybe_elem_ty_inst: Zir.Inst.Ref,
    is_ref: bool,
) InnerError!Zir.Inst.Ref {
    const astgen = gz.astgen;

    const len = elements.len + 1; // 为类型额外增加 1
    const payload_index = try addExtra(astgen, Zir.Inst.MultiOp{
        .operands_len = @intCast(len),
    });
    var extra_index = try reserveExtra(astgen, len);
    astgen.extra.items[extra_index] = @backingInt(ty_inst);
    extra_index += 1;

    if (maybe_elem_ty_inst != .none) {
        const elem_ri: ResultInfo = .{ .rl = .{ .coerced_ty = maybe_elem_ty_inst } };
        for (elements) |elem_init| {
            const elem_inst = try expr(gz, scope, elem_ri, elem_init);
            astgen.extra.items[extra_index] = @backingInt(elem_inst);
            extra_index += 1;
        }
    } else {
        for (elements, 0..) |elem_init, i| {
            const ri: ResultInfo = .{ .rl = .{ .coerced_ty = try gz.add(.{
                .tag = .array_init_elem_type,
                .data = .{ .bin = .{
                    .lhs = ty_inst,
                    .rhs = @fromBackingInt(@intCast(i)),
                } },
            }) } };

            const elem_inst = try expr(gz, scope, ri, elem_init);
            astgen.extra.items[extra_index] = @backingInt(elem_inst);
            extra_index += 1;
        }
    }

    const tag: Zir.Inst.Tag = if (is_ref) .array_init_ref else .array_init;
    return try gz.addPlNodePayloadIndex(tag, node, payload_index);
}

/// 使用元素指针的数组初始化表达式。
fn arrayInitExprPtr(
    gz: *GenZir,
    scope: *Scope,
    node: Ast.Node.Index,
    elements: []const Ast.Node.Index,
    ptr_inst: Zir.Inst.Ref,
) InnerError!void {
    const astgen = gz.astgen;

    const array_ptr_inst = try gz.addUnNode(.opt_eu_base_ptr_init, ptr_inst, node);

    const payload_index = try addExtra(astgen, Zir.Inst.Block{
        .body_len = @intCast(elements.len),
    });
    var extra_index = try reserveExtra(astgen, elements.len);

    for (elements, 0..) |elem_init, i| {
        const elem_ptr_inst = try gz.addPlNode(.array_init_elem_ptr, elem_init, Zir.Inst.ElemPtrImm{
            .ptr = array_ptr_inst,
            .index = @intCast(i),
        });
        astgen.extra.items[extra_index] = @backingInt(elem_ptr_inst.toIndex().?);
        extra_index += 1;
        _ = try expr(gz, scope, .{ .rl = .{ .ptr = .{ .inst = elem_ptr_inst } } }, elem_init);
    }

    _ = try gz.addPlNodePayloadIndex(.validate_ptr_array_init, node, payload_index);
}

fn structInitExpr(
    gz: *GenZir,
    scope: *Scope,
    ri: ResultInfo,
    node: Ast.Node.Index,
    struct_init: Ast.full.StructInit,
) InnerError!Zir.Inst.Ref {
    const astgen = gz.astgen;
    const tree = astgen.tree;

    if (struct_init.ast.type_expr == .none) {
        if (struct_init.ast.fields.len == 0) {
            // 不含字段的匿名初始化。
            switch (ri.rl) {
                .discard => return .void_value,
                .ref_coerced_ty => |ptr_ty_inst| return gz.addUnNode(.struct_init_empty_ref_result, ptr_ty_inst, node),
                .ty, .coerced_ty => |ty_inst| return gz.addUnNode(.struct_init_empty_result, ty_inst, node),
                .ptr => {
                    // TODO: 是否应改为使用 RLS 完成这里的字段存储?
                    const ty_inst = (try ri.rl.resultType(gz, node)).?;
                    const val = try gz.addUnNode(.struct_init_empty_result, ty_inst, node);
                    return rvalue(gz, ri, val, node);
                },
                .none, .ref, .ref_const, .inferred_ptr => {
                    return rvalue(gz, ri, .empty_tuple, node);
                },
                .destructure => |destructure| {
                    return astgen.failNodeNotes(node, "empty initializer cannot be destructured", .{}, &.{
                        try astgen.errNoteNode(destructure.src_node, "result destructured here", .{}),
                    });
                },
            }
        }
    } else array: {
        const type_expr = struct_init.ast.type_expr.unwrap().?;
        const array_type: Ast.full.ArrayType = tree.fullArrayType(type_expr) orelse {
            if (struct_init.ast.fields.len == 0) {
                const ty_inst = try typeExpr(gz, scope, type_expr);
                const result = try gz.addUnNode(.struct_init_empty, ty_inst, node);
                return rvalue(gz, ri, result, node);
            }
            break :array;
        };
        const is_inferred_array_len = tree.nodeTag(array_type.ast.elem_count) == .identifier and
            // 此处有意不支持 `@"_"` 语法。
            mem.eql(u8, tree.tokenSlice(tree.nodeMainToken(array_type.ast.elem_count)), "_");
        if (struct_init.ast.fields.len == 0) {
            if (is_inferred_array_len) {
                const saved_cursor = astgen.saveSourceCursor();
                const elem_type = try typeExpr(gz, scope, array_type.ast.elem_type);
                const array_type_inst = if (array_type.ast.sentinel == .none) blk: {
                    break :blk try gz.addPlNode(.array_type, type_expr, Zir.Inst.Bin{
                        .lhs = .zero_usize,
                        .rhs = elem_type,
                    });
                } else blk: {
                    astgen.restoreSourceCursor(saved_cursor);
                    const sentinel_node = array_type.ast.sentinel.unwrap().?;
                    const sentinel = try comptimeExpr(gz, scope, .{ .rl = .{ .ty = elem_type } }, sentinel_node, .array_sentinel);
                    break :blk try gz.addPlNode(
                        .array_type_sentinel,
                        type_expr,
                        Zir.Inst.ArrayTypeSentinel{
                            .len = .zero_usize,
                            .elem_type = elem_type,
                            .sentinel = sentinel,
                        },
                    );
                };
                const result = try gz.addUnNode(.struct_init_empty, array_type_inst, node);
                return rvalue(gz, ri, result, node);
            }
            const ty_inst = try typeExpr(gz, scope, type_expr);
            const result = try gz.addUnNode(.struct_init_empty, ty_inst, node);
            return rvalue(gz, ri, result, node);
        } else {
            return astgen.failNode(
                type_expr,
                "initializing array with struct syntax",
                .{},
            );
        }
    }

    {
        var bfa_buf: [256]u8 = undefined;
        var bfa_state: std.heap.BufferFirstAllocator = .init(&bfa_buf, astgen.arena);
        const bfa = bfa_state.allocator();

        var duplicate_names: std.array_hash_map.Auto(Zir.NullTerminatedString, ArrayList(Ast.TokenIndex)) = .empty;
        try duplicate_names.ensureTotalCapacity(bfa, @intCast(struct_init.ast.fields.len));

        // 没有错误时,使用此项以避免第二次迭代。
        var any_duplicate = false;

        for (struct_init.ast.fields) |field| {
            const name_token = tree.firstToken(field) - 2;
            const name_index = try astgen.identAsString(name_token);

            const gop = try duplicate_names.getOrPut(bfa, name_index);

            if (gop.found_existing) {
                try gop.value_ptr.append(bfa, name_token);
                any_duplicate = true;
            } else {
                gop.value_ptr.* = .empty;
                try gop.value_ptr.append(bfa, name_token);
            }
        }

        if (any_duplicate) {
            var it = duplicate_names.iterator();

            while (it.next()) |entry| {
                const record = entry.value_ptr.*;
                if (record.items.len > 1) {
                    var error_notes = std.array_list.Managed(u32).init(astgen.arena);

                    for (record.items[1..]) |duplicate| {
                        try error_notes.append(try astgen.errNoteTok(duplicate, "duplicate name here", .{}));
                    }

                    try error_notes.append(try astgen.errNoteNode(node, "struct declared here", .{}));

                    try astgen.appendErrorTokNotes(
                        record.items[0],
                        "duplicate struct field name",
                        .{},
                        error_notes.items,
                    );
                }
            }

            return error.AnalysisFail;
        }
    }

    if (struct_init.ast.type_expr.unwrap()) |type_expr| {
        // 为简化语言,带类型初始化不使用 RLS。
        const ty_inst = try typeExpr(gz, scope, type_expr);
        _ = try gz.addUnNode(.validate_struct_init_ty, ty_inst, node);
        switch (ri.rl) {
            .ref, .ref_const => return structInitExprTyped(gz, scope, node, struct_init, ty_inst, true),
            else => {
                const struct_inst = try structInitExprTyped(gz, scope, node, struct_init, ty_inst, false);
                return rvalue(gz, ri, struct_inst, node);
            },
        }
    }

    switch (ri.rl) {
        .none => return structInitExprAnon(gz, scope, node, struct_init),
        .discard => {
            // 即使丢弃结果,也必须执行副作用。
            for (struct_init.ast.fields) |field_init| {
                _ = try expr(gz, scope, .{ .rl = .discard }, field_init);
            }
            return .void_value;
        },
        .ref, .ref_const => {
            const result = try structInitExprAnon(gz, scope, node, struct_init);
            return gz.addUnTok(.ref, result, tree.firstToken(node));
        },
        .ref_coerced_ty => |ptr_ty_inst| {
            const result_ty_inst = try gz.addUnNode(.elem_type, ptr_ty_inst, node);
            _ = try gz.addUnNode(.validate_struct_init_result_ty, result_ty_inst, node);
            return structInitExprTyped(gz, scope, node, struct_init, result_ty_inst, true);
        },
        .ty, .coerced_ty => |result_ty_inst| {
            _ = try gz.addUnNode(.validate_struct_init_result_ty, result_ty_inst, node);
            return structInitExprTyped(gz, scope, node, struct_init, result_ty_inst, false);
        },
        .ptr => |ptr| {
            try structInitExprPtr(gz, scope, node, struct_init, ptr.inst);
            return .void_value;
        },
        .inferred_ptr => {
            // 无法取得无类型推断分配的字段指针,因此必须先执行
            // 标准匿名初始化,再执行右值存储。
            // 参见 arrayInitExpr 中的对应逻辑。
            const struct_inst = try structInitExprAnon(gz, scope, node, struct_init);
            return rvalue(gz, ri, struct_inst, node);
        },
        .destructure => |destructure| {
            // 这是无类型初始化,因此是实际的结构体,
            // 不支持解构。
            return astgen.failNodeNotes(node, "struct value cannot be destructured", .{}, &.{
                try astgen.errNoteNode(destructure.src_node, "result destructured here", .{}),
            });
        },
    }
}

/// 使用 `struct_init_anon` 指令的结构体初始化表达式。
fn structInitExprAnon(
    gz: *GenZir,
    scope: *Scope,
    node: Ast.Node.Index,
    struct_init: Ast.full.StructInit,
) InnerError!Zir.Inst.Ref {
    const astgen = gz.astgen;
    const tree = astgen.tree;

    const payload_index = try addExtra(astgen, Zir.Inst.StructInitAnon{
        .abs_node = node,
        .src_line = astgen.source_line,
        .src_column = astgen.source_column,
        .fields_len = @intCast(struct_init.ast.fields.len),
    });
    const field_size = @typeInfo(Zir.Inst.StructInitAnon.Item).@"struct".field_names.len;
    var extra_index: usize = try reserveExtra(astgen, struct_init.ast.fields.len * field_size);

    for (struct_init.ast.fields) |field_init| {
        const name_token = tree.firstToken(field_init) - 2;
        const str_index = try astgen.identAsString(name_token);
        setExtra(astgen, extra_index, Zir.Inst.StructInitAnon.Item{
            .field_name = str_index,
            .init = try expr(gz, scope, .{ .rl = .none }, field_init),
        });
        extra_index += field_size;
    }

    return gz.addPlNodePayloadIndex(.struct_init_anon, node, payload_index);
}

/// 使用 `struct_init` 或 `struct_init_ref` 指令的结构体初始化表达式。
fn structInitExprTyped(
    gz: *GenZir,
    scope: *Scope,
    node: Ast.Node.Index,
    struct_init: Ast.full.StructInit,
    ty_inst: Zir.Inst.Ref,
    is_ref: bool,
) InnerError!Zir.Inst.Ref {
    const astgen = gz.astgen;
    const tree = astgen.tree;

    const payload_index = try addExtra(astgen, Zir.Inst.StructInit{
        .abs_node = node,
        .src_line = astgen.source_line,
        .src_column = astgen.source_column,
        .fields_len = @intCast(struct_init.ast.fields.len),
    });
    const field_size = @typeInfo(Zir.Inst.StructInit.Item).@"struct".field_names.len;
    var extra_index: usize = try reserveExtra(astgen, struct_init.ast.fields.len * field_size);

    for (struct_init.ast.fields) |field_init| {
        const name_token = tree.firstToken(field_init) - 2;
        const str_index = try astgen.identAsString(name_token);
        const field_ty_inst = try gz.addPlNode(.struct_init_field_type, field_init, Zir.Inst.FieldType{
            .container_type = ty_inst,
            .name_start = str_index,
        });
        setExtra(astgen, extra_index, Zir.Inst.StructInit.Item{
            .field_type = field_ty_inst.toIndex().?,
            .init = try expr(gz, scope, .{ .rl = .{ .coerced_ty = field_ty_inst } }, field_init),
        });
        extra_index += field_size;
    }

    const tag: Zir.Inst.Tag = if (is_ref) .struct_init_ref else .struct_init;
    return gz.addPlNodePayloadIndex(tag, node, payload_index);
}

/// 使用字段指针的结构体初始化表达式。
fn structInitExprPtr(
    gz: *GenZir,
    scope: *Scope,
    node: Ast.Node.Index,
    struct_init: Ast.full.StructInit,
    ptr_inst: Zir.Inst.Ref,
) InnerError!void {
    const astgen = gz.astgen;
    const tree = astgen.tree;

    const struct_ptr_inst = try gz.addUnNode(.opt_eu_base_ptr_init, ptr_inst, node);

    const payload_index = try addExtra(astgen, Zir.Inst.Block{
        .body_len = @intCast(struct_init.ast.fields.len),
    });
    var extra_index = try reserveExtra(astgen, struct_init.ast.fields.len);

    for (struct_init.ast.fields) |field_init| {
        const name_token = tree.firstToken(field_init) - 2;
        const str_index = try astgen.identAsString(name_token);
        const field_ptr = try gz.addPlNode(.struct_init_field_ptr, field_init, Zir.Inst.Field{
            .lhs = struct_ptr_inst,
            .field_name_start = str_index,
        });
        astgen.extra.items[extra_index] = @backingInt(field_ptr.toIndex().?);
        extra_index += 1;
        _ = try expr(gz, scope, .{ .rl = .{ .ptr = .{ .inst = field_ptr } } }, field_init);
    }

    _ = try gz.addPlNodePayloadIndex(.validate_ptr_struct_init, node, payload_index);
}

/// 必要时通过包装 `block_comptime`,在编译期作用域中显式求值 expr。
/// 需要强制在编译期求值某个内容,例如类型时,
/// 都应使用此函数。
/// 与 `comptime` 表达式语法对应的函数是 `comptimeExprAst`。
fn comptimeExpr(
    gz: *GenZir,
    scope: *Scope,
    ri: ResultInfo,
    node: Ast.Node.Index,
    reason: std.zig.SimpleComptimeReason,
) InnerError!Zir.Inst.Ref {
    return comptimeExpr2(gz, scope, ri, node, node, reason);
}

/// 类似 `comptimeExpr`,但区分要在编译期求值的 `node` 表达式,
/// 以及要附加到 `block_comptime` 的 `src_node` 节点。
fn comptimeExpr2(
    gz: *GenZir,
    scope: *Scope,
    ri: ResultInfo,
    node: Ast.Node.Index,
    src_node: Ast.Node.Index,
    reason: std.zig.SimpleComptimeReason,
) InnerError!Zir.Inst.Ref {
    if (gz.is_comptime) {
        // 无需修改任何内容!
        return expr(gz, scope, ri, node);
    }

    // 此处有一项优化:若主体无论如何都会在编译期求值,就无需将其包裹在块中。
    // 通常难以判定这一点,但可以识别常见、显然在编译期求值的表达式子集,从而略微减小 ZIR。
    //
    const tree = gz.astgen.tree;
    switch (tree.nodeTag(node)) {
        .identifier => {
            // 许多标识符无需 `block_comptime` 即可处理,因此 `AstGen.identifier` 对此情况进行特殊处理。
            //
            return identifier(gz, scope, ri, node, .{ .src_node = src_node, .reason = reason });
        },

        // 这些是始终在编译期已知的叶节点。
        .number_literal,
        .char_literal,
        .string_literal,
        .multiline_string_literal,
        .enum_literal,
        .error_value,
        .anyframe_literal,
        .error_set_decl,
        // 这些节点不是叶节点,但会强制对所有子表达式进行编译期求值,
        // 因此无论其是否位于编译期作用域,行为均相同。
        .error_union,
        .merge_error_sets,
        .optional_type,
        .anyframe_type,
        .ptr_type_aligned,
        .ptr_type_sentinel,
        .ptr_type,
        .ptr_type_bit_range,
        .array_type,
        .array_type_sentinel,
        .fn_proto_simple,
        .fn_proto_multi,
        .fn_proto_one,
        .fn_proto,
        .container_decl,
        .container_decl_trailing,
        .container_decl_arg,
        .container_decl_arg_trailing,
        .container_decl_two,
        .container_decl_two_trailing,
        .tagged_union,
        .tagged_union_trailing,
        .tagged_union_enum_tag,
        .tagged_union_enum_tag_trailing,
        .tagged_union_two,
        .tagged_union_two_trailing,
        => {
            // 此处无需考虑结果位置,因为我们没有创建 comptime 块!
            return expr(gz, scope, ri, node);
        },

        // 最后,对于带标签的块,避免在此编译时块内直接生成带标签的块,
        // 否则就太荒谬了!注意,无标签块不需要处理,
        // 因为它们在编译时本来就不会生成块(见 `blockExpr`)。
        .block_two, .block_two_semicolon, .block, .block_semicolon => {
            const lbrace = tree.nodeMainToken(node);
            // 注意!此处不能传入真实结果位置,因为它可能
            // 引用运行时内存。跨越运行时到编译时的边界时,必须移除
            // 结果位置信息,计算结果,再在运行时将其复制到真实
            // 结果位置。下方也采用相同处理。
            const ty_only_ri: ResultInfo = .{
                .ctx = ri.ctx,
                .rl = if (try ri.rl.resultType(gz, node)) |res_ty|
                    .{ .coerced_ty = res_ty }
                else
                    .none,
            };
            if (tree.isTokenPrecededByTags(lbrace, &.{ .identifier, .colon })) {
                var buf: [2]Ast.Node.Index = undefined;
                const stmts = tree.blockStatements(&buf, node).?;

                // 替换结果位置,稍后再复制回来——参见上文。
                const block_ref = try labeledBlockExpr(gz, scope, ty_only_ri, node, stmts, true, .normal);
                return rvalue(gz, ri, block_ref, node);
            }
        },

        // 其他情况下不做任何优化,需要一个外层编译期块。
        else => {},
    }

    var block_scope = gz.makeSubBlock(scope);
    block_scope.is_comptime = true;
    defer block_scope.unstack();

    const block_inst = try gz.makeBlockInst(.block_comptime, src_node);
    // 替换结果位置,稍后再复制回来——参见上文。
    const ty_only_ri: ResultInfo = .{
        .ctx = ri.ctx,
        .rl = if (try ri.rl.resultType(gz, src_node)) |res_ty|
            .{ .coerced_ty = res_ty }
        else
            .none,
    };
    const block_result = try fullBodyExpr(&block_scope, scope, ty_only_ri, node, .normal);
    if (!gz.refIsNoReturn(block_result)) {
        _ = try block_scope.addBreak(.break_inline, block_inst, block_result);
    }
    try block_scope.setBlockComptimeBody(block_inst, reason);
    try gz.instructions.append(gz.astgen.gpa, block_inst);

    return rvalue(gz, ri, block_inst.toRef(), src_node);
}

/// 此项用于实际的 `comptime` 语法;若已知作用域在编译时求值,
/// 则生成编译错误。
/// 用于在编译时作用域中调用 expr 的辅助函数见 `comptimeExpr`。
fn comptimeExprAst(
    gz: *GenZir,
    scope: *Scope,
    ri: ResultInfo,
    node: Ast.Node.Index,
) InnerError!Zir.Inst.Ref {
    const astgen = gz.astgen;
    const tree = astgen.tree;
    if (gz.is_comptime) {
        try astgen.appendErrorTok(tree.nodeMainToken(node), "redundant comptime keyword in already comptime scope", .{});
    }
    const body_node = tree.nodeData(node).node;
    return comptimeExpr2(gz, scope, ri, body_node, node, .comptime_keyword);
}

/// 恢复错误返回追踪索引。仅当结果不是错误,或结果位置不是错误处理表达式时执行恢复。
///
fn restoreErrRetIndex(
    gz: *GenZir,
    bt: GenZir.BranchTarget,
    ri: ResultInfo,
    node: Ast.Node.Index,
    result: Zir.Inst.Ref,
) !void {
    const op = switch (nodeMayEvalToError(gz.astgen.tree, node)) {
        .always => return, // 从不恢复/弹出
        .never => .none, // 始终恢复/弹出
        .maybe => switch (ri.ctx) {
            .error_handling_expr, .@"return", .fn_arg, .const_init => switch (ri.rl) {
                .ptr => |ptr_res| try gz.addUnNode(.load, ptr_res.inst, node),
                .inferred_ptr => blk: {
                    // 这是对 Sema 限制的糟糕变通:在类型解析完成前,无法从 .alloc_inferred 指针
                    // 加载。此处没有有效操作数可用,因此错误
                    // 跟踪会被过早弹出。
                    // TODO: 当 Sema 支持后,更新为从 rl_ptr 正确加载。
                    break :blk .none;
                },
                .destructure => return, // 值必须为元组或数组,因此绝不恢复/弹出
                else => result,
            },
            else => .none, // 始终恢复/弹出
        },
    };
    _ = try gz.addRestoreErrRetIndex(bt, .{ .if_non_error = op }, node);
}

fn breakExpr(parent_gz: *GenZir, parent_scope: *Scope, node: Ast.Node.Index) InnerError!Zir.Inst.Ref {
    const astgen = parent_gz.astgen;
    const tree = astgen.tree;
    const opt_break_label, const opt_rhs = tree.nodeData(node).opt_token_and_opt_node;

    // 在作用域中查找标签。
    find_scope: switch (parent_scope.unwrap()) {
        .gen_zir => |gen_zir| {
            const scope = &gen_zir.base;

            if (gen_zir.cur_defer_node.unwrap()) |cur_defer_node| {
                // 我们正在跳出 `defer` 块。
                return astgen.failNodeNotes(node, "cannot break out of defer expression", .{}, &.{
                    try astgen.errNoteNode(
                        cur_defer_node,
                        "defer expression here",
                        .{},
                    ),
                });
            }

            if (opt_break_label.unwrap()) |break_label| labeled: {
                if (gen_zir.label) |*label| {
                    if (try astgen.tokenIdentEql(label.token, break_label)) {
                        label.used = true;
                        break :labeled;
                    }
                }
                // gz 不带标签或标签不同,继续查找父作用域。
                continue :find_scope gen_zir.parent.unwrap();
            } else if (!gen_zir.allow_unlabeled_control_flow) {
                // 此 `break` 无标签,且找到的 gz 不允许
                // 无标签控制流。继续查找父作用域。
                continue :find_scope gen_zir.parent.unwrap();
            }

            const break_tag: Zir.Inst.Tag = if (gen_zir.is_inline)
                .break_inline
            else
                .@"break";

            if (opt_rhs.unwrap()) |rhs| {
                // 存在一个 `break` 操作数。
                const operand = try reachableExpr(parent_gz, parent_scope, gen_zir.break_result_info, rhs, node);

                try genDefers(parent_gz, scope, parent_scope, .normal_only);

                // 作为 break 前最后一个操作,必要时“弹出”错误跟踪
                if (!gen_zir.is_comptime) {
                    try restoreErrRetIndex(parent_gz, .{ .block = gen_zir.break_target }, gen_zir.break_result_info, rhs, operand);
                }
                switch (gen_zir.break_result_info.rl) {
                    .ptr => {
                        // 此时没有任何拦截机制;
                        // 假定结果位置已写入,并以 void 退出。
                        _ = try parent_gz.addBreak(break_tag, gen_zir.break_target, .void_value);
                    },
                    .discard => {
                        _ = try parent_gz.addBreak(break_tag, gen_zir.break_target, .void_value);
                    },
                    else => {
                        _ = try parent_gz.addBreakWithSrcNode(break_tag, gen_zir.break_target, operand, rhs);
                    },
                }
                return .unreachable_value;
            } else {
                _ = try rvalue(parent_gz, gen_zir.break_result_info, .void_value, node);

                try genDefers(parent_gz, scope, parent_scope, .normal_only);

                // 作为 break 前最后一个操作,必要时“弹出”错误跟踪
                if (!gen_zir.is_comptime)
                    _ = try parent_gz.addRestoreErrRetIndex(.{ .block = gen_zir.break_target }, .always, node);

                _ = try parent_gz.addBreak(break_tag, gen_zir.break_target, .void_value);
                return .unreachable_value;
            }
        },
        .local_val => |local_val| continue :find_scope local_val.parent.unwrap(),
        .local_ptr => |local_ptr| continue :find_scope local_ptr.parent.unwrap(),
        .defer_normal, .defer_error => |defer_scope| continue :find_scope defer_scope.parent.unwrap(),
        .namespace => {
            if (opt_break_label.unwrap()) |break_label| {
                const label_name = try astgen.identifierTokenString(break_label);
                return astgen.failTok(break_label, "label not found: '{s}'", .{label_name});
            } else {
                return astgen.failNode(node, "break expression outside loop", .{});
            }
        },
        .top => unreachable,
    }
}

fn continueExpr(parent_gz: *GenZir, parent_scope: *Scope, node: Ast.Node.Index) InnerError!Zir.Inst.Ref {
    const astgen = parent_gz.astgen;
    const tree = astgen.tree;
    const opt_break_label, const opt_rhs = tree.nodeData(node).opt_token_and_opt_node;

    if (opt_break_label == .none and opt_rhs != .none) {
        return astgen.failNode(node, "cannot continue with operand without label", .{});
    }

    // 在作用域中查找标签。
    find_scope: switch (parent_scope.unwrap()) {
        .gen_zir => |gen_zir| {
            const scope = &gen_zir.base;

            if (gen_zir.cur_defer_node.unwrap()) |cur_defer_node| {
                return astgen.failNodeNotes(node, "cannot continue out of defer expression", .{}, &.{
                    try astgen.errNoteNode(
                        cur_defer_node,
                        "defer expression here",
                        .{},
                    ),
                });
            }

            if (opt_break_label.unwrap()) |break_label| labeled: {
                if (gen_zir.label) |*label| {
                    if (try astgen.tokenIdentEql(label.token, break_label)) {
                        switch (gen_zir.continue_target) {
                            .none => {
                                return astgen.failNode(node, "continue outside of loop or labeled switch expression", .{});
                            },
                            .@"break" => if (opt_rhs != .none) {
                                return astgen.failNode(node, "cannot continue loop with operand", .{});
                            },
                            .switch_continue => if (opt_rhs == .none) {
                                return astgen.failNode(node, "cannot continue switch without operand", .{});
                            },
                        }
                        label.used = true;
                        label.used_for_continue = true;
                        break :labeled;
                    }
                }
                // gz 不带标签或标签不同,继续查找父作用域。
                continue :find_scope gen_zir.parent.unwrap();
            } else if (gen_zir.allow_unlabeled_control_flow) {
                // 此 `continue` 不带标签。若找到的 gz 没有
                // 提供 `continue` 目标,或对应带标签的
                // `switch`,则忽略它,继续查找父作用域。
                switch (gen_zir.continue_target) {
                    .none, .switch_continue => {
                        continue :find_scope gen_zir.parent.unwrap();
                    },
                    .@"break" => {},
                }
            } else {
                // 没有 break 标签,且找到的 gz 不允许
                // 无标签控制流,因此继续查找其父作用域。
                continue :find_scope gen_zir.parent.unwrap();
            }

            switch (gen_zir.continue_target) {
                .none => unreachable, // 到此应已失败,或继续查找父作用域。
                .@"break" => |block| {
                    try genDefers(parent_gz, scope, parent_scope, .normal_only);

                    const break_tag: Zir.Inst.Tag = if (gen_zir.is_inline)
                        .break_inline
                    else
                        .@"break";
                    if (break_tag == .break_inline) {
                        _ = try parent_gz.addUnNode(.check_comptime_control_flow, block.toRef(), node);
                    }

                    // 在 continue 之前的最后一步,按需“弹出”错误回溯。
                    if (!gen_zir.is_comptime) {
                        _ = try parent_gz.addRestoreErrRetIndex(.{ .block = block }, .always, node);
                    }
                    _ = try parent_gz.addBreak(break_tag, block, .void_value);
                    return .unreachable_value;
                },
                .switch_continue => |switch_block| {
                    const rhs = opt_rhs.unwrap().?; // 已在上方检查
                    const operand = try reachableExpr(parent_gz, parent_scope, gen_zir.continue_result_info, rhs, node);

                    try genDefers(parent_gz, scope, parent_scope, .normal_only);

                    // 在 continue 之前的最后一步,按需“弹出”错误回溯。
                    if (!gen_zir.is_comptime) {
                        _ = try parent_gz.addRestoreErrRetIndex(.{ .block = switch_block }, .always, node);
                    }
                    _ = try parent_gz.addBreakWithSrcNode(.switch_continue, switch_block, operand, rhs);
                    return .unreachable_value;
                },
            }
        },
        .local_val => |local_val| continue :find_scope local_val.parent.unwrap(),
        .local_ptr => |local_ptr| continue :find_scope local_ptr.parent.unwrap(),
        .defer_normal, .defer_error => |defer_scope| continue :find_scope defer_scope.parent.unwrap(),
        .namespace => {
            if (opt_break_label.unwrap()) |break_label| {
                const label_name = try astgen.identifierTokenString(break_label);
                return astgen.failTok(break_label, "label not found: '{s}'", .{label_name});
            } else {
                return astgen.failNode(node, "continue expression outside loop", .{});
            }
        },
        .top => unreachable,
    }
}

/// 类似 `expr`,但用于 `gz` 对应的指令体
/// 仅包含此节点代码的情况。与 `expr` 不同,如果
/// 根表达式是无标签块,则不生成实际的块。
/// 而是将块内容直接生成到 `gz`。
fn fullBodyExpr(
    gz: *GenZir,
    scope: *Scope,
    ri: ResultInfo,
    node: Ast.Node.Index,
    block_kind: BlockKind,
) InnerError!Zir.Inst.Ref {
    const tree = gz.astgen.tree;

    var stmt_buf: [2]Ast.Node.Index = undefined;
    const statements = tree.blockStatements(&stmt_buf, node) orelse
        return expr(gz, scope, ri, node);

    const lbrace = tree.nodeMainToken(node);

    if (tree.isTokenPrecededByTags(lbrace, &.{ .identifier, .colon })) {
        // 带标签块较复杂:正确转发结果位置信息并不简单,
        // 而且如果用 `break_inline` 退出此块,则不允许多个 break。
        // 此情况少见,因此直接将其当作普通表达式,并创建嵌套块。
        return blockExpr(gz, scope, ri, node, statements, block_kind);
    }

    var sub_gz = gz.makeSubBlock(scope);
    try blockExprStmts(&sub_gz, &sub_gz.base, statements, block_kind);

    return rvalue(gz, ri, .void_value, node);
}

const BlockKind = enum { normal, allow_branch_hint };

fn blockExpr(
    gz: *GenZir,
    scope: *Scope,
    ri: ResultInfo,
    block_node: Ast.Node.Index,
    statements: []const Ast.Node.Index,
    kind: BlockKind,
) InnerError!Zir.Inst.Ref {
    const astgen = gz.astgen;
    const tree = astgen.tree;

    const lbrace = tree.nodeMainToken(block_node);
    if (tree.isTokenPrecededByTags(lbrace, &.{ .identifier, .colon })) {
        return labeledBlockExpr(gz, scope, ri, block_node, statements, false, kind);
    }

    if (!gz.is_comptime) {
        // 由于此块没有标签,控制流实际上是线性的,
        // 几乎可以在此处将块内联。不过,实际仍需
        // 为 Sema 保留 .block,以正确弹出错误返回跟踪。

        const block_tag: Zir.Inst.Tag = .block;
        const block_inst = try gz.makeBlockInst(block_tag, block_node);
        try gz.instructions.append(astgen.gpa, block_inst);

        var block_scope = gz.makeSubBlock(scope);
        defer block_scope.unstack();

        try blockExprStmts(&block_scope, &block_scope.base, statements, kind);

        if (!block_scope.endsWithNoReturn()) {
            // 作为 break 前最后一个操作,必要时“弹出”错误跟踪
            _ = try gz.addRestoreErrRetIndex(.{ .block = block_inst }, .always, block_node);
            // 此处不调用 `rvalue`,因为块结果始终为 `void`,故在下方执行。
            _ = try block_scope.addBreak(.@"break", block_inst, .void_value);
        }

        try block_scope.setBlockBody(block_inst);
    } else {
        var sub_gz = gz.makeSubBlock(scope);
        try blockExprStmts(&sub_gz, &sub_gz.base, statements, kind);
    }

    return rvalue(gz, ri, .void_value, block_node);
}

fn checkLabelRedefinition(astgen: *AstGen, parent_scope: *Scope, label: Ast.TokenIndex) !void {
    // 在作用域中查找标签。
    find_scope: switch (parent_scope.unwrap()) {
        .gen_zir => |gen_zir| {
            if (gen_zir.label) |prev_label| {
                if (try astgen.tokenIdentEql(label, prev_label.token)) {
                    const label_name = try astgen.identifierTokenString(label);
                    return astgen.failTokNotes(label, "redefinition of label '{s}'", .{
                        label_name,
                    }, &[_]u32{
                        try astgen.errNoteTok(
                            prev_label.token,
                            "previous definition here",
                            .{},
                        ),
                    });
                }
            }
            continue :find_scope gen_zir.parent.unwrap();
        },
        .local_val => |local_val| continue :find_scope local_val.parent.unwrap(),
        .local_ptr => |local_ptr| continue :find_scope local_ptr.parent.unwrap(),
        .defer_normal, .defer_error => |defer_scope| continue :find_scope defer_scope.parent.unwrap(),
        .namespace => break :find_scope,
        .top => unreachable,
    }
}

fn labeledBlockExpr(
    gz: *GenZir,
    parent_scope: *Scope,
    ri: ResultInfo,
    block_node: Ast.Node.Index,
    statements: []const Ast.Node.Index,
    force_comptime: bool,
    block_kind: BlockKind,
) InnerError!Zir.Inst.Ref {
    const astgen = gz.astgen;
    const tree = astgen.tree;

    const lbrace = tree.nodeMainToken(block_node);
    const label_token = lbrace - 2;
    assert(tree.tokenTag(label_token) == .identifier);

    try astgen.checkLabelRedefinition(parent_scope, label_token);

    const need_rl = astgen.nodes_need_rl.contains(block_node);
    const block_ri: ResultInfo = if (need_rl) ri else .{
        .rl = switch (ri.rl) {
            .ptr => .{ .ty = (try ri.rl.resultType(gz, block_node)).? },
            .inferred_ptr => .none,
            else => ri.rl,
        },
        .ctx = ri.ctx,
    };
    // 仅当已有结果指针且未转发该指针时,才需调用 `rvalue` 通过指针写入。
    //
    const LocTag = @typeInfo(ResultInfo.Loc).@"union".tag_type.?;
    const need_result_rvalue = @as(LocTag, block_ri.rl) != @as(LocTag, ri.rl);

    // 预留 Block ZIR 指令索引,以便将其放入 GenZir 结构体,
    // 使 break 语句能够引用它。
    const block_inst = try gz.makeBlockInst(if (force_comptime) .block_comptime else .block, block_node);
    try gz.instructions.append(astgen.gpa, block_inst);
    var block_scope = gz.makeSubBlock(parent_scope);
    block_scope.is_inline = force_comptime;
    block_scope.label = .{ .token = label_token };
    block_scope.break_target = block_inst;
    block_scope.continue_target = .none;
    block_scope.setBreakResultInfo(block_ri);
    if (force_comptime) block_scope.is_comptime = true;
    defer block_scope.unstack();

    try blockExprStmts(&block_scope, &block_scope.base, statements, block_kind);
    if (!block_scope.endsWithNoReturn()) {
        // 作为返回前最后一个操作,必要时“弹出”错误跟踪
        _ = try gz.addRestoreErrRetIndex(.{ .block = block_inst }, .always, block_node);
        const result = try rvalue(gz, block_scope.break_result_info, .void_value, block_node);
        const break_tag: Zir.Inst.Tag = if (force_comptime) .break_inline else .@"break";
        _ = try block_scope.addBreak(break_tag, block_inst, result);
    }

    if (!block_scope.label.?.used) {
        try astgen.appendErrorTok(label_token, "unused block label", .{});
    }

    if (force_comptime) {
        try block_scope.setBlockComptimeBody(block_inst, .comptime_keyword);
    } else {
        try block_scope.setBlockBody(block_inst);
    }

    if (need_result_rvalue) {
        return rvalue(gz, ri, block_inst.toRef(), block_node);
    } else {
        return block_inst.toRef();
    }
}

fn blockExprStmts(gz: *GenZir, parent_scope: *Scope, statements: []const Ast.Node.Index, block_kind: BlockKind) !void {
    const astgen = gz.astgen;
    const tree = astgen.tree;

    if (statements.len == 0) return;

    var block_arena = std.heap.ArenaAllocator.init(gz.astgen.gpa);
    defer block_arena.deinit();
    const block_arena_allocator = block_arena.allocator();

    var noreturn_src_node: Ast.Node.OptionalIndex = .none;
    var scope = parent_scope;
    for (statements, 0..) |statement, stmt_idx| {
        if (noreturn_src_node.unwrap()) |src_node| {
            try astgen.appendErrorNodeNotes(
                statement,
                "unreachable code",
                .{},
                &[_]u32{
                    try astgen.errNoteNode(
                        src_node,
                        "control flow is diverted here",
                        .{},
                    ),
                },
            );
        }
        const allow_branch_hint = switch (block_kind) {
            .normal => false,
            .allow_branch_hint => stmt_idx == 0,
        };
        var inner_node = statement;
        while (true) {
            switch (tree.nodeTag(inner_node)) {
                // zig fmt: off
                .global_var_decl,
                .local_var_decl,
                .simple_var_decl,
                .aligned_var_decl, => scope = try varDecl(gz, scope, statement, block_arena_allocator, tree.fullVarDecl(statement).?),

                .assign_destructure => scope = try assignDestructureMaybeDecls(gz, scope, statement, block_arena_allocator),

                .@"defer"    => scope = try deferStmt(gz, scope, statement, block_arena_allocator, .defer_normal),
                .@"errdefer" => scope = try deferStmt(gz, scope, statement, block_arena_allocator, .defer_error),

                .assign => try assign(gz, scope, statement),

                .assign_shl => try assignShift(gz, scope, statement, .shl),
                .assign_shr => try assignShift(gz, scope, statement, .shr),

                .assign_bit_and  => try assignOp(gz, scope, statement, .bit_and),
                .assign_bit_or   => try assignOp(gz, scope, statement, .bit_or),
                .assign_bit_xor  => try assignOp(gz, scope, statement, .xor),
                .assign_div      => try assignOp(gz, scope, statement, .div),
                .assign_sub      => try assignOp(gz, scope, statement, .sub),
                .assign_sub_wrap => try assignOp(gz, scope, statement, .subwrap),
                .assign_mod      => try assignOp(gz, scope, statement, .mod_rem),
                .assign_add      => try assignOp(gz, scope, statement, .add),
                .assign_add_wrap => try assignOp(gz, scope, statement, .addwrap),
                .assign_mul      => try assignOp(gz, scope, statement, .mul),
                .assign_mul_wrap => try assignOp(gz, scope, statement, .mulwrap),

                .grouped_expression => {
                    inner_node = tree.nodeData(inner_node).node_and_token[0];
                    continue;
                },

                .while_simple,
                .while_cont,
                .@"while", => _ = try whileExpr(gz, scope, .{ .rl = .none }, inner_node, tree.fullWhile(inner_node).?, true),

                .for_simple,
                .@"for", => _ = try forExpr(gz, scope, .{ .rl = .none }, inner_node, tree.fullFor(inner_node).?, true),
                // zig fmt: on

                // 此处保留这些分支以允许分支提示。
                .builtin_call_two,
                .builtin_call_two_comma,
                .builtin_call,
                .builtin_call_comma,
                => {
                    var buf: [2]Ast.Node.Index = undefined;
                    const params = tree.builtinCallParams(&buf, inner_node).?;

                    try emitDbgNode(gz, inner_node);
                    const result = try builtinCall(gz, scope, .{ .rl = .none }, inner_node, params, allow_branch_hint, .anon);
                    noreturn_src_node = try addEnsureResult(gz, result, inner_node);
                },

                else => noreturn_src_node = try unusedResultExpr(gz, scope, inner_node),
            }
            break;
        }
    }

    if (noreturn_src_node == .none) {
        try genDefers(gz, parent_scope, scope, .normal_only);
    }
    try checkUsed(gz, parent_scope, scope);
}

/// 若语句确定为 `noreturn`,返回其中 noreturn 部分的 AST 源节点。
/// 否则返回 .none。
fn unusedResultExpr(gz: *GenZir, scope: *Scope, statement: Ast.Node.Index) InnerError!Ast.Node.OptionalIndex {
    try emitDbgNode(gz, statement);
    // 若结果不是 `noreturn` 或 `void`,需要报错;但出于性能考虑,希望尽可能避免添加 ZIR 指令。
    //
    const maybe_unused_result = try expr(gz, scope, .{ .rl = .none }, statement);
    return addEnsureResult(gz, maybe_unused_result, statement);
}

fn addEnsureResult(gz: *GenZir, maybe_unused_result: Zir.Inst.Ref, statement: Ast.Node.Index) InnerError!Ast.Node.OptionalIndex {
    var noreturn_src_node: Ast.Node.OptionalIndex = .none;
    const elide_check = if (maybe_unused_result.toIndex()) |inst| b: {
        // 注意,在上方 while 循环中向此数组
        // 追加更多元素后,该数组会失效。
        const zir_tags = gz.astgen.instructions.items(.tag);
        switch (zir_tags[@backingInt(inst)]) {
            // 对于某些指令,修改 zir 数据,
            // 以避免单独的 ensure_result_used 指令。
            .call, .field_call => {
                const break_extra = gz.astgen.instructions.items(.data)[@backingInt(inst)].pl_node.payload_index;
                comptime assert(std.meta.fieldIndex(Zir.Inst.Call, "flags") ==
                    std.meta.fieldIndex(Zir.Inst.FieldCall, "flags"));
                const flags: *Zir.Inst.Call.Flags = @ptrCast(&gz.astgen.extra.items[
                    break_extra + std.meta.fieldIndex(Zir.Inst.Call, "flags").?
                ]);
                flags.ensure_result_used = true;
                break :b true;
            },
            .builtin_call => {
                const break_extra = gz.astgen.instructions.items(.data)[@backingInt(inst)].pl_node.payload_index;
                const flags: *Zir.Inst.BuiltinCall.Flags = @ptrCast(&gz.astgen.extra.items[
                    break_extra + std.meta.fieldIndex(Zir.Inst.BuiltinCall, "flags").?
                ]);
                flags.ensure_result_used = true;
                break :b true;
            },

            // 类型可能不是 `noreturn` 或 `void` 的 ZIR 指令。
            .add,
            .addwrap,
            .add_sat,
            .add_unsafe,
            .param,
            .param_comptime,
            .param_anytype,
            .param_anytype_comptime,
            .alloc,
            .alloc_mut,
            .alloc_comptime_mut,
            .alloc_inferred,
            .alloc_inferred_mut,
            .alloc_inferred_comptime,
            .alloc_inferred_comptime_mut,
            .make_ptr_const,
            .array_cat,
            .array_type,
            .array_type_sentinel,
            .elem_type,
            .indexable_ptr_elem_type,
            .splat_op_result_ty,
            .from_backing_int_arg_ty,
            .reify_int,
            .vector_type,
            .indexable_ptr_len,
            .anyframe_type,
            .as_node,
            .as_shift_operand,
            .bit_and,
            .bitcast,
            .bit_or,
            .block,
            .block_comptime,
            .block_inline,
            .declaration,
            .suspend_block,
            .loop,
            .bool_br_and,
            .bool_br_or,
            .bool_not,
            .cmp_lt,
            .cmp_lte,
            .cmp_eq,
            .cmp_gte,
            .cmp_gt,
            .cmp_neq,
            .decl_ref,
            .decl_val,
            .load,
            .div,
            .elem_ptr,
            .elem_val,
            .elem_ptr_node,
            .elem_ptr_load,
            .elem_val_imm,
            .field_ptr,
            .field_ptr_load,
            .field_ptr_named,
            .field_ptr_named_load,
            .func,
            .func_inferred,
            .func_fancy,
            .int,
            .int_big,
            .float,
            .float128,
            .int_type,
            .is_non_null,
            .is_non_null_ptr,
            .is_non_err,
            .is_non_err_ptr,
            .ret_is_non_err,
            .mod_rem,
            .mul,
            .mulwrap,
            .mul_sat,
            .ref,
            .deref,
            .ref_deref,
            .shl,
            .shl_sat,
            .shr,
            .str,
            .sub,
            .subwrap,
            .sub_sat,
            .negate,
            .negate_wrap,
            .typeof,
            .typeof_builtin,
            .xor,
            .optional_type,
            .optional_payload_safe,
            .optional_payload_unsafe,
            .optional_payload_safe_ptr,
            .optional_payload_unsafe_ptr,
            .err_union_payload_unsafe,
            .err_union_payload_unsafe_ptr,
            .err_union_code,
            .err_union_code_ptr,
            .ptr_type,
            .enum_literal,
            .decl_literal,
            .decl_literal_no_coerce,
            .merge_error_sets,
            .error_union_type,
            .bit_not,
            .error_value,
            .slice_start,
            .slice_end,
            .slice_sentinel,
            .slice_length,
            .slice_sentinel_ty,
            .import,
            .switch_block,
            .switch_block_ref,
            .switch_block_err_union,
            .union_init,
            .field_type_ref,
            .error_set_decl,
            .enum_from_int,
            .int_from_enum,
            .backing_int,
            .from_backing_int,
            .type_info,
            .size_of,
            .bit_size_of,
            .typeof_log2_int_type,
            .int_from_ptr,
            .align_of,
            .int_from_bool,
            .embed_file,
            .error_name,
            .sqrt,
            .sin,
            .cos,
            .tan,
            .exp,
            .exp2,
            .log,
            .log2,
            .log10,
            .abs,
            .floor,
            .ceil,
            .trunc,
            .round,
            .tag_name,
            .type_name,
            .frame_type,
            .int_from_float,
            .float_from_int,
            .ptr_from_int,
            .float_cast,
            .int_cast,
            .ptr_cast,
            .truncate,
            .has_decl,
            .has_field,
            .clz,
            .ctz,
            .pop_count,
            .byte_swap,
            .bit_reverse,
            .div_exact,
            .div_floor,
            .div_ceil,
            .div_trunc,
            .mod,
            .rem,
            .shl_exact,
            .shr_exact,
            .bit_offset_of,
            .offset_of,
            .splat,
            .reduce,
            .shuffle,
            .atomic_load,
            .atomic_rmw,
            .mul_add,
            .max,
            .min,
            .@"resume",
            .ret_ptr,
            .ret_type,
            .for_len,
            .@"try",
            .try_ptr,
            .opt_eu_base_ptr_init,
            .coerce_ptr_elem_ty,
            .struct_init_empty,
            .struct_init_empty_result,
            .struct_init_empty_ref_result,
            .struct_init_anon,
            .struct_init,
            .struct_init_ref,
            .struct_init_field_type,
            .struct_init_field_ptr,
            .array_init_anon,
            .array_init,
            .array_init_ref,
            .validate_array_init_ref_ty,
            .array_init_elem_type,
            .array_init_elem_ptr,
            => break :b false,

            .extended => switch (gz.astgen.instructions.items(.data)[@backingInt(inst)].extended.opcode) {
                .breakpoint,
                .disable_instrumentation,
                .disable_intrinsics,
                .set_float_mode,
                .branch_hint,
                => break :b true,
                else => break :b false,
            },

            // 始终为 `noreturn` 的 ZIR 指令。
            .@"break",
            .break_inline,
            .condbr,
            .condbr_inline,
            .compile_error,
            .ret_node,
            .ret_load,
            .ret_implicit,
            .ret_err_value,
            .@"unreachable",
            .repeat,
            .repeat_inline,
            .panic,
            .trap,
            .check_comptime_control_flow,
            .switch_continue,
            => {
                noreturn_src_node = statement.toOptional();
                break :b true;
            },

            // 始终为 `void` 的 ZIR 指令。
            .dbg_stmt,
            .dbg_var_ptr,
            .dbg_var_val,
            .ensure_result_used,
            .ensure_result_non_error,
            .ensure_err_union_payload_void,
            .@"export",
            .set_eval_branch_quota,
            .atomic_store,
            .store_node,
            .store_to_inferred_ptr,
            .resolve_inferred_alloc,
            .set_runtime_safety,
            .memcpy,
            .memset,
            .memmove,
            .validate_destructure,
            .save_err_ret_index,
            .restore_err_ret_index_unconditional,
            .restore_err_ret_index_fn_entry,
            .validate_struct_init_ty,
            .validate_struct_init_result_ty,
            .validate_ptr_struct_init,
            .validate_array_init_ty,
            .validate_array_init_result_ty,
            .validate_ptr_array_init,
            .validate_ref_ty,
            .validate_const,
            => break :b true,

            .@"defer" => unreachable,
        }
    } else switch (maybe_unused_result) {
        .none => unreachable,

        .unreachable_value => b: {
            noreturn_src_node = statement.toOptional();
            break :b true;
        },

        .void_value => true,

        else => false,
    };
    if (!elide_check) {
        _ = try gz.addUnNode(.ensure_result_used, maybe_unused_result, statement);
    }
    return noreturn_src_node;
}

fn anyErrdefers(outer_scope: *Scope, inner_scope: *Scope) bool {
    var scope = inner_scope;
    while (scope != outer_scope) {
        switch (scope.unwrap()) {
            .gen_zir => |gen_zir| scope = gen_zir.parent,
            .local_val => |local_val| scope = local_val.parent,
            .local_ptr => |local_ptr| scope = local_ptr.parent,
            .defer_normal => |defer_normal| scope = defer_normal.parent,
            .defer_error => return true,
            .namespace => unreachable,
            .top => unreachable,
        }
    }
    return false;
}

fn genDefers(
    gz: *GenZir,
    outer_scope: *Scope,
    inner_scope: *Scope,
    which_ones: enum { normal_only, normal_and_error },
) InnerError!void {
    var scope = inner_scope;
    while (scope != outer_scope) {
        switch (scope.unwrap()) {
            .gen_zir => |gen_zir| scope = gen_zir.parent,
            .local_val => |local_val| scope = local_val.parent,
            .local_ptr => |local_ptr| scope = local_ptr.parent,
            .defer_normal => |defer_scope| {
                scope = defer_scope.parent;
                try gz.addDefer(defer_scope.index, defer_scope.len);
            },
            .defer_error => |defer_scope| {
                scope = defer_scope.parent;
                switch (which_ones) {
                    .normal_only => continue,
                    .normal_and_error => {
                        try gz.addDefer(defer_scope.index, defer_scope.len);
                    },
                }
            },
            .namespace => unreachable,
            .top => unreachable,
        }
    }
}

fn checkUsed(gz: *GenZir, outer_scope: *Scope, inner_scope: *Scope) InnerError!void {
    const astgen = gz.astgen;

    var scope = inner_scope;
    while (scope != outer_scope) {
        switch (scope.unwrap()) {
            .gen_zir => |gen_zir| scope = gen_zir.parent,
            .local_val => |s| {
                if (s.used == .none and s.discarded == .none) {
                    try astgen.appendErrorTok(s.token_src, "unused {s}", .{@tagName(s.id_cat)});
                } else if (s.used != .none and s.discarded != .none) {
                    try astgen.appendErrorTokNotes(s.discarded.unwrap().?, "pointless discard of {s}", .{@tagName(s.id_cat)}, &[_]u32{
                        try gz.astgen.errNoteTok(s.used.unwrap().?, "used here", .{}),
                    });
                }
                scope = s.parent;
            },
            .local_ptr => |s| {
                if (s.used == .none and s.discarded == .none) {
                    try astgen.appendErrorTok(s.token_src, "unused {s}", .{@tagName(s.id_cat)});
                } else {
                    if (s.used != .none and s.discarded != .none) {
                        try astgen.appendErrorTokNotes(s.discarded.unwrap().?, "pointless discard of {s}", .{@tagName(s.id_cat)}, &[_]u32{
                            try astgen.errNoteTok(s.used.unwrap().?, "used here", .{}),
                        });
                    }
                    if (s.id_cat == .@"local variable" and !s.used_as_lvalue) {
                        try astgen.appendErrorTokNotes(s.token_src, "local variable is never mutated", .{}, &.{
                            try astgen.errNoteTok(s.token_src, "consider using 'const'", .{}),
                        });
                    }
                }
                scope = s.parent;
            },
            .defer_normal, .defer_error => |defer_scope| scope = defer_scope.parent,
            .namespace => unreachable,
            .top => unreachable,
        }
    }
}

fn deferStmt(
    gz: *GenZir,
    scope: *Scope,
    node: Ast.Node.Index,
    block_arena: Allocator,
    scope_tag: Scope.Tag,
) InnerError!*Scope {
    var defer_gen = gz.makeSubBlock(scope);
    defer_gen.cur_defer_node = node.toOptional();
    defer_gen.any_defer_node = node.toOptional();
    defer defer_gen.unstack();

    const tree = gz.astgen.tree;
    const expr_node = tree.nodeData(node).node;
    _ = try unusedResultExpr(&defer_gen, &defer_gen.base, expr_node);
    try checkUsed(gz, scope, &defer_gen.base);
    _ = try defer_gen.addBreak(.break_inline, @fromBackingInt(@intCast(0)), .void_value);

    const body = defer_gen.instructionsSlice();
    const body_len = gz.astgen.countBodyLenAfterFixupsExtraRefs(body, &.{});

    const index: u32 = @intCast(gz.astgen.extra.items.len);
    try gz.astgen.extra.ensureUnusedCapacity(gz.astgen.gpa, body_len);
    gz.astgen.appendBodyWithFixupsExtraRefsArrayList(&gz.astgen.extra, body, &.{});

    const defer_scope = try block_arena.create(Scope.Defer);

    defer_scope.* = .{
        .base = .{ .tag = scope_tag },
        .parent = scope,
        .index = index,
        .len = body_len,
    };
    return &defer_scope.base;
}

fn varDecl(
    gz: *GenZir,
    scope: *Scope,
    node: Ast.Node.Index,
    block_arena: Allocator,
    var_decl: Ast.full.VarDecl,
) InnerError!*Scope {
    try emitDbgNode(gz, node);
    const astgen = gz.astgen;
    const tree = astgen.tree;

    const name_token = var_decl.ast.mut_token + 1;
    const ident_name_raw = tree.tokenSlice(name_token);
    if (mem.eql(u8, ident_name_raw, "_")) {
        return astgen.failTok(name_token, "'_' used as an identifier without @\"_\" syntax", .{});
    }
    const ident_name = try astgen.identAsString(name_token);

    try astgen.detectLocalShadowing(
        scope,
        ident_name,
        name_token,
        ident_name_raw,
        if (tree.tokenTag(var_decl.ast.mut_token) == .keyword_const) .@"local constant" else .@"local variable",
    );

    const init_node = var_decl.ast.init_node.unwrap() orelse {
        return astgen.failNode(node, "variables must be initialized", .{});
    };

    if (var_decl.ast.addrspace_node.unwrap()) |addrspace_node| {
        return astgen.failTok(tree.nodeMainToken(addrspace_node), "cannot set address space of local variable '{s}'", .{ident_name_raw});
    }

    if (var_decl.ast.section_node.unwrap()) |section_node| {
        return astgen.failTok(tree.nodeMainToken(section_node), "cannot set section of local variable '{s}'", .{ident_name_raw});
    }

    const type_inst: Zir.Inst.Ref = if (var_decl.ast.type_node.unwrap()) |type_node|
        try typeExpr(gz, scope, type_node)
    else
        .none;

    const align_inst: Zir.Inst.Ref = if (var_decl.ast.align_node.unwrap()) |align_node|
        try comptimeExpr(gz, scope, coerced_align_ri, align_node, .@"align")
    else
        .none;

    switch (tree.tokenTag(var_decl.ast.mut_token)) {
        .keyword_const => {
            if (var_decl.comptime_token) |comptime_token| {
                try astgen.appendErrorTok(comptime_token, "'comptime const' is redundant; instead wrap the initialization expression with 'comptime'", .{});
            }

            // `comptime const` 是非致命错误;将其视为初始化被标记为 `comptime`。
            const force_comptime = var_decl.comptime_token != null;

            // 根据初始化表达式的 AST 类型,可能需要左值或右值作为结果位置。
            // 若为右值,则可直接将指令用作变量,
            // 无需内存位置。
            if (align_inst == .none and
                !astgen.nodes_need_rl.contains(node))
            {
                const result_info: ResultInfo = if (type_inst != .none) .{
                    .rl = .{ .ty = type_inst },
                    .ctx = .const_init,
                } else .{ .rl = .none, .ctx = .const_init };
                const init_inst: Zir.Inst.Ref = try nameStratExpr(gz, scope, result_info, init_node, .dbg_var) orelse
                    try reachableExprComptime(gz, scope, result_info, init_node, node, if (force_comptime) .comptime_keyword else null);

                _ = try gz.addUnNode(.validate_const, init_inst, init_node);
                try gz.addDbgVar(.dbg_var_val, ident_name, init_inst);

                // const 初始化表达式可能已修改错误返回追踪,因此通知 Sema 保存新索引,以供稍后恢复。
                //
                if (nodeMayAppendToErrorTrace(tree, init_node))
                    _ = try gz.addSaveErrRetIndex(.{ .if_of_error_type = init_inst });

                const sub_scope = try block_arena.create(Scope.LocalVal);
                sub_scope.* = .{
                    .parent = scope,
                    .gen_zir = gz,
                    .name = ident_name,
                    .inst = init_inst,
                    .token_src = name_token,
                    .id_cat = .@"local constant",
                };
                return &sub_scope.base;
            }

            const is_comptime = gz.is_comptime or
                tree.nodeTag(init_node) == .@"comptime";

            const init_rl: ResultInfo.Loc = if (type_inst != .none) init_rl: {
                if (align_inst == .none) {
                    break :init_rl .{ .ptr = .{ .inst = try gz.addUnNode(.alloc, type_inst, node) } };
                } else {
                    break :init_rl .{ .ptr = .{ .inst = try gz.addAllocExtended(.{
                        .node = node,
                        .type_inst = type_inst,
                        .align_inst = align_inst,
                        .is_const = true,
                        .is_comptime = is_comptime,
                    }) } };
                }
            } else init_rl: {
                const alloc_inst = if (align_inst == .none) ptr: {
                    const tag: Zir.Inst.Tag = if (is_comptime)
                        .alloc_inferred_comptime
                    else
                        .alloc_inferred;
                    break :ptr try gz.addNode(tag, node);
                } else ptr: {
                    break :ptr try gz.addAllocExtended(.{
                        .node = node,
                        .type_inst = .none,
                        .align_inst = align_inst,
                        .is_const = true,
                        .is_comptime = is_comptime,
                    });
                };
                break :init_rl .{ .inferred_ptr = alloc_inst };
            };
            const var_ptr: Zir.Inst.Ref, const resolve_inferred: bool = switch (init_rl) {
                .ptr => |ptr| .{ ptr.inst, false },
                .inferred_ptr => |inst| .{ inst, true },
                else => unreachable,
            };
            const init_result_info: ResultInfo = .{ .rl = init_rl, .ctx = .const_init };

            const init_inst: Zir.Inst.Ref = try nameStratExpr(gz, scope, init_result_info, init_node, .dbg_var) orelse
                try reachableExprComptime(gz, scope, init_result_info, init_node, node, if (force_comptime) .comptime_keyword else null);

            // const 初始化表达式可能已修改错误返回追踪,因此通知 Sema 保存新索引,以供稍后恢复。
            //
            if (nodeMayAppendToErrorTrace(tree, init_node))
                _ = try gz.addSaveErrRetIndex(.{ .if_of_error_type = init_inst });

            const const_ptr = if (resolve_inferred)
                try gz.addUnNode(.resolve_inferred_alloc, var_ptr, node)
            else
                try gz.addUnNode(.make_ptr_const, var_ptr, node);

            try gz.addDbgVar(.dbg_var_ptr, ident_name, const_ptr);

            const sub_scope = try block_arena.create(Scope.LocalPtr);
            sub_scope.* = .{
                .parent = scope,
                .gen_zir = gz,
                .name = ident_name,
                .ptr = const_ptr,
                .token_src = name_token,
                .maybe_comptime = true,
                .id_cat = .@"local constant",
            };
            return &sub_scope.base;
        },
        .keyword_var => {
            if (var_decl.comptime_token != null and gz.is_comptime)
                return astgen.failTok(var_decl.comptime_token.?, "'comptime var' is redundant in comptime scope", .{});
            const is_comptime = var_decl.comptime_token != null or gz.is_comptime;
            const alloc: Zir.Inst.Ref, const resolve_inferred: bool, const result_info: ResultInfo = if (type_inst != .none) a: {
                const alloc = alloc: {
                    if (align_inst == .none) {
                        const tag: Zir.Inst.Tag = if (is_comptime)
                            .alloc_comptime_mut
                        else
                            .alloc_mut;
                        break :alloc try gz.addUnNode(tag, type_inst, node);
                    } else {
                        break :alloc try gz.addAllocExtended(.{
                            .node = node,
                            .type_inst = type_inst,
                            .align_inst = align_inst,
                            .is_const = false,
                            .is_comptime = is_comptime,
                        });
                    }
                };
                break :a .{ alloc, false, .{ .rl = .{ .ptr = .{ .inst = alloc } } } };
            } else a: {
                const alloc = alloc: {
                    if (align_inst == .none) {
                        const tag: Zir.Inst.Tag = if (is_comptime)
                            .alloc_inferred_comptime_mut
                        else
                            .alloc_inferred_mut;
                        break :alloc try gz.addNode(tag, node);
                    } else {
                        break :alloc try gz.addAllocExtended(.{
                            .node = node,
                            .type_inst = .none,
                            .align_inst = align_inst,
                            .is_const = false,
                            .is_comptime = is_comptime,
                        });
                    }
                };
                break :a .{ alloc, true, .{ .rl = .{ .inferred_ptr = alloc } } };
            };
            _ = try nameStratExpr(
                gz,
                scope,
                result_info,
                init_node,
                .dbg_var,
            ) orelse try reachableExprComptime(
                gz,
                scope,
                result_info,
                init_node,
                node,
                if (var_decl.comptime_token != null) .comptime_keyword else null,
            );
            const final_ptr: Zir.Inst.Ref = if (resolve_inferred) ptr: {
                break :ptr try gz.addUnNode(.resolve_inferred_alloc, alloc, node);
            } else alloc;

            try gz.addDbgVar(.dbg_var_ptr, ident_name, final_ptr);

            const sub_scope = try block_arena.create(Scope.LocalPtr);
            sub_scope.* = .{
                .parent = scope,
                .gen_zir = gz,
                .name = ident_name,
                .ptr = final_ptr,
                .token_src = name_token,
                .maybe_comptime = is_comptime,
                .id_cat = .@"local variable",
            };
            return &sub_scope.base;
        },
        else => unreachable,
    }
}

fn emitDbgNode(gz: *GenZir, node: Ast.Node.Index) !void {
    // 此处生成的指令用于调试运行时代码。
    // 若当前块仅在语义分析期间求值,
    // 则无需生成 dbg_stmt ZIR 指令。
    if (gz.is_comptime) return;
    const astgen = gz.astgen;
    astgen.advanceSourceCursorToNode(node);
    const line = astgen.source_line - gz.decl_line;
    const column = astgen.source_column;
    try emitDbgStmt(gz, .{ line, column });
}

fn assign(gz: *GenZir, scope: *Scope, infix_node: Ast.Node.Index) InnerError!void {
    try emitDbgNode(gz, infix_node);
    const astgen = gz.astgen;
    const tree = astgen.tree;

    const lhs, const rhs = tree.nodeData(infix_node).node_and_node;
    if (tree.nodeTag(lhs) == .identifier) {
        // 此处有意不支持 `@"_"` 语法。
        const ident_name = tree.tokenSlice(tree.nodeMainToken(lhs));
        if (mem.eql(u8, ident_name, "_")) {
            _ = try expr(gz, scope, .{ .rl = .discard, .ctx = .assignment }, rhs);
            return;
        }
    }
    const lvalue = try lvalExpr(gz, scope, lhs);
    _ = try expr(gz, scope, .{ .rl = .{ .ptr = .{
        .inst = lvalue,
        .src_node = infix_node,
    } } }, rhs);
}

/// 处理左侧均不为 `const` 或 `var` 声明的解构赋值。
fn assignDestructure(gz: *GenZir, scope: *Scope, node: Ast.Node.Index) InnerError!void {
    try emitDbgNode(gz, node);
    const astgen = gz.astgen;
    const tree = astgen.tree;

    const full = tree.assignDestructure(node);
    if (full.comptime_token != null and gz.is_comptime) {
        return astgen.appendErrorTok(full.comptime_token.?, "redundant comptime keyword in already comptime scope", .{});
    }

    // 若此表达式标记为 comptime,则必须将整个表达式包装在 comptime 块中。
    var gz_buf: GenZir = undefined;
    const inner_gz = if (full.comptime_token) |_| bs: {
        gz_buf = gz.makeSubBlock(scope);
        gz_buf.is_comptime = true;
        break :bs &gz_buf;
    } else gz;
    defer if (full.comptime_token) |_| inner_gz.unstack();

    const rl_components = try astgen.arena.alloc(ResultInfo.Loc.DestructureComponent, full.ast.variables.len);
    for (rl_components, full.ast.variables) |*variable_rl, variable_node| {
        if (tree.nodeTag(variable_node) == .identifier) {
            // 此处有意不支持 `@"_"` 语法。
            const ident_name = tree.tokenSlice(tree.nodeMainToken(variable_node));
            if (mem.eql(u8, ident_name, "_")) {
                variable_rl.* = .discard;
                continue;
            }
        }
        variable_rl.* = .{ .typed_ptr = .{
            .inst = try lvalExpr(inner_gz, scope, variable_node),
            .src_node = variable_node,
        } };
    }

    const ri: ResultInfo = .{ .rl = .{ .destructure = .{
        .src_node = node,
        .components = rl_components,
    } } };

    _ = try expr(inner_gz, scope, ri, full.ast.value_expr);

    if (full.comptime_token) |_| {
        const comptime_block_inst = try gz.makeBlockInst(.block_comptime, node);
        _ = try inner_gz.addBreak(.break_inline, comptime_block_inst, .void_value);
        try inner_gz.setBlockComptimeBody(comptime_block_inst, .comptime_keyword);
        try gz.instructions.append(gz.astgen.gpa, comptime_block_inst);
    }
}

/// 处理左侧可能包含 `const` 或 `var` 声明的解构赋值。
fn assignDestructureMaybeDecls(
    gz: *GenZir,
    scope: *Scope,
    node: Ast.Node.Index,
    block_arena: Allocator,
) InnerError!*Scope {
    try emitDbgNode(gz, node);
    const astgen = gz.astgen;
    const tree = astgen.tree;

    const full = tree.assignDestructure(node);
    if (full.comptime_token != null and gz.is_comptime) {
        try astgen.appendErrorTok(full.comptime_token.?, "redundant comptime keyword in already comptime scope", .{});
    }

    const is_comptime = full.comptime_token != null or gz.is_comptime;
    const value_is_comptime = tree.nodeTag(full.ast.value_expr) == .@"comptime";

    const saved_cursor = astgen.saveSourceCursor();
    // 通过解构声明常量时,始终使用结果指针。
    // 这样无需创建元组类型,也可能更容易优化,
    // 因为优化器随后要将该值拆分为
    // 逐个指针写入会比较棘手。

    // 已知此 rl 信息的生存期不会超过当前表达式的求值,因此也可将其放入块区域分配器。
    //
    const rl_components = try block_arena.alloc(ResultInfo.Loc.DestructureComponent, full.ast.variables.len);
    var any_non_const_variables = false;
    var any_lvalue_expr = false;
    for (rl_components, full.ast.variables) |*variable_rl, variable_node| {
        switch (tree.nodeTag(variable_node)) {
            .identifier => {
                // 此处有意不支持 `@"_"` 语法。
                const ident_name = tree.tokenSlice(tree.nodeMainToken(variable_node));
                if (mem.eql(u8, ident_name, "_")) {
                    any_non_const_variables = true;
                    variable_rl.* = .discard;
                    continue;
                }
            },
            .global_var_decl, .local_var_decl, .simple_var_decl, .aligned_var_decl => {
                const full_var_decl = tree.fullVarDecl(variable_node).?;

                const name_token = full_var_decl.ast.mut_token + 1;
                const ident_name_raw = tree.tokenSlice(name_token);
                if (mem.eql(u8, ident_name_raw, "_")) {
                    return astgen.failTok(name_token, "'_' used as an identifier without @\"_\" syntax", .{});
                }

                // 第二次遍历这些内容、创建作用域时,检测名称遮蔽。

                if (full_var_decl.ast.addrspace_node.unwrap()) |addrspace_node| {
                    return astgen.failTok(tree.nodeMainToken(addrspace_node), "cannot set address space of local variable '{s}'", .{ident_name_raw});
                }
                if (full_var_decl.ast.section_node.unwrap()) |section_node| {
                    return astgen.failTok(tree.nodeMainToken(section_node), "cannot set section of local variable '{s}'", .{ident_name_raw});
                }

                const is_const = switch (tree.tokenTag(full_var_decl.ast.mut_token)) {
                    .keyword_var => false,
                    .keyword_const => true,
                    else => unreachable,
                };
                if (!is_const) any_non_const_variables = true;

                // 若 RHS 确定在编译期已知,也将 `const` 标记为编译期值。
                const this_variable_comptime = is_comptime or (is_const and value_is_comptime);

                const type_inst = if (full_var_decl.ast.type_node.unwrap()) |type_node|
                    try typeExpr(gz, scope, type_node)
                else
                    .none;

                const align_inst: Zir.Inst.Ref = if (full_var_decl.ast.align_node.unwrap()) |align_node|
                    try comptimeExpr(gz, scope, coerced_align_ri, align_node, .@"align")
                else
                    .none;

                if (type_inst != .none) {
                    // 有类型分配
                    const ptr = if (align_inst == .none) ptr: {
                        const tag: Zir.Inst.Tag = if (this_variable_comptime)
                            .alloc_comptime_mut
                        else if (is_const)
                            .alloc
                        else
                            .alloc_mut;
                        break :ptr try gz.addUnNode(tag, type_inst, node);
                    } else try gz.addAllocExtended(.{
                        .node = node,
                        .type_inst = type_inst,
                        .align_inst = align_inst,
                        .is_const = is_const,
                        .is_comptime = this_variable_comptime,
                    });
                    variable_rl.* = .{ .typed_ptr = .{ .inst = ptr } };
                } else {
                    // 推导分配
                    const ptr = if (align_inst == .none) ptr: {
                        const tag: Zir.Inst.Tag = if (is_const) tag: {
                            break :tag if (this_variable_comptime) .alloc_inferred_comptime else .alloc_inferred;
                        } else tag: {
                            break :tag if (this_variable_comptime) .alloc_inferred_comptime_mut else .alloc_inferred_mut;
                        };
                        break :ptr try gz.addNode(tag, node);
                    } else try gz.addAllocExtended(.{
                        .node = node,
                        .type_inst = .none,
                        .align_inst = align_inst,
                        .is_const = is_const,
                        .is_comptime = this_variable_comptime,
                    });
                    variable_rl.* = .{ .inferred_ptr = ptr };
                }

                continue;
            },
            else => {},
        }
        // 此变量只是左值表达式。
        // 稍后会在编译期块内填入其结果指针。
        any_non_const_variables = true;
        any_lvalue_expr = true;
        variable_rl.* = .{ .typed_ptr = .{
            .inst = undefined,
            .src_node = variable_node,
        } };
    }

    if (full.comptime_token != null and !any_non_const_variables) {
        try astgen.appendErrorTok(full.comptime_token.?, "'comptime const' is redundant; instead wrap the initialization expression with 'comptime'", .{});
        // 注意,这不是致命错误;仍将在编译期求值。
    }

    // 如果此表达式被标记为 comptime,则必须将其包装在 comptime 块中。
    var gz_buf: GenZir = undefined;
    const inner_gz = if (full.comptime_token) |_| bs: {
        gz_buf = gz.makeSubBlock(scope);
        gz_buf.is_comptime = true;
        break :bs &gz_buf;
    } else gz;
    defer if (full.comptime_token) |_| inner_gz.unstack();

    if (any_lvalue_expr) {
        // 至少一个变量为左值表达式。再次遍历,
        // 以便在可能存在的 block_comptime 中对左值求值。
        astgen.restoreSourceCursor(saved_cursor);
        for (rl_components, full.ast.variables) |*variable_rl, variable_node| {
            if (variable_rl.* != .typed_ptr) continue;
            switch (tree.nodeTag(variable_node)) {
                .global_var_decl, .local_var_decl, .simple_var_decl, .aligned_var_decl => continue,
                else => {},
            }
            variable_rl.typed_ptr.inst = try lvalExpr(inner_gz, scope, variable_node);
        }
    }

    // 无法为解构初始化提供合理的匿名命名策略,因此
    // 保留默认值 `.anon`。
    _ = try reachableExpr(inner_gz, scope, .{ .rl = .{ .destructure = .{
        .src_node = node,
        .components = rl_components,
    } } }, full.ast.value_expr, node);

    if (full.comptime_token) |_| {
        // 结束 block_comptime。
        // 推断分配解析等操作将在父块中进行。
        const comptime_block_inst = try gz.makeBlockInst(.block_comptime, node);
        _ = try inner_gz.addBreak(.break_inline, comptime_block_inst, .void_value);
        try inner_gz.setBlockComptimeBody(comptime_block_inst, .comptime_keyword);
        try gz.instructions.append(gz.astgen.gpa, comptime_block_inst);
    }

    // 现在遍历变量表达式,构造所需的新作用域。
    // 若存在推导分配,则解析它们。
    // 若存在 `const` 声明,则将指针设为常量。
    var cur_scope = scope;
    for (rl_components, full.ast.variables) |variable_rl, variable_node| {
        switch (tree.nodeTag(variable_node)) {
            .local_var_decl, .simple_var_decl, .aligned_var_decl => {},
            else => continue, // 此前在修改已有左值,无需操作
        }
        const full_var_decl = tree.fullVarDecl(variable_node).?;
        const raw_ptr, const resolve_inferred = switch (variable_rl) {
            .discard => unreachable,
            .typed_ptr => |typed_ptr| .{ typed_ptr.inst, false },
            .inferred_ptr => |ptr_inst| .{ ptr_inst, true },
        };
        const is_const = switch (tree.tokenTag(full_var_decl.ast.mut_token)) {
            .keyword_var => false,
            .keyword_const => true,
            else => unreachable,
        };

        // 若分配类型是推断的,则解析它;若分配为 const,则使其保持 const。
        const final_ptr = if (resolve_inferred)
            try gz.addUnNode(.resolve_inferred_alloc, raw_ptr, variable_node)
        else if (is_const)
            try gz.addUnNode(.make_ptr_const, raw_ptr, node)
        else
            raw_ptr;

        const name_token = full_var_decl.ast.mut_token + 1;
        const ident_name_raw = tree.tokenSlice(name_token);
        const ident_name = try astgen.identAsString(name_token);
        try astgen.detectLocalShadowing(
            cur_scope,
            ident_name,
            name_token,
            ident_name_raw,
            if (is_const) .@"local constant" else .@"local variable",
        );
        try gz.addDbgVar(.dbg_var_ptr, ident_name, final_ptr);
        // 最后创建作用域。
        const sub_scope = try block_arena.create(Scope.LocalPtr);
        sub_scope.* = .{
            .parent = cur_scope,
            .gen_zir = gz,
            .name = ident_name,
            .ptr = final_ptr,
            .token_src = name_token,
            .maybe_comptime = is_const or is_comptime,
            .id_cat = if (is_const) .@"local constant" else .@"local variable",
        };
        cur_scope = &sub_scope.base;
    }

    return cur_scope;
}

fn assignOp(
    gz: *GenZir,
    scope: *Scope,
    infix_node: Ast.Node.Index,
    op_inst_tag: Zir.Inst.Tag,
) InnerError!void {
    try emitDbgNode(gz, infix_node);
    const astgen = gz.astgen;
    const tree = astgen.tree;

    const lhs_node, const rhs_node = tree.nodeData(infix_node).node_and_node;
    const lhs_ptr = try lvalExpr(gz, scope, lhs_node);

    const cursor = switch (op_inst_tag) {
        .add, .sub, .mul, .div, .mod_rem => maybeAdvanceSourceCursorToMainToken(gz, infix_node),
        else => undefined,
    };
    const lhs = try gz.addUnNode(.load, lhs_ptr, infix_node);

    const rhs_res_ty = switch (op_inst_tag) {
        .add,
        .sub,
        => try gz.add(.{
            .tag = .extended,
            .data = .{ .extended = .{
                .opcode = .inplace_arith_result_ty,
                .small = @backingInt(@as(Zir.Inst.InplaceOp, switch (op_inst_tag) {
                    .add => .add_eq,
                    .sub => .sub_eq,
                    else => unreachable,
                })),
                .operand = @backingInt(lhs),
            } },
        }),
        else => try gz.addUnNode(.typeof, lhs, infix_node), // 与左操作数类型相同
    };
    // 不是 `coerced_ty`,因为 `add` 等不会强制转换为此类型。
    const rhs = try expr(gz, scope, .{ .rl = .{ .ty = rhs_res_ty } }, rhs_node);

    switch (op_inst_tag) {
        .add, .sub, .mul, .div, .mod_rem => {
            try emitDbgStmt(gz, cursor);
        },
        else => {},
    }
    const result = try gz.addPlNode(op_inst_tag, infix_node, Zir.Inst.Bin{
        .lhs = lhs,
        .rhs = rhs,
    });
    _ = try gz.addPlNode(.store_node, infix_node, Zir.Inst.Bin{
        .lhs = lhs_ptr,
        .rhs = result,
    });
}

fn assignShift(
    gz: *GenZir,
    scope: *Scope,
    infix_node: Ast.Node.Index,
    op_inst_tag: Zir.Inst.Tag,
) InnerError!void {
    try emitDbgNode(gz, infix_node);
    const astgen = gz.astgen;
    const tree = astgen.tree;

    const lhs_node, const rhs_node = tree.nodeData(infix_node).node_and_node;
    const lhs_ptr = try lvalExpr(gz, scope, lhs_node);
    const lhs = try gz.addUnNode(.load, lhs_ptr, infix_node);
    const rhs_type = try gz.addUnNode(.typeof_log2_int_type, lhs, infix_node);
    const rhs = try expr(gz, scope, .{ .rl = .{ .ty = rhs_type } }, rhs_node);

    const result = try gz.addPlNode(op_inst_tag, infix_node, Zir.Inst.Bin{
        .lhs = lhs,
        .rhs = rhs,
    });
    _ = try gz.addPlNode(.store_node, infix_node, Zir.Inst.Bin{
        .lhs = lhs_ptr,
        .rhs = result,
    });
}

fn assignShiftSat(gz: *GenZir, scope: *Scope, infix_node: Ast.Node.Index) InnerError!void {
    try emitDbgNode(gz, infix_node);
    const astgen = gz.astgen;
    const tree = astgen.tree;

    const lhs_node, const rhs_node = tree.nodeData(infix_node).node_and_node;
    const lhs_ptr = try lvalExpr(gz, scope, lhs_node);
    const lhs = try gz.addUnNode(.load, lhs_ptr, infix_node);
    // 饱和左移的左、右操作数均可使用任意整数类型。
    const rhs = try expr(gz, scope, .{ .rl = .none }, rhs_node);

    const result = try gz.addPlNode(.shl_sat, infix_node, Zir.Inst.Bin{
        .lhs = lhs,
        .rhs = rhs,
    });
    _ = try gz.addPlNode(.store_node, infix_node, Zir.Inst.Bin{
        .lhs = lhs_ptr,
        .rhs = result,
    });
}

fn ptrType(
    gz: *GenZir,
    scope: *Scope,
    ri: ResultInfo,
    node: Ast.Node.Index,
    ptr_info: Ast.full.PtrType,
) InnerError!Zir.Inst.Ref {
    if (ptr_info.size == .c and ptr_info.allowzero_token != null) {
        return gz.astgen.failTok(ptr_info.allowzero_token.?, "C pointers always allow address zero", .{});
    }
    if (ptr_info.duplicate_token) |duplicate| {
        return gz.astgen.failTok(duplicate, "Extra pointer qualifier", .{});
    }

    const source_offset = gz.astgen.source_offset;
    const source_line = gz.astgen.source_line;
    const source_column = gz.astgen.source_column;
    const elem_type = try typeExpr(gz, scope, ptr_info.ast.child_type);

    var sentinel_ref: Zir.Inst.Ref = .none;
    var align_ref: Zir.Inst.Ref = .none;
    var addrspace_ref: Zir.Inst.Ref = .none;
    var bit_start_ref: Zir.Inst.Ref = .none;
    var bit_end_ref: Zir.Inst.Ref = .none;
    var trailing_count: u32 = 0;

    if (ptr_info.ast.sentinel.unwrap()) |sentinel| {
        // 这些属性可按任意顺序出现,且全都位于元素类型之前,
        // 因此生成它们之前需要重置源码游标。
        gz.astgen.source_offset = source_offset;
        gz.astgen.source_line = source_line;
        gz.astgen.source_column = source_column;

        sentinel_ref = try comptimeExpr(
            gz,
            scope,
            .{ .rl = .{ .ty = elem_type } },
            sentinel,
            switch (ptr_info.size) {
                .slice => .slice_sentinel,
                else => .pointer_sentinel,
            },
        );
        trailing_count += 1;
    }
    if (ptr_info.ast.addrspace_node.unwrap()) |addrspace_node| {
        gz.astgen.source_offset = source_offset;
        gz.astgen.source_line = source_line;
        gz.astgen.source_column = source_column;

        const addrspace_ty = try gz.addStdLangValue(addrspace_node, .address_space);
        addrspace_ref = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = addrspace_ty } }, addrspace_node, .@"addrspace");
        trailing_count += 1;
    }
    if (ptr_info.ast.align_node.unwrap()) |align_node| {
        gz.astgen.source_offset = source_offset;
        gz.astgen.source_line = source_line;
        gz.astgen.source_column = source_column;

        align_ref = try comptimeExpr(gz, scope, coerced_align_ri, align_node, .@"align");
        trailing_count += 1;
    }
    if (ptr_info.ast.bit_range_start.unwrap()) |bit_range_start| {
        const bit_range_end = ptr_info.ast.bit_range_end.unwrap().?;
        bit_start_ref = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = .u16_type } }, bit_range_start, .type);
        bit_end_ref = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = .u16_type } }, bit_range_end, .type);
        trailing_count += 2;
    }

    const gpa = gz.astgen.gpa;
    try gz.instructions.ensureUnusedCapacity(gpa, 1);
    try gz.astgen.instructions.ensureUnusedCapacity(gpa, 1);
    try gz.astgen.extra.ensureUnusedCapacity(gpa, @typeInfo(Zir.Inst.PtrType).@"struct".field_names.len +
        trailing_count);

    const payload_index = gz.astgen.addExtraAssumeCapacity(Zir.Inst.PtrType{
        .elem_type = elem_type,
        .src_node = gz.nodeIndexToRelative(node),
    });
    if (sentinel_ref != .none) {
        gz.astgen.extra.appendAssumeCapacity(@backingInt(sentinel_ref));
    }
    if (align_ref != .none) {
        gz.astgen.extra.appendAssumeCapacity(@backingInt(align_ref));
    }
    if (addrspace_ref != .none) {
        gz.astgen.extra.appendAssumeCapacity(@backingInt(addrspace_ref));
    }
    if (bit_start_ref != .none) {
        gz.astgen.extra.appendAssumeCapacity(@backingInt(bit_start_ref));
        gz.astgen.extra.appendAssumeCapacity(@backingInt(bit_end_ref));
    }

    const new_index: Zir.Inst.Index = @fromBackingInt(@intCast(gz.astgen.instructions.len));
    const result = new_index.toRef();
    gz.astgen.instructions.appendAssumeCapacity(.{ .tag = .ptr_type, .data = .{
        .ptr_type = .{
            .flags = .{
                .is_allowzero = ptr_info.allowzero_token != null,
                .is_mutable = ptr_info.const_token == null,
                .is_volatile = ptr_info.volatile_token != null,
                .has_sentinel = sentinel_ref != .none,
                .has_align = align_ref != .none,
                .has_addrspace = addrspace_ref != .none,
                .has_bit_range = bit_start_ref != .none,
            },
            .size = ptr_info.size,
            .payload_index = payload_index,
        },
    } });
    gz.instructions.appendAssumeCapacity(new_index);

    return rvalue(gz, ri, result, node);
}

fn arrayType(gz: *GenZir, scope: *Scope, ri: ResultInfo, node: Ast.Node.Index) !Zir.Inst.Ref {
    const astgen = gz.astgen;
    const tree = astgen.tree;

    const len_node, const elem_type_node = tree.nodeData(node).node_and_node;
    if (tree.nodeTag(len_node) == .identifier and
        mem.eql(u8, tree.tokenSlice(tree.nodeMainToken(len_node)), "_"))
    {
        return astgen.failNode(len_node, "unable to infer array size", .{});
    }
    const len = try reachableExprComptime(gz, scope, .{ .rl = .{ .coerced_ty = .usize_type } }, len_node, node, .type);
    const elem_type = try typeExpr(gz, scope, elem_type_node);

    const result = try gz.addPlNode(.array_type, node, Zir.Inst.Bin{
        .lhs = len,
        .rhs = elem_type,
    });
    return rvalue(gz, ri, result, node);
}

fn arrayTypeSentinel(gz: *GenZir, scope: *Scope, ri: ResultInfo, node: Ast.Node.Index) !Zir.Inst.Ref {
    const astgen = gz.astgen;
    const tree = astgen.tree;

    const len_node, const extra_index = tree.nodeData(node).node_and_extra;
    const extra = tree.extraData(extra_index, Ast.Node.ArrayTypeSentinel);

    if (tree.nodeTag(len_node) == .identifier and
        mem.eql(u8, tree.tokenSlice(tree.nodeMainToken(len_node)), "_"))
    {
        return astgen.failNode(len_node, "unable to infer array size", .{});
    }
    const len = try reachableExprComptime(gz, scope, .{ .rl = .{ .coerced_ty = .usize_type } }, len_node, node, .array_length);
    const saved_cursor = astgen.saveSourceCursor();
    const elem_type = try typeExpr(gz, scope, extra.elem_type);
    astgen.restoreSourceCursor(saved_cursor);
    const sentinel = try reachableExprComptime(gz, scope, .{ .rl = .{ .coerced_ty = elem_type } }, extra.sentinel, node, .array_sentinel);

    const result = try gz.addPlNode(.array_type_sentinel, node, Zir.Inst.ArrayTypeSentinel{
        .len = len,
        .elem_type = elem_type,
        .sentinel = sentinel,
    });
    return rvalue(gz, ri, result, node);
}

const Scratch = struct {
    astgen: *AstGen,
    scratch_top: u32,
    fn init(astgen: *AstGen) Scratch {
        return .{
            .astgen = astgen,
            .scratch_top = @intCast(astgen.scratch.items.len),
        };
    }
    fn reset(s: *Scratch) void {
        s.astgen.scratch.shrinkRetainingCapacity(s.scratch_top);
        s.* = undefined;
    }
    fn addSlice(s: *Scratch, len: u32) Allocator.Error!Slice {
        const start: u32 = @intCast(s.astgen.scratch.items.len);
        try s.astgen.scratch.resize(s.astgen.gpa, start + len);
        return .{ .start = start, .len = len };
    }
    fn addOptionalSlice(s: *Scratch, present: bool, len: u32) Allocator.Error!?Slice {
        if (!present) return null;
        return try addSlice(s, len);
    }
    fn appendBodyWithFixups(s: *Scratch, body: []const Zir.Inst.Index) Allocator.Error!u32 {
        const len = countBodyLenAfterFixups(s.astgen, body);
        try s.astgen.scratch.ensureUnusedCapacity(s.astgen.gpa, len);
        appendBodyWithFixupsArrayList(s.astgen, &s.astgen.scratch, body);
        return len;
    }
    /// 返回包含添加到此 `Scratch` 的全部数据的切片。
    fn all(s: *Scratch) Slice {
        const len = s.astgen.scratch.items.len - s.scratch_top;
        return .{ .start = s.scratch_top, .len = @intCast(len) };
    }
    const Slice = struct {
        start: u32,
        len: u32,
        fn get(s: Slice, astgen: *AstGen) []u32 {
            return astgen.scratch.items[s.start..][0..s.len];
        }
    };
};

const WipDecls = struct {
    astgen: *AstGen,
    slice: Scratch.Slice,
    index: u32,

    fn init(scratch: *Scratch, decls_len: u32) Allocator.Error!WipDecls {
        return .{
            .astgen = scratch.astgen,
            .slice = try scratch.addSlice(decls_len),
            .index = 0,
        };
    }
    fn finish(wip: *WipDecls) void {
        assert(wip.index == wip.slice.len);
        wip.* = undefined;
    }
    fn nextDecl(wip: *WipDecls, decl_inst: Zir.Inst.Index) void {
        wip.slice.get(wip.astgen)[wip.index] = @backingInt(decl_inst);
        wip.index += 1;
    }
};

fn fnDecl(
    astgen: *AstGen,
    gz: *GenZir,
    scope: *Scope,
    wip_decls: *WipDecls,
    decl_node: Ast.Node.Index,
    body_node: Ast.Node.OptionalIndex,
    fn_proto: Ast.full.FnProto,
) InnerError!void {
    const tree = astgen.tree;

    const old_hasher = astgen.src_hasher;
    defer astgen.src_hasher = old_hasher;
    astgen.src_hasher = std.zig.SrcHasher.init(.{});
    // 暂不添加完整源码,因为还需要原型哈希!
    // 源码切片会在此函数*末尾*附近添加。
    astgen.src_hasher.update(std.mem.asBytes(&astgen.source_column));

    // scanContainer() 中已检查缺少函数名称的情况
    const fn_name_token = fn_proto.name_token.?;

    // 将其插入开头,使其指令索引标记
    // 顶层声明的起始位置。
    const decl_inst = try gz.makeDeclaration(fn_proto.ast.proto_node);
    astgen.advanceSourceCursorToNode(decl_node);

    const saved_cursor = astgen.saveSourceCursor();

    const decl_column = astgen.source_column;

    // 现在设置此项,因为参数类型、返回类型等可能是泛型。
    const prev_within_fn = astgen.within_fn;
    defer astgen.within_fn = prev_within_fn;
    astgen.within_fn = true;

    const is_pub = fn_proto.visib_token != null;
    const is_export = blk: {
        const maybe_export_token = fn_proto.extern_export_inline_token orelse break :blk false;
        break :blk tree.tokenTag(maybe_export_token) == .keyword_export;
    };
    const is_extern = blk: {
        const maybe_extern_token = fn_proto.extern_export_inline_token orelse break :blk false;
        break :blk tree.tokenTag(maybe_extern_token) == .keyword_extern;
    };
    const has_inline_keyword = blk: {
        const maybe_inline_token = fn_proto.extern_export_inline_token orelse break :blk false;
        break :blk tree.tokenTag(maybe_inline_token) == .keyword_inline;
    };
    const lib_name = if (fn_proto.lib_name) |lib_name_token| blk: {
        const lib_name_str = try astgen.strLitAsString(lib_name_token);
        const lib_name_slice = astgen.string_bytes.items[@backingInt(lib_name_str.index)..][0..lib_name_str.len];
        if (mem.findScalar(u8, lib_name_slice, 0) != null) {
            return astgen.failTok(lib_name_token, "library name cannot contain null bytes", .{});
        } else if (lib_name_str.len == 0) {
            return astgen.failTok(lib_name_token, "library name cannot be empty", .{});
        }
        break :blk lib_name_str.index;
    } else .empty;
    if (fn_proto.ast.callconv_expr != .none and has_inline_keyword) {
        return astgen.failNode(
            fn_proto.ast.callconv_expr.unwrap().?,
            "explicit callconv incompatible with inline keyword",
            .{},
        );
    }

    const return_type = fn_proto.ast.return_type.unwrap().?;
    const maybe_bang = tree.firstToken(return_type) - 1;
    const is_inferred_error = tree.tokenTag(maybe_bang) == .bang;
    if (body_node == .none) {
        if (!is_extern) {
            return astgen.failTok(fn_proto.ast.fn_token, "non-extern function has no body", .{});
        }
        if (is_inferred_error) {
            return astgen.failTok(maybe_bang, "function prototype may not have inferred error set", .{});
        }
    } else {
        assert(!is_extern); // 由解析器验证(TODO: 为什么?)
    }

    wip_decls.nextDecl(decl_inst);

    var type_gz: GenZir = .{
        .is_comptime = true,
        .src_baseline = fn_proto.ast.proto_node,
        .decl_line = astgen.source_line,
        .parent = scope,
        .astgen = astgen,
        .instructions = gz.instructions,
        .instructions_top = gz.instructions.items.len,
    };
    defer type_gz.unstack();

    if (is_extern) {
        // 包含的是函数*类型*,而非函数值。
        const type_inst = try fnProtoExprInner(&type_gz, &type_gz.base, .{ .rl = .none }, decl_node, fn_proto, true);
        _ = try type_gz.addBreakWithSrcNode(.break_inline, decl_inst, type_inst, decl_node);
        astgen.restoreSourceCursor(saved_cursor);
    }

    var align_gz = type_gz.makeSubBlock(scope);
    defer align_gz.unstack();

    if (fn_proto.ast.align_expr.unwrap()) |align_expr| {
        const inst = try expr(&align_gz, &align_gz.base, coerced_align_ri, align_expr);
        _ = try align_gz.addBreakWithSrcNode(.break_inline, decl_inst, inst, decl_node);
    }

    var addrspace_gz = align_gz.makeSubBlock(scope);
    defer addrspace_gz.unstack();

    if (fn_proto.ast.addrspace_expr.unwrap()) |addrspace_expr| {
        const addrspace_ty = try addrspace_gz.addStdLangValue(addrspace_expr, .address_space);
        const inst = try expr(&addrspace_gz, &addrspace_gz.base, .{ .rl = .{ .coerced_ty = addrspace_ty } }, addrspace_expr);
        _ = try addrspace_gz.addBreakWithSrcNode(.break_inline, decl_inst, inst, decl_node);
    }

    var linksection_gz = addrspace_gz.makeSubBlock(scope);
    defer linksection_gz.unstack();

    if (fn_proto.ast.section_expr.unwrap()) |section_expr| {
        const inst = try expr(&linksection_gz, &linksection_gz.base, coerced_linksection_ri, section_expr);
        _ = try linksection_gz.addBreakWithSrcNode(.break_inline, decl_inst, inst, decl_node);
    }

    var value_gz = linksection_gz.makeSubBlock(scope);
    defer value_gz.unstack();

    if (!is_extern) {
        // 包含的是函数*值*,而不是类型。
        astgen.restoreSourceCursor(saved_cursor);
        try astgen.fnDeclInner(&value_gz, &value_gz.base, decl_inst, decl_node, body_node.unwrap().?, fn_proto);
    }

    // *现在*可以将完整源码纳入哈希计算。
    astgen.src_hasher.update(tree.getNodeSource(decl_node));

    var hash: std.zig.SrcHash = undefined;
    astgen.src_hasher.final(&hash);
    try setDeclaration(decl_inst, .{
        .src_hash = hash,
        .src_line = type_gz.decl_line,
        .src_column = decl_column,

        .kind = .@"const",
        .name = try astgen.identAsString(fn_name_token),
        .is_pub = is_pub,
        .is_threadlocal = false,
        .linkage = if (is_extern) .@"extern" else if (is_export) .@"export" else .normal,
        .lib_name = lib_name,

        .type_gz = &type_gz,
        .align_gz = &align_gz,
        .addrspace_gz = &addrspace_gz,
        .linksection_gz = &linksection_gz,
        .value_gz = &value_gz,
    });
}

fn fnDeclInner(
    astgen: *AstGen,
    decl_gz: *GenZir,
    scope: *Scope,
    decl_inst: Zir.Inst.Index,
    decl_node: Ast.Node.Index,
    body_node: Ast.Node.Index,
    fn_proto: Ast.full.FnProto,
) InnerError!void {
    const tree = astgen.tree;

    const is_noinline = blk: {
        const maybe_noinline_token = fn_proto.extern_export_inline_token orelse break :blk false;
        break :blk tree.tokenTag(maybe_noinline_token) == .keyword_noinline;
    };
    const has_inline_keyword = blk: {
        const maybe_inline_token = fn_proto.extern_export_inline_token orelse break :blk false;
        break :blk tree.tokenTag(maybe_inline_token) == .keyword_inline;
    };

    const return_type = fn_proto.ast.return_type.unwrap().?;
    const maybe_bang = tree.firstToken(return_type) - 1;
    const is_inferred_error = tree.tokenTag(maybe_bang) == .bang;

    // 注意,此处的容量可能不足,因为其中不包括 `anytype` 参数。
    var param_insts: std.ArrayList(Zir.Inst.Index) = try .initCapacity(astgen.arena, fn_proto.ast.params.len);

    // 将此值用作 `is_used_or_discarded`,以确定参数或返回类型是否为泛型。
    var any_param_used = false;

    var noalias_bits: u32 = 0;
    var params_scope = scope;
    const is_var_args = is_var_args: {
        var param_type_i: usize = 0;
        var it = fn_proto.iterate(tree);
        while (it.next()) |param| : (param_type_i += 1) {
            const is_comptime = if (param.comptime_noalias) |token| switch (tree.tokenTag(token)) {
                .keyword_noalias => is_comptime: {
                    noalias_bits |= @as(u32, 1) << (std.math.cast(u5, param_type_i) orelse
                        return astgen.failTok(token, "this compiler implementation only supports 'noalias' on the first 32 parameters", .{}));
                    break :is_comptime false;
                },
                .keyword_comptime => true,
                else => false,
            } else false;

            const is_anytype = if (param.anytype_ellipsis3) |token| blk: {
                switch (tree.tokenTag(token)) {
                    .keyword_anytype => break :blk true,
                    .ellipsis3 => break :is_var_args true,
                    else => unreachable,
                }
            } else false;

            const param_name: Zir.NullTerminatedString = if (param.name_token) |name_token| blk: {
                const name_bytes = tree.tokenSlice(name_token);
                if (mem.eql(u8, "_", name_bytes))
                    break :blk .empty;

                const param_name = try astgen.identAsString(name_token);
                try astgen.detectLocalShadowing(params_scope, param_name, name_token, name_bytes, .@"function parameter");
                break :blk param_name;
            } else {
                if (param.anytype_ellipsis3) |tok| {
                    return astgen.failTok(tok, "missing parameter name", .{});
                } else {
                    const type_expr = param.type_expr.?;
                    ambiguous: {
                        if (tree.nodeTag(type_expr) != .identifier) break :ambiguous;
                        const main_token = tree.nodeMainToken(type_expr);
                        const identifier_str = tree.tokenSlice(main_token);
                        if (isPrimitive(identifier_str)) break :ambiguous;
                        return astgen.failNodeNotes(
                            type_expr,
                            "missing parameter name or type",
                            .{},
                            &[_]u32{
                                try astgen.errNoteNode(
                                    type_expr,
                                    "if this is a name, annotate its type: '{s}: T'",
                                    .{identifier_str},
                                ),
                                try astgen.errNoteNode(
                                    type_expr,
                                    "if this is a type, give it a name: 'name: {s}'",
                                    .{identifier_str},
                                ),
                            },
                        );
                    }
                    return astgen.failNode(type_expr, "missing parameter name", .{});
                }
            };

            const param_inst = if (is_anytype) param: {
                const name_token = param.name_token orelse param.anytype_ellipsis3.?;
                const tag: Zir.Inst.Tag = if (is_comptime)
                    .param_anytype_comptime
                else
                    .param_anytype;
                break :param try decl_gz.addStrTok(tag, param_name, name_token);
            } else param: {
                const param_type_node = param.type_expr.?;
                any_param_used = false; // 稍后检查此项
                var param_gz = decl_gz.makeSubBlock(scope);
                defer param_gz.unstack();
                const param_type = try fullBodyExpr(&param_gz, params_scope, coerced_type_ri, param_type_node, .normal);
                const param_inst_expected: Zir.Inst.Index = @fromBackingInt(@intCast(astgen.instructions.len + 1));
                _ = try param_gz.addBreakWithSrcNode(.break_inline, param_inst_expected, param_type, param_type_node);
                const param_type_is_generic = any_param_used;

                const name_token = param.name_token orelse tree.nodeMainToken(param_type_node);
                const tag: Zir.Inst.Tag = if (is_comptime) .param_comptime else .param;
                const param_inst = try decl_gz.addParam(&param_gz, param_insts.items, param_type_is_generic, tag, name_token, param_name);
                assert(param_inst_expected == param_inst);
                break :param param_inst.toRef();
            };

            if (param_name == .empty) continue;

            const sub_scope = try astgen.arena.create(Scope.LocalVal);
            sub_scope.* = .{
                .parent = params_scope,
                .gen_zir = decl_gz,
                .name = param_name,
                .inst = param_inst,
                .token_src = param.name_token.?,
                .id_cat = .@"function parameter",
                .is_used_or_discarded = &any_param_used,
            };
            params_scope = &sub_scope.base;
            try param_insts.append(astgen.arena, param_inst.toIndex().?);
        }
        break :is_var_args false;
    };

    // 创建函数 ZIR 指令后,需要更新 cc 和 ret_ty 表达式块
    // 内部的 break 指令,使其以该函数指令
    // 作为要退出的主体。

    var cc_gz = decl_gz.makeSubBlock(scope);
    defer cc_gz.unstack();
    const cc_ref: Zir.Inst.Ref = blk: {
        if (fn_proto.ast.callconv_expr.unwrap()) |callconv_expr| {
            const inst = try expr(
                &cc_gz,
                scope,
                .{ .rl = .{ .coerced_ty = try cc_gz.addStdLangValue(callconv_expr, .calling_convention) } },
                callconv_expr,
            );
            if (cc_gz.instructionsSlice().len == 0) {
                // 此时将发送 len=0 的消息体,以便更高效地编码。
                break :blk inst;
            }
            _ = try cc_gz.addBreak(.break_inline, @fromBackingInt(@intCast(0)), inst);
            break :blk inst;
        } else if (has_inline_keyword) {
            const inst = try cc_gz.addStdLangValue(decl_node, .calling_convention_inline);
            _ = try cc_gz.addBreak(.break_inline, @fromBackingInt(@intCast(0)), inst);
            break :blk inst;
        } else {
            break :blk .none;
        }
    };

    var ret_gz = decl_gz.makeSubBlock(params_scope);
    defer ret_gz.unstack();
    any_param_used = false; // 稍后检查此项
    const ret_ref: Zir.Inst.Ref = inst: {
        // 参数在返回类型中处于作用域内,因此此处使用 `params_scope`。
        // 调用约定中没有参数作用域,因此仅使用 `scope`。
        // 解决此处不一致的提案参见 #22263。
        const inst = try fullBodyExpr(&ret_gz, params_scope, coerced_type_ri, fn_proto.ast.return_type.unwrap().?, .normal);
        if (ret_gz.instructionsSlice().len == 0) {
            // 此时将发送 len=0 的消息体,以便更高效地编码。
            break :inst inst;
        }
        _ = try ret_gz.addBreak(.break_inline, @fromBackingInt(@intCast(0)), inst);
        break :inst inst;
    };
    const ret_body_param_refs = try astgen.fetchRemoveRefEntries(param_insts.items);
    const ret_ty_is_generic = any_param_used;

    var body_gz: GenZir = .{
        .is_comptime = false,
        .src_baseline = fn_proto.ast.proto_node,
        .decl_line = decl_gz.decl_line,
        .parent = params_scope,
        .astgen = astgen,
        .instructions = decl_gz.instructions,
        .instructions_top = decl_gz.instructions.items.len,
    };
    defer body_gz.unstack();

    // 作用域栈如下:
    //  body_gz(顶部)
    //  param2
    //  param1
    //  param0
    //  decl_gz(底部)

    // 构造原型哈希。
    // 保持 `astgen.src_hasher` 不变;它将用于哈希
    // 整个函数声明,包括函数主体。
    var proto_hasher = astgen.src_hasher;
    const proto_node = tree.nodeData(decl_node).node_and_node[0];
    proto_hasher.update(tree.getNodeSource(proto_node));
    var proto_hash: std.zig.SrcHash = undefined;
    proto_hasher.final(&proto_hash);

    const prev_fn_block = astgen.fn_block;
    const prev_fn_ret_ty = astgen.fn_ret_ty;
    defer {
        astgen.fn_block = prev_fn_block;
        astgen.fn_ret_ty = prev_fn_ret_ty;
    }
    astgen.fn_block = &body_gz;
    astgen.fn_ret_ty = if (is_inferred_error or ret_ref.toIndex() != null) r: {
        // 几乎可以确定迟早需要返回类型,因为它很可能既不是 `void`,也不是 `noreturn`,
        // 因此可能会有需要 RLS 的显式 return。现在先获取此
        // 返回类型,以便函数其余部分使用。
        //
        break :r try body_gz.addNode(.ret_type, decl_node);
    } else ret_ref;

    const prev_var_args = astgen.fn_var_args;
    astgen.fn_var_args = is_var_args;
    defer astgen.fn_var_args = prev_var_args;

    astgen.advanceSourceCursorToNode(body_node);
    const lbrace_line = astgen.source_line - decl_gz.decl_line;
    const lbrace_column = astgen.source_column;

    _ = try fullBodyExpr(&body_gz, &body_gz.base, .{ .rl = .none }, body_node, .allow_branch_hint);
    try checkUsed(decl_gz, scope, params_scope);

    if (!body_gz.endsWithNoReturn()) {
        // 作为返回前最后一个操作,必要时“弹出”错误跟踪
        _ = try body_gz.addRestoreErrRetIndex(.ret, .always, decl_node);

        // 在函数末尾添加隐式返回。
        _ = try body_gz.addUnTok(.ret_implicit, .void_value, tree.lastToken(body_node));
    }

    const func_inst = try decl_gz.addFunc(.{
        .src_node = decl_node,
        .cc_ref = cc_ref,
        .cc_gz = &cc_gz,
        .ret_ref = ret_ref,
        .ret_gz = &ret_gz,
        .ret_param_refs = ret_body_param_refs,
        .ret_ty_is_generic = ret_ty_is_generic,
        .lbrace_line = lbrace_line,
        .lbrace_column = lbrace_column,
        .param_block = decl_inst,
        .param_insts = param_insts.items,
        .body_gz = &body_gz,
        .is_var_args = is_var_args,
        .is_inferred_error = is_inferred_error,
        .is_noinline = is_noinline,
        .noalias_bits = noalias_bits,
        .proto_hash = proto_hash,
    });
    _ = try decl_gz.addBreakWithSrcNode(.break_inline, decl_inst, func_inst, decl_node);
}

fn globalVarDecl(
    astgen: *AstGen,
    gz: *GenZir,
    scope: *Scope,
    wip_decls: *WipDecls,
    node: Ast.Node.Index,
    var_decl: Ast.full.VarDecl,
) InnerError!void {
    const tree = astgen.tree;

    const old_hasher = astgen.src_hasher;
    defer astgen.src_hasher = old_hasher;
    astgen.src_hasher = std.zig.SrcHasher.init(.{});
    astgen.src_hasher.update(tree.getNodeSource(node));
    astgen.src_hasher.update(std.mem.asBytes(&astgen.source_column));

    const is_mutable = tree.tokenTag(var_decl.ast.mut_token) == .keyword_var;
    const name_token = var_decl.ast.mut_token + 1;
    const is_pub = var_decl.visib_token != null;
    const is_export = blk: {
        const maybe_export_token = var_decl.extern_export_token orelse break :blk false;
        break :blk tree.tokenTag(maybe_export_token) == .keyword_export;
    };
    const is_extern = blk: {
        const maybe_extern_token = var_decl.extern_export_token orelse break :blk false;
        break :blk tree.tokenTag(maybe_extern_token) == .keyword_extern;
    };
    const is_threadlocal = if (var_decl.threadlocal_token) |tok| blk: {
        if (!is_mutable) {
            return astgen.failTok(tok, "threadlocal variable cannot be constant", .{});
        }
        break :blk true;
    } else false;
    const lib_name = if (var_decl.lib_name) |lib_name_token| blk: {
        const lib_name_str = try astgen.strLitAsString(lib_name_token);
        const lib_name_slice = astgen.string_bytes.items[@backingInt(lib_name_str.index)..][0..lib_name_str.len];
        if (mem.findScalar(u8, lib_name_slice, 0) != null) {
            return astgen.failTok(lib_name_token, "library name cannot contain null bytes", .{});
        } else if (lib_name_str.len == 0) {
            return astgen.failTok(lib_name_token, "library name cannot be empty", .{});
        }
        break :blk lib_name_str.index;
    } else .empty;

    astgen.advanceSourceCursorToNode(node);

    const decl_column = astgen.source_column;

    const decl_inst = try gz.makeDeclaration(node);
    wip_decls.nextDecl(decl_inst);

    if (var_decl.ast.init_node.unwrap()) |init_node| {
        if (is_extern) {
            return astgen.failNode(
                init_node,
                "extern variables have no initializers",
                .{},
            );
        }
    } else {
        if (!is_extern) {
            return astgen.failNode(node, "variables must be initialized", .{});
        }
    }

    if (is_extern and var_decl.ast.type_node == .none) {
        return astgen.failNode(node, "unable to infer variable type", .{});
    }

    assert(var_decl.comptime_token == null); // 由解析器处理

    var type_gz: GenZir = .{
        .parent = scope,
        .src_baseline = node,
        .decl_line = astgen.source_line,
        .astgen = astgen,
        .is_comptime = true,
        .instructions = gz.instructions,
        .instructions_top = gz.instructions.items.len,
    };
    defer type_gz.unstack();

    if (var_decl.ast.type_node.unwrap()) |type_node| {
        const type_inst = try expr(&type_gz, &type_gz.base, coerced_type_ri, type_node);
        _ = try type_gz.addBreakWithSrcNode(.break_inline, decl_inst, type_inst, node);
    }

    var align_gz = type_gz.makeSubBlock(scope);
    defer align_gz.unstack();

    if (var_decl.ast.align_node.unwrap()) |align_node| {
        const align_inst = try expr(&align_gz, &align_gz.base, coerced_align_ri, align_node);
        _ = try align_gz.addBreakWithSrcNode(.break_inline, decl_inst, align_inst, node);
    }

    var addrspace_gz = type_gz.makeSubBlock(scope);
    defer addrspace_gz.unstack();

    if (var_decl.ast.addrspace_node.unwrap()) |addrspace_node| {
        const addrspace_ty = try addrspace_gz.addStdLangValue(addrspace_node, .address_space);
        const addrspace_inst = try expr(&addrspace_gz, &addrspace_gz.base, .{ .rl = .{ .coerced_ty = addrspace_ty } }, addrspace_node);
        _ = try addrspace_gz.addBreakWithSrcNode(.break_inline, decl_inst, addrspace_inst, node);
    }

    var linksection_gz = type_gz.makeSubBlock(scope);
    defer linksection_gz.unstack();

    if (var_decl.ast.section_node.unwrap()) |section_node| {
        const linksection_inst = try expr(&linksection_gz, &linksection_gz.base, coerced_linksection_ri, section_node);
        _ = try linksection_gz.addBreakWithSrcNode(.break_inline, decl_inst, linksection_inst, node);
    }

    var init_gz = type_gz.makeSubBlock(scope);
    defer init_gz.unstack();

    if (var_decl.ast.init_node.unwrap()) |init_node| {
        const init_ri: ResultInfo = if (var_decl.ast.type_node != .none) .{
            .rl = .{ .coerced_ty = decl_inst.toRef() },
        } else .{ .rl = .none };
        const init_inst: Zir.Inst.Ref = try nameStratExpr(&init_gz, &init_gz.base, init_ri, init_node, .parent) orelse init: {
            break :init try expr(&init_gz, &init_gz.base, init_ri, init_node);
        };
        _ = try init_gz.addBreakWithSrcNode(.break_inline, decl_inst, init_inst, node);
    }

    var hash: std.zig.SrcHash = undefined;
    astgen.src_hasher.final(&hash);
    try setDeclaration(decl_inst, .{
        .src_hash = hash,
        .src_line = type_gz.decl_line,
        .src_column = decl_column,

        .kind = if (is_mutable) .@"var" else .@"const",
        .name = try astgen.identAsString(name_token),
        .is_pub = is_pub,
        .is_threadlocal = is_threadlocal,
        .linkage = if (is_extern) .@"extern" else if (is_export) .@"export" else .normal,
        .lib_name = lib_name,

        .type_gz = &type_gz,
        .align_gz = &align_gz,
        .addrspace_gz = &addrspace_gz,
        .linksection_gz = &linksection_gz,
        .value_gz = &init_gz,
    });
}

fn comptimeDecl(
    astgen: *AstGen,
    gz: *GenZir,
    scope: *Scope,
    wip_decls: *WipDecls,
    node: Ast.Node.Index,
) InnerError!void {
    const tree = astgen.tree;
    const body_node = tree.nodeData(node).node;

    const old_hasher = astgen.src_hasher;
    defer astgen.src_hasher = old_hasher;
    astgen.src_hasher = std.zig.SrcHasher.init(.{});
    astgen.src_hasher.update(tree.getNodeSource(node));
    astgen.src_hasher.update(std.mem.asBytes(&astgen.source_column));

    // 放在最前面,使 ZIR 指令索引标记此
    // 顶层声明的范围起点。
    const decl_inst = try gz.makeDeclaration(node);
    wip_decls.nextDecl(decl_inst);
    astgen.advanceSourceCursorToNode(node);

    // 仅 `setDeclaration` 调用需要此项。
    var dummy_gz = gz.makeSubBlock(scope);
    defer dummy_gz.unstack();

    var comptime_gz: GenZir = .{
        .is_comptime = true,
        .src_baseline = node,
        .decl_line = astgen.source_line,
        .parent = scope,
        .astgen = astgen,
        .instructions = dummy_gz.instructions,
        .instructions_top = dummy_gz.instructions.items.len,
    };
    defer comptime_gz.unstack();

    const decl_column = astgen.source_column;

    const block_result = try fullBodyExpr(&comptime_gz, &comptime_gz.base, .{ .rl = .none }, body_node, .normal);
    if (comptime_gz.isEmpty() or !comptime_gz.refIsNoReturn(block_result)) {
        _ = try comptime_gz.addBreak(.break_inline, decl_inst, .void_value);
    }

    var hash: std.zig.SrcHash = undefined;
    astgen.src_hasher.final(&hash);
    try setDeclaration(decl_inst, .{
        .src_hash = hash,
        .src_line = comptime_gz.decl_line,
        .src_column = decl_column,
        .kind = .@"comptime",
        .name = .empty,
        .is_pub = false,
        .is_threadlocal = false,
        .linkage = .normal,
        .type_gz = &dummy_gz,
        .align_gz = &dummy_gz,
        .addrspace_gz = &dummy_gz,
        .linksection_gz = &dummy_gz,
        .value_gz = &comptime_gz,
    });
}

fn testDecl(
    astgen: *AstGen,
    gz: *GenZir,
    scope: *Scope,
    wip_decls: *WipDecls,
    node: Ast.Node.Index,
) InnerError!void {
    const tree = astgen.tree;
    _, const body_node = tree.nodeData(node).opt_token_and_node;

    const old_hasher = astgen.src_hasher;
    defer astgen.src_hasher = old_hasher;
    astgen.src_hasher = std.zig.SrcHasher.init(.{});
    astgen.src_hasher.update(tree.getNodeSource(node));
    astgen.src_hasher.update(std.mem.asBytes(&astgen.source_column));

    // 放在最前面,使 ZIR 指令索引标记此
    // 顶层声明的范围起点。
    const decl_inst = try gz.makeDeclaration(node);

    wip_decls.nextDecl(decl_inst);
    astgen.advanceSourceCursorToNode(node);

    // 仅 `setDeclaration` 调用需要此项。
    var dummy_gz: GenZir = gz.makeSubBlock(scope);
    defer dummy_gz.unstack();

    var decl_block: GenZir = .{
        .is_comptime = true,
        .src_baseline = node,
        .decl_line = astgen.source_line,
        .parent = scope,
        .astgen = astgen,
        .instructions = dummy_gz.instructions,
        .instructions_top = dummy_gz.instructions.items.len,
    };
    defer decl_block.unstack();

    const decl_column = astgen.source_column;

    const test_token = tree.nodeMainToken(node);

    const test_name_token = test_token + 1;
    const test_name: Zir.NullTerminatedString = switch (tree.tokenTag(test_name_token)) {
        else => .empty,
        .string_literal => name: {
            const name = try astgen.strLitAsString(test_name_token);
            const slice = astgen.string_bytes.items[@backingInt(name.index)..][0..name.len];
            if (mem.findScalar(u8, slice, 0) != null) {
                return astgen.failTok(test_name_token, "test name cannot contain null bytes", .{});
            } else if (slice.len == 0) {
                return astgen.failTok(test_name_token, "empty test name must be omitted", .{});
            }
            break :name name.index;
        },
        .identifier => name: {
            const ident_name_raw = tree.tokenSlice(test_name_token);

            if (mem.eql(u8, ident_name_raw, "_")) return astgen.failTok(test_name_token, "'_' used as an identifier without @\"_\" syntax", .{});

            // 若非 @"" 语法,直接使用原始词法标记切片
            if (ident_name_raw[0] != '@') {
                if (isPrimitive(ident_name_raw)) return astgen.failTok(test_name_token, "cannot test a primitive", .{});
            }

            // 局部变量,包括函数参数。
            const name_str_index = try astgen.identAsString(test_name_token);
            var found_already: ?Ast.Node.Index = null; // 已找到同名声明
            var num_namespaces_out: u32 = 0;
            var capturing_namespace: ?*Scope.Namespace = null;
            find_scope: switch (scope.unwrap()) {
                .local_val => |local_val| {
                    if (local_val.name == name_str_index) {
                        local_val.used = .fromToken(test_name_token);
                        return astgen.failTokNotes(test_name_token, "cannot test a {s}", .{
                            @tagName(local_val.id_cat),
                        }, &[_]u32{
                            try astgen.errNoteTok(local_val.token_src, "{s} declared here", .{
                                @tagName(local_val.id_cat),
                            }),
                        });
                    }
                    continue :find_scope local_val.parent.unwrap();
                },
                .local_ptr => |local_ptr| {
                    if (local_ptr.name == name_str_index) {
                        local_ptr.used = .fromToken(test_name_token);
                        return astgen.failTokNotes(test_name_token, "cannot test a {s}", .{
                            @tagName(local_ptr.id_cat),
                        }, &[_]u32{
                            try astgen.errNoteTok(local_ptr.token_src, "{s} declared here", .{
                                @tagName(local_ptr.id_cat),
                            }),
                        });
                    }
                    continue :find_scope local_ptr.parent.unwrap();
                },
                .gen_zir => |gen_zir| continue :find_scope gen_zir.parent.unwrap(),
                .defer_normal, .defer_error => |defer_scope| continue :find_scope defer_scope.parent.unwrap(),
                .namespace => |ns| {
                    if (ns.decls.get(name_str_index)) |i| {
                        if (found_already) |f| {
                            return astgen.failTokNotes(test_name_token, "ambiguous reference", .{}, &.{
                                try astgen.errNoteNode(f, "declared here", .{}),
                                try astgen.errNoteNode(i, "also declared here", .{}),
                            });
                        }
                        // 已找到匹配项,但必须继续查找对声明的歧义引用。
                        found_already = i;
                    }
                    num_namespaces_out += 1;
                    capturing_namespace = ns;
                    continue :find_scope ns.parent.unwrap();
                },
                .top => break :find_scope,
            }
            if (found_already == null) {
                const ident_name = try astgen.identifierTokenString(test_name_token);
                return astgen.failTok(test_name_token, "use of undeclared identifier '{s}'", .{ident_name});
            }

            break :name try astgen.identAsString(test_name_token);
        },
    };

    var fn_block: GenZir = .{
        .is_comptime = false,
        .src_baseline = node,
        .decl_line = decl_block.decl_line,
        .parent = &decl_block.base,
        .astgen = astgen,
        .instructions = decl_block.instructions,
        .instructions_top = decl_block.instructions.items.len,
    };
    defer fn_block.unstack();

    const prev_within_fn = astgen.within_fn;
    const prev_fn_block = astgen.fn_block;
    const prev_fn_ret_ty = astgen.fn_ret_ty;
    astgen.within_fn = true;
    astgen.fn_block = &fn_block;
    astgen.fn_ret_ty = .anyerror_void_error_union_type;
    defer {
        astgen.within_fn = prev_within_fn;
        astgen.fn_block = prev_fn_block;
        astgen.fn_ret_ty = prev_fn_ret_ty;
    }

    astgen.advanceSourceCursorToNode(body_node);
    const lbrace_line = astgen.source_line - decl_block.decl_line;
    const lbrace_column = astgen.source_column;

    const block_result = try fullBodyExpr(&fn_block, &fn_block.base, .{ .rl = .none }, body_node, .normal);
    if (fn_block.isEmpty() or !fn_block.refIsNoReturn(block_result)) {

        // 作为返回前最后一个操作,必要时“弹出”错误跟踪
        _ = try fn_block.addRestoreErrRetIndex(.ret, .always, node);

        // 在函数末尾添加隐式返回。
        _ = try fn_block.addUnTok(.ret_implicit, .void_value, tree.lastToken(body_node));
    }

    const func_inst = try decl_block.addFunc(.{
        .src_node = node,

        .cc_ref = .none,
        .cc_gz = null,
        .ret_ref = .anyerror_void_error_union_type,
        .ret_gz = null,

        .ret_param_refs = &.{},
        .param_insts = &.{},
        .ret_ty_is_generic = false,

        .lbrace_line = lbrace_line,
        .lbrace_column = lbrace_column,
        .param_block = decl_inst,
        .body_gz = &fn_block,
        .is_var_args = false,
        .is_inferred_error = false,
        .is_noinline = false,
        .noalias_bits = 0,

        // 测试无需进行原型哈希
        .proto_hash = @splat(0),
    });

    _ = try decl_block.addBreak(.break_inline, decl_inst, func_inst);

    var hash: std.zig.SrcHash = undefined;
    astgen.src_hasher.final(&hash);
    try setDeclaration(decl_inst, .{
        .src_hash = hash,
        .src_line = decl_block.decl_line,
        .src_column = decl_column,

        .kind = switch (tree.tokenTag(test_name_token)) {
            .string_literal => .@"test",
            .identifier => .decltest,
            else => .unnamed_test,
        },
        .name = test_name,
        .is_pub = false,
        .is_threadlocal = false,
        .linkage = .normal,

        .type_gz = &dummy_gz,
        .align_gz = &dummy_gz,
        .linksection_gz = &dummy_gz,
        .addrspace_gz = &dummy_gz,
        .value_gz = &decl_block,
    });
}

fn structDeclInner(
    gz: *GenZir,
    scope: *Scope,
    node: Ast.Node.Index,
    container_decl: Ast.full.ContainerDecl,
    layout: std.lang.Type.ContainerLayout,
    maybe_backing_int_node: Ast.Node.OptionalIndex,
    name_strat: Zir.Inst.NameStrategy,
) InnerError!Zir.Inst.Ref {
    const astgen = gz.astgen;
    const gpa = astgen.gpa;
    const tree = astgen.tree;

    is_tuple: {
        const tuple_field_node = for (container_decl.ast.members) |member_node| {
            const container_field = tree.fullContainerField(member_node) orelse continue;
            if (container_field.ast.tuple_like) break member_node;
        } else break :is_tuple;

        if (node == .root) {
            return astgen.failNode(tuple_field_node, "file cannot be a tuple", .{});
        } else {
            return tupleDecl(gz, scope, node, container_decl, layout, maybe_backing_int_node);
        }
    }

    astgen.advanceSourceCursorToNode(node);

    const decl_inst = try gz.reserveInstructionIndex();
    const src_line = astgen.source_line;
    const src_column = astgen.source_column;

    if (container_decl.ast.members.len == 0 and maybe_backing_int_node == .none) {
        try gz.setStruct(decl_inst, .{
            .src_line = src_line,
            .src_column = src_column,
            .src_node = node,
            .name_strat = name_strat,
            .arg_baseline_src_node = .none,
            .fields_baseline_src_node = .none,
            .layout = layout,
            .backing_int_type_body_len = null,
            .decls_len = 0,
            .fields_len = 0,
            .any_field_aligns = false,
            .any_field_defaults = false,
            .any_comptime_fields = false,
            .fields_hash = @splat(0),
            .captures = &.{},
            .capture_names = &.{},
            .remaining = &.{},
        });
        return decl_inst.toRef();
    }

    var namespace: Scope.Namespace = .{
        .parent = scope,
        .node = node,
        .inst = decl_inst,
        .declaring_gz = gz,
        .maybe_generic = astgen.within_fn,
    };
    defer namespace.deinit(gpa);

    // struct_decl 指令引入一个作用域,其中可见该结构体的声明,
    // 以便字段类型、对齐及默认值表达式
    // 能够引用结构体自身内部的声明。
    var block_scope: GenZir = .{
        .parent = &namespace.base,
        .src_baseline = node,
        .decl_line = gz.decl_line,
        .astgen = astgen,
        .is_comptime = true,
        .instructions = gz.instructions,
        .instructions_top = gz.instructions.items.len,
    };
    defer block_scope.unstack();

    const scan_result = try astgen.scanContainer(&namespace, container_decl.ast.members, .@"struct");

    var scratch: Scratch = .init(astgen);
    defer scratch.reset();

    // 在 `scratch` 中复现 ZIR 尾随数据的结构
    var wip_decls: WipDecls = try .init(&scratch, scan_result.decls_len);
    const field_names = try scratch.addSlice(scan_result.fields_len);
    const field_type_body_lens = try scratch.addSlice(scan_result.fields_len);
    const field_align_body_lens = try scratch.addOptionalSlice(scan_result.any_field_aligns, scan_result.fields_len);
    const field_default_body_lens = try scratch.addOptionalSlice(scan_result.any_field_values, scan_result.fields_len);
    const field_comptime_bits = try scratch.addOptionalSlice(
        scan_result.any_comptime_fields,
        @divCeil(scan_result.fields_len, 32),
    );
    if (field_comptime_bits) |bits| @memset(bits.get(astgen), 0);

    const old_hasher = astgen.src_hasher;
    defer astgen.src_hasher = old_hasher;
    astgen.src_hasher = .init(.{});

    // 若指定了底层整数类型,它位于所有字段主体之前。
    const backing_int_type_body_len: ?u32 = if (maybe_backing_int_node.unwrap()) |backing_int_node| len: {
        block_scope.src_baseline = backing_int_node;
        defer block_scope.src_baseline = node;
        if (layout != .@"packed") return astgen.failNode(
            backing_int_node,
            "non-packed struct does not support backing integer type",
            .{},
        );
        astgen.src_hasher.update(astgen.tree.getNodeSource(backing_int_node));
        const type_ref = try typeExpr(&block_scope, &namespace.base, backing_int_node);
        if (!block_scope.endsWithNoReturn()) {
            _ = try block_scope.addBreak(.break_inline, decl_inst, type_ref);
        }
        const body_len = try scratch.appendBodyWithFixups(block_scope.instructionsSlice());
        block_scope.instructions.items.len = block_scope.instructions_top;
        break :len body_len;
    } else null;

    var fields_src_baseline: Ast.Node.OptionalIndex = .none;
    var next_field_idx: u32 = 0;
    for (container_decl.ast.members) |member_node| {
        var member = switch (try containerMember(&block_scope, &namespace.base, &wip_decls, member_node)) {
            .decl => continue,
            .field => |field| field,
        };
        const field_idx = next_field_idx;
        next_field_idx += 1;

        if (field_idx == 0) {
            assert(fields_src_baseline == .none);
            fields_src_baseline = member_node.toOptional();
        }
        block_scope.src_baseline = fields_src_baseline.unwrap().?;
        defer block_scope.src_baseline = node;

        astgen.src_hasher.update(tree.getNodeSource(member_node));

        member.convertToNonTupleLike(astgen.tree);
        assert(!member.ast.tuple_like);

        field_names.get(astgen)[field_idx] = @backingInt(try astgen.identAsString(member.ast.main_token));

        {
            const type_node = member.ast.type_expr.unwrap() orelse {
                return astgen.failTok(member.ast.main_token, "struct field missing type", .{});
            };
            const type_ref = try typeExpr(&block_scope, &namespace.base, type_node);
            if (!block_scope.endsWithNoReturn()) {
                _ = try block_scope.addBreak(.break_inline, decl_inst, type_ref);
            }
            const body_len = try scratch.appendBodyWithFixups(block_scope.instructionsSlice());
            field_type_body_lens.get(astgen)[field_idx] = body_len;
            block_scope.instructions.items.len = block_scope.instructions_top;
        }

        if (member.ast.align_expr.unwrap()) |align_node| {
            if (layout == .@"packed") {
                return astgen.failNode(align_node, "unable to override alignment of packed struct fields", .{});
            }
            const align_ref = try expr(&block_scope, &namespace.base, coerced_align_ri, align_node);
            if (!block_scope.endsWithNoReturn()) {
                _ = try block_scope.addBreak(.break_inline, decl_inst, align_ref);
            }
            const body_len = try scratch.appendBodyWithFixups(block_scope.instructionsSlice());
            field_align_body_lens.?.get(astgen)[field_idx] = body_len;
            block_scope.instructions.items.len = block_scope.instructions_top;
        } else if (field_align_body_lens) |lens| {
            lens.get(astgen)[field_idx] = 0;
        }

        if (member.ast.value_expr.unwrap()) |default_node| {
            const ri: ResultInfo = .{ .rl = .{ .coerced_ty = decl_inst.toRef() } };
            const default_ref = try expr(&block_scope, &namespace.base, ri, default_node);
            if (!block_scope.endsWithNoReturn()) {
                _ = try block_scope.addBreak(.break_inline, decl_inst, default_ref);
            }
            const body_len = try scratch.appendBodyWithFixups(block_scope.instructionsSlice());
            field_default_body_lens.?.get(astgen)[field_idx] = body_len;
            block_scope.instructions.items.len = block_scope.instructions_top;
        } else if (field_default_body_lens) |lens| {
            lens.get(astgen)[field_idx] = 0;
        }

        if (member.comptime_token) |comptime_token| {
            switch (layout) {
                .@"packed", .@"extern" => return astgen.failTok(comptime_token, "{s} struct fields cannot be marked comptime", .{@tagName(layout)}),
                .auto => {},
            }
            if (member.ast.value_expr == .none) {
                return astgen.failTok(comptime_token, "comptime field without default initialization value", .{});
            }
            const mask = @as(u32, 1) << @intCast(field_idx % 32);
            field_comptime_bits.?.get(astgen)[field_idx / 32] |= mask;
        }
    }
    assert(next_field_idx == scan_result.fields_len);
    wip_decls.finish();

    var fields_hash: std.zig.SrcHash = undefined;
    astgen.src_hasher.final(&fields_hash);

    try gz.setStruct(decl_inst, .{
        .src_line = src_line,
        .src_column = src_column,
        .src_node = node,
        .name_strat = name_strat,
        .arg_baseline_src_node = maybe_backing_int_node,
        .fields_baseline_src_node = fields_src_baseline,
        .layout = layout,
        .backing_int_type_body_len = backing_int_type_body_len,
        .decls_len = scan_result.decls_len,
        .fields_len = scan_result.fields_len,
        .any_field_aligns = scan_result.any_field_aligns,
        .any_field_defaults = scan_result.any_field_values,
        .any_comptime_fields = scan_result.any_comptime_fields,
        .fields_hash = fields_hash,
        .captures = namespace.captures.keys(),
        .capture_names = namespace.captures.values(),
        .remaining = scratch.all().get(astgen),
    });

    block_scope.unstack();
    return decl_inst.toRef();
}

fn tupleDecl(
    gz: *GenZir,
    scope: *Scope,
    node: Ast.Node.Index,
    container_decl: Ast.full.ContainerDecl,
    layout: std.lang.Type.ContainerLayout,
    backing_int_node: Ast.Node.OptionalIndex,
) InnerError!Zir.Inst.Ref {
    const astgen = gz.astgen;
    const gpa = astgen.gpa;
    const tree = astgen.tree;

    switch (layout) {
        .auto => {},
        .@"extern", .@"packed" => return astgen.failNode(node, "{s} tuples are not supported", .{@tagName(layout)}),
    }

    if (backing_int_node.unwrap()) |arg| {
        return astgen.failNode(arg, "tuple does not support backing integer type", .{});
    }

    // 从此处起,使用暂存缓冲区保存字段数据:
    // 1. fields: { // 每个 `fields_len` 对应一个,存储在 `extended.small` 中
    //        type: Inst.Ref,
    //        init: Inst.Ref, // 非 `comptime` 字段为 `.none`
    //    }
    const fields_start = astgen.scratch.items.len;
    defer astgen.scratch.items.len = fields_start;

    try astgen.scratch.ensureUnusedCapacity(gpa, container_decl.ast.members.len * 2);

    for (container_decl.ast.members) |member_node| {
        const field = tree.fullContainerField(member_node) orelse {
            const tuple_member = for (container_decl.ast.members) |maybe_tuple| switch (tree.nodeTag(maybe_tuple)) {
                .container_field_init,
                .container_field_align,
                .container_field,
                => break maybe_tuple,
                else => {},
            } else unreachable;
            return astgen.failNodeNotes(
                member_node,
                "tuple declarations cannot contain declarations",
                .{},
                &.{try astgen.errNoteNode(tuple_member, "tuple field here", .{})},
            );
        };

        if (!field.ast.tuple_like) {
            return astgen.failTok(field.ast.main_token, "tuple field has a name", .{});
        }

        if (field.ast.align_expr != .none) {
            return astgen.failTok(field.ast.main_token, "tuple field has alignment", .{});
        }

        if (field.ast.value_expr != .none and field.comptime_token == null) {
            return astgen.failTok(field.ast.main_token, "non-comptime tuple field has default initialization value", .{});
        }

        if (field.ast.value_expr == .none and field.comptime_token != null) {
            return astgen.failTok(field.comptime_token.?, "comptime field without default initialization value", .{});
        }

        const field_type_ref = try typeExpr(gz, scope, field.ast.type_expr.unwrap().?);
        astgen.scratch.appendAssumeCapacity(@backingInt(field_type_ref));

        if (field.ast.value_expr.unwrap()) |value_expr| {
            const field_init_ref = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = field_type_ref } }, value_expr, .tuple_field_default_value);
            astgen.scratch.appendAssumeCapacity(@backingInt(field_init_ref));
        } else {
            astgen.scratch.appendAssumeCapacity(@backingInt(Zir.Inst.Ref.none));
        }
    }

    const fields_len = std.math.cast(u16, container_decl.ast.members.len) orelse {
        return astgen.failNode(node, "this compiler implementation only supports 65535 tuple fields", .{});
    };

    const extra_trail = astgen.scratch.items[fields_start..];
    assert(extra_trail.len == fields_len * 2);
    try astgen.extra.ensureUnusedCapacity(gpa, @typeInfo(Zir.Inst.TupleDecl).@"struct".field_names.len + extra_trail.len);
    const payload_index = astgen.addExtraAssumeCapacity(Zir.Inst.TupleDecl{
        .src_node = gz.nodeIndexToRelative(node),
    });
    astgen.extra.appendSliceAssumeCapacity(extra_trail);

    return gz.add(.{
        .tag = .extended,
        .data = .{ .extended = .{
            .opcode = .tuple_decl,
            .small = fields_len,
            .operand = payload_index,
        } },
    });
}

fn unionDeclInner(
    gz: *GenZir,
    scope: *Scope,
    node: Ast.Node.Index,
    members: []const Ast.Node.Index,
    layout: std.lang.Type.ContainerLayout,
    opt_arg_node: Ast.Node.OptionalIndex,
    auto_enum_tok: ?Ast.TokenIndex,
    name_strat: Zir.Inst.NameStrategy,
) InnerError!Zir.Inst.Ref {
    const astgen = gz.astgen;
    const gpa = astgen.gpa;

    const explicit_int_or_enum_tag = switch (layout) {
        .auto => opt_arg_node != .none,
        .@"extern" => if (opt_arg_node.unwrap()) |arg_node| {
            return astgen.failNode(arg_node, "{s} union does not support enum tag type", .{@tagName(layout)});
        } else false,
        .@"packed" => false,
    };

    if (auto_enum_tok) |t| {
        if (layout != .auto) {
            return astgen.failTok(t, "{s} union does not support enum tag type", .{@tagName(layout)});
        }
    }

    const is_tagged = explicit_int_or_enum_tag or auto_enum_tok != null;

    astgen.advanceSourceCursorToNode(node);

    const decl_inst = try gz.reserveInstructionIndex();
    const src_line = astgen.source_line;
    const src_column = astgen.source_column;

    var namespace: Scope.Namespace = .{
        .parent = scope,
        .node = node,
        .inst = decl_inst,
        .declaring_gz = gz,
        .maybe_generic = astgen.within_fn,
    };
    defer namespace.deinit(gpa);

    // union_decl 指令引入一个作用域,使联合体内声明
    // 可见,因此字段类型、对齐和默认值表达式
    // 均可引用联合体自身的声明。
    var block_scope: GenZir = .{
        .parent = &namespace.base,
        .src_baseline = node,
        .decl_line = gz.decl_line,
        .astgen = astgen,
        .is_comptime = true,
        .instructions = gz.instructions,
        .instructions_top = gz.instructions.items.len,
    };
    defer block_scope.unstack();

    const scan_result = try astgen.scanContainer(&namespace, members, .@"union");

    var scratch: Scratch = .init(astgen);
    defer scratch.reset();

    // 在 `scratch` 中复现 ZIR 尾随数据的结构
    var wip_decls: WipDecls = try .init(&scratch, scan_result.decls_len);
    const field_names = try scratch.addSlice(scan_result.fields_len);
    const field_type_body_lens = try scratch.addSlice(scan_result.fields_len);
    const field_align_body_lens = try scratch.addOptionalSlice(scan_result.any_field_aligns, scan_result.fields_len);
    const field_value_body_lens = try scratch.addOptionalSlice(scan_result.any_field_values, scan_result.fields_len);

    const old_hasher = astgen.src_hasher;
    defer astgen.src_hasher = old_hasher;
    astgen.src_hasher = .init(.{});

    // 如果指定了标签/底层类型,它位于所有字段体之前。
    const arg_type_body_len: ?u32 = if (opt_arg_node.unwrap()) |arg_node| len: {
        block_scope.src_baseline = arg_node;
        defer block_scope.src_baseline = node;
        astgen.src_hasher.update(astgen.tree.getNodeSource(arg_node));
        const type_ref = try typeExpr(&block_scope, &namespace.base, arg_node);
        if (!block_scope.endsWithNoReturn()) {
            _ = try block_scope.addBreak(.break_inline, decl_inst, type_ref);
        }
        const body_len = try scratch.appendBodyWithFixups(block_scope.instructionsSlice());
        block_scope.instructions.items.len = block_scope.instructions_top;
        break :len body_len;
    } else null;

    var fields_src_baseline: Ast.Node.OptionalIndex = .none;
    var next_field_idx: u32 = 0;
    for (members) |member_node| {
        var member = switch (try containerMember(&block_scope, &namespace.base, &wip_decls, member_node)) {
            .decl => continue,
            .field => |field| field,
        };
        const field_idx = next_field_idx;
        next_field_idx += 1;

        if (field_idx == 0) {
            assert(fields_src_baseline == .none);
            fields_src_baseline = member_node.toOptional();
        }
        block_scope.src_baseline = fields_src_baseline.unwrap().?;
        defer block_scope.src_baseline = node;

        astgen.src_hasher.update(astgen.tree.getNodeSource(member_node));
        member.convertToNonTupleLike(astgen.tree);
        if (member.ast.tuple_like) {
            return astgen.failTok(member.ast.main_token, "union field missing name", .{});
        }
        if (member.comptime_token) |comptime_token| {
            return astgen.failTok(comptime_token, "union fields cannot be marked comptime", .{});
        }

        field_names.get(astgen)[field_idx] = @backingInt(try astgen.identAsString(member.ast.main_token));

        if (member.ast.type_expr.unwrap()) |type_node| {
            const type_ref = try typeExpr(&block_scope, &namespace.base, type_node);
            if (!block_scope.endsWithNoReturn()) {
                _ = try block_scope.addBreak(.break_inline, decl_inst, type_ref);
            }
            const body_len = try scratch.appendBodyWithFixups(block_scope.instructionsSlice());
            field_type_body_lens.get(astgen)[field_idx] = body_len;
            block_scope.instructions.items.len = block_scope.instructions_top;
        } else if (!is_tagged) {
            return astgen.failNode(member_node, "union field missing type", .{});
        } else {
            field_type_body_lens.get(astgen)[field_idx] = 0;
        }

        if (member.ast.align_expr.unwrap()) |align_node| {
            if (layout == .@"packed") {
                return astgen.failNode(align_node, "unable to override alignment of packed union fields", .{});
            }
            const align_ref = try expr(&block_scope, &namespace.base, coerced_align_ri, align_node);
            if (!block_scope.endsWithNoReturn()) {
                _ = try block_scope.addBreak(.break_inline, decl_inst, align_ref);
            }
            const body_len = try scratch.appendBodyWithFixups(block_scope.instructionsSlice());
            field_align_body_lens.?.get(astgen)[field_idx] = body_len;
            block_scope.instructions.items.len = block_scope.instructions_top;
        } else if (field_align_body_lens) |lens| {
            lens.get(astgen)[field_idx] = 0;
        }

        if (member.ast.value_expr.unwrap()) |value_node| {
            if (!explicit_int_or_enum_tag) return astgen.failNodeNotes(
                node,
                "explicitly valued tagged union missing integer tag type",
                .{},
                &.{try astgen.errNoteNode(value_node, "tag value specified here", .{})},
            );
            if (auto_enum_tok == null) return astgen.failNodeNotes(
                node,
                "explicitly valued tagged union requires inferred enum tag type",
                .{},
                &.{try astgen.errNoteNode(value_node, "tag value specified here", .{})},
            );
            const ri: ResultInfo = .{ .rl = .{ .coerced_ty = decl_inst.toRef() } };
            const value_ref = try expr(&block_scope, &namespace.base, ri, value_node);
            if (!block_scope.endsWithNoReturn()) {
                _ = try block_scope.addBreak(.break_inline, decl_inst, value_ref);
            }
            const body_len = try scratch.appendBodyWithFixups(block_scope.instructionsSlice());
            field_value_body_lens.?.get(astgen)[field_idx] = body_len;
            block_scope.instructions.items.len = block_scope.instructions_top;
        } else if (field_value_body_lens) |lens| {
            lens.get(astgen)[field_idx] = 0;
        }
    }
    assert(next_field_idx == scan_result.fields_len);
    wip_decls.finish();

    var fields_hash: std.zig.SrcHash = undefined;
    astgen.src_hasher.final(&fields_hash);

    try gz.setUnion(decl_inst, .{
        .src_line = src_line,
        .src_column = src_column,
        .src_node = node,
        .name_strat = name_strat,
        .arg_baseline_src_node = opt_arg_node,
        .fields_baseline_src_node = fields_src_baseline,
        .kind = switch (layout) {
            .auto => if (auto_enum_tok == null) l: {
                break :l if (opt_arg_node == .none) .auto else .tagged_explicit;
            } else l: {
                break :l if (opt_arg_node == .none) .tagged_enum else .tagged_enum_explicit;
            },
            .@"extern" => .@"extern",
            .@"packed" => if (opt_arg_node != .none) .packed_explicit else .@"packed",
        },
        .arg_type_body_len = arg_type_body_len,
        .decls_len = scan_result.decls_len,
        .fields_len = scan_result.fields_len,
        .any_field_aligns = scan_result.any_field_aligns,
        .any_field_values = scan_result.any_field_values,
        .fields_hash = fields_hash,
        .captures = namespace.captures.keys(),
        .capture_names = namespace.captures.values(),
        .remaining = scratch.all().get(astgen),
    });

    block_scope.unstack();
    return decl_inst.toRef();
}

fn containerDecl(
    gz: *GenZir,
    scope: *Scope,
    ri: ResultInfo,
    node: Ast.Node.Index,
    container_decl: Ast.full.ContainerDecl,
    name_strat: Zir.Inst.NameStrategy,
) InnerError!Zir.Inst.Ref {
    const astgen = gz.astgen;
    const gpa = astgen.gpa;
    const tree = astgen.tree;

    const prev_fn_block = astgen.fn_block;
    astgen.fn_block = null;
    defer astgen.fn_block = prev_fn_block;

    // 在 Sema 之前不得创建任何类型。此处仅为所有字段类型、
    // 对齐值及默认值表达式生成 ZIR。

    switch (tree.tokenTag(container_decl.ast.main_token)) {
        .keyword_struct => {
            const layout: std.lang.Type.ContainerLayout = if (container_decl.layout_token) |t| switch (tree.tokenTag(t)) {
                .keyword_packed => .@"packed",
                .keyword_extern => .@"extern",
                else => unreachable,
            } else .auto;

            const result = try structDeclInner(gz, scope, node, container_decl, layout, container_decl.ast.arg, name_strat);
            return rvalue(gz, ri, result, node);
        },
        .keyword_union => {
            const layout: std.lang.Type.ContainerLayout = if (container_decl.layout_token) |t| switch (tree.tokenTag(t)) {
                .keyword_packed => .@"packed",
                .keyword_extern => .@"extern",
                else => unreachable,
            } else .auto;

            const result = try unionDeclInner(gz, scope, node, container_decl.ast.members, layout, container_decl.ast.arg, container_decl.ast.enum_token, name_strat);
            return rvalue(gz, ri, result, node);
        },
        .keyword_enum => {
            if (container_decl.layout_token) |t| {
                return astgen.failTok(t, "enums do not support 'packed' or 'extern'; instead provide an explicit integer tag type", .{});
            }

            astgen.advanceSourceCursorToNode(node);

            const decl_inst = try gz.reserveInstructionIndex();
            const src_line = astgen.source_line;
            const src_column = astgen.source_column;

            var namespace: Scope.Namespace = .{
                .parent = scope,
                .node = node,
                .inst = decl_inst,
                .declaring_gz = gz,
                .maybe_generic = astgen.within_fn,
            };
            defer namespace.deinit(gpa);

            // enum_decl 指令引入一个作用域,枚举的声明在其中
            // 可见,使标签值可以引用枚举自身内部的声明。
            var block_scope: GenZir = .{
                .parent = &namespace.base,
                .src_baseline = node,
                .decl_line = gz.decl_line,
                .astgen = astgen,
                .is_comptime = true,
                .instructions = gz.instructions,
                .instructions_top = gz.instructions.items.len,
            };
            defer block_scope.unstack();

            const scan_result = try astgen.scanContainer(&namespace, container_decl.ast.members, .@"enum");
            // 名称 `_` 实际上不是字段;它标记非穷尽枚举。
            const fields_len: u32 = scan_result.fields_len - @intFromBool(scan_result.has_underscore_field);

            var scratch: Scratch = .init(astgen);
            defer scratch.reset();

            // 在 `scratch` 中复现 ZIR 尾随数据的结构
            var wip_decls: WipDecls = try .init(&scratch, scan_result.decls_len);
            const field_names = try scratch.addSlice(fields_len);
            const field_value_body_lens = try scratch.addOptionalSlice(scan_result.any_field_values, fields_len);

            const old_hasher = astgen.src_hasher;
            defer astgen.src_hasher = old_hasher;
            astgen.src_hasher = .init(.{});

            // 如果指定了标签类型,它位于所有字段体之前。
            const tag_type_body_len: ?u32 = if (container_decl.ast.arg.unwrap()) |tag_type_node| len: {
                block_scope.src_baseline = tag_type_node;
                defer block_scope.src_baseline = node;
                astgen.src_hasher.update(astgen.tree.getNodeSource(tag_type_node));
                const type_ref = try typeExpr(&block_scope, &namespace.base, tag_type_node);
                if (!block_scope.endsWithNoReturn()) {
                    _ = try block_scope.addBreak(.break_inline, decl_inst, type_ref);
                }
                const body_len = try scratch.appendBodyWithFixups(block_scope.instructionsSlice());
                block_scope.instructions.items.len = block_scope.instructions_top;
                break :len body_len;
            } else null;

            var next_field_idx: u32 = 0;
            var fields_src_baseline: Ast.Node.OptionalIndex = .none;
            var opt_nonexhaustive_node: Ast.Node.OptionalIndex = .none;
            for (container_decl.ast.members) |member_node| {
                var member = switch (try containerMember(&block_scope, &namespace.base, &wip_decls, member_node)) {
                    .decl => continue,
                    .field => |field| field,
                };
                member.convertToNonTupleLike(astgen.tree);
                if (member.ast.tuple_like) return astgen.failTok(member.ast.main_token, "enum field missing name", .{});
                if (member.comptime_token) |t| return astgen.failTok(t, "enum fields cannot be marked comptime", .{});
                if (member.ast.type_expr.unwrap()) |type_node| {
                    return astgen.failNodeNotes(type_node, "enum fields do not have types", .{}, &.{
                        try astgen.errNoteNode(node, "consider 'union(enum)' here to make it a tagged union", .{}),
                    });
                }
                if (member.ast.align_expr.unwrap()) |n| return astgen.failNode(n, "enum fields cannot be aligned", .{});
                if (mem.eql(u8, tree.tokenSlice(member.ast.main_token), "_")) {
                    // 非穷尽标记
                    assert(scan_result.has_underscore_field);
                    if (opt_nonexhaustive_node.unwrap()) |prev_node| {
                        return astgen.failNodeNotes(member_node, "redundant non-exhaustive enum mark", .{}, &.{
                            try astgen.errNoteNode(prev_node, "other mark here", .{}),
                        });
                    }
                    if (member.ast.value_expr.unwrap()) |value_node| {
                        return astgen.failNode(value_node, "'_' is used to mark an enum as non-exhaustive and cannot be assigned a value", .{});
                    }
                    if (next_field_idx != fields_len) {
                        return astgen.failNode(member_node, "'_' field of non-exhaustive enum must be last", .{});
                    }
                    if (tag_type_body_len == null) {
                        return astgen.failNodeNotes(node, "non-exhaustive enum missing integer tag type", .{}, &.{
                            try astgen.errNoteNode(member_node, "marked non-exhaustive here", .{}),
                        });
                    }
                    opt_nonexhaustive_node = member_node.toOptional();
                    continue;
                }

                // 这是真正的字段,而不是非穷尽标记。
                const field_idx = next_field_idx;
                next_field_idx += 1;

                if (field_idx == 0) {
                    assert(fields_src_baseline == .none);
                    fields_src_baseline = member_node.toOptional();
                }
                block_scope.src_baseline = fields_src_baseline.unwrap().?;
                defer block_scope.src_baseline = node;

                astgen.src_hasher.update(tree.getNodeSource(member_node));

                field_names.get(astgen)[field_idx] = @backingInt(try astgen.identAsString(member.ast.main_token));

                if (member.ast.value_expr.unwrap()) |value_node| {
                    if (tag_type_body_len == null) {
                        return astgen.failNodeNotes(node, "explicitly valued enum missing integer tag type", .{}, &.{
                            try astgen.errNoteNode(value_node, "tag value specified here", .{}),
                        });
                    }
                    const val_ri: ResultInfo = .{ .rl = .{ .coerced_ty = decl_inst.toRef() } };
                    const value_ref = try expr(&block_scope, &namespace.base, val_ri, value_node);
                    if (!block_scope.endsWithNoReturn()) {
                        _ = try block_scope.addBreak(.break_inline, decl_inst, value_ref);
                    }
                    const body_len = try scratch.appendBodyWithFixups(block_scope.instructionsSlice());
                    field_value_body_lens.?.get(astgen)[field_idx] = body_len;
                    block_scope.instructions.items.len = block_scope.instructions_top;
                } else if (field_value_body_lens) |lens| {
                    lens.get(astgen)[field_idx] = 0;
                }
            }
            assert(scan_result.has_underscore_field == (opt_nonexhaustive_node != .none));
            assert(next_field_idx == fields_len);
            wip_decls.finish();

            var fields_hash: std.zig.SrcHash = undefined;
            astgen.src_hasher.final(&fields_hash);

            try gz.setEnum(decl_inst, .{
                .src_line = src_line,
                .src_column = src_column,
                .src_node = node,
                .name_strat = name_strat,
                .arg_baseline_src_node = container_decl.ast.arg,
                .fields_baseline_src_node = fields_src_baseline,
                .tag_type_body_len = tag_type_body_len,
                .nonexhaustive = scan_result.has_underscore_field,
                .decls_len = scan_result.decls_len,
                .fields_len = fields_len,
                .any_field_values = scan_result.any_field_values,
                .fields_hash = fields_hash,
                .captures = namespace.captures.keys(),
                .capture_names = namespace.captures.values(),
                .remaining = scratch.all().get(astgen),
            });

            block_scope.unstack();
            return rvalue(gz, ri, decl_inst.toRef(), node);
        },
        .keyword_opaque => {
            assert(container_decl.ast.arg == .none);

            astgen.advanceSourceCursorToNode(node);

            const decl_inst = try gz.reserveInstructionIndex();
            const src_line = astgen.source_line;
            const src_column = astgen.source_column;

            var namespace: Scope.Namespace = .{
                .parent = scope,
                .node = node,
                .inst = decl_inst,
                .declaring_gz = gz,
                .maybe_generic = astgen.within_fn,
            };
            defer namespace.deinit(gpa);

            var block_scope: GenZir = .{
                .parent = &namespace.base,
                .src_baseline = node,
                .decl_line = gz.decl_line,
                .astgen = astgen,
                .is_comptime = true,
                .instructions = gz.instructions,
                .instructions_top = gz.instructions.items.len,
            };
            defer block_scope.unstack();

            const scan_result = try astgen.scanContainer(&namespace, container_decl.ast.members, .@"opaque");

            var scratch: Scratch = .init(astgen);
            defer scratch.reset();
            var wip_decls: WipDecls = try .init(&scratch, scan_result.decls_len);

            if (container_decl.layout_token) |layout_token| {
                return astgen.failTok(layout_token, "opaque types do not support 'packed' or 'extern'", .{});
            }

            for (container_decl.ast.members) |member_node| {
                switch (try containerMember(&block_scope, &namespace.base, &wip_decls, member_node)) {
                    .decl => {},
                    .field => return astgen.failNode(member_node, "opaque types cannot have fields", .{}),
                }
            }

            wip_decls.finish();

            try gz.setOpaque(decl_inst, .{
                .src_line = src_line,
                .src_column = src_column,
                .src_node = node,
                .name_strat = name_strat,
                .decls_len = scan_result.decls_len,
                .captures = namespace.captures.keys(),
                .capture_names = namespace.captures.values(),
                .decls = @ptrCast(scratch.all().get(astgen)),
            });

            block_scope.unstack();
            return rvalue(gz, ri, decl_inst.toRef(), node);
        },
        else => unreachable,
    }
}

const ContainerMemberResult = union(enum) { decl, field: Ast.full.ContainerField };

fn containerMember(
    gz: *GenZir,
    scope: *Scope,
    wip_decls: *WipDecls,
    member_node: Ast.Node.Index,
) InnerError!ContainerMemberResult {
    const astgen = gz.astgen;
    const tree = astgen.tree;
    switch (tree.nodeTag(member_node)) {
        .container_field_init,
        .container_field_align,
        .container_field,
        => return ContainerMemberResult{ .field = tree.fullContainerField(member_node).? },

        .fn_proto,
        .fn_proto_multi,
        .fn_proto_one,
        .fn_proto_simple,
        .fn_decl,
        => {
            var buf: [1]Ast.Node.Index = undefined;
            const full = tree.fullFnProto(&buf, member_node).?;

            const body: Ast.Node.OptionalIndex = if (tree.nodeTag(member_node) == .fn_decl)
                tree.nodeData(member_node).node_and_node[1].toOptional()
            else
                .none;

            const prev_decl_index = wip_decls.index;
            astgen.fnDecl(gz, scope, wip_decls, member_node, body, full) catch |err| switch (err) {
                error.OutOfMemory => |e| return e,
                error.AnalysisFail => {
                    wip_decls.index = prev_decl_index;
                    try addFailedDeclaration(
                        wip_decls,
                        gz,
                        .@"const",
                        try astgen.identAsString(full.name_token.?),
                        full.ast.proto_node,
                        full.visib_token != null,
                    );
                },
            };
        },

        .global_var_decl,
        .local_var_decl,
        .simple_var_decl,
        .aligned_var_decl,
        => {
            const full = tree.fullVarDecl(member_node).?;
            const prev_decl_index = wip_decls.index;
            astgen.globalVarDecl(gz, scope, wip_decls, member_node, full) catch |err| switch (err) {
                error.OutOfMemory => |e| return e,
                error.AnalysisFail => {
                    wip_decls.index = prev_decl_index;
                    try addFailedDeclaration(
                        wip_decls,
                        gz,
                        .@"const", // 实际上没有影响
                        try astgen.identAsString(full.ast.mut_token + 1),
                        member_node,
                        full.visib_token != null,
                    );
                },
            };
        },

        .@"comptime" => {
            const prev_decl_index = wip_decls.index;
            astgen.comptimeDecl(gz, scope, wip_decls, member_node) catch |err| switch (err) {
                error.OutOfMemory => |e| return e,
                error.AnalysisFail => {
                    wip_decls.index = prev_decl_index;
                    try addFailedDeclaration(
                        wip_decls,
                        gz,
                        .@"comptime",
                        .empty,
                        member_node,
                        false,
                    );
                },
            };
        },
        .test_decl => {
            const prev_decl_index = wip_decls.index;
            // 此处需要某个声明,使声明数量符合预期。
            // 具体是什么并不严格重要,因此无需重复测试名称的处理逻辑,
            // 直接将其视为未命名测试即可。
            astgen.testDecl(gz, scope, wip_decls, member_node) catch |err| switch (err) {
                error.OutOfMemory => |e| return e,
                error.AnalysisFail => {
                    wip_decls.index = prev_decl_index;
                    try addFailedDeclaration(
                        wip_decls,
                        gz,
                        .unnamed_test,
                        .empty,
                        member_node,
                        false,
                    );
                },
            };
        },
        else => unreachable,
    }
    return .decl;
}

fn errorSetDecl(gz: *GenZir, ri: ResultInfo, node: Ast.Node.Index) InnerError!Zir.Inst.Ref {
    const astgen = gz.astgen;
    const gpa = astgen.gpa;
    const tree = astgen.tree;

    const payload_index = try reserveExtra(astgen, @typeInfo(Zir.Inst.ErrorSetDecl).@"struct".field_names.len);
    var fields_len: usize = 0;
    {
        var idents: std.AutoHashMapUnmanaged(Zir.NullTerminatedString, Ast.TokenIndex) = .empty;
        defer idents.deinit(gpa);

        const lbrace, const rbrace = tree.nodeData(node).token_and_token;
        for (lbrace + 1..rbrace) |i| {
            const tok_i: Ast.TokenIndex = @intCast(i);
            switch (tree.tokenTag(tok_i)) {
                .doc_comment, .comma => {},
                .identifier => {
                    const str_index = try astgen.identAsString(tok_i);
                    const gop = try idents.getOrPut(gpa, str_index);
                    if (gop.found_existing) {
                        const name = try gpa.dupe(u8, mem.span(astgen.nullTerminatedString(str_index)));
                        defer gpa.free(name);
                        return astgen.failTokNotes(
                            tok_i,
                            "duplicate error set field '{s}'",
                            .{name},
                            &[_]u32{
                                try astgen.errNoteTok(
                                    gop.value_ptr.*,
                                    "previous declaration here",
                                    .{},
                                ),
                            },
                        );
                    }
                    gop.value_ptr.* = tok_i;

                    try astgen.extra.append(gpa, @backingInt(str_index));
                    fields_len += 1;
                },
                else => unreachable,
            }
        }
    }

    setExtra(astgen, payload_index, Zir.Inst.ErrorSetDecl{
        .fields_len = @intCast(fields_len),
    });
    const result = try gz.addPlNodePayloadIndex(.error_set_decl, node, payload_index);
    return rvalue(gz, ri, result, node);
}

fn tryExpr(
    parent_gz: *GenZir,
    scope: *Scope,
    ri: ResultInfo,
    node: Ast.Node.Index,
    operand_node: Ast.Node.Index,
) InnerError!Zir.Inst.Ref {
    const astgen = parent_gz.astgen;

    const fn_block = astgen.fn_block orelse {
        return astgen.failNode(node, "'try' outside function scope", .{});
    };

    if (parent_gz.any_defer_node.unwrap()) |any_defer_node| {
        return astgen.failNodeNotes(node, "'try' not allowed inside defer expression", .{}, &.{
            try astgen.errNoteNode(
                any_defer_node,
                "defer expression here",
                .{},
            ),
        });
    }

    // 确保为此 try 表达式生成调试行列信息。
    // 随后保存行列,以便再生成一条向
    // “后方”移动的信息:需要先对操作数求值,再将调试
    // 位置恢复到 try 关键字,以用于错误返回跟踪。
    if (!parent_gz.is_comptime) {
        try emitDbgNode(parent_gz, node);
    }
    const try_lc: LineColumn = .{ astgen.source_line - parent_gz.decl_line, astgen.source_column };

    const operand_rl: ResultInfo.Loc, const block_tag: Zir.Inst.Tag = switch (ri.rl) {
        .ref, .ref_coerced_ty => .{ .ref, .try_ptr },
        .ref_const => .{ .ref_const, .try_ptr },
        else => .{ .none, .@"try" },
    };
    const operand_ri: ResultInfo = .{ .rl = operand_rl, .ctx = .error_handling_expr };
    const operand = operand: {
        // 作为特殊情况,需要检测以下形式:
        // `try .foo(...)`
        // 这是声明字面量形式,即使我们不会通过 `try` 传播结果类型。
        var buf: [1]Ast.Node.Index = undefined;
        if (astgen.tree.fullCall(&buf, operand_node)) |full_call| {
            const res_ty: Zir.Inst.Ref = try ri.rl.resultType(parent_gz, operand_node) orelse .none;
            break :operand try callExpr(parent_gz, scope, operand_ri, res_ty, operand_node, full_call);
        }

        // 根据 `ri` 参数的不同,这可能是指针,也可能是值。
        break :operand try reachableExpr(parent_gz, scope, operand_ri, operand_node, node);
    };

    const try_inst = try parent_gz.makeBlockInst(block_tag, node);
    try parent_gz.instructions.append(astgen.gpa, try_inst);

    var else_scope = parent_gz.makeSubBlock(scope);
    defer else_scope.unstack();

    const err_tag = switch (ri.rl) {
        .ref, .ref_const, .ref_coerced_ty => Zir.Inst.Tag.err_union_code_ptr,
        else => Zir.Inst.Tag.err_union_code,
    };
    const err_code = try else_scope.addUnNode(err_tag, operand, node);
    try genDefers(&else_scope, &fn_block.base, scope, .normal_and_error);
    try emitDbgStmt(&else_scope, try_lc);
    _ = try else_scope.addUnNode(.ret_node, err_code, node);

    try else_scope.setTryBody(try_inst, operand);
    const result = try_inst.toRef();
    switch (ri.rl) {
        .ref, .ref_const, .ref_coerced_ty => return result,
        else => return rvalue(parent_gz, ri, result, node),
    }
}

fn orelseCatchExpr(
    parent_gz: *GenZir,
    scope: *Scope,
    ri: ResultInfo,
    node: Ast.Node.Index,
    cond_op: Zir.Inst.Tag,
    unwrap_op: Zir.Inst.Tag,
    unwrap_code_op: Zir.Inst.Tag,
    payload_token: ?Ast.TokenIndex,
) InnerError!Zir.Inst.Ref {
    const astgen = parent_gz.astgen;
    const tree = astgen.tree;

    const lhs, const rhs = tree.nodeData(node).node_and_node;

    const need_rl = astgen.nodes_need_rl.contains(node);
    const block_ri: ResultInfo = if (need_rl) ri else .{
        .rl = switch (ri.rl) {
            .ptr => .{ .ty = (try ri.rl.resultType(parent_gz, node)).? },
            .inferred_ptr => .none,
            else => ri.rl,
        },
        .ctx = ri.ctx,
    };
    // 仅当已有结果指针且未转发该指针时,才需调用 `rvalue` 通过指针写入。
    //
    const LocTag = @typeInfo(ResultInfo.Loc).@"union".tag_type.?;
    const need_result_rvalue = @as(LocTag, block_ri.rl) != @as(LocTag, ri.rl);

    const do_err_trace = astgen.fn_block != null and (cond_op == .is_non_err or cond_op == .is_non_err_ptr);

    var block_scope = parent_gz.makeSubBlock(scope);
    block_scope.setBreakResultInfo(block_ri);
    defer block_scope.unstack();

    const operand_ri: ResultInfo = switch (block_scope.break_result_info.rl) {
        .ref, .ref_coerced_ty => .{ .rl = .ref, .ctx = if (do_err_trace) .error_handling_expr else .none },
        .ref_const => .{ .rl = .ref_const, .ctx = if (do_err_trace) .error_handling_expr else .none },
        else => .{ .rl = .none, .ctx = if (do_err_trace) .error_handling_expr else .none },
    };
    // 根据 `operand_ri` 参数,这可能是指针,也可能是值。
    // 不能使用 `block_scope.break_result_info`,因为它具有裸
    // 类型,而此表达式具有可选类型。稍后通过对 else 分支
    // 调用 rvalue 来弥补这一差别。
    const operand = try reachableExpr(&block_scope, &block_scope.base, operand_ri, lhs, rhs);
    const cond = try block_scope.addUnNode(cond_op, operand, node);
    const condbr = try block_scope.addCondBr(.condbr, node);

    const block = try parent_gz.makeBlockInst(.block, node);
    try block_scope.setBlockBody(block);
    // block_scope 已弹出,现在可向 parent_gz 添加新指令。
    try parent_gz.instructions.append(astgen.gpa, block);

    var then_scope = block_scope.makeSubBlock(scope);
    defer then_scope.unstack();

    // 根据 `unwrap_op` 的不同,这可能是指针,也可能是值。
    const unwrapped_payload = try then_scope.addUnNode(unwrap_op, operand, node);
    const then_result = switch (ri.rl) {
        .ref, .ref_const, .ref_coerced_ty => unwrapped_payload,
        else => try rvalue(&then_scope, block_scope.break_result_info, unwrapped_payload, node),
    };
    _ = try then_scope.addBreakWithSrcNode(.@"break", block, then_result, node);

    var else_scope = block_scope.makeSubBlock(scope);
    defer else_scope.unstack();

    // 已知操作数(几乎肯定)修改了错误返回跟踪,
    // 因此通知 Sema 保存新的索引,以便稍后恢复。
    if (do_err_trace and nodeMayAppendToErrorTrace(tree, lhs))
        _ = try else_scope.addSaveErrRetIndex(.always);

    var err_val_scope: Scope.LocalVal = undefined;
    const else_sub_scope = blk: {
        const payload = payload_token orelse break :blk &else_scope.base;
        const err_str = tree.tokenSlice(payload);
        if (mem.eql(u8, err_str, "_")) {
            try astgen.appendErrorTok(payload, "discard of error capture; omit it instead", .{});
            break :blk &else_scope.base;
        }
        const err_name = try astgen.identAsString(payload);

        try astgen.detectLocalShadowing(scope, err_name, payload, err_str, .capture);

        err_val_scope = .{
            .parent = &else_scope.base,
            .gen_zir = &else_scope,
            .name = err_name,
            .inst = try else_scope.addUnNode(unwrap_code_op, operand, node),
            .token_src = payload,
            .id_cat = .capture,
        };
        break :blk &err_val_scope.base;
    };

    const else_result = else_result: {
        if (tree.fullSwitch(rhs)) |switch_full| no_switch_on_err: {
            if (tree.nodeTag(node) != .@"catch") break :no_switch_on_err;
            const catch_token = tree.nodeMainToken(node);
            const capture_token = if (tree.tokenTag(catch_token + 1) == .pipe) token: {
                break :token catch_token + 2;
            } else break :no_switch_on_err;
            if (switch_full.label_token == null) break :no_switch_on_err; // 必须使用带有 `non_err = .@"if"` 的 `switchExpr`
            if (tree.nodeTag(switch_full.ast.condition) != .identifier) break :no_switch_on_err;
            if (!try astgen.tokenIdentEql(capture_token, tree.nodeMainToken(switch_full.ast.condition))) break :no_switch_on_err;
            break :else_result try switchExpr(
                &else_scope,
                else_sub_scope,
                block_scope.break_result_info,
                rhs,
                switch_full,
                .{ .peer_break_target = .{
                    .block_inst = block,
                    .block_ri = block_ri,
                } },
            );
        }
        break :else_result try fullBodyExpr(&else_scope, else_sub_scope, block_scope.break_result_info, rhs, .allow_branch_hint);
    };
    if (!else_scope.endsWithNoReturn()) {
        // 作为 break 前最后一个操作,必要时“弹出”错误跟踪
        if (do_err_trace)
            try restoreErrRetIndex(&else_scope, .{ .block = block }, block_scope.break_result_info, rhs, else_result);

        _ = try else_scope.addBreakWithSrcNode(.@"break", block, else_result, rhs);
    }
    try checkUsed(parent_gz, &else_scope.base, else_sub_scope);

    try setCondBrPayload(condbr, cond, &then_scope, &else_scope);

    if (need_result_rvalue) {
        return rvalue(parent_gz, ri, block.toRef(), node);
    } else {
        return block.toRef();
    }
}

/// 返回两个词法标记的标识符名称是否相等。不分配内存即可解析
/// @"" 形式的标记。
/// 确切地说,理论上可以不分配内存;此实现
/// 在使用 @"" 形式时会进行分配。
fn tokenIdentEql(astgen: *AstGen, token1: Ast.TokenIndex, token2: Ast.TokenIndex) !bool {
    const ident_name_1 = try astgen.identifierTokenString(token1);
    const ident_name_2 = try astgen.identifierTokenString(token2);
    return mem.eql(u8, ident_name_1, ident_name_2);
}

fn fieldAccess(
    gz: *GenZir,
    scope: *Scope,
    ri: ResultInfo,
    node: Ast.Node.Index,
) InnerError!Zir.Inst.Ref {
    switch (ri.rl) {
        .ref, .ref_coerced_ty => return addFieldAccess(.field_ptr, gz, scope, .{ .rl = .ref }, node),
        .ref_const => return addFieldAccess(.field_ptr, gz, scope, .{ .rl = .ref_const }, node),
        else => {
            const access = try addFieldAccess(.field_ptr_load, gz, scope, .{ .rl = .ref_const }, node);
            return rvalue(gz, ri, access, node);
        },
    }
}

fn addFieldAccess(
    tag: Zir.Inst.Tag,
    gz: *GenZir,
    scope: *Scope,
    lhs_ri: ResultInfo,
    node: Ast.Node.Index,
) InnerError!Zir.Inst.Ref {
    const astgen = gz.astgen;
    const tree = astgen.tree;

    const object_node, const field_ident = tree.nodeData(node).node_and_token;
    const str_index = try astgen.identAsString(field_ident);
    const lhs = try expr(gz, scope, lhs_ri, object_node);

    const cursor = maybeAdvanceSourceCursorToMainToken(gz, node);
    try emitDbgStmt(gz, cursor);

    return gz.addPlNode(tag, node, Zir.Inst.Field{
        .lhs = lhs,
        .field_name_start = str_index,
    });
}

fn arrayAccess(
    gz: *GenZir,
    scope: *Scope,
    ri: ResultInfo,
    node: Ast.Node.Index,
) InnerError!Zir.Inst.Ref {
    const tree = gz.astgen.tree;
    switch (ri.rl) {
        .ref, .ref_coerced_ty => {
            const lhs_node, const rhs_node = tree.nodeData(node).node_and_node;
            const lhs = try expr(gz, scope, .{ .rl = .ref }, lhs_node);

            const cursor = maybeAdvanceSourceCursorToMainToken(gz, node);

            const rhs = try expr(gz, scope, .{ .rl = .{ .coerced_ty = .usize_type } }, rhs_node);
            try emitDbgStmt(gz, cursor);

            return gz.addPlNode(.elem_ptr_node, node, Zir.Inst.Bin{ .lhs = lhs, .rhs = rhs });
        },
        .ref_const => {
            const lhs_node, const rhs_node = tree.nodeData(node).node_and_node;
            const lhs = try expr(gz, scope, .{ .rl = .ref_const }, lhs_node);

            const cursor = maybeAdvanceSourceCursorToMainToken(gz, node);

            const rhs = try expr(gz, scope, .{ .rl = .{ .coerced_ty = .usize_type } }, rhs_node);
            try emitDbgStmt(gz, cursor);

            return gz.addPlNode(.elem_ptr_node, node, Zir.Inst.Bin{ .lhs = lhs, .rhs = rhs });
        },
        else => {
            const lhs_node, const rhs_node = tree.nodeData(node).node_and_node;
            const lhs = try expr(gz, scope, .{ .rl = .ref_const }, lhs_node);

            const cursor = maybeAdvanceSourceCursorToMainToken(gz, node);

            const rhs = try expr(gz, scope, .{ .rl = .{ .coerced_ty = .usize_type } }, rhs_node);
            try emitDbgStmt(gz, cursor);

            return rvalue(gz, ri, try gz.addPlNode(.elem_ptr_load, node, Zir.Inst.Bin{ .lhs = lhs, .rhs = rhs }), node);
        },
    }
}

fn simpleBinOp(
    gz: *GenZir,
    scope: *Scope,
    ri: ResultInfo,
    node: Ast.Node.Index,
    op_inst_tag: Zir.Inst.Tag,
) InnerError!Zir.Inst.Ref {
    const astgen = gz.astgen;
    const tree = astgen.tree;

    const lhs_node, const rhs_node = tree.nodeData(node).node_and_node;

    if (op_inst_tag == .cmp_neq or op_inst_tag == .cmp_eq) {
        const str = if (op_inst_tag == .cmp_eq) "==" else "!=";
        if (tree.nodeTag(lhs_node) == .string_literal or
            tree.nodeTag(rhs_node) == .string_literal)
            return astgen.failNode(node, "cannot compare strings with {s}", .{str});
    }

    const lhs = try reachableExpr(gz, scope, .{ .rl = .none }, lhs_node, node);
    const cursor = switch (op_inst_tag) {
        .add, .sub, .mul, .div, .mod_rem => maybeAdvanceSourceCursorToMainToken(gz, node),
        else => undefined,
    };
    const rhs = try reachableExpr(gz, scope, .{ .rl = .none }, rhs_node, node);

    switch (op_inst_tag) {
        .add, .sub, .mul, .div, .mod_rem => {
            try emitDbgStmt(gz, cursor);
        },
        else => {},
    }
    const result = try gz.addPlNode(op_inst_tag, node, Zir.Inst.Bin{ .lhs = lhs, .rhs = rhs });
    return rvalue(gz, ri, result, node);
}

fn simpleStrTok(
    gz: *GenZir,
    ri: ResultInfo,
    ident_token: Ast.TokenIndex,
    node: Ast.Node.Index,
    op_inst_tag: Zir.Inst.Tag,
) InnerError!Zir.Inst.Ref {
    const astgen = gz.astgen;
    const str_index = try astgen.identAsString(ident_token);
    const result = try gz.addStrTok(op_inst_tag, str_index, ident_token);
    return rvalue(gz, ri, result, node);
}

fn boolBinOp(
    gz: *GenZir,
    scope: *Scope,
    ri: ResultInfo,
    node: Ast.Node.Index,
    zir_tag: Zir.Inst.Tag,
) InnerError!Zir.Inst.Ref {
    const astgen = gz.astgen;
    const tree = astgen.tree;

    const lhs_node, const rhs_node = tree.nodeData(node).node_and_node;
    const lhs = try expr(gz, scope, coerced_bool_ri, lhs_node);
    const bool_br = (try gz.addPlNodePayloadIndex(zir_tag, node, undefined)).toIndex().?;

    var rhs_scope = gz.makeSubBlock(scope);
    defer rhs_scope.unstack();
    const rhs = try fullBodyExpr(&rhs_scope, &rhs_scope.base, coerced_bool_ri, rhs_node, .allow_branch_hint);
    if (!gz.refIsNoReturn(rhs)) {
        _ = try rhs_scope.addBreakWithSrcNode(.break_inline, bool_br, rhs, rhs_node);
    }
    try rhs_scope.setBoolBrBody(bool_br, lhs);

    const block_ref = bool_br.toRef();
    return rvalue(gz, ri, block_ref, node);
}

fn ifExpr(
    parent_gz: *GenZir,
    scope: *Scope,
    ri: ResultInfo,
    node: Ast.Node.Index,
    if_full: Ast.full.If,
) InnerError!Zir.Inst.Ref {
    const astgen = parent_gz.astgen;
    const tree = astgen.tree;

    const do_err_trace = astgen.fn_block != null and if_full.error_token != null;

    const need_rl = astgen.nodes_need_rl.contains(node);
    const block_ri: ResultInfo = if (need_rl) ri else .{
        .rl = switch (ri.rl) {
            .ptr => .{ .ty = (try ri.rl.resultType(parent_gz, node)).? },
            .inferred_ptr => .none,
            else => ri.rl,
        },
        .ctx = ri.ctx,
    };
    // 仅当已有结果指针且未转发该指针时,才需调用 `rvalue` 通过指针写入。
    //
    const LocTag = @typeInfo(ResultInfo.Loc).@"union".tag_type.?;
    const need_result_rvalue = @as(LocTag, block_ri.rl) != @as(LocTag, ri.rl);

    var block_scope = parent_gz.makeSubBlock(scope);
    block_scope.setBreakResultInfo(block_ri);
    defer block_scope.unstack();

    const payload_is_ref = if (if_full.payload_token) |payload_token|
        tree.tokenTag(payload_token) == .asterisk
    else
        false;

    try emitDbgNode(parent_gz, if_full.ast.cond_expr);
    const cond: struct {
        inst: Zir.Inst.Ref,
        bool_bit: Zir.Inst.Ref,
    } = c: {
        if (if_full.error_token) |_| {
            const cond_ri: ResultInfo = .{ .rl = if (payload_is_ref) .ref else .none, .ctx = .error_handling_expr };
            const err_union = try expr(&block_scope, &block_scope.base, cond_ri, if_full.ast.cond_expr);
            const tag: Zir.Inst.Tag = if (payload_is_ref) .is_non_err_ptr else .is_non_err;
            break :c .{
                .inst = err_union,
                .bool_bit = try block_scope.addUnNode(tag, err_union, if_full.ast.cond_expr),
            };
        } else if (if_full.payload_token) |_| {
            const cond_ri: ResultInfo = .{ .rl = if (payload_is_ref) .ref else .none };
            const optional = try expr(&block_scope, &block_scope.base, cond_ri, if_full.ast.cond_expr);
            const tag: Zir.Inst.Tag = if (payload_is_ref) .is_non_null_ptr else .is_non_null;
            break :c .{
                .inst = optional,
                .bool_bit = try block_scope.addUnNode(tag, optional, if_full.ast.cond_expr),
            };
        } else {
            const cond = try expr(&block_scope, &block_scope.base, coerced_bool_ri, if_full.ast.cond_expr);
            break :c .{
                .inst = cond,
                .bool_bit = cond,
            };
        }
    };

    const condbr = try block_scope.addCondBr(.condbr, node);

    const block = try parent_gz.makeBlockInst(.block, node);
    try block_scope.setBlockBody(block);
    // block_scope 已弹出,现在可向 parent_gz 添加新指令。
    try parent_gz.instructions.append(astgen.gpa, block);

    var then_scope = parent_gz.makeSubBlock(scope);
    defer then_scope.unstack();

    var payload_val_scope: Scope.LocalVal = undefined;

    const then_node = if_full.ast.then_expr;
    const then_sub_scope = s: {
        if (if_full.error_token != null) {
            if (if_full.payload_token) |payload_token| {
                const tag: Zir.Inst.Tag = if (payload_is_ref)
                    .err_union_payload_unsafe_ptr
                else
                    .err_union_payload_unsafe;
                const payload_inst = try then_scope.addUnNode(tag, cond.inst, then_node);
                const token_name_index = payload_token + @intFromBool(payload_is_ref);
                const ident_name = try astgen.identAsString(token_name_index);
                const token_name_str = tree.tokenSlice(token_name_index);
                if (mem.eql(u8, "_", token_name_str)) {
                    if (payload_is_ref) return astgen.failTok(payload_token, "pointer modifier invalid on discard", .{});
                    break :s &then_scope.base;
                }
                try astgen.detectLocalShadowing(&then_scope.base, ident_name, token_name_index, token_name_str, .capture);
                payload_val_scope = .{
                    .parent = &then_scope.base,
                    .gen_zir = &then_scope,
                    .name = ident_name,
                    .inst = payload_inst,
                    .token_src = token_name_index,
                    .id_cat = .capture,
                };
                try then_scope.addDbgVar(.dbg_var_val, ident_name, payload_inst);
                break :s &payload_val_scope.base;
            } else {
                _ = try then_scope.addUnNode(.ensure_err_union_payload_void, cond.inst, node);
                break :s &then_scope.base;
            }
        } else if (if_full.payload_token) |payload_token| {
            const ident_token = payload_token + @intFromBool(payload_is_ref);
            const tag: Zir.Inst.Tag = if (payload_is_ref)
                .optional_payload_unsafe_ptr
            else
                .optional_payload_unsafe;
            const ident_bytes = tree.tokenSlice(ident_token);
            if (mem.eql(u8, "_", ident_bytes)) {
                if (payload_is_ref) return astgen.failTok(payload_token, "pointer modifier invalid on discard", .{});
                break :s &then_scope.base;
            }
            const payload_inst = try then_scope.addUnNode(tag, cond.inst, then_node);
            const ident_name = try astgen.identAsString(ident_token);
            try astgen.detectLocalShadowing(&then_scope.base, ident_name, ident_token, ident_bytes, .capture);
            payload_val_scope = .{
                .parent = &then_scope.base,
                .gen_zir = &then_scope,
                .name = ident_name,
                .inst = payload_inst,
                .token_src = ident_token,
                .id_cat = .capture,
            };
            try then_scope.addDbgVar(.dbg_var_val, ident_name, payload_inst);
            break :s &payload_val_scope.base;
        } else {
            break :s &then_scope.base;
        }
    };

    const then_result = try fullBodyExpr(&then_scope, then_sub_scope, block_scope.break_result_info, then_node, .allow_branch_hint);
    try checkUsed(parent_gz, &then_scope.base, then_sub_scope);
    if (!then_scope.endsWithNoReturn()) {
        _ = try then_scope.addBreakWithSrcNode(.@"break", block, then_result, then_node);
    }

    var else_scope = parent_gz.makeSubBlock(scope);
    defer else_scope.unstack();

    // 已知操作数(几乎肯定)修改了错误返回跟踪,
    // 因此通知 Sema 保存新的索引,以便稍后恢复。
    if (do_err_trace and nodeMayAppendToErrorTrace(tree, if_full.ast.cond_expr))
        _ = try else_scope.addSaveErrRetIndex(.always);

    if (if_full.ast.else_expr.unwrap()) |else_node| {
        const sub_scope = s: {
            if (if_full.error_token) |error_token| {
                const tag: Zir.Inst.Tag = if (payload_is_ref)
                    .err_union_code_ptr
                else
                    .err_union_code;
                const payload_inst = try else_scope.addUnNode(tag, cond.inst, if_full.ast.cond_expr);
                const ident_name = try astgen.identAsString(error_token);
                const error_token_str = tree.tokenSlice(error_token);
                if (mem.eql(u8, "_", error_token_str))
                    break :s &else_scope.base;
                try astgen.detectLocalShadowing(&else_scope.base, ident_name, error_token, error_token_str, .capture);
                payload_val_scope = .{
                    .parent = &else_scope.base,
                    .gen_zir = &else_scope,
                    .name = ident_name,
                    .inst = payload_inst,
                    .token_src = error_token,
                    .id_cat = .capture,
                };
                try else_scope.addDbgVar(.dbg_var_val, ident_name, payload_inst);
                break :s &payload_val_scope.base;
            } else {
                break :s &else_scope.base;
            }
        };
        const else_result = else_result: {
            if (tree.fullSwitch(else_node)) |switch_full| no_switch_on_err: {
                const error_token = if_full.error_token orelse break :no_switch_on_err;
                if (switch_full.label_token == null) break :no_switch_on_err; // 必须使用带有 `non_err = .@"if"` 的 `switchExpr`
                if (tree.nodeTag(switch_full.ast.condition) != .identifier) break :no_switch_on_err;
                if (!try astgen.tokenIdentEql(error_token, tree.nodeMainToken(switch_full.ast.condition))) break :no_switch_on_err;
                break :else_result try switchExpr(
                    &else_scope,
                    sub_scope,
                    block_scope.break_result_info,
                    else_node,
                    switch_full,
                    .{ .peer_break_target = .{
                        .block_inst = block,
                        .block_ri = block_ri,
                    } },
                );
            }
            break :else_result try fullBodyExpr(&else_scope, sub_scope, block_scope.break_result_info, else_node, .allow_branch_hint);
        };
        if (!else_scope.endsWithNoReturn()) {
            // 作为 break 前最后一个操作,必要时“弹出”错误跟踪
            if (do_err_trace)
                try restoreErrRetIndex(&else_scope, .{ .block = block }, block_scope.break_result_info, else_node, else_result);
            _ = try else_scope.addBreakWithSrcNode(.@"break", block, else_result, else_node);
        }
        try checkUsed(parent_gz, &else_scope.base, sub_scope);
    } else {
        const result = try rvalue(&else_scope, ri, .void_value, node);
        _ = try else_scope.addBreak(.@"break", block, result);
    }

    try setCondBrPayload(condbr, cond.bool_bit, &then_scope, &else_scope);

    if (need_result_rvalue) {
        return rvalue(parent_gz, ri, block.toRef(), node);
    } else {
        return block.toRef();
    }
}

/// 支持 `else_scope` 叠加于 `then_scope`。先退出 `else_scope`,再退出 `then_scope`。
fn setCondBrPayload(
    condbr: Zir.Inst.Index,
    cond: Zir.Inst.Ref,
    then_scope: *GenZir,
    else_scope: *GenZir,
) !void {
    defer then_scope.unstack();
    defer else_scope.unstack();
    const astgen = then_scope.astgen;
    const then_body = then_scope.instructionsSliceUpto(else_scope);
    const else_body = else_scope.instructionsSlice();
    const then_body_len = astgen.countBodyLenAfterFixups(then_body);
    const else_body_len = astgen.countBodyLenAfterFixups(else_body);
    try astgen.extra.ensureUnusedCapacity(
        astgen.gpa,
        @typeInfo(Zir.Inst.CondBr).@"struct".field_names.len + then_body_len + else_body_len,
    );

    const zir_datas = astgen.instructions.items(.data);
    zir_datas[@backingInt(condbr)].pl_node.payload_index = astgen.addExtraAssumeCapacity(Zir.Inst.CondBr{
        .condition = cond,
        .then_body_len = then_body_len,
        .else_body_len = else_body_len,
    });
    astgen.appendBodyWithFixups(then_body);
    astgen.appendBodyWithFixups(else_body);
}

fn whileExpr(
    parent_gz: *GenZir,
    scope: *Scope,
    ri: ResultInfo,
    node: Ast.Node.Index,
    while_full: Ast.full.While,
    is_statement: bool,
) InnerError!Zir.Inst.Ref {
    const astgen = parent_gz.astgen;
    const tree = astgen.tree;

    const need_rl = astgen.nodes_need_rl.contains(node);
    const block_ri: ResultInfo = if (need_rl) ri else .{
        .rl = switch (ri.rl) {
            .ptr => .{ .ty = (try ri.rl.resultType(parent_gz, node)).? },
            .inferred_ptr => .none,
            else => ri.rl,
        },
        .ctx = ri.ctx,
    };
    // 仅当已有结果指针且未转发该指针时,才需调用 `rvalue` 通过指针写入。
    //
    const LocTag = @typeInfo(ResultInfo.Loc).@"union".tag_type.?;
    const need_result_rvalue = @as(LocTag, block_ri.rl) != @as(LocTag, ri.rl);

    if (while_full.label_token) |label_token| {
        try astgen.checkLabelRedefinition(scope, label_token);
    }

    const is_inline = while_full.inline_token != null;
    if (parent_gz.is_comptime and is_inline) {
        try astgen.appendErrorTok(while_full.inline_token.?, "redundant inline keyword in comptime scope", .{});
    }
    const loop_tag: Zir.Inst.Tag = if (is_inline) .block_inline else .loop;
    const loop_block = try parent_gz.makeBlockInst(loop_tag, node);
    try parent_gz.instructions.append(astgen.gpa, loop_block);

    var loop_scope = parent_gz.makeSubBlock(scope);
    loop_scope.is_inline = is_inline;
    defer loop_scope.unstack();

    var cond_scope = parent_gz.makeSubBlock(&loop_scope.base);
    defer cond_scope.unstack();

    const payload_is_ref = if (while_full.payload_token) |payload_token|
        tree.tokenTag(payload_token) == .asterisk
    else
        false;

    try emitDbgNode(parent_gz, while_full.ast.cond_expr);
    const cond: struct {
        inst: Zir.Inst.Ref,
        bool_bit: Zir.Inst.Ref,
    } = c: {
        if (while_full.error_token) |_| {
            const cond_ri: ResultInfo = .{ .rl = if (payload_is_ref) .ref else .none };
            const err_union = try fullBodyExpr(&cond_scope, &cond_scope.base, cond_ri, while_full.ast.cond_expr, .normal);
            const tag: Zir.Inst.Tag = if (payload_is_ref) .is_non_err_ptr else .is_non_err;
            break :c .{
                .inst = err_union,
                .bool_bit = try cond_scope.addUnNode(tag, err_union, while_full.ast.cond_expr),
            };
        } else if (while_full.payload_token) |_| {
            const cond_ri: ResultInfo = .{ .rl = if (payload_is_ref) .ref else .none };
            const optional = try fullBodyExpr(&cond_scope, &cond_scope.base, cond_ri, while_full.ast.cond_expr, .normal);
            const tag: Zir.Inst.Tag = if (payload_is_ref) .is_non_null_ptr else .is_non_null;
            break :c .{
                .inst = optional,
                .bool_bit = try cond_scope.addUnNode(tag, optional, while_full.ast.cond_expr),
            };
        } else {
            const cond = try fullBodyExpr(&cond_scope, &cond_scope.base, coerced_bool_ri, while_full.ast.cond_expr, .normal);
            break :c .{
                .inst = cond,
                .bool_bit = cond,
            };
        }
    };

    const condbr_tag: Zir.Inst.Tag = if (is_inline) .condbr_inline else .condbr;
    const condbr = try cond_scope.addCondBr(condbr_tag, node);
    const block_tag: Zir.Inst.Tag = if (is_inline) .block_inline else .block;
    const cond_block = try loop_scope.makeBlockInst(block_tag, node);
    try cond_scope.setBlockBody(cond_block);
    // cond_scope 现已退出,可向 loop_scope 添加新指令
    try loop_scope.instructions.append(astgen.gpa, cond_block);

    // 现在创建作用域,但在下方输出并添加 cont_expr,
    // 且 loop_scope 出栈之前,不将其压入 parent_gz。
    var then_scope = parent_gz.makeSubBlock(&cond_scope.base);
    then_scope.instructions_top = GenZir.unstacked_top;
    defer then_scope.unstack();

    var dbg_var_name: Zir.NullTerminatedString = .empty;
    var dbg_var_inst: Zir.Inst.Ref = undefined;
    var opt_payload_inst: Zir.Inst.OptionalIndex = .none;
    var payload_val_scope: Scope.LocalVal = undefined;
    const then_sub_scope = s: {
        if (while_full.error_token != null) {
            if (while_full.payload_token) |payload_token| {
                const tag: Zir.Inst.Tag = if (payload_is_ref)
                    .err_union_payload_unsafe_ptr
                else
                    .err_union_payload_unsafe;
                // 将在下方将此指令添加到 then_scope.instructions。
                const payload_inst = try then_scope.makeUnNode(tag, cond.inst, while_full.ast.cond_expr);
                opt_payload_inst = payload_inst.toOptional();
                const ident_token = payload_token + @intFromBool(payload_is_ref);
                const ident_bytes = tree.tokenSlice(ident_token);
                if (mem.eql(u8, "_", ident_bytes)) {
                    if (payload_is_ref) return astgen.failTok(payload_token, "pointer modifier invalid on discard", .{});
                    break :s &then_scope.base;
                }
                const ident_name = try astgen.identAsString(ident_token);
                try astgen.detectLocalShadowing(&then_scope.base, ident_name, ident_token, ident_bytes, .capture);
                payload_val_scope = .{
                    .parent = &then_scope.base,
                    .gen_zir = &then_scope,
                    .name = ident_name,
                    .inst = payload_inst.toRef(),
                    .token_src = ident_token,
                    .id_cat = .capture,
                };
                dbg_var_name = ident_name;
                dbg_var_inst = payload_inst.toRef();
                break :s &payload_val_scope.base;
            } else {
                _ = try then_scope.addUnNode(.ensure_err_union_payload_void, cond.inst, node);
                break :s &then_scope.base;
            }
        } else if (while_full.payload_token) |payload_token| {
            const tag: Zir.Inst.Tag = if (payload_is_ref)
                .optional_payload_unsafe_ptr
            else
                .optional_payload_unsafe;
            // 将在下方将此指令添加到 then_scope.instructions。
            const payload_inst = try then_scope.makeUnNode(tag, cond.inst, while_full.ast.cond_expr);
            opt_payload_inst = payload_inst.toOptional();
            const ident_token = payload_token + @intFromBool(payload_is_ref);
            const ident_name = try astgen.identAsString(ident_token);
            const ident_bytes = tree.tokenSlice(ident_token);
            if (mem.eql(u8, "_", ident_bytes)) {
                if (payload_is_ref) return astgen.failTok(payload_token, "pointer modifier invalid on discard", .{});
                break :s &then_scope.base;
            }
            try astgen.detectLocalShadowing(&then_scope.base, ident_name, ident_token, ident_bytes, .capture);
            payload_val_scope = .{
                .parent = &then_scope.base,
                .gen_zir = &then_scope,
                .name = ident_name,
                .inst = payload_inst.toRef(),
                .token_src = ident_token,
                .id_cat = .capture,
            };
            dbg_var_name = ident_name;
            dbg_var_inst = payload_inst.toRef();
            break :s &payload_val_scope.base;
        } else {
            break :s &then_scope.base;
        }
    };

    var continue_scope = parent_gz.makeSubBlock(then_sub_scope);
    continue_scope.instructions_top = GenZir.unstacked_top;
    defer continue_scope.unstack();
    const continue_block = try then_scope.makeBlockInst(block_tag, node);

    const repeat_tag: Zir.Inst.Tag = if (is_inline) .repeat_inline else .repeat;
    _ = try loop_scope.addNode(repeat_tag, node);

    try loop_scope.setBlockBody(loop_block);
    if (while_full.label_token) |label_token| {
        loop_scope.label = .{ .token = label_token };
    }
    loop_scope.allow_unlabeled_control_flow = true;
    loop_scope.break_target = loop_block;
    loop_scope.continue_target = .{ .@"break" = continue_block };
    loop_scope.setBreakResultInfo(block_ri);

    // 向 loop_scope 添加指令已完成,现在可以压入 then_scope
    then_scope.instructions_top = then_scope.instructions.items.len;

    const then_node = while_full.ast.then_expr;
    if (opt_payload_inst.unwrap()) |payload_inst| {
        try then_scope.instructions.append(astgen.gpa, payload_inst);
    }
    if (dbg_var_name != .empty) try then_scope.addDbgVar(.dbg_var_val, dbg_var_name, dbg_var_inst);
    try then_scope.instructions.append(astgen.gpa, continue_block);
    // 可以改进此代码:如果没有跳转到 continue 表达式,就不生成它。
    // 这会发生在 while 循环体的最后一条语句为 noreturn,
    // 且没有 `continue` 语句时。
    // 跟踪问题:https://github.com/ziglang/zig/issues/9185
    if (while_full.ast.cont_expr.unwrap()) |cont_expr| {
        _ = try unusedResultExpr(&then_scope, then_sub_scope, cont_expr);
    }

    continue_scope.instructions_top = continue_scope.instructions.items.len;
    {
        try emitDbgNode(&continue_scope, then_node);
        const unused_result = try fullBodyExpr(&continue_scope, &continue_scope.base, .{ .rl = .none }, then_node, .allow_branch_hint);
        _ = try addEnsureResult(&continue_scope, unused_result, then_node);
    }
    try checkUsed(parent_gz, &then_scope.base, then_sub_scope);
    const break_tag: Zir.Inst.Tag = if (is_inline) .break_inline else .@"break";
    if (!continue_scope.endsWithNoReturn()) {
        astgen.advanceSourceCursor(tree.tokenStart(tree.lastToken(then_node)));
        try emitDbgStmt(parent_gz, .{ astgen.source_line - parent_gz.decl_line, astgen.source_column });
        _ = try parent_gz.add(.{
            .tag = .extended,
            .data = .{ .extended = .{
                .opcode = .dbg_empty_stmt,
                .small = undefined,
                .operand = undefined,
            } },
        });
        if (!continue_scope.is_comptime) {
            _ = try continue_scope.addRestoreErrRetIndex(.{ .block = continue_block }, .always, then_node);
        }
        _ = try continue_scope.addBreak(break_tag, continue_block, .void_value);
    }
    try continue_scope.setBlockBody(continue_block);
    if (!then_scope.is_comptime) {
        const cont_node = while_full.ast.cont_expr.unwrap() orelse then_node;
        _ = try then_scope.addRestoreErrRetIndex(.{ .block = cond_block }, .always, cont_node);
    }
    _ = try then_scope.addBreak(break_tag, cond_block, .void_value);

    var else_scope = parent_gz.makeSubBlock(&cond_scope.base);
    defer else_scope.unstack();

    if (while_full.ast.else_expr.unwrap()) |else_node| {
        const sub_scope = s: {
            if (while_full.error_token) |error_token| {
                const tag: Zir.Inst.Tag = if (payload_is_ref)
                    .err_union_code_ptr
                else
                    .err_union_code;
                const else_payload_inst = try else_scope.addUnNode(tag, cond.inst, while_full.ast.cond_expr);
                const ident_name = try astgen.identAsString(error_token);
                const ident_bytes = tree.tokenSlice(error_token);
                if (mem.eql(u8, ident_bytes, "_"))
                    break :s &else_scope.base;
                try astgen.detectLocalShadowing(&else_scope.base, ident_name, error_token, ident_bytes, .capture);
                payload_val_scope = .{
                    .parent = &else_scope.base,
                    .gen_zir = &else_scope,
                    .name = ident_name,
                    .inst = else_payload_inst,
                    .token_src = error_token,
                    .id_cat = .capture,
                };
                try else_scope.addDbgVar(.dbg_var_val, ident_name, else_payload_inst);
                break :s &payload_val_scope.base;
            } else {
                break :s &else_scope.base;
            }
        };
        // 禁止无标签控制流进入此作用域,使无标签的 `continue`
        // 和 `break` 作用于外层循环,而非本循环。
        // 也禁止以本循环标签为目标的 `continue`。
        loop_scope.allow_unlabeled_control_flow = false;
        loop_scope.continue_target = .none;
        const else_result = try fullBodyExpr(&else_scope, sub_scope, loop_scope.break_result_info, else_node, .allow_branch_hint);
        if (is_statement) {
            _ = try addEnsureResult(&else_scope, else_result, else_node);
        }

        try checkUsed(parent_gz, &else_scope.base, sub_scope);
        if (!else_scope.endsWithNoReturn()) {
            if (!else_scope.is_comptime) {
                _ = try else_scope.addRestoreErrRetIndex(.{ .block = loop_block }, .always, else_node);
            }
            _ = try else_scope.addBreakWithSrcNode(break_tag, loop_block, else_result, else_node);
        }
    } else {
        const result = try rvalue(&else_scope, ri, .void_value, node);
        _ = try else_scope.addBreak(break_tag, loop_block, result);
    }

    if (loop_scope.label) |some| {
        if (!some.used) {
            try astgen.appendErrorTok(some.token, "unused while loop label", .{});
        }
    }

    try setCondBrPayload(condbr, cond.bool_bit, &then_scope, &else_scope);

    const result = if (need_result_rvalue)
        try rvalue(parent_gz, ri, loop_block.toRef(), node)
    else
        loop_block.toRef();

    if (is_statement) {
        _ = try parent_gz.addUnNode(.ensure_result_used, result, node);
    }

    return result;
}

fn forExpr(
    parent_gz: *GenZir,
    scope: *Scope,
    ri: ResultInfo,
    node: Ast.Node.Index,
    for_full: Ast.full.For,
    is_statement: bool,
) InnerError!Zir.Inst.Ref {
    const astgen = parent_gz.astgen;

    if (for_full.label_token) |label_token| {
        try astgen.checkLabelRedefinition(scope, label_token);
    }

    const need_rl = astgen.nodes_need_rl.contains(node);
    const block_ri: ResultInfo = if (need_rl) ri else .{
        .rl = switch (ri.rl) {
            .ptr => .{ .ty = (try ri.rl.resultType(parent_gz, node)).? },
            .inferred_ptr => .none,
            else => ri.rl,
        },
        .ctx = ri.ctx,
    };
    // 仅当已有结果指针且未转发该指针时,才需调用 `rvalue` 通过指针写入。
    //
    const LocTag = @typeInfo(ResultInfo.Loc).@"union".tag_type.?;
    const need_result_rvalue = @as(LocTag, block_ri.rl) != @as(LocTag, ri.rl);

    const is_inline = for_full.inline_token != null;
    if (parent_gz.is_comptime and is_inline) {
        try astgen.appendErrorTok(for_full.inline_token.?, "redundant inline keyword in comptime scope", .{});
    }
    const tree = astgen.tree;
    const gpa = astgen.gpa;

    // 对计数器而言,这是起始值;对可索引对象而言,这是可供 elem_ptr 等指令使用的基指针。
    // 特殊值 `none` 表示这是一个起始值为零的计数器,可直接使用主索引计数器。
    //
    //
    const indexables = try gpa.alloc(Zir.Inst.Ref, for_full.ast.inputs.len);
    defer gpa.free(indexables);
    // 此数组的元素可以为 `none`,表示不检查长度。
    const lens = try gpa.alloc([2]Zir.Inst.Ref, for_full.ast.inputs.len);
    defer gpa.free(lens);

    // 无论有多少可索引项,都使用单个从零开始的计数器。
    const index_ptr = blk: {
        const alloc_tag: Zir.Inst.Tag = if (is_inline) .alloc_comptime_mut else .alloc;
        const index_ptr = try parent_gz.addUnNode(alloc_tag, .usize_type, node);
        // 初始化为零
        _ = try parent_gz.addPlNode(.store_node, node, Zir.Inst.Bin{
            .lhs = index_ptr,
            .rhs = .zero_usize,
        });
        break :blk index_ptr;
    };

    var any_len_checks = false;

    {
        var capture_token = for_full.payload_token;
        for (for_full.ast.inputs, indexables, lens) |input, *indexable_ref, *len_refs| {
            const capture_is_ref = tree.tokenTag(capture_token) == .asterisk;
            const ident_tok = capture_token + @intFromBool(capture_is_ref);
            if (tree.tokenTag(ident_tok) != .identifier) {
                return astgen.failNode(input, "for input is not captured", .{});
            }
            const is_discard = mem.eql(u8, tree.tokenSlice(ident_tok), "_");

            if (is_discard and capture_is_ref) {
                return astgen.failTok(capture_token, "pointer modifier invalid on discard", .{});
            }
            // 跳过逗号,移动到下一个捕获或结束管道字符。
            capture_token = ident_tok + 2;

            try emitDbgNode(parent_gz, input);
            if (tree.nodeTag(input) == .for_range) {
                if (capture_is_ref) {
                    return astgen.failTok(ident_tok, "cannot capture reference to range", .{});
                }
                const start_node, const end_node = tree.nodeData(input).node_and_opt_node;
                const start_val = try expr(parent_gz, scope, .{ .rl = .{ .ty = .usize_type } }, start_node);

                const end_val = if (end_node.unwrap()) |end|
                    try expr(parent_gz, scope, .{ .rl = .{ .ty = .usize_type } }, end)
                else
                    .none;

                if (end_val == .none and is_discard) {
                    try astgen.appendErrorTok(ident_tok, "discard of unbounded counter", .{});
                }

                if (end_val == .none) {
                    len_refs.* = .{ .none, .none };
                } else {
                    any_len_checks = true;
                    len_refs.* = .{ start_val, end_val };
                }

                const start_is_zero = nodeIsTriviallyZero(tree, start_node);
                indexable_ref.* = if (start_is_zero) .none else start_val;
            } else {
                const indexable = try expr(parent_gz, scope, .{ .rl = .none }, input);

                any_len_checks = true;
                indexable_ref.* = indexable;
                len_refs.* = .{ indexable, .none };
            }
        }
        // 最后一个捕获项之后可能存在尾随逗号,也可能不存在。
        if (tree.tokenTag(capture_token) != .pipe and tree.tokenTag(capture_token - 1) != .pipe) {
            return astgen.failTok(capture_token, "extra capture in for loop", .{});
        }
    }

    if (!any_len_checks) {
        return astgen.failNode(node, "unbounded for loop", .{});
    }

    // 使用专用 ZIR 指令断言长度,以便
    // 提供更好的错误报告,并减少生成的 ZIR 字节数。
    const len: Zir.Inst.Ref = len: {
        const all_lens = @as([*]Zir.Inst.Ref, @ptrCast(lens))[0 .. lens.len * 2];
        const lens_len: u32 = @intCast(all_lens.len);
        try astgen.extra.ensureUnusedCapacity(gpa, @typeInfo(Zir.Inst.MultiOp).@"struct".field_names.len + lens_len);
        const len = try parent_gz.addPlNode(.for_len, node, Zir.Inst.MultiOp{
            .operands_len = lens_len,
        });
        appendRefsAssumeCapacity(astgen, all_lens);
        break :len len;
    };

    const loop_tag: Zir.Inst.Tag = if (is_inline) .block_inline else .loop;
    const loop_block = try parent_gz.makeBlockInst(loop_tag, node);
    try parent_gz.instructions.append(gpa, loop_block);

    var loop_scope = parent_gz.makeSubBlock(scope);
    loop_scope.is_inline = is_inline;
    loop_scope.setBreakResultInfo(block_ri);
    defer loop_scope.unstack();

    // 需要等获得 then_scope 中延迟处理的引用后,才能完成 loop_scope。
    // 但在此期间必须从指令中移除 load,否则它看起来会属于 parent_gz。
    const index = try loop_scope.addUnNode(.load, index_ptr, node);
    _ = loop_scope.instructions.pop();

    var cond_scope = parent_gz.makeSubBlock(&loop_scope.base);
    defer cond_scope.unstack();

    // 检查条件。
    const cond = try cond_scope.addPlNode(.cmp_lt, node, Zir.Inst.Bin{
        .lhs = index,
        .rhs = len,
    });

    const condbr_tag: Zir.Inst.Tag = if (is_inline) .condbr_inline else .condbr;
    const condbr = try cond_scope.addCondBr(condbr_tag, node);
    const block_tag: Zir.Inst.Tag = if (is_inline) .block_inline else .block;
    const cond_block = try loop_scope.makeBlockInst(block_tag, node);
    try cond_scope.setBlockBody(cond_block);

    if (for_full.label_token) |label_token| {
        loop_scope.label = .{ .token = label_token };
    }
    loop_scope.allow_unlabeled_control_flow = true;
    loop_scope.break_target = loop_block;
    loop_scope.continue_target = .{ .@"break" = cond_block };

    const then_node = for_full.ast.then_expr;
    var then_scope = parent_gz.makeSubBlock(&cond_scope.base);
    defer then_scope.unstack();

    const capture_scopes = try gpa.alloc(Scope.LocalVal, for_full.ast.inputs.len);
    defer gpa.free(capture_scopes);

    const then_sub_scope = blk: {
        var capture_token = for_full.payload_token;
        var capture_sub_scope: *Scope = &then_scope.base;
        for (for_full.ast.inputs, indexables, capture_scopes) |input, indexable_ref, *capture_scope| {
            const capture_is_ref = tree.tokenTag(capture_token) == .asterisk;
            const ident_tok = capture_token + @intFromBool(capture_is_ref);
            const capture_name = tree.tokenSlice(ident_tok);
            // 跳过逗号,移动到下一个捕获或结束管道字符。
            capture_token = ident_tok + 2;

            if (mem.eql(u8, capture_name, "_")) continue;

            const name_str_index = try astgen.identAsString(ident_tok);
            try astgen.detectLocalShadowing(capture_sub_scope, name_str_index, ident_tok, capture_name, .capture);

            const capture_inst = inst: {
                const is_counter = tree.nodeTag(input) == .for_range;

                if (indexable_ref == .none) {
                    // 特殊情况:可以直接使用主索引。
                    assert(is_counter);
                    assert(!capture_is_ref);
                    break :inst index;
                }

                // 对于计数器,将索引变量加到起始值;
                // 对于可索引对象,将其用作元素索引。二者足够相似,
                // 因此可共享同一代码路径,
                // 仅根据 ZIR 标签分支。
                const switch_cond = (@as(u2, @intFromBool(capture_is_ref)) << 1) | @intFromBool(is_counter);
                const tag: Zir.Inst.Tag = switch (switch_cond) {
                    0b00 => .elem_val,
                    0b01 => .add,
                    0b10 => .elem_ptr,
                    0b11 => unreachable, // 已发出编译错误
                };
                break :inst try then_scope.addPlNode(tag, input, Zir.Inst.Bin{
                    .lhs = indexable_ref,
                    .rhs = index,
                });
            };

            capture_scope.* = .{
                .parent = capture_sub_scope,
                .gen_zir = &then_scope,
                .name = name_str_index,
                .inst = capture_inst,
                .token_src = ident_tok,
                .id_cat = .capture,
            };

            try then_scope.addDbgVar(.dbg_var_val, name_str_index, capture_inst);
            capture_sub_scope = &capture_scope.base;
        }

        break :blk capture_sub_scope;
    };

    const then_result = try fullBodyExpr(&then_scope, then_sub_scope, .{ .rl = .none }, then_node, .allow_branch_hint);
    _ = try addEnsureResult(&then_scope, then_result, then_node);

    try checkUsed(parent_gz, &then_scope.base, then_sub_scope);

    astgen.advanceSourceCursor(tree.tokenStart(tree.lastToken(then_node)));
    try emitDbgStmt(parent_gz, .{ astgen.source_line - parent_gz.decl_line, astgen.source_column });
    _ = try parent_gz.add(.{
        .tag = .extended,
        .data = .{ .extended = .{
            .opcode = .dbg_empty_stmt,
            .small = undefined,
            .operand = undefined,
        } },
    });

    const break_tag: Zir.Inst.Tag = if (is_inline) .break_inline else .@"break";
    if (!then_scope.is_comptime) {
        _ = try then_scope.addRestoreErrRetIndex(.{ .block = cond_block }, .always, then_node);
    }
    _ = try then_scope.addBreak(break_tag, cond_block, .void_value);

    var else_scope = parent_gz.makeSubBlock(&cond_scope.base);
    defer else_scope.unstack();

    if (for_full.ast.else_expr.unwrap()) |else_node| {
        const sub_scope = &else_scope.base;
        // 禁止无标签控制流进入此作用域,使无标签的 `continue`
        // 和 `break` 作用于外层循环,而非本循环。
        // 也禁止以本循环标签为目标的 `continue`。
        loop_scope.allow_unlabeled_control_flow = false;
        loop_scope.continue_target = .none;
        const else_result = try fullBodyExpr(&else_scope, sub_scope, loop_scope.break_result_info, else_node, .allow_branch_hint);
        if (is_statement) {
            _ = try addEnsureResult(&else_scope, else_result, else_node);
        }
        if (!else_scope.endsWithNoReturn()) {
            if (!else_scope.is_comptime) {
                _ = try else_scope.addRestoreErrRetIndex(.{ .block = loop_block }, .always, else_node);
            }
            _ = try else_scope.addBreakWithSrcNode(break_tag, loop_block, else_result, else_node);
        }
    } else {
        const result = try rvalue(&else_scope, ri, .void_value, node);
        _ = try else_scope.addBreak(break_tag, loop_block, result);
    }

    if (loop_scope.label) |some| {
        if (!some.used) {
            try astgen.appendErrorTok(some.token, "unused for loop label", .{});
        }
    }

    try setCondBrPayload(condbr, cond, &then_scope, &else_scope);

    // then_block 和 else_block 现已退出,可恢复 loop_scope 并最终完成它
    {
        loop_scope.instructions_top = loop_scope.instructions.items.len;
        try loop_scope.instructions.appendSlice(gpa, &.{ index.toIndex().?, cond_block });

        // 递增索引变量。
        const index_plus_one = try loop_scope.addPlNode(.add_unsafe, node, Zir.Inst.Bin{
            .lhs = index,
            .rhs = .one_usize,
        });
        _ = try loop_scope.addPlNode(.store_node, node, Zir.Inst.Bin{
            .lhs = index_ptr,
            .rhs = index_plus_one,
        });

        const repeat_tag: Zir.Inst.Tag = if (is_inline) .repeat_inline else .repeat;
        _ = try loop_scope.addNode(repeat_tag, node);

        try loop_scope.setBlockBody(loop_block);
    }

    const result = if (need_result_rvalue)
        try rvalue(parent_gz, ri, loop_block.toRef(), node)
    else
        loop_block.toRef();

    if (is_statement) {
        _ = try parent_gz.addUnNode(.ensure_result_used, result, node);
    }
    return result;
}

const SwitchNonErr = union(enum) {
    /// 常规 switch 表达式。
    /// 生成 `switch_block[_ref]`。
    none,
    /// `eu catch |err| switch (err) { ... }`
    ///
    /// `switch` 不得带标签。
    /// 生成 `switch_block_err_union`。
    @"catch",
    /// `if (eu) |payload| { ... } else |err| switch (err) { ... }`
    ///
    /// `switch` 不得带标签。
    /// 输出 `switch_block_err_union`。
    @"if": Ast.full.If,
    /// `eu catch |err| label: switch (err) { ... }`
    /// `if (eu) |payload| { ... } else |err| label: switch (err) { ... }`
    ///
    /// `switch` 必须带有标签。
    /// 为非错误分支体生成 `condbr`,并生成普通 switch;但非错误
    /// 分支与所有 switch 分支中的 `break` 均参与同级类型解析。
    /// 此指令用于避免 `switch_block_err_union` 中相当复杂的特殊情况。
    peer_break_target: struct {
        /// 引用整个基于错误值执行 switch 的表达式的外层块。
        block_inst: Zir.Inst.Index,
        /// 属于 `block_inst`。
        block_ri: ResultInfo,
    },
};

fn switchExpr(
    parent_gz: *GenZir,
    scope: *Scope,
    ri: ResultInfo,
    node: Ast.Node.Index,
    switch_full: Ast.full.Switch,
    non_err: SwitchNonErr,
) InnerError!Zir.Inst.Ref {
    const astgen = parent_gz.astgen;
    const gpa = astgen.gpa;
    const tree = astgen.tree;

    const switch_node, const operand_node, const err_token = switch (non_err) {
        .none, .peer_break_target => .{
            node,
            switch_full.ast.condition,
            undefined,
        },
        .@"catch" => .{
            tree.nodeData(node).node_and_node[1],
            tree.nodeData(node).node_and_node[0],
            tree.nodeMainToken(node) + 2,
        },
        .@"if" => |if_full| .{
            if_full.ast.else_expr.unwrap().?,
            if_full.ast.cond_expr,
            if_full.error_token.?,
        },
    };
    const case_nodes = switch_full.ast.cases;

    const is_err_switch = non_err != .none;
    const needs_non_err_handling = switch (non_err) {
        .none => false,
        .peer_break_target => false, // 由父表达式处理
        .@"catch", .@"if" => true,
    };

    const need_rl = astgen.nodes_need_rl.contains(node);
    const block_ri: ResultInfo = if (need_rl) ri else .{
        .rl = switch (ri.rl) {
            .ptr => .{ .ty = (try ri.rl.resultType(parent_gz, node)).? },
            .inferred_ptr => .none,
            else => ri.rl,
        },
        .ctx = ri.ctx,
    };

    // 仅当已有结果指针且未转发该指针时,才需调用 `rvalue` 通过指针写入。
    //
    const LocTag = @typeInfo(ResultInfo.Loc).@"union".tag_type.?;
    const need_result_rvalue = @as(LocTag, block_ri.rl) != @as(LocTag, ri.rl);

    const catch_or_if_node = if (needs_non_err_handling) node else undefined;
    const do_err_trace = needs_non_err_handling and astgen.fn_block != null;
    const non_err_is_ref: enum { no, yes, yes_const } = switch (non_err) {
        .none, .peer_break_target => undefined,
        .@"catch" => switch (ri.rl) {
            .ref, .ref_coerced_ty => .yes,
            .ref_const => .yes_const,
            else => .no,
        },
        .@"if" => |if_full| if (if_full.payload_token != null and
            tree.tokenTag(if_full.payload_token.?) == .asterisk) .yes else .no,
    };

    if (switch_full.label_token) |label_token| {
        try astgen.checkLabelRedefinition(scope, label_token);
    }

    const err_capture_name: Zir.NullTerminatedString = if (needs_non_err_handling) blk: {
        const err_str = tree.tokenSlice(err_token);
        if (mem.eql(u8, err_str, "_")) {
            // 这是致命错误,因为已知正在对捕获的错误进行 switch 分支选择。
            return astgen.failTok(err_token, "discard of error capture; omit it instead", .{});
        }
        const err_name = try astgen.identAsString(err_token);
        try astgen.detectLocalShadowing(scope, err_name, err_token, err_str, .capture);
        break :blk err_name;
    } else undefined;

    // 我们遍历 AST 两次。第一次遍历用于收集
    // 以下变量的信息,记录特殊分支的 AST 节点索引,
    // 并在存在不兼容的特殊分支时以编译错误中止。
    var any_payload_is_ref = false;
    var any_has_payload_capture = false;
    var any_has_tag_capture = false;
    var any_maybe_runtime_capture = false;
    var scalar_cases_len: u32 = 0;
    var multi_cases_len: u32 = 0;
    var total_items_len: usize = 0;
    var total_ranges_len: usize = 0;
    var else_case_node: Ast.Node.OptionalIndex = .none;
    var underscore_node: Ast.Node.OptionalIndex = .none;
    for (case_nodes) |case_node| {
        const case = tree.fullSwitchCase(case_node).?;
        if (case.payload_token) |payload_token| {
            const ident = if (tree.tokenTag(payload_token) == .asterisk) blk: {
                // 始终不允许按引用捕获错误,但由于稍后
                // 会再次检查此条件,因此尽可能延后失败。
                any_payload_is_ref = true;
                break :blk payload_token + 1;
            } else payload_token;

            if (!mem.eql(u8, tree.tokenSlice(ident), "_")) {
                any_has_payload_capture = true;

                // 如果捕获联合体,其载荷值不一定
                // 在编译期已知,即使分支被内联,因为内联只
                // 影响其枚举标签。
                // 此检查并不完美,因为对于枚举等类型,
                // 内联分支的整个捕获值*确实*在编译期已知!
                // 但得知这一点需要语义分析。
                any_maybe_runtime_capture = true;
            }
            if (tree.tokenTag(ident + 1) == .comma) {
                any_has_tag_capture = true;

                if (case.inline_token == null) {
                    any_maybe_runtime_capture = true;
                }
            }
        }

        // 检查 else 分支。
        if (case.ast.values.len == 0) {
            if (else_case_node.unwrap()) |prev_case_node| {
                const prev_else_tok = tree.fullSwitchCase(prev_case_node).?.ast.arrow_token - 1;
                const else_tok = case.ast.arrow_token - 1;
                return astgen.failTokNotes(
                    else_tok,
                    "multiple else prongs in switch expression",
                    .{},
                    &.{try astgen.errNoteTok(prev_else_tok, "previous else prong here", .{})},
                );
            }
            else_case_node = case_node.toOptional();
            continue;
        }

        // 检查 '_' 分支和范围。
        var case_has_ranges = false;
        for (case.ast.values) |val| {
            switch (tree.nodeTag(val)) {
                .switch_range => {
                    total_ranges_len += 1;
                    case_has_ranges = true;
                },
                .string_literal => return astgen.failNode(val, "cannot switch on strings", .{}),
                else => |tag| {
                    total_items_len += 1;
                    if (tag == .identifier and
                        mem.eql(u8, tree.tokenSlice(tree.nodeMainToken(val)), "_"))
                    {
                        if (is_err_switch) {
                            const case_src = case.ast.arrow_token - 1;
                            return astgen.failTokNotes(
                                case_src,
                                "'_' prong is not allowed when switching on errors",
                                .{},
                                &.{
                                    try astgen.errNoteTok(
                                        case_src,
                                        "consider using 'else'",
                                        .{},
                                    ),
                                },
                            );
                        }
                        if (underscore_node.unwrap()) |prev_src| {
                            return astgen.failNodeNotes(
                                val,
                                "multiple '_' prongs in switch expression",
                                .{},
                                &.{try astgen.errNoteNode(prev_src, "previous '_' prong here", .{})},
                            );
                        }
                        if (case.inline_token != null) {
                            return astgen.failNode(val, "cannot inline '_' prong", .{});
                        }
                        underscore_node = val.toOptional();
                    }
                },
            }
        }

        const case_len = case.ast.values.len;
        if (case_len == 1 and !case_has_ranges) {
            scalar_cases_len += 1;
        } else if (case_len >= 1) {
            multi_cases_len += 1;
        }
    }

    const has_else = else_case_node != .none;
    const has_under = underscore_node != .none;
    if (is_err_switch) assert(!has_under); // 此时应已失败
    const any_ranges = total_ranges_len > 0;

    // 包含全部主体长度,顺序已经正确,以及各长度所属的主体,稍后将放入 `extra` 数组。
    // 但前 item_table_end 个槽位是索引各项主体的表,也间接索引分支主体,因为分支主体始终紧随其项主体之后。
    //
    //
    //
    const payloads = &astgen.scratch;
    const scratch_top = astgen.scratch.items.len;
    var payloads_end = scratch_top;

    // 范围项的表达式体对始终连续,因此严格来说,
    // 无需记录第二个表达式体的位置。不过,处理
    // 多个索引和偏移量本身已相当复杂,
    // 因此为使函数稍微简单一些,
    // 仍记录该位置。

    const scalar_body_table = payloads_end;
    payloads_end += scalar_cases_len;
    const multi_item_body_table = payloads_end;
    payloads_end += total_items_len + 2 * total_ranges_len - scalar_cases_len;
    const multi_prong_body_table = payloads_end;
    payloads_end += multi_cases_len;
    const body_table_end = payloads_end;

    const scalar_prong_infos_start = payloads_end;
    payloads_end += scalar_cases_len;
    const multi_prong_infos_start = payloads_end;
    payloads_end += multi_cases_len;
    const multi_case_items_lens_start = payloads_end;
    payloads_end += multi_cases_len;
    const multi_case_ranges_lens_start = if (any_ranges) blk: {
        const multi_case_ranges_lens_start = payloads_end;
        payloads_end += multi_cases_len;
        break :blk multi_case_ranges_lens_start;
    } else undefined;
    const scalar_item_infos_start = payloads_end;
    payloads_end += scalar_cases_len;
    const multi_items_infos_start = payloads_end;
    payloads_end += total_items_len - scalar_cases_len + 2 * total_ranges_len;
    const bodies_start = payloads_end;

    try payloads.resize(gpa, bodies_start);
    defer astgen.scratch.items.len = scratch_top;

    var non_err_prong_body_start: u32 = undefined;
    var else_prong_body_start: u32 = undefined;
    var non_err_info: Zir.Inst.SwitchBlock.ProngInfo.NonErr = undefined;
    var else_info: Zir.Inst.SwitchBlock.ProngInfo.Else = undefined;

    var block_scope = parent_gz.makeSubBlock(scope);
    // block_scope 不用于收集指令
    block_scope.instructions_top = GenZir.unstacked_top;

    const operand_ri: ResultInfo = .{
        .rl = loc: {
            if (any_payload_is_ref) break :loc .ref;
            if (needs_non_err_handling and non_err_is_ref == .yes) break :loc .ref;
            if (needs_non_err_handling and non_err_is_ref == .yes_const) break :loc .ref_const;
            break :loc .none;
        },
        .ctx = if (do_err_trace) .error_handling_expr else .none,
    };

    astgen.advanceSourceCursorToNode(operand_node);
    const operand_lc: LineColumn = .{ astgen.source_line - parent_gz.decl_line, astgen.source_column };

    const raw_operand: Zir.Inst.Ref = if (needs_non_err_handling)
        try reachableExpr(parent_gz, scope, operand_ri, operand_node, switch_node)
    else
        try expr(parent_gz, scope, operand_ri, operand_node);

    // Sema 预期任何 switch_block 指令之前都紧邻 dbg_stmt。
    try emitDbgStmtForceCurrentIndex(parent_gz, operand_lc);
    // 稍后会将此项添加到父块中,位于各项表达式之后。
    const switch_tag: Zir.Inst.Tag = switch (non_err) {
        .none, .peer_break_target => if (any_payload_is_ref) .switch_block_ref else .switch_block,
        .@"if", .@"catch" => .switch_block_err_union,
    };
    const switch_block = try parent_gz.makeBlockInst(switch_tag, switch_node);

    // 适用时设置 `break` 目标;`continue` 目标可能不同!
    switch (non_err) {
        .none => {
            if (switch_full.label_token != null) {
                block_scope.break_target = switch_block;
            }
            block_scope.setBreakResultInfo(block_ri);
        },
        .@"catch", .@"if" => {
            assert(switch_full.label_token == null); // 改为使用 `peer_break_target` 代码路径!
            block_scope.setBreakResultInfo(block_ri);
        },
        .peer_break_target => |peer_break_target| {

            // 特殊情况:存在错误 switch 与标签的组合,需要
            // 生成如下代码:
            // ```
            // %1 = block({
            //   %2 = is_non_err(%operand)
            //   %3 = condbr(%2, {
            //     %4 = err_union_payload_unsafe(%operand)
            //     %5 = break(%1, result) // 目标为外层 `block`
            //   }, {
            //     %6 = err_union_code(%operand)
            //     %7 = switch_block(%6,
            //       { ... } => {
            //         %8 = break(%1, result) // 目标为外层 `block`
            //       },
            //       { ... } => {
            //         %9 = switch_continue(%7, result) // 目标为 `switch_block`
            //       },
            //     )
            //     %10 = break(%1, @void_value)
            //   })
            // })
            // ```
            // 以确保只有从非错误分支或 switch 中跳出时,二者才互为同级表达式;
            // 继续 switch 时则不是。通过这种降低表示的方式,
            // 避免在 Sema 中处理相当复杂的特例。

            assert(switch_full.label_token != null); // 改用 `switch_block_err_union` 代码路径!
            assert(.block == astgen.instructions.items(.tag)[@backingInt(peer_break_target.block_inst)]);
            block_scope.break_target = peer_break_target.block_inst;
            block_scope.setBreakResultInfo(peer_break_target.block_ri);
        },
    }

    // 我们需要若干独立位置来存储多个捕获值:
    // `... |err| switch (err) { else => |e| { ... } }` // `err` 和 `e`
    // `... => |payload, tag| { ... }` // `payload` 和 `tag`
    // 还需要存储结果类型:
    // `foo => { ... }` // `foo` 需要结果类型
    // `... => continue :sw val` // `val` 需要结果类型
    // 一些观察:
    // - 如果直接使用 switch 指令本身,就不需要占位符!
    // - 我们总能确定是否存在捕获,并且也知道:一旦存在,就必定会被使用。
    // - 在分析完所有分支体之前,无法确定是否存在任何 `continue`。但到那时,我们已经需要结果位置。我们确实可以通过查找标签,确定是否有可能出现 continue。
    // - Sema 在 `zirSwitchContinue` 中需要结果位置。如果该位置就是 switch 指令本身,就不必查看 switch 指令数据。
    // 一些结论:
    // - 如果需要 continue 结果位置,应使用 switch 指令本身。
    // - 如果捕获值需要更多指令,而 switch 指令本身已另作他用,则开始创建占位指令。
    //
    //
    //
    //
    //

    // 分支项使用 switch 块指令作为其结果类型。
    // 解析分支项期间,switch 语句的其他部分
    // 均不处于作用域内,因此不会产生问题。
    const item_ri: ResultInfo = .{ .rl = .{ .coerced_ty = switch_block.toRef() } };

    var switch_block_inst_is_occupied: bool = false;

    if (switch_full.label_token) |label_token| {
        block_scope.label = .{ .token = label_token };
        block_scope.continue_target = .{ .switch_continue = switch_block };
        block_scope.continue_result_info = .{
            .rl = if (any_payload_is_ref)
                .{ .ref_coerced_ty = switch_block.toRef() }
            else
                .{ .coerced_ty = switch_block.toRef() },
        };
        switch_block_inst_is_occupied = true;

        // `break_target` 和 `break_result_info` 已在上方设置。
    }
    if (needs_non_err_handling) {
        // `switch_block_err_union` 使用 switch 块指令作为其错误捕获/
        // switch 操作数。由于此 switch 绝不可能带标签,因此始终可行。
        assert(!switch_block_inst_is_occupied);
        switch_block_inst_is_occupied = true;
    }
    // `... => |payload| { ... }`
    const payload_capture_inst, const payload_capture_inst_is_placeholder = inst: {
        if (!any_has_payload_capture) break :inst .{ undefined, false };
        if (!switch_block_inst_is_occupied) {
            switch_block_inst_is_occupied = true;
            break :inst .{ switch_block, false };
        }
        break :inst .{ try astgen.appendPlaceholder(), true };
    };
    // `... => |_, tag| { ... }`
    const tag_capture_inst, const tag_capture_inst_is_placeholder = inst: {
        if (!any_has_tag_capture) break :inst .{ undefined, false };
        if (!switch_block_inst_is_occupied) {
            switch_block_inst_is_occupied = true;
            break :inst .{ switch_block, false };
        }
        break :inst .{ try astgen.appendPlaceholder(), true };
    };

    var prong_body_extra_insts_buf: [3]Zir.Inst.Index = undefined;
    const prong_body_extra_insts: []const Zir.Inst.Index = extra_insts: {
        var extra_insts: std.ArrayList(Zir.Inst.Index) = .initBuffer(&prong_body_extra_insts_buf);
        if (switch_block_inst_is_occupied) extra_insts.appendAssumeCapacity(switch_block);
        if (payload_capture_inst_is_placeholder) extra_insts.appendAssumeCapacity(payload_capture_inst);
        if (tag_capture_inst_is_placeholder) extra_insts.appendAssumeCapacity(tag_capture_inst);
        break :extra_insts extra_insts.items;
    };

    const switch_operand, const catch_or_if_operand = if (needs_non_err_handling)
        .{ switch_block.toRef(), raw_operand }
    else
        .{ raw_operand, undefined };

    // 对所有 case 项及其内容复用同一作用域。
    var scratch_scope = parent_gz.makeSubBlock(&block_scope.base);
    scratch_scope.instructions_top = GenZir.unstacked_top;

    // 若存在非错误分支体,必须先处理它。
    non_err_body: {
        if (!needs_non_err_handling) break :non_err_body;

        scratch_scope.instructions_top = parent_gz.instructions.items.len;
        defer scratch_scope.unstack();

        // 始终可以使用 switch 块指令引用错误联合体载荷,因为实际 switch 语句此时尚未进入作用域。
        //
        const non_err_payload_inst = switch_block;
        var non_err_capture: Zir.Inst.SwitchBlock.ProngInfo.Capture = .none;

        switch (non_err) {
            .none, .peer_break_target => unreachable,
            .@"catch" => {
                // 实际上始终捕获错误联合体载荷;使用
                // 它来 `break` 跳出整个 `switch_block_err_union`。
                non_err_capture = if (non_err_is_ref != .no) .by_ref else .by_val;

                const then_result = switch (ri.rl) {
                    .ref, .ref_const, .ref_coerced_ty => non_err_payload_inst.toRef(),
                    else => try rvalue(
                        &scratch_scope,
                        block_scope.break_result_info,
                        non_err_payload_inst.toRef(),
                        catch_or_if_node,
                    ),
                };
                _ = try scratch_scope.addBreakWithSrcNode(
                    .@"break",
                    switch_block,
                    then_result,
                    catch_or_if_node,
                );
            },
            .@"if" => |if_full| {
                var payload_val_scope: Scope.LocalVal = undefined;

                const then_node = if_full.ast.then_expr;
                const then_sub_scope: *Scope = scope: {
                    if (if_full.payload_token) |payload_token| {
                        const ident_token = payload_token + @intFromBool(non_err_is_ref != .no);
                        const ident_name = try astgen.identAsString(ident_token);
                        const ident_name_str = tree.tokenSlice(ident_token);
                        if (mem.eql(u8, "_", ident_name_str)) {
                            if (non_err_is_ref != .no) return astgen.failTok(payload_token, "pointer modifier invalid on discard", .{});
                            break :scope &scratch_scope.base;
                        }
                        non_err_capture = if (non_err_is_ref != .no) .by_ref else .by_val;
                        try astgen.detectLocalShadowing(&scratch_scope.base, ident_name, ident_token, ident_name_str, .capture);
                        payload_val_scope = .{
                            .parent = &scratch_scope.base,
                            .gen_zir = &scratch_scope,
                            .name = ident_name,
                            .inst = non_err_payload_inst.toRef(),
                            .token_src = ident_token,
                            .id_cat = .capture,
                        };
                        try scratch_scope.addDbgVar(.dbg_var_val, ident_name, non_err_payload_inst.toRef());
                        break :scope &payload_val_scope.base;
                    } else {
                        _ = try scratch_scope.addUnNode(
                            .ensure_err_union_payload_void,
                            catch_or_if_operand,
                            catch_or_if_node,
                        );
                        break :scope &scratch_scope.base;
                    }
                };
                const then_result = try fullBodyExpr(&scratch_scope, then_sub_scope, block_scope.break_result_info, then_node, .allow_branch_hint);
                try checkUsed(parent_gz, &scratch_scope.base, then_sub_scope);
                if (!scratch_scope.endsWithNoReturn()) {
                    _ = try scratch_scope.addBreakWithSrcNode(.@"break", switch_block, then_result, then_node);
                }
            },
        }
        const body_slice = scratch_scope.instructionsSlice();
        const body_start: u32 = @intCast(payloads.items.len);
        const body_len = astgen.countBodyLenAfterFixupsExtraRefs(body_slice, &.{non_err_payload_inst});
        try payloads.ensureUnusedCapacity(gpa, body_len);
        astgen.appendBodyWithFixupsExtraRefsArrayList(payloads, body_slice, &.{non_err_payload_inst});

        non_err_prong_body_start = body_start;
        non_err_info = .{
            .body_len = @intCast(body_len),
            .capture = non_err_capture,
            .operand_is_ref = non_err_is_ref != .no,
        };
    }

    // 此遍生成所有项表达式及分支表达式。
    var multi_case_index: u32 = 0;
    var scalar_case_index: u32 = 0;
    var multi_item_offset: usize = 0;
    for (case_nodes) |case_node| {
        const case = tree.fullSwitchCase(case_node).?;

        const ranges_len: u32 = if (any_ranges) blk: {
            var ranges_len: u32 = 0;
            for (case.ast.values) |value| {
                ranges_len += @intFromBool(tree.nodeTag(value) == .switch_range);
            }
            break :blk ranges_len;
        } else 0;
        const items_len: u32 = @intCast(case.ast.values.len - ranges_len);
        const is_multi_case = items_len > 1 or ranges_len > 0;

        // 按出现顺序排列的条目或范围主体
        var item_i: usize = 0;
        var range_i: usize = 0;
        for (case.ast.values) |value| {
            const is_range = tree.nodeTag(value) == .switch_range;
            const range: [2]Ast.Node.Index = if (is_range) tree.nodeData(value).node_and_node else undefined;
            const nodes: []const Ast.Node.Index = if (is_range) &range else &.{value};
            for (nodes) |item| {
                // 手动降低枚举字面量、错误值和数字字面量,
                // 以节省空间,因为它们非常常见地用作
                // switch 分支项。
                const body_start: u32 = @intCast(payloads.items.len);
                const item_info: Zir.Inst.SwitchBlock.ItemInfo = blk: switch (tree.nodeTag(item)) {
                    .enum_literal => {
                        const str_index = try astgen.identAsString(tree.nodeMainToken(item));
                        break :blk .wrap(.{ .enum_literal = str_index });
                    },
                    .error_value => {
                        const ident_token = tree.nodeMainToken(item) + 2; // 跳过 'error'、'.'
                        const str_index = try astgen.identAsString(ident_token);
                        break :blk .wrap(.{ .error_value = str_index });
                    },
                    else => if (value.toOptional() == underscore_node) {
                        break :blk .wrap(.under);
                    } else {
                        scratch_scope.instructions_top = parent_gz.instructions.items.len;
                        defer scratch_scope.unstack();
                        const item_result = try fullBodyExpr(&scratch_scope, scope, item_ri, item, .normal);
                        if (!scratch_scope.endsWithNoReturn()) {
                            _ = try scratch_scope.addBreakWithSrcNode(.break_inline, switch_block, item_result, item);
                        }
                        const item_slice = scratch_scope.instructionsSlice();
                        const body_len = astgen.countBodyLenAfterFixupsExtraRefs(item_slice, &.{switch_block});
                        try payloads.ensureUnusedCapacity(gpa, body_len);
                        astgen.appendBodyWithFixupsExtraRefsArrayList(payloads, item_slice, &.{switch_block});
                        break :blk .wrap(.{ .body_len = body_len });
                    },
                };
                if (is_multi_case) {
                    if (is_range) {
                        const offset = multi_item_offset + items_len + range_i;
                        payloads.items[multi_item_body_table + offset] = body_start;
                        payloads.items[multi_items_infos_start + offset] = @bitCast(item_info);
                        range_i += 1;
                    } else {
                        const offset = multi_item_offset + item_i;
                        payloads.items[multi_item_body_table + offset] = body_start;
                        payloads.items[multi_items_infos_start + offset] = @bitCast(item_info);
                        item_i += 1;
                    }
                } else {
                    payloads.items[scalar_body_table + scalar_case_index] = body_start;
                    payloads.items[scalar_item_infos_start + scalar_case_index] = @bitCast(item_info);
                }
            }
        }
        if (is_multi_case) {
            assert(item_i == items_len and range_i == 2 * ranges_len);
            payloads.items[multi_case_items_lens_start + multi_case_index] = items_len;
            if (any_ranges) {
                payloads.items[multi_case_ranges_lens_start + multi_case_index] = ranges_len;
            }
            multi_item_offset += items_len + 2 * ranges_len;
        }

        // 捕获和 prong 主体

        var dbg_var_payload_name: Zir.NullTerminatedString = .empty;
        var dbg_var_payload_inst: Zir.Inst.Ref = undefined;
        var dbg_var_tag_name: Zir.NullTerminatedString = .empty;
        var dbg_var_tag_inst: Zir.Inst.Ref = undefined;
        var has_tag_capture = false;
        var err_capture_scope: Scope.LocalVal = undefined;
        var payload_capture_scope: Scope.LocalVal = undefined;
        var tag_capture_scope: Scope.LocalVal = undefined;

        var capture: Zir.Inst.SwitchBlock.ProngInfo.Capture = .none;

        // 检查所有捕获,并使其在分支体中可用。
        // 可能的捕获包括:
        // - 普通 switch:载荷和标签
        // - 错误 switch:switch 操作数和载荷
        const prong_body_scope: *Scope = scope: {
            const switch_scope: *Scope = if (needs_non_err_handling) blk: {
                // 需要让捕获的、用作 switch 操作数的错误处于作用域内!
                err_capture_scope = .{
                    .parent = &scratch_scope.base,
                    .gen_zir = &scratch_scope,
                    .name = err_capture_name,
                    .inst = switch_operand,
                    .token_src = err_token,
                    .id_cat = .capture,
                };
                break :blk &err_capture_scope.base;
            } else &scratch_scope.base;

            const payload_token = case.payload_token orelse break :scope switch_scope;
            const capture_is_ref = tree.tokenTag(payload_token) == .asterisk;
            const ident = payload_token + @intFromBool(capture_is_ref);

            capture = if (capture_is_ref) .by_ref else .by_val;

            const ident_slice = tree.tokenSlice(ident);
            var payload_sub_scope: *Scope = undefined;
            if (mem.eql(u8, ident_slice, "_")) {
                if (capture_is_ref) {
                    // |*_, tag| 无效,因此可提前失败
                    return astgen.failTok(payload_token, "pointer modifier invalid on discard", .{});
                }
                capture = .none;
                payload_sub_scope = switch_scope;
            } else {
                const capture_name = try astgen.identAsString(ident);
                try astgen.detectLocalShadowing(switch_scope, capture_name, ident, ident_slice, .capture);
                payload_capture_scope = .{
                    .parent = switch_scope,
                    .gen_zir = &scratch_scope,
                    .name = capture_name,
                    .inst = payload_capture_inst.toRef(),
                    .token_src = ident,
                    .id_cat = .capture,
                };
                dbg_var_payload_name = payload_capture_scope.name;
                dbg_var_payload_inst = payload_capture_scope.inst;
                payload_sub_scope = &payload_capture_scope.base;
            }

            if (is_err_switch and capture == .by_ref) {
                return astgen.failTok(ident, "error set cannot be captured by reference", .{});
            }

            const tag_token = if (tree.tokenTag(ident + 1) == .comma) blk: {
                break :blk ident + 2;
            } else if (capture == .none) {
                // 只有捕获了标签时才允许丢弃捕获值;
                // 标签捕获是否被丢弃将在下文处理。
                return astgen.failTok(payload_token, "discard of capture; omit it instead", .{});
            } else break :scope payload_sub_scope;

            const tag_slice = tree.tokenSlice(tag_token);
            if (mem.eql(u8, tag_slice, "_")) {
                return astgen.failTok(tag_token, "discard of tag capture; omit it instead", .{});
            }
            const tag_name = try astgen.identAsString(tag_token);
            try astgen.detectLocalShadowing(payload_sub_scope, tag_name, tag_token, tag_slice, .@"switch tag capture");

            assert(any_has_tag_capture);
            has_tag_capture = true;

            if (is_err_switch) {
                return astgen.failTok(tag_token, "cannot capture tag of error union", .{});
            }

            tag_capture_scope = .{
                .parent = payload_sub_scope,
                .gen_zir = &scratch_scope,
                .name = tag_name,
                .inst = tag_capture_inst.toRef(),
                .token_src = tag_token,
                .id_cat = .@"switch tag capture",
            };
            dbg_var_tag_name = tag_capture_scope.name;
            dbg_var_tag_inst = tag_capture_scope.inst;
            break :scope &tag_capture_scope.base;
        };

        if (capture != .none) assert(any_has_payload_capture);

        prong_body: {
            scratch_scope.instructions_top = parent_gz.instructions.items.len;
            defer scratch_scope.unstack();

            if (dbg_var_payload_name != .empty) {
                try scratch_scope.addDbgVar(.dbg_var_val, dbg_var_payload_name, dbg_var_payload_inst);
            }
            if (dbg_var_tag_name != .empty) {
                try scratch_scope.addDbgVar(.dbg_var_val, dbg_var_tag_name, dbg_var_tag_inst);
            }
            if (do_err_trace and nodeMayAppendToErrorTrace(tree, operand_node)) {
                _ = try scratch_scope.addSaveErrRetIndex(.always);
            }
            const target_expr_node = case.ast.target_expr;
            const case_result = try fullBodyExpr(&scratch_scope, prong_body_scope, block_scope.break_result_info, target_expr_node, .allow_branch_hint);
            if (needs_non_err_handling) {
                // 如果在此检查 `scratch_scope`,就会产生误报,
                // 因为 switch 操作数本身就在其中!
                try checkUsed(parent_gz, &err_capture_scope.base, prong_body_scope);
            } else {
                try checkUsed(parent_gz, &scratch_scope.base, prong_body_scope);
            }
            if (!scratch_scope.endsWithNoReturn()) {
                // 作为 break 前最后一个操作,必要时“弹出”错误跟踪
                if (do_err_trace) {
                    try restoreErrRetIndex(
                        &scratch_scope,
                        .{ .block = switch_block },
                        block_scope.break_result_info,
                        target_expr_node,
                        case_result,
                    );
                }
                _ = try scratch_scope.addBreakWithSrcNode(.@"break", switch_block, case_result, target_expr_node);
            }

            const body_slice = scratch_scope.instructionsSlice();
            const body_start: u32 = @intCast(payloads.items.len);
            const body_len = astgen.countBodyLenAfterFixupsExtraRefs(body_slice, prong_body_extra_insts);
            try payloads.ensureUnusedCapacity(gpa, body_len);
            astgen.appendBodyWithFixupsExtraRefsArrayList(payloads, body_slice, prong_body_extra_insts);

            if (case_node.toOptional() == else_case_node) {
                assert(case.ast.values.len == 0);

                // 某些特定 `else` 分支体会使 Sema 省略
                // “else 分支不可达”错误,以免某些泛型代码
                // 模式触发该错误。以下分支体采用此处理:
                // `else => unreachable,`
                // `else => return,`
                // `else => |e| return e,`(其中 `e` 可以是任意标识符)
                const is_simple_noreturn = switch (tree.nodeTag(target_expr_node)) {
                    .unreachable_literal => true, // `=> unreachable,`
                    .@"return" => simple_noreturn: {
                        const retval_node = tree.nodeData(target_expr_node).opt_node.unwrap() orelse {
                            break :simple_noreturn true; // `=> return,`
                        };
                        // 检查 `=> |e| return e,`
                        if (capture != .by_val) break :simple_noreturn false;
                        if (tree.nodeTag(retval_node) != .identifier) break :simple_noreturn false;
                        const payload_name = try astgen.identAsString(case.payload_token.?);
                        const retval_name = try astgen.identAsString(tree.nodeMainToken(retval_node));
                        break :simple_noreturn payload_name == retval_name;
                    },
                    else => false,
                };

                else_info = .{
                    .body_len = @intCast(body_len),
                    .capture = capture,
                    .is_inline = case.inline_token != null,
                    .has_tag_capture = has_tag_capture,
                    .is_simple_noreturn = is_simple_noreturn,
                };
                else_prong_body_start = body_start;
                break :prong_body;
            }

            // 若分支体为 `=> comptime unreachable,`,则允许分支包含不属于所切换错误集合的错误项。
            //
            const is_comptime_unreach = comptime_unreach: {
                if (tree.nodeTag(target_expr_node) != .@"comptime") break :comptime_unreach false;
                const comptime_node = tree.nodeData(target_expr_node).node;
                break :comptime_unreach tree.nodeTag(comptime_node) == .unreachable_literal;
            };

            const prong_info: Zir.Inst.SwitchBlock.ProngInfo = .{
                .body_len = @intCast(body_len),
                .capture = capture,
                .is_inline = case.inline_token != null,
                .has_tag_capture = has_tag_capture,
                .is_comptime_unreach = is_comptime_unreach,
            };

            if (is_multi_case) {
                payloads.items[multi_prong_body_table + multi_case_index] = body_start;
                payloads.items[multi_prong_infos_start + multi_case_index] = @bitCast(prong_info);
                multi_case_index += 1;
            } else {
                // 分支主体起点是隐式的,就在唯一的项之后。
                payloads.items[scalar_prong_infos_start + scalar_case_index] = @bitCast(prong_info);
                scalar_case_index += 1;
            }
        }
    }
    if (is_err_switch) {
        assert(!any_payload_is_ref); // 此时应已失败
        assert(!any_has_tag_capture); // 此时应已失败
    }
    assert(scalar_case_index + multi_case_index + @intFromBool(has_else) == case_nodes.len);
    assert(multi_items_infos_start + multi_item_offset == bodies_start);

    if (switch_full.label_token) |label_token| if (!block_scope.label.?.used) {
        try astgen.appendErrorTok(label_token, "unused switch label", .{});
    };

    // 元素表达式现已生成,可以添加此内容。
    try parent_gz.instructions.append(gpa, switch_block);

    // 所需数据已全部收集完毕。现在只需将主体
    // 从 `payloads` 复制到 `extra` 完成收尾;此次按照
    // ZIR 使用方所预期的顺序排列。

    try astgen.extra.ensureUnusedCapacity(gpa, @typeInfo(Zir.Inst.SwitchBlock).@"struct".field_names.len +
        @intFromBool(multi_cases_len > 0) + // multi_cases_len
        @intFromBool(payload_capture_inst_is_placeholder) + // payload_capture_placeholder
        @intFromBool(tag_capture_inst_is_placeholder) + // tag_capture_placeholder
        @intFromBool(needs_non_err_handling) + // catch_or_if_src_node_offset
        @intFromBool(needs_non_err_handling) + // non_err_info
        @intFromBool(has_else) + // else_info
        payloads.items.len - body_table_end); // 项目的信息与主体

    // 单个数据片段
    const zir_payload_index = astgen.addExtraAssumeCapacity(Zir.Inst.SwitchBlock{
        .raw_operand = raw_operand,
        .bits = .{
            .has_multi_cases = multi_cases_len > 0,
            .any_ranges = any_ranges,
            .has_else = has_else,
            .has_under = has_under,
            .has_continue = switch_full.label_token != null and block_scope.label.?.used_for_continue,
            .any_maybe_runtime_capture = any_maybe_runtime_capture,
            .payload_capture_inst_is_placeholder = payload_capture_inst_is_placeholder,
            .tag_capture_inst_is_placeholder = tag_capture_inst_is_placeholder,
            .scalar_cases_len = @intCast(scalar_cases_len),
        },
    });
    astgen.instructions.items(.data)[@backingInt(switch_block)].pl_node.payload_index = zir_payload_index;

    if (multi_cases_len > 0) astgen.extra.appendAssumeCapacity(multi_cases_len);
    if (payload_capture_inst_is_placeholder) astgen.extra.appendAssumeCapacity(@backingInt(payload_capture_inst));
    if (tag_capture_inst_is_placeholder) astgen.extra.appendAssumeCapacity(@backingInt(tag_capture_inst));
    if (needs_non_err_handling) {
        const catch_or_if_src_node_offset = parent_gz.nodeIndexToRelative(catch_or_if_node);
        astgen.extra.appendAssumeCapacity(@bitCast(@backingInt(catch_or_if_src_node_offset)));
        astgen.extra.appendAssumeCapacity(@bitCast(non_err_info));
    }
    if (has_else) astgen.extra.appendAssumeCapacity(@bitCast(else_info));

    const extra_payloads_start = astgen.extra.items.len;

    // 主体长度
    astgen.extra.appendSliceAssumeCapacity(payloads.items[body_table_end..bodies_start]);

    // 主体
    if (needs_non_err_handling) {
        const body = payloads.items[non_err_prong_body_start..][0..non_err_info.body_len];
        astgen.extra.appendSliceAssumeCapacity(body);
    }
    if (has_else) {
        const body = payloads.items[else_prong_body_start..][0..else_info.body_len];
        astgen.extra.appendSliceAssumeCapacity(body);
    }
    for (0..scalar_cases_len) |scalar_i| {
        const item_info: Zir.Inst.SwitchBlock.ItemInfo = @bitCast(payloads.items[scalar_item_infos_start + scalar_i]);
        const item_body_start = payloads.items[scalar_body_table + scalar_i];
        const item_body = payloads.items[item_body_start..][0 .. item_info.bodyLen() orelse 0];
        const prong_info: Zir.Inst.SwitchBlock.ProngInfo = @bitCast(payloads.items[scalar_prong_infos_start + scalar_i]);
        const prong_body_start = item_body_start + item_body.len;
        const prong_body = payloads.items[prong_body_start..][0..prong_info.body_len];
        astgen.extra.appendSliceAssumeCapacity(prong_body);
        astgen.extra.appendSliceAssumeCapacity(item_body);
    }
    var multi_item_i: usize = 0;
    for (0..multi_cases_len) |multi_i| {
        const prong_body_start = payloads.items[multi_prong_body_table + multi_i];
        const prong_info: Zir.Inst.SwitchBlock.ProngInfo = @bitCast(payloads.items[multi_prong_infos_start + multi_i]);
        const prong_body = payloads.items[prong_body_start..][0..prong_info.body_len];
        astgen.extra.appendSliceAssumeCapacity(prong_body);

        const items_len = payloads.items[multi_case_items_lens_start + multi_i];
        const ranges_len = if (any_ranges) ranges_len: {
            break :ranges_len payloads.items[multi_case_ranges_lens_start + multi_i];
        } else 0;
        // 表条目和函数体长度已按正确顺序排列,因此此处无需区分项目和范围。
        //
        for (0..items_len + 2 * ranges_len) |_| {
            const item_info: Zir.Inst.SwitchBlock.ItemInfo = @bitCast(payloads.items[multi_items_infos_start + multi_item_i]);
            if (item_info.bodyLen()) |body_len| {
                const body_start = payloads.items[multi_item_body_table + multi_item_i];
                const body = payloads.items[body_start..][0..body_len];
                astgen.extra.appendSliceAssumeCapacity(body);
            }
            multi_item_i += 1;
        }
    }

    // 确保没有遗漏任何内容……
    assert(multi_item_i == total_items_len + 2 * total_ranges_len - scalar_cases_len);
    assert(astgen.extra.items.len - extra_payloads_start == payloads.items.len - body_table_end);

    if (need_result_rvalue) {
        return rvalue(parent_gz, ri, switch_block.toRef(), switch_node);
    } else {
        return switch_block.toRef();
    }
}

fn ret(gz: *GenZir, scope: *Scope, node: Ast.Node.Index) InnerError!Zir.Inst.Ref {
    const astgen = gz.astgen;
    const tree = astgen.tree;

    if (astgen.fn_block == null) {
        return astgen.failNode(node, "'return' outside function scope", .{});
    }

    if (gz.any_defer_node.unwrap()) |any_defer_node| {
        return astgen.failNodeNotes(node, "cannot return from defer expression", .{}, &.{
            try astgen.errNoteNode(
                any_defer_node,
                "defer expression here",
                .{},
            ),
        });
    }

    // 确保为此 return 表达式生成调试行列信息。
    // 随后保存行列,以便再生成一条向
    // “后方”移动的信息:需要先对操作数求值,再将调试
    // 位置恢复到 return 关键字,以用于错误返回跟踪。
    if (!gz.is_comptime) {
        try emitDbgNode(gz, node);
    }
    const ret_lc: LineColumn = .{ astgen.source_line - gz.decl_line, astgen.source_column };

    const defer_outer = &astgen.fn_block.?.base;

    const operand_node = tree.nodeData(node).opt_node.unwrap() orelse {
        // 返回 void 值;跳过错误延迟执行语句。
        try genDefers(gz, defer_outer, scope, .normal_only);

        // 作为返回前最后一个操作,必要时“弹出”错误跟踪
        _ = try gz.addRestoreErrRetIndex(.ret, .always, node);

        _ = try gz.addUnNode(.ret_node, .void_value, node);
        return Zir.Inst.Ref.unreachable_value;
    };

    if (tree.nodeTag(operand_node) == .error_value) {
        // `return error.Foo` 的快速路径。绕过结果位置逻辑,
        // 也绕过判断是否将某内容加入函数推断错误集的逻辑。
        const ident_token = tree.nodeMainToken(operand_node) + 2;
        const err_name_str_index = try astgen.identAsString(ident_token);
        try genDefers(gz, defer_outer, scope, .normal_and_error);
        try emitDbgStmt(gz, ret_lc);
        _ = try gz.addStrTok(.ret_err_value, err_name_str_index, ident_token);
        return .unreachable_value;
    }

    const ri: ResultInfo = if (astgen.nodes_need_rl.contains(node)) .{
        .rl = .{ .ptr = .{ .inst = try gz.addNode(.ret_ptr, node) } },
        .ctx = .@"return",
    } else .{
        .rl = .{ .coerced_ty = astgen.fn_ret_ty },
        .ctx = .@"return",
    };
    const operand: Zir.Inst.Ref = try nameStratExpr(gz, scope, ri, operand_node, .func) orelse
        try reachableExpr(gz, scope, ri, operand_node, node);

    switch (nodeMayEvalToError(tree, operand_node)) {
        .never => {
            // 返回不可能是错误的值;跳过错误延迟执行操作。
            try genDefers(gz, defer_outer, scope, .normal_only);

            // 作为返回前最后一个操作,必要时“弹出”错误跟踪
            _ = try gz.addRestoreErrRetIndex(.ret, .always, node);

            try emitDbgStmt(gz, ret_lc);
            try gz.addRet(ri, operand, node);
            return Zir.Inst.Ref.unreachable_value;
        },
        .always => {
            // 值始终为错误。同时输出 errdefer 和普通 defer。
            try genDefers(gz, defer_outer, scope, .normal_and_error);
            try emitDbgStmt(gz, ret_lc);
            try gz.addRet(ri, operand, node);
            return Zir.Inst.Ref.unreachable_value;
        },
        .maybe => {
            if (!anyErrdefers(defer_outer, scope)) {
                // 仅包含常规延迟执行语句,无需分支。
                try genDefers(gz, defer_outer, scope, .normal_only);
                try emitDbgStmt(gz, ret_lc);

                // 作为返回前最后一个操作,必要时“弹出”错误跟踪
                const result = if (ri.rl == .ptr) try gz.addUnNode(.load, ri.rl.ptr.inst, node) else operand;
                _ = try gz.addRestoreErrRetIndex(.ret, .{ .if_non_error = result }, node);

                try gz.addRet(ri, operand, node);
                return Zir.Inst.Ref.unreachable_value;
            }

            // 生成用于生成 errdefer 的条件分支。
            const result = if (ri.rl == .ptr) try gz.addUnNode(.load, ri.rl.ptr.inst, node) else operand;
            const is_non_err = try gz.addUnNode(.ret_is_non_err, result, node);
            const condbr = try gz.addCondBr(.condbr, node);

            var then_scope = gz.makeSubBlock(scope);
            defer then_scope.unstack();

            try genDefers(&then_scope, defer_outer, scope, .normal_only);

            // 作为返回前最后一个操作,必要时“弹出”错误跟踪
            _ = try then_scope.addRestoreErrRetIndex(.ret, .always, node);

            try emitDbgStmt(&then_scope, ret_lc);
            try then_scope.addRet(ri, operand, node);

            var else_scope = gz.makeSubBlock(scope);
            defer else_scope.unstack();

            try genDefers(&else_scope, defer_outer, scope, .normal_and_error);
            try emitDbgStmt(&else_scope, ret_lc);
            try else_scope.addRet(ri, operand, node);

            try setCondBrPayload(condbr, is_non_err, &then_scope, &else_scope);

            return Zir.Inst.Ref.unreachable_value;
        },
    }
}

/// 将字符串 `buf` 解析为 `u16` 类型的十进制整数。
///
/// 与 std.fmt.parseInt 不同,不允许 `buf` 中存在“_”字符。
fn parseBitCount(buf: []const u8) std.fmt.ParseIntError!u16 {
    if (buf.len == 0) return error.InvalidCharacter;

    var x: u16 = 0;

    for (buf) |c| {
        const digit = switch (c) {
            '0'...'9' => c - '0',
            else => return error.InvalidCharacter,
        };

        if (x != 0) x = try std.math.mul(u16, x, 10);
        x = try std.math.add(u16, x, digit);
    }

    return x;
}

const ComptimeBlockInfo = struct {
    src_node: Ast.Node.Index,
    reason: std.zig.SimpleComptimeReason,
};

fn identifier(
    gz: *GenZir,
    scope: *Scope,
    ri: ResultInfo,
    ident: Ast.Node.Index,
    force_comptime: ?ComptimeBlockInfo,
) InnerError!Zir.Inst.Ref {
    const astgen = gz.astgen;
    const tree = astgen.tree;

    const ident_token = tree.nodeMainToken(ident);
    const ident_name_raw = tree.tokenSlice(ident_token);
    if (mem.eql(u8, ident_name_raw, "_")) {
        return astgen.failNode(ident, "'_' used as an identifier without @\"_\" syntax", .{});
    }

    // 若非 @"" 语法,直接使用原始词法标记切片
    if (ident_name_raw[0] != '@') {
        if (primitive_instrs.get(ident_name_raw)) |zir_const_ref| {
            return rvalue(gz, ri, zir_const_ref, ident);
        }

        int_type: {
            if (ident_name_raw.len < 2) break :int_type;
            const signedness: std.lang.Signedness = switch (ident_name_raw[0]) {
                'u' => .unsigned,
                'i' => .signed,
                else => break :int_type,
            };
            // `u0` 已由 `primitive_instrs` 处理
            if (std.mem.eql(u8, ident_name_raw, "i0")) {
                return astgen.failNode(ident, "signed integer cannot have bit width 0", .{});
            }
            const bit_count = parseBitCount(ident_name_raw[1..]) catch |err| switch (err) {
                error.Overflow => return astgen.failNode(
                    ident,
                    "primitive integer type '{s}' exceeds maximum bit width of 65535",
                    .{ident_name_raw},
                ),
                error.InvalidCharacter => break :int_type,
            };
            if (ident_name_raw[1] == '0') {
                assert(ident_name_raw.len >= 3); // 已处理 `u0` 和 `i0`
                return astgen.failNode(
                    ident,
                    "primitive integer type '{s}' has leading zero",
                    .{ident_name_raw},
                );
            }
            const result = try gz.add(.{
                .tag = .int_type,
                .data = .{ .int_type = .{
                    .src_node = gz.nodeIndexToRelative(ident),
                    .signedness = signedness,
                    .bit_count = bit_count,
                } },
            });
            return rvalue(gz, ri, result, ident);
        }
    }

    // 局部变量(包括函数参数)以及容器级声明。

    if (force_comptime) |fc| {
        // 复现 `comptimeExpr2` 末尾的逻辑。
        const block_inst = try gz.makeBlockInst(.block_comptime, fc.src_node);

        var comptime_gz = gz.makeSubBlock(scope);
        comptime_gz.is_comptime = true;
        defer comptime_gz.unstack();

        const sub_ri: ResultInfo = .{
            .ctx = ri.ctx,
            .rl = .none, // 无需提供结果类型,因为它不会改变任何行为
        };
        const block_result = try localVarRef(&comptime_gz, scope, sub_ri, ident, ident_token);
        assert(!comptime_gz.endsWithNoReturn());
        _ = try comptime_gz.addBreak(.break_inline, block_inst, block_result);

        try comptime_gz.setBlockComptimeBody(block_inst, fc.reason);
        try gz.instructions.append(astgen.gpa, block_inst);

        return rvalue(gz, ri, block_inst.toRef(), fc.src_node);
    } else {
        return localVarRef(gz, scope, ri, ident, ident_token);
    }
}

fn localVarRef(
    gz: *GenZir,
    scope: *Scope,
    ri: ResultInfo,
    ident: Ast.Node.Index,
    ident_token: Ast.TokenIndex,
) InnerError!Zir.Inst.Ref {
    const astgen = gz.astgen;
    const name_str_index = try astgen.identAsString(ident_token);
    var found_already: ?Ast.Node.Index = null; // 已找到同名声明
    var found_needs_tunnel: bool = undefined; // 当 `found_already != null` 时已定义
    var found_namespaces_out: u32 = undefined; // 当 `found_already != null` 时已定义

    // 当前位于 `gz` 上方的命名空间层数。
    var num_namespaces_out: u32 = 0;
    // 由 `num_namespaces_out != 0` 决定
    var capturing_namespace: *Scope.Namespace = undefined;

    find_scope: switch (scope.unwrap()) {
        .local_val => |local_val| {
            if (local_val.name == name_str_index) {
                // 局部声明不能遮蔽任何名称,因此此时无需查找
                // 有歧义的引用。
                if (ri.rl == .discard and ri.ctx == .assignment) {
                    local_val.discarded = .fromToken(ident_token);
                } else {
                    local_val.used = .fromToken(ident_token);
                }

                if (local_val.is_used_or_discarded) |ptr| ptr.* = true;

                const value_inst = if (num_namespaces_out != 0) try tunnelThroughClosure(
                    gz,
                    ident,
                    num_namespaces_out,
                    .{ .ref = local_val.inst },
                    .{ .token = local_val.token_src },
                    name_str_index,
                ) else local_val.inst;

                return rvalueNoCoercePreRef(gz, ri, value_inst, ident);
            }
            continue :find_scope local_val.parent.unwrap();
        },
        .local_ptr => |local_ptr| {
            if (local_ptr.name == name_str_index) {
                if (ri.rl == .discard and ri.ctx == .assignment) {
                    local_ptr.discarded = .fromToken(ident_token);
                } else {
                    local_ptr.used = .fromToken(ident_token);
                }

                if (!local_ptr.maybe_comptime and !gz.is_typeof) {
                    if (num_namespaces_out != 0) {
                        const ident_name = try astgen.identifierTokenString(ident_token);
                        return astgen.failNodeNotes(ident, "mutable '{s}' not accessible from here", .{ident_name}, &.{
                            try astgen.errNoteTok(local_ptr.token_src, "declared mutable here", .{}),
                            try astgen.errNoteNode(capturing_namespace.node, "crosses namespace boundary here", .{}),
                        });
                    } else if (ri.ctx == .return_addrof) {
                        const ident_name = try astgen.identifierTokenString(ident_token);
                        return astgen.failNodeNotes(ident, "returning address of expired local variable '{s}'", .{ident_name}, &.{
                            try astgen.errNoteTok(local_ptr.token_src, "declared runtime-known here", .{}),
                        });
                    }
                }

                switch (ri.rl) {
                    .ref, .ref_const, .ref_coerced_ty => {
                        const ptr_inst = if (num_namespaces_out != 0) try tunnelThroughClosure(
                            gz,
                            ident,
                            num_namespaces_out,
                            .{ .ref = local_ptr.ptr },
                            .{ .token = local_ptr.token_src },
                            name_str_index,
                        ) else local_ptr.ptr;
                        if (ri.rl != .ref_const) local_ptr.used_as_lvalue = true;
                        return ptr_inst;
                    },
                    else => {
                        const val_inst = if (num_namespaces_out != 0) try tunnelThroughClosure(
                            gz,
                            ident,
                            num_namespaces_out,
                            .{ .ref_load = local_ptr.ptr },
                            .{ .token = local_ptr.token_src },
                            name_str_index,
                        ) else try gz.addUnNode(.load, local_ptr.ptr, ident);
                        return rvalueNoCoercePreRef(gz, ri, val_inst, ident);
                    },
                }
            }
            continue :find_scope local_ptr.parent.unwrap();
        },
        .gen_zir => |gen_zir| continue :find_scope gen_zir.parent.unwrap(),
        .defer_normal, .defer_error => |defer_scope| continue :find_scope defer_scope.parent.unwrap(),
        .namespace => |ns| {
            if (ns.decls.get(name_str_index)) |i| {
                if (found_already) |f| {
                    return astgen.failNodeNotes(ident, "ambiguous reference", .{}, &.{
                        try astgen.errNoteNode(f, "declared here", .{}),
                        try astgen.errNoteNode(i, "also declared here", .{}),
                    });
                }
                // 已找到匹配项,但必须继续查找对声明的歧义引用。
                found_already = i;
                found_needs_tunnel = ns.maybe_generic;
                found_namespaces_out = num_namespaces_out;
            }
            num_namespaces_out += 1;
            capturing_namespace = ns;
            continue :find_scope ns.parent.unwrap();
        },
        .top => break :find_scope,
    }
    if (found_already == null) {
        const ident_name = try astgen.identifierTokenString(ident_token);
        return astgen.failNode(ident, "use of undeclared identifier '{s}'", .{ident_name});
    }

    // 声明引用通过名称而非 ZIR 索引实现,因此修改无关声明时,
    // 包含对其引用的 ZIR 代码可以保持不变。

    if (found_namespaces_out > 0 and found_needs_tunnel) {
        switch (ri.rl) {
            .ref, .ref_const, .ref_coerced_ty => return tunnelThroughClosure(
                gz,
                ident,
                found_namespaces_out,
                .{ .decl_ref = name_str_index },
                .{ .node = found_already.? },
                name_str_index,
            ),
            else => {
                const result = try tunnelThroughClosure(
                    gz,
                    ident,
                    found_namespaces_out,
                    .{ .decl_val = name_str_index },
                    .{ .node = found_already.? },
                    name_str_index,
                );
                return rvalueNoCoercePreRef(gz, ri, result, ident);
            },
        }
    }

    switch (ri.rl) {
        .ref, .ref_const, .ref_coerced_ty => return gz.addStrTok(.decl_ref, name_str_index, ident_token),
        else => {
            const result = try gz.addStrTok(.decl_val, name_str_index, ident_token);
            return rvalueNoCoercePreRef(gz, ri, result, ident);
        },
    }
}

/// 通过闭包访问 ZIR 指令。可以穿透任意
/// 数量的命名空间,并按需添加闭包捕获。
/// 返回加入 `gz` 的 `closure_get` 指令索引。
fn tunnelThroughClosure(
    gz: *GenZir,
    /// 引用待捕获值的节点。
    inner_ref_node: Ast.Node.Index,
    /// 穿过的命名空间数量。至少为 1。
    num_tunnels: u32,
    /// 被捕获的值。
    value: union(enum) {
        ref: Zir.Inst.Ref,
        ref_load: Zir.Inst.Ref,
        decl_val: Zir.NullTerminatedString,
        decl_ref: Zir.NullTerminatedString,
    },
    /// 值的声明位置。
    decl_src: union(enum) {
        token: Ast.TokenIndex,
        node: Ast.Node.Index,
    },
    name_str_index: Zir.NullTerminatedString,
) !Zir.Inst.Ref {
    switch (value) {
        .ref => |v| if (v.toIndex() == null) return v, // 简单值;无需隧道
        .ref_load => |v| assert(v.toIndex() != null), // 没有常量指针引用
        .decl_val, .decl_ref => {},
    }

    const astgen = gz.astgen;
    const gpa = astgen.gpa;

    // 否则需要建立隧道。首先确定要穿越的
    // 命名空间路径。通常只有一两个,因此使用
    // BFA 优化常见情况。
    var bfa_buf: [2]usize = undefined;
    var bfa: std.heap.BufferFirstAllocator = .init(@ptrCast(&bfa_buf), astgen.arena);
    var intermediate_tunnels = try bfa.allocator().alloc(*Scope.Namespace, num_tunnels - 1);

    const root_ns = ns: {
        var i: usize = num_tunnels - 1;
        var scope: *Scope = gz.parent;
        while (i > 0) {
            if (scope.cast(Scope.Namespace)) |mid_ns| {
                i -= 1;
                intermediate_tunnels[i] = mid_ns;
            }
            scope = scope.parent().?;
        }
        while (true) {
            if (scope.cast(Scope.Namespace)) |ns| break :ns ns;
            scope = scope.parent().?;
        }
    };

    // 现已确定所穿越的作用域,从最外层命名空间开始,
    // 按需添加捕获。
    const root_capture: Zir.Inst.Capture = .wrap(switch (value) {
        .ref => |v| .{ .instruction = v.toIndex().? },
        .ref_load => |v| .{ .instruction_load = v.toIndex().? },
        .decl_val => |str| .{ .decl_val = str },
        .decl_ref => |str| .{ .decl_ref = str },
    });

    const root_gop = try root_ns.captures.getOrPut(gpa, root_capture);
    root_gop.value_ptr.* = name_str_index;
    var cur_capture_index = std.math.cast(u16, root_gop.index) orelse return astgen.failNodeNotes(
        root_ns.node,
        "this compiler implementation only supports up to 65536 captures per namespace",
        .{},
        &.{
            switch (decl_src) {
                .token => |t| try astgen.errNoteTok(t, "captured value here", .{}),
                .node => |n| try astgen.errNoteNode(n, "captured value here", .{}),
            },
            try astgen.errNoteNode(inner_ref_node, "value used here", .{}),
        },
    );

    for (intermediate_tunnels) |tunnel_ns| {
        const tunnel_gop = try tunnel_ns.captures.getOrPut(gpa, .wrap(.{ .nested = cur_capture_index }));
        tunnel_gop.value_ptr.* = name_str_index;
        cur_capture_index = std.math.cast(u16, tunnel_gop.index) orelse return astgen.failNodeNotes(
            tunnel_ns.node,
            "this compiler implementation only supports up to 65536 captures per namespace",
            .{},
            &.{
                switch (decl_src) {
                    .token => |t| try astgen.errNoteTok(t, "captured value here", .{}),
                    .node => |n| try astgen.errNoteNode(n, "captured value here", .{}),
                },
                try astgen.errNoteNode(inner_ref_node, "value used here", .{}),
            },
        );
    }

    // 将捕获索引纳入源码哈希,使捕获顺序变化时
    // 触发相应的重新分析。
    astgen.src_hasher.update(std.mem.asBytes(&cur_capture_index));

    // 添加从闭包获取值的指令。
    return gz.addExtendedNodeSmall(.closure_get, inner_ref_node, cur_capture_index);
}

fn stringLiteral(
    gz: *GenZir,
    ri: ResultInfo,
    node: Ast.Node.Index,
) InnerError!Zir.Inst.Ref {
    const astgen = gz.astgen;
    const tree = astgen.tree;
    const str_lit_token = tree.nodeMainToken(node);
    const str = try astgen.strLitAsString(str_lit_token);
    const result = try gz.add(.{
        .tag = .str,
        .data = .{ .str = .{
            .start = str.index,
            .len = str.len,
        } },
    });
    return rvalue(gz, ri, result, node);
}

fn multilineStringLiteral(
    gz: *GenZir,
    ri: ResultInfo,
    node: Ast.Node.Index,
) InnerError!Zir.Inst.Ref {
    const astgen = gz.astgen;
    const str = try astgen.strLitNodeAsString(node);
    const result = try gz.add(.{
        .tag = .str,
        .data = .{ .str = .{
            .start = str.index,
            .len = str.len,
        } },
    });
    return rvalue(gz, ri, result, node);
}

fn charLiteral(gz: *GenZir, ri: ResultInfo, node: Ast.Node.Index) InnerError!Zir.Inst.Ref {
    const astgen = gz.astgen;
    const tree = astgen.tree;
    const main_token = tree.nodeMainToken(node);
    const slice = tree.tokenSlice(main_token);

    switch (std.zig.parseCharLiteral(slice)) {
        .success => |codepoint| {
            const result = try gz.addInt(codepoint);
            return rvalue(gz, ri, result, node);
        },
        .failure => |err| return astgen.failWithStrLitError(err, main_token, slice, 0),
    }
}

const Sign = enum { negative, positive };

fn numberLiteral(gz: *GenZir, ri: ResultInfo, node: Ast.Node.Index, source_node: Ast.Node.Index, sign: Sign) InnerError!Zir.Inst.Ref {
    const astgen = gz.astgen;
    const tree = astgen.tree;
    const num_token = tree.nodeMainToken(node);
    const bytes = tree.tokenSlice(num_token);

    const result: Zir.Inst.Ref = switch (std.zig.parseNumberLiteral(bytes)) {
        .int => |num| switch (num) {
            0 => if (sign == .positive) .zero else return astgen.failTokNotes(
                num_token,
                "integer literal '-0' is ambiguous",
                .{},
                &.{
                    try astgen.errNoteTok(num_token, "use '0' for an integer zero", .{}),
                    try astgen.errNoteTok(num_token, "use '-0.0' for a floating-point signed zero", .{}),
                },
            ),
            1 => {
                // 在此处理取反!
                const result: Zir.Inst.Ref = switch (sign) {
                    .positive => .one,
                    .negative => .negative_one,
                };
                return rvalue(gz, ri, result, source_node);
            },
            else => try gz.addInt(num),
        },
        .big_int => |base| big: {
            const gpa = astgen.gpa;
            var big_int = try std.math.big.int.Managed.init(gpa);
            defer big_int.deinit();
            const prefix_offset: usize = if (base == .decimal) 0 else 2;
            big_int.setString(@backingInt(base), bytes[prefix_offset..]) catch |err| switch (err) {
                error.InvalidCharacter => unreachable, // 在 `parseNumberLiteral` 中捕获
                error.InvalidBase => unreachable, // 仅传入 16、8、2,参见上文
                error.OutOfMemory => |e| return e,
            };

            const limbs = big_int.limbs[0..big_int.len()];
            assert(big_int.isPositive());
            break :big try gz.addIntBig(limbs);
        },
        .float => {
            const unsigned_float_number = std.fmt.parseFloat(f128, bytes) catch |err| switch (err) {
                error.InvalidCharacter => unreachable, // 由 `parseNumberLiteral` 验证
            };
            const float_number = switch (sign) {
                .negative => -unsigned_float_number,
                .positive => unsigned_float_number,
            };
            // 若值可无精度损失地装入 f64,则以该形式存储。
            @setFloatMode(.strict);
            const smaller_float: f64 = @floatCast(float_number);
            const bigger_again: f128 = smaller_float;
            if (bigger_again == float_number) {
                const result = try gz.addFloat(smaller_float);
                return rvalue(gz, ri, result, source_node);
            }
            // 需要使用 128 位。将浮点数拆分成 4 个 u32 值,
            // 以便放入 `extra` 数组。
            const int_bits: u128 = @bitCast(float_number);
            const result = try gz.addPlNode(.float128, node, Zir.Inst.Float128{
                .piece0 = @truncate(int_bits),
                .piece1 = @truncate(int_bits >> 32),
                .piece2 = @truncate(int_bits >> 64),
                .piece3 = @truncate(int_bits >> 96),
            });
            return rvalue(gz, ri, result, source_node);
        },
        .failure => |err| return astgen.failWithNumberError(err, num_token, bytes),
    };

    if (sign == .positive) {
        return rvalue(gz, ri, result, source_node);
    } else {
        const negated = try gz.addUnNode(.negate, result, source_node);
        return rvalue(gz, ri, negated, source_node);
    }
}

fn failWithNumberError(astgen: *AstGen, err: std.zig.number_literal.Error, token: Ast.TokenIndex, bytes: []const u8) InnerError {
    const is_float = std.mem.findScalar(u8, bytes, '.') != null;
    switch (err) {
        .leading_zero => if (is_float) {
            return astgen.failTok(token, "number '{s}' has leading zero", .{bytes});
        } else {
            return astgen.failTokNotes(token, "number '{s}' has leading zero", .{bytes}, &.{
                try astgen.errNoteTok(token, "use '0o' prefix for octal literals", .{}),
            });
        },
        .digit_after_base => return astgen.failTok(token, "expected a digit after base prefix", .{}),
        .upper_case_base => |i| return astgen.failOff(token, @intCast(i), "base prefix must be lowercase", .{}),
        .invalid_float_base => |i| return astgen.failOff(token, @intCast(i), "invalid base for float literal", .{}),
        .repeated_underscore => |i| return astgen.failOff(token, @intCast(i), "repeated digit separator", .{}),
        .invalid_underscore_after_special => |i| return astgen.failOff(token, @intCast(i), "expected digit before digit separator", .{}),
        .invalid_digit => |info| return astgen.failOff(token, @intCast(info.i), "invalid digit '{c}' for {s} base", .{ bytes[info.i], @tagName(info.base) }),
        .invalid_digit_exponent => |i| return astgen.failOff(token, @intCast(i), "invalid digit '{c}' in exponent", .{bytes[i]}),
        .duplicate_exponent => |i| return astgen.failOff(token, @intCast(i), "duplicate exponent", .{}),
        .exponent_after_underscore => |i| return astgen.failOff(token, @intCast(i), "expected digit before exponent", .{}),
        .special_after_underscore => |i| return astgen.failOff(token, @intCast(i), "expected digit before '{c}'", .{bytes[i]}),
        .trailing_special => |i| return astgen.failOff(token, @intCast(i), "expected digit after '{c}'", .{bytes[i - 1]}),
        .trailing_underscore => |i| return astgen.failOff(token, @intCast(i), "trailing digit separator", .{}),
        .duplicate_period => unreachable, // 由词法分析器验证
        .invalid_character => unreachable, // 由词法分析器验证
        .invalid_exponent_sign => |i| {
            assert(bytes.len >= 2 and bytes[0] == '0' and bytes[1] == 'x'); // 由词法分析器验证
            return astgen.failOff(token, @intCast(i), "sign '{c}' cannot follow digit '{c}' in hex base", .{ bytes[i], bytes[i - 1] });
        },
        .period_after_exponent => |i| return astgen.failOff(token, @intCast(i), "unexpected period after exponent", .{}),
    }
}

fn asmExpr(
    gz: *GenZir,
    scope: *Scope,
    ri: ResultInfo,
    node: Ast.Node.Index,
    full: Ast.full.Asm,
) InnerError!Zir.Inst.Ref {
    const astgen = gz.astgen;
    const tree = astgen.tree;

    const TagAndTmpl = struct { tag: Zir.Inst.Extended, tmpl: Zir.NullTerminatedString };
    const tag_and_tmpl: TagAndTmpl = switch (tree.nodeTag(full.ast.template)) {
        .string_literal => .{
            .tag = .@"asm",
            .tmpl = (try astgen.strLitAsString(tree.nodeMainToken(full.ast.template))).index,
        },
        .multiline_string_literal => .{
            .tag = .@"asm",
            .tmpl = (try astgen.strLitNodeAsString(full.ast.template)).index,
        },
        else => .{
            .tag = .asm_expr,
            .tmpl = @fromBackingInt(@intCast(@backingInt(try comptimeExpr(gz, scope, .{ .rl = .none }, full.ast.template, .inline_assembly_code)))),
        },
    };

    // 关于内联汇编可能的改进,参见 https://github.com/ziglang/zig/issues/215
    // 及相关议题。在此之前,这里保持汇编语法现有的 AstGen 处理方式。
    // 标准库的密码学代码 aesni.zig 会使用它。
    const is_container_asm = astgen.fn_block == null;
    if (is_container_asm) {
        if (full.volatile_token) |t|
            return astgen.failTok(t, "volatile is meaningless on global assembly", .{});
        if (full.outputs.len != 0 or full.inputs.len != 0 or full.ast.clobbers != .none)
            return astgen.failNode(node, "global assembly cannot have inputs, outputs, or clobbers", .{});
    } else {
        if (full.outputs.len == 0 and full.volatile_token == null) {
            return astgen.failNode(node, "assembly expression with no output must be marked volatile", .{});
        }
    }
    if (full.outputs.len >= 16) {
        return astgen.failNode(full.outputs[16], "too many asm outputs", .{});
    }
    var outputs_buffer: [15]Zir.Inst.Asm.Output = undefined;
    const outputs = outputs_buffer[0..full.outputs.len];

    var output_type_bits: u32 = 0;

    for (full.outputs, 0..) |output_node, i| {
        const symbolic_name = tree.nodeMainToken(output_node);
        const name = try astgen.identAsString(symbolic_name);
        const constraint_token = symbolic_name + 2;
        const constraint = (try astgen.strLitAsString(constraint_token)).index;
        const has_arrow = tree.tokenTag(symbolic_name + 4) == .arrow;
        if (has_arrow) {
            if (output_type_bits != 0) {
                return astgen.failNode(output_node, "inline assembly allows up to one output value", .{});
            }
            output_type_bits |= @as(u32, 1) << @intCast(i);
            const out_type_node = tree.nodeData(output_node).opt_node_and_token[0].unwrap().?;
            const out_type_inst = try typeExpr(gz, scope, out_type_node);
            outputs[i] = .{
                .name = name,
                .constraint = constraint,
                .operand = out_type_inst,
            };
        } else {
            const ident_token = symbolic_name + 4;
            // TODO: 查看 #215 及相关问题,决定如何
            // 处理输出。是否应使用标识符?
            // 或者要求它们必须是指针类型表达式?
            outputs[i] = .{
                .name = name,
                .constraint = constraint,
                .operand = try localVarRef(gz, scope, .{ .rl = .ref }, node, ident_token),
            };
        }
    }

    if (full.inputs.len >= 32) {
        return astgen.failNode(full.inputs[32], "too many asm inputs", .{});
    }
    var inputs_buffer: [31]Zir.Inst.Asm.Input = undefined;
    const inputs = inputs_buffer[0..full.inputs.len];

    for (full.inputs, 0..) |input_node, i| {
        const symbolic_name = tree.nodeMainToken(input_node);
        const name = try astgen.identAsString(symbolic_name);
        const constraint_token = symbolic_name + 2;
        const constraint = (try astgen.strLitAsString(constraint_token)).index;
        const operand = try expr(gz, scope, .{ .rl = .none }, tree.nodeData(input_node).node_and_token[0]);
        inputs[i] = .{
            .name = name,
            .constraint = constraint,
            .operand = operand,
        };
    }

    const clobbers: Zir.Inst.Ref = if (full.ast.clobbers.unwrap()) |clobbers_node|
        try comptimeExpr(gz, scope, .{ .rl = .{
            .coerced_ty = try gz.addStdLangValue(clobbers_node, .clobbers),
        } }, clobbers_node, .clobber)
    else
        .none;

    const result = try gz.addAsm(.{
        .tag = tag_and_tmpl.tag,
        .node = node,
        .asm_source = tag_and_tmpl.tmpl,
        .is_volatile = full.volatile_token != null,
        .output_type_bits = output_type_bits,
        .outputs = outputs,
        .inputs = inputs,
        .clobbers = clobbers,
    });
    return rvalue(gz, ri, result, node);
}

fn as(
    gz: *GenZir,
    scope: *Scope,
    ri: ResultInfo,
    node: Ast.Node.Index,
    lhs: Ast.Node.Index,
    rhs: Ast.Node.Index,
) InnerError!Zir.Inst.Ref {
    const dest_type = try typeExpr(gz, scope, lhs);
    const result = try reachableExpr(gz, scope, .{ .rl = .{ .ty = dest_type } }, rhs, node);
    return rvalue(gz, ri, result, node);
}

fn unionInit(
    gz: *GenZir,
    scope: *Scope,
    ri: ResultInfo,
    node: Ast.Node.Index,
    params: []const Ast.Node.Index,
) InnerError!Zir.Inst.Ref {
    const union_type = try typeExpr(gz, scope, params[0]);
    const field_name = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = .slice_const_u8_type } }, params[1], .union_field_names);
    const field_type = try gz.addPlNode(.field_type_ref, node, Zir.Inst.FieldTypeRef{
        .container_type = union_type,
        .field_name = field_name,
    });
    const init = try reachableExpr(gz, scope, .{ .rl = .{ .ty = field_type } }, params[2], node);
    const result = try gz.addPlNode(.union_init, node, Zir.Inst.UnionInit{
        .union_type = union_type,
        .init = init,
        .field_name = field_name,
    });
    return rvalue(gz, ri, result, node);
}

fn bitCast(
    gz: *GenZir,
    scope: *Scope,
    ri: ResultInfo,
    node: Ast.Node.Index,
    operand_node: Ast.Node.Index,
) InnerError!Zir.Inst.Ref {
    const cursor = maybeAdvanceSourceCursorToMainToken(gz, node);
    const dest_type = try ri.rl.resultTypeForCast(gz, node, "@bitCast");
    const operand = try reachableExpr(gz, scope, .{ .rl = .none }, operand_node, node);

    try emitDbgStmt(gz, cursor);
    const result = try gz.addPlNode(.bitcast, node, Zir.Inst.Bin{
        .lhs = dest_type,
        .rhs = operand,
    });
    return rvalue(gz, ri, result, node);
}

/// 处理一个或多个嵌套的指针转换内置函数:
/// * @ptrCast
/// * @alignCast
/// * @addrSpaceCast
/// * @constCast
/// * @volatileCast
/// 这些内置函数的任意序列均视为单个操作。这样,
/// 即使中间结果类型未知,`@ptrCast(@alignCast(ptr))`
/// 等序列也能正确工作。
fn ptrCast(
    gz: *GenZir,
    scope: *Scope,
    ri: ResultInfo,
    root_node: Ast.Node.Index,
) InnerError!Zir.Inst.Ref {
    const astgen = gz.astgen;
    const tree = astgen.tree;

    const FlagsInt = @typeInfo(Zir.Inst.FullPtrCastFlags).@"struct".backing_integer.?;
    var flags: Zir.Inst.FullPtrCastFlags = .{};

    // 注意,所有指针转换内置函数均只有一个参数,因此只需
    // 处理 `builtin_call_two`。
    var node = root_node;
    while (true) {
        switch (tree.nodeTag(node)) {
            .builtin_call_two, .builtin_call_two_comma => {},
            .grouped_expression => {
                // 即使有多余圆括号,也处理链式表达式。
                node = tree.nodeData(node).node_and_token[0];
                continue;
            },
            else => break,
        }

        var buf: [2]Ast.Node.Index = undefined;
        const args = tree.builtinCallParams(&buf, node).?;
        std.debug.assert(args.len <= 2);

        if (args.len == 0) break; // 0 个参数

        const builtin_token = tree.nodeMainToken(node);
        const builtin_name = tree.tokenSlice(builtin_token);
        const info = BuiltinFn.list.get(builtin_name) orelse break;
        if (args.len == 1) {
            if (info.param_count != 1) break;

            switch (info.tag) {
                else => break,
                inline .ptr_cast,
                .align_cast,
                .addrspace_cast,
                .const_cast,
                .volatile_cast,
                => |tag| {
                    if (@field(flags, @tagName(tag))) {
                        return astgen.failNode(node, "redundant {s}", .{builtin_name});
                    }
                    @field(flags, @tagName(tag)) = true;
                },
            }

            node = args[0];
        } else {
            std.debug.assert(args.len == 2);
            if (info.param_count != 2) break;

            switch (info.tag) {
                else => break,
                .field_parent_ptr => {
                    if (flags.ptr_cast) break;

                    const flags_int: FlagsInt = @bitCast(flags);
                    const cursor = maybeAdvanceSourceCursorToMainToken(gz, root_node);
                    const parent_ptr_type = try ri.rl.resultTypeForCast(gz, root_node, "@alignCast");
                    const field_name = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = .slice_const_u8_type } }, args[0], .field_name);
                    const field_ptr = try expr(gz, scope, .{ .rl = .none }, args[1]);
                    try emitDbgStmt(gz, cursor);
                    const result = try gz.addExtendedPayloadSmall(.field_parent_ptr, flags_int, Zir.Inst.FieldParentPtr{
                        .src_node = gz.nodeIndexToRelative(node),
                        .parent_ptr_type = parent_ptr_type,
                        .field_name = field_name,
                        .field_ptr = field_ptr,
                    });
                    return rvalue(gz, ri, result, root_node);
                },
            }
        }
    }

    const flags_int: FlagsInt = @bitCast(flags);
    assert(flags_int != 0);

    const ptr_only: Zir.Inst.FullPtrCastFlags = .{ .ptr_cast = true };
    if (flags_int == @as(FlagsInt, @bitCast(ptr_only))) {
        // 特殊情况:更简单的表示
        return typeCast(gz, scope, ri, root_node, node, .ptr_cast, "@ptrCast");
    }

    const no_result_ty_flags: Zir.Inst.FullPtrCastFlags = .{
        .const_cast = true,
        .volatile_cast = true,
    };
    if ((flags_int & ~@as(FlagsInt, @bitCast(no_result_ty_flags))) == 0) {
        // 不需要结果类型
        const cursor = maybeAdvanceSourceCursorToMainToken(gz, root_node);
        const operand = try expr(gz, scope, .{ .rl = .none }, node);
        try emitDbgStmt(gz, cursor);
        const result = try gz.addExtendedPayloadSmall(.ptr_cast_no_dest, flags_int, Zir.Inst.UnNode{
            .node = gz.nodeIndexToRelative(root_node),
            .operand = operand,
        });
        return rvalue(gz, ri, result, root_node);
    }

    // 包括结果类型的完整类型转换

    const cursor = maybeAdvanceSourceCursorToMainToken(gz, root_node);
    const result_type = try ri.rl.resultTypeForCast(gz, root_node, flags.needResultTypeBuiltinName());
    const operand = try expr(gz, scope, .{ .rl = .none }, node);
    try emitDbgStmt(gz, cursor);
    const result = try gz.addExtendedPayloadSmall(.ptr_cast_full, flags_int, Zir.Inst.BinNode{
        .node = gz.nodeIndexToRelative(root_node),
        .lhs = result_type,
        .rhs = operand,
    });
    return rvalue(gz, ri, result, root_node);
}

fn typeOf(
    gz: *GenZir,
    scope: *Scope,
    ri: ResultInfo,
    node: Ast.Node.Index,
    args: []const Ast.Node.Index,
) InnerError!Zir.Inst.Ref {
    const astgen = gz.astgen;
    if (args.len < 1) {
        return astgen.failNode(node, "expected at least 1 argument, found 0", .{});
    }
    const gpa = astgen.gpa;
    if (args.len == 1) {
        const typeof_inst = try gz.makeBlockInst(.typeof_builtin, node);

        var typeof_scope = gz.makeSubBlock(scope);
        typeof_scope.is_comptime = false;
        typeof_scope.is_typeof = true;
        defer typeof_scope.unstack();

        const ty_expr = try reachableExpr(&typeof_scope, &typeof_scope.base, .{ .rl = .none }, args[0], node);
        if (!gz.refIsNoReturn(ty_expr)) {
            _ = try typeof_scope.addBreak(.break_inline, typeof_inst, ty_expr);
        }
        try typeof_scope.setBlockBody(typeof_inst);

        // typeof_scope 已弹出,现在可向 gz 添加新指令。
        try gz.instructions.append(gpa, typeof_inst);
        return rvalue(gz, ri, typeof_inst.toRef(), node);
    }
    const payload_size: u32 = @typeInfo(Zir.Inst.TypeOfPeer).@"struct".field_names.len;
    const payload_index = try reserveExtra(astgen, payload_size + args.len);
    const args_index = payload_index + payload_size;

    const typeof_inst = try gz.addExtendedMultiOpPayloadIndex(.typeof_peer, payload_index, args.len);

    var typeof_scope = gz.makeSubBlock(scope);
    typeof_scope.is_comptime = false;

    for (args, 0..) |arg, i| {
        const param_ref = try reachableExpr(&typeof_scope, &typeof_scope.base, .{ .rl = .none }, arg, node);
        astgen.extra.items[args_index + i] = @backingInt(param_ref);
    }
    _ = try typeof_scope.addBreak(.break_inline, typeof_inst.toIndex().?, .void_value);

    const body = typeof_scope.instructionsSlice();
    const body_len = astgen.countBodyLenAfterFixups(body);
    astgen.setExtra(payload_index, Zir.Inst.TypeOfPeer{
        .body_len = @intCast(body_len),
        .body_index = @intCast(astgen.extra.items.len),
        .src_node = gz.nodeIndexToRelative(node),
    });
    try astgen.extra.ensureUnusedCapacity(gpa, body_len);
    astgen.appendBodyWithFixups(body);
    typeof_scope.unstack();

    return rvalue(gz, ri, typeof_inst, node);
}

fn minMax(
    gz: *GenZir,
    scope: *Scope,
    ri: ResultInfo,
    node: Ast.Node.Index,
    args: []const Ast.Node.Index,
    comptime op: enum { min, max },
) InnerError!Zir.Inst.Ref {
    const astgen = gz.astgen;
    if (args.len < 2) {
        return astgen.failNode(node, "expected at least 2 arguments, found {}", .{args.len});
    }
    if (args.len == 2) {
        const tag: Zir.Inst.Tag = switch (op) {
            .min => .min,
            .max => .max,
        };
        const a = try expr(gz, scope, .{ .rl = .none }, args[0]);
        const b = try expr(gz, scope, .{ .rl = .none }, args[1]);
        const result = try gz.addPlNode(tag, node, Zir.Inst.Bin{
            .lhs = a,
            .rhs = b,
        });
        return rvalue(gz, ri, result, node);
    }
    const payload_index = try addExtra(astgen, Zir.Inst.NodeMultiOp{
        .src_node = gz.nodeIndexToRelative(node),
    });
    var extra_index = try reserveExtra(gz.astgen, args.len);
    for (args) |arg| {
        const arg_ref = try expr(gz, scope, .{ .rl = .none }, arg);
        astgen.extra.items[extra_index] = @backingInt(arg_ref);
        extra_index += 1;
    }
    const tag: Zir.Inst.Extended = switch (op) {
        .min => .min_multi,
        .max => .max_multi,
    };
    const result = try gz.addExtendedMultiOpPayloadIndex(tag, payload_index, args.len);
    return rvalue(gz, ri, result, node);
}

fn builtinCall(
    gz: *GenZir,
    scope: *Scope,
    ri: ResultInfo,
    node: Ast.Node.Index,
    params: []const Ast.Node.Index,
    allow_branch_hint: bool,
    reify_name_strat: Zir.Inst.NameStrategy,
) InnerError!Zir.Inst.Ref {
    const astgen = gz.astgen;
    const tree = astgen.tree;

    const builtin_token = tree.nodeMainToken(node);
    const builtin_name = tree.tokenSlice(builtin_token);

    // 手动处理不同内置函数,因为它们的语义因函数而异。
    // 例如,`@as` 等参与结果位置语义。
    // 此外,某些内置函数的参数个数可变。

    const info = BuiltinFn.list.get(builtin_name) orelse {
        return astgen.failNode(node, "invalid builtin function: '{s}'", .{
            builtin_name,
        });
    };
    if (info.param_count) |expected| {
        if (expected != params.len) {
            const s = if (expected == 1) "" else "s";
            return astgen.failNode(node, "expected {d} argument{s}, found {d}", .{
                expected, s, params.len,
            });
        }
    }

    // 检查仅限函数作用域的内置函数

    if (astgen.fn_block == null and info.illegal_outside_function)
        return astgen.failNode(node, "'{s}' outside function scope", .{builtin_name});

    switch (info.tag) {
        .branch_hint => {
            if (!allow_branch_hint) {
                return astgen.failNode(node, "'@branchHint' must appear as the first statement in a function or conditional branch", .{});
            }
            const hint_ty = try gz.addStdLangValue(node, .branch_hint);
            const hint_val = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = hint_ty } }, params[0], .operand_branchHint);
            _ = try gz.addExtendedPayload(.branch_hint, Zir.Inst.UnNode{
                .node = gz.nodeIndexToRelative(node),
                .operand = hint_val,
            });
            return rvalue(gz, ri, .void_value, node);
        },
        .import => {
            const operand_node = params[0];

            if (tree.nodeTag(operand_node) != .string_literal) {
                // 规范参考:https://github.com/ziglang/zig/issues/2206
                return astgen.failNode(operand_node, "@import operand must be a string literal", .{});
            }
            const str_lit_token = tree.nodeMainToken(operand_node);
            const str = try astgen.strLitAsString(str_lit_token);
            const str_slice = astgen.string_bytes.items[@backingInt(str.index)..][0..str.len];
            if (mem.findScalar(u8, str_slice, 0) != null) {
                return astgen.failTok(str_lit_token, "import path cannot contain null bytes", .{});
            } else if (str.len == 0) {
                return astgen.failTok(str_lit_token, "import path cannot be empty", .{});
            }
            const res_ty = try ri.rl.resultType(gz, node) orelse .none;
            const payload_index = try addExtra(gz.astgen, Zir.Inst.Import{
                .res_ty = res_ty,
                .path = str.index,
            });
            const result = try gz.add(.{
                .tag = .import,
                .data = .{ .pl_tok = .{
                    .src_tok = gz.tokenIndexToRelative(str_lit_token),
                    .payload_index = payload_index,
                } },
            });
            const gop = try astgen.imports.getOrPut(astgen.gpa, str.index);
            if (!gop.found_existing) {
                gop.value_ptr.* = str_lit_token;
            }
            return rvalue(gz, ri, result, node);
        },
        .compile_log => {
            const payload_index = try addExtra(gz.astgen, Zir.Inst.NodeMultiOp{
                .src_node = gz.nodeIndexToRelative(node),
            });
            var extra_index = try reserveExtra(gz.astgen, params.len);
            for (params) |param| {
                const param_ref = try expr(gz, scope, .{ .rl = .none }, param);
                astgen.extra.items[extra_index] = @backingInt(param_ref);
                extra_index += 1;
            }
            const result = try gz.addExtendedMultiOpPayloadIndex(.compile_log, payload_index, params.len);
            return rvalue(gz, ri, result, node);
        },
        .field => {
            switch (ri.rl) {
                .ref, .ref_coerced_ty => {
                    return gz.addPlNode(.field_ptr_named, node, Zir.Inst.FieldNamed{
                        .lhs = try expr(gz, scope, .{ .rl = .ref }, params[0]),
                        .field_name = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = .slice_const_u8_type } }, params[1], .field_name),
                    });
                },
                .ref_const => {
                    return gz.addPlNode(.field_ptr_named, node, Zir.Inst.FieldNamed{
                        .lhs = try expr(gz, scope, .{ .rl = .ref_const }, params[0]),
                        .field_name = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = .slice_const_u8_type } }, params[1], .field_name),
                    });
                },
                else => {
                    const result = try gz.addPlNode(.field_ptr_named_load, node, Zir.Inst.FieldNamed{
                        .lhs = try expr(gz, scope, .{ .rl = .ref_const }, params[0]),
                        .field_name = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = .slice_const_u8_type } }, params[1], .field_name),
                    });
                    return rvalue(gz, ri, result, node);
                },
            }
        },
        .FieldType => {
            const ty_inst = try typeExpr(gz, scope, params[0]);
            const name_inst = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = .slice_const_u8_type } }, params[1], .field_name);
            const result = try gz.addPlNode(.field_type_ref, node, Zir.Inst.FieldTypeRef{
                .container_type = ty_inst,
                .field_name = name_inst,
            });
            return rvalue(gz, ri, result, node);
        },

        // zig fmt: off
        .as         => return as(       gz, scope, ri, node, params[0], params[1]),
        .bit_cast   => return bitCast(  gz, scope, ri, node, params[0]),
        .TypeOf     => return typeOf(   gz, scope, ri, node, params),
        .union_init => return unionInit(gz, scope, ri, node, params),
        .min        => return minMax(   gz, scope, ri, node, params, .min),
        .max        => return minMax(   gz, scope, ri, node, params, .max),
        // zig fmt: on

        .@"export" => {
            const exported = try expr(gz, scope, .{ .rl = .none }, params[0]);
            const export_options_ty = try gz.addStdLangValue(node, .export_options);
            const options = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = export_options_ty } }, params[1], .export_options);
            _ = try gz.addPlNode(.@"export", node, Zir.Inst.Export{
                .exported = exported,
                .options = options,
            });
            return rvalue(gz, ri, .void_value, node);
        },
        .@"extern" => {
            const type_inst = try typeExpr(gz, scope, params[0]);
            const extern_options_ty = try gz.addStdLangValue(node, .extern_options);
            const options = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = extern_options_ty } }, params[1], .extern_options);
            const result = try gz.addExtendedPayload(.builtin_extern, Zir.Inst.BinNode{
                .node = gz.nodeIndexToRelative(node),
                .lhs = type_inst,
                .rhs = options,
            });
            return rvalue(gz, ri, result, node);
        },
        .set_float_mode => {
            const float_mode_ty = try gz.addStdLangValue(node, .float_mode);
            const order = try expr(gz, scope, .{ .rl = .{ .coerced_ty = float_mode_ty } }, params[0]);
            _ = try gz.addExtendedPayload(.set_float_mode, Zir.Inst.UnNode{
                .node = gz.nodeIndexToRelative(node),
                .operand = order,
            });
            return rvalue(gz, ri, .void_value, node);
        },

        .src => {
            // 将源码位置纳入源码哈希,使
            // `@src()` 的源码位置变化会触发重新分析。
            astgen.src_hasher.update(
                std.mem.asBytes(&astgen.source_line) ++
                    std.mem.asBytes(&astgen.source_column),
            );

            const node_start = tree.tokenStart(tree.firstToken(node));
            astgen.advanceSourceCursor(node_start);
            const result = try gz.addExtendedPayload(.builtin_src, Zir.Inst.Src{
                .node = gz.nodeIndexToRelative(node),
                .line = astgen.source_line,
                .column = astgen.source_column,
            });
            return rvalue(gz, ri, result, node);
        },

        // zig fmt: off
        .This                    => return rvalue(gz, ri, try gz.addNodeExtended(.this,                    node), node),
        .return_address          => return rvalue(gz, ri, try gz.addNodeExtended(.ret_addr,                node), node),
        .error_return_trace      => return rvalue(gz, ri, try gz.addNodeExtended(.error_return_trace,      node), node),
        .frame                   => return rvalue(gz, ri, try gz.addNodeExtended(.frame,                   node), node),
        .frame_address           => return rvalue(gz, ri, try gz.addNodeExtended(.frame_address,           node), node),
        .breakpoint              => return rvalue(gz, ri, try gz.addNodeExtended(.breakpoint,              node), node),
        .disable_instrumentation => return rvalue(gz, ri, try gz.addNodeExtended(.disable_instrumentation, node), node),
        .disable_intrinsics      => return rvalue(gz, ri, try gz.addNodeExtended(.disable_intrinsics,      node), node),

        .type_info   => return simpleUnOpType(gz, scope, ri, node, params[0], .type_info),
        .size_of     => return simpleUnOpType(gz, scope, ri, node, params[0], .size_of),
        .bit_size_of => return simpleUnOpType(gz, scope, ri, node, params[0], .bit_size_of),
        .align_of    => return simpleUnOpType(gz, scope, ri, node, params[0], .align_of),

        .int_from_ptr          => return simpleUnOp(gz, scope, ri, node, .{ .rl = .none },                                     params[0], .int_from_ptr),
        .compile_error         => return simpleUnOp(gz, scope, ri, node, .{ .rl = .{ .coerced_ty = .slice_const_u8_type } },   params[0], .compile_error),
        .set_eval_branch_quota => return simpleUnOp(gz, scope, ri, node, .{ .rl = .{ .coerced_ty = .u32_type } },              params[0], .set_eval_branch_quota),
        .int_from_enum         => return simpleUnOp(gz, scope, ri, node, .{ .rl = .none },                                     params[0], .int_from_enum),
        .int_from_bool         => return simpleUnOp(gz, scope, ri, node, .{ .rl = .none },                                     params[0], .int_from_bool),
        .backing_int           => return simpleUnOp(gz, scope, ri, node, .{ .rl = .none },                                     params[0], .backing_int),
        .embed_file            => return simpleUnOp(gz, scope, ri, node, .{ .rl = .{ .coerced_ty = .slice_const_u8_type } },   params[0], .embed_file),
        .error_name            => return simpleUnOp(gz, scope, ri, node, .{ .rl = .{ .coerced_ty = .anyerror_type } },         params[0], .error_name),
        .set_runtime_safety    => return simpleUnOp(gz, scope, ri, node, coerced_bool_ri,                                      params[0], .set_runtime_safety),
        .abs                   => return simpleUnOp(gz, scope, ri, node, .{ .rl = .none },                                     params[0], .abs),
        .tag_name              => return simpleUnOp(gz, scope, ri, node, .{ .rl = .none },                                     params[0], .tag_name),
        .type_name             => return simpleUnOp(gz, scope, ri, node, .{ .rl = .none },                                     params[0], .type_name),
        .Frame                 => return simpleUnOp(gz, scope, ri, node, .{ .rl = .none },                                     params[0], .frame_type),

        .sqrt  => return floatUnOp(gz, scope, ri, node, params[0], .sqrt),
        .sin   => return floatUnOp(gz, scope, ri, node, params[0], .sin),
        .cos   => return floatUnOp(gz, scope, ri, node, params[0], .cos),
        .tan   => return floatUnOp(gz, scope, ri, node, params[0], .tan),
        .exp   => return floatUnOp(gz, scope, ri, node, params[0], .exp),
        .exp2  => return floatUnOp(gz, scope, ri, node, params[0], .exp2),
        .log   => return floatUnOp(gz, scope, ri, node, params[0], .log),
        .log2  => return floatUnOp(gz, scope, ri, node, params[0], .log2),
        .log10 => return floatUnOp(gz, scope, ri, node, params[0], .log10),
        .floor => return floatRoundOp(gz, scope, ri, node, params[0], .floor),
        .ceil  => return floatRoundOp(gz, scope, ri, node, params[0], .ceil),
        .trunc => return floatRoundOp(gz, scope, ri, node, params[0], .trunc),
        .round => return floatRoundOp(gz, scope, ri, node, params[0], .round),

        .int_from_float => return typeCast(gz, scope, ri, node, params[0], .int_from_float, builtin_name),
        .float_from_int => return typeCast(gz, scope, ri, node, params[0], .float_from_int, builtin_name),
        .ptr_from_int   => return typeCast(gz, scope, ri, node, params[0], .ptr_from_int, builtin_name),
        .enum_from_int  => return typeCast(gz, scope, ri, node, params[0], .enum_from_int, builtin_name),
        .float_cast     => return typeCast(gz, scope, ri, node, params[0], .float_cast, builtin_name),
        .int_cast       => return typeCast(gz, scope, ri, node, params[0], .int_cast, builtin_name),
        .truncate       => return typeCast(gz, scope, ri, node, params[0], .truncate, builtin_name),
        // zig fmt: on

        .from_backing_int => {
            const cursor = maybeAdvanceSourceCursorToMainToken(gz, node);
            const result_ty = try ri.rl.resultTypeForCast(gz, node, builtin_name);
            const backing_int_ty = try gz.addUnNode(.from_backing_int_arg_ty, result_ty, node);
            const operand = try expr(gz, scope, .{ .rl = .{ .coerced_ty = backing_int_ty } }, params[0]);

            try emitDbgStmt(gz, cursor);
            const result = try gz.addPlNode(.from_backing_int, node, Zir.Inst.Bin{
                .lhs = result_ty,
                .rhs = operand,
            });
            return rvalue(gz, ri, result, node);
        },

        .in_comptime => if (gz.is_comptime) {
            return astgen.failNode(node, "redundant '@inComptime' in comptime scope", .{});
        } else {
            return rvalue(gz, ri, try gz.addNodeExtended(.in_comptime, node), node);
        },

        .EnumLiteral => return rvalue(gz, ri, .enum_literal_type, node),
        .Int => {
            const signedness_ty = try gz.addStdLangValue(node, .signedness);
            const result = try gz.addPlNode(.reify_int, node, Zir.Inst.Bin{
                .lhs = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = signedness_ty } }, params[0], .int_signedness),
                .rhs = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = .u16_type } }, params[1], .int_bit_width),
            });
            return rvalue(gz, ri, result, node);
        },
        .Tuple => {
            const result = try gz.addExtendedPayload(.reify_tuple, Zir.Inst.UnNode{
                .node = gz.nodeIndexToRelative(node),
                .operand = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = .slice_const_type_type } }, params[0], .tuple_field_types),
            });
            return rvalue(gz, ri, result, node);
        },
        .Pointer => {
            const ptr_size_ty = try gz.addStdLangValue(node, .pointer_size);
            const ptr_attrs_ty = try gz.addStdLangValue(node, .pointer_attributes);
            const size = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = ptr_size_ty } }, params[0], .pointer_size);
            const attrs = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = ptr_attrs_ty } }, params[1], .pointer_attrs);
            const elem_ty = try typeExpr(gz, scope, params[2]);
            const sentinel_ty = try gz.addExtendedPayload(.reify_pointer_sentinel_ty, Zir.Inst.UnNode{
                .node = gz.nodeIndexToRelative(params[2]),
                .operand = elem_ty,
            });
            const sentinel = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = sentinel_ty } }, params[3], .pointer_sentinel);
            const result = try gz.addExtendedPayload(.reify_pointer, Zir.Inst.ReifyPointer{
                .node = gz.nodeIndexToRelative(node),
                .size = size,
                .attrs = attrs,
                .elem_ty = elem_ty,
                .sentinel = sentinel,
            });
            return rvalue(gz, ri, result, node);
        },
        .Fn => {
            const fn_attrs_ty = try gz.addStdLangValue(node, .fn_attributes);
            const param_types = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = .slice_const_type_type } }, params[0], .fn_param_types);
            const param_attrs_ty = try gz.addExtendedPayloadSmall(
                .reify_slice_arg_ty,
                @backingInt(Zir.Inst.ReifySliceArgInfo.type_to_fn_param_attrs),
                Zir.Inst.UnNode{ .node = gz.nodeIndexToRelative(params[0]), .operand = param_types },
            );
            const param_attrs = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = param_attrs_ty } }, params[1], .fn_param_attrs);
            const ret_ty = try comptimeExpr(gz, scope, coerced_type_ri, params[2], .fn_ret_ty);
            const fn_attrs = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = fn_attrs_ty } }, params[3], .fn_attrs);
            const result = try gz.addExtendedPayload(.reify_fn, Zir.Inst.ReifyFn{
                .node = gz.nodeIndexToRelative(node),
                .param_types = param_types,
                .param_attrs = param_attrs,
                .ret_ty = ret_ty,
                .fn_attrs = fn_attrs,
            });
            return rvalue(gz, ri, result, node);
        },
        .Struct => {
            const container_layout_ty = try gz.addStdLangValue(node, .container_layout);
            const layout = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = container_layout_ty } }, params[0], .struct_layout);
            const backing_ty = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = .optional_type_type } }, params[1], .type);
            const field_names = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = .slice_const_slice_const_u8_type } }, params[2], .struct_field_names);
            const field_types_ty = try gz.addExtendedPayloadSmall(
                .reify_slice_arg_ty,
                @backingInt(Zir.Inst.ReifySliceArgInfo.string_to_struct_field_type),
                Zir.Inst.UnNode{ .node = gz.nodeIndexToRelative(params[2]), .operand = field_names },
            );
            const field_attrs_ty = try gz.addExtendedPayloadSmall(
                .reify_slice_arg_ty,
                @backingInt(Zir.Inst.ReifySliceArgInfo.string_to_struct_field_attrs),
                Zir.Inst.UnNode{ .node = gz.nodeIndexToRelative(params[2]), .operand = field_names },
            );
            const field_types = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = field_types_ty } }, params[3], .struct_field_types);
            const field_attrs = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = field_attrs_ty } }, params[4], .struct_field_attrs);
            const result = try gz.addExtendedPayloadSmall(.reify_struct, @backingInt(reify_name_strat), Zir.Inst.ReifyStruct{
                .src_line = gz.astgen.source_line,
                .src_column = gz.astgen.source_column,
                .node = node,
                .layout = layout,
                .backing_ty = backing_ty,
                .field_names = field_names,
                .field_types = field_types,
                .field_attrs = field_attrs,
            });
            return rvalue(gz, ri, result, node);
        },
        .Union => {
            const container_layout_ty = try gz.addStdLangValue(node, .container_layout);
            const layout = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = container_layout_ty } }, params[0], .union_layout);
            const arg_ty = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = .optional_type_type } }, params[1], .type);
            const field_names = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = .slice_const_slice_const_u8_type } }, params[2], .union_field_names);
            const field_types_ty = try gz.addExtendedPayloadSmall(
                .reify_slice_arg_ty,
                @backingInt(Zir.Inst.ReifySliceArgInfo.string_to_union_field_type),
                Zir.Inst.UnNode{ .node = gz.nodeIndexToRelative(params[2]), .operand = field_names },
            );
            const field_attrs_ty = try gz.addExtendedPayloadSmall(
                .reify_slice_arg_ty,
                @backingInt(Zir.Inst.ReifySliceArgInfo.string_to_union_field_attrs),
                Zir.Inst.UnNode{ .node = gz.nodeIndexToRelative(params[2]), .operand = field_names },
            );
            const field_types = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = field_types_ty } }, params[3], .union_field_types);
            const field_attrs = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = field_attrs_ty } }, params[4], .union_field_attrs);
            const result = try gz.addExtendedPayloadSmall(.reify_union, @backingInt(reify_name_strat), Zir.Inst.ReifyUnion{
                .src_line = gz.astgen.source_line,
                .src_column = gz.astgen.source_column,
                .node = node,
                .layout = layout,
                .arg_ty = arg_ty,
                .field_names = field_names,
                .field_types = field_types,
                .field_attrs = field_attrs,
            });
            return rvalue(gz, ri, result, node);
        },
        .Enum => {
            const enum_mode_ty = try gz.addStdLangValue(node, .enum_mode);
            const tag_ty = try typeExpr(gz, scope, params[0]);
            const mode = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = enum_mode_ty } }, params[1], .type);
            const field_names = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = .slice_const_slice_const_u8_type } }, params[2], .enum_field_names);
            const field_values_ty = try gz.addExtendedPayload(.reify_enum_value_slice_ty, Zir.Inst.BinNode{
                .node = gz.nodeIndexToRelative(node),
                .lhs = tag_ty,
                .rhs = field_names,
            });
            const field_values = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = field_values_ty } }, params[3], .enum_field_values);
            const result = try gz.addExtendedPayloadSmall(.reify_enum, @backingInt(reify_name_strat), Zir.Inst.ReifyEnum{
                .src_line = gz.astgen.source_line,
                .src_column = gz.astgen.source_column,
                .node = node,
                .tag_ty = tag_ty,
                .mode = mode,
                .field_names = field_names,
                .field_values = field_values,
            });
            return rvalue(gz, ri, result, node);
        },
        .SpirvType => {
            const spirv_type_options_ty = try gz.addStdLangValue(node, .spirv_type_options);
            const operand = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = spirv_type_options_ty } }, params[0], .type);
            const result = try gz.addExtendedPayload(.reify_spirv_type, Zir.Inst.ReifySpirvType{
                .src_line = gz.astgen.source_line,
                .src_column = gz.astgen.source_column,
                .node = node,
                .operand = operand,
            });
            return rvalue(gz, ri, result, node);
        },

        .panic => {
            try emitDbgNode(gz, node);
            return simpleUnOp(gz, scope, ri, node, .{ .rl = .{ .coerced_ty = .slice_const_u8_type } }, params[0], .panic);
        },
        .trap => {
            try emitDbgNode(gz, node);
            _ = try gz.addNode(.trap, node);
            return rvalue(gz, ri, .unreachable_value, node);
        },
        .int_from_error => {
            const operand = try expr(gz, scope, .{ .rl = .none }, params[0]);
            const result = try gz.addExtendedPayload(.int_from_error, Zir.Inst.UnNode{
                .node = gz.nodeIndexToRelative(node),
                .operand = operand,
            });
            return rvalue(gz, ri, result, node);
        },
        .error_from_int => {
            const operand = try expr(gz, scope, .{ .rl = .none }, params[0]);
            const result = try gz.addExtendedPayload(.error_from_int, Zir.Inst.UnNode{
                .node = gz.nodeIndexToRelative(node),
                .operand = operand,
            });
            return rvalue(gz, ri, result, node);
        },
        .error_cast => {
            try emitDbgNode(gz, node);

            const result = try gz.addExtendedPayload(.error_cast, Zir.Inst.BinNode{
                .lhs = try ri.rl.resultTypeForCast(gz, node, builtin_name),
                .rhs = try expr(gz, scope, .{ .rl = .none }, params[0]),
                .node = gz.nodeIndexToRelative(node),
            });
            return rvalue(gz, ri, result, node);
        },
        .ptr_cast,
        .align_cast,
        .addrspace_cast,
        .const_cast,
        .volatile_cast,
        => return ptrCast(gz, scope, ri, node),

        // zig fmt: off
        .has_decl  => return hasDeclOrField(gz, scope, ri, node, params[0], params[1], .has_decl),
        .has_field => return hasDeclOrField(gz, scope, ri, node, params[0], params[1], .has_field),

        .clz         => return bitBuiltin(gz, scope, ri, node, params[0], .clz),
        .ctz         => return bitBuiltin(gz, scope, ri, node, params[0], .ctz),
        .pop_count   => return bitBuiltin(gz, scope, ri, node, params[0], .pop_count),
        .byte_swap   => return bitBuiltin(gz, scope, ri, node, params[0], .byte_swap),
        .bit_reverse => return bitBuiltin(gz, scope, ri, node, params[0], .bit_reverse),

        .div_exact => return divBuiltin(gz, scope, ri, node, params[0], params[1], .div_exact),
        .div_floor => return divBuiltin(gz, scope, ri, node, params[0], params[1], .div_floor),
        .div_ceil  => return divBuiltin(gz, scope, ri, node, params[0], params[1], .div_ceil),
        .div_trunc => return divBuiltin(gz, scope, ri, node, params[0], params[1], .div_trunc),
        .mod       => return divBuiltin(gz, scope, ri, node, params[0], params[1], .mod),
        .rem       => return divBuiltin(gz, scope, ri, node, params[0], params[1], .rem),

        .shl_exact => return shiftOp(gz, scope, ri, node, params[0], params[1], .shl_exact),
        .shr_exact => return shiftOp(gz, scope, ri, node, params[0], params[1], .shr_exact),

        .bit_offset_of => return offsetOf(gz, scope, ri, node, params[0], params[1], .bit_offset_of),
        .offset_of     => return offsetOf(gz, scope, ri, node, params[0], params[1], .offset_of),

        .cmpxchg_strong => return cmpxchg(gz, scope, ri, node, params, 1),
        .cmpxchg_weak   => return cmpxchg(gz, scope, ri, node, params, 0),
        // zig fmt: on

        .wasm_memory_size => {
            const operand = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = .u32_type } }, params[0], .wasm_memory_index);
            const result = try gz.addExtendedPayload(.wasm_memory_size, Zir.Inst.UnNode{
                .node = gz.nodeIndexToRelative(node),
                .operand = operand,
            });
            return rvalue(gz, ri, result, node);
        },
        .wasm_memory_grow => {
            const index_arg = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = .u32_type } }, params[0], .wasm_memory_index);
            const delta_arg = try expr(gz, scope, .{ .rl = .{ .coerced_ty = .usize_type } }, params[1]);
            const result = try gz.addExtendedPayload(.wasm_memory_grow, Zir.Inst.BinNode{
                .node = gz.nodeIndexToRelative(node),
                .lhs = index_arg,
                .rhs = delta_arg,
            });
            return rvalue(gz, ri, result, node);
        },
        .splat => {
            const result_type = try ri.rl.resultTypeForCast(gz, node, builtin_name);
            const elem_type = try gz.addUnNode(.splat_op_result_ty, result_type, node);
            const scalar = try expr(gz, scope, .{ .rl = .{ .ty = elem_type } }, params[0]);
            const result = try gz.addPlNode(.splat, node, Zir.Inst.Bin{
                .lhs = result_type,
                .rhs = scalar,
            });
            return rvalue(gz, ri, result, node);
        },
        .reduce => {
            const reduce_op_ty = try gz.addStdLangValue(node, .reduce_op);
            const op = try expr(gz, scope, .{ .rl = .{ .coerced_ty = reduce_op_ty } }, params[0]);
            const scalar = try expr(gz, scope, .{ .rl = .none }, params[1]);
            const result = try gz.addPlNode(.reduce, node, Zir.Inst.Bin{
                .lhs = op,
                .rhs = scalar,
            });
            return rvalue(gz, ri, result, node);
        },

        .add_with_overflow => return overflowArithmetic(gz, scope, ri, node, params, .add_with_overflow),
        .sub_with_overflow => return overflowArithmetic(gz, scope, ri, node, params, .sub_with_overflow),
        .mul_with_overflow => return overflowArithmetic(gz, scope, ri, node, params, .mul_with_overflow),
        .shl_with_overflow => return overflowArithmetic(gz, scope, ri, node, params, .shl_with_overflow),

        .atomic_load => {
            const atomic_order_type = try gz.addStdLangValue(node, .atomic_order);
            const result = try gz.addPlNode(.atomic_load, node, Zir.Inst.AtomicLoad{
                // zig fmt: off
                .elem_type = try typeExpr(gz, scope,                                                  params[0]),
                .ptr       = try expr    (gz, scope, .{ .rl = .none },                                params[1]),
                .ordering  = try expr    (gz, scope, .{ .rl = .{ .coerced_ty = atomic_order_type } }, params[2]),
                // zig fmt: on
            });
            return rvalue(gz, ri, result, node);
        },
        .atomic_rmw => {
            const atomic_order_type = try gz.addStdLangValue(node, .atomic_order);
            const atomic_rmw_op_type = try gz.addStdLangValue(node, .atomic_rmw_op);
            const int_type = try typeExpr(gz, scope, params[0]);
            const result = try gz.addPlNode(.atomic_rmw, node, Zir.Inst.AtomicRmw{
                // zig fmt: off
                .ptr       = try expr(gz, scope, .{ .rl = .none },                                 params[1]),
                .operation = try expr(gz, scope, .{ .rl = .{ .coerced_ty = atomic_rmw_op_type } }, params[2]),
                .operand   = try expr(gz, scope, .{ .rl = .{ .ty = int_type } },                   params[3]),
                .ordering  = try expr(gz, scope, .{ .rl = .{ .coerced_ty = atomic_order_type } },  params[4]),
                // zig fmt: on
            });
            return rvalue(gz, ri, result, node);
        },
        .atomic_store => {
            const atomic_order_type = try gz.addStdLangValue(node, .atomic_order);
            const int_type = try typeExpr(gz, scope, params[0]);
            _ = try gz.addPlNode(.atomic_store, node, Zir.Inst.AtomicStore{
                // zig fmt: off
                .ptr      = try expr(gz, scope, .{ .rl = .none },                                params[1]),
                .operand  = try expr(gz, scope, .{ .rl = .{ .ty = int_type } },                  params[2]),
                .ordering = try expr(gz, scope, .{ .rl = .{ .coerced_ty = atomic_order_type } }, params[3]),
                // zig fmt: on
            });
            return rvalue(gz, ri, .void_value, node);
        },
        .mul_add => {
            const float_type = try typeExpr(gz, scope, params[0]);
            const mulend1 = try expr(gz, scope, .{ .rl = .{ .coerced_ty = float_type } }, params[1]);
            const mulend2 = try expr(gz, scope, .{ .rl = .{ .coerced_ty = float_type } }, params[2]);
            const addend = try expr(gz, scope, .{ .rl = .{ .ty = float_type } }, params[3]);
            const result = try gz.addPlNode(.mul_add, node, Zir.Inst.MulAdd{
                .mulend1 = mulend1,
                .mulend2 = mulend2,
                .addend = addend,
            });
            return rvalue(gz, ri, result, node);
        },
        .call => {
            const call_modifier_ty = try gz.addStdLangValue(node, .call_modifier);
            const modifier = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = call_modifier_ty } }, params[0], .call_modifier);
            const callee = try expr(gz, scope, .{ .rl = .none }, params[1]);
            const args = try expr(gz, scope, .{ .rl = .none }, params[2]);
            const result = try gz.addPlNode(.builtin_call, node, Zir.Inst.BuiltinCall{
                .modifier = modifier,
                .callee = callee,
                .args = args,
                .flags = .{
                    .is_nosuspend = gz.nosuspend_node != .none,
                    .ensure_result_used = false,
                },
            });
            return rvalue(gz, ri, result, node);
        },
        .field_parent_ptr => {
            const parent_ptr_type = try ri.rl.resultTypeForCast(gz, node, builtin_name);
            const field_name = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = .slice_const_u8_type } }, params[0], .field_name);
            const result = try gz.addExtendedPayloadSmall(.field_parent_ptr, 0, Zir.Inst.FieldParentPtr{
                .src_node = gz.nodeIndexToRelative(node),
                .parent_ptr_type = parent_ptr_type,
                .field_name = field_name,
                .field_ptr = try expr(gz, scope, .{ .rl = .none }, params[1]),
            });
            return rvalue(gz, ri, result, node);
        },
        .memcpy => {
            _ = try gz.addPlNode(.memcpy, node, Zir.Inst.Bin{
                .lhs = try expr(gz, scope, .{ .rl = .none }, params[0]),
                .rhs = try expr(gz, scope, .{ .rl = .none }, params[1]),
            });
            return rvalue(gz, ri, .void_value, node);
        },
        .memset => {
            const lhs = try expr(gz, scope, .{ .rl = .none }, params[0]);
            const lhs_ty = try gz.addUnNode(.typeof, lhs, params[0]);
            const elem_ty = try gz.addUnNode(.indexable_ptr_elem_type, lhs_ty, params[0]);
            _ = try gz.addPlNode(.memset, node, Zir.Inst.Bin{
                .lhs = lhs,
                .rhs = try expr(gz, scope, .{ .rl = .{ .coerced_ty = elem_ty } }, params[1]),
            });
            return rvalue(gz, ri, .void_value, node);
        },
        .memmove => {
            _ = try gz.addPlNode(.memmove, node, Zir.Inst.Bin{
                .lhs = try expr(gz, scope, .{ .rl = .none }, params[0]),
                .rhs = try expr(gz, scope, .{ .rl = .none }, params[1]),
            });
            return rvalue(gz, ri, .void_value, node);
        },
        .shuffle => {
            const result = try gz.addPlNode(.shuffle, node, Zir.Inst.Shuffle{
                .elem_type = try typeExpr(gz, scope, params[0]),
                .a = try expr(gz, scope, .{ .rl = .none }, params[1]),
                .b = try expr(gz, scope, .{ .rl = .none }, params[2]),
                .mask = try comptimeExpr(gz, scope, .{ .rl = .none }, params[3], .operand_shuffle_mask),
            });
            return rvalue(gz, ri, result, node);
        },
        .select => {
            const result = try gz.addExtendedPayload(.select, Zir.Inst.Select{
                .node = gz.nodeIndexToRelative(node),
                .elem_type = try typeExpr(gz, scope, params[0]),
                .pred = try expr(gz, scope, .{ .rl = .none }, params[1]),
                .a = try expr(gz, scope, .{ .rl = .none }, params[2]),
                .b = try expr(gz, scope, .{ .rl = .none }, params[3]),
            });
            return rvalue(gz, ri, result, node);
        },
        .Vector => {
            const result = try gz.addPlNode(.vector_type, node, Zir.Inst.Bin{
                .lhs = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = .u32_type } }, params[0], .type),
                .rhs = try typeExpr(gz, scope, params[1]),
            });
            return rvalue(gz, ri, result, node);
        },
        .prefetch => {
            const prefetch_options_ty = try gz.addStdLangValue(node, .prefetch_options);
            const ptr = try expr(gz, scope, .{ .rl = .none }, params[0]);
            const options = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = prefetch_options_ty } }, params[1], .prefetch_options);
            _ = try gz.addExtendedPayload(.prefetch, Zir.Inst.BinNode{
                .node = gz.nodeIndexToRelative(node),
                .lhs = ptr,
                .rhs = options,
            });
            return rvalue(gz, ri, .void_value, node);
        },
        .c_va_arg => {
            const result = try gz.addExtendedPayload(.c_va_arg, Zir.Inst.BinNode{
                .node = gz.nodeIndexToRelative(node),
                .lhs = try expr(gz, scope, .{ .rl = .none }, params[0]),
                .rhs = try typeExpr(gz, scope, params[1]),
            });
            return rvalue(gz, ri, result, node);
        },
        .c_va_copy => {
            const result = try gz.addExtendedPayload(.c_va_copy, Zir.Inst.UnNode{
                .node = gz.nodeIndexToRelative(node),
                .operand = try expr(gz, scope, .{ .rl = .none }, params[0]),
            });
            return rvalue(gz, ri, result, node);
        },
        .c_va_end => {
            const result = try gz.addExtendedPayload(.c_va_end, Zir.Inst.UnNode{
                .node = gz.nodeIndexToRelative(node),
                .operand = try expr(gz, scope, .{ .rl = .none }, params[0]),
            });
            return rvalue(gz, ri, result, node);
        },
        .c_va_start => {
            if (!astgen.fn_var_args) {
                return astgen.failNode(node, "'@cVaStart' in a non-variadic function", .{});
            }
            return rvalue(gz, ri, try gz.addNodeExtended(.c_va_start, node), node);
        },

        .work_item_id => {
            const operand = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = .u32_type } }, params[0], .work_group_dim_index);
            const result = try gz.addExtendedPayload(.work_item_id, Zir.Inst.UnNode{
                .node = gz.nodeIndexToRelative(node),
                .operand = operand,
            });
            return rvalue(gz, ri, result, node);
        },
        .work_group_size => {
            const operand = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = .u32_type } }, params[0], .work_group_dim_index);
            const result = try gz.addExtendedPayload(.work_group_size, Zir.Inst.UnNode{
                .node = gz.nodeIndexToRelative(node),
                .operand = operand,
            });
            return rvalue(gz, ri, result, node);
        },
        .work_group_id => {
            const operand = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = .u32_type } }, params[0], .work_group_dim_index);
            const result = try gz.addExtendedPayload(.work_group_id, Zir.Inst.UnNode{
                .node = gz.nodeIndexToRelative(node),
                .operand = operand,
            });
            return rvalue(gz, ri, result, node);
        },
    }
}

fn hasDeclOrField(
    gz: *GenZir,
    scope: *Scope,
    ri: ResultInfo,
    node: Ast.Node.Index,
    lhs_node: Ast.Node.Index,
    rhs_node: Ast.Node.Index,
    tag: Zir.Inst.Tag,
) InnerError!Zir.Inst.Ref {
    const container_type = try typeExpr(gz, scope, lhs_node);
    const name = try comptimeExpr(
        gz,
        scope,
        .{ .rl = .{ .coerced_ty = .slice_const_u8_type } },
        rhs_node,
        if (tag == .has_decl) .decl_name else .field_name,
    );
    const result = try gz.addPlNode(tag, node, Zir.Inst.Bin{
        .lhs = container_type,
        .rhs = name,
    });
    return rvalue(gz, ri, result, node);
}

fn typeCast(
    gz: *GenZir,
    scope: *Scope,
    ri: ResultInfo,
    node: Ast.Node.Index,
    operand_node: Ast.Node.Index,
    tag: Zir.Inst.Tag,
    builtin_name: []const u8,
) InnerError!Zir.Inst.Ref {
    const cursor = maybeAdvanceSourceCursorToMainToken(gz, node);
    const result_type = try ri.rl.resultTypeForCast(gz, node, builtin_name);
    const operand = try expr(gz, scope, .{ .rl = .none }, operand_node);

    try emitDbgStmt(gz, cursor);
    const result = try gz.addPlNode(tag, node, Zir.Inst.Bin{
        .lhs = result_type,
        .rhs = operand,
    });
    return rvalue(gz, ri, result, node);
}

fn simpleUnOpType(
    gz: *GenZir,
    scope: *Scope,
    ri: ResultInfo,
    node: Ast.Node.Index,
    operand_node: Ast.Node.Index,
    tag: Zir.Inst.Tag,
) InnerError!Zir.Inst.Ref {
    const operand = try typeExpr(gz, scope, operand_node);
    const result = try gz.addUnNode(tag, operand, node);
    return rvalue(gz, ri, result, node);
}

fn simpleUnOp(
    gz: *GenZir,
    scope: *Scope,
    ri: ResultInfo,
    node: Ast.Node.Index,
    operand_ri: ResultInfo,
    operand_node: Ast.Node.Index,
    tag: Zir.Inst.Tag,
) InnerError!Zir.Inst.Ref {
    const cursor = maybeAdvanceSourceCursorToMainToken(gz, node);
    const operand = if (tag == .compile_error)
        try comptimeExpr(gz, scope, operand_ri, operand_node, .compile_error_string)
    else
        try expr(gz, scope, operand_ri, operand_node);
    switch (tag) {
        .tag_name, .error_name, .int_from_ptr => try emitDbgStmt(gz, cursor),
        else => {},
    }
    const result = try gz.addUnNode(tag, operand, node);
    return rvalue(gz, ri, result, node);
}

fn floatRoundOp(
    gz: *GenZir,
    scope: *Scope,
    ri: ResultInfo,
    node: Ast.Node.Index,
    operand_node: Ast.Node.Index,
    float_tag: Zir.Inst.Tag,
) InnerError!Zir.Inst.Ref {
    if (try ri.rl.resultType(gz, node)) |dest_type| {
        const cursor = maybeAdvanceSourceCursorToMainToken(gz, node);

        const operand_ty_inst = try gz.addExtendedPayload(.round_op_ty, Zir.Inst.UnNode{
            .node = gz.nodeIndexToRelative(node),
            .operand = dest_type,
        });

        const operand = try expr(gz, scope, .{ .rl = .{ .coerced_ty = operand_ty_inst } }, operand_node);

        try emitDbgStmt(gz, cursor);
        const round_op: Zir.Inst.RoundOp = switch (float_tag) {
            .round => .round,
            .floor => .floor,
            .ceil => .ceil,
            .trunc => .trunc,
            else => unreachable,
        };
        const result = try gz.addExtendedPayloadSmall(.round_op, @backingInt(round_op), Zir.Inst.BinNode{
            .node = gz.nodeIndexToRelative(node),
            .lhs = dest_type,
            .rhs = operand,
        });
        return rvalue(gz, ri, result, node);
    } else {
        return floatUnOp(gz, scope, ri, node, operand_node, float_tag);
    }
}

fn floatUnOp(
    gz: *GenZir,
    scope: *Scope,
    ri: ResultInfo,
    node: Ast.Node.Index,
    operand_node: Ast.Node.Index,
    tag: Zir.Inst.Tag,
) InnerError!Zir.Inst.Ref {
    const result_type = try ri.rl.resultType(gz, node);
    const operand_ri: ResultInfo.Loc = if (result_type) |rt| .{
        .ty = try gz.addExtendedPayload(.float_op_result_ty, Zir.Inst.UnNode{
            .node = gz.nodeIndexToRelative(node),
            .operand = rt,
        }),
    } else .none;
    const operand = try expr(gz, scope, .{ .rl = operand_ri }, operand_node);
    const result = try gz.addUnNode(tag, operand, node);
    return rvalue(gz, ri, result, node);
}

fn negation(
    gz: *GenZir,
    scope: *Scope,
    ri: ResultInfo,
    node: Ast.Node.Index,
) InnerError!Zir.Inst.Ref {
    const astgen = gz.astgen;
    const tree = astgen.tree;

    // 检查子表达式是否为浮点字面量,因为需要保留其负号,而不通过编译期减法处理。
    //
    const operand_node = tree.nodeData(node).node;
    if (tree.nodeTag(operand_node) == .number_literal) {
        return numberLiteral(gz, ri, operand_node, node, .negative);
    }

    const operand = try expr(gz, scope, .{ .rl = .none }, operand_node);
    const result = try gz.addUnNode(.negate, operand, node);
    return rvalue(gz, ri, result, node);
}

fn cmpxchg(
    gz: *GenZir,
    scope: *Scope,
    ri: ResultInfo,
    node: Ast.Node.Index,
    params: []const Ast.Node.Index,
    small: u16,
) InnerError!Zir.Inst.Ref {
    const int_type = try typeExpr(gz, scope, params[0]);
    const atomic_order_type = try gz.addStdLangValue(node, .atomic_order);
    const result = try gz.addExtendedPayloadSmall(.cmpxchg, small, Zir.Inst.Cmpxchg{
        // zig fmt: off
        .node           = gz.nodeIndexToRelative(node),
        .ptr            = try expr(gz, scope, .{ .rl = .none },                                params[1]),
        .expected_value = try expr(gz, scope, .{ .rl = .{ .ty = int_type } },                  params[2]),
        .new_value      = try expr(gz, scope, .{ .rl = .{ .coerced_ty = int_type } },          params[3]),
        .success_order  = try expr(gz, scope, .{ .rl = .{ .coerced_ty = atomic_order_type } }, params[4]),
        .failure_order  = try expr(gz, scope, .{ .rl = .{ .coerced_ty = atomic_order_type } }, params[5]),
        // zig fmt: on
    });
    return rvalue(gz, ri, result, node);
}

fn bitBuiltin(
    gz: *GenZir,
    scope: *Scope,
    ri: ResultInfo,
    node: Ast.Node.Index,
    operand_node: Ast.Node.Index,
    tag: Zir.Inst.Tag,
) InnerError!Zir.Inst.Ref {
    const operand = try expr(gz, scope, .{ .rl = .none }, operand_node);
    const result = try gz.addUnNode(tag, operand, node);
    return rvalue(gz, ri, result, node);
}

fn divBuiltin(
    gz: *GenZir,
    scope: *Scope,
    ri: ResultInfo,
    node: Ast.Node.Index,
    lhs_node: Ast.Node.Index,
    rhs_node: Ast.Node.Index,
    tag: Zir.Inst.Tag,
) InnerError!Zir.Inst.Ref {
    const cursor = maybeAdvanceSourceCursorToMainToken(gz, node);
    const lhs = try expr(gz, scope, .{ .rl = .none }, lhs_node);
    const rhs = try expr(gz, scope, .{ .rl = .none }, rhs_node);

    try emitDbgStmt(gz, cursor);
    const result = try gz.addPlNode(tag, node, Zir.Inst.Bin{ .lhs = lhs, .rhs = rhs });
    return rvalue(gz, ri, result, node);
}

fn offsetOf(
    gz: *GenZir,
    scope: *Scope,
    ri: ResultInfo,
    node: Ast.Node.Index,
    lhs_node: Ast.Node.Index,
    rhs_node: Ast.Node.Index,
    tag: Zir.Inst.Tag,
) InnerError!Zir.Inst.Ref {
    const type_inst = try typeExpr(gz, scope, lhs_node);
    const field_name = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = .slice_const_u8_type } }, rhs_node, .field_name);
    const result = try gz.addPlNode(tag, node, Zir.Inst.Bin{
        .lhs = type_inst,
        .rhs = field_name,
    });
    return rvalue(gz, ri, result, node);
}

fn shiftOp(
    gz: *GenZir,
    scope: *Scope,
    ri: ResultInfo,
    node: Ast.Node.Index,
    lhs_node: Ast.Node.Index,
    rhs_node: Ast.Node.Index,
    tag: Zir.Inst.Tag,
) InnerError!Zir.Inst.Ref {
    const lhs = try expr(gz, scope, .{ .rl = .none }, lhs_node);

    const cursor = switch (gz.astgen.tree.nodeTag(node)) {
        .shl, .shr => maybeAdvanceSourceCursorToMainToken(gz, node),
        else => undefined,
    };

    const log2_int_type = try gz.addUnNode(.typeof_log2_int_type, lhs, lhs_node);
    const rhs = try expr(gz, scope, .{ .rl = .{ .ty = log2_int_type }, .ctx = .shift_op }, rhs_node);

    switch (gz.astgen.tree.nodeTag(node)) {
        .shl, .shr => try emitDbgStmt(gz, cursor),
        else => undefined,
    }

    const result = try gz.addPlNode(tag, node, Zir.Inst.Bin{
        .lhs = lhs,
        .rhs = rhs,
    });
    return rvalue(gz, ri, result, node);
}

fn overflowArithmetic(
    gz: *GenZir,
    scope: *Scope,
    ri: ResultInfo,
    node: Ast.Node.Index,
    params: []const Ast.Node.Index,
    tag: Zir.Inst.Extended,
) InnerError!Zir.Inst.Ref {
    const lhs = try expr(gz, scope, .{ .rl = .none }, params[0]);
    const rhs = try expr(gz, scope, .{ .rl = .none }, params[1]);
    const result = try gz.addExtendedPayload(tag, Zir.Inst.BinNode{
        .node = gz.nodeIndexToRelative(node),
        .lhs = lhs,
        .rhs = rhs,
    });
    return rvalue(gz, ri, result, node);
}

fn callExpr(
    gz: *GenZir,
    scope: *Scope,
    ri: ResultInfo,
    /// 若此项不为 `.none`,且调用采用声明字面量形式(`.foo(...)`),则使用
    /// 此类型作为声明字面量的结果类型,而非 `ri.rl` 中的结果类型。
    override_decl_literal_type: Zir.Inst.Ref,
    node: Ast.Node.Index,
    call: Ast.full.Call,
) InnerError!Zir.Inst.Ref {
    const astgen = gz.astgen;

    const callee = try calleeExpr(gz, scope, ri.rl, override_decl_literal_type, call.ast.fn_expr);
    const modifier: std.lang.CallModifier = blk: {
        if (gz.nosuspend_node != .none) {
            break :blk .no_suspend;
        }
        break :blk .auto;
    };

    {
        astgen.advanceSourceCursor(astgen.tree.tokenStart(call.ast.lparen));
        const line = astgen.source_line - gz.decl_line;
        const column = astgen.source_column;
        // Sema 预期 call 紧前方存在 dbg_stmt。
        try emitDbgStmtForceCurrentIndex(gz, .{ line, column });
    }

    switch (callee) {
        .direct => |obj| assert(obj != .none),
        .field => |field| assert(field.obj_ptr != .none),
    }

    const call_index: Zir.Inst.Index = @fromBackingInt(@intCast(astgen.instructions.len));
    const call_inst = call_index.toRef();
    try gz.astgen.instructions.append(astgen.gpa, undefined);
    try gz.instructions.append(astgen.gpa, call_index);

    const scratch_top = astgen.scratch.items.len;
    defer astgen.scratch.items.len = scratch_top;

    var scratch_index = scratch_top;
    try astgen.scratch.resize(astgen.gpa, scratch_top + call.ast.params.len);

    for (call.ast.params) |param_node| {
        var arg_block = gz.makeSubBlock(scope);
        defer arg_block.unstack();

        // 复用 `call_inst`,以提供参数类型。
        const arg_ref = try fullBodyExpr(&arg_block, &arg_block.base, .{ .rl = .{ .coerced_ty = call_inst }, .ctx = .fn_arg }, param_node, .normal);
        _ = try arg_block.addBreakWithSrcNode(.break_inline, call_index, arg_ref, param_node);

        const body = arg_block.instructionsSlice();
        try astgen.scratch.ensureUnusedCapacity(astgen.gpa, countBodyLenAfterFixups(astgen, body));
        appendBodyWithFixupsArrayList(astgen, &astgen.scratch, body);

        astgen.scratch.items[scratch_index] = @intCast(astgen.scratch.items.len - scratch_top);
        scratch_index += 1;
    }

    // 若结果位置为 try/catch/错误联合体 if/return、函数参数,
    // 或 `const` 变量的初始化器,则传播错误轨迹。
    // 否则应始终将其弹出,由 Sema 处理。
    const propagate_error_trace = switch (ri.ctx) {
        .error_handling_expr, .@"return", .fn_arg, .const_init => true,
        else => false,
    };

    switch (callee) {
        .direct => |callee_obj| {
            const payload_index = try addExtra(astgen, Zir.Inst.Call{
                .callee = callee_obj,
                .flags = .{
                    .pop_error_return_trace = !propagate_error_trace,
                    .packed_modifier = @intCast(@backingInt(modifier)),
                    .args_len = @intCast(call.ast.params.len),
                },
            });
            if (call.ast.params.len != 0) {
                try astgen.extra.appendSlice(astgen.gpa, astgen.scratch.items[scratch_top..]);
            }
            gz.astgen.instructions.set(@backingInt(call_index), .{
                .tag = .call,
                .data = .{ .pl_node = .{
                    .src_node = gz.nodeIndexToRelative(node),
                    .payload_index = payload_index,
                } },
            });
        },
        .field => |callee_field| {
            const payload_index = try addExtra(astgen, Zir.Inst.FieldCall{
                .obj_ptr = callee_field.obj_ptr,
                .field_name_start = callee_field.field_name_start,
                .flags = .{
                    .pop_error_return_trace = !propagate_error_trace,
                    .packed_modifier = @intCast(@backingInt(modifier)),
                    .args_len = @intCast(call.ast.params.len),
                },
            });
            if (call.ast.params.len != 0) {
                try astgen.extra.appendSlice(astgen.gpa, astgen.scratch.items[scratch_top..]);
            }
            gz.astgen.instructions.set(@backingInt(call_index), .{
                .tag = .field_call,
                .data = .{ .pl_node = .{
                    .src_node = gz.nodeIndexToRelative(node),
                    .payload_index = payload_index,
                } },
            });
        },
    }
    return rvalue(gz, ri, call_inst, node); // TODO 带结果位置的函数调用
}

const Callee = union(enum) {
    field: struct {
        /// 指向所获取字段所属对象的*指针*,以便在第一个参数需要时,
        /// 能够将左值提升为地址。
        obj_ptr: Zir.Inst.Ref,
        /// `string_bytes` 中的偏移。
        field_name_start: Zir.NullTerminatedString,
    },
    direct: Zir.Inst.Ref,
};

/// calleeExpr 生成调用表达式的函数部分,即 f(x) 中的 f,而不是 @call() 内置函数的被调用方参数。
/// 其目的是区分普通调用与方法调用语法 `a.b()`。因此,若左侧是字段访问,则使用 `field` 联合体字段返回;否则使用 `direct` 联合体字段。
///
///
///
fn calleeExpr(
    gz: *GenZir,
    scope: *Scope,
    call_rl: ResultInfo.Loc,
    /// 若此值不是 `.none`,且调用采用声明字面量形式(`.foo(...)`),则将此
    /// 类型作为声明字面量的结果类型,而非 `call_rl` 中的结果类型。
    override_decl_literal_type: Zir.Inst.Ref,
    node: Ast.Node.Index,
) InnerError!Callee {
    const astgen = gz.astgen;
    const tree = astgen.tree;

    const tag = tree.nodeTag(node);
    switch (tag) {
        .field_access => {
            const object_node, const field_ident = tree.nodeData(node).node_and_token;
            const str_index = try astgen.identAsString(field_ident);
            // 按引用捕获对象,以便必要时在 Sema 中
            // 将其提升为地址。
            const lhs = try expr(gz, scope, .{ .rl = .ref }, object_node);

            const cursor = maybeAdvanceSourceCursorToMainToken(gz, node);
            try emitDbgStmt(gz, cursor);

            return .{ .field = .{
                .obj_ptr = lhs,
                .field_name_start = str_index,
            } };
        },
        .enum_literal => {
            const res_ty = res_ty: {
                if (override_decl_literal_type != .none) break :res_ty override_decl_literal_type;
                break :res_ty try call_rl.resultType(gz, node) orelse {
                    // 没有结果类型;降级为对枚举字面量的字面调用。
                    return .{ .direct = try expr(gz, scope, .{ .rl = .none }, node) };
                };
            };
            // 声明字面量调用语法,例如:
            // `const foo: T = .init();`
            // 在 `T` 中查找 `init`,但不尝试强制转换。
            const str_index = try astgen.identAsString(tree.nodeMainToken(node));
            const callee = try gz.addPlNode(.decl_literal_no_coerce, node, Zir.Inst.Field{
                .lhs = res_ty,
                .field_name_start = str_index,
            });
            return .{ .direct = callee };
        },
        else => return .{ .direct = try expr(gz, scope, .{ .rl = .none }, node) },
    }
}

const primitive_instrs = std.StaticStringMap(Zir.Inst.Ref).initComptime(.{
    .{ "anyerror", .anyerror_type },
    .{ "anyframe", .anyframe_type },
    .{ "anyopaque", .anyopaque_type },
    .{ "bool", .bool_type },
    .{ "c_int", .c_int_type },
    .{ "c_long", .c_long_type },
    .{ "c_longdouble", .c_longdouble_type },
    .{ "c_longlong", .c_longlong_type },
    .{ "c_char", .c_char_type },
    .{ "c_short", .c_short_type },
    .{ "c_uint", .c_uint_type },
    .{ "c_ulong", .c_ulong_type },
    .{ "c_ulonglong", .c_ulonglong_type },
    .{ "c_ushort", .c_ushort_type },
    .{ "comptime_float", .comptime_float_type },
    .{ "comptime_int", .comptime_int_type },
    .{ "false", .bool_false },
    .{ "noreturn", .noreturn_type },
    .{ "null", .null_value },
    .{ "true", .bool_true },
    .{ "type", .type_type },
    .{ "undefined", .undef },
    .{ "void", .void_type },

    .{ "f16", .f16_type },
    .{ "f32", .f32_type },
    .{ "f64", .f64_type },
    .{ "f80", .f80_type },
    .{ "f128", .f128_type },

    .{ "u0", .u0_type },
    .{ "u1", .u1_type },
    .{ "u8", .u8_type },
    .{ "i8", .i8_type },
    .{ "u16", .u16_type },
    .{ "i16", .i16_type },
    .{ "u29", .u29_type },
    .{ "u32", .u32_type },
    .{ "i32", .i32_type },
    .{ "u64", .u64_type },
    .{ "i64", .i64_type },
    .{ "u80", .u80_type },
    .{ "u128", .u128_type },
    .{ "i128", .i128_type },
    .{ "u256", .u256_type },
    .{ "usize", .usize_type },
    .{ "isize", .isize_type },
});

comptime {
    // 这些检查确保 std.zig.primitives 与 primitive->Zir 映射保持同步。
    const primitives = std.zig.primitives;
    for (primitive_instrs.keys(), primitive_instrs.values()) |key, value| {
        if (!primitives.isPrimitive(key)) {
            @compileError("std.zig.isPrimitive() is not aware of Zir instr '" ++ @tagName(value) ++ "'");
        }
    }
    for (primitives.names.keys()) |key| {
        if (primitive_instrs.get(key) == null) {
            @compileError("std.zig.primitives entry '" ++ key ++ "' does not have a corresponding Zir instr");
        }
    }
}

fn nodeIsTriviallyZero(tree: *const Ast, node: Ast.Node.Index) bool {
    switch (tree.nodeTag(node)) {
        .number_literal => {
            const ident = tree.nodeMainToken(node);
            return switch (std.zig.parseNumberLiteral(tree.tokenSlice(ident))) {
                .int => |number| switch (number) {
                    0 => true,
                    else => false,
                },
                else => false,
            };
        },
        else => return false,
    }
}

fn nodeMayAppendToErrorTrace(tree: *const Ast, start_node: Ast.Node.Index) bool {
    var node = start_node;
    while (true) {
        switch (tree.nodeTag(node)) {
            // 这些没有机会调用任何运行期函数。
            .error_value,
            .identifier,
            .@"comptime",
            => return false,

            // 将问题转交给左侧子表达式。
            .@"try",
            .@"nosuspend",
            => node = tree.nodeData(node).node,
            .grouped_expression,
            .unwrap_optional,
            => node = tree.nodeData(node).node_and_token[0],

            // 任何求值结果不是错误的表达式,都保证弹出新增的
            // 错误轨迹,因此实际上不会追加。
            else => return nodeMayEvalToError(tree, start_node) != .never,
        }
    }
}

fn nodeMayEvalToError(tree: *const Ast, start_node: Ast.Node.Index) BuiltinFn.EvalToError {
    var node = start_node;
    while (true) {
        switch (tree.nodeTag(node)) {
            .root,
            .test_decl,
            .switch_case,
            .switch_case_inline,
            .switch_case_one,
            .switch_case_inline_one,
            .container_field_init,
            .container_field_align,
            .container_field,
            .asm_output,
            .asm_input,
            => unreachable,

            .error_value => return .always,

            .@"asm",
            .asm_simple,
            .identifier,
            .field_access,
            .deref,
            .array_access,
            .while_simple,
            .while_cont,
            .for_simple,
            .if_simple,
            .@"while",
            .@"if",
            .@"for",
            .@"switch",
            .switch_comma,
            .call_one,
            .call_one_comma,
            .call,
            .call_comma,
            => return .maybe,

            .@"return",
            .@"break",
            .@"continue",
            .bit_not,
            .bool_not,
            .global_var_decl,
            .local_var_decl,
            .simple_var_decl,
            .aligned_var_decl,
            .@"defer",
            .@"errdefer",
            .address_of,
            .optional_type,
            .negation,
            .negation_wrap,
            .@"resume",
            .array_type,
            .array_type_sentinel,
            .ptr_type_aligned,
            .ptr_type_sentinel,
            .ptr_type,
            .ptr_type_bit_range,
            .@"suspend",
            .fn_proto_simple,
            .fn_proto_multi,
            .fn_proto_one,
            .fn_proto,
            .fn_decl,
            .anyframe_type,
            .anyframe_literal,
            .number_literal,
            .enum_literal,
            .string_literal,
            .multiline_string_literal,
            .char_literal,
            .unreachable_literal,
            .error_set_decl,
            .container_decl,
            .container_decl_trailing,
            .container_decl_two,
            .container_decl_two_trailing,
            .container_decl_arg,
            .container_decl_arg_trailing,
            .tagged_union,
            .tagged_union_trailing,
            .tagged_union_two,
            .tagged_union_two_trailing,
            .tagged_union_enum_tag,
            .tagged_union_enum_tag_trailing,
            .add,
            .add_wrap,
            .add_sat,
            .array_cat,
            .assign,
            .assign_destructure,
            .assign_bit_and,
            .assign_bit_or,
            .assign_shl,
            .assign_shl_sat,
            .assign_shr,
            .assign_bit_xor,
            .assign_div,
            .assign_sub,
            .assign_sub_wrap,
            .assign_sub_sat,
            .assign_mod,
            .assign_add,
            .assign_add_wrap,
            .assign_add_sat,
            .assign_mul,
            .assign_mul_wrap,
            .assign_mul_sat,
            .bang_equal,
            .bit_and,
            .bit_or,
            .shl,
            .shl_sat,
            .shr,
            .bit_xor,
            .bool_and,
            .bool_or,
            .div,
            .equal_equal,
            .error_union,
            .greater_or_equal,
            .greater_than,
            .less_or_equal,
            .less_than,
            .merge_error_sets,
            .mod,
            .mul,
            .mul_wrap,
            .mul_sat,
            .switch_range,
            .for_range,
            .sub,
            .sub_wrap,
            .sub_sat,
            .slice,
            .slice_open,
            .slice_sentinel,
            .array_init_one,
            .array_init_one_comma,
            .array_init_dot_two,
            .array_init_dot_two_comma,
            .array_init_dot,
            .array_init_dot_comma,
            .array_init,
            .array_init_comma,
            .struct_init_one,
            .struct_init_one_comma,
            .struct_init_dot_two,
            .struct_init_dot_two_comma,
            .struct_init_dot,
            .struct_init_dot_comma,
            .struct_init,
            .struct_init_comma,
            => return .never,

            // 将问题转交给左侧子表达式。
            .@"try",
            .@"comptime",
            .@"nosuspend",
            => node = tree.nodeData(node).node,
            .grouped_expression,
            .unwrap_optional,
            => node = tree.nodeData(node).node_and_token[0],

            // 左侧子表达式在外层可选类型或错误联合之下,仍可能是错误。
            .@"catch",
            .@"orelse",
            => return .maybe,

            .block_two,
            .block_two_semicolon,
            .block,
            .block_semicolon,
            => {
                const lbrace = tree.nodeMainToken(node);
                if (tree.tokenTag(lbrace - 1) == .colon) {
                    // 带标签块可能需要内存位置,
                    // 以传递给其 break 语句。
                    return .maybe;
                } else {
                    return .never;
                }
            },

            .builtin_call,
            .builtin_call_comma,
            .builtin_call_two,
            .builtin_call_two_comma,
            => {
                const builtin_token = tree.nodeMainToken(node);
                const builtin_name = tree.tokenSlice(builtin_token);
                // 若内置函数名称无效,此处不报错,而是允许通过,稍后再报告“invalid builtin function”。
                //
                const builtin_info = BuiltinFn.list.get(builtin_name) orelse return .maybe;
                return builtin_info.eval_to_error;
            },
        }
    }
}

/// 将 `rl` 语义应用于 `result`。不自行处理结果位置
/// 的表达式,必须对结果调用此函数。
/// 例如,若 `ri.rl` 为 `.ptr`,则将结果写入该指针。
/// 若 `ri.rl` 为 `.ty`,则将结果强制转换为该类型。
/// 假定 `gz` 上没有堆叠的内容。
fn rvalue(
    gz: *GenZir,
    ri: ResultInfo,
    raw_result: Zir.Inst.Ref,
    src_node: Ast.Node.Index,
) InnerError!Zir.Inst.Ref {
    return rvalueInner(gz, ri, raw_result, src_node, true);
}

/// 类似 `rvalue`,但对于 `ref_coerced_ty` 结果类型,
/// 拒绝在取得引用前进行强制转换。用于没有
/// `alloc` 的局部变量,因为希望变量具有稳定地址,
/// 即表现为左值。
fn rvalueNoCoercePreRef(
    gz: *GenZir,
    ri: ResultInfo,
    raw_result: Zir.Inst.Ref,
    src_node: Ast.Node.Index,
) InnerError!Zir.Inst.Ref {
    return rvalueInner(gz, ri, raw_result, src_node, false);
}

fn rvalueInner(
    gz: *GenZir,
    ri: ResultInfo,
    raw_result: Zir.Inst.Ref,
    src_node: Ast.Node.Index,
    allow_coerce_pre_ref: bool,
) InnerError!Zir.Inst.Ref {
    const result = r: {
        if (raw_result.toIndex()) |result_index| {
            const zir_tags = gz.astgen.instructions.items(.tag);
            const data = gz.astgen.instructions.items(.data)[@backingInt(result_index)];
            if (zir_tags[@backingInt(result_index)].isAlwaysVoid(data)) {
                break :r Zir.Inst.Ref.void_value;
            }
        }
        break :r raw_result;
    };
    if (gz.endsWithNoReturn()) return result;
    switch (ri.rl) {
        .none, .coerced_ty => return result,
        .discard => {
            // 丢弃错误值时生成编译错误。
            _ = try gz.addUnNode(.ensure_result_non_error, result, src_node);
            return .void_value;
        },
        .ref, .ref_const, .ref_coerced_ty => {
            const coerced_result = if (allow_coerce_pre_ref and ri.rl == .ref_coerced_ty) res: {
                const ptr_ty = ri.rl.ref_coerced_ty;
                break :res try gz.addPlNode(.coerce_ptr_elem_ty, src_node, Zir.Inst.Bin{
                    .lhs = ptr_ty,
                    .rhs = result,
                });
            } else result;
            // 需要指针,但当前持有的是值。
            // 遗憾的是,不能简单地在此直接生成 ref 指令,
            // 因为必须确保后续对 const 局部变量使用取地址运算符时,
            // 返回相同地址。
            const astgen = gz.astgen;
            const tree = astgen.tree;
            const src_token = tree.firstToken(src_node);
            const result_index = coerced_result.toIndex() orelse
                return gz.addUnTok(.ref, coerced_result, src_token);
            const gop = try astgen.ref_table.getOrPut(astgen.gpa, result_index);
            if (!gop.found_existing) {
                gop.value_ptr.* = try gz.makeUnTok(.ref, coerced_result, src_token);
            }
            return gop.value_ptr.*.toRef();
        },
        .ty => |ty_inst| {
            // 快速消除一些常见且不必要的类型强制转换。
            const as_ty = @as(u64, @backingInt(Zir.Inst.Ref.type_type)) << 32;
            const as_bool = @as(u64, @backingInt(Zir.Inst.Ref.bool_type)) << 32;
            const as_void = @as(u64, @backingInt(Zir.Inst.Ref.void_type)) << 32;
            const as_comptime_int = @as(u64, @backingInt(Zir.Inst.Ref.comptime_int_type)) << 32;
            const as_usize = @as(u64, @backingInt(Zir.Inst.Ref.usize_type)) << 32;
            const as_u1 = @as(u64, @backingInt(Zir.Inst.Ref.u1_type)) << 32;
            const as_u8 = @as(u64, @backingInt(Zir.Inst.Ref.u8_type)) << 32;
            switch ((@as(u64, @backingInt(ty_inst)) << 32) | @as(u64, @backingInt(result))) {
                as_ty | @backingInt(Zir.Inst.Ref.u1_type),
                as_ty | @backingInt(Zir.Inst.Ref.u8_type),
                as_ty | @backingInt(Zir.Inst.Ref.i8_type),
                as_ty | @backingInt(Zir.Inst.Ref.u16_type),
                as_ty | @backingInt(Zir.Inst.Ref.u29_type),
                as_ty | @backingInt(Zir.Inst.Ref.i16_type),
                as_ty | @backingInt(Zir.Inst.Ref.u32_type),
                as_ty | @backingInt(Zir.Inst.Ref.i32_type),
                as_ty | @backingInt(Zir.Inst.Ref.u64_type),
                as_ty | @backingInt(Zir.Inst.Ref.i64_type),
                as_ty | @backingInt(Zir.Inst.Ref.u128_type),
                as_ty | @backingInt(Zir.Inst.Ref.i128_type),
                as_ty | @backingInt(Zir.Inst.Ref.usize_type),
                as_ty | @backingInt(Zir.Inst.Ref.isize_type),
                as_ty | @backingInt(Zir.Inst.Ref.c_char_type),
                as_ty | @backingInt(Zir.Inst.Ref.c_short_type),
                as_ty | @backingInt(Zir.Inst.Ref.c_ushort_type),
                as_ty | @backingInt(Zir.Inst.Ref.c_int_type),
                as_ty | @backingInt(Zir.Inst.Ref.c_uint_type),
                as_ty | @backingInt(Zir.Inst.Ref.c_long_type),
                as_ty | @backingInt(Zir.Inst.Ref.c_ulong_type),
                as_ty | @backingInt(Zir.Inst.Ref.c_longlong_type),
                as_ty | @backingInt(Zir.Inst.Ref.c_ulonglong_type),
                as_ty | @backingInt(Zir.Inst.Ref.c_longdouble_type),
                as_ty | @backingInt(Zir.Inst.Ref.f16_type),
                as_ty | @backingInt(Zir.Inst.Ref.f32_type),
                as_ty | @backingInt(Zir.Inst.Ref.f64_type),
                as_ty | @backingInt(Zir.Inst.Ref.f80_type),
                as_ty | @backingInt(Zir.Inst.Ref.f128_type),
                as_ty | @backingInt(Zir.Inst.Ref.anyopaque_type),
                as_ty | @backingInt(Zir.Inst.Ref.bool_type),
                as_ty | @backingInt(Zir.Inst.Ref.void_type),
                as_ty | @backingInt(Zir.Inst.Ref.type_type),
                as_ty | @backingInt(Zir.Inst.Ref.anyerror_type),
                as_ty | @backingInt(Zir.Inst.Ref.comptime_int_type),
                as_ty | @backingInt(Zir.Inst.Ref.comptime_float_type),
                as_ty | @backingInt(Zir.Inst.Ref.noreturn_type),
                as_ty | @backingInt(Zir.Inst.Ref.anyframe_type),
                as_ty | @backingInt(Zir.Inst.Ref.null_type),
                as_ty | @backingInt(Zir.Inst.Ref.undefined_type),
                as_ty | @backingInt(Zir.Inst.Ref.enum_literal_type),
                as_ty | @backingInt(Zir.Inst.Ref.ptr_usize_type),
                as_ty | @backingInt(Zir.Inst.Ref.ptr_const_comptime_int_type),
                as_ty | @backingInt(Zir.Inst.Ref.manyptr_u8_type),
                as_ty | @backingInt(Zir.Inst.Ref.manyptr_const_u8_type),
                as_ty | @backingInt(Zir.Inst.Ref.manyptr_const_u8_sentinel_0_type),
                as_ty | @backingInt(Zir.Inst.Ref.slice_const_u8_type),
                as_ty | @backingInt(Zir.Inst.Ref.slice_const_u8_sentinel_0_type),
                as_ty | @backingInt(Zir.Inst.Ref.anyerror_void_error_union_type),
                as_ty | @backingInt(Zir.Inst.Ref.generic_poison_type),
                as_ty | @backingInt(Zir.Inst.Ref.empty_tuple_type),
                as_comptime_int | @backingInt(Zir.Inst.Ref.zero),
                as_comptime_int | @backingInt(Zir.Inst.Ref.one),
                as_comptime_int | @backingInt(Zir.Inst.Ref.negative_one),
                as_usize | @backingInt(Zir.Inst.Ref.undef_usize),
                as_usize | @backingInt(Zir.Inst.Ref.zero_usize),
                as_usize | @backingInt(Zir.Inst.Ref.one_usize),
                as_u1 | @backingInt(Zir.Inst.Ref.undef_u1),
                as_u1 | @backingInt(Zir.Inst.Ref.zero_u1),
                as_u1 | @backingInt(Zir.Inst.Ref.one_u1),
                as_u8 | @backingInt(Zir.Inst.Ref.zero_u8),
                as_u8 | @backingInt(Zir.Inst.Ref.one_u8),
                as_u8 | @backingInt(Zir.Inst.Ref.four_u8),
                as_bool | @backingInt(Zir.Inst.Ref.undef_bool),
                as_bool | @backingInt(Zir.Inst.Ref.bool_true),
                as_bool | @backingInt(Zir.Inst.Ref.bool_false),
                as_void | @backingInt(Zir.Inst.Ref.void_value),
                => return result, // 结果类型已经正确

                as_bool | @backingInt(Zir.Inst.Ref.undef) => return .undef_bool,
                as_usize | @backingInt(Zir.Inst.Ref.undef) => return .undef_usize,
                as_usize | @backingInt(Zir.Inst.Ref.undef_u1) => return .undef_usize,
                as_u1 | @backingInt(Zir.Inst.Ref.undef) => return .undef_u1,

                as_usize | @backingInt(Zir.Inst.Ref.zero) => return .zero_usize,
                as_u1 | @backingInt(Zir.Inst.Ref.zero) => return .zero_u1,
                as_u8 | @backingInt(Zir.Inst.Ref.zero) => return .zero_u8,
                as_usize | @backingInt(Zir.Inst.Ref.one) => return .one_usize,
                as_u1 | @backingInt(Zir.Inst.Ref.one) => return .one_u1,
                as_u8 | @backingInt(Zir.Inst.Ref.one) => return .one_u8,
                as_comptime_int | @backingInt(Zir.Inst.Ref.zero_usize) => return .zero,
                as_u1 | @backingInt(Zir.Inst.Ref.zero_usize) => return .zero_u1,
                as_u8 | @backingInt(Zir.Inst.Ref.zero_usize) => return .zero_u8,
                as_comptime_int | @backingInt(Zir.Inst.Ref.one_usize) => return .one,
                as_u1 | @backingInt(Zir.Inst.Ref.one_usize) => return .one_u1,
                as_u8 | @backingInt(Zir.Inst.Ref.one_usize) => return .one_u8,
                as_comptime_int | @backingInt(Zir.Inst.Ref.zero_u1) => return .zero,
                as_comptime_int | @backingInt(Zir.Inst.Ref.zero_u8) => return .zero,
                as_usize | @backingInt(Zir.Inst.Ref.zero_u1) => return .zero_usize,
                as_usize | @backingInt(Zir.Inst.Ref.zero_u8) => return .zero_usize,
                as_comptime_int | @backingInt(Zir.Inst.Ref.one_u1) => return .one,
                as_comptime_int | @backingInt(Zir.Inst.Ref.one_u8) => return .one,
                as_usize | @backingInt(Zir.Inst.Ref.one_u1) => return .one_usize,
                as_usize | @backingInt(Zir.Inst.Ref.one_u8) => return .one_usize,

                // 需要显式的类型强制转换指令。
                else => return gz.addPlNode(ri.zirTag(), src_node, Zir.Inst.As{
                    .dest_type = ty_inst,
                    .operand = result,
                }),
            }
        },
        .ptr => |ptr_res| {
            _ = try gz.addPlNode(.store_node, ptr_res.src_node orelse src_node, Zir.Inst.Bin{
                .lhs = ptr_res.inst,
                .rhs = result,
            });
            return .void_value;
        },
        .inferred_ptr => |alloc| {
            _ = try gz.addPlNode(.store_to_inferred_ptr, src_node, Zir.Inst.Bin{
                .lhs = alloc,
                .rhs = result,
            });
            return .void_value;
        },
        .destructure => |destructure| {
            const components = destructure.components;
            _ = try gz.addPlNode(.validate_destructure, src_node, Zir.Inst.ValidateDestructure{
                .operand = result,
                .destructure_node = gz.nodeIndexToRelative(destructure.src_node),
                .expect_len = @intCast(components.len),
            });
            for (components, 0..) |component, i| {
                if (component == .discard) continue;
                const elem_val = try gz.add(.{
                    .tag = .elem_val_imm,
                    .data = .{ .elem_val_imm = .{
                        .operand = result,
                        .idx = @intCast(i),
                    } },
                });
                switch (component) {
                    .typed_ptr => |ptr_res| {
                        _ = try gz.addPlNode(.store_node, ptr_res.src_node orelse src_node, Zir.Inst.Bin{
                            .lhs = ptr_res.inst,
                            .rhs = elem_val,
                        });
                    },
                    .inferred_ptr => |ptr_inst| {
                        _ = try gz.addPlNode(.store_to_inferred_ptr, src_node, Zir.Inst.Bin{
                            .lhs = ptr_inst,
                            .rhs = elem_val,
                        });
                    },
                    .discard => unreachable,
                }
            }
            return .void_value;
        },
    }
}

/// 给定标识符词法单元,获取对应字符串。
/// 若词法单元使用 @"" 语法,则按字符串解析,必要时报告错误,并在 `astgen.arena` 中分配结果。
/// 否则直接返回对源码字节的引用。
/// 另见 `appendIdentStr` 和 `parseStrLit`。
///
fn identifierTokenString(astgen: *AstGen, token: Ast.TokenIndex) InnerError![]const u8 {
    const tree = astgen.tree;
    assert(tree.tokenTag(token) == .identifier);
    const ident_name = tree.tokenSlice(token);
    if (!mem.startsWith(u8, ident_name, "@")) {
        return ident_name;
    }
    var buf: ArrayList(u8) = .empty;
    defer buf.deinit(astgen.gpa);
    try astgen.parseStrLit(token, &buf, ident_name, 1);
    if (mem.findScalar(u8, buf.items, 0) != null) {
        return astgen.failTok(token, "identifier cannot contain null bytes", .{});
    } else if (buf.items.len == 0) {
        return astgen.failTok(token, "identifier cannot be empty", .{});
    }
    const duped = try astgen.arena.dupe(u8, buf.items);
    return duped;
}

/// 给定标识符词法标记,获取其字符串;若使用 @"" 语法,可能需要将其作为
/// 字符串字面量解析。将所得字符串追加到 `buf`。
/// 另见 `identifierTokenString` 和 `parseStrLit`。
fn appendIdentStr(
    astgen: *AstGen,
    token: Ast.TokenIndex,
    buf: *ArrayList(u8),
) InnerError!void {
    const tree = astgen.tree;
    assert(tree.tokenTag(token) == .identifier);
    const ident_name = tree.tokenSlice(token);
    if (!mem.startsWith(u8, ident_name, "@")) {
        return buf.appendSlice(astgen.gpa, ident_name);
    } else {
        const start = buf.items.len;
        try astgen.parseStrLit(token, buf, ident_name, 1);
        const slice = buf.items[start..];
        if (mem.findScalar(u8, slice, 0) != null) {
            return astgen.failTok(token, "identifier cannot contain null bytes", .{});
        } else if (slice.len == 0) {
            return astgen.failTok(token, "identifier cannot be empty", .{});
        }
    }
}

/// 将结果追加至 `buf`。
fn parseStrLit(
    astgen: *AstGen,
    token: Ast.TokenIndex,
    buf: *ArrayList(u8),
    bytes: []const u8,
    offset: u32,
) InnerError!void {
    const raw_string = bytes[offset..];
    const result = r: {
        var aw: std.Io.Writer.Allocating = .fromArrayList(astgen.gpa, buf);
        defer buf.* = aw.toArrayList();
        break :r std.zig.string_literal.parseWrite(&aw.writer, raw_string) catch |err| switch (err) {
            error.WriteFailed => return error.OutOfMemory,
        };
    };
    switch (result) {
        .success => return,
        .failure => |err| return astgen.failWithStrLitError(err, token, bytes, offset),
    }
}

fn failWithStrLitError(
    astgen: *AstGen,
    err: std.zig.string_literal.Error,
    token: Ast.TokenIndex,
    bytes: []const u8,
    offset: u32,
) InnerError {
    const raw_string = bytes[offset..];
    return failOff(astgen, token, @intCast(offset + err.offset()), "{f}", .{err.fmt(raw_string)});
}

fn failNode(
    astgen: *AstGen,
    node: Ast.Node.Index,
    comptime format: []const u8,
    args: anytype,
) InnerError {
    return astgen.failNodeNotes(node, format, args, &[0]u32{});
}

fn appendErrorNode(
    astgen: *AstGen,
    node: Ast.Node.Index,
    comptime format: []const u8,
    args: anytype,
) Allocator.Error!void {
    try astgen.appendErrorNodeNotes(node, format, args, &[0]u32{});
}

fn appendErrorNodeNotes(
    astgen: *AstGen,
    node: Ast.Node.Index,
    comptime format: []const u8,
    args: anytype,
    notes: []const u32,
) Allocator.Error!void {
    @branchHint(.cold);
    const gpa = astgen.gpa;
    const string_bytes = &astgen.string_bytes;
    const msg: Zir.NullTerminatedString = @fromBackingInt(@intCast(string_bytes.items.len));
    try string_bytes.print(gpa, format ++ "\x00", args);
    const notes_index: u32 = if (notes.len != 0) blk: {
        const notes_start = astgen.extra.items.len;
        try astgen.extra.ensureTotalCapacity(gpa, notes_start + 1 + notes.len);
        astgen.extra.appendAssumeCapacity(@intCast(notes.len));
        astgen.extra.appendSliceAssumeCapacity(notes);
        break :blk @intCast(notes_start);
    } else 0;
    try astgen.compile_errors.append(gpa, .{
        .msg = msg,
        .node = node.toOptional(),
        .token = .none,
        .byte_offset = 0,
        .notes = notes_index,
    });
}

fn failNodeNotes(
    astgen: *AstGen,
    node: Ast.Node.Index,
    comptime format: []const u8,
    args: anytype,
    notes: []const u32,
) InnerError {
    try appendErrorNodeNotes(astgen, node, format, args, notes);
    return error.AnalysisFail;
}

fn failTok(
    astgen: *AstGen,
    token: Ast.TokenIndex,
    comptime format: []const u8,
    args: anytype,
) InnerError {
    return astgen.failTokNotes(token, format, args, &[0]u32{});
}

fn appendErrorTok(
    astgen: *AstGen,
    token: Ast.TokenIndex,
    comptime format: []const u8,
    args: anytype,
) !void {
    try astgen.appendErrorTokNotesOff(token, 0, format, args, &[0]u32{});
}

fn failTokNotes(
    astgen: *AstGen,
    token: Ast.TokenIndex,
    comptime format: []const u8,
    args: anytype,
    notes: []const u32,
) InnerError {
    try appendErrorTokNotesOff(astgen, token, 0, format, args, notes);
    return error.AnalysisFail;
}

fn appendErrorTokNotes(
    astgen: *AstGen,
    token: Ast.TokenIndex,
    comptime format: []const u8,
    args: anytype,
    notes: []const u32,
) !void {
    return appendErrorTokNotesOff(astgen, token, 0, format, args, notes);
}

/// 与 `fail` 相同,但会传入一个标记,以及相对于其起始字节偏移的偏移量。
///
fn failOff(
    astgen: *AstGen,
    token: Ast.TokenIndex,
    byte_offset: u32,
    comptime format: []const u8,
    args: anytype,
) InnerError {
    try appendErrorTokNotesOff(astgen, token, byte_offset, format, args, &.{});
    return error.AnalysisFail;
}

fn appendErrorTokNotesOff(
    astgen: *AstGen,
    token: Ast.TokenIndex,
    byte_offset: u32,
    comptime format: []const u8,
    args: anytype,
    notes: []const u32,
) !void {
    @branchHint(.cold);
    const gpa = astgen.gpa;
    const string_bytes = &astgen.string_bytes;
    const msg: Zir.NullTerminatedString = @fromBackingInt(@intCast(string_bytes.items.len));
    try string_bytes.print(gpa, format ++ "\x00", args);
    const notes_index: u32 = if (notes.len != 0) blk: {
        const notes_start = astgen.extra.items.len;
        try astgen.extra.ensureTotalCapacity(gpa, notes_start + 1 + notes.len);
        astgen.extra.appendAssumeCapacity(@intCast(notes.len));
        astgen.extra.appendSliceAssumeCapacity(notes);
        break :blk @intCast(notes_start);
    } else 0;
    try astgen.compile_errors.append(gpa, .{
        .msg = msg,
        .node = .none,
        .token = .fromToken(token),
        .byte_offset = byte_offset,
        .notes = notes_index,
    });
}

fn errNoteTok(
    astgen: *AstGen,
    token: Ast.TokenIndex,
    comptime format: []const u8,
    args: anytype,
) Allocator.Error!u32 {
    return errNoteTokOff(astgen, token, 0, format, args);
}

fn errNoteTokOff(
    astgen: *AstGen,
    token: Ast.TokenIndex,
    byte_offset: u32,
    comptime format: []const u8,
    args: anytype,
) Allocator.Error!u32 {
    @branchHint(.cold);
    const string_bytes = &astgen.string_bytes;
    const msg: Zir.NullTerminatedString = @fromBackingInt(@intCast(string_bytes.items.len));
    try string_bytes.print(astgen.gpa, format ++ "\x00", args);
    return astgen.addExtra(Zir.Inst.CompileErrors.Item{
        .msg = msg,
        .node = .none,
        .token = .fromToken(token),
        .byte_offset = byte_offset,
        .notes = 0,
    });
}

fn errNoteNode(
    astgen: *AstGen,
    node: Ast.Node.Index,
    comptime format: []const u8,
    args: anytype,
) Allocator.Error!u32 {
    @branchHint(.cold);
    const string_bytes = &astgen.string_bytes;
    const msg: Zir.NullTerminatedString = @fromBackingInt(@intCast(string_bytes.items.len));
    try string_bytes.print(astgen.gpa, format ++ "\x00", args);
    return astgen.addExtra(Zir.Inst.CompileErrors.Item{
        .msg = msg,
        .node = node.toOptional(),
        .token = .none,
        .byte_offset = 0,
        .notes = 0,
    });
}

fn identAsString(astgen: *AstGen, ident_token: Ast.TokenIndex) !Zir.NullTerminatedString {
    const gpa = astgen.gpa;
    const string_bytes = &astgen.string_bytes;
    const str_index: u32 = @intCast(string_bytes.items.len);
    try astgen.appendIdentStr(ident_token, string_bytes);
    const key: []const u8 = string_bytes.items[str_index..];
    const gop = try astgen.string_table.getOrPutContextAdapted(gpa, key, StringIndexAdapter{
        .bytes = string_bytes,
    }, StringIndexContext{
        .bytes = string_bytes,
    });
    if (gop.found_existing) {
        string_bytes.shrinkRetainingCapacity(str_index);
        return @fromBackingInt(@intCast(gop.key_ptr.*));
    } else {
        gop.key_ptr.* = str_index;
        try string_bytes.append(gpa, 0);
        return @fromBackingInt(@intCast(str_index));
    }
}

const IndexSlice = struct { index: Zir.NullTerminatedString, len: u32 };

fn strLitAsString(astgen: *AstGen, str_lit_token: Ast.TokenIndex) !IndexSlice {
    const gpa = astgen.gpa;
    const string_bytes = &astgen.string_bytes;
    const str_index: u32 = @intCast(string_bytes.items.len);
    const token_bytes = astgen.tree.tokenSlice(str_lit_token);
    try astgen.parseStrLit(str_lit_token, string_bytes, token_bytes, 0);
    const key: []const u8 = string_bytes.items[str_index..];
    if (std.mem.findScalar(u8, key, 0)) |_| return .{
        .index = @fromBackingInt(@intCast(str_index)),
        .len = @intCast(key.len),
    };
    const gop = try astgen.string_table.getOrPutContextAdapted(gpa, key, StringIndexAdapter{
        .bytes = string_bytes,
    }, StringIndexContext{
        .bytes = string_bytes,
    });
    if (gop.found_existing) {
        string_bytes.shrinkRetainingCapacity(str_index);
        return .{
            .index = @fromBackingInt(@intCast(gop.key_ptr.*)),
            .len = @intCast(key.len),
        };
    } else {
        gop.key_ptr.* = str_index;
        // 仍需要一个 null 字节,因为我们使用同一张表
        // 查找以 null 结尾的字符串,因此若匹配成功,
        // 它必须以 null 结尾才能正常工作。
        try string_bytes.append(gpa, 0);
        return .{
            .index = @fromBackingInt(@intCast(str_index)),
            .len = @intCast(key.len),
        };
    }
}

fn strLitNodeAsString(astgen: *AstGen, node: Ast.Node.Index) !IndexSlice {
    const tree = astgen.tree;

    const start, const end = tree.nodeData(node).token_and_token;

    const gpa = astgen.gpa;
    const string_bytes = &astgen.string_bytes;
    const str_index = string_bytes.items.len;

    // 首行:不追加换行符。
    var tok_i = start;
    {
        const slice = tree.tokenSlice(tok_i);
        const line_bytes = slice[2..];
        try string_bytes.appendSlice(gpa, line_bytes);
        tok_i += 1;
    }
    // 后续各行:每行前添加换行符。
    while (tok_i <= end) : (tok_i += 1) {
        const slice = tree.tokenSlice(tok_i);
        const line_bytes = slice[2..];
        try string_bytes.ensureUnusedCapacity(gpa, line_bytes.len + 1);
        string_bytes.appendAssumeCapacity('\n');
        string_bytes.appendSliceAssumeCapacity(line_bytes);
    }
    const len = string_bytes.items.len - str_index;
    try string_bytes.append(gpa, 0);
    return IndexSlice{
        .index = @fromBackingInt(@intCast(str_index)),
        .len = @intCast(len),
    };
}

const Scope = struct {
    tag: Tag,

    fn cast(base: *Scope, comptime T: type) ?*T {
        if (T == Defer) {
            switch (base.tag) {
                .defer_normal, .defer_error => return @alignCast(@fieldParentPtr("base", base)),
                else => return null,
            }
        }
        if (T == Namespace) {
            switch (base.tag) {
                .namespace => return @alignCast(@fieldParentPtr("base", base)),
                else => return null,
            }
        }
        if (base.tag != T.base_tag)
            return null;

        return @alignCast(@fieldParentPtr("base", base));
    }

    fn parent(base: *Scope) ?*Scope {
        return switch (base.tag) {
            .gen_zir => base.cast(GenZir).?.parent,
            .local_val => base.cast(LocalVal).?.parent,
            .local_ptr => base.cast(LocalPtr).?.parent,
            .defer_normal, .defer_error => base.cast(Defer).?.parent,
            .namespace => base.cast(Namespace).?.parent,
            .top => null,
        };
    }

    fn unwrap(base: *Scope) Unwrapped {
        return switch (base.tag) {
            inline else => |tag| @unionInit(
                Unwrapped,
                @tagName(tag),
                @alignCast(@fieldParentPtr("base", base)),
            ),
        };
    }

    const Unwrapped = union(Tag) {
        gen_zir: *GenZir,
        local_val: *LocalVal,
        local_ptr: *LocalPtr,
        defer_normal: *Defer,
        defer_error: *Defer,
        namespace: *Namespace,
        top: *Top,
    };

    const Tag = enum {
        gen_zir,
        local_val,
        local_ptr,
        defer_normal,
        defer_error,
        namespace,
        top,
    };

    /// 标识符类别。这些标签名称会在编译错误中向用户显示。
    const IdCat = enum {
        @"function parameter",
        @"local constant",
        @"local variable",
        @"switch tag capture",
        capture,
    };

    /// 这始终是 `const` 局部变量,且 `inst` 是值类型,而非指针。
    /// 此结构体的生命周期与包含该变量的 Block
    /// 节点的 AST 生成过程相同。
    const LocalVal = struct {
        const base_tag: Tag = .local_val;
        base: Scope = Scope{ .tag = base_tag },
        /// 父级可以为 `LocalVal`、`LocalPtr`、`GenZir`、`Defer` 或 `Namespace`。
        parent: *Scope,
        gen_zir: *GenZir,
        inst: Zir.Inst.Ref,
        /// 对应变量声明的源码位置。
        token_src: Ast.TokenIndex,
        /// 跟踪标识符首次被引用的位置。
        /// .none 表示从未引用。
        used: Ast.OptionalTokenIndex = .none,
        /// 跟踪标识符被丢弃的位置,例如 `_ = foo;`。
        /// .none 表示从未丢弃。
        discarded: Ast.OptionalTokenIndex = .none,
        is_used_or_discarded: ?*bool = null,
        /// 字符串表索引。
        name: Zir.NullTerminatedString,
        id_cat: IdCat,
    };

    /// 可能为 `const` 或 `var` 局部变量。持有指针而非值。
    /// 此结构的生存期与包含该变量的 Block
    /// 节点的 AST 生成过程相同。
    const LocalPtr = struct {
        const base_tag: Tag = .local_ptr;
        base: Scope = Scope{ .tag = base_tag },
        /// 父级可以为 `LocalVal`、`LocalPtr`、`GenZir`、`Defer` 或 `Namespace`。
        parent: *Scope,
        gen_zir: *GenZir,
        ptr: Zir.Inst.Ref,
        /// 对应变量声明的源码位置。
        token_src: Ast.TokenIndex,
        /// 跟踪标识符首次被引用的位置。
        /// .none 表示从未引用。
        used: Ast.OptionalTokenIndex = .none,
        /// 跟踪标识符被丢弃的位置,例如 `_ = foo;`。
        /// .none 表示从未丢弃。
        discarded: Ast.OptionalTokenIndex = .none,
        /// 此值在初始化后是否用作左值。
        /// 若不是,则可确定其能够为 `const`,因此若声明为 `var` 则产生编译错误。
        used_as_lvalue: bool = false,
        /// 字符串表索引。
        name: Zir.NullTerminatedString,
        id_cat: IdCat,
        /// true 表示在 Sema 阶段确定该值是否为编译期值。
        /// false 表示在 AstGen 阶段已知该值仅在运行时确定。
        maybe_comptime: bool,
    };

    const Defer = struct {
        base: Scope,
        /// 父级可以为 `LocalVal`、`LocalPtr`、`GenZir`、`Defer` 或 `Namespace`。
        parent: *Scope,
        index: u32,
        len: u32,
    };

    /// 表示可包含任意数量声明的全局作用域。
    /// 每个声明均以其为父作用域。
    const Namespace = struct {
        const base_tag: Tag = .namespace;
        base: Scope = Scope{ .tag = base_tag },

        /// 父级可以为 `LocalVal`、`LocalPtr`、`GenZir`、`Defer` 或 `Namespace`。
        parent: *Scope,
        /// 将字符串表索引映射到声明源码位置,用于报告名称遮蔽编译错误。
        ///
        decls: std.AutoHashMapUnmanaged(Zir.NullTerminatedString, Ast.Node.Index) = .empty,
        node: Ast.Node.Index,
        inst: Zir.Inst.Index,
        maybe_generic: bool,

        /// 包含此命名空间的 astgen 作用域。
        /// 仅在 astgen 期间有效。
        declaring_gz: ?*GenZir,

        /// 此命名空间使用的捕获集合。
        captures: std.array_hash_map.Auto(Zir.Inst.Capture, Zir.NullTerminatedString) = .empty,

        fn deinit(self: *Namespace, gpa: Allocator) void {
            self.decls.deinit(gpa);
            self.captures.deinit(gpa);
            self.* = undefined;
        }
    };

    const Top = struct {
        const base_tag: Scope.Tag = .top;
        base: Scope = Scope{ .tag = base_tag },
    };
};

/// 这是临时结构;对其引用仅在构造 `Zir`
/// 期间有效。
const GenZir = struct {
    const base_tag: Scope.Tag = .gen_zir;
    base: Scope = Scope{ .tag = base_tag },
    /// 是否已位于已知为编译时的作用域中。
    /// 只要知道 Sema 将以 `is_comptime` 分析当前块,就设置此值,
    /// 例如位于 `struct_decl` 或 `block_comptime` 内部时。
    is_comptime: bool,
    /// 当前是否位于 `@TypeOf` 操作数内的表达式中。此时允许捕获运行期变量,而通常情况下不允许。
    ///
    is_typeof: bool = false,
    /// 对 `block_inline` 的 `GenZir` 将此值设为 true,表示
    /// 退出此块时应使用 `break_inline`,而非 `break`。
    is_inline: bool = false,
    /// 包含该声明的 AST 节点。
    src_baseline: Ast.Node.Index,
    /// 包含该声明的行索引,使用绝对索引。
    decl_line: u32,
    /// 父级可以为 `LocalVal`、`LocalPtr`、`GenZir`、`Defer` 或 `Namespace`。
    parent: *Scope,
    /// 同一 ZIR 的所有 `GenZir` 作用域共用此项。
    astgen: *AstGen,
    /// 跟踪此作用域中的指令列表。可能被共享。
    /// 索引指向 `astgen` 中的指令。
    instructions: *ArrayList(Zir.Inst.Index),
    /// 若使用严格嵌套,子块可与包含它的 GenZir 共享指令 ArrayList。
    /// 此处保存列表先前的大小,以便退出嵌套时恢复。
    instructions_top: usize,
    label: ?Label = null,
    /// 为 `true` 时,无标签的 `break` 和 `continue` 表达式可以指向此 `GenZir`。
    allow_unlabeled_control_flow: bool = false,
    /// 若 `label` 为 `null` 且 `unlabeled_control_flow_target` 为 `false`,
    /// 则此字段不使用,可为 `undefined`。
    /// 否则,当 `break` 指向此 `GenZir` 时,
    /// 此字段就是该 `break` 指令的目标。
    break_target: Zir.Inst.Index = undefined,
    /// 若 `label` 为 `null` 且 `unlabeled_control_flow_target` 为 `false`,
    /// 则此字段未使用,可为 `undefined`。
    continue_target: union(enum) {
        /// `continue` 不能指向此 `GenZir`;报告错误。
        none,
        /// 生成以此块为目标的 `break` 指令。
        @"break": Zir.Inst.Index,
        /// 输出指向此 `switch_block` 的 `switch_continue` 指令。
        switch_continue: Zir.Inst.Index,
    } = undefined,
    /// 仅在调用 setBreakResultInfo 时有效。
    break_result_info: AstGen.ResultInfo = undefined,
    /// 若 `continue_target` 不是 *`switch_continue`*,则此项未使用,并可能为 `undefined`。
    ///
    continue_result_info: AstGen.ResultInfo = undefined,

    suspend_node: Ast.Node.OptionalIndex = .none,
    nosuspend_node: Ast.Node.OptionalIndex = .none,
    /// 若此 GenZir 为延迟执行语句,则置位。
    cur_defer_node: Ast.Node.OptionalIndex = .none,
    // 此 GenZir 是 defer 或位于 defer 内部时设置。
    any_defer_node: Ast.Node.OptionalIndex = .none,

    const unstacked_top = std.math.maxInt(usize);
    /// 向所属 GenZir 添加任何新指令之前,先调用 unstack。
    fn unstack(self: *GenZir) void {
        if (self.instructions_top != unstacked_top) {
            self.instructions.items.len = self.instructions_top;
            self.instructions_top = unstacked_top;
        }
    }

    fn isEmpty(self: *const GenZir) bool {
        return (self.instructions_top == unstacked_top) or
            (self.instructions.items.len == self.instructions_top);
    }

    fn instructionsSlice(self: *const GenZir) []Zir.Inst.Index {
        return if (self.instructions_top == unstacked_top)
            &[0]Zir.Inst.Index{}
        else
            self.instructions.items[self.instructions_top..];
    }

    fn instructionsSliceUpto(self: *const GenZir, stacked_gz: *GenZir) []Zir.Inst.Index {
        return if (self.instructions_top == unstacked_top)
            &[0]Zir.Inst.Index{}
        else if (self.instructions == stacked_gz.instructions and stacked_gz.instructions_top != unstacked_top)
            self.instructions.items[self.instructions_top..stacked_gz.instructions_top]
        else
            self.instructions.items[self.instructions_top..];
    }

    fn instructionsSliceUptoOpt(gz: *const GenZir, maybe_stacked_gz: ?*GenZir) []Zir.Inst.Index {
        if (maybe_stacked_gz) |stacked_gz| {
            return gz.instructionsSliceUpto(stacked_gz);
        } else {
            return gz.instructionsSlice();
        }
    }

    fn makeSubBlock(gz: *GenZir, scope: *Scope) GenZir {
        return .{
            .is_comptime = gz.is_comptime,
            .is_typeof = gz.is_typeof,
            .src_baseline = gz.src_baseline,
            .decl_line = gz.decl_line,
            .parent = scope,
            .astgen = gz.astgen,
            .suspend_node = gz.suspend_node,
            .nosuspend_node = gz.nosuspend_node,
            .any_defer_node = gz.any_defer_node,
            .instructions = gz.instructions,
            .instructions_top = gz.instructions.items.len,
        };
    }

    const Label = struct {
        token: Ast.TokenIndex,
        used: bool = false,
        used_for_continue: bool = false,
    };

    /// 假定 `gz` 上方没有其他堆叠项。
    fn endsWithNoReturn(gz: GenZir) bool {
        if (gz.isEmpty()) return false;
        const tags = gz.astgen.instructions.items(.tag);
        const last_inst = gz.instructions.items[gz.instructions.items.len - 1];
        return tags[@backingInt(last_inst)].isNoReturn();
    }

    /// TODO: 此项的所有用法均应替换为 `endsWithNoReturn`。
    fn refIsNoReturn(gz: GenZir, inst_ref: Zir.Inst.Ref) bool {
        if (inst_ref == .unreachable_value) return true;
        if (inst_ref.toIndex()) |inst_index| {
            return gz.astgen.instructions.items(.tag)[@backingInt(inst_index)].isNoReturn();
        }
        return false;
    }

    fn nodeIndexToRelative(gz: GenZir, node_index: Ast.Node.Index) Ast.Node.Offset {
        return gz.src_baseline.toOffset(node_index);
    }

    fn tokenIndexToRelative(gz: GenZir, token: Ast.TokenIndex) Ast.TokenOffset {
        return .init(gz.astgen.tree.firstToken(gz.src_baseline), token);
    }

    fn setBreakResultInfo(gz: *GenZir, parent_ri: AstGen.ResultInfo) void {
        // 根据结果位置是指针还是值,需要生成不同的
        // ZIR。前一种情况依靠写入
        // 指针来传递结果,并使用 breakvoid;后一种情况,
        // 块的跳出指令将携带结果值。
        switch (parent_ri.rl) {
            .coerced_ty => |ty_inst| {
                // 类型强制转换需要在退出前完成。
                gz.break_result_info = .{ .rl = .{ .ty = ty_inst }, .ctx = parent_ri.ctx };
            },
            .discard => {
                // 这里不转发结果上下文。这样可以避免
                // 远离实际丢弃位置的表达式导致“不必要的丢弃”错误,
                // 例如从结果被丢弃的块中
                // 执行 `break`。
                gz.break_result_info = .{ .rl = .discard };
            },
            else => {
                gz.break_result_info = parent_ri;
            },
        }
    }

    /// 假定 `gz` 上没有压入任何内容。弹出 `gz`。
    fn setBoolBrBody(gz: *GenZir, bool_br: Zir.Inst.Index, bool_br_lhs: Zir.Inst.Ref) !void {
        const astgen = gz.astgen;
        const gpa = astgen.gpa;
        const body = gz.instructionsSlice();
        const body_len = astgen.countBodyLenAfterFixups(body);
        try astgen.extra.ensureUnusedCapacity(
            gpa,
            @typeInfo(Zir.Inst.BoolBr).@"struct".field_names.len + body_len,
        );
        const zir_datas = astgen.instructions.items(.data);
        zir_datas[@backingInt(bool_br)].pl_node.payload_index = astgen.addExtraAssumeCapacity(Zir.Inst.BoolBr{
            .lhs = bool_br_lhs,
            .body_len = body_len,
        });
        astgen.appendBodyWithFixups(body);
        gz.unstack();
    }

    /// 假定 `gz` 上未叠加任何内容。弹出 `gz`。
    /// 断言 `inst` 不是 `block_comptime`。
    fn setBlockBody(gz: *GenZir, inst: Zir.Inst.Index) !void {
        const astgen = gz.astgen;
        const gpa = astgen.gpa;
        const body = gz.instructionsSlice();
        const body_len = astgen.countBodyLenAfterFixups(body);

        const zir_tags = astgen.instructions.items(.tag);
        assert(zir_tags[@backingInt(inst)] != .block_comptime); // 改用 `setComptimeBlockBody`

        try astgen.extra.ensureUnusedCapacity(
            gpa,
            @typeInfo(Zir.Inst.Block).@"struct".field_names.len + body_len,
        );
        const zir_datas = astgen.instructions.items(.data);
        zir_datas[@backingInt(inst)].pl_node.payload_index = astgen.addExtraAssumeCapacity(
            Zir.Inst.Block{ .body_len = body_len },
        );
        astgen.appendBodyWithFixups(body);
        gz.unstack();
    }

    /// 假定 `gz` 上没有压入任何内容。弹出 `gz`。
    /// 断言 `inst` 是 `block_comptime`。
    fn setBlockComptimeBody(gz: *GenZir, inst: Zir.Inst.Index, comptime_reason: std.zig.SimpleComptimeReason) !void {
        const astgen = gz.astgen;
        const gpa = astgen.gpa;
        const body = gz.instructionsSlice();
        const body_len = astgen.countBodyLenAfterFixups(body);

        const zir_tags = astgen.instructions.items(.tag);
        assert(zir_tags[@backingInt(inst)] == .block_comptime); // 改用 `setBlockBody`

        try astgen.extra.ensureUnusedCapacity(
            gpa,
            @typeInfo(Zir.Inst.BlockComptime).@"struct".field_names.len + body_len,
        );
        const zir_datas = astgen.instructions.items(.data);
        zir_datas[@backingInt(inst)].pl_node.payload_index = astgen.addExtraAssumeCapacity(
            Zir.Inst.BlockComptime{
                .reason = comptime_reason,
                .body_len = body_len,
            },
        );
        astgen.appendBodyWithFixups(body);
        gz.unstack();
    }

    /// 假定 `gz` 上没有压入任何内容。弹出 `gz`。
    fn setTryBody(gz: *GenZir, inst: Zir.Inst.Index, operand: Zir.Inst.Ref) !void {
        const astgen = gz.astgen;
        const gpa = astgen.gpa;
        const body = gz.instructionsSlice();
        const body_len = astgen.countBodyLenAfterFixups(body);
        try astgen.extra.ensureUnusedCapacity(
            gpa,
            @typeInfo(Zir.Inst.Try).@"struct".field_names.len + body_len,
        );
        const zir_datas = astgen.instructions.items(.data);
        zir_datas[@backingInt(inst)].pl_node.payload_index = astgen.addExtraAssumeCapacity(
            Zir.Inst.Try{
                .operand = operand,
                .body_len = body_len,
            },
        );
        astgen.appendBodyWithFixups(body);
        gz.unstack();
    }

    /// 调用时栈须按以下顺序设置:
    ///  * gz(栈底)
    ///  * cc_gz
    ///  * ret_gz
    ///  * body_gz(栈顶)
    /// 除 `gz` 外,所有这些项都会出栈。
    fn addFunc(
        gz: *GenZir,
        args: struct {
            src_node: Ast.Node.Index,
            lbrace_line: u32 = 0,
            lbrace_column: u32 = 0,
            param_block: Zir.Inst.Index,

            ret_gz: ?*GenZir,
            body_gz: ?*GenZir,
            cc_gz: ?*GenZir,

            ret_param_refs: []Zir.Inst.Index,
            param_insts: []Zir.Inst.Index, // `body_gz` 中对参数的引用仍应位于 `astgen.ref_table` 中
            ret_ty_is_generic: bool,

            cc_ref: Zir.Inst.Ref,
            ret_ref: Zir.Inst.Ref,

            noalias_bits: u32,
            is_var_args: bool,
            is_inferred_error: bool,
            is_noinline: bool,

            /// `body_gz == null` 时忽略。
            proto_hash: std.zig.SrcHash,
        },
    ) !Zir.Inst.Ref {
        assert(args.src_node != .root);
        const astgen = gz.astgen;
        const gpa = astgen.gpa;
        const ret_ref = if (args.ret_ref == .void_type) .none else args.ret_ref;
        const new_index: Zir.Inst.Index = @fromBackingInt(@intCast(astgen.instructions.len));

        try gz.instructions.ensureUnusedCapacity(gpa, 1);
        try astgen.instructions.ensureUnusedCapacity(gpa, 1);

        const body, const cc_body, const ret_body = bodies: {
            var stacked_gz: ?*GenZir = null;
            const body: []const Zir.Inst.Index = if (args.body_gz) |body_gz| body: {
                const body = body_gz.instructionsSliceUptoOpt(stacked_gz);
                stacked_gz = body_gz;
                break :body body;
            } else &.{};
            const ret_body: []const Zir.Inst.Index = if (args.ret_gz) |ret_gz| body: {
                const ret_body = ret_gz.instructionsSliceUptoOpt(stacked_gz);
                stacked_gz = ret_gz;
                break :body ret_body;
            } else &.{};
            const cc_body: []const Zir.Inst.Index = if (args.cc_gz) |cc_gz| body: {
                const cc_body = cc_gz.instructionsSliceUptoOpt(stacked_gz);
                stacked_gz = cc_gz;
                break :body cc_body;
            } else &.{};
            break :bodies .{ body, cc_body, ret_body };
        };

        var src_locs_and_hash_buffer: [7]u32 = undefined;
        const src_locs_and_hash: []const u32 = if (args.body_gz != null) src_locs_and_hash: {
            const tree = astgen.tree;
            const fn_decl = args.src_node;
            const block = switch (tree.nodeTag(fn_decl)) {
                .fn_decl => tree.nodeData(fn_decl).node_and_node[1],
                .test_decl => tree.nodeData(fn_decl).opt_token_and_node[1],
                else => unreachable,
            };
            const rbrace_start = tree.tokenStart(tree.lastToken(block));
            astgen.advanceSourceCursor(rbrace_start);
            const rbrace_line: u32 = @intCast(astgen.source_line - gz.decl_line);
            const rbrace_column: u32 = @intCast(astgen.source_column);

            const columns = args.lbrace_column | (rbrace_column << 16);

            const proto_hash_arr: [4]u32 = @bitCast(args.proto_hash);

            src_locs_and_hash_buffer = .{
                args.lbrace_line,
                rbrace_line,
                columns,
                proto_hash_arr[0],
                proto_hash_arr[1],
                proto_hash_arr[2],
                proto_hash_arr[3],
            };
            break :src_locs_and_hash &src_locs_and_hash_buffer;
        } else &.{};

        const body_len = astgen.countBodyLenAfterFixupsExtraRefs(body, args.param_insts);

        const tag: Zir.Inst.Tag, const payload_index: u32 = if (args.cc_ref != .none or
            args.is_var_args or args.noalias_bits != 0 or args.is_noinline)
        inst_info: {
            try astgen.extra.ensureUnusedCapacity(
                gpa,
                @typeInfo(Zir.Inst.FuncFancy).@"struct".field_names.len +
                    fancyFnExprExtraLen(astgen, &.{}, cc_body, args.cc_ref) +
                    fancyFnExprExtraLen(astgen, args.ret_param_refs, ret_body, ret_ref) +
                    body_len + src_locs_and_hash.len +
                    @intFromBool(args.noalias_bits != 0),
            );
            const payload_index = astgen.addExtraAssumeCapacity(Zir.Inst.FuncFancy{
                .param_block = args.param_block,
                .body_len = body_len,
                .bits = .{
                    .is_var_args = args.is_var_args,
                    .is_inferred_error = args.is_inferred_error,
                    .is_noinline = args.is_noinline,
                    .has_any_noalias = args.noalias_bits != 0,

                    .has_cc_ref = args.cc_ref != .none,
                    .has_ret_ty_ref = ret_ref != .none,

                    .has_cc_body = cc_body.len != 0,
                    .has_ret_ty_body = ret_body.len != 0,

                    .ret_ty_is_generic = args.ret_ty_is_generic,
                },
            });

            const zir_datas = astgen.instructions.items(.data);
            if (cc_body.len != 0) {
                astgen.extra.appendAssumeCapacity(astgen.countBodyLenAfterFixups(cc_body));
                astgen.appendBodyWithFixups(cc_body);
                const break_extra = zir_datas[@backingInt(cc_body[cc_body.len - 1])].@"break".payload_index;
                astgen.extra.items[break_extra + std.meta.fieldIndex(Zir.Inst.Break, "block_inst").?] =
                    @backingInt(new_index);
            } else if (args.cc_ref != .none) {
                astgen.extra.appendAssumeCapacity(@backingInt(args.cc_ref));
            }
            if (ret_body.len != 0) {
                astgen.extra.appendAssumeCapacity(
                    astgen.countBodyLenAfterFixups(args.ret_param_refs) +
                        astgen.countBodyLenAfterFixups(ret_body),
                );
                astgen.appendBodyWithFixups(args.ret_param_refs);
                astgen.appendBodyWithFixups(ret_body);
                const break_extra = zir_datas[@backingInt(ret_body[ret_body.len - 1])].@"break".payload_index;
                astgen.extra.items[break_extra + std.meta.fieldIndex(Zir.Inst.Break, "block_inst").?] =
                    @backingInt(new_index);
            } else if (ret_ref != .none) {
                astgen.extra.appendAssumeCapacity(@backingInt(ret_ref));
            }

            if (args.noalias_bits != 0) {
                astgen.extra.appendAssumeCapacity(args.noalias_bits);
            }

            astgen.appendBodyWithFixupsExtraRefsArrayList(&astgen.extra, body, args.param_insts);
            astgen.extra.appendSliceAssumeCapacity(src_locs_and_hash);

            break :inst_info .{ .func_fancy, payload_index };
        } else inst_info: {
            try astgen.extra.ensureUnusedCapacity(
                gpa,
                @typeInfo(Zir.Inst.Func).@"struct".field_names.len + 1 +
                    fancyFnExprExtraLen(astgen, args.ret_param_refs, ret_body, ret_ref) +
                    body_len + src_locs_and_hash.len,
            );

            const ret_body_len = if (ret_body.len != 0)
                countBodyLenAfterFixups(astgen, args.ret_param_refs) + countBodyLenAfterFixups(astgen, ret_body)
            else
                @intFromBool(ret_ref != .none);

            const payload_index = astgen.addExtraAssumeCapacity(Zir.Inst.Func{
                .param_block = args.param_block,
                .ret_ty = .{
                    .body_len = @intCast(ret_body_len),
                    .is_generic = args.ret_ty_is_generic,
                },
                .body_len = body_len,
            });
            const zir_datas = astgen.instructions.items(.data);
            if (ret_body.len != 0) {
                astgen.appendBodyWithFixups(args.ret_param_refs);
                astgen.appendBodyWithFixups(ret_body);

                const break_extra = zir_datas[@backingInt(ret_body[ret_body.len - 1])].@"break".payload_index;
                astgen.extra.items[break_extra + std.meta.fieldIndex(Zir.Inst.Break, "block_inst").?] =
                    @backingInt(new_index);
            } else if (ret_ref != .none) {
                astgen.extra.appendAssumeCapacity(@backingInt(ret_ref));
            }
            astgen.appendBodyWithFixupsExtraRefsArrayList(&astgen.extra, body, args.param_insts);
            astgen.extra.appendSliceAssumeCapacity(src_locs_and_hash);

            break :inst_info .{
                if (args.is_inferred_error) .func_inferred else .func,
                payload_index,
            };
        };

        // 出栈时顺序很重要。
        if (args.body_gz) |body_gz| body_gz.unstack();
        if (args.ret_gz) |ret_gz| ret_gz.unstack();
        if (args.cc_gz) |cc_gz| cc_gz.unstack();

        astgen.instructions.appendAssumeCapacity(.{
            .tag = tag,
            .data = .{ .pl_node = .{
                .src_node = gz.nodeIndexToRelative(args.src_node),
                .payload_index = payload_index,
            } },
        });
        gz.instructions.appendAssumeCapacity(new_index);
        return new_index.toRef();
    }

    fn fancyFnExprExtraLen(astgen: *AstGen, param_refs_body: []const Zir.Inst.Index, main_body: []const Zir.Inst.Index, ref: Zir.Inst.Ref) u32 {
        return countBodyLenAfterFixups(astgen, param_refs_body) +
            countBodyLenAfterFixups(astgen, main_body) +
            // 如果存在函数体,则需要一个元素记录其长度;否则,如果存在引用,则需要包含该引用。
            @intFromBool(main_body.len > 0 or ref != .none);
    }

    fn addInt(gz: *GenZir, integer: u64) !Zir.Inst.Ref {
        return gz.add(.{
            .tag = .int,
            .data = .{ .int = integer },
        });
    }

    fn addIntBig(gz: *GenZir, limbs: []const std.math.big.Limb) !Zir.Inst.Ref {
        const astgen = gz.astgen;
        const gpa = astgen.gpa;
        try gz.instructions.ensureUnusedCapacity(gpa, 1);
        try astgen.instructions.ensureUnusedCapacity(gpa, 1);
        try astgen.string_bytes.ensureUnusedCapacity(gpa, @sizeOf(std.math.big.Limb) * limbs.len);

        const new_index: Zir.Inst.Index = @fromBackingInt(@intCast(astgen.instructions.len));
        astgen.instructions.appendAssumeCapacity(.{
            .tag = .int_big,
            .data = .{ .str = .{
                .start = @fromBackingInt(@intCast(astgen.string_bytes.items.len)),
                .len = @intCast(limbs.len),
            } },
        });
        gz.instructions.appendAssumeCapacity(new_index);
        astgen.string_bytes.appendSliceAssumeCapacity(mem.sliceAsBytes(limbs));
        return new_index.toRef();
    }

    fn addFloat(gz: *GenZir, number: f64) !Zir.Inst.Ref {
        return gz.add(.{
            .tag = .float,
            .data = .{ .float = number },
        });
    }

    fn addUnNode(
        gz: *GenZir,
        tag: Zir.Inst.Tag,
        operand: Zir.Inst.Ref,
        /// 绝对节点索引。此函数将其转换为相对于 Decl 的偏移。
        src_node: Ast.Node.Index,
    ) !Zir.Inst.Ref {
        assert(operand != .none);
        return gz.add(.{
            .tag = tag,
            .data = .{ .un_node = .{
                .operand = operand,
                .src_node = gz.nodeIndexToRelative(src_node),
            } },
        });
    }

    fn makeUnNode(
        gz: *GenZir,
        tag: Zir.Inst.Tag,
        operand: Zir.Inst.Ref,
        /// 绝对节点索引。此函数将其转换为相对于 Decl 的偏移。
        src_node: Ast.Node.Index,
    ) !Zir.Inst.Index {
        assert(operand != .none);
        const new_index: Zir.Inst.Index = @fromBackingInt(@intCast(gz.astgen.instructions.len));
        try gz.astgen.instructions.append(gz.astgen.gpa, .{
            .tag = tag,
            .data = .{ .un_node = .{
                .operand = operand,
                .src_node = gz.nodeIndexToRelative(src_node),
            } },
        });
        return new_index;
    }

    fn addPlNode(
        gz: *GenZir,
        tag: Zir.Inst.Tag,
        /// 绝对节点索引。此函数将其转换为相对于 Decl 的偏移。
        src_node: Ast.Node.Index,
        extra: anytype,
    ) !Zir.Inst.Ref {
        const gpa = gz.astgen.gpa;
        try gz.instructions.ensureUnusedCapacity(gpa, 1);
        try gz.astgen.instructions.ensureUnusedCapacity(gpa, 1);

        const payload_index = try gz.astgen.addExtra(extra);
        const new_index: Zir.Inst.Index = @fromBackingInt(@intCast(gz.astgen.instructions.len));
        gz.astgen.instructions.appendAssumeCapacity(.{
            .tag = tag,
            .data = .{ .pl_node = .{
                .src_node = gz.nodeIndexToRelative(src_node),
                .payload_index = payload_index,
            } },
        });
        gz.instructions.appendAssumeCapacity(new_index);
        return new_index.toRef();
    }

    fn addPlNodePayloadIndex(
        gz: *GenZir,
        tag: Zir.Inst.Tag,
        /// 绝对节点索引。此函数将其转换为相对于 Decl 的偏移。
        src_node: Ast.Node.Index,
        payload_index: u32,
    ) !Zir.Inst.Ref {
        return try gz.add(.{
            .tag = tag,
            .data = .{ .pl_node = .{
                .src_node = gz.nodeIndexToRelative(src_node),
                .payload_index = payload_index,
            } },
        });
    }

    /// 支持将 `param_gz` 叠加在 `gz` 上。假定 `param_gz` 上未叠加任何内容。弹出 `param_gz`。
    fn addParam(
        gz: *GenZir,
        param_gz: *GenZir,
        /// 此前的参数,可能在 `param_gz`(新参数类型)中被引用。
        /// 这些指令的 `ref` 会放入此参数的类型体,并从 `AstGen.ref_table` 中移除。
        prev_param_insts: []const Zir.Inst.Index,
        ty_is_generic: bool,
        tag: Zir.Inst.Tag,
        /// 绝对词法标记索引。此函数负责转换为 Decl 偏移量。
        abs_tok_index: Ast.TokenIndex,
        name: Zir.NullTerminatedString,
    ) !Zir.Inst.Index {
        const gpa = gz.astgen.gpa;
        const param_body = param_gz.instructionsSlice();
        const body_len = gz.astgen.countBodyLenAfterFixupsExtraRefs(param_body, prev_param_insts);
        try gz.astgen.instructions.ensureUnusedCapacity(gpa, 1);
        try gz.astgen.extra.ensureUnusedCapacity(gpa, @typeInfo(Zir.Inst.Param).@"struct".field_names.len + body_len);

        const payload_index = gz.astgen.addExtraAssumeCapacity(Zir.Inst.Param{
            .name = name,
            .type = .{
                .body_len = @intCast(body_len),
                .is_generic = ty_is_generic,
            },
        });
        gz.astgen.appendBodyWithFixupsExtraRefsArrayList(&gz.astgen.extra, param_body, prev_param_insts);
        param_gz.unstack();

        const new_index: Zir.Inst.Index = @fromBackingInt(@intCast(gz.astgen.instructions.len));
        gz.astgen.instructions.appendAssumeCapacity(.{
            .tag = tag,
            .data = .{ .pl_tok = .{
                .src_tok = gz.tokenIndexToRelative(abs_tok_index),
                .payload_index = payload_index,
            } },
        });
        gz.instructions.appendAssumeCapacity(new_index);
        return new_index;
    }

    fn addStdLangValue(gz: *GenZir, src_node: Ast.Node.Index, val: Zir.Inst.StdLangValue) !Zir.Inst.Ref {
        return addExtendedNodeSmall(gz, .std_lang_value, src_node, @backingInt(val));
    }

    fn addExtendedPayload(gz: *GenZir, opcode: Zir.Inst.Extended, extra: anytype) !Zir.Inst.Ref {
        return addExtendedPayloadSmall(gz, opcode, undefined, extra);
    }

    fn addExtendedPayloadSmall(
        gz: *GenZir,
        opcode: Zir.Inst.Extended,
        small: u16,
        extra: anytype,
    ) !Zir.Inst.Ref {
        const gpa = gz.astgen.gpa;

        try gz.instructions.ensureUnusedCapacity(gpa, 1);
        try gz.astgen.instructions.ensureUnusedCapacity(gpa, 1);

        const payload_index = try gz.astgen.addExtra(extra);
        const new_index: Zir.Inst.Index = @fromBackingInt(@intCast(gz.astgen.instructions.len));
        gz.astgen.instructions.appendAssumeCapacity(.{
            .tag = .extended,
            .data = .{ .extended = .{
                .opcode = opcode,
                .small = small,
                .operand = payload_index,
            } },
        });
        gz.instructions.appendAssumeCapacity(new_index);
        return new_index.toRef();
    }

    fn addExtendedMultiOp(
        gz: *GenZir,
        opcode: Zir.Inst.Extended,
        node: Ast.Node.Index,
        operands: []const Zir.Inst.Ref,
    ) !Zir.Inst.Ref {
        const astgen = gz.astgen;
        const gpa = astgen.gpa;

        try gz.instructions.ensureUnusedCapacity(gpa, 1);
        try astgen.instructions.ensureUnusedCapacity(gpa, 1);
        try astgen.extra.ensureUnusedCapacity(
            gpa,
            @typeInfo(Zir.Inst.NodeMultiOp).@"struct".field_names.len + operands.len,
        );

        const payload_index = astgen.addExtraAssumeCapacity(Zir.Inst.NodeMultiOp{
            .src_node = gz.nodeIndexToRelative(node),
        });
        const new_index: Zir.Inst.Index = @fromBackingInt(@intCast(astgen.instructions.len));
        astgen.instructions.appendAssumeCapacity(.{
            .tag = .extended,
            .data = .{ .extended = .{
                .opcode = opcode,
                .small = @intCast(operands.len),
                .operand = payload_index,
            } },
        });
        gz.instructions.appendAssumeCapacity(new_index);
        astgen.appendRefsAssumeCapacity(operands);
        return new_index.toRef();
    }

    fn addExtendedMultiOpPayloadIndex(
        gz: *GenZir,
        opcode: Zir.Inst.Extended,
        payload_index: u32,
        trailing_len: usize,
    ) !Zir.Inst.Ref {
        const astgen = gz.astgen;
        const gpa = astgen.gpa;

        try gz.instructions.ensureUnusedCapacity(gpa, 1);
        try astgen.instructions.ensureUnusedCapacity(gpa, 1);
        const new_index: Zir.Inst.Index = @fromBackingInt(@intCast(astgen.instructions.len));
        astgen.instructions.appendAssumeCapacity(.{
            .tag = .extended,
            .data = .{ .extended = .{
                .opcode = opcode,
                .small = @intCast(trailing_len),
                .operand = payload_index,
            } },
        });
        gz.instructions.appendAssumeCapacity(new_index);
        return new_index.toRef();
    }

    fn addExtendedNodeSmall(
        gz: *GenZir,
        opcode: Zir.Inst.Extended,
        src_node: Ast.Node.Index,
        small: u16,
    ) !Zir.Inst.Ref {
        const astgen = gz.astgen;
        const gpa = astgen.gpa;

        try gz.instructions.ensureUnusedCapacity(gpa, 1);
        try astgen.instructions.ensureUnusedCapacity(gpa, 1);
        const new_index: Zir.Inst.Index = @fromBackingInt(@intCast(astgen.instructions.len));
        astgen.instructions.appendAssumeCapacity(.{
            .tag = .extended,
            .data = .{ .extended = .{
                .opcode = opcode,
                .small = small,
                .operand = @bitCast(@backingInt(gz.nodeIndexToRelative(src_node))),
            } },
        });
        gz.instructions.appendAssumeCapacity(new_index);
        return new_index.toRef();
    }

    fn addUnTok(
        gz: *GenZir,
        tag: Zir.Inst.Tag,
        operand: Zir.Inst.Ref,
        /// 绝对词法标记索引。此函数负责转换为 Decl 偏移量。
        abs_tok_index: Ast.TokenIndex,
    ) !Zir.Inst.Ref {
        assert(operand != .none);
        return gz.add(.{
            .tag = tag,
            .data = .{ .un_tok = .{
                .operand = operand,
                .src_tok = gz.tokenIndexToRelative(abs_tok_index),
            } },
        });
    }

    fn makeUnTok(
        gz: *GenZir,
        tag: Zir.Inst.Tag,
        operand: Zir.Inst.Ref,
        /// 绝对词法标记索引。此函数负责转换为 Decl 偏移量。
        abs_tok_index: Ast.TokenIndex,
    ) !Zir.Inst.Index {
        const astgen = gz.astgen;
        const new_index: Zir.Inst.Index = @fromBackingInt(@intCast(astgen.instructions.len));
        assert(operand != .none);
        try astgen.instructions.append(astgen.gpa, .{
            .tag = tag,
            .data = .{ .un_tok = .{
                .operand = operand,
                .src_tok = gz.tokenIndexToRelative(abs_tok_index),
            } },
        });
        return new_index;
    }

    fn addStrTok(
        gz: *GenZir,
        tag: Zir.Inst.Tag,
        str_index: Zir.NullTerminatedString,
        /// 绝对词法标记索引。此函数负责转换为 Decl 偏移量。
        abs_tok_index: Ast.TokenIndex,
    ) !Zir.Inst.Ref {
        return gz.add(.{
            .tag = tag,
            .data = .{ .str_tok = .{
                .start = str_index,
                .src_tok = gz.tokenIndexToRelative(abs_tok_index),
            } },
        });
    }

    fn addSaveErrRetIndex(
        gz: *GenZir,
        cond: union(enum) {
            always: void,
            if_of_error_type: Zir.Inst.Ref,
        },
    ) !Zir.Inst.Index {
        return gz.addAsIndex(.{
            .tag = .save_err_ret_index,
            .data = .{ .save_err_ret_index = .{
                .operand = switch (cond) {
                    .if_of_error_type => |x| x,
                    else => .none,
                },
            } },
        });
    }

    const BranchTarget = union(enum) {
        ret,
        block: Zir.Inst.Index,
    };

    fn addRestoreErrRetIndex(
        gz: *GenZir,
        bt: BranchTarget,
        cond: union(enum) {
            always: void,
            if_non_error: Zir.Inst.Ref,
        },
        src_node: Ast.Node.Index,
    ) !Zir.Inst.Index {
        switch (cond) {
            .always => return gz.addAsIndex(.{
                .tag = .restore_err_ret_index_unconditional,
                .data = .{ .un_node = .{
                    .operand = switch (bt) {
                        .ret => .none,
                        .block => |b| b.toRef(),
                    },
                    .src_node = gz.nodeIndexToRelative(src_node),
                } },
            }),
            .if_non_error => |operand| switch (bt) {
                .ret => return gz.addAsIndex(.{
                    .tag = .restore_err_ret_index_fn_entry,
                    .data = .{ .un_node = .{
                        .operand = operand,
                        .src_node = gz.nodeIndexToRelative(src_node),
                    } },
                }),
                .block => |block| return (try gz.addExtendedPayload(
                    .restore_err_ret_index,
                    Zir.Inst.RestoreErrRetIndex{
                        .src_node = gz.nodeIndexToRelative(src_node),
                        .block = block.toRef(),
                        .operand = operand,
                    },
                )).toIndex().?,
            },
        }
    }

    fn addBreak(
        gz: *GenZir,
        tag: Zir.Inst.Tag,
        block_inst: Zir.Inst.Index,
        operand: Zir.Inst.Ref,
    ) !Zir.Inst.Index {
        const gpa = gz.astgen.gpa;
        try gz.instructions.ensureUnusedCapacity(gpa, 1);

        const new_index = try gz.makeBreak(tag, block_inst, operand);
        gz.instructions.appendAssumeCapacity(new_index);
        return new_index;
    }

    fn makeBreak(
        gz: *GenZir,
        tag: Zir.Inst.Tag,
        block_inst: Zir.Inst.Index,
        operand: Zir.Inst.Ref,
    ) !Zir.Inst.Index {
        return gz.makeBreakCommon(tag, block_inst, operand, null);
    }

    fn addBreakWithSrcNode(
        gz: *GenZir,
        tag: Zir.Inst.Tag,
        block_inst: Zir.Inst.Index,
        operand: Zir.Inst.Ref,
        operand_src_node: Ast.Node.Index,
    ) !Zir.Inst.Index {
        const gpa = gz.astgen.gpa;
        try gz.instructions.ensureUnusedCapacity(gpa, 1);

        const new_index = try gz.makeBreakWithSrcNode(tag, block_inst, operand, operand_src_node);
        gz.instructions.appendAssumeCapacity(new_index);
        return new_index;
    }

    fn makeBreakWithSrcNode(
        gz: *GenZir,
        tag: Zir.Inst.Tag,
        block_inst: Zir.Inst.Index,
        operand: Zir.Inst.Ref,
        operand_src_node: Ast.Node.Index,
    ) !Zir.Inst.Index {
        return gz.makeBreakCommon(tag, block_inst, operand, operand_src_node);
    }

    fn makeBreakCommon(
        gz: *GenZir,
        tag: Zir.Inst.Tag,
        block_inst: Zir.Inst.Index,
        operand: Zir.Inst.Ref,
        operand_src_node: ?Ast.Node.Index,
    ) !Zir.Inst.Index {
        const gpa = gz.astgen.gpa;
        try gz.astgen.instructions.ensureUnusedCapacity(gpa, 1);
        try gz.astgen.extra.ensureUnusedCapacity(gpa, @typeInfo(Zir.Inst.Break).@"struct".field_names.len);

        const new_index: Zir.Inst.Index = @fromBackingInt(@intCast(gz.astgen.instructions.len));
        gz.astgen.instructions.appendAssumeCapacity(.{
            .tag = tag,
            .data = .{ .@"break" = .{
                .operand = operand,
                .payload_index = gz.astgen.addExtraAssumeCapacity(Zir.Inst.Break{
                    .operand_src_node = if (operand_src_node) |src_node|
                        gz.nodeIndexToRelative(src_node).toOptional()
                    else
                        .none,
                    .block_inst = block_inst,
                }),
            } },
        });
        return new_index;
    }

    fn addBin(
        gz: *GenZir,
        tag: Zir.Inst.Tag,
        lhs: Zir.Inst.Ref,
        rhs: Zir.Inst.Ref,
    ) !Zir.Inst.Ref {
        assert(lhs != .none);
        assert(rhs != .none);
        return gz.add(.{
            .tag = tag,
            .data = .{ .bin = .{
                .lhs = lhs,
                .rhs = rhs,
            } },
        });
    }

    fn addDefer(gz: *GenZir, index: u32, len: u32) !void {
        _ = try gz.add(.{
            .tag = .@"defer",
            .data = .{ .@"defer" = .{
                .index = index,
                .len = len,
            } },
        });
    }

    fn addDecl(
        gz: *GenZir,
        tag: Zir.Inst.Tag,
        decl_index: u32,
        src_node: Ast.Node.Index,
    ) !Zir.Inst.Ref {
        return gz.add(.{
            .tag = tag,
            .data = .{ .pl_node = .{
                .src_node = gz.nodeIndexToRelative(src_node),
                .payload_index = decl_index,
            } },
        });
    }

    fn addNode(
        gz: *GenZir,
        tag: Zir.Inst.Tag,
        /// 绝对节点索引。此函数将其转换为相对于 Decl 的偏移。
        src_node: Ast.Node.Index,
    ) !Zir.Inst.Ref {
        return gz.add(.{
            .tag = tag,
            .data = .{ .node = gz.nodeIndexToRelative(src_node) },
        });
    }

    fn addInstNode(
        gz: *GenZir,
        tag: Zir.Inst.Tag,
        inst: Zir.Inst.Index,
        /// 绝对节点索引。此函数将其转换为相对于 Decl 的偏移。
        src_node: Ast.Node.Index,
    ) !Zir.Inst.Ref {
        return gz.add(.{
            .tag = tag,
            .data = .{ .inst_node = .{
                .inst = inst,
                .src_node = gz.nodeIndexToRelative(src_node),
            } },
        });
    }

    fn addNodeExtended(
        gz: *GenZir,
        opcode: Zir.Inst.Extended,
        /// 绝对节点索引。此函数将其转换为相对于 Decl 的偏移。
        src_node: Ast.Node.Index,
    ) !Zir.Inst.Ref {
        return gz.add(.{
            .tag = .extended,
            .data = .{ .extended = .{
                .opcode = opcode,
                .small = undefined,
                .operand = @bitCast(@backingInt(gz.nodeIndexToRelative(src_node))),
            } },
        });
    }

    fn addAllocExtended(
        gz: *GenZir,
        args: struct {
            /// 绝对节点索引。此函数将其转换为相对于 Decl 的偏移。
            node: Ast.Node.Index,
            type_inst: Zir.Inst.Ref,
            align_inst: Zir.Inst.Ref,
            is_const: bool,
            is_comptime: bool,
        },
    ) !Zir.Inst.Ref {
        const astgen = gz.astgen;
        const gpa = astgen.gpa;

        try gz.instructions.ensureUnusedCapacity(gpa, 1);
        try astgen.instructions.ensureUnusedCapacity(gpa, 1);
        try astgen.extra.ensureUnusedCapacity(
            gpa,
            @typeInfo(Zir.Inst.AllocExtended).@"struct".field_names.len +
                @intFromBool(args.type_inst != .none) +
                @intFromBool(args.align_inst != .none),
        );
        const payload_index = gz.astgen.addExtraAssumeCapacity(Zir.Inst.AllocExtended{
            .src_node = gz.nodeIndexToRelative(args.node),
        });
        if (args.type_inst != .none) {
            astgen.extra.appendAssumeCapacity(@backingInt(args.type_inst));
        }
        if (args.align_inst != .none) {
            astgen.extra.appendAssumeCapacity(@backingInt(args.align_inst));
        }

        const has_type: u4 = @intFromBool(args.type_inst != .none);
        const has_align: u4 = @intFromBool(args.align_inst != .none);
        const is_const: u4 = @intFromBool(args.is_const);
        const is_comptime: u4 = @intFromBool(args.is_comptime);
        const small: u16 = has_type | (has_align << 1) | (is_const << 2) | (is_comptime << 3);

        const new_index: Zir.Inst.Index = @fromBackingInt(@intCast(astgen.instructions.len));
        astgen.instructions.appendAssumeCapacity(.{
            .tag = .extended,
            .data = .{ .extended = .{
                .opcode = .alloc,
                .small = small,
                .operand = payload_index,
            } },
        });
        gz.instructions.appendAssumeCapacity(new_index);
        return new_index.toRef();
    }

    fn addAsm(
        gz: *GenZir,
        args: struct {
            tag: Zir.Inst.Extended,
            /// 绝对节点索引。此函数将其转换为相对于 Decl 的偏移。
            node: Ast.Node.Index,
            asm_source: Zir.NullTerminatedString,
            output_type_bits: u32,
            is_volatile: bool,
            outputs: []const Zir.Inst.Asm.Output,
            inputs: []const Zir.Inst.Asm.Input,
            clobbers: Zir.Inst.Ref,
        },
    ) !Zir.Inst.Ref {
        const astgen = gz.astgen;
        const gpa = astgen.gpa;

        try gz.instructions.ensureUnusedCapacity(gpa, 1);
        try astgen.instructions.ensureUnusedCapacity(gpa, 1);
        try astgen.extra.ensureUnusedCapacity(gpa, @typeInfo(Zir.Inst.Asm).@"struct".field_names.len +
            args.outputs.len * @typeInfo(Zir.Inst.Asm.Output).@"struct".field_names.len +
            args.inputs.len * @typeInfo(Zir.Inst.Asm.Input).@"struct".field_names.len);

        const payload_index = gz.astgen.addExtraAssumeCapacity(Zir.Inst.Asm{
            .src_node = gz.nodeIndexToRelative(args.node),
            .asm_source = args.asm_source,
            .output_type_bits = args.output_type_bits,
            .clobbers = args.clobbers,
        });
        for (args.outputs) |output| {
            _ = gz.astgen.addExtraAssumeCapacity(output);
        }
        for (args.inputs) |input| {
            _ = gz.astgen.addExtraAssumeCapacity(input);
        }

        const small: Zir.Inst.Asm.Small = .{
            .is_volatile = args.is_volatile,
            .outputs_len = @intCast(args.outputs.len),
            .inputs_len = @intCast(args.inputs.len),
        };

        const new_index: Zir.Inst.Index = @fromBackingInt(@intCast(astgen.instructions.len));
        astgen.instructions.appendAssumeCapacity(.{
            .tag = .extended,
            .data = .{ .extended = .{
                .opcode = args.tag,
                .small = @bitCast(small),
                .operand = payload_index,
            } },
        });
        gz.instructions.appendAssumeCapacity(new_index);
        return new_index.toRef();
    }

    /// 注意,返回的是 `Zir.Inst.Index`,而非引用。
    /// 不会将块指令追加到作用域。
    /// 使 `payload_index` 字段保持未定义。
    fn makeBlockInst(gz: *GenZir, tag: Zir.Inst.Tag, node: Ast.Node.Index) !Zir.Inst.Index {
        const new_index: Zir.Inst.Index = @fromBackingInt(@intCast(gz.astgen.instructions.len));
        const gpa = gz.astgen.gpa;
        try gz.astgen.instructions.append(gpa, .{
            .tag = tag,
            .data = .{ .pl_node = .{
                .src_node = gz.nodeIndexToRelative(node),
                .payload_index = undefined,
            } },
        });
        return new_index;
    }

    /// 注意,此处返回 `Zir.Inst.Index`,而非 ref。
    /// *不会*将块指令追加到作用域。
    /// 将 `payload_index` 字段保持为未定义。用 `setDeclaration` 完成设置。
    fn makeDeclaration(gz: *GenZir, node: Ast.Node.Index) !Zir.Inst.Index {
        const new_index: Zir.Inst.Index = @fromBackingInt(@intCast(gz.astgen.instructions.len));
        try gz.astgen.instructions.append(gz.astgen.gpa, .{
            .tag = .declaration,
            .data = .{ .declaration = .{
                .src_node = node,
                .payload_index = undefined,
            } },
        });
        return new_index;
    }

    /// 注意,返回的是 `Zir.Inst.Index`,而非引用。
    /// 使 `payload_index` 字段保持未定义。
    fn addCondBr(gz: *GenZir, tag: Zir.Inst.Tag, node: Ast.Node.Index) !Zir.Inst.Index {
        const gpa = gz.astgen.gpa;
        try gz.instructions.ensureUnusedCapacity(gpa, 1);
        const new_index: Zir.Inst.Index = @fromBackingInt(@intCast(gz.astgen.instructions.len));
        try gz.astgen.instructions.append(gpa, .{
            .tag = tag,
            .data = .{ .pl_node = .{
                .src_node = gz.nodeIndexToRelative(node),
                .payload_index = undefined,
            } },
        });
        gz.instructions.appendAssumeCapacity(new_index);
        return new_index;
    }

    fn setStruct(gz: *GenZir, inst: Zir.Inst.Index, args: struct {
        src_line: u32,
        src_column: u32,
        src_node: Ast.Node.Index,
        name_strat: Zir.Inst.NameStrategy,
        arg_baseline_src_node: Ast.Node.OptionalIndex,
        fields_baseline_src_node: Ast.Node.OptionalIndex,
        layout: std.lang.Type.ContainerLayout,
        backing_int_type_body_len: ?u32,
        decls_len: u32,
        fields_len: u32,
        any_field_aligns: bool,
        any_field_defaults: bool,
        any_comptime_fields: bool,
        fields_hash: std.zig.SrcHash,
        captures: []const Zir.Inst.Capture,
        capture_names: []const Zir.NullTerminatedString,
        /// 尾随的声明列表、字段信息及体指令。
        remaining: []const u32,
    }) !void {
        const astgen = gz.astgen;
        const gpa = astgen.gpa;

        // 节点 .root 对文件的根 `struct_decl` 有效!
        assert(args.src_node != .root or gz.parent.tag == .top);

        const captures_len: u32 = @intCast(args.captures.len);
        assert(args.capture_names.len == captures_len);

        const fields_hash_arr: [4]u32 = @bitCast(args.fields_hash);

        try astgen.extra.ensureUnusedCapacity(gpa, @typeInfo(Zir.Inst.StructDecl).@"struct".field_names.len +
            3 + // `captures_len`, `decls_len`, `fields_len`
            2 + // `arg_baseline_src_node`、`fields_baseline_src_node`
            1 + // `backing_int_type_body_len`
            captures_len * 2 + // `capture`, `capture_name`
            args.remaining.len);

        const payload_index = astgen.addExtraAssumeCapacity(Zir.Inst.StructDecl{
            .fields_hash_0 = fields_hash_arr[0],
            .fields_hash_1 = fields_hash_arr[1],
            .fields_hash_2 = fields_hash_arr[2],
            .fields_hash_3 = fields_hash_arr[3],
            .src_line = args.src_line,
            .src_column = args.src_column,
            .src_node = args.src_node,
        });

        if (captures_len != 0) astgen.extra.appendAssumeCapacity(captures_len);
        if (args.decls_len != 0) astgen.extra.appendAssumeCapacity(args.decls_len);
        if (args.fields_len != 0) astgen.extra.appendAssumeCapacity(args.fields_len);
        if (args.backing_int_type_body_len != null) astgen.extra.appendAssumeCapacity(
            @backingInt(args.arg_baseline_src_node.unwrap().?),
        );
        if (args.fields_len != 0) astgen.extra.appendAssumeCapacity(
            @backingInt(args.fields_baseline_src_node.unwrap().?),
        );
        if (args.backing_int_type_body_len) |n| astgen.extra.appendAssumeCapacity(n);
        astgen.extra.appendSliceAssumeCapacity(@ptrCast(args.captures));
        astgen.extra.appendSliceAssumeCapacity(@ptrCast(args.capture_names));
        astgen.extra.appendSliceAssumeCapacity(args.remaining);

        astgen.instructions.set(@backingInt(inst), .{
            .tag = .extended,
            .data = .{ .extended = .{
                .opcode = .struct_decl,
                .small = @bitCast(Zir.Inst.StructDecl.Small{
                    .has_captures_len = captures_len != 0,
                    .has_decls_len = args.decls_len != 0,
                    .has_fields_len = args.fields_len != 0,
                    .name_strategy = args.name_strat,
                    .layout = args.layout,
                    .has_backing_int_type = args.backing_int_type_body_len != null,
                    .any_field_aligns = args.any_field_aligns,
                    .any_field_defaults = args.any_field_defaults,
                    .any_comptime_fields = args.any_comptime_fields,
                }),
                .operand = payload_index,
            } },
        });
    }

    fn setUnion(gz: *GenZir, inst: Zir.Inst.Index, args: struct {
        src_line: u32,
        src_column: u32,
        src_node: Ast.Node.Index,
        name_strat: Zir.Inst.NameStrategy,
        arg_baseline_src_node: Ast.Node.OptionalIndex,
        fields_baseline_src_node: Ast.Node.OptionalIndex,
        kind: Zir.Inst.UnionDecl.Kind,
        arg_type_body_len: ?u32,
        decls_len: u32,
        fields_len: u32,
        any_field_aligns: bool,
        any_field_values: bool,
        fields_hash: std.zig.SrcHash,
        captures: []const Zir.Inst.Capture,
        capture_names: []const Zir.NullTerminatedString,
        /// 尾随的声明列表、字段信息及体指令。
        remaining: []const u32,
    }) !void {
        const astgen = gz.astgen;
        const gpa = astgen.gpa;

        assert(args.src_node != .root);

        const captures_len: u32 = @intCast(args.captures.len);
        assert(args.capture_names.len == captures_len);

        const fields_hash_arr: [4]u32 = @bitCast(args.fields_hash);

        try astgen.extra.ensureUnusedCapacity(gpa, @typeInfo(Zir.Inst.UnionDecl).@"struct".field_names.len +
            3 + // `captures_len`, `decls_len`, `fields_len`
            2 + // `arg_baseline_src_node`、`fields_baseline_src_node`
            1 + // `arg_type_body_len`
            captures_len * 2 + // `capture`, `capture_name`
            args.remaining.len);

        const payload_index = astgen.addExtraAssumeCapacity(Zir.Inst.UnionDecl{
            .fields_hash_0 = fields_hash_arr[0],
            .fields_hash_1 = fields_hash_arr[1],
            .fields_hash_2 = fields_hash_arr[2],
            .fields_hash_3 = fields_hash_arr[3],
            .src_line = args.src_line,
            .src_column = args.src_column,
            .src_node = args.src_node,
        });

        if (captures_len != 0) astgen.extra.appendAssumeCapacity(captures_len);
        if (args.decls_len != 0) astgen.extra.appendAssumeCapacity(args.decls_len);
        if (args.fields_len != 0) astgen.extra.appendAssumeCapacity(args.fields_len);
        if (args.kind.hasArgType()) astgen.extra.appendAssumeCapacity(
            @backingInt(args.arg_baseline_src_node.unwrap().?),
        );
        if (args.fields_len != 0) astgen.extra.appendAssumeCapacity(
            @backingInt(args.fields_baseline_src_node.unwrap().?),
        );
        if (args.kind.hasArgType()) {
            astgen.extra.appendAssumeCapacity(args.arg_type_body_len.?);
        } else {
            assert(args.arg_type_body_len == null);
        }
        astgen.extra.appendSliceAssumeCapacity(@ptrCast(args.captures));
        astgen.extra.appendSliceAssumeCapacity(@ptrCast(args.capture_names));
        astgen.extra.appendSliceAssumeCapacity(args.remaining);

        astgen.instructions.set(@backingInt(inst), .{
            .tag = .extended,
            .data = .{ .extended = .{
                .opcode = .union_decl,
                .small = @bitCast(Zir.Inst.UnionDecl.Small{
                    .has_captures_len = captures_len != 0,
                    .has_decls_len = args.decls_len != 0,
                    .has_fields_len = args.fields_len != 0,
                    .name_strategy = args.name_strat,
                    .kind = args.kind,
                    .any_field_aligns = args.any_field_aligns,
                    .any_field_values = args.any_field_values,
                }),
                .operand = payload_index,
            } },
        });
    }

    fn setEnum(gz: *GenZir, inst: Zir.Inst.Index, args: struct {
        src_line: u32,
        src_column: u32,
        src_node: Ast.Node.Index,
        name_strat: Zir.Inst.NameStrategy,
        arg_baseline_src_node: Ast.Node.OptionalIndex,
        fields_baseline_src_node: Ast.Node.OptionalIndex,
        tag_type_body_len: ?u32,
        nonexhaustive: bool,
        decls_len: u32,
        fields_len: u32,
        any_field_values: bool,
        fields_hash: std.zig.SrcHash,
        captures: []const Zir.Inst.Capture,
        capture_names: []const Zir.NullTerminatedString,
        /// 尾随的声明列表、字段信息及体指令。
        remaining: []const u32,
    }) !void {
        const astgen = gz.astgen;
        const gpa = astgen.gpa;

        assert(args.src_node != .root);

        const captures_len: u32 = @intCast(args.captures.len);
        assert(args.capture_names.len == captures_len);

        const fields_hash_arr: [4]u32 = @bitCast(args.fields_hash);

        try astgen.extra.ensureUnusedCapacity(gpa, @typeInfo(Zir.Inst.EnumDecl).@"struct".field_names.len +
            3 + // `captures_len`, `decls_len`, `fields_len`
            2 + // `arg_baseline_src_node`、`fields_baseline_src_node`
            1 + // `tag_type_body_len`
            captures_len * 2 + // `capture`, `capture_name`
            args.remaining.len);

        const payload_index = astgen.addExtraAssumeCapacity(Zir.Inst.EnumDecl{
            .fields_hash_0 = fields_hash_arr[0],
            .fields_hash_1 = fields_hash_arr[1],
            .fields_hash_2 = fields_hash_arr[2],
            .fields_hash_3 = fields_hash_arr[3],
            .src_line = args.src_line,
            .src_column = args.src_column,
            .src_node = args.src_node,
        });

        if (captures_len != 0) astgen.extra.appendAssumeCapacity(captures_len);
        if (args.decls_len != 0) astgen.extra.appendAssumeCapacity(args.decls_len);
        if (args.fields_len != 0) astgen.extra.appendAssumeCapacity(args.fields_len);
        if (args.tag_type_body_len != null) astgen.extra.appendAssumeCapacity(
            @backingInt(args.arg_baseline_src_node.unwrap().?),
        );
        if (args.fields_len != 0) astgen.extra.appendAssumeCapacity(
            @backingInt(args.fields_baseline_src_node.unwrap().?),
        );
        if (args.tag_type_body_len) |n| astgen.extra.appendAssumeCapacity(n);
        astgen.extra.appendSliceAssumeCapacity(@ptrCast(args.captures));
        astgen.extra.appendSliceAssumeCapacity(@ptrCast(args.capture_names));
        astgen.extra.appendSliceAssumeCapacity(args.remaining);

        astgen.instructions.set(@backingInt(inst), .{
            .tag = .extended,
            .data = .{ .extended = .{
                .opcode = .enum_decl,
                .small = @bitCast(Zir.Inst.EnumDecl.Small{
                    .has_captures_len = captures_len != 0,
                    .has_decls_len = args.decls_len != 0,
                    .has_fields_len = args.fields_len != 0,
                    .name_strategy = args.name_strat,
                    .has_tag_type = args.tag_type_body_len != null,
                    .nonexhaustive = args.nonexhaustive,
                    .any_field_values = args.any_field_values,
                }),
                .operand = payload_index,
            } },
        });
    }

    fn setOpaque(gz: *GenZir, inst: Zir.Inst.Index, args: struct {
        src_line: u32,
        src_column: u32,
        src_node: Ast.Node.Index,
        name_strat: Zir.Inst.NameStrategy,
        decls_len: u32,
        captures: []const Zir.Inst.Capture,
        capture_names: []const Zir.NullTerminatedString,
        decls: []const Zir.Inst.Index,
    }) !void {
        const astgen = gz.astgen;
        const gpa = astgen.gpa;

        assert(args.src_node != .root);

        const captures_len: u32 = @intCast(args.captures.len);
        assert(args.capture_names.len == captures_len);

        try astgen.extra.ensureUnusedCapacity(gpa, @typeInfo(Zir.Inst.OpaqueDecl).@"struct".field_names.len +
            2 + // `captures_len`, `decls_len`
            captures_len * 2 + // `capture`, `capture_name`
            args.decls.len);

        const payload_index = astgen.addExtraAssumeCapacity(Zir.Inst.OpaqueDecl{
            .src_line = args.src_line,
            .src_column = args.src_column,
            .src_node = args.src_node,
        });
        if (captures_len != 0) astgen.extra.appendAssumeCapacity(captures_len);
        if (args.decls_len != 0) astgen.extra.appendAssumeCapacity(args.decls_len);
        astgen.extra.appendSliceAssumeCapacity(@ptrCast(args.captures));
        astgen.extra.appendSliceAssumeCapacity(@ptrCast(args.capture_names));
        astgen.extra.appendSliceAssumeCapacity(@ptrCast(args.decls));

        astgen.instructions.set(@backingInt(inst), .{
            .tag = .extended,
            .data = .{ .extended = .{
                .opcode = .opaque_decl,
                .small = @bitCast(Zir.Inst.OpaqueDecl.Small{
                    .has_captures_len = captures_len != 0,
                    .has_decls_len = args.decls_len != 0,
                    .name_strategy = args.name_strat,
                }),
                .operand = payload_index,
            } },
        });
    }

    fn add(gz: *GenZir, inst: Zir.Inst) !Zir.Inst.Ref {
        return (try gz.addAsIndex(inst)).toRef();
    }

    fn addAsIndex(gz: *GenZir, inst: Zir.Inst) !Zir.Inst.Index {
        const gpa = gz.astgen.gpa;
        try gz.instructions.ensureUnusedCapacity(gpa, 1);
        try gz.astgen.instructions.ensureUnusedCapacity(gpa, 1);

        const new_index: Zir.Inst.Index = @fromBackingInt(@intCast(gz.astgen.instructions.len));
        gz.astgen.instructions.appendAssumeCapacity(inst);
        gz.instructions.appendAssumeCapacity(new_index);
        return new_index;
    }

    fn reserveInstructionIndex(gz: *GenZir) !Zir.Inst.Index {
        const gpa = gz.astgen.gpa;
        try gz.instructions.ensureUnusedCapacity(gpa, 1);
        try gz.astgen.instructions.ensureUnusedCapacity(gpa, 1);

        const new_index: Zir.Inst.Index = @fromBackingInt(@intCast(gz.astgen.instructions.len));
        gz.astgen.instructions.len += 1;
        gz.instructions.appendAssumeCapacity(new_index);
        return new_index;
    }

    fn addRet(gz: *GenZir, ri: ResultInfo, operand: Zir.Inst.Ref, node: Ast.Node.Index) !void {
        switch (ri.rl) {
            .ptr => |ptr_res| _ = try gz.addUnNode(.ret_load, ptr_res.inst, node),
            .coerced_ty => _ = try gz.addUnNode(.ret_node, operand, node),
            else => unreachable,
        }
    }

    fn addDbgVar(gz: *GenZir, tag: Zir.Inst.Tag, name: Zir.NullTerminatedString, inst: Zir.Inst.Ref) !void {
        if (gz.is_comptime) return;

        _ = try gz.add(.{ .tag = tag, .data = .{
            .str_op = .{
                .str = name,
                .operand = inst,
            },
        } });
    }
};

/// 这只能用于短期引用;
/// 添加另一个字符串时,该内存即失效。
fn nullTerminatedString(astgen: AstGen, index: Zir.NullTerminatedString) [*:0]const u8 {
    return @ptrCast(astgen.string_bytes.items[@backingInt(index)..]);
}

/// 局部变量遮蔽检测,包括函数参数。
fn detectLocalShadowing(
    astgen: *AstGen,
    scope: *Scope,
    ident_name: Zir.NullTerminatedString,
    name_token: Ast.TokenIndex,
    ident_name_raw: []const u8,
    id_cat: Scope.IdCat,
) !void {
    const gpa = astgen.gpa;
    if (ident_name_raw[0] != '@' and isPrimitive(ident_name_raw)) {
        return astgen.failTokNotes(name_token, "name shadows primitive '{s}'", .{
            ident_name_raw,
        }, &[_]u32{
            try astgen.errNoteTok(name_token, "consider using @\"{s}\" to disambiguate", .{
                ident_name_raw,
            }),
        });
    }

    var outer_scope = false;
    find_scope: switch (scope.unwrap()) {
        .local_val => |local_val| {
            if (local_val.name == ident_name) {
                const name_slice = mem.span(astgen.nullTerminatedString(ident_name));
                const name = try gpa.dupe(u8, name_slice);
                defer gpa.free(name);
                if (outer_scope) {
                    return astgen.failTokNotes(name_token, "{s} '{s}' shadows {s} from outer scope", .{
                        @tagName(id_cat), name, @tagName(local_val.id_cat),
                    }, &[_]u32{
                        try astgen.errNoteTok(
                            local_val.token_src,
                            "previous declaration here",
                            .{},
                        ),
                    });
                }
                return astgen.failTokNotes(name_token, "redeclaration of {s} '{s}'", .{
                    @tagName(local_val.id_cat), name,
                }, &[_]u32{
                    try astgen.errNoteTok(
                        local_val.token_src,
                        "previous declaration here",
                        .{},
                    ),
                });
            }
            continue :find_scope local_val.parent.unwrap();
        },
        .local_ptr => |local_ptr| {
            if (local_ptr.name == ident_name) {
                const name_slice = mem.span(astgen.nullTerminatedString(ident_name));
                const name = try gpa.dupe(u8, name_slice);
                defer gpa.free(name);
                if (outer_scope) {
                    return astgen.failTokNotes(name_token, "{s} '{s}' shadows {s} from outer scope", .{
                        @tagName(id_cat), name, @tagName(local_ptr.id_cat),
                    }, &[_]u32{
                        try astgen.errNoteTok(
                            local_ptr.token_src,
                            "previous declaration here",
                            .{},
                        ),
                    });
                }
                return astgen.failTokNotes(name_token, "redeclaration of {s} '{s}'", .{
                    @tagName(local_ptr.id_cat), name,
                }, &[_]u32{
                    try astgen.errNoteTok(
                        local_ptr.token_src,
                        "previous declaration here",
                        .{},
                    ),
                });
            }
            continue :find_scope local_ptr.parent.unwrap();
        },
        .namespace => |ns| {
            outer_scope = true;
            const decl_node = ns.decls.get(ident_name) orelse {
                continue :find_scope ns.parent.unwrap();
            };
            const name_slice = mem.span(astgen.nullTerminatedString(ident_name));
            const name = try gpa.dupe(u8, name_slice);
            defer gpa.free(name);
            return astgen.failTokNotes(name_token, "{s} shadows declaration of '{s}'", .{
                @tagName(id_cat), name,
            }, &[_]u32{
                try astgen.errNoteNode(decl_node, "declared here", .{}),
            });
        },
        .gen_zir => |gen_zir| {
            outer_scope = true;
            continue :find_scope gen_zir.parent.unwrap();
        },
        .defer_normal, .defer_error => |defer_scope| continue :find_scope defer_scope.parent.unwrap(),
        .top => break :find_scope,
    }
}

const LineColumn = struct { u32, u32 };

/// 若不在编译期作用域中,将源码游标推进到 `node` 的主标记。
/// 通常与 `emitDbgStmt` 配合使用。
fn maybeAdvanceSourceCursorToMainToken(gz: *GenZir, node: Ast.Node.Index) LineColumn {
    if (gz.is_comptime) return .{ gz.astgen.source_line - gz.decl_line, gz.astgen.source_column };

    const tree = gz.astgen.tree;
    const node_start = tree.tokenStart(tree.nodeMainToken(node));
    gz.astgen.advanceSourceCursor(node_start);

    return .{ gz.astgen.source_line - gz.decl_line, gz.astgen.source_column };
}

/// 将源码游标推进到 `node` 的起点。
fn advanceSourceCursorToNode(astgen: *AstGen, node: Ast.Node.Index) void {
    const tree = astgen.tree;
    const node_start = tree.tokenStart(tree.firstToken(node));
    astgen.advanceSourceCursor(node_start);
}

/// 将源码游标推进至文件中的绝对字节偏移 `end`。
fn advanceSourceCursor(astgen: *AstGen, end: usize) void {
    const source = astgen.tree.source;
    var i = astgen.source_offset;
    var line = astgen.source_line;
    var column = astgen.source_column;
    assert(i <= end);
    while (i < end) : (i += 1) {
        if (source[i] == '\n') {
            line += 1;
            column = 0;
        } else {
            column += 1;
        }
    }
    astgen.source_offset = i;
    astgen.source_line = line;
    astgen.source_column = column;
}

const SourceCursor = struct {
    offset: u32,
    line: u32,
    column: u32,
};

/// 获取当前源码游标,稍后可通过 `restoreSourceCursor` 恢复。
/// 适用于乱序分析源码。
fn saveSourceCursor(astgen: *const AstGen) SourceCursor {
    return .{
        .offset = astgen.source_offset,
        .line = astgen.source_line,
        .column = astgen.source_column,
    };
}
fn restoreSourceCursor(astgen: *AstGen, cursor: SourceCursor) void {
    astgen.source_offset = cursor.offset;
    astgen.source_line = cursor.line;
    astgen.source_column = cursor.column;
}

const ScanContainerResult = struct {
    /// 包含未命名声明(例如 `comptime` 声明)
    decls_len: u32,
    fields_len: u32,
    any_field_aligns: bool,
    any_field_values: bool,
    any_comptime_fields: bool,
    /// 是否存在名为 `_` 的字段(表示非穷尽枚举)
    has_underscore_field: bool,
};

/// 检测声明和字段的名称冲突,并将所有具名声明填入 `namespace.decls`。
fn scanContainer(
    astgen: *AstGen,
    namespace: *Scope.Namespace,
    members: []const Ast.Node.Index,
    container_kind: enum { @"struct", @"union", @"enum", @"opaque" },
) !ScanContainerResult {
    const gpa = astgen.gpa;
    const tree = astgen.tree;

    var any_invalid_declarations = false;

    // 此类型组成一个链表,保存声明同一名称的源码 token。
    const NameEntry = struct {
        tok: Ast.TokenIndex,
        /// 此处使用链表可简化内存管理,且仅在出错时
        /// 才分配条目,因此可以接受。条目分配到
        /// AstGen 的 arena 中。
        next: ?*@This(),
    };

    // 以下映射使用此 BFA 分配,以避免对小型命名空间使用 GPA。
    var bfa_buf: [512]u8 = undefined;
    var bfa_state: std.heap.BufferFirstAllocator = .init(&bfa_buf, astgen.gpa);
    const bfa = bfa_state.allocator();

    var names: std.array_hash_map.Auto(Zir.NullTerminatedString, NameEntry) = .empty;
    var test_names: std.array_hash_map.Auto(Zir.NullTerminatedString, NameEntry) = .empty;
    var decltest_names: std.array_hash_map.Auto(Zir.NullTerminatedString, NameEntry) = .empty;
    defer {
        names.deinit(bfa);
        test_names.deinit(bfa);
        decltest_names.deinit(bfa);
    }

    var any_duplicates = false;
    var decl_count: u32 = 0;
    var any_field_aligns = false;
    var any_field_values = false;
    var any_comptime_fields = false;
    var has_underscore_field = false;
    for (members) |member_node| {
        const Kind = enum { decl, field };
        const kind: Kind, const name_token = switch (tree.nodeTag(member_node)) {
            .container_field_init,
            .container_field_align,
            .container_field,
            => blk: {
                var full = tree.fullContainerField(member_node).?;
                switch (container_kind) {
                    .@"struct", .@"opaque" => {},
                    .@"union", .@"enum" => full.convertToNonTupleLike(astgen.tree),
                }
                if (full.ast.align_expr != .none) any_field_aligns = true;
                if (full.ast.value_expr != .none) any_field_values = true;
                if (full.comptime_token != null) any_comptime_fields = true;
                if (mem.eql(u8, tree.tokenSlice(full.ast.main_token), "_")) has_underscore_field = true;
                if (full.ast.tuple_like) continue;
                break :blk .{ .field, full.ast.main_token };
            },

            .global_var_decl,
            .local_var_decl,
            .simple_var_decl,
            .aligned_var_decl,
            => blk: {
                decl_count += 1;
                break :blk .{ .decl, tree.nodeMainToken(member_node) + 1 };
            },

            .fn_proto_simple,
            .fn_proto_multi,
            .fn_proto_one,
            .fn_proto,
            .fn_decl,
            => blk: {
                decl_count += 1;
                const ident = tree.nodeMainToken(member_node) + 1;
                if (tree.tokenTag(ident) != .identifier) {
                    try astgen.appendErrorNode(member_node, "missing function name", .{});
                    any_invalid_declarations = true;
                    continue;
                }
                break :blk .{ .decl, ident };
            },

            .@"comptime" => {
                decl_count += 1;
                continue;
            },

            .test_decl => {
                decl_count += 1;
                // 此处不需要遮蔽检测,且测试名称的处理略有不同,
                // 因此必须自行检测重复声明。
                const test_name_token = tree.nodeMainToken(member_node) + 1;
                const new_ent: NameEntry = .{
                    .tok = test_name_token,
                    .next = null,
                };
                switch (tree.tokenTag(test_name_token)) {
                    else => {}, // 未命名测试
                    .string_literal => {
                        const name = try astgen.strLitAsString(test_name_token);
                        const gop = try test_names.getOrPut(bfa, name.index);
                        if (gop.found_existing) {
                            var e = gop.value_ptr;
                            while (e.next) |n| e = n;
                            e.next = try astgen.arena.create(NameEntry);
                            e.next.?.* = new_ent;
                            any_duplicates = true;
                        } else {
                            gop.value_ptr.* = new_ent;
                        }
                    },
                    .identifier => {
                        const name = try astgen.identAsString(test_name_token);
                        const gop = try decltest_names.getOrPut(bfa, name);
                        if (gop.found_existing) {
                            var e = gop.value_ptr;
                            while (e.next) |n| e = n;
                            e.next = try astgen.arena.create(NameEntry);
                            e.next.?.* = new_ent;
                            any_duplicates = true;
                        } else {
                            gop.value_ptr.* = new_ent;
                        }
                    },
                }
                continue;
            },

            else => unreachable,
        };

        const name_str_index = try astgen.identAsString(name_token);

        if (kind == .decl) {
            // 即使存在编译错误,也直接将名称放入 `decls`。
            // 这可避免后续出现不正确的“未声明标识符”错误。
            try namespace.decls.put(gpa, name_str_index, member_node);
        }

        {
            const gop = try names.getOrPut(bfa, name_str_index);
            const new_ent: NameEntry = .{
                .tok = name_token,
                .next = null,
            };
            if (gop.found_existing) {
                var e = gop.value_ptr;
                while (e.next) |n| e = n;
                e.next = try astgen.arena.create(NameEntry);
                e.next.?.* = new_ent;
                any_duplicates = true;
                continue;
            } else {
                gop.value_ptr.* = new_ent;
            }
        }

        // 对于字段,只需执行重复检查!不过,声明还需要更多检查。
        switch (kind) {
            .decl => {},
            .field => continue,
        }

        const token_bytes = astgen.tree.tokenSlice(name_token);
        if (token_bytes[0] != '@' and isPrimitive(token_bytes)) {
            try astgen.appendErrorTokNotes(name_token, "name shadows primitive '{s}'", .{
                token_bytes,
            }, &.{
                try astgen.errNoteTok(name_token, "consider using @\"{s}\" to disambiguate", .{
                    token_bytes,
                }),
            });
            any_invalid_declarations = true;
            continue;
        }

        find_scope: switch (namespace.parent.unwrap()) {
            .local_val => |local_val| {
                if (local_val.name == name_str_index) {
                    try astgen.appendErrorTokNotes(name_token, "declaration '{s}' shadows {s} from outer scope", .{
                        token_bytes, @tagName(local_val.id_cat),
                    }, &.{
                        try astgen.errNoteTok(
                            local_val.token_src,
                            "previous declaration here",
                            .{},
                        ),
                    });
                    any_invalid_declarations = true;
                    break :find_scope;
                }
                continue :find_scope local_val.parent.unwrap();
            },
            .local_ptr => |local_ptr| {
                if (local_ptr.name == name_str_index) {
                    try astgen.appendErrorTokNotes(name_token, "declaration '{s}' shadows {s} from outer scope", .{
                        token_bytes, @tagName(local_ptr.id_cat),
                    }, &.{
                        try astgen.errNoteTok(
                            local_ptr.token_src,
                            "previous declaration here",
                            .{},
                        ),
                    });
                    any_invalid_declarations = true;
                    break :find_scope;
                }
                continue :find_scope local_ptr.parent.unwrap();
            },
            .namespace => |ns| continue :find_scope ns.parent.unwrap(),
            .gen_zir => |gen_zir| continue :find_scope gen_zir.parent.unwrap(),
            .defer_normal, .defer_error => |defer_scope| continue :find_scope defer_scope.parent.unwrap(),
            .top => break :find_scope,
        }
    }

    if (!any_duplicates) {
        if (any_invalid_declarations) return error.AnalysisFail;
        return .{
            .decls_len = decl_count,
            .fields_len = @intCast(members.len - decl_count),
            .any_field_aligns = any_field_aligns,
            .any_field_values = any_field_values,
            .any_comptime_fields = any_comptime_fields,
            .has_underscore_field = has_underscore_field,
        };
    }

    for (names.keys(), names.values()) |name, first| {
        if (first.next == null) continue;
        var notes: std.ArrayList(u32) = .empty;
        var prev: NameEntry = first;
        while (prev.next) |cur| : (prev = cur.*) {
            try notes.append(astgen.arena, try astgen.errNoteTok(cur.tok, "duplicate name here", .{}));
        }
        try notes.append(astgen.arena, try astgen.errNoteNode(namespace.node, "{s} declared here", .{@tagName(container_kind)}));
        const name_duped = try astgen.arena.dupe(u8, mem.span(astgen.nullTerminatedString(name)));
        try astgen.appendErrorTokNotes(first.tok, "duplicate {s} member name '{s}'", .{ @tagName(container_kind), name_duped }, notes.items);
        any_invalid_declarations = true;
    }

    for (test_names.keys(), test_names.values()) |name, first| {
        if (first.next == null) continue;
        var notes: std.ArrayList(u32) = .empty;
        var prev: NameEntry = first;
        while (prev.next) |cur| : (prev = cur.*) {
            try notes.append(astgen.arena, try astgen.errNoteTok(cur.tok, "duplicate test here", .{}));
        }
        try notes.append(astgen.arena, try astgen.errNoteNode(namespace.node, "{s} declared here", .{@tagName(container_kind)}));
        const name_duped = try astgen.arena.dupe(u8, mem.span(astgen.nullTerminatedString(name)));
        try astgen.appendErrorTokNotes(first.tok, "duplicate test name '{s}'", .{name_duped}, notes.items);
        any_invalid_declarations = true;
    }

    for (decltest_names.keys(), decltest_names.values()) |name, first| {
        if (first.next == null) continue;
        var notes: std.ArrayList(u32) = .empty;
        var prev: NameEntry = first;
        while (prev.next) |cur| : (prev = cur.*) {
            try notes.append(astgen.arena, try astgen.errNoteTok(cur.tok, "duplicate decltest here", .{}));
        }
        try notes.append(astgen.arena, try astgen.errNoteNode(namespace.node, "{s} declared here", .{@tagName(container_kind)}));
        const name_duped = try astgen.arena.dupe(u8, mem.span(astgen.nullTerminatedString(name)));
        try astgen.appendErrorTokNotes(first.tok, "duplicate decltest '{s}'", .{name_duped}, notes.items);
        any_invalid_declarations = true;
    }

    assert(any_invalid_declarations);
    return error.AnalysisFail;
}

fn appendPlaceholder(astgen: *AstGen) Allocator.Error!Zir.Inst.Index {
    const inst: Zir.Inst.Index = @fromBackingInt(@intCast(astgen.instructions.len));
    try astgen.instructions.append(astgen.gpa, .{
        .tag = .extended,
        .data = .{ .extended = .{
            .opcode = .value_placeholder,
            .small = undefined,
            .operand = undefined,
        } },
    });
    return inst;
}

/// 假定已为消息体增加容量。计入修正项后所需的
/// 容量可通过 `countBodyLenAfterFixups` 获得。
fn appendBodyWithFixups(astgen: *AstGen, body: []const Zir.Inst.Index) void {
    return appendBodyWithFixupsArrayList(astgen, &astgen.extra, body);
}

fn appendBodyWithFixupsArrayList(
    astgen: *AstGen,
    list: *std.ArrayList(u32),
    body: []const Zir.Inst.Index,
) void {
    astgen.appendBodyWithFixupsExtraRefsArrayList(list, body, &.{});
}

fn appendBodyWithFixupsExtraRefsArrayList(
    astgen: *AstGen,
    list: *std.ArrayList(u32),
    body: []const Zir.Inst.Index,
    extra_refs: []const Zir.Inst.Index,
) void {
    for (extra_refs) |extra_inst| {
        if (astgen.ref_table.fetchRemove(extra_inst)) |kv| {
            appendPossiblyRefdBodyInst(astgen, list, kv.value);
        }
    }
    for (body) |body_inst| {
        appendPossiblyRefdBodyInst(astgen, list, body_inst);
    }
}

fn appendPossiblyRefdBodyInst(
    astgen: *AstGen,
    list: *std.ArrayList(u32),
    body_inst: Zir.Inst.Index,
) void {
    list.appendAssumeCapacity(@backingInt(body_inst));
    const kv = astgen.ref_table.fetchRemove(body_inst) orelse return;
    const ref_inst = kv.value;
    return appendPossiblyRefdBodyInst(astgen, list, ref_inst);
}

fn countBodyLenAfterFixups(astgen: *AstGen, body: []const Zir.Inst.Index) u32 {
    return astgen.countBodyLenAfterFixupsExtraRefs(body, &.{});
}

/// 返回 `body` 中的指令数量,包含前置的 `ref` 指令,这些指令来自 `ref_table`。
/// 除 `body` 中的全部指令外,还会前置 `ref`,对应于 `extra_refs` 中的任意指令。
/// 例如,若某个索引已为子块保留特殊含义,必须将其传入 `extra_refs`,以确保正确添加该索引的 `ref`。
///
fn countBodyLenAfterFixupsExtraRefs(astgen: *AstGen, body: []const Zir.Inst.Index, extra_refs: []const Zir.Inst.Index) u32 {
    var count = body.len;
    for (body) |body_inst| {
        var check_inst = body_inst;
        while (astgen.ref_table.get(check_inst)) |ref_inst| {
            count += 1;
            check_inst = ref_inst;
        }
    }
    for (extra_refs) |extra_inst| {
        var check_inst = extra_inst;
        while (astgen.ref_table.get(check_inst)) |ref_inst| {
            count += 1;
            check_inst = ref_inst;
        }
    }
    return @intCast(count);
}

fn emitDbgStmt(gz: *GenZir, lc: LineColumn) !void {
    if (gz.is_comptime) return;
    if (gz.instructions.items.len > gz.instructions_top) {
        const astgen = gz.astgen;
        const last = gz.instructions.items[gz.instructions.items.len - 1];
        if (astgen.instructions.items(.tag)[@backingInt(last)] == .dbg_stmt) {
            astgen.instructions.items(.data)[@backingInt(last)].dbg_stmt = .{
                .line = lc[0],
                .column = lc[1],
            };
            return;
        }
    }

    _ = try gz.add(.{ .tag = .dbg_stmt, .data = .{
        .dbg_stmt = .{
            .line = lc[0],
            .column = lc[1],
        },
    } });
}

/// 某些情况下,Sema 要求在紧挨下一条指令之前的指令
/// *索引*处生成 `dbg_stmt`(例如调用位于 %10 时,
/// 期望 %9 处为 dbg_stmt)。TODO: 此逻辑可能产生冗余的 dbg_stmt
/// 指令;应修正 Sema,使此逻辑不再必要!
fn emitDbgStmtForceCurrentIndex(gz: *GenZir, lc: LineColumn) !void {
    const astgen = gz.astgen;
    if (gz.instructions.items.len > gz.instructions_top and
        @backingInt(gz.instructions.items[gz.instructions.items.len - 1]) == astgen.instructions.len - 1)
    {
        const last = astgen.instructions.len - 1;
        if (astgen.instructions.items(.tag)[last] == .dbg_stmt) {
            astgen.instructions.items(.data)[last].dbg_stmt = .{
                .line = lc[0],
                .column = lc[1],
            };
            return;
        }
    }

    _ = try gz.add(.{ .tag = .dbg_stmt, .data = .{
        .dbg_stmt = .{
            .line = lc[0],
            .column = lc[1],
        },
    } });
}

fn lowerAstErrors(astgen: *AstGen) error{OutOfMemory}!void {
    const gpa = astgen.gpa;
    const tree = astgen.tree;
    assert(tree.errors.len > 0);

    var msg: std.Io.Writer.Allocating = .init(gpa);
    defer msg.deinit();
    const msg_w = &msg.writer;

    var notes: std.ArrayList(u32) = .empty;
    defer notes.deinit(gpa);

    const token_starts = tree.tokens.items(.start);
    const token_tags = tree.tokens.items(.tag);
    const parse_err = tree.errors[0];
    const tok = parse_err.token + @intFromBool(parse_err.token_is_prev);
    const tok_start = token_starts[tok];
    const start_char = tree.source[tok_start];

    if (token_tags[tok] == .invalid and
        (start_char == '\"' or start_char == '\'' or start_char == '/' or mem.startsWith(u8, tree.source[tok_start..], "\\\\")))
    {
        const tok_len: u32 = @intCast(tree.tokenSlice(tok).len);
        const tok_end = tok_start + tok_len;
        const bad_off = blk: {
            var idx = tok_start;
            while (idx < tok_end) : (idx += 1) {
                switch (tree.source[idx]) {
                    0x00...0x09, 0x0b...0x1f, 0x7f => break,
                    else => {},
                }
            }
            break :blk idx - tok_start;
        };

        const ast_err: Ast.Error = .{
            .tag = Ast.Error.Tag.invalid_byte,
            .token = tok,
            .extra = .{ .offset = bad_off },
        };
        msg.clearRetainingCapacity();
        tree.renderError(ast_err, msg_w) catch return error.OutOfMemory;
        return try astgen.appendErrorTokNotesOff(tok, bad_off, "{s}", .{msg.written()}, notes.items);
    }

    var cur_err = tree.errors[0];
    for (tree.errors[1..]) |err| {
        if (err.is_note) {
            tree.renderError(err, msg_w) catch return error.OutOfMemory;
            try notes.append(gpa, try astgen.errNoteTok(err.token, "{s}", .{msg.written()}));
        } else {
            // 刷新错误
            const extra_offset = tree.errorOffset(cur_err);
            tree.renderError(cur_err, msg_w) catch return error.OutOfMemory;
            try astgen.appendErrorTokNotesOff(cur_err.token, extra_offset, "{s}", .{msg.written()}, notes.items);
            notes.clearRetainingCapacity();
            cur_err = err;

            // TODO: `Parse` 当前没有完善的错误恢复机制,因此剩余错误可能是伪错误。
            // 因此暂时忽略所有剩余错误。我们应改进 `Parse`,以便报告所有错误。
            return;
        }
        msg.clearRetainingCapacity();
    }

    // 刷新错误
    const extra_offset = tree.errorOffset(cur_err);
    tree.renderError(cur_err, msg_w) catch return error.OutOfMemory;
    try astgen.appendErrorTokNotesOff(cur_err.token, extra_offset, "{s}", .{msg.written()}, notes.items);
}

const DeclarationName = union(enum) {
    named: Ast.TokenIndex,
    named_test: Ast.TokenIndex,
    decltest: Ast.TokenIndex,
    unnamed_test,
    @"comptime",
};

fn addFailedDeclaration(
    wip_decls: *WipDecls,
    gz: *GenZir,
    kind: Zir.Inst.Declaration.Unwrapped.Kind,
    name: Zir.NullTerminatedString,
    src_node: Ast.Node.Index,
    is_pub: bool,
) !void {
    const decl_inst = try gz.makeDeclaration(src_node);
    wip_decls.nextDecl(decl_inst);

    var dummy_gz = gz.makeSubBlock(&gz.base);

    var value_gz = gz.makeSubBlock(&gz.base); // 此处作用域无关紧要
    _ = try value_gz.add(.{
        .tag = .extended,
        .data = .{ .extended = .{
            .opcode = .astgen_error,
            .small = undefined,
            .operand = undefined,
        } },
    });

    try setDeclaration(decl_inst, .{
        .src_hash = @splat(0), // 使用固定哈希表示 AstGen 失败;只要 AstGen 仍失败,就不关心源码变化!
        .src_line = gz.astgen.source_line,
        .src_column = gz.astgen.source_column,
        .kind = kind,
        .name = name,
        .is_pub = is_pub,
        .is_threadlocal = false,
        .linkage = .normal,
        .type_gz = &dummy_gz,
        .align_gz = &dummy_gz,
        .linksection_gz = &dummy_gz,
        .addrspace_gz = &dummy_gz,
        .value_gz = &value_gz,
    });
}

/// 设置 `declaration` 指令的全部额外数据。
/// 弹出 `type_gz`、`align_gz`、`linksection_gz`、`addrspace_gz` 和 `value_gz`。
fn setDeclaration(
    decl_inst: Zir.Inst.Index,
    args: struct {
        src_hash: std.zig.SrcHash,
        src_line: u32,
        src_column: u32,

        kind: Zir.Inst.Declaration.Unwrapped.Kind,
        name: Zir.NullTerminatedString,
        is_pub: bool,
        is_threadlocal: bool,
        linkage: Zir.Inst.Declaration.Unwrapped.Linkage,
        lib_name: Zir.NullTerminatedString = .empty,

        type_gz: *GenZir,
        /// 必须叠加在 `type_gz` 上。
        align_gz: *GenZir,
        /// 必须堆叠在 `align_gz` 之上。
        addrspace_gz: *GenZir,
        /// 必须叠放在 `addrspace_gz` 之上。
        linksection_gz: *GenZir,
        /// 必须叠放在 `linksection_gz` 之上,且其上方不得有其他项。
        value_gz: *GenZir,
    },
) !void {
    const astgen = args.value_gz.astgen;
    const gpa = astgen.gpa;

    const type_body = args.type_gz.instructionsSliceUpto(args.align_gz);
    const align_body = args.align_gz.instructionsSliceUpto(args.addrspace_gz);
    const addrspace_body = args.addrspace_gz.instructionsSliceUpto(args.linksection_gz);
    const linksection_body = args.linksection_gz.instructionsSliceUpto(args.value_gz);
    const value_body = args.value_gz.instructionsSlice();

    const has_name = args.name != .empty;
    const has_lib_name = args.lib_name != .empty;
    const has_type_body = type_body.len != 0;
    const has_special_body = align_body.len != 0 or linksection_body.len != 0 or addrspace_body.len != 0;
    const has_value_body = value_body.len != 0;

    const id: Zir.Inst.Declaration.Flags.Id = switch (args.kind) {
        .unnamed_test => .unnamed_test,
        .@"test" => .@"test",
        .decltest => .decltest,
        .@"comptime" => .@"comptime",
        .@"const" => switch (args.linkage) {
            .normal => if (args.is_pub) id: {
                if (has_special_body) break :id .pub_const;
                if (has_type_body) break :id .pub_const_typed;
                break :id .pub_const_simple;
            } else id: {
                if (has_special_body) break :id .@"const";
                if (has_type_body) break :id .const_typed;
                break :id .const_simple;
            },
            .@"extern" => if (args.is_pub) id: {
                if (has_lib_name) break :id .pub_extern_const;
                if (has_special_body) break :id .pub_extern_const;
                break :id .pub_extern_const_simple;
            } else id: {
                if (has_lib_name) break :id .extern_const;
                if (has_special_body) break :id .extern_const;
                break :id .extern_const_simple;
            },
            .@"export" => if (args.is_pub) .pub_export_const else .export_const,
        },
        .@"var" => switch (args.linkage) {
            .normal => if (args.is_pub) id: {
                if (args.is_threadlocal) break :id .pub_var_threadlocal;
                if (has_special_body) break :id .pub_var;
                if (has_type_body) break :id .pub_var;
                break :id .pub_var_simple;
            } else id: {
                if (args.is_threadlocal) break :id .var_threadlocal;
                if (has_special_body) break :id .@"var";
                if (has_type_body) break :id .@"var";
                break :id .var_simple;
            },
            .@"extern" => if (args.is_pub) id: {
                if (args.is_threadlocal) break :id .pub_extern_var_threadlocal;
                break :id .pub_extern_var;
            } else id: {
                if (args.is_threadlocal) break :id .extern_var_threadlocal;
                break :id .extern_var;
            },
            .@"export" => if (args.is_pub) id: {
                if (args.is_threadlocal) break :id .pub_export_var_threadlocal;
                break :id .pub_export_var;
            } else id: {
                if (args.is_threadlocal) break :id .export_var_threadlocal;
                break :id .export_var;
            },
        },
    };

    assert(id.hasTypeBody() or !has_type_body);
    assert(id.hasSpecialBodies() or !has_special_body);
    assert(id.hasValueBody() == has_value_body);
    assert(id.linkage() == args.linkage);
    assert(id.hasName() == has_name);
    assert(id.hasLibName() or !has_lib_name);
    assert(id.isPub() == args.is_pub);
    assert(id.isThreadlocal() == args.is_threadlocal);

    const type_len = astgen.countBodyLenAfterFixups(type_body);
    const align_len = astgen.countBodyLenAfterFixups(align_body);
    const linksection_len = astgen.countBodyLenAfterFixups(linksection_body);
    const addrspace_len = astgen.countBodyLenAfterFixups(addrspace_body);
    const value_len = astgen.countBodyLenAfterFixups(value_body);

    const src_hash_arr: [4]u32 = @bitCast(args.src_hash);
    const flags: Zir.Inst.Declaration.Flags = .{
        .src_line = @intCast(args.src_line),
        .src_column = @intCast(args.src_column),
        .id = id,
    };
    const flags_arr: [2]u32 = @bitCast(flags);

    const need_extra: usize =
        @typeInfo(Zir.Inst.Declaration).@"struct".field_names.len +
        @as(usize, @intFromBool(id.hasName())) +
        @as(usize, @intFromBool(id.hasLibName())) +
        @as(usize, @intFromBool(id.hasTypeBody())) +
        3 * @as(usize, @intFromBool(id.hasSpecialBodies())) +
        @as(usize, @intFromBool(id.hasValueBody())) +
        type_len + align_len + linksection_len + addrspace_len + value_len;

    try astgen.extra.ensureUnusedCapacity(gpa, need_extra);

    const extra: Zir.Inst.Declaration = .{
        .src_hash_0 = src_hash_arr[0],
        .src_hash_1 = src_hash_arr[1],
        .src_hash_2 = src_hash_arr[2],
        .src_hash_3 = src_hash_arr[3],
        .flags_0 = flags_arr[0],
        .flags_1 = flags_arr[1],
    };
    astgen.instructions.items(.data)[@backingInt(decl_inst)].declaration.payload_index =
        astgen.addExtraAssumeCapacity(extra);

    if (id.hasName()) {
        astgen.extra.appendAssumeCapacity(@backingInt(args.name));
    }
    if (id.hasLibName()) {
        astgen.extra.appendAssumeCapacity(@backingInt(args.lib_name));
    }
    if (id.hasTypeBody()) {
        astgen.extra.appendAssumeCapacity(type_len);
    }
    if (id.hasSpecialBodies()) {
        astgen.extra.appendSliceAssumeCapacity(&.{
            align_len,
            linksection_len,
            addrspace_len,
        });
    }
    if (id.hasValueBody()) {
        astgen.extra.appendAssumeCapacity(value_len);
    }

    astgen.appendBodyWithFixups(type_body);
    astgen.appendBodyWithFixups(align_body);
    astgen.appendBodyWithFixups(linksection_body);
    astgen.appendBodyWithFixups(addrspace_body);
    astgen.appendBodyWithFixups(value_body);

    args.value_gz.unstack();
    args.addrspace_gz.unstack();
    args.linksection_gz.unstack();
    args.align_gz.unstack();
    args.type_gz.unstack();
}

/// 给定指令列表,返回对其中任一原始指令执行 `ref` 的全部指令列表,来源为 `astgen.ref_table`,不递归搜索。条目会从 `astgen.ref_table` 移除,返回的切片随后可作为独立主体,将 `ref` 指令追加到不同于其通常所属主体的其他主体中。
///
/// 这用于函数降级。极少数情况下,调用约定表达式、对齐表达式等可能通过 `&param` 引用函数参数;此时必须在调用约定、对齐等表达式主体中降级为 `ref` 指令,而不是放在声明主体中。然而,不会立即将这些主体追加到 `extra`,而是等到所有主体都求值到一个大型 `GenZir` 栈中之后才执行追加。因此,使用此函数提取每个主体中必须输出的 `ref` 指令。
///
///
///
///
///
///
///
fn fetchRemoveRefEntries(astgen: *AstGen, param_insts: []const Zir.Inst.Index) ![]Zir.Inst.Index {
    var refs: std.ArrayList(Zir.Inst.Index) = .empty;
    for (param_insts) |param_inst| {
        if (astgen.ref_table.fetchRemove(param_inst)) |kv| {
            try refs.append(astgen.arena, kv.value);
        }
    }
    return refs.items;
}

test {
    _ = &generate;
}