Zig 源码的抽象语法树。 对于 Zig 语法,根节点位于 nodes[0],包含 子节点列表。 对于 ZON 语法,根节点位于 nodes[0],其 lhs 为 主表达式的节点索引。
字段
source: [:0]const u8对外部拥有数据的引用。
tokens: TokenList.Slice
nodes: NodeList.Slice
extra_data: []u32
mode: Mode = .zig
errors: []const Error
stdasserttestingmemTokenAstAllocatorParseWriterByteOffsetTokenListNodeListTokenIndexOptionalTokenIndexTokenOffsetOptionalTokenOffsettokenTagtokenStartnodeTagnodeMainTokennodeDataisTokenPrecededByTagsLocationSpandeinitModeParseOptionsparseparseTokensrenderAllocRenderrendererrorOffsettokenLocationtokenSliceextraDataSliceextraDataSliceWithLenextraDataloadOptionalNodesIntoBufferrootDeclsrenderErrorfirstTokenlastTokentokensOnSameLinegetNodeSourceglobalVarDecllocalVarDeclsimpleVarDeclalignedVarDeclassignDestructureifSimpleifFullcontainerFieldcontainerFieldInitcontainerFieldAlignfnProtoSimplefnProtoMultifnProtoOnefnProtostructInitOnestructInitDotTwostructInitDotstructInitarrayInitOnearrayInitDotTwoarrayInitDotarrayInitarrayTypearrayTypeSentinelptrTypeAlignedptrTypeSentinelptrTypeptrTypeBitRangesliceOpenslicesliceSentinelcontainerDeclTwocontainerDeclcontainerDeclArgcontainerDeclRoottaggedUnionTwotaggedUniontaggedUnionEnumTagswitchFullswitchCaseOneswitchCaseasmSimpleasmFullwhileSimplewhileContwhileFullforSimpleforFullcallOnecallFullfullVarDeclComponentsfullAssignDestructureComponentsfullIfComponentsfullContainerFieldComponentsfullFnProtoComponentsfullPtrTypeComponentsfullContainerDeclComponentsfullSwitchComponentsfullSwitchCaseComponentsfullAsmComponentsfullWhileComponentsfullForComponentsfullVarDeclfullIffullWhilefullForfullContainerFieldfullFnProtofullStructInitfullArrayInitfullArrayTypefullPtrTypefullSlicefullContainerDeclfullSwitchfullSwitchCasefullAsmfullCallbuiltinCallParamsblockStatementsfullErrorExtraIndexNodenodeToSpantokenToSpantokensToSpan
std.zig.Ast.alignedVarDecl
函数
pub fn alignedVarDecl(tree: Ast, node: Node.Index) full.VarDecl
参数
std.zig.Ast.Allocator
别名
别名目标 std.mem.Allocator
std.zig.Ast.arrayInit
函数
pub fn arrayInit(tree: Ast, node: Node.Index) full.ArrayInit
参数
std.zig.Ast.arrayInitDot
函数
pub fn arrayInitDot(tree: Ast, node: Node.Index) full.ArrayInit
参数
std.zig.Ast.arrayInitDotTwo
函数
pub fn arrayInitDotTwo(tree: Ast, buffer: *[2]Node.Index, node: Node.Index) full.ArrayInit
参数
std.zig.Ast.arrayInitOne
函数
pub fn arrayInitOne(tree: Ast, buffer: *[1]Node.Index, node: Node.Index) full.ArrayInit
参数
std.zig.Ast.arrayType
函数
pub fn arrayType(tree: Ast, node: Node.Index) full.ArrayType
参数
std.zig.Ast.arrayTypeSentinel
函数
pub fn arrayTypeSentinel(tree: Ast, node: Node.Index) full.ArrayType
参数
std.zig.Ast.asmFull
函数
pub fn asmFull(tree: Ast, node: Node.Index) full.Asm
参数
std.zig.Ast.asmSimple
函数
pub fn asmSimple(tree: Ast, node: Node.Index) full.Asm
参数
std.zig.Ast.assert
别名
别名目标 std.debug.assert
std.zig.Ast.assignDestructure
函数
pub fn assignDestructure(tree: Ast, node: Node.Index) full.AssignDestructure
参数
std.zig.Ast.Ast
别名
别名目标 std.zig.Ast
std.zig.Ast.blockStatements
函数
pub fn blockStatements(tree: Ast, buffer: *[2]Ast.Node.Index, node: Ast.Node.Index) ?[]const Node.Index
参数
std.zig.Ast.builtinCallParams
函数
pub fn builtinCallParams(tree: Ast, buffer: *[2]Ast.Node.Index, node: Ast.Node.Index) ?[]const Node.Index
参数
std.zig.Ast.ByteOffset
类型
std.zig.Ast.callFull
函数
pub fn callFull(tree: Ast, node: Node.Index) full.Call
参数
std.zig.Ast.callOne
函数
pub fn callOne(tree: Ast, buffer: *[1]Node.Index, node: Node.Index) full.Call
参数
std.zig.Ast.containerDecl
函数
pub fn containerDecl(tree: Ast, node: Node.Index) full.ContainerDecl
参数
std.zig.Ast.containerDeclArg
函数
pub fn containerDeclArg(tree: Ast, node: Node.Index) full.ContainerDecl
参数
std.zig.Ast.containerDeclRoot
函数
pub fn containerDeclRoot(tree: Ast) full.ContainerDecl
参数
tree: Ast
std.zig.Ast.containerDeclTwo
函数
pub fn containerDeclTwo(tree: Ast, buffer: *[2]Node.Index, node: Node.Index) full.ContainerDecl
参数
std.zig.Ast.containerField
函数
pub fn containerField(tree: Ast, node: Node.Index) full.ContainerField
参数
std.zig.Ast.containerFieldAlign
函数
pub fn containerFieldAlign(tree: Ast, node: Node.Index) full.ContainerField
参数
std.zig.Ast.containerFieldInit
函数
pub fn containerFieldInit(tree: Ast, node: Node.Index) full.ContainerField
参数
std.zig.Ast.deinit
函数
pub fn deinit(tree: *Ast, gpa: Allocator) void
参数
std.zig.Ast.Error
容器
字段
tag: Tag
is_note: bool = false
token_is_prev: bool = false若 token 指向引发问题的 token 之前的 token,则为 True。
token: TokenIndex
extra: union {
none: void,
expected_tag: Token.Tag,
offset: usize,
} = .{ .none = {} }
std.zig.Ast.Error.Tag
容器
字段
chained_comparison_operators
decl_between_fields
expected_block
expected_block_or_assignment
expected_block_or_expr
expected_block_or_field
expected_container_members
expected_expr
expected_expr_or_assignment
expected_expr_or_var_decl
expected_fn
expected_inlinable
expected_labelable
expected_param_list
expected_prefix_expr
expected_primary_type_expr
expected_pub_item
expected_return_type
expected_semi_or_else
expected_semi_or_lbrace
expected_statement
expected_suffix_op
expected_type_expr
expected_var_decl
expected_var_decl_or_fn
expected_loop_payload
expected_container
extern_fn_body
extra_addrspace_qualifier
extra_align_qualifier
ptr_mod_on_array_child_type
invalid_bit_range
same_line_doc_comment
unattached_doc_comment
test_doc_comment
comptime_doc_comment
varargs_nonfinal
expected_semi_after_decl
expected_semi_after_stmt
expected_comma_after_field
expected_comma_after_arg
expected_comma_after_param
expected_comma_after_initializer
expected_comma_after_switch_prong
expected_comma_after_for_operand
expected_comma_after_capture
expected_initializer
mismatched_binary_op_whitespace
invalid_ampersand_ampersand
c_style_container
expected_var_const
wrong_equal_var_decl
var_const_decl
zig_style_container
previous_field
next_field
expected_tokenexpected_tag 已填充。
invalid_byteoffset 已填充
std.zig.Ast.errorOffset
函数
为错误的列偏移和字节偏移返回额外偏移量, 使错误消息指向 token 之后。
pub fn errorOffset(tree: Ast, parse_error: Error) u32
参数
std.zig.Ast.extraData
函数
pub fn extraData(tree: Ast, index: ExtraIndex, comptime T: type) T
参数
std.zig.Ast.extraDataSlice
函数
pub fn extraDataSlice(tree: Ast, range: Node.SubRange, comptime T: type) []const T
参数
std.zig.Ast.extraDataSliceWithLen
函数
pub fn extraDataSliceWithLen(tree: Ast, start: ExtraIndex, len: u32, comptime T: type) []const T
参数
std.zig.Ast.ExtraIndex
容器
extra_data 中的索引。
字段
_
std.zig.Ast.firstToken
函数
pub fn firstToken(tree: Ast, node: Node.Index) TokenIndex
参数
std.zig.Ast.fnProto
函数
pub fn fnProto(tree: Ast, node: Node.Index) full.FnProto
参数
std.zig.Ast.fnProtoMulti
函数
pub fn fnProtoMulti(tree: Ast, node: Node.Index) full.FnProto
参数
std.zig.Ast.fnProtoOne
函数
pub fn fnProtoOne(tree: Ast, buffer: *[1]Node.Index, node: Node.Index) full.FnProto
参数
std.zig.Ast.fnProtoSimple
函数
pub fn fnProtoSimple(tree: Ast, buffer: *[1]Node.Index, node: Node.Index) full.FnProto
参数
std.zig.Ast.forFull
函数
pub fn forFull(tree: Ast, node: Node.Index) full.For
参数
std.zig.Ast.forSimple
函数
pub fn forSimple(tree: Ast, node: Node.Index) full.For
参数
std.zig.Ast.full
命名空间
完整组装的 AST 节点信息。
std.zig.Ast.full.ArrayInit
容器
字段
ast: Components
std.zig.Ast.full.ArrayInit.Components
容器
字段
std.zig.Ast.full.ArrayType
容器
字段
ast: Components
std.zig.Ast.full.ArrayType.Components
容器
字段
std.zig.Ast.full.Asm
容器
字段
std.zig.Ast.full.Asm.Components
容器
字段
asm_token: TokenIndex
template: Node.Index
items: []const Node.Index
clobbers: Node.OptionalIndex
rparen: TokenIndex
std.zig.Ast.full.AssignDestructure
容器
字段
comptime_token: ?TokenIndex
ast: Components
std.zig.Ast.full.AssignDestructure.Components
容器
字段
std.zig.Ast.full.Call
容器
字段
ast: Components
std.zig.Ast.full.Call.Components
容器
字段
std.zig.Ast.full.ContainerDecl
容器
字段
layout_token: ?TokenIndex
ast: Components
std.zig.Ast.full.ContainerDecl.Components
容器
字段
main_token: TokenIndex
enum_token: ?TokenIndex当 main_token 为 Keyword_union 时填充。
members: []const Node.Index
arg: Node.OptionalIndex
std.zig.Ast.full.ContainerField
容器
字段
comptime_token: ?TokenIndex
ast: Components
std.zig.Ast.full.ContainerField.Components
容器
字段
main_token: TokenIndex
type_expr: Node.OptionalIndex仅在调用 convertToNonTupleLike 后才可为 .none。
align_expr: Node.OptionalIndex
value_expr: Node.OptionalIndex
tuple_like: bool
std.zig.Ast.full.ContainerField.convertToNonTupleLike
函数
pub fn convertToNonTupleLike(cf: *ContainerField, tree: *const Ast) void
参数
cf: *ContainerField
tree: *const Ast
std.zig.Ast.full.ContainerField.firstToken
函数
pub fn firstToken(cf: ContainerField) TokenIndex
参数
cf: ContainerField
std.zig.Ast.full.FnProto
容器
字段
visib_token: ?TokenIndex
extern_export_inline_token: ?TokenIndex
lib_name: ?TokenIndex
name_token: ?TokenIndex
lparen: TokenIndex
ast: Components
std.zig.Ast.full.FnProto.Components
容器
字段
proto_node: Node.Index
fn_token: TokenIndex
return_type: Node.OptionalIndex
params: []const Node.Index
align_expr: Node.OptionalIndex
addrspace_expr: Node.OptionalIndex
section_expr: Node.OptionalIndex
callconv_expr: Node.OptionalIndex
std.zig.Ast.full.FnProto.firstToken
函数
pub fn firstToken(fn_proto: FnProto) TokenIndex
参数
fn_proto: FnProto
std.zig.Ast.full.FnProto.iterate
函数
pub fn iterate(fn_proto: *const FnProto, tree: *const Ast) Iterator
参数
std.zig.Ast.full.FnProto.Iterator
容器
对 anytype 和 ... 不包含在 params 切片中这一事实进行抽象, 因为它们只是简单标识符, 并非子表达式。
字段
std.zig.Ast.full.FnProto.Iterator.next
函数
pub fn next(it: *Iterator) ?Param
参数
it: *Iterator
std.zig.Ast.full.FnProto.Param
容器
字段
first_doc_comment: ?TokenIndex
name_token: ?TokenIndex
comptime_noalias: ?TokenIndex
anytype_ellipsis3: ?TokenIndex
type_expr: ?Node.Index
std.zig.Ast.full.For
容器
字段
ast: Components
inline_token: ?TokenIndex
label_token: ?TokenIndex
payload_token: TokenIndex
else_token: ?TokenIndex仅当 else_expr != .none 时填充。
std.zig.Ast.full.For.Components
容器
字段
for_token: TokenIndex
inputs: []const Node.Index
then_expr: Node.Index
else_expr: Node.OptionalIndex
std.zig.Ast.full.If
容器
字段
payload_token: ?TokenIndex指向 | 之后的第一个 token。它要么是标识符,要么
是 *(后面紧接一个标识符)。
error_token: ?TokenIndex指向 | 后的标识符。
else_token: TokenIndex仅当 else_expr != .none 时填充。
ast: Components
std.zig.Ast.full.If.Components
容器
字段
std.zig.Ast.full.PtrType
容器
字段
size: std.lang.Type.Pointer.Size
allowzero_token: ?TokenIndex
const_token: ?TokenIndex
volatile_token: ?TokenIndex
duplicate_token: ?TokenIndex
ast: Components
std.zig.Ast.full.PtrType.Components
容器
字段
main_token: TokenIndex
align_node: Node.OptionalIndex
addrspace_node: Node.OptionalIndex
sentinel: Node.OptionalIndex
bit_range_start: Node.OptionalIndex
bit_range_end: Node.OptionalIndex
child_type: Node.Index
std.zig.Ast.full.Slice
容器
字段
ast: Components
std.zig.Ast.full.Slice.Components
容器
字段
sliced: Node.Index
lbracket: TokenIndex
start: Node.Index
end: Node.OptionalIndex
sentinel: Node.OptionalIndex
std.zig.Ast.full.StructInit
容器
字段
ast: Components
std.zig.Ast.full.StructInit.Components
容器
字段
std.zig.Ast.full.Switch
容器
字段
ast: Components
label_token: ?TokenIndex
std.zig.Ast.full.Switch.Components
容器
字段
std.zig.Ast.full.SwitchCase
容器
字段
inline_token: ?TokenIndex
payload_token: ?TokenIndex指向 | 之后的第一个 token。它要么是标识符,要么
是 *(后面紧接一个标识符)。
ast: Components
std.zig.Ast.full.SwitchCase.Components
容器
字段
std.zig.Ast.full.VarDecl
容器
字段
visib_token: ?TokenIndex
extern_export_token: ?TokenIndex
lib_name: ?TokenIndex
threadlocal_token: ?TokenIndex
comptime_token: ?TokenIndex
ast: Components
std.zig.Ast.full.VarDecl.Components
容器
字段
mut_token: TokenIndex
type_node: Node.OptionalIndex
align_node: Node.OptionalIndex
addrspace_node: Node.OptionalIndex
section_node: Node.OptionalIndex
init_node: Node.OptionalIndex
std.zig.Ast.full.VarDecl.firstToken
函数
pub fn firstToken(var_decl: VarDecl) TokenIndex
参数
var_decl: VarDecl
std.zig.Ast.full.While
容器
字段
ast: Components
inline_token: ?TokenIndex
label_token: ?TokenIndex
payload_token: ?TokenIndex
error_token: ?TokenIndex
else_token: TokenIndex仅当 else_expr != none 时填充。
std.zig.Ast.full.While.Components
容器
字段
while_token: TokenIndex
cond_expr: Node.Index
cont_expr: Node.OptionalIndex
then_expr: Node.Index
else_expr: Node.OptionalIndex
std.zig.Ast.fullArrayInit
函数
pub fn fullArrayInit(tree: Ast, buffer: *[2]Node.Index, node: Node.Index) ?full.ArrayInit
参数
std.zig.Ast.fullArrayType
函数
pub fn fullArrayType(tree: Ast, node: Node.Index) ?full.ArrayType
参数
std.zig.Ast.fullAsm
函数
pub fn fullAsm(tree: Ast, node: Node.Index) ?full.Asm
参数
std.zig.Ast.fullAsmComponents
函数
fn fullAsmComponents(tree: Ast, info: full.Asm.Components) full.Asm
参数
tree: Ast
info: full.Asm.Components
std.zig.Ast.fullAssignDestructureComponents
函数
fn fullAssignDestructureComponents(tree: Ast, info: full.AssignDestructure.Components) full.AssignDestructure
参数
tree: Ast
info: full.AssignDestructure.Components
std.zig.Ast.fullCall
函数
pub fn fullCall(tree: Ast, buffer: *[1]Ast.Node.Index, node: Node.Index) ?full.Call
参数
std.zig.Ast.fullContainerDecl
函数
pub fn fullContainerDecl(tree: Ast, buffer: *[2]Ast.Node.Index, node: Node.Index) ?full.ContainerDecl
参数
std.zig.Ast.fullContainerDeclComponents
函数
fn fullContainerDeclComponents(tree: Ast, info: full.ContainerDecl.Components) full.ContainerDecl
参数
tree: Ast
info: full.ContainerDecl.Components
std.zig.Ast.fullContainerField
函数
pub fn fullContainerField(tree: Ast, node: Node.Index) ?full.ContainerField
参数
std.zig.Ast.fullContainerFieldComponents
函数
fn fullContainerFieldComponents(tree: Ast, info: full.ContainerField.Components) full.ContainerField
参数
tree: Ast
info: full.ContainerField.Components
std.zig.Ast.fullFnProto
函数
pub fn fullFnProto(tree: Ast, buffer: *[1]Ast.Node.Index, node: Node.Index) ?full.FnProto
参数
std.zig.Ast.fullFnProtoComponents
函数
fn fullFnProtoComponents(tree: Ast, info: full.FnProto.Components) full.FnProto
参数
tree: Ast
info: full.FnProto.Components
std.zig.Ast.fullFor
函数
pub fn fullFor(tree: Ast, node: Node.Index) ?full.For
参数
std.zig.Ast.fullForComponents
函数
fn fullForComponents(tree: Ast, info: full.For.Components) full.For
参数
tree: Ast
info: full.For.Components
std.zig.Ast.fullIf
函数
pub fn fullIf(tree: Ast, node: Node.Index) ?full.If
参数
std.zig.Ast.fullIfComponents
函数
fn fullIfComponents(tree: Ast, info: full.If.Components) full.If
参数
tree: Ast
info: full.If.Components
std.zig.Ast.fullPtrType
函数
pub fn fullPtrType(tree: Ast, node: Node.Index) ?full.PtrType
参数
std.zig.Ast.fullPtrTypeComponents
函数
fn fullPtrTypeComponents(tree: Ast, info: full.PtrType.Components) full.PtrType
参数
tree: Ast
info: full.PtrType.Components
std.zig.Ast.fullSlice
函数
pub fn fullSlice(tree: Ast, node: Node.Index) ?full.Slice
参数
std.zig.Ast.fullStructInit
函数
pub fn fullStructInit(tree: Ast, buffer: *[2]Ast.Node.Index, node: Node.Index) ?full.StructInit
参数
std.zig.Ast.fullSwitch
函数
pub fn fullSwitch(tree: Ast, node: Node.Index) ?full.Switch
参数
std.zig.Ast.fullSwitchCase
函数
pub fn fullSwitchCase(tree: Ast, node: Node.Index) ?full.SwitchCase
参数
std.zig.Ast.fullSwitchCaseComponents
函数
fn fullSwitchCaseComponents(tree: Ast, info: full.SwitchCase.Components, node: Node.Index) full.SwitchCase
参数
std.zig.Ast.fullSwitchComponents
函数
fn fullSwitchComponents(tree: Ast, info: full.Switch.Components) full.Switch
参数
tree: Ast
info: full.Switch.Components
std.zig.Ast.fullVarDecl
函数
pub fn fullVarDecl(tree: Ast, node: Node.Index) ?full.VarDecl
参数
std.zig.Ast.fullVarDeclComponents
函数
fn fullVarDeclComponents(tree: Ast, info: full.VarDecl.Components) full.VarDecl
参数
tree: Ast
info: full.VarDecl.Components
std.zig.Ast.fullWhile
函数
pub fn fullWhile(tree: Ast, node: Node.Index) ?full.While
参数
std.zig.Ast.fullWhileComponents
函数
fn fullWhileComponents(tree: Ast, info: full.While.Components) full.While
参数
tree: Ast
info: full.While.Components
std.zig.Ast.getNodeSource
函数
pub fn getNodeSource(tree: Ast, node: Node.Index) []const u8
参数
std.zig.Ast.globalVarDecl
函数
pub fn globalVarDecl(tree: Ast, node: Node.Index) full.VarDecl
参数
std.zig.Ast.ifFull
函数
pub fn ifFull(tree: Ast, node: Node.Index) full.If
参数
std.zig.Ast.ifSimple
函数
pub fn ifSimple(tree: Ast, node: Node.Index) full.If
参数
std.zig.Ast.isTokenPrecededByTags
函数
pub fn isTokenPrecededByTags( tree: *const Ast, ti: TokenIndex, expected_token_tags: []const Token.Tag, ) bool
参数
std.zig.Ast.lastToken
函数
pub fn lastToken(tree: Ast, node: Node.Index) TokenIndex
参数
std.zig.Ast.loadOptionalNodesIntoBuffer
函数
fn loadOptionalNodesIntoBuffer(comptime size: usize, buffer: *[size]Node.Index, items: [size]Node.OptionalIndex) []Node.Index
参数
std.zig.Ast.localVarDecl
函数
pub fn localVarDecl(tree: Ast, node: Node.Index) full.VarDecl
参数
std.zig.Ast.Location
容器
字段
line: usize
column: usize
line_start: usize
line_end: usize
std.zig.Ast.mem
别名
别名目标 std.mem
std.zig.Ast.Mode
容器
字段
zig
zon
std.zig.Ast.Node
容器
字段
std.zig.Ast.Node.ArrayTypeSentinel
容器
字段
std.zig.Ast.Node.Asm
容器
字段
items_start: ExtraIndex
items_end: ExtraIndex
clobbers: OptionalIndex
rparen: TokenIndex用于使 lastToken() 正常工作。
std.zig.Ast.Node.ContainerField
容器
字段
std.zig.Ast.Node.Data
容器
字段
node: Index
opt_node: OptionalIndex
token: TokenIndex
node_and_node: struct { Index, Index }
opt_node_and_opt_node: struct { OptionalIndex, OptionalIndex }
node_and_opt_node: struct { Index, OptionalIndex }
opt_node_and_node: struct { OptionalIndex, Index }
node_and_extra: struct { Index, ExtraIndex }
extra_and_node: struct { ExtraIndex, Index }
extra_and_opt_node: struct { ExtraIndex, OptionalIndex }
node_and_token: struct { Index, TokenIndex }
token_and_node: struct { TokenIndex, Index }
token_and_token: struct { TokenIndex, TokenIndex }
opt_node_and_token: struct { OptionalIndex, TokenIndex }
opt_token_and_node: struct { OptionalTokenIndex, Index }
opt_token_and_opt_node: struct { OptionalTokenIndex, OptionalIndex }
opt_token_and_opt_token: struct { OptionalTokenIndex, OptionalTokenIndex }
@"for": struct { ExtraIndex, For }
extra_range: SubRange
std.zig.Ast.Node.FnProto
容器
字段
params_start: ExtraIndex
params_end: ExtraIndex
align_expr: OptionalIndex存在 align(A) 时填充。
addrspace_expr: OptionalIndex存在 addrspace(A) 时填充。
section_expr: OptionalIndex存在 linksection(A) 时填充。
callconv_expr: OptionalIndex存在 callconv(A) 时填充。
std.zig.Ast.Node.FnProtoOne
容器
字段
param: OptionalIndex恰有 1 个参数时填充,否则参数数为 0。
align_expr: OptionalIndex存在 align(A) 时填充。
addrspace_expr: OptionalIndex存在 addrspace(A) 时填充。
section_expr: OptionalIndex存在 linksection(A) 时填充。
callconv_expr: OptionalIndex存在 callconv(A) 时填充。
std.zig.Ast.Node.For
容器
字段
inputs: u31
has_else: bool
std.zig.Ast.Node.GlobalVarDecl
容器
字段
type_node: OptionalIndex存在显式类型标注时填充。
align_node: OptionalIndex存在 align(A) 时填充。
addrspace_node: OptionalIndex存在 addrspace(A) 时填充。
section_node: OptionalIndex存在 linksection(A) 时填充。
std.zig.Ast.Node.If
容器
字段
std.zig.Ast.Node.Index
容器
nodes 中的索引。
字段
root = 0
_
std.zig.Ast.Node.Index.toOffset
函数
pub fn toOffset(base: Index, destination: Index) Offset
参数
std.zig.Ast.Node.Index.toOptional
函数
pub fn toOptional(i: Index) OptionalIndex
参数
i: Index
std.zig.Ast.Node.LocalVarDecl
容器
字段
std.zig.Ast.Node.Offset
容器
相对节点索引。
字段
zero = 0
_
std.zig.Ast.Node.Offset.toAbsolute
函数
pub fn toAbsolute(offset: Offset, base: Index) Index
参数
std.zig.Ast.Node.Offset.toOptional
函数
pub fn toOptional(o: Offset) OptionalOffset
参数
o: Offset
std.zig.Ast.Node.OptionalIndex
容器
nodes 中的索引,或 null。
字段
std.zig.Ast.Node.OptionalIndex.fromOptional
函数
pub fn fromOptional(oi: ?Index) OptionalIndex
参数
oi: ?Index
std.zig.Ast.Node.OptionalIndex.unwrap
函数
pub fn unwrap(oi: OptionalIndex) ?Index
参数
oi: OptionalIndex
std.zig.Ast.Node.OptionalOffset
容器
相对节点索引,或 null。
字段
std.zig.Ast.Node.OptionalOffset.unwrap
函数
pub fn unwrap(oo: OptionalOffset) ?Offset
参数
oo: OptionalOffset
std.zig.Ast.Node.PtrType
容器
字段
std.zig.Ast.Node.PtrTypeBitRange
容器
字段
sentinel: OptionalIndex
align_node: Index
addrspace_node: OptionalIndex
bit_range_start: Index
bit_range_end: Index
std.zig.Ast.Node.Slice
容器
字段
std.zig.Ast.Node.SliceSentinel
容器
字段
std.zig.Ast.Node.SubRange
容器
字段
std.zig.Ast.Node.Tag
容器
FooComma/FooSemicolon 变体用于简化 Ast.lastToken() 的实现
字段
root根节点,保证位于 Node.Index.root。
data 字段的含义取决于文件是 .zig 还是
.zon。
main_token 字段是源文件的首个词法标记。
test_decltest {}、
test "name" {}、
test identifier {}。
data 字段为 .opt_token_and_node:
- 指向测试名称词元的
OptionalTokenIndex,如果存在;必须是字符串字面量或标识符。 - 指向块的
Node.Index。
main_token 字段是 test 词元。
global_var_decldata 字段为 .extra_and_opt_node:
- 指向
GlobalVarDecl的ExtraIndex。 - 指向初始化表达式的
Node.OptionalIndex。
main_token 字段是 var 或 const 词元。
除非属于 assign_destructure 节点,或发生解析错误,
否则初始化表达式不能为 .none。
local_var_declvar a: b align(c) = d。
const main_token: type_node align(align_node) = init_expr。
data 字段为 .extra_and_opt_node:
- 指向
LocalVarDecl的ExtraIndex。 - 指向初始化表达式的
Node.OptionalIndex。
main_token 字段是 var 或 const 词元。
除非属于 assign_destructure 节点,或发生解析错误,
否则初始化表达式不能为 .none。
simple_var_declvar a: b = c。
const name_token: type_expr = init_expr。
可以是局部或全局声明。
data 字段为 .opt_node_and_opt_node:
- 指向类型表达式的
Node.OptionalIndex,如果存在。 - 指向初始化表达式的
Node.OptionalIndex。
main_token 字段是 var 或 const 词元。
除非属于 assign_destructure 节点,或发生解析错误,
否则初始化表达式不能为 .none。
aligned_var_declvar a align(b) = c。
const name_token align(align_expr) = init_expr。
可以是局部或全局声明。
data 字段为 .node_and_opt_node:
- 指向对齐表达式的
Node.Index。 - 指向初始化表达式的
Node.OptionalIndex。
main_token 字段是 var 或 const 词元。
除非属于 assign_destructure 节点,或发生解析错误,
否则初始化表达式不能为 .none。
@"errdefer"errdefer expr,
data 字段是指向延迟执行表达式的 .node。
main_token 字段是 errdefer token。
@"defer"defer expr。
data 字段为指向延迟表达式的 .node。
main_token 字段为 defer 标记。
@"catch"lhs catch rhs、
lhs catch |err| rhs。
main_token 字段为 catch 标记。
通过查看 catch 标记之后的下一个标记,
确定错误载荷。
field_accesslhs.a。
data 字段为 .node_and_token:
- 一个指向字段访问左侧表达式的
Node.Index。 - 一个指向字段名标识符的
TokenIndex。
main_token 字段是 . 词法标记。
unwrap_optional
equal_equallhs == rhs。main_token 字段为 == 词法标记。
bang_equallhs != rhs。main_token 字段是 != token。
less_thanlhs < rhs。main_token 字段为 < 词法标记。
greater_thanlhs > rhs。main_token 字段是 > token。
less_or_equallhs <= rhs。main_token 字段为 <= 标记。
greater_or_equallhs >= rhs。main_token 字段为 >= 词法标记。
assign_mullhs *= rhs。main_token 字段是 *= token。
assign_divlhs /= rhs。main_token 字段为 /= 标记。
assign_modlhs %= rhs。main_token 字段为 %= 词法标记。
assign_addlhs += rhs。main_token 字段是 += token。
assign_sublhs -= rhs。main_token 字段为 -= 标记。
assign_shllhs <<= rhs。main_token 字段为 <<= 标记。
assign_shl_satlhs <<|= rhs。main_token 字段为 <<|= 标记。
assign_shrlhs >>= rhs。main_token 字段为 >>= 词法标记。
assign_bit_andlhs &= rhs。main_token 字段为 &= 词法标记。
assign_bit_xorlhs ^= rhs。main_token 字段是 ^= token。
assign_bit_orlhs |= rhs。main_token 字段为 |= 标记。
assign_mul_wraplhs *%= rhs。main_token 字段是 *%= token。
assign_add_wraplhs +%= rhs。main_token 字段为 +%= 标记。
assign_sub_wraplhs -%= rhs。main_token 字段为 -%= 词法标记。
assign_mul_satlhs *|= rhs。main_token 字段是 *%= token。
assign_add_satlhs +|= rhs。main_token 字段为 +|= 标记。
assign_sub_satlhs -|= rhs。main_token 字段为 -|= 词法标记。
assignlhs = rhs。main_token 字段为 = 标记。
assign_destructurea, b, ... = rhs。
data 字段为 .extra_and_node:
- 一个
ExtraIndex,详见下文。 - 指向初始化表达式的
Node.Index。
main_token 字段是 = 词法单元。
ExtraIndex 存储以下数据:
elem_count: u32,
variables: [elem_count]Node.Index,
variables 中的每个节点具有以下标签之一:
global_var_decllocal_var_declsimple_var_declaligned_var_decl- 任意表达式节点
前 4 个标签对应 var 或 const 左侧节点,注意其初始化表达式始终为 .none。
表达式节点对应普通赋值左侧,必须按左值求值。前方可能有 comptime 词法单元,但不会创建对应的 comptime 节点,因此必须手动检测。
merge_error_setslhs || rhs。main_token 字段为 || 词法标记。
mullhs * rhs。main_token 字段为 * 词法标记。
divlhs / rhs。main_token 字段是 / token。
modlhs % rhs。main_token 字段为 % 标记。
mul_wraplhs *% rhs。main_token 字段是 *% token。
mul_satlhs *| rhs。main_token 字段为 *| 标记。
addlhs + rhs。main_token 字段为 + 词法标记。
sublhs - rhs。main_token 字段是 - token。
array_catlhs ++ rhs。main_token 字段为 ++ 词法标记。
add_wraplhs +% rhs。main_token 字段是 +% token。
sub_wraplhs -% rhs。main_token 字段为 -% 标记。
add_satlhs +| rhs。main_token 字段为 +| 词法标记。
sub_satlhs -| rhs。main_token 字段是 -| token。
shllhs << rhs。main_token 字段为 << 标记。
shl_satlhs <<| rhs。main_token 字段是 <<| token。
shrlhs >> rhs。main_token 字段为 >> 词法标记。
bit_andlhs & rhs。main_token 字段为 & 标记。
bit_xorlhs ^ rhs。main_token 字段为 ^ 词法标记。
bit_orlhs | rhs。main_token 字段是 | token。
@"orelse"lhs orelse rhs。main_token 字段是 orelse token。
bool_andlhs and rhs。main_token 字段为 and 标记。
bool_orlhs or rhs。main_token 字段是 or token。
bool_not!expr。main_token 字段为 ! 标记。
negation-expr。main_token 字段为 - 词法标记。
bit_not~expr。main_token 字段是 ~ token。
negation_wrap-%expr。main_token 字段是 -% token。
address_of&expr。main_token 字段为 & 标记。
@"try"try expr。main_token 字段是 try token。
optional_type?expr。main_token 字段为 ? 词法标记。
array_type[lhs]rhs。main_token 字段是 [ token。
array_type_sentinel[lhs:a]b。
data 字段为 .node_and_extra:
- 一个指向长度表达式的
Node.Index。 - 一个指向
ArrayTypeSentinel的ExtraIndex。
main_token 字段是 [ 词法标记。
ptr_type_aligned[*]align(lhs) rhs、
*align(lhs) rhs、
[]rhs。
data 字段为 .opt_node_and_node:
- 指向对齐表达式的
Node.OptionalIndex,如果存在。 - 指向元素类型表达式的
Node.Index。
单项指针的 main_token 是星号;
切片、多项指针或 C 指针的则是左方括号。
ptr_type_sentinel[*:lhs]rhs、
*rhs、
[:lhs]rhs。
data 字段为 .opt_node_and_node:
- 一个
Node.OptionalIndex,指向哨兵表达式,若存在。 - 一个
Node.Index,指向元素类型表达式。
main_token 对单元素指针为星号;对切片、多元素指针或 C 指针为左方括号。
ptr_typedata 字段为 .extra_and_node:
- 指向
PtrType的ExtraIndex。 - 指向元素类型表达式的
Node.Index。
单项指针的 main_token 是星号;
切片、多项指针或 C 指针的则是左方括号。
ptr_type_bit_rangedata 字段为 .extra_and_node:
- 指向
PtrTypeBitRange的ExtraIndex。 - 指向元素类型表达式的
Node.Index。
单项指针的 main_token 是星号;
切片、多项指针或 C 指针的则是左方括号。
slice_openlhs[rhs..]
main_token 字段为 [ 标记。
slicesliced[start..end]。
data 字段采用 .node_and_extra:
- 指向被切片表达式的
Node.Index。 - 指向
Slice的ExtraIndex。
main_token 字段是 [ 标记。
slice_sentinelsliced[start..end :sentinel]、
sliced[start.. :sentinel]。
data 字段采用 .node_and_extra:
- 指向被切片表达式的
Node.Index。 - 指向
SliceSentinel的ExtraIndex。
main_token 字段是 [ 标记。
derefexpr.*。
data 字段是指向 expr 的 .node。
main_token 字段是 * 词元。
array_accesslhs[rhs]。
main_token 字段为 [ 标记。
array_init_onelhs{rhs}。
main_token 字段为 { 词法标记。
array_init_one_comma与 array_init_one 相同,但已知最终右花括号前
存在末尾逗号。
array_init_dot_two.{a}、
.{a, b}。
data 字段为 .opt_node_and_opt_node:
- 一个指向首个元素的
Node.OptionalIndex。绝不会为.none - 一个指向第二个元素的
Node.OptionalIndex,若存在。
main_token 字段是 { 词法标记。
array_init_dot_two_comma与 array_init_dot_two 相同,但已知最后一个右花括号
之前存在尾随逗号。
array_init_dot
array_init_dot_comma与 array_init_dot 相同,
但已知最后的右花括号之前有尾随逗号。
array_inita{b, c}。
data 字段为 .node_and_extra:
- 一个指向类型表达式的
Node.Index。 - 一个指向
SubRange的ExtraIndex,其中为每个元素 存储一个Node.Index。
main_token 字段是 { 词法标记。
array_init_comma与 array_init 相同,
但已知最后的右花括号之前有尾随逗号。
struct_init_onea{.x = b}、a{}。
data 字段采用 .node_and_opt_node:
- 指向类型表达式的
Node.Index。 - 指向第一个字段初始化的
Node.OptionalIndex(若存在)。
main_token 字段是 { 标记。
字段名通过查看字段初始化之前的 标记确定。
struct_init_one_comma与 struct_init_one 相同,但已知最终右花括号前
存在末尾逗号。
struct_init_dot_two.{.x = a, .y = b}。
data 字段为 .opt_node_and_opt_node:
- 一个
Node.OptionalIndex,指向第一个字段初始化,绝不会为.none。 - 一个
Node.OptionalIndex,指向第二个字段初始化,若存在。
main_token 字段是“{”词法单元。
通过查看字段初始化之前的词法单元,确定字段名称。
struct_init_dot_two_comma与 struct_init_dot_two 相同,但已知最终右花括号前
存在末尾逗号。
struct_init_dot.{.x = a, .y = b, .z = c}。
data 字段为 .extra_range,为每个字段初始化
存储一个 Node.Index。
main_token 字段是 { 词法标记。
通过查看字段初始化之前的词法标记 确定字段名。
struct_init_dot_comma与 struct_init_dot 相同,
但已知最后的右花括号之前有尾随逗号。
struct_inita{.x = b, .y = c}。
data 字段采用 .node_and_extra:
- 指向类型表达式的
Node.Index。 - 指向
SubRange的ExtraIndex,其中为 每个字段初始化存储一个Node.Index。
main_token 字段是 { 标记。
字段名通过查看字段初始化之前的 标记确定。
struct_init_comma与 struct_init 相同,
但已知最后的右花括号之前有尾随逗号。
call_onea(b)、a()。
data 字段采用 .node_and_opt_node:
- 指向函数表达式的
Node.Index。 - 指向第一个参数的
Node.OptionalIndex(若存在)。
main_token 字段是 ( 标记。
call_one_comma与 call_one 相同,
但已知最后的右圆括号之前有尾随逗号。
calla(b, c, d)。
data 字段采用 .node_and_extra:
- 指向函数表达式的
Node.Index。 - 指向
SubRange的ExtraIndex,其中为 每个参数存储一个Node.Index。
main_token 字段是 ( 标记。
call_comma与 call 相同,
但已知最后的右圆括号之前有尾随逗号。
@"switch"switch(a) {}。
data 字段采用 .node_and_extra:
- 指向 switch 操作数的
Node.Index。 - 指向
SubRange的ExtraIndex,其中为 每个 switch 分支存储一个Node.Index。
The main_token field 是前置标签的标识符(若存在),否则为 switch。
switch_comma与 switch 相同,但已知最终右花括号前有逗号。
switch_case_onea => b、
else => b。
data 字段为 .opt_node_and_node:
- 一个
Node.OptionalIndex,其中.none表示else。 - 一个指向目标表达式的
Node.Index。
main_token 字段是 => 词法标记。
switch_case_inline_one与 switch_case_one 相同,但 case 为 inline。
switch_casea, b, c => d。
data 字段为 .extra_and_node:
- 一个指向
SubRange的ExtraIndex,其中为每个 switch 项 存储一个Node.Index。 - 一个指向目标表达式的
Node.Index。
main_token 字段是 => 词法标记。
switch_case_inline与 switch_case 相同,但分支为内联分支。
switch_rangelhs...rhs。
main_token 字段为 ... 词法标记。
while_simplewhile (a) b,
while (a) |x| b.
while_contwhile (a) : (b) c,
while (a) |x| : (b) c.
@"while"while (a) : (b) c else d、
while (a) |x| : (b) c else d、
while (a) |x| : (b) c else |y| d。
可省略继续表达式部分 : (b)。
for_simplefor (a) b.
@"for"for (lhs[0..inputs]) lhs[inputs + 1] else lhs[inputs + 2]。For[rhs]。
for_rangelhs..rhs, lhs...
if_simpleif (a) b.
if (b) |x| b.
@"if"if (a) b else c.
if (a) |x| b else c.
if (a) |x| b else |y| d.
@"suspend"suspend expr。
data 字段是指向 expr 的 .node。
main_token 字段为 suspend 词法标记。
@"resume"resume expr。
data 字段是指向 expr 的 .node。
main_token 字段为 resume 词法标记。
@"continue"continue :label expr、
continue expr、
continue :label、
continue。
data 字段为 .opt_token_and_opt_node:
- 一个
OptionalTokenIndex,指向标签标识符,若存在。 - 一个
Node.OptionalIndex,指向目标表达式,若存在。
main_token 字段是 continue 词法单元。
@"break"break :label expr、
break expr、
break :label、
break。
data 字段为 .opt_token_and_opt_node:
- 指向标签标识符的
OptionalTokenIndex,如果存在。 - 指向目标表达式的
Node.OptionalIndex,如果存在。
main_token 字段是 break 词元。
@"return"return expr、return。
若有返回值,data 字段是指向该返回值的 .opt_node。
main_token 字段是 return token。
fn_proto_simplefn (a: type_expr) return_type。
data 字段为 .opt_node_and_opt_node:
- 指向首个参数类型表达式的
Node.OptionalIndex,如果存在。 - 指向返回类型表达式的
Node.OptionalIndex。除非 发生解析错误,否则不能为.none。
main_token 字段是 fn 词元。
AST 树中省略 anytype 和 ... 参数。
extern 函数声明使用此标签。
fn_proto_multifn (a: b, c: d) return_type。
data 字段为 .extra_and_opt_node:
- 一个
ExtraIndex,指向SubRange,其中为每个参数类型表达式存储一个Node.Index。 - 一个
Node.OptionalIndex,指向返回类型表达式。除非发生解析错误,否则不能为.none。
main_token 字段是 fn 词法单元。
anytype 和 ... 参数不包含在 AST 树中。
外部函数声明使用此标签。
fn_proto_onefn (a: b) addrspace(e) linksection(f) callconv(g) return_type。
零个或一个参数。
data 字段为 .extra_and_opt_node:
- 一个
Node.ExtraIndex,指向FnProtoOne。 - 一个
Node.OptionalIndex,指向返回类型表达式。除非发生解析错误,否则不能为.none。
main_token 字段是 fn 词法单元。
anytype 和 ... 参数不包含在 AST 树中。
外部函数声明使用此标签。
fn_protofn (a: b, c: d) addrspace(e) linksection(f) callconv(g) return_type。
data 字段为 .extra_and_opt_node:
Node.ExtraIndex,指向FnProto。- 指向返回类型表达式的
Node.OptionalIndex;除非 发生解析错误,否则不得为.none。
main_token 字段为 fn 标记。
AST 树中省略 anytype 和 ... 参数。
外部函数声明使用此标签。
fn_declextern 函数声明使用 fn_proto 标签,而非此标签。
data 字段为 .node_and_node:
- 指向
fn_proto_*的Node.Index。 - 指向函数体块的
Node.Index。
main_token 字段是 fn 词元。
anyframe_typeanyframe->return_type。
data 字段为 .token_and_node:
- 指向
->词元的TokenIndex。 - 指向函数帧返回类型表达式的
Node.Index。
main_token 字段是 anyframe 词元。
anyframe_literaldata 字段未使用。
char_literaldata 字段未使用。
number_literaldata 字段未使用。
unreachable_literaldata 字段未使用。
identifierdata 字段未使用。
大多数标识符没有显式的 AST 节点,但对于 可能属于多种不同 AST 节点类型的表达式, 会为其创建标识符 AST 节点。
enum_literal.foo。
data 字段未使用。
main_token 字段为标识符。
string_literaldata 字段未使用。
main_token 字段为字符串字面量标记。
multiline_string_literaldata 字段为 .token_and_token:
- 指向首个
.multiline_string_literal_line词元的TokenIndex。 - 指向最后一个
.multiline_string_literal_line词元的TokenIndex。
main_token 字段是首个词元索引,与 data 冗余。
grouped_expression
builtin_call_two@a(b, c)。
data 字段为 .opt_node_and_opt_node:
- 一个指向第一个参数的
Node.OptionalIndex,若存在。 - 一个指向第二个参数的
Node.OptionalIndex,若存在。
main_token 字段是内置函数词法标记。
builtin_call_two_comma与 builtin_call_two 相同,但已知最后一个右圆括号
之前存在尾随逗号。
builtin_call
builtin_call_comma与 builtin_call 相同,但已知最后一个右圆括号
之前存在尾随逗号。
error_set_declerror{a, b}。
data 字段为 .token_and_token:
- 一个指向
{词法标记的TokenIndex。 - 一个指向
}词法标记的TokenIndex。
main_token 字段为 error。
container_declstruct {}、union {}、opaque {}、enum {}。
data 字段采用 .extra_range,为
每个容器成员存储一个 Node.Index。
main_token 字段是 struct、union、opaque 或 enum 标记。
container_decl_trailing与 container_decl 相同,但已知最后一个右花括号
之前存在尾随逗号。
container_decl_twostruct {lhs, rhs}、union {lhs, rhs}、opaque {lhs, rhs}、enum {lhs, rhs}。
data 字段为 .opt_node_and_opt_node:
- 一个
Node.OptionalIndex,指向第一个容器成员,若存在。 - 一个
Node.OptionalIndex,指向第二个容器成员,若存在。
main_token 字段是 struct、union、opaque 或 enum 词法单元。
container_decl_two_trailing与 container_decl_two 相同,但已知最终右花括号前
存在末尾逗号。
container_decl_argstruct(arg)、union(arg)、enum(arg)。
data 字段采用 .node_and_extra:
- 指向 arg 的
Node.Index。 - 指向
SubRange的ExtraIndex,其中为 每个容器成员存储一个Node.Index。
main_token 字段是 struct、union 或 enum 标记。
container_decl_arg_trailing与 container_decl_arg 相同,
但已知最后的右花括号之前有尾随逗号。
tagged_unionunion(enum) {}。
data 字段为 .extra_range,为每个容器成员
存储一个 Node.Index。
main_token 字段是 union 词法标记。
显式提供枚举的带标签联合体则由
container_decl_arg 表示。
tagged_union_trailing与 tagged_union 相同,但已知最终右花括号前
存在末尾逗号。
tagged_union_twounion(enum) {lhs, rhs}。
data 字段为 .opt_node_and_opt_node:
- 指向第一个容器成员的
Node.OptionalIndex,如果存在。 - 指向第二个容器成员的
Node.OptionalIndex,如果存在。
main_token 字段是 union 词元。
显式提供枚举的带标签联合体则使用
container_decl_arg 表示。
tagged_union_two_trailing与 tagged_union_two 相同,但已知最终右花括号前
存在末尾逗号。
tagged_union_enum_tagunion(enum(arg)) {}。
data 字段为 .node_and_extra:
- 指向 arg 的
Node.Index。 - 指向
SubRange的ExtraIndex,其中为每个 容器成员存储一个Node.Index。
main_token 字段是 union 词元。
tagged_union_enum_tag_trailing与 tagged_union_enum_tag 相同,但已知最后一个右花括号
之前存在尾随逗号。
container_field_inita: lhs = rhs,、
a: lhs,。
data 字段采用 .node_and_opt_node:
- 指向字段类型表达式的
Node.Index。 - 指向默认值表达式的
Node.OptionalIndex(若存在)。
main_token 字段是字段名标识符。
lastToken() 不包含可能存在的尾随逗号。
container_field_aligna: lhs align(rhs),。
data 字段为 .node_and_node:
- 指向字段类型表达式的
Node.Index。 - 指向对齐表达式的
Node.Index。
main_token 字段是字段名标识符。
lastToken() 不包含可能存在的末尾逗号。
container_fielda: lhs align(c) = d,。
data 字段为 .node_and_extra:
- 一个
Node.Index,指向字段类型表达式。 - 一个
ExtraIndex,指向ContainerField。
main_token 字段为字段名标识符。
lastToken() 不包含可能出现的尾随逗号。
@"comptime"comptime expr。
data 字段是指向 expr 的 .node。
main_token 字段是 comptime token。
@"nosuspend"nosuspend expr。
data 字段是指向 expr 的 .node。
main_token 字段是 nosuspend 词元。
block_two{lhs rhs}。
data 字段采用 .opt_node_and_opt_node:
- 指向第一条语句的
Node.OptionalIndex(若存在)。 - 指向第二条语句的
Node.OptionalIndex(若存在)。
main_token 字段是 { 标记。
block_two_semicolon与 block_two 相同,
但已知最后的右花括号之前有尾随逗号。
block
block_semicolon与 block 相同,但已知最终右花括号前有逗号。
asm_simpleasm(a)。
main_token 字段是 asm token。
@"asm"asm(a, b)。
data 字段采用 .node_and_extra:
- 指向 a 的
Node.Index。 - 指向
Asm的ExtraIndex。
main_token 字段是 asm 标记。
asm_output[a] "b" (c)。
[a] "b" (-> lhs)。
data 字段为 .opt_node_and_token:
- 一个指向 lhs 的
Node.OptionalIndex,若存在。 - 一个指向
)词法标记的TokenIndex。
main_token 字段为 a。
asm_input[a] "b" (lhs)。
data 字段为 .node_and_token:
- 一个指向 lhs 的
Node.Index。 - 一个指向
)词法标记的TokenIndex。
main_token 字段为 a。
error_valueerror.a。
data 字段未使用。
main_token 字段为 error 词法标记。
error_unionlhs!rhs。
main_token 字段为 ! 标记。
std.zig.Ast.Node.Tag.isContainerField
函数
pub fn isContainerField(tag: Tag) bool
参数
tag: Tag
std.zig.Ast.Node.While
容器
字段
std.zig.Ast.Node.WhileCont
容器
字段
std.zig.Ast.nodeData
函数
pub fn nodeData(tree: *const Ast, node: Node.Index) Node.Data
参数
std.zig.Ast.NodeList
类型
std.zig.Ast.nodeMainToken
函数
pub fn nodeMainToken(tree: *const Ast, node: Node.Index) TokenIndex
参数
std.zig.Ast.nodeTag
函数
pub fn nodeTag(tree: *const Ast, node: Node.Index) Node.Tag
参数
std.zig.Ast.nodeToSpan
函数
pub fn nodeToSpan(tree: *const Ast, node: Ast.Node.Index) Span
参数
std.zig.Ast.OptionalTokenIndex
容器
tokens 的索引或 null。
字段
std.zig.Ast.OptionalTokenIndex.fromOptional
函数
pub fn fromOptional(oti: ?TokenIndex) OptionalTokenIndex
参数
oti: ?TokenIndex
std.zig.Ast.OptionalTokenIndex.fromToken
函数
pub fn fromToken(ti: TokenIndex) OptionalTokenIndex
参数
ti: TokenIndex
std.zig.Ast.OptionalTokenIndex.unwrap
函数
pub fn unwrap(oti: OptionalTokenIndex) ?TokenIndex
参数
oti: OptionalTokenIndex
std.zig.Ast.OptionalTokenOffset
容器
相对词法标记索引或 null。
字段
std.zig.Ast.OptionalTokenOffset.unwrap
函数
pub fn unwrap(oto: OptionalTokenOffset) ?TokenOffset
参数
oto: OptionalTokenOffset
std.zig.Ast.parse
函数
当不再引用任何词法标记或节点时, 应使用 tree.deinit() 释放结果。
pub fn parse(gpa: Allocator, source: [:0]const u8, options: ParseOptions) Allocator.Error!Ast
参数
错误
- OutOfMemory
std.zig.Ast.Parse
别名
别名目标 std.zig.Parse
std.zig.Ast.ParseOptions
容器
字段
recover: bool = true
mode: Mode = .zig
std.zig.Ast.parseTokens
函数
pub fn parseTokens( gpa: Allocator, source: [:0]const u8, tokens: Ast.TokenList.Slice, options: ParseOptions, ) Allocator.Error!Ast
参数
错误
- OutOfMemory
std.zig.Ast.ptrType
函数
pub fn ptrType(tree: Ast, node: Node.Index) full.PtrType
参数
std.zig.Ast.ptrTypeAligned
函数
pub fn ptrTypeAligned(tree: Ast, node: Node.Index) full.PtrType
参数
std.zig.Ast.ptrTypeBitRange
函数
pub fn ptrTypeBitRange(tree: Ast, node: Node.Index) full.PtrType
参数
std.zig.Ast.ptrTypeSentinel
函数
pub fn ptrTypeSentinel(tree: Ast, node: Node.Index) full.PtrType
参数
std.zig.Ast.render
函数
pub fn render(tree: Ast, gpa: Allocator, w: *Writer, fixups: Render.Fixups) Render.Error!void
参数
错误
- OutOfMemory
为完成渲染而分配调用栈帧时,内存耗尽。
- WriteFailed
由下列来源传递的失败
std.zig.Ast.Render
别名
别名目标 std.zig.Ast.Render
std.zig.Ast.renderAlloc
函数
gpa 用于为格式化后的源码分配内存。
调用方拥有返回字节切片的所有权,它由 gpa 分配。
pub fn renderAlloc(tree: Ast, gpa: Allocator) error{OutOfMemory}![]u8
参数
错误
- OutOfMemory
std.zig.Ast.renderError
函数
pub fn renderError(tree: Ast, parse_error: Error, w: *Writer) Writer.Error!void
参数
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.zig.Ast.rootDecls
函数
pub fn rootDecls(tree: Ast) []const Node.Index
参数
tree: Ast
std.zig.Ast.simpleVarDecl
函数
pub fn simpleVarDecl(tree: Ast, node: Node.Index) full.VarDecl
参数
std.zig.Ast.slice
函数
pub fn slice(tree: Ast, node: Node.Index) full.Slice
参数
std.zig.Ast.sliceOpen
函数
pub fn sliceOpen(tree: Ast, node: Node.Index) full.Slice
参数
std.zig.Ast.sliceSentinel
函数
pub fn sliceSentinel(tree: Ast, node: Node.Index) full.Slice
参数
std.zig.Ast.Span
容器
字段
start: u32
end: u32
main: u32
std.zig.Ast.std
别名
别名目标 std
std.zig.Ast.structInit
函数
pub fn structInit(tree: Ast, node: Node.Index) full.StructInit
参数
std.zig.Ast.structInitDot
函数
pub fn structInitDot(tree: Ast, node: Node.Index) full.StructInit
参数
std.zig.Ast.structInitDotTwo
函数
pub fn structInitDotTwo(tree: Ast, buffer: *[2]Node.Index, node: Node.Index) full.StructInit
参数
std.zig.Ast.structInitOne
函数
pub fn structInitOne(tree: Ast, buffer: *[1]Node.Index, node: Node.Index) full.StructInit
参数
std.zig.Ast.switchCase
函数
pub fn switchCase(tree: Ast, node: Node.Index) full.SwitchCase
参数
std.zig.Ast.switchCaseOne
函数
pub fn switchCaseOne(tree: Ast, node: Node.Index) full.SwitchCase
参数
std.zig.Ast.switchFull
函数
pub fn switchFull(tree: Ast, node: Node.Index) full.Switch
参数
std.zig.Ast.taggedUnion
函数
pub fn taggedUnion(tree: Ast, node: Node.Index) full.ContainerDecl
参数
std.zig.Ast.taggedUnionEnumTag
函数
pub fn taggedUnionEnumTag(tree: Ast, node: Node.Index) full.ContainerDecl
参数
std.zig.Ast.taggedUnionTwo
函数
pub fn taggedUnionTwo(tree: Ast, buffer: *[2]Node.Index, node: Node.Index) full.ContainerDecl
参数
std.zig.Ast.testing
别名
别名目标 std.testing
std.zig.Ast.Token
别名
别名目标 std.zig.Token
std.zig.Ast.TokenIndex
类型
tokens 中的索引。
std.zig.Ast.TokenList
类型
std.zig.Ast.tokenLocation
函数
pub fn tokenLocation(self: Ast, start_offset: ByteOffset, token_index: TokenIndex) Location
参数
std.zig.Ast.TokenOffset
容器
相对词法标记索引。
字段
zero = 0
_
std.zig.Ast.TokenOffset.init
函数
pub fn init(base: TokenIndex, destination: TokenIndex) TokenOffset
参数
base: TokenIndex
destination: TokenIndex
std.zig.Ast.TokenOffset.toAbsolute
函数
pub fn toAbsolute(offset: TokenOffset, base: TokenIndex) TokenIndex
参数
offset: TokenOffset
base: TokenIndex
std.zig.Ast.TokenOffset.toOptional
函数
pub fn toOptional(to: TokenOffset) OptionalTokenOffset
参数
to: TokenOffset
std.zig.Ast.tokenSlice
函数
pub fn tokenSlice(tree: Ast, token_index: TokenIndex) []const u8
参数
tree: Ast
token_index: TokenIndex
std.zig.Ast.tokensOnSameLine
函数
pub fn tokensOnSameLine(tree: Ast, token1: TokenIndex, token2: TokenIndex) bool
参数
std.zig.Ast.tokenStart
函数
pub fn tokenStart(tree: *const Ast, token_index: TokenIndex) ByteOffset
参数
tree: *const Ast
token_index: TokenIndex
std.zig.Ast.tokensToSpan
函数
pub fn tokensToSpan(tree: *const Ast, start: Ast.TokenIndex, end: Ast.TokenIndex, main: Ast.TokenIndex) Span
参数
std.zig.Ast.tokenTag
函数
pub fn tokenTag(tree: *const Ast, token_index: TokenIndex) Token.Tag
参数
tree: *const Ast
token_index: TokenIndex
std.zig.Ast.tokenToSpan
函数
pub fn tokenToSpan(tree: *const Ast, token: Ast.TokenIndex) Span
参数
tree: *const Ast
token: Ast.TokenIndex
std.zig.Ast.whileCont
函数
pub fn whileCont(tree: Ast, node: Node.Index) full.While
参数
std.zig.Ast.whileFull
函数
pub fn whileFull(tree: Ast, node: Node.Index) full.While
参数
std.zig.Ast.whileSimple
函数
pub fn whileSimple(tree: Ast, node: Node.Index) full.While
参数
std.zig.Ast.Writer
别名
别名目标 std.Io.Writer
源码
std/zig/Ast.zig
//! Zig 源码的抽象语法树。
//! 对于 Zig 语法,根节点位于 nodes[0],包含
//! 子节点列表。
//! 对于 ZON 语法,根节点位于 nodes[0],其 lhs 为
//! 主表达式的节点索引。
const std = @import("../std.zig");
const assert = std.debug.assert;
const testing = std.testing;
const mem = std.mem;
const Token = std.zig.Token;
const Ast = @This();
const Allocator = std.mem.Allocator;
const Parse = @import("Parse.zig");
const Writer = std.Io.Writer;
/// 对外部拥有数据的引用。
source: [:0]const u8,
tokens: TokenList.Slice,
nodes: NodeList.Slice,
extra_data: []u32,
mode: Mode = .zig,
errors: []const Error,
pub const ByteOffset = u32;
pub const TokenList = std.MultiArrayList(struct {
tag: Token.Tag,
start: ByteOffset,
});
pub const NodeList = std.MultiArrayList(Node);
/// `tokens` 中的索引。
pub const TokenIndex = u32;
/// `tokens` 的索引或 null。
pub const OptionalTokenIndex = enum(u32) {
none = std.math.maxInt(u32),
_,
pub fn unwrap(oti: OptionalTokenIndex) ?TokenIndex {
return if (oti == .none) null else @backingInt(oti);
}
pub fn fromToken(ti: TokenIndex) OptionalTokenIndex {
return @fromBackingInt(@intCast(ti));
}
pub fn fromOptional(oti: ?TokenIndex) OptionalTokenIndex {
return if (oti) |ti| @fromBackingInt(@intCast(ti)) else .none;
}
};
/// 相对词法标记索引。
pub const TokenOffset = enum(i32) {
zero = 0,
_,
pub fn init(base: TokenIndex, destination: TokenIndex) TokenOffset {
const base_i64: i64 = base;
const destination_i64: i64 = destination;
return @fromBackingInt(@intCast(destination_i64 - base_i64));
}
pub fn toOptional(to: TokenOffset) OptionalTokenOffset {
const result: OptionalTokenOffset = @fromBackingInt(@intCast(@backingInt(to)));
assert(result != .none);
return result;
}
pub fn toAbsolute(offset: TokenOffset, base: TokenIndex) TokenIndex {
return @intCast(@as(i64, base) + @backingInt(offset));
}
};
/// 相对词法标记索引或 null。
pub const OptionalTokenOffset = enum(i32) {
none = std.math.maxInt(i32),
_,
pub fn unwrap(oto: OptionalTokenOffset) ?TokenOffset {
return if (oto == .none) null else @fromBackingInt(@intCast(@backingInt(oto)));
}
};
pub fn tokenTag(tree: *const Ast, token_index: TokenIndex) Token.Tag {
return tree.tokens.items(.tag)[token_index];
}
pub fn tokenStart(tree: *const Ast, token_index: TokenIndex) ByteOffset {
return tree.tokens.items(.start)[token_index];
}
pub fn nodeTag(tree: *const Ast, node: Node.Index) Node.Tag {
return tree.nodes.items(.tag)[@backingInt(node)];
}
pub fn nodeMainToken(tree: *const Ast, node: Node.Index) TokenIndex {
return tree.nodes.items(.main_token)[@backingInt(node)];
}
pub fn nodeData(tree: *const Ast, node: Node.Index) Node.Data {
return tree.nodes.items(.data)[@backingInt(node)];
}
pub fn isTokenPrecededByTags(
tree: *const Ast,
ti: TokenIndex,
expected_token_tags: []const Token.Tag,
) bool {
return std.mem.endsWith(
Token.Tag,
tree.tokens.items(.tag)[0..ti],
expected_token_tags,
);
}
pub const Location = struct {
line: usize,
column: usize,
line_start: usize,
line_end: usize,
};
pub const Span = struct {
start: u32,
end: u32,
main: u32,
};
pub fn deinit(tree: *Ast, gpa: Allocator) void {
tree.tokens.deinit(gpa);
tree.nodes.deinit(gpa);
gpa.free(tree.extra_data);
gpa.free(tree.errors);
tree.* = undefined;
}
pub const Mode = enum { zig, zon };
pub const ParseOptions = struct {
recover: bool = true,
mode: Mode = .zig,
};
/// 当不再引用任何词法标记或节点时,
/// 应使用 tree.deinit() 释放结果。
pub fn parse(gpa: Allocator, source: [:0]const u8, options: ParseOptions) Allocator.Error!Ast {
var tokens = Ast.TokenList{};
defer tokens.deinit(gpa);
// 实际观察中,zig 标准库的源码字节数与 token 数约为 8:1。
const estimated_token_count = source.len / 8;
try tokens.ensureTotalCapacity(gpa, estimated_token_count);
var tokenizer = std.zig.Tokenizer.init(source);
while (true) {
const token = tokenizer.next();
try tokens.append(gpa, .{
.tag = token.tag,
.start = @intCast(token.loc.start),
});
if (token.tag == .eof) break;
}
var tokens_slice = tokens.toOwnedSlice();
errdefer tokens_slice.deinit(gpa);
return parseTokens(gpa, source, tokens_slice, options);
}
pub fn parseTokens(
gpa: Allocator,
source: [:0]const u8,
tokens: Ast.TokenList.Slice,
options: ParseOptions,
) Allocator.Error!Ast {
var parser: Parse = .{
.source = source,
.gpa = gpa,
.tokens = tokens,
.errors = .empty,
.nodes = .empty,
.extra_data = .empty,
.scratch = .empty,
.tok_i = 0,
.recover = options.recover,
};
defer parser.errors.deinit(gpa);
defer parser.nodes.deinit(gpa);
defer parser.extra_data.deinit(gpa);
defer parser.scratch.deinit(gpa);
// 根据经验,Zig 源码中标记与 AST 节点的比例为 2:1。
// 确保至少为 1,以便下方可对根节点使用 appendAssumeCapacity。
const estimated_node_count = (tokens.len + 2) / 2;
try parser.nodes.ensureTotalCapacity(gpa, estimated_node_count);
switch (options.mode) {
.zig => try parser.parseRoot(),
.zon => try parser.parseZon(),
}
try parser.extra_data.shrinkToLen(gpa);
try parser.errors.shrinkToLen(gpa);
// TODO 尝试在此压缩 MultiArrayList 切片
return .{
.source = source,
.mode = options.mode,
.tokens = tokens,
.nodes = parser.nodes.toOwnedSlice(),
.extra_data = parser.extra_data.toOwnedSliceAssert(),
.errors = parser.errors.toOwnedSliceAssert(),
};
}
/// `gpa` 用于为格式化后的源码分配内存。
/// 调用方拥有返回字节切片的所有权,它由 `gpa` 分配。
pub fn renderAlloc(tree: Ast, gpa: Allocator) error{OutOfMemory}![]u8 {
var aw: std.Io.Writer.Allocating = .init(gpa);
defer aw.deinit();
render(tree, gpa, &aw.writer, .{}) catch |err| switch (err) {
error.WriteFailed, error.OutOfMemory => return error.OutOfMemory,
};
return aw.toOwnedSlice();
}
pub const Render = @import("Ast/Render.zig");
pub fn render(tree: Ast, gpa: Allocator, w: *Writer, fixups: Render.Fixups) Render.Error!void {
return Render.renderTree(gpa, w, tree, fixups);
}
/// 为错误的列偏移和字节偏移返回额外偏移量,
/// 使错误消息指向 token 之后。
pub fn errorOffset(tree: Ast, parse_error: Error) u32 {
return if (parse_error.token_is_prev) @intCast(tree.tokenSlice(parse_error.token).len) else 0;
}
pub fn tokenLocation(self: Ast, start_offset: ByteOffset, token_index: TokenIndex) Location {
var loc = Location{
.line = 0,
.column = 0,
.line_start = start_offset,
.line_end = self.source.len,
};
const token_start = self.tokenStart(token_index);
// 逐行扫描,直到超过标记的起始位置
while (std.mem.findScalarPos(u8, self.source, loc.line_start, '\n')) |i| {
if (i >= token_start) {
break; // 已越过
}
loc.line += 1;
loc.line_start = i + 1;
}
const offset = loc.line_start;
for (self.source[offset..], 0..) |c, i| {
if (i + offset == token_start) {
loc.line_end = i + offset;
while (loc.line_end < self.source.len and self.source[loc.line_end] != '\n') {
loc.line_end += 1;
}
return loc;
}
if (c == '\n') {
loc.line += 1;
loc.column = 0;
loc.line_start = i + 1;
} else {
loc.column += 1;
}
}
return loc;
}
pub fn tokenSlice(tree: Ast, token_index: TokenIndex) []const u8 {
const token_tag = tree.tokenTag(token_index);
// 许多词法标记仅凭标签即可完全确定。
if (token_tag.lexeme()) |lexeme| {
return lexeme;
}
// 某些 token 需要重新词法分析,才能确定末尾。
var tokenizer: std.zig.Tokenizer = .{
.buffer = tree.source,
.index = tree.tokenStart(token_index),
};
const token = tokenizer.next();
assert(token.tag == token_tag);
return tree.source[token.loc.start..token.loc.end];
}
pub fn extraDataSlice(tree: Ast, range: Node.SubRange, comptime T: type) []const T {
return @ptrCast(tree.extra_data[@backingInt(range.start)..@backingInt(range.end)]);
}
pub fn extraDataSliceWithLen(tree: Ast, start: ExtraIndex, len: u32, comptime T: type) []const T {
return @ptrCast(tree.extra_data[@backingInt(start)..][0..len]);
}
pub fn extraData(tree: Ast, index: ExtraIndex, comptime T: type) T {
const info = @typeInfo(T).@"struct";
var result: T = undefined;
inline for (info.field_names, info.field_types, 0..) |field_name, field_type, i| {
@field(result, field_name) = switch (field_type) {
Node.Index,
Node.OptionalIndex,
OptionalTokenIndex,
ExtraIndex,
=> @fromBackingInt(@intCast(tree.extra_data[@backingInt(index) + i])),
TokenIndex => tree.extra_data[@backingInt(index) + i],
else => @compileError("unexpected field type: " ++ @typeName(field_type)),
};
}
return result;
}
fn loadOptionalNodesIntoBuffer(comptime size: usize, buffer: *[size]Node.Index, items: [size]Node.OptionalIndex) []Node.Index {
for (buffer, items, 0..) |*node, opt_node, i| {
node.* = opt_node.unwrap() orelse return buffer[0..i];
}
return buffer[0..];
}
pub fn rootDecls(tree: Ast) []const Node.Index {
switch (tree.mode) {
.zig => return tree.extraDataSlice(tree.nodeData(.root).extra_range, Node.Index),
// 确保返回的切片指向 Ast 已有的内存。
.zon => return (&tree.nodes.items(.data)[@backingInt(Node.Index.root)].node)[0..1],
}
}
pub fn renderError(tree: Ast, parse_error: Error, w: *Writer) Writer.Error!void {
switch (parse_error.tag) {
.chained_comparison_operators => {
return w.writeAll("comparison operators cannot be chained");
},
.decl_between_fields => {
return w.writeAll("declarations are not allowed between container fields");
},
.expected_block => {
return w.print("expected block, found '{s}'", .{
tree.tokenTag(parse_error.token + @intFromBool(parse_error.token_is_prev)).symbol(),
});
},
.expected_block_or_assignment => {
return w.print("expected block or assignment, found '{s}'", .{
tree.tokenTag(parse_error.token + @intFromBool(parse_error.token_is_prev)).symbol(),
});
},
.expected_block_or_expr => {
return w.print("expected block or expression, found '{s}'", .{
tree.tokenTag(parse_error.token + @intFromBool(parse_error.token_is_prev)).symbol(),
});
},
.expected_block_or_field => {
return w.print("expected block or field, found '{s}'", .{
tree.tokenTag(parse_error.token + @intFromBool(parse_error.token_is_prev)).symbol(),
});
},
.expected_container_members => {
return w.print("expected test, comptime, var decl, or container field, found '{s}'", .{
tree.tokenTag(parse_error.token).symbol(),
});
},
.expected_expr => {
return w.print("expected expression, found '{s}'", .{
tree.tokenTag(parse_error.token + @intFromBool(parse_error.token_is_prev)).symbol(),
});
},
.expected_expr_or_assignment => {
return w.print("expected expression or assignment, found '{s}'", .{
tree.tokenTag(parse_error.token + @intFromBool(parse_error.token_is_prev)).symbol(),
});
},
.expected_expr_or_var_decl => {
return w.print("expected expression or var decl, found '{s}'", .{
tree.tokenTag(parse_error.token + @intFromBool(parse_error.token_is_prev)).symbol(),
});
},
.expected_fn => {
return w.print("expected function, found '{s}'", .{
tree.tokenTag(parse_error.token + @intFromBool(parse_error.token_is_prev)).symbol(),
});
},
.expected_inlinable => {
return w.print("expected 'while' or 'for', found '{s}'", .{
tree.tokenTag(parse_error.token + @intFromBool(parse_error.token_is_prev)).symbol(),
});
},
.expected_labelable => {
return w.print("expected 'while', 'for', 'inline', or '{{', found '{s}'", .{
tree.tokenTag(parse_error.token + @intFromBool(parse_error.token_is_prev)).symbol(),
});
},
.expected_param_list => {
return w.print("expected parameter list, found '{s}'", .{
tree.tokenTag(parse_error.token + @intFromBool(parse_error.token_is_prev)).symbol(),
});
},
.expected_prefix_expr => {
return w.print("expected prefix expression, found '{s}'", .{
tree.tokenTag(parse_error.token + @intFromBool(parse_error.token_is_prev)).symbol(),
});
},
.expected_primary_type_expr => {
return w.print("expected primary type expression, found '{s}'", .{
tree.tokenTag(parse_error.token + @intFromBool(parse_error.token_is_prev)).symbol(),
});
},
.expected_pub_item => {
return w.writeAll("expected function or variable declaration after pub");
},
.expected_return_type => {
return w.print("expected return type expression, found '{s}'", .{
tree.tokenTag(parse_error.token + @intFromBool(parse_error.token_is_prev)).symbol(),
});
},
.expected_semi_or_else => {
return w.writeAll("expected ';' or 'else' after statement");
},
.expected_semi_or_lbrace => {
return w.writeAll("expected ';' or block after function prototype");
},
.expected_statement => {
return w.print("expected statement, found '{s}'", .{
tree.tokenTag(parse_error.token).symbol(),
});
},
.expected_suffix_op => {
return w.print("expected pointer dereference, optional unwrap, or field access, found '{s}'", .{
tree.tokenTag(parse_error.token + @intFromBool(parse_error.token_is_prev)).symbol(),
});
},
.expected_type_expr => {
return w.print("expected type expression, found '{s}'", .{
tree.tokenTag(parse_error.token + @intFromBool(parse_error.token_is_prev)).symbol(),
});
},
.expected_var_decl => {
return w.print("expected variable declaration, found '{s}'", .{
tree.tokenTag(parse_error.token + @intFromBool(parse_error.token_is_prev)).symbol(),
});
},
.expected_var_decl_or_fn => {
return w.print("expected variable declaration or function, found '{s}'", .{
tree.tokenTag(parse_error.token + @intFromBool(parse_error.token_is_prev)).symbol(),
});
},
.expected_loop_payload => {
return w.print("expected loop payload, found '{s}'", .{
tree.tokenTag(parse_error.token + @intFromBool(parse_error.token_is_prev)).symbol(),
});
},
.expected_container => {
return w.print("expected a struct, enum or union, found '{s}'", .{
tree.tokenTag(parse_error.token + @intFromBool(parse_error.token_is_prev)).symbol(),
});
},
.extern_fn_body => {
return w.writeAll("extern functions have no body");
},
.extra_addrspace_qualifier => {
return w.writeAll("extra addrspace qualifier");
},
.extra_align_qualifier => {
return w.writeAll("extra align qualifier");
},
.ptr_mod_on_array_child_type => {
return w.print("pointer modifier '{s}' not allowed on array child type", .{
tree.tokenTag(parse_error.token).symbol(),
});
},
.invalid_bit_range => {
return w.writeAll("bit range only allowed on single item pointers");
},
.same_line_doc_comment => {
return w.writeAll("same line documentation comment");
},
.unattached_doc_comment => {
return w.writeAll("unattached documentation comment");
},
.test_doc_comment => {
return w.writeAll("documentation comments cannot be attached to tests");
},
.comptime_doc_comment => {
return w.writeAll("documentation comments cannot be attached to comptime blocks");
},
.varargs_nonfinal => {
return w.writeAll("function prototype has parameter after varargs");
},
.expected_semi_after_decl => {
return w.writeAll("expected ';' after declaration");
},
.expected_semi_after_stmt => {
return w.writeAll("expected ';' after statement");
},
.expected_comma_after_field => {
return w.writeAll("expected ',' after field");
},
.expected_comma_after_arg => {
return w.writeAll("expected ',' after argument");
},
.expected_comma_after_param => {
return w.writeAll("expected ',' after parameter");
},
.expected_comma_after_initializer => {
return w.writeAll("expected ',' after initializer");
},
.expected_comma_after_switch_prong => {
return w.writeAll("expected ',' after switch prong");
},
.expected_comma_after_for_operand => {
return w.writeAll("expected ',' after for operand");
},
.expected_comma_after_capture => {
return w.writeAll("expected ',' after for capture");
},
.expected_initializer => {
return w.writeAll("expected field initializer");
},
.mismatched_binary_op_whitespace => {
return w.print("binary operator '{s}' has whitespace on one side, but not the other", .{tree.tokenTag(parse_error.token).lexeme().?});
},
.invalid_ampersand_ampersand => {
return w.writeAll("ambiguous use of '&&'; use 'and' for logical AND, or change whitespace to ' & &' for bitwise AND");
},
.c_style_container => {
return w.print("'{s} {s}' is invalid", .{
parse_error.extra.expected_tag.symbol(), tree.tokenSlice(parse_error.token),
});
},
.zig_style_container => {
return w.print("to declare a container do 'const {s} = {s}'", .{
tree.tokenSlice(parse_error.token), parse_error.extra.expected_tag.symbol(),
});
},
.previous_field => {
return w.writeAll("field before declarations here");
},
.next_field => {
return w.writeAll("field after declarations here");
},
.expected_var_const => {
return w.writeAll("expected 'var' or 'const' before variable declaration");
},
.wrong_equal_var_decl => {
return w.writeAll("variable initialized with '==' instead of '='");
},
.var_const_decl => {
return w.writeAll("use 'var' or 'const' to declare variable");
},
.invalid_byte => {
const tok_slice = tree.source[tree.tokens.items(.start)[parse_error.token]..];
return w.print("{s} contains invalid byte: '{f}'", .{
switch (tok_slice[0]) {
'\'' => "character literal",
'"', '\\' => "string literal",
'/' => "comment",
else => unreachable,
},
std.zig.fmtChar(tok_slice[parse_error.extra.offset]),
});
},
.expected_token => {
const found_tag = tree.tokenTag(parse_error.token + @intFromBool(parse_error.token_is_prev));
const expected_symbol = parse_error.extra.expected_tag.symbol();
switch (found_tag) {
.invalid => return w.print("expected '{s}', found invalid bytes", .{
expected_symbol,
}),
else => return w.print("expected '{s}', found '{s}'", .{
expected_symbol, found_tag.symbol(),
}),
}
},
}
}
pub fn firstToken(tree: Ast, node: Node.Index) TokenIndex {
var end_offset: u32 = 0;
var n = node;
while (true) switch (tree.nodeTag(n)) {
.root => return 0,
.test_decl,
.@"errdefer",
.@"defer",
.bool_not,
.negation,
.bit_not,
.negation_wrap,
.address_of,
.@"try",
.optional_type,
.@"switch",
.switch_comma,
.if_simple,
.@"if",
.@"suspend",
.@"resume",
.@"continue",
.@"break",
.@"return",
.anyframe_type,
.identifier,
.anyframe_literal,
.char_literal,
.number_literal,
.unreachable_literal,
.string_literal,
.multiline_string_literal,
.grouped_expression,
.builtin_call_two,
.builtin_call_two_comma,
.builtin_call,
.builtin_call_comma,
.error_set_decl,
.@"comptime",
.@"nosuspend",
.asm_simple,
.@"asm",
.array_type,
.array_type_sentinel,
.error_value,
=> return tree.nodeMainToken(n) - end_offset,
.array_init_dot,
.array_init_dot_comma,
.array_init_dot_two,
.array_init_dot_two_comma,
.struct_init_dot,
.struct_init_dot_comma,
.struct_init_dot_two,
.struct_init_dot_two_comma,
.enum_literal,
=> return tree.nodeMainToken(n) - 1 - end_offset,
.@"catch",
.equal_equal,
.bang_equal,
.less_than,
.greater_than,
.less_or_equal,
.greater_or_equal,
.assign_mul,
.assign_div,
.assign_mod,
.assign_add,
.assign_sub,
.assign_shl,
.assign_shl_sat,
.assign_shr,
.assign_bit_and,
.assign_bit_xor,
.assign_bit_or,
.assign_mul_wrap,
.assign_add_wrap,
.assign_sub_wrap,
.assign_mul_sat,
.assign_add_sat,
.assign_sub_sat,
.assign,
.merge_error_sets,
.mul,
.div,
.mod,
.mul_wrap,
.mul_sat,
.add,
.sub,
.array_cat,
.add_wrap,
.sub_wrap,
.add_sat,
.sub_sat,
.shl,
.shl_sat,
.shr,
.bit_and,
.bit_xor,
.bit_or,
.@"orelse",
.bool_and,
.bool_or,
.slice_open,
.array_access,
.array_init_one,
.array_init_one_comma,
.switch_range,
.error_union,
=> n = tree.nodeData(n).node_and_node[0],
.for_range,
.call_one,
.call_one_comma,
.struct_init_one,
.struct_init_one_comma,
=> n = tree.nodeData(n).node_and_opt_node[0],
.field_access,
.unwrap_optional,
=> n = tree.nodeData(n).node_and_token[0],
.slice,
.slice_sentinel,
.array_init,
.array_init_comma,
.struct_init,
.struct_init_comma,
.call,
.call_comma,
=> n = tree.nodeData(n).node_and_extra[0],
.deref => n = tree.nodeData(n).node,
.assign_destructure => n = tree.assignDestructure(n).ast.variables[0],
.fn_decl,
.fn_proto_simple,
.fn_proto_multi,
.fn_proto_one,
.fn_proto,
=> {
var i = tree.nodeMainToken(n); // fn 词法标记
while (i > 0) {
i -= 1;
switch (tree.tokenTag(i)) {
.keyword_extern,
.keyword_export,
.keyword_pub,
.keyword_inline,
.keyword_noinline,
.string_literal,
=> continue,
else => return i + 1 - end_offset,
}
}
return i - end_offset;
},
.container_field_init,
.container_field_align,
.container_field,
=> {
const name_token = tree.nodeMainToken(n);
const has_comptime_token = tree.isTokenPrecededByTags(name_token, &.{.keyword_comptime});
end_offset += @intFromBool(has_comptime_token);
return name_token - end_offset;
},
.global_var_decl,
.local_var_decl,
.simple_var_decl,
.aligned_var_decl,
=> {
var i = tree.nodeMainToken(n); // mut 词法标记
while (i > 0) {
i -= 1;
switch (tree.tokenTag(i)) {
.keyword_extern,
.keyword_export,
.keyword_comptime,
.keyword_pub,
.keyword_threadlocal,
.string_literal,
=> continue,
else => return i + 1 - end_offset,
}
}
return i - end_offset;
},
.block,
.block_semicolon,
.block_two,
.block_two_semicolon,
=> {
// 查找标签。
const lbrace = tree.nodeMainToken(n);
if (tree.isTokenPrecededByTags(lbrace, &.{ .identifier, .colon })) {
end_offset += 2;
}
return lbrace - end_offset;
},
.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,
=> {
const main_token = tree.nodeMainToken(n);
switch (tree.tokenTag(main_token -| 1)) {
.keyword_packed, .keyword_extern => end_offset += 1,
else => {},
}
return main_token - end_offset;
},
.ptr_type_aligned,
.ptr_type_sentinel,
.ptr_type,
.ptr_type_bit_range,
=> return tree.nodeMainToken(n) - end_offset,
.switch_case_one,
.switch_case_inline_one,
.switch_case,
.switch_case_inline,
=> {
const full_switch = tree.fullSwitchCase(n).?;
if (full_switch.inline_token) |inline_token| {
return inline_token;
} else if (full_switch.ast.values.len == 0) {
return full_switch.ast.arrow_token - 1 - end_offset; // else 词法标记
} else {
n = full_switch.ast.values[0];
}
},
.asm_output, .asm_input => {
assert(tree.tokenTag(tree.nodeMainToken(n) - 1) == .l_bracket);
return tree.nodeMainToken(n) - 1 - end_offset;
},
.while_simple,
.while_cont,
.@"while",
.for_simple,
.@"for",
=> {
// 查找标签和 inline。
const main_token = tree.nodeMainToken(n);
var result = main_token;
if (tree.isTokenPrecededByTags(result, &.{.keyword_inline})) {
result = result - 1;
}
if (tree.isTokenPrecededByTags(result, &.{ .identifier, .colon })) {
result = result - 2;
}
return result - end_offset;
},
};
}
pub fn lastToken(tree: Ast, node: Node.Index) TokenIndex {
var n = node;
var end_offset: u32 = 0;
while (true) switch (tree.nodeTag(n)) {
.root => return @intCast(tree.tokens.len - 1),
.bool_not,
.negation,
.bit_not,
.negation_wrap,
.address_of,
.@"try",
.optional_type,
.@"suspend",
.@"resume",
.@"nosuspend",
.@"comptime",
=> n = tree.nodeData(n).node,
.@"catch",
.equal_equal,
.bang_equal,
.less_than,
.greater_than,
.less_or_equal,
.greater_or_equal,
.assign_mul,
.assign_div,
.assign_mod,
.assign_add,
.assign_sub,
.assign_shl,
.assign_shl_sat,
.assign_shr,
.assign_bit_and,
.assign_bit_xor,
.assign_bit_or,
.assign_mul_wrap,
.assign_add_wrap,
.assign_sub_wrap,
.assign_mul_sat,
.assign_add_sat,
.assign_sub_sat,
.assign,
.merge_error_sets,
.mul,
.div,
.mod,
.mul_wrap,
.mul_sat,
.add,
.sub,
.array_cat,
.add_wrap,
.sub_wrap,
.add_sat,
.sub_sat,
.shl,
.shl_sat,
.shr,
.bit_and,
.bit_xor,
.bit_or,
.@"orelse",
.bool_and,
.bool_or,
.error_union,
.if_simple,
.while_simple,
.for_simple,
.fn_decl,
.array_type,
.switch_range,
=> n = tree.nodeData(n).node_and_node[1],
.test_decl => n = tree.nodeData(n).opt_token_and_node[1],
.@"defer", .@"errdefer" => n = tree.nodeData(n).node,
.anyframe_type => n = tree.nodeData(n).token_and_node[1],
.switch_case_one,
.switch_case_inline_one,
.ptr_type_aligned,
.ptr_type_sentinel,
=> n = tree.nodeData(n).opt_node_and_node[1],
.assign_destructure,
.ptr_type,
.ptr_type_bit_range,
.switch_case,
.switch_case_inline,
=> n = tree.nodeData(n).extra_and_node[1],
.fn_proto_simple => n = tree.nodeData(n).opt_node_and_opt_node[1].unwrap().?,
.fn_proto_multi,
.fn_proto_one,
.fn_proto,
=> n = tree.nodeData(n).extra_and_opt_node[1].unwrap().?,
.for_range => {
n = tree.nodeData(n).node_and_opt_node[1].unwrap() orelse {
return tree.nodeMainToken(n) + end_offset;
};
},
.field_access,
.unwrap_optional,
.asm_simple,
=> return tree.nodeData(n).node_and_token[1] + end_offset,
.grouped_expression, .asm_input => return tree.nodeData(n).node_and_token[1] + end_offset,
.multiline_string_literal, .error_set_decl => return tree.nodeData(n).token_and_token[1] + end_offset,
.asm_output => return tree.nodeData(n).opt_node_and_token[1] + end_offset,
.error_value => return tree.nodeMainToken(n) + 2 + end_offset,
.anyframe_literal,
.char_literal,
.number_literal,
.unreachable_literal,
.identifier,
.deref,
.enum_literal,
.string_literal,
=> return tree.nodeMainToken(n) + end_offset,
.@"return" => {
n = tree.nodeData(n).opt_node.unwrap() orelse {
return tree.nodeMainToken(n) + end_offset;
};
},
.call => {
_, const extra_index = tree.nodeData(n).node_and_extra;
const params = tree.extraData(extra_index, Node.SubRange);
assert(params.start != params.end);
end_offset += 1; // 用于右圆括号
n = @fromBackingInt(@intCast(tree.extra_data[@backingInt(params.end) - 1])); // 最后一个参数
},
.tagged_union_enum_tag => {
const arg, const extra_index = tree.nodeData(n).node_and_extra;
const members = tree.extraData(extra_index, Node.SubRange);
if (members.start == members.end) {
end_offset += 4; // 用于右圆括号 + 右圆括号 + 左花括号 + 右花括号
n = arg;
} else {
end_offset += 1; // 用于右花括号
n = @fromBackingInt(@intCast(tree.extra_data[@backingInt(members.end) - 1])); // 最后一个参数
}
},
.call_comma,
.tagged_union_enum_tag_trailing,
=> {
_, const extra_index = tree.nodeData(n).node_and_extra;
const params = tree.extraData(extra_index, Node.SubRange);
assert(params.start != params.end);
end_offset += 2; // 用于逗号或分号加右圆括号或右花括号
n = @fromBackingInt(@intCast(tree.extra_data[@backingInt(params.end) - 1])); // 最后一个参数
},
.@"switch" => {
const condition, const extra_index = tree.nodeData(n).node_and_extra;
const cases = tree.extraData(extra_index, Node.SubRange);
if (cases.start == cases.end) {
end_offset += 3; // 右圆括号、左花括号、右花括号
n = condition;
} else {
end_offset += 1; // 用于右花括号
n = @fromBackingInt(@intCast(tree.extra_data[@backingInt(cases.end) - 1])); // 最后一种情况
}
},
.container_decl_arg => {
const arg, const extra_index = tree.nodeData(n).node_and_extra;
const members = tree.extraData(extra_index, Node.SubRange);
if (members.end == members.start) {
end_offset += 3; // 用于右圆括号 + 左花括号 + 右花括号
n = arg;
} else {
end_offset += 1; // 用于右花括号
n = @fromBackingInt(@intCast(tree.extra_data[@backingInt(members.end) - 1])); // 最后一个参数
}
},
.@"asm" => {
_, const extra_index = tree.nodeData(n).node_and_extra;
const extra = tree.extraData(extra_index, Node.Asm);
return extra.rparen + end_offset;
},
.array_init,
.struct_init,
=> {
_, const extra_index = tree.nodeData(n).node_and_extra;
const elements = tree.extraData(extra_index, Node.SubRange);
assert(elements.start != elements.end);
end_offset += 1; // 用于右花括号
n = @fromBackingInt(@intCast(tree.extra_data[@backingInt(elements.end) - 1])); // 最后一个元素
},
.array_init_comma,
.struct_init_comma,
.container_decl_arg_trailing,
.switch_comma,
=> {
_, const extra_index = tree.nodeData(n).node_and_extra;
const members = tree.extraData(extra_index, Node.SubRange);
assert(members.start != members.end);
end_offset += 2; // 用于逗号和右花括号
n = @fromBackingInt(@intCast(tree.extra_data[@backingInt(members.end) - 1])); // 最后一个参数
},
.array_init_dot,
.struct_init_dot,
.block,
.container_decl,
.tagged_union,
.builtin_call,
=> {
const range = tree.nodeData(n).extra_range;
assert(range.start != range.end);
end_offset += 1; // 用于右花括号
n = @fromBackingInt(@intCast(tree.extra_data[@backingInt(range.end) - 1])); // 最后一条语句
},
.array_init_dot_comma,
.struct_init_dot_comma,
.block_semicolon,
.container_decl_trailing,
.tagged_union_trailing,
.builtin_call_comma,
=> {
const range = tree.nodeData(n).extra_range;
assert(range.start != range.end);
end_offset += 2; // 用于逗号/分号 + 右花括号/右圆括号
n = @fromBackingInt(@intCast(tree.extra_data[@backingInt(range.end) - 1])); // 最后一个成员
},
.call_one,
=> {
_, const first_param = tree.nodeData(n).node_and_opt_node;
end_offset += 1; // 用于右圆括号
n = first_param.unwrap() orelse {
return tree.nodeMainToken(n) + end_offset;
};
},
.array_init_dot_two,
.block_two,
.builtin_call_two,
.struct_init_dot_two,
.container_decl_two,
.tagged_union_two,
=> {
const opt_lhs, const opt_rhs = tree.nodeData(n).opt_node_and_opt_node;
if (opt_rhs.unwrap()) |rhs| {
end_offset += 1; // 用于右圆括号/右花括号
n = rhs;
} else if (opt_lhs.unwrap()) |lhs| {
end_offset += 1; // 用于右圆括号/右花括号
n = lhs;
} else {
switch (tree.nodeTag(n)) {
.array_init_dot_two,
.block_two,
.struct_init_dot_two,
=> end_offset += 1, // 右花括号
.builtin_call_two => end_offset += 2, // 左圆括号或左花括号 + 右圆括号或右花括号
.container_decl_two => {
var i: u32 = 2; // 左花括号 + 右花括号
while (tree.tokenTag(tree.nodeMainToken(n) + i) == .container_doc_comment) i += 1;
end_offset += i;
},
.tagged_union_two => {
var i: u32 = 5; // (enum) {}
while (tree.tokenTag(tree.nodeMainToken(n) + i) == .container_doc_comment) i += 1;
end_offset += i;
},
else => unreachable,
}
return tree.nodeMainToken(n) + end_offset;
}
},
.array_init_dot_two_comma,
.builtin_call_two_comma,
.block_two_semicolon,
.struct_init_dot_two_comma,
.container_decl_two_trailing,
.tagged_union_two_trailing,
=> {
const opt_lhs, const opt_rhs = tree.nodeData(n).opt_node_and_opt_node;
end_offset += 2; // 用于逗号/分号 + 右花括号/右圆括号
if (opt_rhs.unwrap()) |rhs| {
n = rhs;
} else if (opt_lhs.unwrap()) |lhs| {
n = lhs;
} else {
unreachable;
}
},
.simple_var_decl => {
const type_node, const init_node = tree.nodeData(n).opt_node_and_opt_node;
if (init_node.unwrap()) |rhs| {
n = rhs;
} else if (type_node.unwrap()) |lhs| {
n = lhs;
} else {
end_offset += 1; // 从 mut 词法标记到名称
return tree.nodeMainToken(n) + end_offset;
}
},
.aligned_var_decl => {
const align_node, const init_node = tree.nodeData(n).node_and_opt_node;
if (init_node.unwrap()) |rhs| {
n = rhs;
} else {
end_offset += 1; // 用于右圆括号
n = align_node;
}
},
.global_var_decl => {
const extra_index, const init_node = tree.nodeData(n).extra_and_opt_node;
if (init_node.unwrap()) |rhs| {
n = rhs;
} else {
const extra = tree.extraData(extra_index, Node.GlobalVarDecl);
if (extra.section_node.unwrap()) |section_node| {
end_offset += 1; // 用于右圆括号
n = section_node;
} else if (extra.addrspace_node.unwrap()) |addrspace_node| {
end_offset += 1; // 用于右圆括号
n = addrspace_node;
} else if (extra.align_node.unwrap()) |align_node| {
end_offset += 1; // 用于右圆括号
n = align_node;
} else if (extra.type_node.unwrap()) |type_node| {
n = type_node;
} else {
end_offset += 1; // 从 mut 词法标记到名称
return tree.nodeMainToken(n) + end_offset;
}
}
},
.local_var_decl => {
const extra_index, const init_node = tree.nodeData(n).extra_and_opt_node;
if (init_node.unwrap()) |rhs| {
n = rhs;
} else {
const extra = tree.extraData(extra_index, Node.LocalVarDecl);
end_offset += 1; // 用于右圆括号
n = extra.align_node;
}
},
.container_field_init => {
const type_expr, const value_expr = tree.nodeData(n).node_and_opt_node;
n = value_expr.unwrap() orelse type_expr;
},
.array_access,
.array_init_one,
.container_field_align,
=> {
_, const rhs = tree.nodeData(n).node_and_node;
end_offset += 1; // 用于右方括号/右花括号/右圆括号
n = rhs;
},
.container_field => {
_, const extra_index = tree.nodeData(n).node_and_extra;
const extra = tree.extraData(extra_index, Node.ContainerField);
n = extra.value_expr;
},
.struct_init_one => {
_, const first_field = tree.nodeData(n).node_and_opt_node;
end_offset += 1; // 右花括号
n = first_field.unwrap() orelse {
return tree.nodeMainToken(n) + end_offset;
};
},
.slice_open => {
_, const start_node = tree.nodeData(n).node_and_node;
end_offset += 2; // ellipsis2 + 右方括号,或逗号 + 右圆括号
n = start_node;
},
.array_init_one_comma => {
_, const first_element = tree.nodeData(n).node_and_node;
end_offset += 2; // 逗号 + 右花括号
n = first_element;
},
.call_one_comma,
.struct_init_one_comma,
=> {
_, const first_field = tree.nodeData(n).node_and_opt_node;
end_offset += 2; // ellipsis2 + 右方括号,或逗号 + 右圆括号
n = first_field.unwrap().?;
},
.slice => {
_, const extra_index = tree.nodeData(n).node_and_extra;
const extra = tree.extraData(extra_index, Node.Slice);
end_offset += 1; // 右方括号
n = extra.end;
},
.slice_sentinel => {
_, const extra_index = tree.nodeData(n).node_and_extra;
const extra = tree.extraData(extra_index, Node.SliceSentinel);
end_offset += 1; // 右方括号
n = extra.sentinel;
},
.@"continue", .@"break" => {
const opt_label, const opt_rhs = tree.nodeData(n).opt_token_and_opt_node;
if (opt_rhs.unwrap()) |rhs| {
n = rhs;
} else if (opt_label.unwrap()) |lhs| {
return lhs + end_offset;
} else {
return tree.nodeMainToken(n) + end_offset;
}
},
.while_cont => {
_, const extra_index = tree.nodeData(n).node_and_extra;
const extra = tree.extraData(extra_index, Node.WhileCont);
n = extra.then_expr;
},
.@"while" => {
_, const extra_index = tree.nodeData(n).node_and_extra;
const extra = tree.extraData(extra_index, Node.While);
n = extra.else_expr;
},
.@"if" => {
_, const extra_index = tree.nodeData(n).node_and_extra;
const extra = tree.extraData(extra_index, Node.If);
n = extra.else_expr;
},
.@"for" => {
const extra_index, const extra = tree.nodeData(n).@"for";
const index = @backingInt(extra_index) + extra.inputs + @intFromBool(extra.has_else);
n = @fromBackingInt(@intCast(tree.extra_data[index]));
},
.array_type_sentinel => {
_, const extra_index = tree.nodeData(n).node_and_extra;
const extra = tree.extraData(extra_index, Node.ArrayTypeSentinel);
n = extra.elem_type;
},
};
}
pub fn tokensOnSameLine(tree: Ast, token1: TokenIndex, token2: TokenIndex) bool {
const source = tree.source[tree.tokenStart(token1)..tree.tokenStart(token2)];
return mem.findScalar(u8, source, '\n') == null;
}
pub fn getNodeSource(tree: Ast, node: Node.Index) []const u8 {
const first_token = tree.firstToken(node);
const last_token = tree.lastToken(node);
const start = tree.tokenStart(first_token);
const end = tree.tokenStart(last_token) + tree.tokenSlice(last_token).len;
return tree.source[start..end];
}
pub fn globalVarDecl(tree: Ast, node: Node.Index) full.VarDecl {
assert(tree.nodeTag(node) == .global_var_decl);
const extra_index, const init_node = tree.nodeData(node).extra_and_opt_node;
const extra = tree.extraData(extra_index, Node.GlobalVarDecl);
return tree.fullVarDeclComponents(.{
.type_node = extra.type_node,
.align_node = extra.align_node,
.addrspace_node = extra.addrspace_node,
.section_node = extra.section_node,
.init_node = init_node,
.mut_token = tree.nodeMainToken(node),
});
}
pub fn localVarDecl(tree: Ast, node: Node.Index) full.VarDecl {
assert(tree.nodeTag(node) == .local_var_decl);
const extra_index, const init_node = tree.nodeData(node).extra_and_opt_node;
const extra = tree.extraData(extra_index, Node.LocalVarDecl);
return tree.fullVarDeclComponents(.{
.type_node = extra.type_node.toOptional(),
.align_node = extra.align_node.toOptional(),
.addrspace_node = .none,
.section_node = .none,
.init_node = init_node,
.mut_token = tree.nodeMainToken(node),
});
}
pub fn simpleVarDecl(tree: Ast, node: Node.Index) full.VarDecl {
assert(tree.nodeTag(node) == .simple_var_decl);
const type_node, const init_node = tree.nodeData(node).opt_node_and_opt_node;
return tree.fullVarDeclComponents(.{
.type_node = type_node,
.align_node = .none,
.addrspace_node = .none,
.section_node = .none,
.init_node = init_node,
.mut_token = tree.nodeMainToken(node),
});
}
pub fn alignedVarDecl(tree: Ast, node: Node.Index) full.VarDecl {
assert(tree.nodeTag(node) == .aligned_var_decl);
const align_node, const init_node = tree.nodeData(node).node_and_opt_node;
return tree.fullVarDeclComponents(.{
.type_node = .none,
.align_node = align_node.toOptional(),
.addrspace_node = .none,
.section_node = .none,
.init_node = init_node,
.mut_token = tree.nodeMainToken(node),
});
}
pub fn assignDestructure(tree: Ast, node: Node.Index) full.AssignDestructure {
const extra_index, const value_expr = tree.nodeData(node).extra_and_node;
const variable_count = tree.extra_data[@backingInt(extra_index)];
return tree.fullAssignDestructureComponents(.{
.variables = tree.extraDataSliceWithLen(@fromBackingInt(@intCast(@backingInt(extra_index) + 1)), variable_count, Node.Index),
.equal_token = tree.nodeMainToken(node),
.value_expr = value_expr,
});
}
pub fn ifSimple(tree: Ast, node: Node.Index) full.If {
assert(tree.nodeTag(node) == .if_simple);
const cond_expr, const then_expr = tree.nodeData(node).node_and_node;
return tree.fullIfComponents(.{
.cond_expr = cond_expr,
.then_expr = then_expr,
.else_expr = .none,
.if_token = tree.nodeMainToken(node),
});
}
pub fn ifFull(tree: Ast, node: Node.Index) full.If {
assert(tree.nodeTag(node) == .@"if");
const cond_expr, const extra_index = tree.nodeData(node).node_and_extra;
const extra = tree.extraData(extra_index, Node.If);
return tree.fullIfComponents(.{
.cond_expr = cond_expr,
.then_expr = extra.then_expr,
.else_expr = extra.else_expr.toOptional(),
.if_token = tree.nodeMainToken(node),
});
}
pub fn containerField(tree: Ast, node: Node.Index) full.ContainerField {
assert(tree.nodeTag(node) == .container_field);
const type_expr, const extra_index = tree.nodeData(node).node_and_extra;
const extra = tree.extraData(extra_index, Node.ContainerField);
const main_token = tree.nodeMainToken(node);
return tree.fullContainerFieldComponents(.{
.main_token = main_token,
.type_expr = type_expr.toOptional(),
.align_expr = extra.align_expr.toOptional(),
.value_expr = extra.value_expr.toOptional(),
.tuple_like = tree.tokenTag(main_token) != .identifier or
tree.tokenTag(main_token + 1) != .colon,
});
}
pub fn containerFieldInit(tree: Ast, node: Node.Index) full.ContainerField {
assert(tree.nodeTag(node) == .container_field_init);
const type_expr, const value_expr = tree.nodeData(node).node_and_opt_node;
const main_token = tree.nodeMainToken(node);
return tree.fullContainerFieldComponents(.{
.main_token = main_token,
.type_expr = type_expr.toOptional(),
.align_expr = .none,
.value_expr = value_expr,
.tuple_like = tree.tokenTag(main_token) != .identifier or
tree.tokenTag(main_token + 1) != .colon,
});
}
pub fn containerFieldAlign(tree: Ast, node: Node.Index) full.ContainerField {
assert(tree.nodeTag(node) == .container_field_align);
const type_expr, const align_expr = tree.nodeData(node).node_and_node;
const main_token = tree.nodeMainToken(node);
return tree.fullContainerFieldComponents(.{
.main_token = main_token,
.type_expr = type_expr.toOptional(),
.align_expr = align_expr.toOptional(),
.value_expr = .none,
.tuple_like = tree.tokenTag(main_token) != .identifier or
tree.tokenTag(main_token + 1) != .colon,
});
}
pub fn fnProtoSimple(tree: Ast, buffer: *[1]Node.Index, node: Node.Index) full.FnProto {
assert(tree.nodeTag(node) == .fn_proto_simple);
const first_param, const return_type = tree.nodeData(node).opt_node_and_opt_node;
const params = loadOptionalNodesIntoBuffer(1, buffer, .{first_param});
return tree.fullFnProtoComponents(.{
.proto_node = node,
.fn_token = tree.nodeMainToken(node),
.return_type = return_type,
.params = params,
.align_expr = .none,
.addrspace_expr = .none,
.section_expr = .none,
.callconv_expr = .none,
});
}
pub fn fnProtoMulti(tree: Ast, node: Node.Index) full.FnProto {
assert(tree.nodeTag(node) == .fn_proto_multi);
const extra_index, const return_type = tree.nodeData(node).extra_and_opt_node;
const params = tree.extraDataSlice(tree.extraData(extra_index, Node.SubRange), Node.Index);
return tree.fullFnProtoComponents(.{
.proto_node = node,
.fn_token = tree.nodeMainToken(node),
.return_type = return_type,
.params = params,
.align_expr = .none,
.addrspace_expr = .none,
.section_expr = .none,
.callconv_expr = .none,
});
}
pub fn fnProtoOne(tree: Ast, buffer: *[1]Node.Index, node: Node.Index) full.FnProto {
assert(tree.nodeTag(node) == .fn_proto_one);
const extra_index, const return_type = tree.nodeData(node).extra_and_opt_node;
const extra = tree.extraData(extra_index, Node.FnProtoOne);
const params = loadOptionalNodesIntoBuffer(1, buffer, .{extra.param});
return tree.fullFnProtoComponents(.{
.proto_node = node,
.fn_token = tree.nodeMainToken(node),
.return_type = return_type,
.params = params,
.align_expr = extra.align_expr,
.addrspace_expr = extra.addrspace_expr,
.section_expr = extra.section_expr,
.callconv_expr = extra.callconv_expr,
});
}
pub fn fnProto(tree: Ast, node: Node.Index) full.FnProto {
assert(tree.nodeTag(node) == .fn_proto);
const extra_index, const return_type = tree.nodeData(node).extra_and_opt_node;
const extra = tree.extraData(extra_index, Node.FnProto);
const params = tree.extraDataSlice(.{ .start = extra.params_start, .end = extra.params_end }, Node.Index);
return tree.fullFnProtoComponents(.{
.proto_node = node,
.fn_token = tree.nodeMainToken(node),
.return_type = return_type,
.params = params,
.align_expr = extra.align_expr,
.addrspace_expr = extra.addrspace_expr,
.section_expr = extra.section_expr,
.callconv_expr = extra.callconv_expr,
});
}
pub fn structInitOne(tree: Ast, buffer: *[1]Node.Index, node: Node.Index) full.StructInit {
assert(tree.nodeTag(node) == .struct_init_one or
tree.nodeTag(node) == .struct_init_one_comma);
const type_expr, const first_field = tree.nodeData(node).node_and_opt_node;
const fields = loadOptionalNodesIntoBuffer(1, buffer, .{first_field});
return .{
.ast = .{
.lbrace = tree.nodeMainToken(node),
.fields = fields,
.type_expr = type_expr.toOptional(),
},
};
}
pub fn structInitDotTwo(tree: Ast, buffer: *[2]Node.Index, node: Node.Index) full.StructInit {
assert(tree.nodeTag(node) == .struct_init_dot_two or
tree.nodeTag(node) == .struct_init_dot_two_comma);
const fields = loadOptionalNodesIntoBuffer(2, buffer, tree.nodeData(node).opt_node_and_opt_node);
return .{
.ast = .{
.lbrace = tree.nodeMainToken(node),
.fields = fields,
.type_expr = .none,
},
};
}
pub fn structInitDot(tree: Ast, node: Node.Index) full.StructInit {
assert(tree.nodeTag(node) == .struct_init_dot or
tree.nodeTag(node) == .struct_init_dot_comma);
const fields = tree.extraDataSlice(tree.nodeData(node).extra_range, Node.Index);
return .{
.ast = .{
.lbrace = tree.nodeMainToken(node),
.fields = fields,
.type_expr = .none,
},
};
}
pub fn structInit(tree: Ast, node: Node.Index) full.StructInit {
assert(tree.nodeTag(node) == .struct_init or
tree.nodeTag(node) == .struct_init_comma);
const type_expr, const extra_index = tree.nodeData(node).node_and_extra;
const fields = tree.extraDataSlice(tree.extraData(extra_index, Node.SubRange), Node.Index);
return .{
.ast = .{
.lbrace = tree.nodeMainToken(node),
.fields = fields,
.type_expr = type_expr.toOptional(),
},
};
}
pub fn arrayInitOne(tree: Ast, buffer: *[1]Node.Index, node: Node.Index) full.ArrayInit {
assert(tree.nodeTag(node) == .array_init_one or
tree.nodeTag(node) == .array_init_one_comma);
const type_expr, buffer[0] = tree.nodeData(node).node_and_node;
return .{
.ast = .{
.lbrace = tree.nodeMainToken(node),
.elements = buffer[0..1],
.type_expr = type_expr.toOptional(),
},
};
}
pub fn arrayInitDotTwo(tree: Ast, buffer: *[2]Node.Index, node: Node.Index) full.ArrayInit {
assert(tree.nodeTag(node) == .array_init_dot_two or
tree.nodeTag(node) == .array_init_dot_two_comma);
const elements = loadOptionalNodesIntoBuffer(2, buffer, tree.nodeData(node).opt_node_and_opt_node);
return .{
.ast = .{
.lbrace = tree.nodeMainToken(node),
.elements = elements,
.type_expr = .none,
},
};
}
pub fn arrayInitDot(tree: Ast, node: Node.Index) full.ArrayInit {
assert(tree.nodeTag(node) == .array_init_dot or
tree.nodeTag(node) == .array_init_dot_comma);
const elements = tree.extraDataSlice(tree.nodeData(node).extra_range, Node.Index);
return .{
.ast = .{
.lbrace = tree.nodeMainToken(node),
.elements = elements,
.type_expr = .none,
},
};
}
pub fn arrayInit(tree: Ast, node: Node.Index) full.ArrayInit {
assert(tree.nodeTag(node) == .array_init or
tree.nodeTag(node) == .array_init_comma);
const type_expr, const extra_index = tree.nodeData(node).node_and_extra;
const elements = tree.extraDataSlice(tree.extraData(extra_index, Node.SubRange), Node.Index);
return .{
.ast = .{
.lbrace = tree.nodeMainToken(node),
.elements = elements,
.type_expr = type_expr.toOptional(),
},
};
}
pub fn arrayType(tree: Ast, node: Node.Index) full.ArrayType {
assert(tree.nodeTag(node) == .array_type);
const elem_count, const elem_type = tree.nodeData(node).node_and_node;
return .{
.ast = .{
.lbracket = tree.nodeMainToken(node),
.elem_count = elem_count,
.sentinel = .none,
.elem_type = elem_type,
},
};
}
pub fn arrayTypeSentinel(tree: Ast, node: Node.Index) full.ArrayType {
assert(tree.nodeTag(node) == .array_type_sentinel);
const elem_count, const extra_index = tree.nodeData(node).node_and_extra;
const extra = tree.extraData(extra_index, Node.ArrayTypeSentinel);
return .{
.ast = .{
.lbracket = tree.nodeMainToken(node),
.elem_count = elem_count,
.sentinel = extra.sentinel.toOptional(),
.elem_type = extra.elem_type,
},
};
}
pub fn ptrTypeAligned(tree: Ast, node: Node.Index) full.PtrType {
assert(tree.nodeTag(node) == .ptr_type_aligned);
const align_node, const child_type = tree.nodeData(node).opt_node_and_node;
return tree.fullPtrTypeComponents(.{
.main_token = tree.nodeMainToken(node),
.align_node = align_node,
.addrspace_node = .none,
.sentinel = .none,
.bit_range_start = .none,
.bit_range_end = .none,
.child_type = child_type,
});
}
pub fn ptrTypeSentinel(tree: Ast, node: Node.Index) full.PtrType {
assert(tree.nodeTag(node) == .ptr_type_sentinel);
const sentinel, const child_type = tree.nodeData(node).opt_node_and_node;
return tree.fullPtrTypeComponents(.{
.main_token = tree.nodeMainToken(node),
.align_node = .none,
.addrspace_node = .none,
.sentinel = sentinel,
.bit_range_start = .none,
.bit_range_end = .none,
.child_type = child_type,
});
}
pub fn ptrType(tree: Ast, node: Node.Index) full.PtrType {
assert(tree.nodeTag(node) == .ptr_type);
const extra_index, const child_type = tree.nodeData(node).extra_and_node;
const extra = tree.extraData(extra_index, Node.PtrType);
return tree.fullPtrTypeComponents(.{
.main_token = tree.nodeMainToken(node),
.align_node = extra.align_node,
.addrspace_node = extra.addrspace_node,
.sentinel = extra.sentinel,
.bit_range_start = .none,
.bit_range_end = .none,
.child_type = child_type,
});
}
pub fn ptrTypeBitRange(tree: Ast, node: Node.Index) full.PtrType {
assert(tree.nodeTag(node) == .ptr_type_bit_range);
const extra_index, const child_type = tree.nodeData(node).extra_and_node;
const extra = tree.extraData(extra_index, Node.PtrTypeBitRange);
return tree.fullPtrTypeComponents(.{
.main_token = tree.nodeMainToken(node),
.align_node = extra.align_node.toOptional(),
.addrspace_node = extra.addrspace_node,
.sentinel = extra.sentinel,
.bit_range_start = extra.bit_range_start.toOptional(),
.bit_range_end = extra.bit_range_end.toOptional(),
.child_type = child_type,
});
}
pub fn sliceOpen(tree: Ast, node: Node.Index) full.Slice {
assert(tree.nodeTag(node) == .slice_open);
const sliced, const start = tree.nodeData(node).node_and_node;
return .{
.ast = .{
.sliced = sliced,
.lbracket = tree.nodeMainToken(node),
.start = start,
.end = .none,
.sentinel = .none,
},
};
}
pub fn slice(tree: Ast, node: Node.Index) full.Slice {
assert(tree.nodeTag(node) == .slice);
const sliced, const extra_index = tree.nodeData(node).node_and_extra;
const extra = tree.extraData(extra_index, Node.Slice);
return .{
.ast = .{
.sliced = sliced,
.lbracket = tree.nodeMainToken(node),
.start = extra.start,
.end = extra.end.toOptional(),
.sentinel = .none,
},
};
}
pub fn sliceSentinel(tree: Ast, node: Node.Index) full.Slice {
assert(tree.nodeTag(node) == .slice_sentinel);
const sliced, const extra_index = tree.nodeData(node).node_and_extra;
const extra = tree.extraData(extra_index, Node.SliceSentinel);
return .{
.ast = .{
.sliced = sliced,
.lbracket = tree.nodeMainToken(node),
.start = extra.start,
.end = extra.end,
.sentinel = extra.sentinel.toOptional(),
},
};
}
pub fn containerDeclTwo(tree: Ast, buffer: *[2]Node.Index, node: Node.Index) full.ContainerDecl {
assert(tree.nodeTag(node) == .container_decl_two or
tree.nodeTag(node) == .container_decl_two_trailing);
const members = loadOptionalNodesIntoBuffer(2, buffer, tree.nodeData(node).opt_node_and_opt_node);
return tree.fullContainerDeclComponents(.{
.main_token = tree.nodeMainToken(node),
.enum_token = null,
.members = members,
.arg = .none,
});
}
pub fn containerDecl(tree: Ast, node: Node.Index) full.ContainerDecl {
assert(tree.nodeTag(node) == .container_decl or
tree.nodeTag(node) == .container_decl_trailing);
const members = tree.extraDataSlice(tree.nodeData(node).extra_range, Node.Index);
return tree.fullContainerDeclComponents(.{
.main_token = tree.nodeMainToken(node),
.enum_token = null,
.members = members,
.arg = .none,
});
}
pub fn containerDeclArg(tree: Ast, node: Node.Index) full.ContainerDecl {
assert(tree.nodeTag(node) == .container_decl_arg or
tree.nodeTag(node) == .container_decl_arg_trailing);
const arg, const extra_index = tree.nodeData(node).node_and_extra;
const members = tree.extraDataSlice(tree.extraData(extra_index, Node.SubRange), Node.Index);
return tree.fullContainerDeclComponents(.{
.main_token = tree.nodeMainToken(node),
.enum_token = null,
.members = members,
.arg = arg.toOptional(),
});
}
pub fn containerDeclRoot(tree: Ast) full.ContainerDecl {
return .{
.layout_token = null,
.ast = .{
.main_token = 0,
.enum_token = null,
.members = tree.rootDecls(),
.arg = .none,
},
};
}
pub fn taggedUnionTwo(tree: Ast, buffer: *[2]Node.Index, node: Node.Index) full.ContainerDecl {
assert(tree.nodeTag(node) == .tagged_union_two or
tree.nodeTag(node) == .tagged_union_two_trailing);
const members = loadOptionalNodesIntoBuffer(2, buffer, tree.nodeData(node).opt_node_and_opt_node);
const main_token = tree.nodeMainToken(node);
return tree.fullContainerDeclComponents(.{
.main_token = main_token,
.enum_token = main_token + 2, // union 左括号 enum
.members = members,
.arg = .none,
});
}
pub fn taggedUnion(tree: Ast, node: Node.Index) full.ContainerDecl {
assert(tree.nodeTag(node) == .tagged_union or
tree.nodeTag(node) == .tagged_union_trailing);
const members = tree.extraDataSlice(tree.nodeData(node).extra_range, Node.Index);
const main_token = tree.nodeMainToken(node);
return tree.fullContainerDeclComponents(.{
.main_token = main_token,
.enum_token = main_token + 2, // union 左括号 enum
.members = members,
.arg = .none,
});
}
pub fn taggedUnionEnumTag(tree: Ast, node: Node.Index) full.ContainerDecl {
assert(tree.nodeTag(node) == .tagged_union_enum_tag or
tree.nodeTag(node) == .tagged_union_enum_tag_trailing);
const arg, const extra_index = tree.nodeData(node).node_and_extra;
const members = tree.extraDataSlice(tree.extraData(extra_index, Node.SubRange), Node.Index);
const main_token = tree.nodeMainToken(node);
return tree.fullContainerDeclComponents(.{
.main_token = main_token,
.enum_token = main_token + 2, // union 左括号 enum
.members = members,
.arg = arg.toOptional(),
});
}
pub fn switchFull(tree: Ast, node: Node.Index) full.Switch {
const main_token = tree.nodeMainToken(node);
const switch_token: TokenIndex, const label_token: ?TokenIndex = switch (tree.tokenTag(main_token)) {
.identifier => .{ main_token + 2, main_token },
.keyword_switch => .{ main_token, null },
else => unreachable,
};
const condition, const extra_index = tree.nodeData(node).node_and_extra;
const cases = tree.extraDataSlice(tree.extraData(extra_index, Ast.Node.SubRange), Node.Index);
return .{
.ast = .{
.switch_token = switch_token,
.condition = condition,
.cases = cases,
},
.label_token = label_token,
};
}
pub fn switchCaseOne(tree: Ast, node: Node.Index) full.SwitchCase {
const first_value, const target_expr = tree.nodeData(node).opt_node_and_node;
return tree.fullSwitchCaseComponents(.{
.values = if (first_value == .none)
&.{}
else
// 确保返回的切片指向 Ast 已有的内存。
(@as(*const Node.Index, @ptrCast(&tree.nodes.items(.data)[@backingInt(node)].opt_node_and_node[0])))[0..1],
.arrow_token = tree.nodeMainToken(node),
.target_expr = target_expr,
}, node);
}
pub fn switchCase(tree: Ast, node: Node.Index) full.SwitchCase {
const extra_index, const target_expr = tree.nodeData(node).extra_and_node;
const values = tree.extraDataSlice(tree.extraData(extra_index, Node.SubRange), Node.Index);
return tree.fullSwitchCaseComponents(.{
.values = values,
.arrow_token = tree.nodeMainToken(node),
.target_expr = target_expr,
}, node);
}
pub fn asmSimple(tree: Ast, node: Node.Index) full.Asm {
const template, const rparen = tree.nodeData(node).node_and_token;
return tree.fullAsmComponents(.{
.asm_token = tree.nodeMainToken(node),
.template = template,
.items = &.{},
.rparen = rparen,
.clobbers = .none,
});
}
pub fn asmFull(tree: Ast, node: Node.Index) full.Asm {
const template, const extra_index = tree.nodeData(node).node_and_extra;
const extra = tree.extraData(extra_index, Node.Asm);
const items = tree.extraDataSlice(.{ .start = extra.items_start, .end = extra.items_end }, Node.Index);
return tree.fullAsmComponents(.{
.asm_token = tree.nodeMainToken(node),
.template = template,
.items = items,
.clobbers = extra.clobbers,
.rparen = extra.rparen,
});
}
pub fn whileSimple(tree: Ast, node: Node.Index) full.While {
const cond_expr, const then_expr = tree.nodeData(node).node_and_node;
return tree.fullWhileComponents(.{
.while_token = tree.nodeMainToken(node),
.cond_expr = cond_expr,
.cont_expr = .none,
.then_expr = then_expr,
.else_expr = .none,
});
}
pub fn whileCont(tree: Ast, node: Node.Index) full.While {
const cond_expr, const extra_index = tree.nodeData(node).node_and_extra;
const extra = tree.extraData(extra_index, Node.WhileCont);
return tree.fullWhileComponents(.{
.while_token = tree.nodeMainToken(node),
.cond_expr = cond_expr,
.cont_expr = extra.cont_expr.toOptional(),
.then_expr = extra.then_expr,
.else_expr = .none,
});
}
pub fn whileFull(tree: Ast, node: Node.Index) full.While {
const cond_expr, const extra_index = tree.nodeData(node).node_and_extra;
const extra = tree.extraData(extra_index, Node.While);
return tree.fullWhileComponents(.{
.while_token = tree.nodeMainToken(node),
.cond_expr = cond_expr,
.cont_expr = extra.cont_expr,
.then_expr = extra.then_expr,
.else_expr = extra.else_expr.toOptional(),
});
}
pub fn forSimple(tree: Ast, node: Node.Index) full.For {
const data = &tree.nodes.items(.data)[@backingInt(node)].node_and_node;
return tree.fullForComponents(.{
.for_token = tree.nodeMainToken(node),
.inputs = (&data[0])[0..1],
.then_expr = data[1],
.else_expr = .none,
});
}
pub fn forFull(tree: Ast, node: Node.Index) full.For {
const extra_index, const extra = tree.nodeData(node).@"for";
const inputs = tree.extraDataSliceWithLen(extra_index, extra.inputs, Node.Index);
const then_expr: Node.Index = @fromBackingInt(@intCast(tree.extra_data[@backingInt(extra_index) + extra.inputs]));
const else_expr: Node.OptionalIndex = if (extra.has_else) @fromBackingInt(@intCast(tree.extra_data[@backingInt(extra_index) + extra.inputs + 1])) else .none;
return tree.fullForComponents(.{
.for_token = tree.nodeMainToken(node),
.inputs = inputs,
.then_expr = then_expr,
.else_expr = else_expr,
});
}
pub fn callOne(tree: Ast, buffer: *[1]Node.Index, node: Node.Index) full.Call {
const fn_expr, const first_param = tree.nodeData(node).node_and_opt_node;
const params = loadOptionalNodesIntoBuffer(1, buffer, .{first_param});
return .{ .ast = .{
.lparen = tree.nodeMainToken(node),
.fn_expr = fn_expr,
.params = params,
} };
}
pub fn callFull(tree: Ast, node: Node.Index) full.Call {
const fn_expr, const extra_index = tree.nodeData(node).node_and_extra;
const params = tree.extraDataSlice(tree.extraData(extra_index, Node.SubRange), Node.Index);
return .{ .ast = .{
.lparen = tree.nodeMainToken(node),
.fn_expr = fn_expr,
.params = params,
} };
}
fn fullVarDeclComponents(tree: Ast, info: full.VarDecl.Components) full.VarDecl {
var result: full.VarDecl = .{
.ast = info,
.visib_token = null,
.extern_export_token = null,
.lib_name = null,
.threadlocal_token = null,
.comptime_token = null,
};
var i = info.mut_token;
while (i > 0) {
i -= 1;
switch (tree.tokenTag(i)) {
.keyword_extern, .keyword_export => result.extern_export_token = i,
.keyword_comptime => result.comptime_token = i,
.keyword_pub => result.visib_token = i,
.keyword_threadlocal => result.threadlocal_token = i,
.string_literal => result.lib_name = i,
else => break,
}
}
return result;
}
fn fullAssignDestructureComponents(tree: Ast, info: full.AssignDestructure.Components) full.AssignDestructure {
var result: full.AssignDestructure = .{
.comptime_token = null,
.ast = info,
};
const first_variable_token = tree.firstToken(info.variables[0]);
const maybe_comptime_token = switch (tree.nodeTag(info.variables[0])) {
.global_var_decl,
.local_var_decl,
.aligned_var_decl,
.simple_var_decl,
=> first_variable_token,
else => first_variable_token - 1,
};
if (tree.tokenTag(maybe_comptime_token) == .keyword_comptime) {
result.comptime_token = maybe_comptime_token;
}
return result;
}
fn fullIfComponents(tree: Ast, info: full.If.Components) full.If {
var result: full.If = .{
.ast = info,
.payload_token = null,
.error_token = null,
.else_token = undefined,
};
// if (cond_expr) |x|
// ^ ^
const payload_pipe = tree.lastToken(info.cond_expr) + 2;
if (tree.tokenTag(payload_pipe) == .pipe) {
result.payload_token = payload_pipe + 1;
}
if (info.else_expr != .none) {
// then_expr else |x|
// ^ ^
result.else_token = tree.lastToken(info.then_expr) + 1;
if (tree.tokenTag(result.else_token + 1) == .pipe) {
result.error_token = result.else_token + 2;
}
}
return result;
}
fn fullContainerFieldComponents(tree: Ast, info: full.ContainerField.Components) full.ContainerField {
var result: full.ContainerField = .{
.ast = info,
.comptime_token = null,
};
if (tree.isTokenPrecededByTags(info.main_token, &.{.keyword_comptime})) {
// comptime type = init,
// ^ ^
// comptime name: type = init,
// ^ ^
result.comptime_token = info.main_token - 1;
}
return result;
}
fn fullFnProtoComponents(tree: Ast, info: full.FnProto.Components) full.FnProto {
var result: full.FnProto = .{
.ast = info,
.visib_token = null,
.extern_export_inline_token = null,
.lib_name = null,
.name_token = null,
.lparen = undefined,
};
var i = info.fn_token;
while (i > 0) {
i -= 1;
switch (tree.tokenTag(i)) {
.keyword_extern,
.keyword_export,
.keyword_inline,
.keyword_noinline,
=> result.extern_export_inline_token = i,
.keyword_pub => result.visib_token = i,
.string_literal => result.lib_name = i,
else => break,
}
}
const after_fn_token = info.fn_token + 1;
if (tree.tokenTag(after_fn_token) == .identifier) {
result.name_token = after_fn_token;
result.lparen = after_fn_token + 1;
} else {
result.lparen = after_fn_token;
}
assert(tree.tokenTag(result.lparen) == .l_paren);
return result;
}
fn fullPtrTypeComponents(tree: Ast, info: full.PtrType.Components) full.PtrType {
const size: std.lang.Type.Pointer.Size = switch (tree.tokenTag(info.main_token)) {
.asterisk => .one,
.l_bracket => switch (tree.tokenTag(info.main_token + 1)) {
.asterisk => if (tree.tokenTag(info.main_token + 2) == .identifier) .c else .many,
else => .slice,
},
else => unreachable,
};
var result: full.PtrType = .{
.size = size,
.allowzero_token = null,
.const_token = null,
.volatile_token = null,
.duplicate_token = null,
.ast = info,
};
// 查找修饰符时,务必避免在此处遍历任何子表达式,
// 否则可能误判。
// 因此,如有哨兵,则从其后开始,
// 并跳过所有 align 节点及位范围节点。
var i = (if (info.sentinel.unwrap()) |sentinel| tree.lastToken(sentinel) + 1 else switch (size) {
.one => info.main_token,
.slice => info.main_token + 1,
.many => info.main_token + 2,
.c => info.main_token + 3,
}) + 1;
const end = tree.firstToken(info.child_type);
while (i < end) : (i += 1) {
switch (tree.tokenTag(i)) {
.keyword_allowzero => {
if (result.allowzero_token != null) {
result.duplicate_token = i;
}
result.allowzero_token = i;
},
.keyword_const => {
if (result.const_token != null) {
result.duplicate_token = i;
}
result.const_token = i;
},
.keyword_volatile => {
if (result.volatile_token != null) {
result.duplicate_token = i;
}
result.volatile_token = i;
},
.keyword_align => {
if (info.bit_range_end.unwrap()) |bit_range_end| {
assert(info.bit_range_start != .none);
i = tree.lastToken(bit_range_end) + 1;
} else if (info.align_node.unwrap()) |align_node| {
i = tree.lastToken(align_node) + 1;
} else unreachable;
},
.keyword_addrspace => i = tree.lastToken(info.addrspace_node.unwrap().?) + 1,
else => unreachable,
}
}
return result;
}
fn fullContainerDeclComponents(tree: Ast, info: full.ContainerDecl.Components) full.ContainerDecl {
var result: full.ContainerDecl = .{
.ast = info,
.layout_token = null,
};
if (info.main_token == 0) return result; // .root
const previous_token = info.main_token - 1;
switch (tree.tokenTag(previous_token)) {
.keyword_extern, .keyword_packed => result.layout_token = previous_token,
else => {},
}
return result;
}
fn fullSwitchComponents(tree: Ast, info: full.Switch.Components) full.Switch {
const tok_i = info.switch_token -| 1;
var result: full.Switch = .{
.ast = info,
.label_token = null,
};
if (tree.tokenTag(tok_i) == .colon and
tree.tokenTag(tok_i -| 1) == .identifier)
{
result.label_token = tok_i - 1;
}
return result;
}
fn fullSwitchCaseComponents(tree: Ast, info: full.SwitchCase.Components, node: Node.Index) full.SwitchCase {
var result: full.SwitchCase = .{
.ast = info,
.payload_token = null,
.inline_token = null,
};
if (tree.tokenTag(info.arrow_token + 1) == .pipe) {
result.payload_token = info.arrow_token + 2;
}
result.inline_token = switch (tree.nodeTag(node)) {
.switch_case_inline, .switch_case_inline_one => if (result.ast.values.len == 0)
info.arrow_token - 2
else
tree.firstToken(result.ast.values[0]) - 1,
else => null,
};
return result;
}
fn fullAsmComponents(tree: Ast, info: full.Asm.Components) full.Asm {
var result: full.Asm = .{
.ast = info,
.volatile_token = null,
.inputs = &.{},
.outputs = &.{},
};
if (tree.tokenTag(info.asm_token + 1) == .keyword_volatile) {
result.volatile_token = info.asm_token + 1;
}
const outputs_end: usize = for (info.items, 0..) |item, i| {
switch (tree.nodeTag(item)) {
.asm_output => continue,
else => break i,
}
} else info.items.len;
result.outputs = info.items[0..outputs_end];
result.inputs = info.items[outputs_end..];
return result;
}
fn fullWhileComponents(tree: Ast, info: full.While.Components) full.While {
var result: full.While = .{
.ast = info,
.inline_token = null,
.label_token = null,
.payload_token = null,
.else_token = undefined,
.error_token = null,
};
var tok_i = info.while_token;
if (tree.isTokenPrecededByTags(tok_i, &.{.keyword_inline})) {
result.inline_token = tok_i - 1;
tok_i = tok_i - 1;
}
if (tree.isTokenPrecededByTags(tok_i, &.{ .identifier, .colon })) {
result.label_token = tok_i - 2;
}
const last_cond_token = tree.lastToken(info.cond_expr);
if (tree.tokenTag(last_cond_token + 2) == .pipe) {
result.payload_token = last_cond_token + 3;
}
if (info.else_expr != .none) {
// then_expr else |x|
// ^ ^
result.else_token = tree.lastToken(info.then_expr) + 1;
if (tree.tokenTag(result.else_token + 1) == .pipe) {
result.error_token = result.else_token + 2;
}
}
return result;
}
fn fullForComponents(tree: Ast, info: full.For.Components) full.For {
var result: full.For = .{
.ast = info,
.inline_token = null,
.label_token = null,
.payload_token = undefined,
.else_token = undefined,
};
var tok_i = info.for_token;
if (tree.isTokenPrecededByTags(tok_i, &.{.keyword_inline})) {
result.inline_token = tok_i - 1;
tok_i = tok_i - 1;
}
if (tree.isTokenPrecededByTags(tok_i, &.{ .identifier, .colon })) {
result.label_token = tok_i - 2;
}
const last_cond_token = tree.lastToken(info.inputs[info.inputs.len - 1]);
result.payload_token = last_cond_token + @as(u32, 3) + @intFromBool(tree.tokenTag(last_cond_token + 1) == .comma);
if (info.else_expr != .none) {
result.else_token = tree.lastToken(info.then_expr) + 1;
}
return result;
}
pub fn fullVarDecl(tree: Ast, node: Node.Index) ?full.VarDecl {
return switch (tree.nodeTag(node)) {
.global_var_decl => tree.globalVarDecl(node),
.local_var_decl => tree.localVarDecl(node),
.aligned_var_decl => tree.alignedVarDecl(node),
.simple_var_decl => tree.simpleVarDecl(node),
else => null,
};
}
pub fn fullIf(tree: Ast, node: Node.Index) ?full.If {
return switch (tree.nodeTag(node)) {
.if_simple => tree.ifSimple(node),
.@"if" => tree.ifFull(node),
else => null,
};
}
pub fn fullWhile(tree: Ast, node: Node.Index) ?full.While {
return switch (tree.nodeTag(node)) {
.while_simple => tree.whileSimple(node),
.while_cont => tree.whileCont(node),
.@"while" => tree.whileFull(node),
else => null,
};
}
pub fn fullFor(tree: Ast, node: Node.Index) ?full.For {
return switch (tree.nodeTag(node)) {
.for_simple => tree.forSimple(node),
.@"for" => tree.forFull(node),
else => null,
};
}
pub fn fullContainerField(tree: Ast, node: Node.Index) ?full.ContainerField {
return switch (tree.nodeTag(node)) {
.container_field_init => tree.containerFieldInit(node),
.container_field_align => tree.containerFieldAlign(node),
.container_field => tree.containerField(node),
else => null,
};
}
pub fn fullFnProto(tree: Ast, buffer: *[1]Ast.Node.Index, node: Node.Index) ?full.FnProto {
return switch (tree.nodeTag(node)) {
.fn_proto => tree.fnProto(node),
.fn_proto_multi => tree.fnProtoMulti(node),
.fn_proto_one => tree.fnProtoOne(buffer, node),
.fn_proto_simple => tree.fnProtoSimple(buffer, node),
.fn_decl => tree.fullFnProto(buffer, tree.nodeData(node).node_and_node[0]),
else => null,
};
}
pub fn fullStructInit(tree: Ast, buffer: *[2]Ast.Node.Index, node: Node.Index) ?full.StructInit {
return switch (tree.nodeTag(node)) {
.struct_init_one, .struct_init_one_comma => tree.structInitOne(buffer[0..1], node),
.struct_init_dot_two, .struct_init_dot_two_comma => tree.structInitDotTwo(buffer, node),
.struct_init_dot, .struct_init_dot_comma => tree.structInitDot(node),
.struct_init, .struct_init_comma => tree.structInit(node),
else => null,
};
}
pub fn fullArrayInit(tree: Ast, buffer: *[2]Node.Index, node: Node.Index) ?full.ArrayInit {
return switch (tree.nodeTag(node)) {
.array_init_one, .array_init_one_comma => tree.arrayInitOne(buffer[0..1], node),
.array_init_dot_two, .array_init_dot_two_comma => tree.arrayInitDotTwo(buffer, node),
.array_init_dot, .array_init_dot_comma => tree.arrayInitDot(node),
.array_init, .array_init_comma => tree.arrayInit(node),
else => null,
};
}
pub fn fullArrayType(tree: Ast, node: Node.Index) ?full.ArrayType {
return switch (tree.nodeTag(node)) {
.array_type => tree.arrayType(node),
.array_type_sentinel => tree.arrayTypeSentinel(node),
else => null,
};
}
pub fn fullPtrType(tree: Ast, node: Node.Index) ?full.PtrType {
return switch (tree.nodeTag(node)) {
.ptr_type_aligned => tree.ptrTypeAligned(node),
.ptr_type_sentinel => tree.ptrTypeSentinel(node),
.ptr_type => tree.ptrType(node),
.ptr_type_bit_range => tree.ptrTypeBitRange(node),
else => null,
};
}
pub fn fullSlice(tree: Ast, node: Node.Index) ?full.Slice {
return switch (tree.nodeTag(node)) {
.slice_open => tree.sliceOpen(node),
.slice => tree.slice(node),
.slice_sentinel => tree.sliceSentinel(node),
else => null,
};
}
pub fn fullContainerDecl(tree: Ast, buffer: *[2]Ast.Node.Index, node: Node.Index) ?full.ContainerDecl {
return switch (tree.nodeTag(node)) {
.root => tree.containerDeclRoot(),
.container_decl, .container_decl_trailing => tree.containerDecl(node),
.container_decl_arg, .container_decl_arg_trailing => tree.containerDeclArg(node),
.container_decl_two, .container_decl_two_trailing => tree.containerDeclTwo(buffer, node),
.tagged_union, .tagged_union_trailing => tree.taggedUnion(node),
.tagged_union_enum_tag, .tagged_union_enum_tag_trailing => tree.taggedUnionEnumTag(node),
.tagged_union_two, .tagged_union_two_trailing => tree.taggedUnionTwo(buffer, node),
else => null,
};
}
pub fn fullSwitch(tree: Ast, node: Node.Index) ?full.Switch {
return switch (tree.nodeTag(node)) {
.@"switch", .switch_comma => tree.switchFull(node),
else => null,
};
}
pub fn fullSwitchCase(tree: Ast, node: Node.Index) ?full.SwitchCase {
return switch (tree.nodeTag(node)) {
.switch_case_one, .switch_case_inline_one => tree.switchCaseOne(node),
.switch_case, .switch_case_inline => tree.switchCase(node),
else => null,
};
}
pub fn fullAsm(tree: Ast, node: Node.Index) ?full.Asm {
return switch (tree.nodeTag(node)) {
.asm_simple => tree.asmSimple(node),
.@"asm" => tree.asmFull(node),
else => null,
};
}
pub fn fullCall(tree: Ast, buffer: *[1]Ast.Node.Index, node: Node.Index) ?full.Call {
return switch (tree.nodeTag(node)) {
.call, .call_comma => tree.callFull(node),
.call_one, .call_one_comma => tree.callOne(buffer, node),
else => null,
};
}
pub fn builtinCallParams(tree: Ast, buffer: *[2]Ast.Node.Index, node: Ast.Node.Index) ?[]const Node.Index {
return switch (tree.nodeTag(node)) {
.builtin_call_two, .builtin_call_two_comma => loadOptionalNodesIntoBuffer(2, buffer, tree.nodeData(node).opt_node_and_opt_node),
.builtin_call, .builtin_call_comma => tree.extraDataSlice(tree.nodeData(node).extra_range, Node.Index),
else => null,
};
}
pub fn blockStatements(tree: Ast, buffer: *[2]Ast.Node.Index, node: Ast.Node.Index) ?[]const Node.Index {
return switch (tree.nodeTag(node)) {
.block_two, .block_two_semicolon => loadOptionalNodesIntoBuffer(2, buffer, tree.nodeData(node).opt_node_and_opt_node),
.block, .block_semicolon => tree.extraDataSlice(tree.nodeData(node).extra_range, Node.Index),
else => null,
};
}
/// 完整组装的 AST 节点信息。
pub const full = struct {
pub const VarDecl = struct {
visib_token: ?TokenIndex,
extern_export_token: ?TokenIndex,
lib_name: ?TokenIndex,
threadlocal_token: ?TokenIndex,
comptime_token: ?TokenIndex,
ast: Components,
pub const Components = struct {
mut_token: TokenIndex,
type_node: Node.OptionalIndex,
align_node: Node.OptionalIndex,
addrspace_node: Node.OptionalIndex,
section_node: Node.OptionalIndex,
init_node: Node.OptionalIndex,
};
pub fn firstToken(var_decl: VarDecl) TokenIndex {
return var_decl.visib_token orelse
var_decl.extern_export_token orelse
var_decl.threadlocal_token orelse
var_decl.comptime_token orelse
var_decl.ast.mut_token;
}
};
pub const AssignDestructure = struct {
comptime_token: ?TokenIndex,
ast: Components,
pub const Components = struct {
variables: []const Node.Index,
equal_token: TokenIndex,
value_expr: Node.Index,
};
};
pub const If = struct {
/// 指向 `|` 之后的第一个 token。它要么是标识符,要么
/// 是 `*`(后面紧接一个标识符)。
payload_token: ?TokenIndex,
/// 指向 `|` 后的标识符。
error_token: ?TokenIndex,
/// 仅当 else_expr != .none 时填充。
else_token: TokenIndex,
ast: Components,
pub const Components = struct {
if_token: TokenIndex,
cond_expr: Node.Index,
then_expr: Node.Index,
else_expr: Node.OptionalIndex,
};
};
pub const While = struct {
ast: Components,
inline_token: ?TokenIndex,
label_token: ?TokenIndex,
payload_token: ?TokenIndex,
error_token: ?TokenIndex,
/// 仅当 else_expr != none 时填充。
else_token: TokenIndex,
pub const Components = struct {
while_token: TokenIndex,
cond_expr: Node.Index,
cont_expr: Node.OptionalIndex,
then_expr: Node.Index,
else_expr: Node.OptionalIndex,
};
};
pub const For = struct {
ast: Components,
inline_token: ?TokenIndex,
label_token: ?TokenIndex,
payload_token: TokenIndex,
/// 仅当 else_expr != .none 时填充。
else_token: ?TokenIndex,
pub const Components = struct {
for_token: TokenIndex,
inputs: []const Node.Index,
then_expr: Node.Index,
else_expr: Node.OptionalIndex,
};
};
pub const ContainerField = struct {
comptime_token: ?TokenIndex,
ast: Components,
pub const Components = struct {
main_token: TokenIndex,
/// 仅在调用 `convertToNonTupleLike` 后才可为 `.none`。
type_expr: Node.OptionalIndex,
align_expr: Node.OptionalIndex,
value_expr: Node.OptionalIndex,
tuple_like: bool,
};
pub fn firstToken(cf: ContainerField) TokenIndex {
return cf.comptime_token orelse cf.ast.main_token;
}
pub fn convertToNonTupleLike(cf: *ContainerField, tree: *const Ast) void {
if (!cf.ast.tuple_like) return;
if (tree.nodeTag(cf.ast.type_expr.unwrap().?) != .identifier) return;
cf.ast.type_expr = .none;
cf.ast.tuple_like = false;
}
};
pub const FnProto = struct {
visib_token: ?TokenIndex,
extern_export_inline_token: ?TokenIndex,
lib_name: ?TokenIndex,
name_token: ?TokenIndex,
lparen: TokenIndex,
ast: Components,
pub const Components = struct {
proto_node: Node.Index,
fn_token: TokenIndex,
return_type: Node.OptionalIndex,
params: []const Node.Index,
align_expr: Node.OptionalIndex,
addrspace_expr: Node.OptionalIndex,
section_expr: Node.OptionalIndex,
callconv_expr: Node.OptionalIndex,
};
pub const Param = struct {
first_doc_comment: ?TokenIndex,
name_token: ?TokenIndex,
comptime_noalias: ?TokenIndex,
anytype_ellipsis3: ?TokenIndex,
type_expr: ?Node.Index,
};
pub fn firstToken(fn_proto: FnProto) TokenIndex {
return fn_proto.visib_token orelse
fn_proto.extern_export_inline_token orelse
fn_proto.ast.fn_token;
}
/// 对 anytype 和 ... 不包含在 params 切片中这一事实进行抽象,
/// 因为它们只是简单标识符,
/// 并非子表达式。
pub const Iterator = struct {
tree: *const Ast,
fn_proto: *const FnProto,
param_i: usize,
tok_i: TokenIndex,
tok_flag: bool,
pub fn next(it: *Iterator) ?Param {
const tree = it.tree;
while (true) {
var first_doc_comment: ?TokenIndex = null;
var comptime_noalias: ?TokenIndex = null;
var name_token: ?TokenIndex = null;
if (!it.tok_flag) {
if (it.param_i >= it.fn_proto.ast.params.len) {
return null;
}
const param_type = it.fn_proto.ast.params[it.param_i];
var tok_i = tree.firstToken(param_type) - 1;
while (true) : (tok_i -= 1) switch (tree.tokenTag(tok_i)) {
.colon => continue,
.identifier => name_token = tok_i,
.doc_comment => first_doc_comment = tok_i,
.keyword_comptime, .keyword_noalias => comptime_noalias = tok_i,
else => break,
};
it.param_i += 1;
it.tok_i = tree.lastToken(param_type) + 1;
// 随后查找 anytype 和 ... 参数。
if (tree.tokenTag(it.tok_i) == .comma) {
it.tok_i += 1;
}
it.tok_flag = true;
return Param{
.first_doc_comment = first_doc_comment,
.comptime_noalias = comptime_noalias,
.name_token = name_token,
.anytype_ellipsis3 = null,
.type_expr = param_type,
};
}
if (tree.tokenTag(it.tok_i) == .comma) {
it.tok_i += 1;
}
if (tree.tokenTag(it.tok_i) == .r_paren) {
return null;
}
if (tree.tokenTag(it.tok_i) == .doc_comment) {
first_doc_comment = it.tok_i;
while (tree.tokenTag(it.tok_i) == .doc_comment) {
it.tok_i += 1;
}
}
switch (tree.tokenTag(it.tok_i)) {
.ellipsis3 => {
it.tok_flag = false; // 下一次迭代应返回 null。
return Param{
.first_doc_comment = first_doc_comment,
.comptime_noalias = null,
.name_token = null,
.anytype_ellipsis3 = it.tok_i,
.type_expr = null,
};
},
.keyword_noalias, .keyword_comptime => {
comptime_noalias = it.tok_i;
it.tok_i += 1;
},
else => {},
}
if (tree.tokenTag(it.tok_i) == .identifier and
tree.tokenTag(it.tok_i + 1) == .colon)
{
name_token = it.tok_i;
it.tok_i += 2;
}
if (tree.tokenTag(it.tok_i) == .keyword_anytype) {
it.tok_i += 1;
return Param{
.first_doc_comment = first_doc_comment,
.comptime_noalias = comptime_noalias,
.name_token = name_token,
.anytype_ellipsis3 = it.tok_i - 1,
.type_expr = null,
};
}
it.tok_flag = false;
}
}
};
pub fn iterate(fn_proto: *const FnProto, tree: *const Ast) Iterator {
return .{
.tree = tree,
.fn_proto = fn_proto,
.param_i = 0,
.tok_i = fn_proto.lparen + 1,
.tok_flag = true,
};
}
};
pub const StructInit = struct {
ast: Components,
pub const Components = struct {
lbrace: TokenIndex,
fields: []const Node.Index,
type_expr: Node.OptionalIndex,
};
};
pub const ArrayInit = struct {
ast: Components,
pub const Components = struct {
lbrace: TokenIndex,
elements: []const Node.Index,
type_expr: Node.OptionalIndex,
};
};
pub const ArrayType = struct {
ast: Components,
pub const Components = struct {
lbracket: TokenIndex,
elem_count: Node.Index,
sentinel: Node.OptionalIndex,
elem_type: Node.Index,
};
};
pub const PtrType = struct {
size: std.lang.Type.Pointer.Size,
allowzero_token: ?TokenIndex,
const_token: ?TokenIndex,
volatile_token: ?TokenIndex,
duplicate_token: ?TokenIndex,
ast: Components,
pub const Components = struct {
main_token: TokenIndex,
align_node: Node.OptionalIndex,
addrspace_node: Node.OptionalIndex,
sentinel: Node.OptionalIndex,
bit_range_start: Node.OptionalIndex,
bit_range_end: Node.OptionalIndex,
child_type: Node.Index,
};
};
pub const Slice = struct {
ast: Components,
pub const Components = struct {
sliced: Node.Index,
lbracket: TokenIndex,
start: Node.Index,
end: Node.OptionalIndex,
sentinel: Node.OptionalIndex,
};
};
pub const ContainerDecl = struct {
layout_token: ?TokenIndex,
ast: Components,
pub const Components = struct {
main_token: TokenIndex,
/// 当 main_token 为 Keyword_union 时填充。
enum_token: ?TokenIndex,
members: []const Node.Index,
arg: Node.OptionalIndex,
};
};
pub const Switch = struct {
ast: Components,
label_token: ?TokenIndex,
pub const Components = struct {
switch_token: TokenIndex,
condition: Node.Index,
cases: []const Node.Index,
};
};
pub const SwitchCase = struct {
inline_token: ?TokenIndex,
/// 指向 `|` 之后的第一个 token。它要么是标识符,要么
/// 是 `*`(后面紧接一个标识符)。
payload_token: ?TokenIndex,
ast: Components,
pub const Components = struct {
/// 若为空,则是 else 分支
values: []const Node.Index,
arrow_token: TokenIndex,
target_expr: Node.Index,
};
};
pub const Asm = struct {
ast: Components,
volatile_token: ?TokenIndex,
outputs: []const Node.Index,
inputs: []const Node.Index,
pub const Components = struct {
asm_token: TokenIndex,
template: Node.Index,
items: []const Node.Index,
clobbers: Node.OptionalIndex,
rparen: TokenIndex,
};
};
pub const Call = struct {
ast: Components,
pub const Components = struct {
lparen: TokenIndex,
fn_expr: Node.Index,
params: []const Node.Index,
};
};
};
pub const Error = struct {
tag: Tag,
is_note: bool = false,
/// 若 `token` 指向引发问题的 token 之前的 token,则为 True。
token_is_prev: bool = false,
token: TokenIndex,
extra: union {
none: void,
expected_tag: Token.Tag,
offset: usize,
} = .{ .none = {} },
pub const Tag = enum {
chained_comparison_operators,
decl_between_fields,
expected_block,
expected_block_or_assignment,
expected_block_or_expr,
expected_block_or_field,
expected_container_members,
expected_expr,
expected_expr_or_assignment,
expected_expr_or_var_decl,
expected_fn,
expected_inlinable,
expected_labelable,
expected_param_list,
expected_prefix_expr,
expected_primary_type_expr,
expected_pub_item,
expected_return_type,
expected_semi_or_else,
expected_semi_or_lbrace,
expected_statement,
expected_suffix_op,
expected_type_expr,
expected_var_decl,
expected_var_decl_or_fn,
expected_loop_payload,
expected_container,
extern_fn_body,
extra_addrspace_qualifier,
extra_align_qualifier,
ptr_mod_on_array_child_type,
invalid_bit_range,
same_line_doc_comment,
unattached_doc_comment,
test_doc_comment,
comptime_doc_comment,
varargs_nonfinal,
expected_semi_after_decl,
expected_semi_after_stmt,
expected_comma_after_field,
expected_comma_after_arg,
expected_comma_after_param,
expected_comma_after_initializer,
expected_comma_after_switch_prong,
expected_comma_after_for_operand,
expected_comma_after_capture,
expected_initializer,
mismatched_binary_op_whitespace,
invalid_ampersand_ampersand,
c_style_container,
expected_var_const,
wrong_equal_var_decl,
var_const_decl,
zig_style_container,
previous_field,
next_field,
/// `expected_tag` 已填充。
expected_token,
/// `offset` 已填充
invalid_byte,
};
};
/// `extra_data` 中的索引。
pub const ExtraIndex = enum(u32) {
_,
};
pub const Node = struct {
tag: Tag,
main_token: TokenIndex,
data: Data,
/// `nodes` 中的索引。
pub const Index = enum(u32) {
root = 0,
_,
pub fn toOptional(i: Index) OptionalIndex {
const result: OptionalIndex = @fromBackingInt(@intCast(@backingInt(i)));
assert(result != .none);
return result;
}
pub fn toOffset(base: Index, destination: Index) Offset {
const base_i64: i64 = @backingInt(base);
const destination_i64: i64 = @backingInt(destination);
return @fromBackingInt(@intCast(destination_i64 - base_i64));
}
};
/// `nodes` 中的索引,或 null。
pub const OptionalIndex = enum(u32) {
root = 0,
none = std.math.maxInt(u32),
_,
pub fn unwrap(oi: OptionalIndex) ?Index {
return if (oi == .none) null else @fromBackingInt(@intCast(@backingInt(oi)));
}
pub fn fromOptional(oi: ?Index) OptionalIndex {
return if (oi) |i| i.toOptional() else .none;
}
};
/// 相对节点索引。
pub const Offset = enum(i32) {
zero = 0,
_,
pub fn toOptional(o: Offset) OptionalOffset {
const result: OptionalOffset = @fromBackingInt(@intCast(@backingInt(o)));
assert(result != .none);
return result;
}
pub fn toAbsolute(offset: Offset, base: Index) Index {
return @fromBackingInt(@intCast(@as(i64, @backingInt(base)) + @backingInt(offset)));
}
};
/// 相对节点索引,或 null。
pub const OptionalOffset = enum(i32) {
none = std.math.maxInt(i32),
_,
pub fn unwrap(oo: OptionalOffset) ?Offset {
return if (oo == .none) null else @fromBackingInt(@intCast(@backingInt(oo)));
}
};
comptime {
// 为提高效率,目标是将其控制在一个字节以内。
assert(@sizeOf(Tag) == 1);
if (!std.debug.runtime_safety) {
assert(@sizeOf(Data) == 8);
}
}
/// FooComma/FooSemicolon 变体用于简化 `Ast.lastToken()` 的实现
///
pub const Tag = enum {
/// 根节点,保证位于 `Node.Index.root`。
/// `data` 字段的含义取决于文件是 `.zig` 还是
/// `.zon`。
///
/// `main_token` 字段是源文件的首个词法标记。
root,
/// `test {}`、
/// `test "name" {}`、
/// `test identifier {}`。
///
/// `data` 字段为 `.opt_token_and_node`:
/// 1. 指向测试名称词元的 `OptionalTokenIndex`,如果存在;必须是字符串字面量或标识符。
/// 2. 指向块的 `Node.Index`。
///
/// `main_token` 字段是 `test` 词元。
test_decl,
/// `data` 字段为 `.extra_and_opt_node`:
/// 1. 指向 `GlobalVarDecl` 的 `ExtraIndex`。
/// 2. 指向初始化表达式的 `Node.OptionalIndex`。
///
/// `main_token` 字段是 `var` 或 `const` 词元。
///
/// 除非属于 `assign_destructure` 节点,或发生解析错误,
/// 否则初始化表达式不能为 `.none`。
global_var_decl,
/// `var a: b align(c) = d`。
/// `const main_token: type_node align(align_node) = init_expr`。
///
/// `data` 字段为 `.extra_and_opt_node`:
/// 1. 指向 `LocalVarDecl` 的 `ExtraIndex`。
/// 2. 指向初始化表达式的 `Node.OptionalIndex`。
///
/// `main_token` 字段是 `var` 或 `const` 词元。
///
/// 除非属于 `assign_destructure` 节点,或发生解析错误,
/// 否则初始化表达式不能为 `.none`。
local_var_decl,
/// `var a: b = c`。
/// `const name_token: type_expr = init_expr`。
/// 可以是局部或全局声明。
///
/// `data` 字段为 `.opt_node_and_opt_node`:
/// 1. 指向类型表达式的 `Node.OptionalIndex`,如果存在。
/// 2. 指向初始化表达式的 `Node.OptionalIndex`。
///
/// `main_token` 字段是 `var` 或 `const` 词元。
///
/// 除非属于 `assign_destructure` 节点,或发生解析错误,
/// 否则初始化表达式不能为 `.none`。
simple_var_decl,
/// `var a align(b) = c`。
/// `const name_token align(align_expr) = init_expr`。
/// 可以是局部或全局声明。
///
/// `data` 字段为 `.node_and_opt_node`:
/// 1. 指向对齐表达式的 `Node.Index`。
/// 2. 指向初始化表达式的 `Node.OptionalIndex`。
///
/// `main_token` 字段是 `var` 或 `const` 词元。
///
/// 除非属于 `assign_destructure` 节点,或发生解析错误,
/// 否则初始化表达式不能为 `.none`。
aligned_var_decl,
/// `errdefer expr`,
///
/// `data` 字段是指向延迟执行表达式的 `.node`。
///
/// `main_token` 字段是 `errdefer` token。
@"errdefer",
/// `defer expr`。
///
/// `data` 字段为指向延迟表达式的 `.node`。
///
/// `main_token` 字段为 `defer` 标记。
@"defer",
/// `lhs catch rhs`、
/// `lhs catch |err| rhs`。
///
/// `main_token` 字段为 `catch` 标记。
///
/// 通过查看 `catch` 标记之后的下一个标记,
/// 确定错误载荷。
@"catch",
/// `lhs.a`。
///
/// `data` 字段为 `.node_and_token`:
/// 1. 一个指向字段访问左侧表达式的 `Node.Index`。
/// 2. 一个指向字段名标识符的 `TokenIndex`。
///
/// `main_token` 字段是 `.` 词法标记。
field_access,
/// `lhs.?`。
///
/// `data` 字段为 `.node_and_token`:
/// 1. 指向可选值解包左侧的 `Node.Index`。
/// 2. 指向 `?` 标记的 `TokenIndex`。
///
/// `main_token` 字段为 `.` 标记。
unwrap_optional,
/// `lhs == rhs`。`main_token` 字段为 `==` 词法标记。
equal_equal,
/// `lhs != rhs`。`main_token` 字段是 `!=` token。
bang_equal,
/// `lhs < rhs`。`main_token` 字段为 `<` 词法标记。
less_than,
/// `lhs > rhs`。`main_token` 字段是 `>` token。
greater_than,
/// `lhs <= rhs`。`main_token` 字段为 `<=` 标记。
less_or_equal,
/// `lhs >= rhs`。`main_token` 字段为 `>=` 词法标记。
greater_or_equal,
/// `lhs *= rhs`。`main_token` 字段是 `*=` token。
assign_mul,
/// `lhs /= rhs`。`main_token` 字段为 `/=` 标记。
assign_div,
/// `lhs %= rhs`。`main_token` 字段为 `%=` 词法标记。
assign_mod,
/// `lhs += rhs`。`main_token` 字段是 `+=` token。
assign_add,
/// `lhs -= rhs`。`main_token` 字段为 `-=` 标记。
assign_sub,
/// `lhs <<= rhs`。`main_token` 字段为 `<<=` 标记。
assign_shl,
/// `lhs <<|= rhs`。`main_token` 字段为 `<<|=` 标记。
assign_shl_sat,
/// `lhs >>= rhs`。`main_token` 字段为 `>>=` 词法标记。
assign_shr,
/// `lhs &= rhs`。`main_token` 字段为 `&=` 词法标记。
assign_bit_and,
/// `lhs ^= rhs`。`main_token` 字段是 `^=` token。
assign_bit_xor,
/// `lhs |= rhs`。`main_token` 字段为 `|=` 标记。
assign_bit_or,
/// `lhs *%= rhs`。`main_token` 字段是 `*%=` token。
assign_mul_wrap,
/// `lhs +%= rhs`。`main_token` 字段为 `+%=` 标记。
assign_add_wrap,
/// `lhs -%= rhs`。`main_token` 字段为 `-%=` 词法标记。
assign_sub_wrap,
/// `lhs *|= rhs`。`main_token` 字段是 `*%=` token。
assign_mul_sat,
/// `lhs +|= rhs`。`main_token` 字段为 `+|=` 标记。
assign_add_sat,
/// `lhs -|= rhs`。`main_token` 字段为 `-|=` 词法标记。
assign_sub_sat,
/// `lhs = rhs`。`main_token` 字段为 `=` 标记。
assign,
/// `a, b, ... = rhs`。
///
/// `data` 字段为 `.extra_and_node`:
/// 1. 一个 `ExtraIndex`,详见下文。
/// 2. 指向初始化表达式的 `Node.Index`。
///
/// `main_token` 字段是 `=` 词法单元。
///
/// `ExtraIndex` 存储以下数据:
/// ```
/// elem_count: u32,
/// variables: [elem_count]Node.Index,
/// ```
///
/// `variables` 中的每个节点具有以下标签之一:
/// - `global_var_decl`
/// - `local_var_decl`
/// - `simple_var_decl`
/// - `aligned_var_decl`
/// - 任意表达式节点
///
/// 前 4 个标签对应 `var` 或 `const` 左侧节点,注意其初始化表达式始终为 `.none`。
/// 表达式节点对应普通赋值左侧,必须按左值求值。前方可能有 `comptime` 词法单元,但不会创建对应的 `comptime` 节点,因此必须手动检测。
///
///
///
///
assign_destructure,
/// `lhs || rhs`。`main_token` 字段为 `||` 词法标记。
merge_error_sets,
/// `lhs * rhs`。`main_token` 字段为 `*` 词法标记。
mul,
/// `lhs / rhs`。`main_token` 字段是 `/` token。
div,
/// `lhs % rhs`。`main_token` 字段为 `%` 标记。
mod,
/// `lhs *% rhs`。`main_token` 字段是 `*%` token。
mul_wrap,
/// `lhs *| rhs`。`main_token` 字段为 `*|` 标记。
mul_sat,
/// `lhs + rhs`。`main_token` 字段为 `+` 词法标记。
add,
/// `lhs - rhs`。`main_token` 字段是 `-` token。
sub,
/// `lhs ++ rhs`。`main_token` 字段为 `++` 词法标记。
array_cat,
/// `lhs +% rhs`。`main_token` 字段是 `+%` token。
add_wrap,
/// `lhs -% rhs`。`main_token` 字段为 `-%` 标记。
sub_wrap,
/// `lhs +| rhs`。`main_token` 字段为 `+|` 词法标记。
add_sat,
/// `lhs -| rhs`。`main_token` 字段是 `-|` token。
sub_sat,
/// `lhs << rhs`。`main_token` 字段为 `<<` 标记。
shl,
/// `lhs <<| rhs`。`main_token` 字段是 `<<|` token。
shl_sat,
/// `lhs >> rhs`。`main_token` 字段为 `>>` 词法标记。
shr,
/// `lhs & rhs`。`main_token` 字段为 `&` 标记。
bit_and,
/// `lhs ^ rhs`。`main_token` 字段为 `^` 词法标记。
bit_xor,
/// `lhs | rhs`。`main_token` 字段是 `|` token。
bit_or,
/// `lhs orelse rhs`。`main_token` 字段是 `orelse` token。
@"orelse",
/// `lhs and rhs`。`main_token` 字段为 `and` 标记。
bool_and,
/// `lhs or rhs`。`main_token` 字段是 `or` token。
bool_or,
/// `!expr`。`main_token` 字段为 `!` 标记。
bool_not,
/// `-expr`。`main_token` 字段为 `-` 词法标记。
negation,
/// `~expr`。`main_token` 字段是 `~` token。
bit_not,
/// `-%expr`。`main_token` 字段是 `-%` token。
negation_wrap,
/// `&expr`。`main_token` 字段为 `&` 标记。
address_of,
/// `try expr`。`main_token` 字段是 `try` token。
@"try",
/// `?expr`。`main_token` 字段为 `?` 词法标记。
optional_type,
/// `[lhs]rhs`。`main_token` 字段是 `[` token。
array_type,
/// `[lhs:a]b`。
///
/// `data` 字段为 `.node_and_extra`:
/// 1. 一个指向长度表达式的 `Node.Index`。
/// 2. 一个指向 `ArrayTypeSentinel` 的 `ExtraIndex`。
///
/// `main_token` 字段是 `[` 词法标记。
array_type_sentinel,
/// `[*]align(lhs) rhs`、
/// `*align(lhs) rhs`、
/// `[]rhs`。
///
/// `data` 字段为 `.opt_node_and_node`:
/// 1. 指向对齐表达式的 `Node.OptionalIndex`,如果存在。
/// 2. 指向元素类型表达式的 `Node.Index`。
///
/// 单项指针的 `main_token` 是星号;
/// 切片、多项指针或 C 指针的则是左方括号。
ptr_type_aligned,
/// `[*:lhs]rhs`、
/// `*rhs`、
/// `[:lhs]rhs`。
///
/// `data` 字段为 `.opt_node_and_node`:
/// 1. 一个 `Node.OptionalIndex`,指向哨兵表达式,若存在。
/// 2. 一个 `Node.Index`,指向元素类型表达式。
///
/// `main_token` 对单元素指针为星号;对切片、多元素指针或 C 指针为左方括号。
///
ptr_type_sentinel,
/// `data` 字段为 `.extra_and_node`:
/// 1. 指向 `PtrType` 的 `ExtraIndex`。
/// 2. 指向元素类型表达式的 `Node.Index`。
///
/// 单项指针的 `main_token` 是星号;
/// 切片、多项指针或 C 指针的则是左方括号。
ptr_type,
/// `data` 字段为 `.extra_and_node`:
/// 1. 指向 `PtrTypeBitRange` 的 `ExtraIndex`。
/// 2. 指向元素类型表达式的 `Node.Index`。
///
/// 单项指针的 `main_token` 是星号;
/// 切片、多项指针或 C 指针的则是左方括号。
ptr_type_bit_range,
/// `lhs[rhs..]`
///
/// `main_token` 字段为 `[` 标记。
slice_open,
/// `sliced[start..end]`。
///
/// `data` 字段采用 `.node_and_extra`:
/// 1. 指向被切片表达式的 `Node.Index`。
/// 2. 指向 `Slice` 的 `ExtraIndex`。
///
/// `main_token` 字段是 `[` 标记。
slice,
/// `sliced[start..end :sentinel]`、
/// `sliced[start.. :sentinel]`。
///
/// `data` 字段采用 `.node_and_extra`:
/// 1. 指向被切片表达式的 `Node.Index`。
/// 2. 指向 `SliceSentinel` 的 `ExtraIndex`。
///
/// `main_token` 字段是 `[` 标记。
slice_sentinel,
/// `expr.*`。
///
/// `data` 字段是指向 expr 的 `.node`。
///
/// `main_token` 字段是 `*` 词元。
deref,
/// `lhs[rhs]`。
///
/// `main_token` 字段为 `[` 标记。
array_access,
/// `lhs{rhs}`。
///
/// `main_token` 字段为 `{` 词法标记。
array_init_one,
/// 与 `array_init_one` 相同,但已知最终右花括号前
/// 存在末尾逗号。
array_init_one_comma,
/// `.{a}`、
/// `.{a, b}`。
///
/// `data` 字段为 `.opt_node_and_opt_node`:
/// 1. 一个指向首个元素的 `Node.OptionalIndex`。绝不会为 `.none`
/// 2. 一个指向第二个元素的 `Node.OptionalIndex`,若存在。
///
/// `main_token` 字段是 `{` 词法标记。
array_init_dot_two,
/// 与 `array_init_dot_two` 相同,但已知最后一个右花括号
/// 之前存在尾随逗号。
array_init_dot_two_comma,
/// `.{a, b, c}`。
///
/// `data` 字段是一个 `.extra_range`,为每个元素存储
/// 一个 `Node.Index`。
///
/// `main_token` 字段是 `{` token。
array_init_dot,
/// 与 `array_init_dot` 相同,
/// 但已知最后的右花括号之前有尾随逗号。
array_init_dot_comma,
/// `a{b, c}`。
///
/// `data` 字段为 `.node_and_extra`:
/// 1. 一个指向类型表达式的 `Node.Index`。
/// 2. 一个指向 `SubRange` 的 `ExtraIndex`,其中为每个元素
/// 存储一个 `Node.Index`。
///
/// `main_token` 字段是 `{` 词法标记。
array_init,
/// 与 `array_init` 相同,
/// 但已知最后的右花括号之前有尾随逗号。
array_init_comma,
/// `a{.x = b}`、`a{}`。
///
/// `data` 字段采用 `.node_and_opt_node`:
/// 1. 指向类型表达式的 `Node.Index`。
/// 2. 指向第一个字段初始化的 `Node.OptionalIndex`(若存在)。
///
/// `main_token` 字段是 `{` 标记。
///
/// 字段名通过查看字段初始化之前的
/// 标记确定。
struct_init_one,
/// 与 `struct_init_one` 相同,但已知最终右花括号前
/// 存在末尾逗号。
struct_init_one_comma,
/// `.{.x = a, .y = b}`。
///
/// `data` 字段为 `.opt_node_and_opt_node`:
/// 1. 一个 `Node.OptionalIndex`,指向第一个字段初始化,绝不会为 `.none`。
/// 2. 一个 `Node.OptionalIndex`,指向第二个字段初始化,若存在。
///
/// `main_token` 字段是“{”词法单元。
///
/// 通过查看字段初始化之前的词法单元,确定字段名称。
///
struct_init_dot_two,
/// 与 `struct_init_dot_two` 相同,但已知最终右花括号前
/// 存在末尾逗号。
struct_init_dot_two_comma,
/// `.{.x = a, .y = b, .z = c}`。
///
/// `data` 字段为 `.extra_range`,为每个字段初始化
/// 存储一个 `Node.Index`。
///
/// `main_token` 字段是 `{` 词法标记。
///
/// 通过查看字段初始化之前的词法标记
/// 确定字段名。
struct_init_dot,
/// 与 `struct_init_dot` 相同,
/// 但已知最后的右花括号之前有尾随逗号。
struct_init_dot_comma,
/// `a{.x = b, .y = c}`。
///
/// `data` 字段采用 `.node_and_extra`:
/// 1. 指向类型表达式的 `Node.Index`。
/// 2. 指向 `SubRange` 的 `ExtraIndex`,其中为
/// 每个字段初始化存储一个 `Node.Index`。
///
/// `main_token` 字段是 `{` 标记。
///
/// 字段名通过查看字段初始化之前的
/// 标记确定。
struct_init,
/// 与 `struct_init` 相同,
/// 但已知最后的右花括号之前有尾随逗号。
struct_init_comma,
/// `a(b)`、`a()`。
///
/// `data` 字段采用 `.node_and_opt_node`:
/// 1. 指向函数表达式的 `Node.Index`。
/// 2. 指向第一个参数的 `Node.OptionalIndex`(若存在)。
///
/// `main_token` 字段是 `(` 标记。
call_one,
/// 与 `call_one` 相同,
/// 但已知最后的右圆括号之前有尾随逗号。
call_one_comma,
/// `a(b, c, d)`。
///
/// `data` 字段采用 `.node_and_extra`:
/// 1. 指向函数表达式的 `Node.Index`。
/// 2. 指向 `SubRange` 的 `ExtraIndex`,其中为
/// 每个参数存储一个 `Node.Index`。
///
/// `main_token` 字段是 `(` 标记。
call,
/// 与 `call` 相同,
/// 但已知最后的右圆括号之前有尾随逗号。
call_comma,
/// `switch(a) {}`。
///
/// `data` 字段采用 `.node_and_extra`:
/// 1. 指向 switch 操作数的 `Node.Index`。
/// 2. 指向 `SubRange` 的 `ExtraIndex`,其中为
/// 每个 switch 分支存储一个 `Node.Index`。
///
/// `The `main_token` field` 是前置标签的标识符(若存在),否则为 `switch`。
@"switch",
/// 与 `switch` 相同,但已知最终右花括号前有逗号。
///
switch_comma,
/// `a => b`、
/// `else => b`。
///
/// `data` 字段为 `.opt_node_and_node`:
/// 1. 一个 `Node.OptionalIndex`,其中 `.none` 表示 `else`。
/// 2. 一个指向目标表达式的 `Node.Index`。
///
/// `main_token` 字段是 `=>` 词法标记。
switch_case_one,
/// 与 `switch_case_one` 相同,但 case 为 inline。
switch_case_inline_one,
/// `a, b, c => d`。
///
/// `data` 字段为 `.extra_and_node`:
/// 1. 一个指向 `SubRange` 的 `ExtraIndex`,其中为每个 switch 项
/// 存储一个 `Node.Index`。
/// 2. 一个指向目标表达式的 `Node.Index`。
///
/// `main_token` 字段是 `=>` 词法标记。
switch_case,
/// 与 `switch_case` 相同,但分支为内联分支。
switch_case_inline,
/// `lhs...rhs`。
///
/// `main_token` 字段为 `...` 词法标记。
switch_range,
/// `while (a) b`,
/// `while (a) |x| b`.
while_simple,
/// `while (a) : (b) c`,
/// `while (a) |x| : (b) c`.
while_cont,
/// `while (a) : (b) c else d`、
/// `while (a) |x| : (b) c else d`、
/// `while (a) |x| : (b) c else |y| d`。
/// 可省略继续表达式部分 `: (b)`。
@"while",
/// `for (a) b`.
for_simple,
/// `for (lhs[0..inputs]) lhs[inputs + 1] else lhs[inputs + 2]`。`For[rhs]`。
@"for",
/// `lhs..rhs`, `lhs..`.
for_range,
/// `if (a) b`.
/// `if (b) |x| b`.
if_simple,
/// `if (a) b else c`.
/// `if (a) |x| b else c`.
/// `if (a) |x| b else |y| d`.
@"if",
/// `suspend expr`。
///
/// `data` 字段是指向 expr 的 `.node`。
///
/// `main_token` 字段为 `suspend` 词法标记。
@"suspend",
/// `resume expr`。
///
/// `data` 字段是指向 expr 的 `.node`。
///
/// `main_token` 字段为 `resume` 词法标记。
@"resume",
/// `continue :label expr`、
/// `continue expr`、
/// `continue :label`、
/// `continue`。
///
/// `data` 字段为 `.opt_token_and_opt_node`:
/// 1. 一个 `OptionalTokenIndex`,指向标签标识符,若存在。
/// 2. 一个 `Node.OptionalIndex`,指向目标表达式,若存在。
///
/// `main_token` 字段是 `continue` 词法单元。
@"continue",
/// `break :label expr`、
/// `break expr`、
/// `break :label`、
/// `break`。
///
/// `data` 字段为 `.opt_token_and_opt_node`:
/// 1. 指向标签标识符的 `OptionalTokenIndex`,如果存在。
/// 2. 指向目标表达式的 `Node.OptionalIndex`,如果存在。
///
/// `main_token` 字段是 `break` 词元。
@"break",
/// `return expr`、`return`。
///
/// 若有返回值,`data` 字段是指向该返回值的 `.opt_node`。
///
/// `main_token` 字段是 `return` token。
@"return",
/// `fn (a: type_expr) return_type`。
///
/// `data` 字段为 `.opt_node_and_opt_node`:
/// 1. 指向首个参数类型表达式的 `Node.OptionalIndex`,如果存在。
/// 2. 指向返回类型表达式的 `Node.OptionalIndex`。除非
/// 发生解析错误,否则不能为 `.none`。
///
/// `main_token` 字段是 `fn` 词元。
///
/// AST 树中省略 `anytype` 和 `...` 参数。
/// extern 函数声明使用此标签。
fn_proto_simple,
/// `fn (a: b, c: d) return_type`。
///
/// `data` 字段为 `.extra_and_opt_node`:
/// 1. 一个 `ExtraIndex`,指向 `SubRange`,其中为每个参数类型表达式存储一个 `Node.Index`。
/// 2. 一个 `Node.OptionalIndex`,指向返回类型表达式。除非发生解析错误,否则不能为 `.none`。
///
/// `main_token` 字段是 `fn` 词法单元。
///
/// `anytype` 和 `...` 参数不包含在 AST 树中。
/// 外部函数声明使用此标签。
///
///
fn_proto_multi,
/// `fn (a: b) addrspace(e) linksection(f) callconv(g) return_type`。
/// 零个或一个参数。
///
/// `data` 字段为 `.extra_and_opt_node`:
/// 1. 一个 `Node.ExtraIndex`,指向 `FnProtoOne`。
/// 2. 一个 `Node.OptionalIndex`,指向返回类型表达式。除非发生解析错误,否则不能为 `.none`。
///
/// `main_token` 字段是 `fn` 词法单元。
///
/// `anytype` 和 `...` 参数不包含在 AST 树中。
/// 外部函数声明使用此标签。
///
fn_proto_one,
/// `fn (a: b, c: d) addrspace(e) linksection(f) callconv(g) return_type`。
///
/// `data` 字段为 `.extra_and_opt_node`:
/// 1. `Node.ExtraIndex`,指向 `FnProto`。
/// 2. 指向返回类型表达式的 `Node.OptionalIndex`;除非
/// 发生解析错误,否则不得为 `.none`。
///
/// `main_token` 字段为 `fn` 标记。
///
/// AST 树中省略 `anytype` 和 `...` 参数。
/// 外部函数声明使用此标签。
fn_proto,
/// extern 函数声明使用 fn_proto 标签,而非此标签。
///
/// `data` 字段为 `.node_and_node`:
/// 1. 指向 `fn_proto_*` 的 `Node.Index`。
/// 2. 指向函数体块的 `Node.Index`。
///
/// `main_token` 字段是 `fn` 词元。
fn_decl,
/// `anyframe->return_type`。
///
/// `data` 字段为 `.token_and_node`:
/// 1. 指向 `->` 词元的 `TokenIndex`。
/// 2. 指向函数帧返回类型表达式的 `Node.Index`。
///
/// `main_token` 字段是 `anyframe` 词元。
anyframe_type,
/// `data` 字段未使用。
anyframe_literal,
/// `data` 字段未使用。
char_literal,
/// `data` 字段未使用。
number_literal,
/// `data` 字段未使用。
unreachable_literal,
/// `data` 字段未使用。
///
/// 大多数标识符没有显式的 AST 节点,但对于
/// 可能属于多种不同 AST 节点类型的表达式,
/// 会为其创建标识符 AST 节点。
identifier,
/// `.foo`。
///
/// `data` 字段未使用。
///
/// `main_token` 字段为标识符。
enum_literal,
/// `data` 字段未使用。
///
/// `main_token` 字段为字符串字面量标记。
string_literal,
/// `data` 字段为 `.token_and_token`:
/// 1. 指向首个 `.multiline_string_literal_line` 词元的 `TokenIndex`。
/// 2. 指向最后一个 `.multiline_string_literal_line` 词元的 `TokenIndex`。
///
/// `main_token` 字段是首个词元索引,与 `data` 冗余。
multiline_string_literal,
/// `(expr)`。
///
/// `data` 字段为 `.node_and_token`:
/// 1. 指向子表达式的 `Node.Index`。
/// 2. 指向 `)` 标记的 `TokenIndex`。
///
/// `main_token` 字段为 `(` 标记。
grouped_expression,
/// `@a(b, c)`。
///
/// `data` 字段为 `.opt_node_and_opt_node`:
/// 1. 一个指向第一个参数的 `Node.OptionalIndex`,若存在。
/// 2. 一个指向第二个参数的 `Node.OptionalIndex`,若存在。
///
/// `main_token` 字段是内置函数词法标记。
builtin_call_two,
/// 与 `builtin_call_two` 相同,但已知最后一个右圆括号
/// 之前存在尾随逗号。
builtin_call_two_comma,
/// `@a(b, c, d)`。
///
/// `data` 字段为 `.extra_range`,为每个参数存储一个 `Node.Index`。
///
/// `main_token` 字段为内置函数标记。
///
builtin_call,
/// 与 `builtin_call` 相同,但已知最后一个右圆括号
/// 之前存在尾随逗号。
builtin_call_comma,
/// `error{a, b}`。
///
/// `data` 字段为 `.token_and_token`:
/// 1. 一个指向 `{` 词法标记的 `TokenIndex`。
/// 2. 一个指向 `}` 词法标记的 `TokenIndex`。
///
/// `main_token` 字段为 `error`。
error_set_decl,
/// `struct {}`、`union {}`、`opaque {}`、`enum {}`。
///
/// `data` 字段采用 `.extra_range`,为
/// 每个容器成员存储一个 `Node.Index`。
///
/// `main_token` 字段是 `struct`、`union`、`opaque` 或 `enum` 标记。
container_decl,
/// 与 `container_decl` 相同,但已知最后一个右花括号
/// 之前存在尾随逗号。
container_decl_trailing,
/// `struct {lhs, rhs}`、`union {lhs, rhs}`、`opaque {lhs, rhs}`、`enum {lhs, rhs}`。
///
/// `data` 字段为 `.opt_node_and_opt_node`:
/// 1. 一个 `Node.OptionalIndex`,指向第一个容器成员,若存在。
/// 2. 一个 `Node.OptionalIndex`,指向第二个容器成员,若存在。
///
/// `main_token` 字段是 `struct`、`union`、`opaque` 或 `enum` 词法单元。
container_decl_two,
/// 与 `container_decl_two` 相同,但已知最终右花括号前
/// 存在末尾逗号。
container_decl_two_trailing,
/// `struct(arg)`、`union(arg)`、`enum(arg)`。
///
/// `data` 字段采用 `.node_and_extra`:
/// 1. 指向 arg 的 `Node.Index`。
/// 2. 指向 `SubRange` 的 `ExtraIndex`,其中为
/// 每个容器成员存储一个 `Node.Index`。
///
/// `main_token` 字段是 `struct`、`union` 或 `enum` 标记。
container_decl_arg,
/// 与 `container_decl_arg` 相同,
/// 但已知最后的右花括号之前有尾随逗号。
container_decl_arg_trailing,
/// `union(enum) {}`。
///
/// `data` 字段为 `.extra_range`,为每个容器成员
/// 存储一个 `Node.Index`。
///
/// `main_token` 字段是 `union` 词法标记。
///
/// 显式提供枚举的带标签联合体则由
/// `container_decl_arg` 表示。
tagged_union,
/// 与 `tagged_union` 相同,但已知最终右花括号前
/// 存在末尾逗号。
tagged_union_trailing,
/// `union(enum) {lhs, rhs}`。
///
/// `data` 字段为 `.opt_node_and_opt_node`:
/// 1. 指向第一个容器成员的 `Node.OptionalIndex`,如果存在。
/// 2. 指向第二个容器成员的 `Node.OptionalIndex`,如果存在。
///
/// `main_token` 字段是 `union` 词元。
///
/// 显式提供枚举的带标签联合体则使用
/// `container_decl_arg` 表示。
tagged_union_two,
/// 与 `tagged_union_two` 相同,但已知最终右花括号前
/// 存在末尾逗号。
tagged_union_two_trailing,
/// `union(enum(arg)) {}`。
///
/// `data` 字段为 `.node_and_extra`:
/// 1. 指向 arg 的 `Node.Index`。
/// 2. 指向 `SubRange` 的 `ExtraIndex`,其中为每个
/// 容器成员存储一个 `Node.Index`。
///
/// `main_token` 字段是 `union` 词元。
tagged_union_enum_tag,
/// 与 `tagged_union_enum_tag` 相同,但已知最后一个右花括号
/// 之前存在尾随逗号。
tagged_union_enum_tag_trailing,
/// `a: lhs = rhs,`、
/// `a: lhs,`。
///
/// `data` 字段采用 `.node_and_opt_node`:
/// 1. 指向字段类型表达式的 `Node.Index`。
/// 2. 指向默认值表达式的 `Node.OptionalIndex`(若存在)。
///
/// `main_token` 字段是字段名标识符。
///
/// `lastToken()` 不包含可能存在的尾随逗号。
container_field_init,
/// `a: lhs align(rhs),`。
///
/// `data` 字段为 `.node_and_node`:
/// 1. 指向字段类型表达式的 `Node.Index`。
/// 2. 指向对齐表达式的 `Node.Index`。
///
/// `main_token` 字段是字段名标识符。
///
/// `lastToken()` 不包含可能存在的末尾逗号。
container_field_align,
/// `a: lhs align(c) = d,`。
///
/// `data` 字段为 `.node_and_extra`:
/// 1. 一个 `Node.Index`,指向字段类型表达式。
/// 2. 一个 `ExtraIndex`,指向 `ContainerField`。
///
/// `main_token` 字段为字段名标识符。
///
/// `lastToken()` 不包含可能出现的尾随逗号。
container_field,
/// `comptime expr`。
///
/// `data` 字段是指向 expr 的 `.node`。
///
/// `main_token` 字段是 `comptime` token。
@"comptime",
/// `nosuspend expr`。
///
/// `data` 字段是指向 expr 的 `.node`。
///
/// `main_token` 字段是 `nosuspend` 词元。
@"nosuspend",
/// `{lhs rhs}`。
///
/// `data` 字段采用 `.opt_node_and_opt_node`:
/// 1. 指向第一条语句的 `Node.OptionalIndex`(若存在)。
/// 2. 指向第二条语句的 `Node.OptionalIndex`(若存在)。
///
/// `main_token` 字段是 `{` 标记。
block_two,
/// 与 `block_two` 相同,
/// 但已知最后的右花括号之前有尾随逗号。
block_two_semicolon,
/// `{a b}`。
///
/// `data` 字段为 `.extra_range`,为每条语句存储一个 `Node.Index`。
///
/// `main_token` 字段为 `{` 标记。
///
block,
/// 与 `block` 相同,但已知最终右花括号前有逗号。
///
block_semicolon,
/// `asm(a)`。
///
/// `main_token` 字段是 `asm` token。
asm_simple,
/// `asm(a, b)`。
///
/// `data` 字段采用 `.node_and_extra`:
/// 1. 指向 a 的 `Node.Index`。
/// 2. 指向 `Asm` 的 `ExtraIndex`。
///
/// `main_token` 字段是 `asm` 标记。
@"asm",
/// `[a] "b" (c)`。
/// `[a] "b" (-> lhs)`。
///
/// `data` 字段为 `.opt_node_and_token`:
/// 1. 一个指向 lhs 的 `Node.OptionalIndex`,若存在。
/// 2. 一个指向 `)` 词法标记的 `TokenIndex`。
///
/// `main_token` 字段为 `a`。
asm_output,
/// `[a] "b" (lhs)`。
///
/// `data` 字段为 `.node_and_token`:
/// 1. 一个指向 lhs 的 `Node.Index`。
/// 2. 一个指向 `)` 词法标记的 `TokenIndex`。
///
/// `main_token` 字段为 `a`。
asm_input,
/// `error.a`。
///
/// `data` 字段未使用。
///
/// `main_token` 字段为 `error` 词法标记。
error_value,
/// `lhs!rhs`。
///
/// `main_token` 字段为 `!` 标记。
error_union,
pub fn isContainerField(tag: Tag) bool {
return switch (tag) {
.container_field_init,
.container_field_align,
.container_field,
=> true,
else => false,
};
}
};
pub const Data = union {
node: Index,
opt_node: OptionalIndex,
token: TokenIndex,
node_and_node: struct { Index, Index },
opt_node_and_opt_node: struct { OptionalIndex, OptionalIndex },
node_and_opt_node: struct { Index, OptionalIndex },
opt_node_and_node: struct { OptionalIndex, Index },
node_and_extra: struct { Index, ExtraIndex },
extra_and_node: struct { ExtraIndex, Index },
extra_and_opt_node: struct { ExtraIndex, OptionalIndex },
node_and_token: struct { Index, TokenIndex },
token_and_node: struct { TokenIndex, Index },
token_and_token: struct { TokenIndex, TokenIndex },
opt_node_and_token: struct { OptionalIndex, TokenIndex },
opt_token_and_node: struct { OptionalTokenIndex, Index },
opt_token_and_opt_node: struct { OptionalTokenIndex, OptionalIndex },
opt_token_and_opt_token: struct { OptionalTokenIndex, OptionalTokenIndex },
@"for": struct { ExtraIndex, For },
extra_range: SubRange,
};
pub const LocalVarDecl = struct {
type_node: Index,
align_node: Index,
};
pub const ArrayTypeSentinel = struct {
sentinel: Index,
elem_type: Index,
};
pub const PtrType = struct {
sentinel: OptionalIndex,
align_node: OptionalIndex,
addrspace_node: OptionalIndex,
};
pub const PtrTypeBitRange = struct {
sentinel: OptionalIndex,
align_node: Index,
addrspace_node: OptionalIndex,
bit_range_start: Index,
bit_range_end: Index,
};
pub const SubRange = struct {
/// extra_data 中的索引。
start: ExtraIndex,
/// extra_data 中的索引。
end: ExtraIndex,
};
pub const If = struct {
then_expr: Index,
else_expr: Index,
};
pub const ContainerField = struct {
align_expr: Index,
value_expr: Index,
};
pub const GlobalVarDecl = struct {
/// 存在显式类型标注时填充。
type_node: OptionalIndex,
/// 存在 align(A) 时填充。
align_node: OptionalIndex,
/// 存在 addrspace(A) 时填充。
addrspace_node: OptionalIndex,
/// 存在 linksection(A) 时填充。
section_node: OptionalIndex,
};
pub const Slice = struct {
start: Index,
end: Index,
};
pub const SliceSentinel = struct {
start: Index,
/// 切片为“开放”状态时可能是 .none
end: OptionalIndex,
sentinel: Index,
};
pub const While = struct {
cont_expr: OptionalIndex,
then_expr: Index,
else_expr: Index,
};
pub const WhileCont = struct {
cont_expr: Index,
then_expr: Index,
};
pub const For = packed struct(u32) {
inputs: u31,
has_else: bool,
};
pub const FnProtoOne = struct {
/// 恰有 1 个参数时填充,否则参数数为 0。
param: OptionalIndex,
/// 存在 align(A) 时填充。
align_expr: OptionalIndex,
/// 存在 addrspace(A) 时填充。
addrspace_expr: OptionalIndex,
/// 存在 linksection(A) 时填充。
section_expr: OptionalIndex,
/// 存在 callconv(A) 时填充。
callconv_expr: OptionalIndex,
};
pub const FnProto = struct {
params_start: ExtraIndex,
params_end: ExtraIndex,
/// 存在 align(A) 时填充。
align_expr: OptionalIndex,
/// 存在 addrspace(A) 时填充。
addrspace_expr: OptionalIndex,
/// 存在 linksection(A) 时填充。
section_expr: OptionalIndex,
/// 存在 callconv(A) 时填充。
callconv_expr: OptionalIndex,
};
pub const Asm = struct {
items_start: ExtraIndex,
items_end: ExtraIndex,
clobbers: OptionalIndex,
/// 用于使 lastToken() 正常工作。
rparen: TokenIndex,
};
};
pub fn nodeToSpan(tree: *const Ast, node: Ast.Node.Index) Span {
return tokensToSpan(
tree,
tree.firstToken(node),
tree.lastToken(node),
tree.nodeMainToken(node),
);
}
pub fn tokenToSpan(tree: *const Ast, token: Ast.TokenIndex) Span {
return tokensToSpan(tree, token, token, token);
}
pub fn tokensToSpan(tree: *const Ast, start: Ast.TokenIndex, end: Ast.TokenIndex, main: Ast.TokenIndex) Span {
var start_tok = start;
var end_tok = end;
if (tree.tokensOnSameLine(start, end)) {
// 不执行操作
} else if (tree.tokensOnSameLine(start, main)) {
end_tok = main;
} else if (tree.tokensOnSameLine(main, end)) {
start_tok = main;
} else {
start_tok = main;
end_tok = main;
}
const start_off = tree.tokenStart(start_tok);
const end_off = tree.tokenStart(end_tok) + @as(u32, @intCast(tree.tokenSlice(end_tok).len));
return Span{ .start = start_off, .end = end_off, .main = tree.tokenStart(main) };
}
test {
_ = Parse;
_ = Render;
}