跳转到内容
标准库Zig 0.17.1官方原文
源码std/Build.zig

第 1 行

字段

graph: *Graph

全部 Build 实例共享的状态。

install_tls: Step.TopLevel
uninstall_tls: Step.TopLevel
allocator: Allocator
default_step: *Step
top_level_steps: std.array_hash_map.String(*Step.TopLevel)
root: Cache.Path

包含 build.zig 的目录路径。

debug_log_scopes: []const []const u8 = &.{}
debug_stack_frames_count: u8 = 8

为调试记录 StackTrace 时捕获的栈帧数, 尤其是在创建 Step 时。 设为 0 可禁用栈信息收集。

user_input_options: PackageOptions.Map
available_options_map: std.array_hash_map.String(AvailableOption) = .empty
invalid_user_input: bool
dep_prefix: []const u8 = ""
modules: std.array_hash_map.String(*Module)
named_writefiles: std.array_hash_map.String(*Step.WriteFile)
named_lazy_paths: std.array_hash_map.String(LazyPath)
pkg_hash: []const u8

此实例所属包的哈希。"" 表示这是根包。

available_deps: AvailableDeps

依赖名称到包哈希值的映射。

std.Build.abi

别名

第 23 行

别名目标 std.Build.abi

std.Build.addCheckFile

函数

第 1529 行

pub fn addCheckFile( b: *Build, file_source: LazyPath, options: Step.CheckFile.Options, ) *Step.CheckFile

参数

b: *Build
file_source: LazyPath
options: Step.CheckFile.Options

std.Build.addConfigHeader

函数

第 827 行

使用提供的 values 生成 C 头文件,可以基于 模板输入文件,例如 config.h.in。 提供输入模板文件时,如果 values 包含输入文件中没有的 选项,或 values 缺少输入文件中存在的 选项,此函数会使构建失败。

pub fn addConfigHeader( b: *Build, options: Step.ConfigHeader.Options, values: anytype, ) *Step.ConfigHeader

参数

std.Build.addExecutable

函数

第 579 行

pub fn addExecutable(b: *Build, options: ExecutableOptions) *Step.Compile

参数

b: *Build
options: ExecutableOptions

std.Build.addFail

函数

第 941 行

pub fn addFail(b: *Build, error_msg: []const u8) *Step.Fail

参数

b: *Build
error_msg: []const u8

std.Build.addFmt

函数

第 945 行

pub fn addFmt(b: *Build, options: Step.Fmt.Options) *Step.Fmt

参数

b: *Build
options: Step.Fmt.Options

std.Build.addInstallArtifact

函数

第 1465 行

这只创建步骤;不会将其添加到 顶层安装步骤的依赖中。

pub fn addInstallArtifact( b: *Build, artifact: *Step.Compile, options: Step.InstallArtifact.Options, ) *Step.InstallArtifact

参数

b: *Build
artifact: *Step.Compile
options: Step.InstallArtifact.Options

std.Build.addInstallBinFile

函数

第 1502 行

dest_rel_path 相对于 bin 路径

pub fn addInstallBinFile(b: *Build, source: LazyPath, dest_rel_path: []const u8) *Step.InstallFile

参数

b: *Build
source: LazyPath
dest_rel_path: []const u8

std.Build.addInstallDirectory

函数

第 1525 行

pub fn addInstallDirectory(b: *Build, options: Step.InstallDir.Options) *Step.InstallDir

参数

b: *Build
options: Step.InstallDir.Options

std.Build.addInstallFile

函数

第 1497 行

dest_rel_path 相对于安装前缀路径。

pub fn addInstallFile(b: *Build, source: LazyPath, dest_rel_path: []const u8) *Step.InstallFile

参数

b: *Build
source: LazyPath
dest_rel_path: []const u8

std.Build.addInstallFileWithDir

函数

第 1516 行

pub fn addInstallFileWithDir( b: *Build, source: LazyPath, install_dir: InstallDir, dest_rel_path: []const u8, ) *Step.InstallFile

参数

b: *Build
source: LazyPath
install_dir: InstallDir
dest_rel_path: []const u8

std.Build.addInstallHeaderFile

函数

第 1512 行

dest_rel_path 相对于头文件路径

pub fn addInstallHeaderFile(b: *Build, source: LazyPath, dest_rel_path: []const u8) *Step.InstallFile

参数

b: *Build
source: LazyPath
dest_rel_path: []const u8

std.Build.addInstallLibFile

函数

第 1507 行

dest_rel_path 相对于库路径

pub fn addInstallLibFile(b: *Build, source: LazyPath, dest_rel_path: []const u8) *Step.InstallFile

参数

b: *Build
source: LazyPath
dest_rel_path: []const u8

std.Build.addLibrary

函数

第 637 行

pub fn addLibrary(b: *Build, options: LibraryOptions) *Step.Compile

参数

b: *Build
options: LibraryOptions

std.Build.addModule

函数

第 704 行

此函数创建模块并将其加入包的模块集合, 使依赖当前包的其他包可以使用该模块。 若要创建私有模块,可改用 createModule。

pub fn addModule(b: *Build, name: []const u8, options: Module.CreateOptions) *Module

参数

b: *Build
name: []const u8
options: Module.CreateOptions

std.Build.addMutateFiles

函数

第 916 行

创建用于修改通过 addTempFiles 创建的临时目录的步骤。

也可考虑 addWriteFiles,它用于创建可缓存的文件目录, 供后续操作使用。

此函数只能与通过 addTempFiles 或 tmpPath 获得的 tmp_path 配合使用。

pub fn addMutateFiles(b: *Build, tmp_path: LazyPath) *Step.WriteFile

参数

b: *Build
tmp_path: LazyPath

std.Build.addNamedLazyPath

函数

第 879 行

pub fn addNamedLazyPath(b: *Build, name: []const u8, lp: LazyPath) void

参数

b: *Build
name: []const u8
lp: LazyPath

std.Build.addNamedWriteFiles

函数

第 862 行

pub fn addNamedWriteFiles(b: *Build, name: []const u8) *Step.WriteFile

参数

b: *Build
name: []const u8

std.Build.addObjCopy

函数

第 1492 行

pub fn addObjCopy(b: *Build, source: LazyPath, options: Step.ObjCopy.Options) *Step.ObjCopy

参数

b: *Build
source: LazyPath
options: Step.ObjCopy.Options

std.Build.addObject

函数

第 603 行

pub fn addObject(b: *Build, options: ObjectOptions) *Step.Compile

参数

b: *Build
options: ObjectOptions

std.Build.addOptions

函数

第 555 行

创建一组键值对,可将其转换为 Zig 源文件, 随后插入 Zig 编译的模块表以供导入。

由此可通过 @import 向 Zig 源码暴露 build.zig 中的值。 相关接口:Module.addOptions。

pub fn addOptions(b: *Build) *Step.Options

参数

b: *Build

std.Build.addPackageOptionFromArg

函数

第 453 行

fn addPackageOptionFromArg( arena: Allocator, map: *PackageOptions.Map, field_name: [:0]const u8, comptime T: type, maybe_value: ?T, ) void

参数

arena: Allocator
map: *PackageOptions.Map
field_name: [:0]const u8
T: type
maybe_value: ?T

若为 null,则不添加该值,但仍会对 T 进行类型检查。

std.Build.addRunArtifact

函数

第 762 行

创建 Step.Run,使用通过 addExecutable 构建的可执行程序。 使用 Step.Run 的方法添加命令行参数。

目标不必是主机。在某些情况下, 交叉编译的二进制文件也可执行。

此操作是声明式的:构造一个构建步骤,是否实际运行 取决于用户传给构建命令的选项。

另请参见:

pub fn addRunArtifact(b: *Build, exe: *Step.Compile) *Step.Run

参数

b: *Build
exe: *Step.Compile

std.Build.addRunFile

函数

第 816 行

创建执行所提供文件的步骤。

通过 Step.Run 的方法添加更多命令行参数。

另见:

pub fn addRunFile(b: *Build, executable: LazyPath) *Step.Run

参数

b: *Build
executable: LazyPath

std.Build.addSearchPrefix

函数

第 1840 行

添加额外路径,等同于用户提供的 --search-prefix 参数。此函数添加的路径优先级低于 用户在命令行指定的路径。

通常最佳实践是避免调用此函数,而是 由用户通过标准构建系统接口 提供这些路径。但与其他构建系统集成时,用户可能 已将信息提供给另一个构建系统,因此 应复用相同信息,避免要求用户 再次提供。

pub fn addSearchPrefix(b: *Build, search_prefix: []const u8) void

参数

b: *Build
search_prefix: []const u8

std.Build.addSystemCommand

函数

第 743 行

创建在主机系统上执行进程的步骤。

argv 是传递给被执行进程的一个或多个命令行 参数。第一个元素是要运行的可执行程序名称。 可使用 Step.Run 的方法添加更多命令行参数,例如:

此函数引入系统依赖,影响可复现性, 并使配置用于从源码构建项目的 计算机环境更加困难。

另请参见:

pub fn addSystemCommand(b: *Build, argv: []const []const u8) *Step.Run

参数

b: *Build
argv: []const []const u8

std.Build.addTempFiles

函数

第 903 行

创建一个步骤,用于修改延迟创建的临时目录内的文件; 构建成功后自动清理该目录。

目录放置于 "tmp" 而不是 "o" 内,且不使用 缓存。在 make 阶段,此步骤始终执行所有文件 系统操作;构建成功完成后,此目录将 与其他 tmp 目录一同删除。因此,其他步骤 可以使用此目录进行修改操作。

另请参见:

pub fn addTempFiles(b: *Build) *Step.WriteFile

参数

b: *Build

std.Build.addTest

函数

第 676 行

创建包含单元测试的可执行文件。

等同于执行命令 zig test --test-no-exec ...。

此步骤不运行单元测试。通常会将此 函数的结果传给 addRunArtifact,创建 Step.Run。 将这两个步骤分开,是因为它们独立配置和 缓存。

pub fn addTest(b: *Build, options: TestOptions) *Step.Compile

参数

b: *Build
options: TestOptions

std.Build.addTranslateC

函数

第 949 行

pub fn addTranslateC(b: *Build, options: Step.TranslateC.Options) *Step.TranslateC

参数

b: *Build
options: Step.TranslateC.Options

std.Build.addUpdateSourceFiles

函数

第 937 行

创建一个步骤,向相对于构建根目录的路径写入数据, 修改项目源码文件。

此构建步骤不用于常规构建 过程,而是供开发者主动运行的工具, 用于更新随后将提交到版本控制的源码文件。

使用场景示例:

  • 预编译纳入版本控制的资源
  • 快照测试
pub fn addUpdateSourceFiles(b: *Build) *Step.UpdateSourceFiles

参数

b: *Build

std.Build.addUserInputFlag

函数

第 1387 行

构建系统实现细节。

pub fn addUserInputFlag(b: *Build, name: []const u8) error{OutOfMemory}!bool

参数

b: *Build
name: []const u8

错误

OutOfMemory

std.Build.addUserInputOption

函数

第 1351 行

构建系统实现细节。

pub fn addUserInputOption(b: *Build, name: []const u8, value_raw: []const u8) error{OutOfMemory}!bool

参数

b: *Build
name: []const u8
value_raw: []const u8

错误

OutOfMemory

std.Build.addWriteFile

函数

第 856 行

pub fn addWriteFile(b: *Build, file_path: []const u8, data: []const u8) *Step.WriteFile

参数

b: *Build
file_path: []const u8
data: []const u8

std.Build.addWriteFiles

函数

第 923 行

pub fn addWriteFiles(b: *Build) *Step.WriteFile

参数

b: *Build

std.Build.Allocator

别名

第 12 行

别名目标 std.mem.Allocator

std.Build.ArrayList

别名

第 17 行

别名目标 std.ArrayList

std.Build.AssemblyOptions

容器

第 690 行

字段

name: []const u8
source_file: LazyPath
target: ResolvedTarget

要选择与构建程序包的计算机相同的目标,请传入 程序包 Build 实例的 host 字段。

optimize: std.builtin.Optimize
max_rss: u64 = 0
zig_lib_dir: ?LazyPath = null

std.Build.assert

别名

第 10 行

别名目标 std.debug.assert

std.Build.AvailableDeps

类型

第 226 行

std.Build.AvailableOption

容器

第 353 行

字段

type_id: Configuration.AvailableOption.Type
description: []const u8
enum_options: ?[]const []const u8

若 type_id 为 enum 或 enum_list,则提供枚举选项列表

std.Build.Build

别名

第 1 行

别名目标 std.Build

std.Build.builtin

常量

第 3 行

std.Build.Cache

别名

第 20 行

别名目标 std.Build.Cache

std.Build.Configuration

别名

第 25 行

configure 阶段序列化的输出,由 make 阶段读取。

别名目标 std.Build.Configuration

std.Build.ConfigureDependency

容器

第 59 行

字段

lazy_path: LazyPath
is_directory: bool
metadata_only: bool

std.Build.create

函数

第 361 行

构建系统实现细节。

pub fn create( graph: *Graph, root: Cache.Path, available_deps: AvailableDeps, ) error{OutOfMemory}!*Build

参数

graph: *Graph
root: Cache.Path
available_deps: AvailableDeps

错误

OutOfMemory

std.Build.createChild

函数

第 405 行

fn createChild( parent: *Build, dep_name: []const u8, root: Cache.Path, pkg_hash: []const u8, pkg_deps: AvailableDeps, user_input_options: PackageOptions.Map, ) error{OutOfMemory}!*Build

参数

parent: *Build
dep_name: []const u8
root: Cache.Path
pkg_hash: []const u8
pkg_deps: AvailableDeps
user_input_options: PackageOptions.Map

错误

OutOfMemory

std.Build.createModule

函数

第 722 行

创建供当前包使用的私有模块, 但不向依赖本包的其他包暴露。 若要创建公共模块,可改用 addModule。

pub fn createModule(b: *Build, options: Module.CreateOptions) *Module

参数

b: *Build
options: Module.CreateOptions

std.Build.dependency

函数

第 2030 行

声明当前配置确实需要某个可能采用惰性获取的依赖。

若已取得该依赖,则返回它;否则退出配置阶段,以获取此惰性依赖并重新执行配置脚本。

若调用者此时已知还需要其他惰性依赖,改用 dependencyLazy 可以节省时间:以适当方式处理 error.LazyDependencyNeeded,在最终从顶层构建函数返回该错误之前,先将多个可能惰性获取的依赖标记为必需。

pub fn dependency(b: *Build, name: []const u8, args: anytype) *Dependency

参数

b: *Build
name: []const u8

std.Build.Dependency

容器

第 1853 行

字段

builder: *Build

std.Build.Dependency.artifact

函数

第 1856 行

pub fn artifact(d: *Dependency, name: []const u8) *Step.Compile

参数

d: *Dependency
name: []const u8

std.Build.Dependency.module

函数

第 1877 行

pub fn module(d: *Dependency, name: []const u8) *Module

参数

d: *Dependency
name: []const u8

std.Build.Dependency.namedLazyPath

函数

第 1895 行

pub fn namedLazyPath(d: *Dependency, name: []const u8) LazyPath

参数

d: *Dependency
name: []const u8

std.Build.Dependency.namedWriteFiles

函数

第 1886 行

pub fn namedWriteFiles(d: *Dependency, name: []const u8) *Step.WriteFile

参数

d: *Dependency
name: []const u8

std.Build.Dependency.path

函数

第 1904 行

pub fn path(d: *Dependency, sub_path: []const u8) LazyPath

参数

d: *Dependency
sub_path: []const u8

std.Build.dependencyFromBuildZig

函数

第 2085 行

构建系统实现细节。

pub fn dependencyFromBuildZig( b: *Build, comptime build_zig: type, args: anytype, ) *Dependency

参数

b: *Build
build_zig: type

依赖项的 build.zig 结构体,通常通过 @import 该依赖项获得。 若在 build.zig 文件自身调用,则用 @This 获取该结构体的引用。

std.Build.dependencyLazy

函数

第 1974 行

声明当前配置确实需要某个可能采用 惰性获取的依赖。

若依赖已获取,则返回该依赖。但如果 依赖尚未获取,构建脚本运行 结束后,工具链不会进入实际构建阶段; 父进程会额外获取运行构建脚本时 实际需要的所有惰性依赖,重新编译构建脚本, 再运行一次。换言之,若此函数返回 error.LazyDependencyNeeded,则完成当前配置阶段的唯一目的 是找出还需要哪些其他惰性依赖。 此时必须将错误一路向上传播, 并从主构建函数返回。

对于非惰性依赖,此操作始终成功。

pub fn dependencyLazy(b: *Build, name: []const u8, args: anytype) error{LazyDependencyNeeded}!*Dependency

参数

b: *Build
name: []const u8

错误

LazyDependencyNeeded

std.Build.dependencyResolved

函数

第 2110 行

接管 package_options 的所有权;其可能尚未排序。

fn dependencyResolved( b: *Build, name: []const u8, entry: PackageEntry, package_options: *PackageOptions.Map, ) *Dependency

参数

b: *Build
name: []const u8
entry: PackageEntry
package_options: *PackageOptions.Map

std.Build.dependOnDirectoryContents

函数

第 2665 行

表示 build.zig 逻辑依赖某个目录中的条目。

这是 Graph.poisonCache 的替代方案,可避免每次 调用 zig build 都导致缓存未命中。

如果在该目录中创建、删除或重命名文件,使其条目的 存在状态和命名相对于上次配置发生变化, 则会重新执行配置阶段。

仅支持 LazyPath 的以下子集:

  • 相对于当前工作目录
  • 相对于任意软件包根目录
  • 相对于 Zig 缓存或 Zig 安装目录

如果该目录位于某个搜索前缀内,则无法跟踪此依赖; 必须改用 Graph.poisonCache。

不递归。

pub fn dependOnDirectoryContents(b: *Build, lazy_path: LazyPath) void

参数

b: *Build
lazy_path: LazyPath

std.Build.dependOnDirectoryMetadata

函数

第 2693 行

表示 build.zig 逻辑依赖特定目录的最后修改时间。

这是 Graph.poisonCache 的替代方案,避免每次调用 zig build 都造成缓存未命中。

若此目录内有任何文件被创建、删除或重命名,将重新执行配置阶段。

仅支持部分 LazyPath:

  • 相对于当前工作目录。
  • 相对于任意包根目录。
  • 相对于 Zig 缓存或 Zig 安装目录。

若目录位于某个搜索前缀内部,则无法跟踪依赖;此时必须改用 Graph.poisonCache。

不递归。

pub fn dependOnDirectoryMetadata(b: *Build, lazy_path: LazyPath) void

参数

b: *Build
lazy_path: LazyPath

std.Build.dependOnFileContents

函数

第 2611 行

表示 build.zig 逻辑依赖某个文件的内容。

若文件被创建、删除或内容发生变化,将重新执行配置阶段。若 inode 或修改时间变化,但内容不变,则不会重新执行配置逻辑。

这是 Graph.poisonCache 的替代方案,避免每次调用 zig build 都造成缓存未命中。

仅支持部分 LazyPath:

  • 相对于当前工作目录。
  • 相对于任意包根目录。
  • 相对于 Zig 缓存或 Zig 安装目录。

若文件位于某个搜索前缀内部,则无法跟踪依赖;此时必须改用 Graph.poisonCache。

pub fn dependOnFileContents(b: *Build, lazy_path: LazyPath) void

参数

b: *Build
lazy_path: LazyPath

std.Build.dependOnFileMetadata

函数

第 2637 行

表示 build.zig 逻辑依赖某个文件的大小、 inode、修改时间和内容。

如果文件被创建、删除、内容改变,或 inode 改变,或修改时间改变,则重新执行配置阶段。

这是 Graph.poisonCache 的替代方案,可避免每次 调用 zig build 都导致缓存未命中。

仅支持 LazyPath 的以下子集:

  • 相对于当前工作目录
  • 相对于任意软件包根目录
  • 相对于 Zig 缓存或 Zig 安装目录

如果该文件位于某个搜索前缀内,则无法跟踪此依赖; 必须改用 Graph.poisonCache。

pub fn dependOnFileMetadata(b: *Build, lazy_path: LazyPath) void

参数

b: *Build
lazy_path: LazyPath

std.Build.dirnameAllowEmpty

函数

第 2181 行

fn dirnameAllowEmpty(full_path: []const u8) ?[]const u8

参数

full_path: []const u8

用法示例

test dirnameAllowEmpty {
    try std.testing.expectEqualStrings(
        "foo",
        dirnameAllowEmpty("foo" ++ fs.path.sep_str ++ "bar") orelse @panic("unexpected null"),
    );

    try std.testing.expectEqualStrings(
        "",
        dirnameAllowEmpty("foo") orelse @panic("unexpected null"),
    );

    try std.testing.expect(dirnameAllowEmpty("") == null);
}

std.Build.dumpBadDirnameHelp

函数

第 2472 行

fn dumpBadDirnameHelp( fail_step: ?*Step, asking_step: ?*Step, comptime msg: []const u8, args: anytype, ) anyerror!void

参数

fail_step: ?*Step
asking_step: ?*Step
msg: []const u8

std.Build.dupe

函数

第 842 行

已弃用,请改为调用 Graph.dupeString。

pub fn dupe(b: *Build, bytes: []const u8) []const u8

参数

b: *Build
bytes: []const u8

std.Build.dupePath

函数

第 852 行

已弃用,改为调用 Graph.dupePath。

pub fn dupePath(b: *Build, bytes: []const u8) []const u8

参数

b: *Build
bytes: []const u8

std.Build.dupeStrings

函数

第 847 行

已弃用,改为调用 Graph.dupeStrings。

pub fn dupeStrings(b: *Build, strings: []const []const u8) []const []const u8

参数

b: *Build
strings: []const []const u8

std.Build.ExecutableOptions

容器

第 559 行

字段

name: []const u8
root_module: *Module
version: ?std.SemanticVersion = null
linkage: ?std.builtin.LinkMode = null
max_rss: u64 = 0
use_llvm: ?bool = null
use_lld: ?bool = null
zig_lib_dir: ?LazyPath = null
win32_manifest: ?LazyPath = null

已弃用。此功能将移至外部包: https://codeberg.org/ziglang/rc

若目标文件格式支持,在编译结果中嵌入 .manifest 文件。 https://learn.microsoft.com/en-us/windows/win32/sbscs/manifest-files-reference 清单文件必须具有 .manifest 扩展名。 无论目标为何均可设置。若目标文件格式不支持嵌入清单,则忽略 .manifest 文件。

std.Build.fatal

别名

第 18 行

别名目标 std.process.fatal

std.Build.File

别名

第 15 行

别名目标 std.Io.File

std.Build.findImportPkgHashOrFatal

函数

第 1923 行

inline fn findImportPkgHashOrFatal(b: *Build, comptime asking_build_zig: type, comptime dep_name: []const u8) []const u8

参数

b: *Build
asking_build_zig: type
dep_name: []const u8

std.Build.findPkgHashOrFatal

函数

第 1914 行

fn findPkgHashOrFatal(b: *Build, name: []const u8) []const u8

参数

b: *Build
name: []const u8

std.Build.findProgram

函数

第 1621 行

立即在配置阶段查找主机上的可执行程序, 该程序可以有多个候选名称。

调用此函数会使配置缓存失效,因此仅适用于 配置逻辑确实需要观察程序是否存在 或其输出的情况。更多信息参见 Graph.CachePoison 文档。

按给定名称的顺序搜索,先检查搜索前缀, 再检查 PATH 环境变量。

Windows 文件扩展名会根据 PATHEXT 环境变量 自动搜索,无需在列表中提供。 但即使在 Windows 上,也会先检查不追加 扩展名的名称,因此可以借此设置优先级。

另请参见:

pub fn findProgram(b: *Build, options: FindProgramOptions) ?[]const u8

参数

b: *Build
options: FindProgramOptions

std.Build.findProgramLazy

函数

第 1597 行

创建一个匿名的 Step,用于在主机上搜索名称不止一种的可执行文件。

返回找到的可执行文件的 LazyPath。仅当依赖该路径的 Step 会使用该 LazyPath 时,才执行搜索。

以下情况适合使用此 API:

  • 不同系统上的二进制文件名称不一致(例如 "python" 和 "python3")。
  • 二进制文件可能由源码构建,而不是全局安装,因此可能位于某个搜索前缀路径中。

按顺序搜索名称:先检查搜索前缀,再检查 PATH 环境变量。

Windows 文件名扩展名会根据 PATHEXT 环境变量自动搜索,因此无需将扩展名包含在此列表中。 不过,即使在 Windows 上,也会先检查不追加扩展名的名称,因此可以用它们设置优先级。

另见:

pub fn findProgramLazy(b: *Build, options: Step.FindProgram.Options) LazyPath

参数

b: *Build
options: Step.FindProgram.Options

std.Build.FindProgramOptions

别名

第 1601 行

别名目标 std.Build.Step.FindProgram.Options

std.Build.fmt

函数

第 1568 行

pub fn fmt(b: *Build, comptime format: []const u8, args: anytype) []u8

参数

b: *Build
format: []const u8

std.Build.fs

别名

第 7 行

别名目标 std.fs

std.Build.getInstallStep

函数

第 953 行

pub fn getInstallStep(b: *Build) *Step

参数

b: *Build

std.Build.getUninstallStep

函数

第 957 行

pub fn getUninstallStep(b: *Build) *Step

参数

b: *Build

std.Build.Graph

容器

第 75 行

所有 Build 实例共享的状态。 位于此处而非 Build 中的设置不能按包配置。

字段

io: Io
arena: Allocator

进程生命周期。

system_integration_options: std.array_hash_map.String(SystemLibraryMode) = .empty
system_package_mode: bool = false
zig_exe: []const u8
environ_map: process.Environ.Map
needed_lazy_dependencies: std.array_hash_map.String(void) = .empty
host: ResolvedTarget

本机目标信息。在调用 build() 之前计算。

dependency_cache: PackageInstanceMap = .empty
allow_so_scripts: ?bool = null
time_report: bool = false
verbose: bool = false
stderr_mode: ?Io.Terminal.Mode = null

类似 Io.lockStderr 返回的 Io.Terminal.Mode, 但也遵循 '--color' 标志。

release_mode: ReleaseMode = .off
generated_files: std.ArrayList(*Step)
wip_configuration: Configuration.Wip
cache_poison: CachePoison = .pure
search_prefixes: std.ArrayList([]const u8) = .empty

观察此数据会污染缓存。参见 CachePoison。

configure_dependencies: ArrayList(ConfigureDependency) = .empty

std.Build.Graph.addBytes

函数

第 199 行

pub fn addBytes(graph: *Graph, bytes: []const u8) Configuration.Bytes

参数

graph: *Graph
bytes: []const u8

std.Build.Graph.addBytesList

函数

第 193 行

pub fn addBytesList(graph: *Graph, bytes_list: []const []const u8) []const Configuration.Bytes

参数

graph: *Graph
bytes_list: []const []const u8

std.Build.Graph.addGeneratedFile

函数

第 137 行

pub fn addGeneratedFile(graph: *Graph, owner: *Step) Configuration.GeneratedFileIndex

参数

graph: *Graph
owner: *Step

std.Build.Graph.addString

函数

第 204 行

pub fn addString(graph: *Graph, bytes: []const u8) Configuration.String

参数

graph: *Graph
bytes: []const u8

std.Build.Graph.alloc

函数

第 183 行

使用进程全局区域分配器分配; 分配失败时使构建失败。

pub fn alloc(graph: *const Graph, comptime T: type, n: usize) []T

参数

graph: *const Graph
T: type
n: usize

std.Build.Graph.CachePoison

容器

第 126 行

缓存受到污染,表示配置逻辑产生了副作用,或执行了其他缓存系统无法跟踪的操作。

这与各个构建步骤在求值时是否产生副作用不同;它涉及 build.zig 本身的逻辑。例如,打印 "hello world" 的 Run 步骤在执行阶段产生副作用,因此不应设置此标志;而在配置阶段检查 scdoc 是否存在,以选择某个配置选项的默认值,则需要设置此标志。

保持缓存纯净可以加快 zig build:如果生成的配置相同,就跳过配置进程。

缓存受到污染时,执行进程会在读入构建配置文件后删除它,因为该文件无法复用。

字段

pure
poisoned
disallowed

表示用户希望在缓存可能被污染时 看到栈回溯。

ignored

表示用户希望忽略缓存已受污染的状态, 仍使用缓存,允许命中过时配置的缓存。

std.Build.Graph.create

函数

第 189 行

使用进程全局区域分配器分配; 分配失败时使构建失败。

pub fn create(graph: *const Graph, comptime T: type) *T

参数

graph: *const Graph
T: type

std.Build.Graph.cwdRelativePath

函数

第 167 行

绝对路径,或相对于构建运行器进程当前工作目录的路径。

使用此函数表示依赖主机系统。

pub fn cwdRelativePath(graph: *Graph, sub_path: []const u8) LazyPath

参数

graph: *Graph
sub_path: []const u8

std.Build.Graph.dupePath

函数

第 146 行

pub fn dupePath(graph: *const Graph, bytes: []const u8) []const u8

参数

graph: *const Graph
bytes: []const u8

std.Build.Graph.dupePathInner

函数

第 150 行

fn dupePathInner(arena: Allocator, bytes: []const u8) []const u8

参数

arena: Allocator
bytes: []const u8

std.Build.Graph.dupeString

函数

第 142 行

pub fn dupeString(graph: *const Graph, bytes: []const u8) []const u8

参数

graph: *const Graph
bytes: []const u8

std.Build.Graph.dupeStrings

函数

第 157 行

pub fn dupeStrings(graph: *const Graph, strings: []const []const u8) []const []const u8

参数

graph: *const Graph
strings: []const []const u8

std.Build.Graph.path

函数

第 173 行

相对于给定基目录的路径,其各分量和内容会在 Step 解析期间的某个时刻确定。

pub fn path(graph: *Graph, base: Configuration.LazyPath.Relative.Base, sub_path: []const u8) LazyPath

参数

graph: *Graph
base: Configuration.LazyPath.Relative.Base
sub_path: []const u8

std.Build.Graph.poisonCache

函数

第 216 行

表示配置逻辑产生了副作用,或者执行了缓存系统无法跟踪的操作。

详情参见 CachePoison 文档。

可考虑使用以下接口替代此函数:

  • dependOnFileContents
pub fn poisonCache(graph: *Graph) void

参数

graph: *Graph

std.Build.installArtifact

函数

第 1459 行

使用所有默认选项创建安装步骤,并将其加入 顶层安装步骤的依赖。 如需更灵活的函数,请参见 addInstallArtifact。

pub fn installArtifact(b: *Build, artifact: *Step.Compile) void

参数

b: *Build
artifact: *Step.Compile

std.Build.installBinFile

函数

第 1483 行

dest_rel_path 相对于 bin 路径

pub fn installBinFile(b: *Build, src_path: []const u8, dest_rel_path: []const u8) void

参数

b: *Build
src_path: []const u8
dest_rel_path: []const u8

std.Build.InstallDir

容器

第 2505 行

字段

prefix: void
lib: void
bin: void
header: void
custom: []const u8

相对于前缀的路径

std.Build.InstallDir.dupe

函数

第 2514 行

复制安装目录;若设为自定义目录,则包含路径。

pub fn dupe(dir: InstallDir, graph: *const Graph) InstallDir

参数

dir: InstallDir
graph: *const Graph

std.Build.installDirectory

函数

第 1478 行

pub fn installDirectory(b: *Build, options: Step.InstallDir.Options) void

参数

b: *Build
options: Step.InstallDir.Options

std.Build.installFile

函数

第 1474 行

dest_rel_path 相对于前缀路径

pub fn installFile(b: *Build, src_path: []const u8, dest_rel_path: []const u8) void

参数

b: *Build
src_path: []const u8
dest_rel_path: []const u8

std.Build.installLibFile

函数

第 1488 行

dest_rel_path 相对于库路径

pub fn installLibFile(b: *Build, src_path: []const u8, dest_rel_path: []const u8) void

参数

b: *Build
src_path: []const u8
dest_rel_path: []const u8

std.Build.Io

别名

第 6 行

别名目标 std.Io

std.Build.isRoot

函数

第 1849 行

pub fn isRoot(b: *const Build) bool

参数

b: *const Build

std.Build.lazyDependency

函数

第 1953 行

已弃用,请改用 dependencyLazy。

pub fn lazyDependency(b: *Build, name: []const u8, args: anytype) ?*Dependency

参数

b: *Build
name: []const u8

std.Build.lazyImport

函数

第 2044 行

在 build.zig 中,此函数之于 @import,相当于 lazyDependency 之于 dependency。 若依赖为惰性依赖且尚未获取,通知父进程在构建脚本运行结束后 获取该依赖,然后返回 null。 若依赖为已获取的惰性依赖,或为非惰性依赖, 则如普通 @import 一样返回该依赖的 build.zig 结构体。

pub inline fn lazyImport( b: *Build, comptime asking_build_zig: type, comptime dep_name: []const u8, ) ?type

参数

b: *Build
asking_build_zig: type

导入依赖项的包的 build.zig 结构体。 从 build.zig 文件的 build 函数调用此函数时,通常传入 @This()。

dep_name: []const u8

std.Build.LazyPath

容器

第 2204 行

对现有路径或未来路径的引用。

字段

src_path: struct {
    owner: *std.Build,
    sub_path: []const u8,
}

相对于构建根目录的源文件路径。

generated: struct {
    index: Configuration.GeneratedFileIndex,

    /// 向上遍历父目录的数量。
    /// 0 表示生成文件自身。
    /// 1 表示生成文件所在目录。
    /// 2 表示该目录的父目录,依此类推。
    up: usize = 0,

    /// 在 `up` 之后应用。
    sub_path: []const u8 = "",
}
cwd_relative: []const u8

已弃用;请改用 Graph.cwdRelativePath。

dependency: struct {
    dependency: *Dependency,
    sub_path: []const u8,
}
relative: struct {
    base: Configuration.LazyPath.Relative.Base,
    sub_path: []const u8 = "",

    pub fn eql(a: @This(), b: @This()) bool {
        return a.base == b.base and mem.eql(u8, a.sub_path, b.sub_path);
    }
}

std.Build.LazyPath.addStepDependencies

函数

第 2370 行

将此文件来源隐含的依赖项添加到给定步骤。

pub fn addStepDependencies(lazy_path: LazyPath, other_step: *Step) void

参数

lazy_path: LazyPath
other_step: *Step

std.Build.LazyPath.cache_root

常量

第 2247 行

项目本地缓存目录的路径(通常名为 ".zig-cache")。

LazyPath

std.Build.LazyPath.dirname

函数

第 2256 行

返回指向包含此路径的目录的延迟路径。

目录名不得越出底层路径的 逻辑根。例如,如果路径相对于构建根目录, 则目录名不得遍历到构建根目录之外。 同样,如果路径为 zig-cache 内生成的文件, 则目录名不得遍历到 zig-cache 之外。

pub fn dirname(lazy_path: LazyPath) LazyPath

参数

lazy_path: LazyPath

std.Build.LazyPath.dupe

函数

第 2384 行

复制内部字符串。

graph 参数仅用于全局区域分配器。

pub fn dupe(lazy_path: LazyPath, graph: *const Graph) LazyPath

参数

lazy_path: LazyPath
graph: *const Graph

std.Build.LazyPath.dupeInner

函数

第 2398 行

fn dupeInner(lazy_path: LazyPath, arena: Allocator) LazyPath

参数

lazy_path: LazyPath
arena: Allocator

std.Build.LazyPath.dupeList

函数

第 2391 行

复制路径切片及其中全部内部字符串。

graph 参数仅用于全局 arena 分配器。

pub fn dupeList(lazy_paths: []const LazyPath, graph: *const Graph) []const LazyPath

参数

lazy_paths: []const LazyPath
graph: *const Graph

std.Build.LazyPath.eql

函数

第 2236 行

pub fn eql(a: @This(), b: @This()) bool

参数

a: @This()
b: @This()

std.Build.LazyPath.eql

函数

第 2418 行

fn eql(a: LazyPath, b: LazyPath) bool

参数

std.Build.LazyPath.format

函数

第 2359 行

pub fn format(lp: LazyPath, w: *Io.Writer) Io.Writer.Error!void

参数

lp: LazyPath
w: *Io.Writer

错误

WriteFailed

详细诊断信息见 Writer 实现。

std.Build.LazyPath.getDisplayName

函数

第 2349 行

已弃用,改用 format。

pub fn getDisplayName(lazy_path: LazyPath) []const u8

参数

lazy_path: LazyPath

std.Build.LazyPath.hash

函数

第 2446 行

fn hash(lp: LazyPath, hasher: *std.hash.Wyhash) void

参数

lp: LazyPath
hasher: *std.hash.Wyhash

std.Build.LazyPath.join

函数

第 2323 行

pub fn join(lazy_path: LazyPath, arena: Allocator, sub_path: []const u8) Allocator.Error!LazyPath

参数

lazy_path: LazyPath
arena: Allocator
sub_path: []const u8

错误

OutOfMemory

std.Build.LazyPath.path

函数

第 2317 行

pub fn path(lazy_path: LazyPath, b: *Build, sub_path: []const u8) LazyPath

参数

lazy_path: LazyPath
b: *Build
sub_path: []const u8

std.Build.LazyPath.zig_exe

常量

第 2242 行

执行“zig build”所使用的 Zig 可执行文件路径。

LazyPath

std.Build.LazyPath.zig_lib

常量

第 2245 行

用于执行 "zig build" 的 Zig 安装中的 "lib/" 目录路径。

LazyPath

std.Build.LibraryOptions

容器

第 615 行

字段

linkage: std.builtin.LinkMode = .static
name: []const u8
root_module: *Module
version: ?std.SemanticVersion = null
max_rss: u64 = 0
use_llvm: ?bool = null
use_lld: ?bool = null
zig_lib_dir: ?LazyPath = null
win32_manifest: ?LazyPath = null

已弃用。此功能将移至外部包: https://codeberg.org/ziglang/rc

若目标文件格式支持,在编译结果中嵌入 .manifest 文件。 https://learn.microsoft.com/en-us/windows/win32/sbscs/manifest-files-reference 清单文件必须具有 .manifest 扩展名。 无论目标为何均可设置。若目标文件格式不支持嵌入清单,则忽略 .manifest 文件。

win32_module_definition: ?LazyPath = null

Win32 模块定义文件(.def)。

std.Build.log

别名

第 11 行

别名目标 std.log

std.Build.markInvalidUserInput

函数

第 1439 行

fn markInvalidUserInput(b: *Build) void

参数

b: *Build

std.Build.markNeededLazyDep

函数

第 1948 行

fn markNeededLazyDep(b: *Build, pkg_hash: []const u8) void

参数

b: *Build
pkg_hash: []const u8

std.Build.mem

别名

第 8 行

别名目标 std.mem

std.Build.Module

别名

第 22 行

别名目标 std.Build.Module

std.Build.ObjectOptions

容器

第 594 行

字段

name: []const u8
root_module: *Module
max_rss: u64 = 0
use_llvm: ?bool = null
use_lld: ?bool = null
zig_lib_dir: ?LazyPath = null

std.Build.option

函数

第 966 行

创建传给 build.zig 脚本的配置选项。 用户直接运行 zig build 时,可以通过 -D 参数设置。 项目依赖某个 Zig 包时,在将依赖的 build.zig 脚本作为函数调用时,以编程方式设置这些选项。 选项保留默认值时返回 null。

pub fn option(b: *Build, comptime T: type, name_raw: []const u8, description_raw: []const u8) ?T

参数

b: *Build
T: type
name_raw: []const u8
description_raw: []const u8

std.Build.package_map

常量

第 1995 行

构建系统实现细节。

std.StaticStringMap(PackageEntry)

std.Build.package_map.run

函数

第 2008 行

fn run(sb: *Build) void

参数

sb: *Build

std.Build.PackageEntry

容器

第 1986 行

字段

hash: []const u8
available: bool
build_root: []const u8
deps: AvailableDeps
run_build: ?*const fn (*Build) void

std.Build.PackageInstanceKey

容器

第 270 行

字段

pkg_hash: []const u8
options: *const PackageOptions.Map

std.Build.PackageInstanceMap

类型

第 243 行

std.Build.PackageInstanceMap.eql

函数

第 254 行

pub fn eql(_: @This(), a: PackageInstanceKey, b: PackageInstanceKey, _: usize) bool

参数

_: @This()
a: PackageInstanceKey
b: PackageInstanceKey
_: usize

std.Build.PackageInstanceMap.hash

函数

第 244 行

pub fn hash(_: @This(), k: PackageInstanceKey) u32

参数

_: @This()
k: PackageInstanceKey

std.Build.PackageOptions

命名空间

第 276 行

构建系统实现细节。

std.Build.PackageOptions.fromArgs

函数

第 335 行

fn fromArgs(arena: Allocator, map: *PackageOptions.Map, args: anytype) void

参数

std.Build.PackageOptions.Map

类型

第 277 行

std.Build.PackageOptions.sort

函数

第 343 行

pub fn sort(map: *Map) void

参数

map: *Map

std.Build.PackageOptions.sort.lessThan

函数

第 346 行

pub fn lessThan(this: @This(), a_index: usize, b_index: usize) bool

参数

this: @This()
a_index: usize
b_index: usize

std.Build.PackageOptions.UserProvided

容器

第 279 行

字段

flag: void
scalar: []const u8
list: std.ArrayList([]const u8)
map: std.array_hash_map.String(*const UserProvided)
lazy_path: LazyPath
lazy_path_list: std.ArrayList(LazyPath)

std.Build.PackageOptions.UserProvided.eql

函数

第 287 行

fn eql(a: UserProvided, b: UserProvided) bool

参数

std.Build.PackageOptions.UserProvided.hash

函数

第 319 行

fn hash(a: UserProvided, hasher: *std.hash.Wyhash) void

参数

a: UserProvided
hasher: *std.hash.Wyhash

std.Build.panic

别名

第 9 行

别名目标 std.debug.panic

std.Build.parseTargetQuery

函数

第 1240 行

从字符串获取目标查询;若解析失败,则将诊断信息输出到标准错误。 断言 options 的 diagnostics 字段为 null。如需此用例, 应改为直接调用 std.Target.Query.parse。

pub fn parseTargetQuery(options: std.Target.Query.ParseOptions) error{ParseFailed}!std.Target.Query

参数

错误

ParseFailed

std.Build.path

函数

第 1538 行

引用相对于源码根目录的文件或目录。

pub fn path(b: *Build, sub_path: []const u8) LazyPath

参数

b: *Build
sub_path: []const u8

std.Build.pathJoin

函数

第 1556 行

pub fn pathJoin(b: *Build, paths: []const []const u8) []u8

参数

b: *Build
paths: []const []const u8

std.Build.pathList

函数

第 1549 行

创建相对于源根目录的文件和/或目录列表。

pub fn pathList(b: *Build, sub_paths: []const []const u8) []const LazyPath

参数

b: *Build
sub_paths: []const []const u8

std.Build.pathResolve

函数

第 1562 行

pub fn pathResolve(b: *Build, paths: []const []const u8) []u8

参数

b: *Build
paths: []const []const u8

std.Build.pkgHashFromBuildZig

函数

第 2074 行

inline fn pkgHashFromBuildZig(comptime build_zig: type) ?[]const u8

参数

build_zig: type

std.Build.process

别名

第 14 行

别名目标 std.process

std.Build.ReleaseMode

容器

第 65 行

字段

off
any
fast
safe
small

std.Build.ResolvedTarget

容器

第 2535 行

由目标查询和完全解析后的目标构成的一对。 需要接收目标的构建系统 API 通常要求此类型。 保留查询是因为 Zig 工具链需要知道目标的哪些部分 为“本机”,可能适用于 CPU、操作系统,甚至 ABI。

字段

query: Target.Query
result: Target

std.Build.resolveTargetQuery

函数

第 2542 行

将目标查询转换为完全解析的目标,可传给 API 的各个部分。

pub fn resolveTargetQuery(b: *Build, query: Target.Query) ResolvedTarget

参数

b: *Build
query: Target.Query

std.Build.run

函数

第 1811 行

立即执行所提供的命令。

若程序成功退出,则返回 stdout。否则,使构建失败, 并提供有助于排查的消息。

另见:

pub fn run(b: *Build, argv: []const []const u8) []u8

参数

b: *Build
argv: []const []const u8

std.Build.runAllowFail

函数

第 1700 行

已弃用;使用 runFallible。

pub fn runAllowFail( b: *Build, argv: []const []const u8, exit_code: *u8, stderr_behavior: process.SpawnOptions.StdIo, ) anyerror![]u8

参数

b: *Build
argv: []const []const u8
exit_code: *u8
stderr_behavior: process.SpawnOptions.StdIo

std.Build.runFallible

函数

第 1755 行

立即执行所提供的命令,允许失败。

若程序成功退出,返回 stdout。否则,返回 失败指示。

另见:

pub fn runFallible(b: *Build, argv: []const []const u8, options: RunOptions) RunResult

参数

b: *Build
argv: []const []const u8
options: RunOptions

std.Build.RunOptions

容器

第 1723 行

字段

stderr_behavior: process.SpawnOptions.StdIo = .inherit
stdout_limit: Io.Limit = .limited(1_000_000)

若标准输出大于此值,使配置失败。

cwd: process.Child.Cwd = .inherit

设置后,在派生子进程时更改当前工作 目录。

environ_map: ?*const process.Environ.Map = null

提供时替换子进程环境。此处的 PATH 值 不用于解析 argv[0];该解析始终使用父进程环境。

expand_arg0: process.ArgExpansion = .no_expand

std.Build.runPackageScript

函数

第 2155 行

构建系统实现细节。

pub inline fn runPackageScript(b: *Build, comptime build_zig: anytype) void

参数

b: *Build

std.Build.RunResult

容器

第 1737 行

字段

success: []u8

子进程以退出码 0 退出,并写出此标准输出。

spawn_failed: process.SpawnError

无法创建子进程。

bad_exit_code: u8

子进程报告执行失败。

crashed

子进程异常终止。

std.Build.Serialize

别名

第 27 行

将 Build 转换为 Configuration 的逻辑。

别名目标 std.Build.Serialize

std.Build.serializeConfigurationExiting

函数

第 2726 行

构建系统实现细节。

pub fn serializeConfigurationExiting(b: *Build) noreturn

参数

b: *Build

std.Build.Sha256

别名

第 16 行

别名目标 std.crypto.sha2.Sha256

std.Build.standardOptimizeOption

函数

第 1193 行

pub fn standardOptimizeOption(b: *Build, options: StandardOptimizeOptionOptions) std.builtin.Optimize

参数

std.Build.StandardOptimizeOptionOptions

容器

第 1189 行

字段

preferred_optimize_mode: ?std.builtin.Optimize = null

std.Build.standardTargetOptions

函数

第 1231 行

提供用于选择目标的标准 zig build 选项, 并额外解析目标查询。

pub fn standardTargetOptions(b: *Build, args: StandardTargetOptionsArgs) ResolvedTarget

参数

std.Build.StandardTargetOptionsArgs

容器

第 1224 行

字段

whitelist: ?[]const Target.Query = null
default_target: Target.Query = .{}

std.Build.standardTargetOptionsQueryOnly

函数

第 1287 行

提供用于选择目标的标准 zig build 选项。

pub fn standardTargetOptionsQueryOnly(b: *Build, args: StandardTargetOptionsArgs) Target.Query

参数

std.Build.std

别名

第 5 行

别名目标 std

std.Build.step

函数

第 1168 行

创建顶层构建步骤,向命令行用户公开, 并在 "--help" 菜单中列出。

pub fn step(b: *Build, name: []const u8, description: []const u8) *Step

参数

b: *Build
name: []const u8
description: []const u8

std.Build.Step

别名

第 21 行

别名目标 std.Build.Step

std.Build.supportedWindowsProgramExtension

函数

第 1650 行

fn supportedWindowsProgramExtension(ext: []const u8) bool

参数

ext: []const u8

std.Build.systemIntegrationOption

函数

第 2564 行

pub fn systemIntegrationOption( b: *Build, name: []const u8, config: SystemIntegrationOptionConfig, ) bool

参数

b: *Build
name: []const u8
config: SystemIntegrationOptionConfig

std.Build.SystemIntegrationOptionConfig

容器

第 2559 行

字段

default: ?bool = null

若保留为 null,则默认值取决于 system_package_mode。

std.Build.SystemLibraryMode

容器

第 228 行

字段

user_disabled

用户要求禁用该库。 构建运行器尚未确认是否识别此设置。

user_enabled

用户要求启用该库。 构建运行器尚未确认是否识别此设置。

declared_disabled

构建运行器已确认识别此设置。 此库的系统集成已确定为关闭。

declared_enabled

构建运行器已确认识别此设置。 与此库的系统集成已确定为开启。

std.Build.Target

别名

第 13 行

别名目标 std.Target

std.Build.TestOptions

容器

第 653 行

字段

name: []const u8 = "test"
root_module: *Module
max_rss: u64 = 0
filters: []const []const u8 = &.{}
test_runner: ?Step.Compile.TestRunner = null
use_llvm: ?bool = null
use_lld: ?bool = null
zig_lib_dir: ?LazyPath = null
emit_object: bool = false

输出目标文件而不是测试二进制文件。 目标文件必须单独链接。 通常与自定义 test_runner 配合使用。

std.Build.tmpPath

函数

第 2526 行

创建指向本地缓存“tmp”子目录内目录的路径。 目录按需创建,并在构建成功后 由构建运行器清理。

pub fn tmpPath(b: *Build) LazyPath

参数

b: *Build

std.Build.tryFindProgram

函数

第 1657 行

fn tryFindProgram(b: *Build, full_path: []const u8) ?[]const u8

参数

b: *Build
full_path: []const u8

std.Build.typeToEnum

函数

第 1416 行

fn typeToEnum(comptime T: type) Configuration.AvailableOption.Type

参数

T: type

std.Build.validateConfigureDependency

函数

第 2703 行

fn validateConfigureDependency(lazy_path: LazyPath) void

参数

lazy_path: LazyPath

std.Build.validateUserInputDidItFail

函数

第 1443 行

fn validateUserInputDidItFail(b: *Build) bool

参数

b: *Build

std.Build.wantSharedLibSymLinks

函数

第 2555 行

pub fn wantSharedLibSymLinks(target: Target) bool

参数

target: Target
源码

std/Build.zig

const Build = @This();

const builtin = @import("builtin");

const std = @import("std.zig");
const Io = std.Io;
const fs = std.fs;
const mem = std.mem;
const panic = std.debug.panic;
const assert = std.debug.assert;
const log = std.log;
const Allocator = std.mem.Allocator;
const Target = std.Target;
const process = std.process;
const File = std.Io.File;
const Sha256 = std.crypto.hash.sha2.Sha256;
const ArrayList = std.ArrayList;
const fatal = std.process.fatal;

pub const Cache = @import("Build/Cache.zig");
pub const Step = @import("Build/Step.zig");
pub const Module = @import("Build/Module.zig");
pub const abi = @import("Build/abi.zig");
/// configure 阶段序列化的输出,由 make 阶段读取。
pub const Configuration = @import("Build/Configuration.zig");
/// 将 `Build` 转换为 `Configuration` 的逻辑。
pub const Serialize = @import("Build/Serialize.zig");

/// 全部 Build 实例共享的状态。
graph: *Graph,
install_tls: Step.TopLevel,
uninstall_tls: Step.TopLevel,
allocator: Allocator,
default_step: *Step,
top_level_steps: std.array_hash_map.String(*Step.TopLevel),
/// 包含 build.zig 的目录路径。
root: Cache.Path,
debug_log_scopes: []const []const u8 = &.{},
/// 为调试记录 `StackTrace` 时捕获的栈帧数,
/// 尤其是在创建 `Step` 时。
/// 设为 0 可禁用栈信息收集。
debug_stack_frames_count: u8 = 8,

user_input_options: PackageOptions.Map,
available_options_map: std.array_hash_map.String(AvailableOption) = .empty,
invalid_user_input: bool,

dep_prefix: []const u8 = "",

modules: std.array_hash_map.String(*Module),

named_writefiles: std.array_hash_map.String(*Step.WriteFile),
named_lazy_paths: std.array_hash_map.String(LazyPath),
/// 此实例所属包的哈希。`""` 表示这是根包。
pkg_hash: []const u8,
/// 依赖名称到包哈希值的映射。
available_deps: AvailableDeps,

pub const ConfigureDependency = struct {
    lazy_path: LazyPath,
    is_directory: bool,
    metadata_only: bool,
};

pub const ReleaseMode = enum {
    off,
    any,
    fast,
    safe,
    small,
};

/// 所有 Build 实例共享的状态。
/// 位于此处而非 Build 中的设置不能按包配置。
pub const Graph = struct {
    io: Io,
    /// 进程生命周期。
    arena: Allocator,
    system_integration_options: std.array_hash_map.String(SystemLibraryMode) = .empty,
    system_package_mode: bool = false,
    zig_exe: []const u8,
    environ_map: process.Environ.Map,
    needed_lazy_dependencies: std.array_hash_map.String(void) = .empty,
    /// 本机目标信息。在调用 build() 之前计算。
    host: ResolvedTarget,
    dependency_cache: PackageInstanceMap = .empty,
    allow_so_scripts: ?bool = null,
    time_report: bool = false,
    verbose: bool = false,
    /// 类似 `Io.lockStderr` 返回的 `Io.Terminal.Mode`,
    /// 但也遵循 '--color' 标志。
    stderr_mode: ?Io.Terminal.Mode = null,
    release_mode: ReleaseMode = .off,

    /// 索引对应 `Configuration.GeneratedFileIndex`。
    generated_files: std.ArrayList(*Step),
    wip_configuration: Configuration.Wip,

    cache_poison: CachePoison = .pure,
    /// 观察此数据会污染缓存。参见 `CachePoison`。
    search_prefixes: std.ArrayList([]const u8) = .empty,

    /// 通过调用以下任一方法填充:
    /// * `dependOnFileContents`
    /// * `dependOnFileMetadata`
    /// * `dependOnDirectoryContents`
    /// * `dependOnDirectoryMetadata`
    configure_dependencies: ArrayList(ConfigureDependency) = .empty,

    /// 缓存受到污染,表示**配置逻辑**产生了副作用,或执行了其他缓存系统无法跟踪的操作。
    ///
    /// 这与各个构建步骤在求值时是否产生副作用不同;它涉及 build.zig 本身的逻辑。例如,打印 "hello world" 的 `Run` 步骤在*执行阶段*产生副作用,因此不应设置此标志;而在*配置阶段*检查 `scdoc` 是否存在,以选择某个配置选项的默认值,则需要设置此标志。
    ///
    /// 保持缓存纯净可以加快 `zig build`:如果生成的配置相同,就跳过配置进程。
    ///
    /// 缓存受到污染时,执行进程会在读入构建配置文件后删除它,因为该文件无法复用。
    ///
    ///
    ///
    ///
    ///
    ///
    ///
    ///
    ///
    pub const CachePoison = enum {
        pure,
        poisoned,
        /// 表示用户希望在缓存可能被污染时
        /// 看到栈回溯。
        disallowed,
        /// 表示用户希望忽略缓存已受污染的状态,
        /// 仍使用缓存,允许命中过时配置的缓存。
        ignored,
    };

    pub fn addGeneratedFile(graph: *Graph, owner: *Step) Configuration.GeneratedFileIndex {
        graph.generated_files.append(graph.arena, owner) catch @panic("OOM");
        return @fromBackingInt(@intCast(graph.generated_files.items.len - 1));
    }

    pub fn dupeString(graph: *const Graph, bytes: []const u8) []const u8 {
        return graph.arena.dupe(u8, bytes) catch @panic("OOM");
    }

    pub fn dupePath(graph: *const Graph, bytes: []const u8) []const u8 {
        return dupePathInner(graph.arena, bytes);
    }

    fn dupePathInner(arena: Allocator, bytes: []const u8) []const u8 {
        if (builtin.os.tag != .windows) return arena.dupe(u8, bytes) catch @panic("OOM");
        const the_copy = arena.dupe(u8, bytes) catch @panic("OOM");
        mem.replaceScalar(u8, the_copy, '/', '\\');
        return the_copy;
    }

    pub fn dupeStrings(graph: *const Graph, strings: []const []const u8) []const []const u8 {
        const array = graph.alloc([]const u8, strings.len);
        for (array, strings) |*dest, source| dest.* = dupeString(graph, source);
        return array;
    }

    /// 绝对路径,或相对于构建运行器进程当前工作目录的路径。
    ///
    /// 使用此函数表示依赖主机系统。
    ///
    pub fn cwdRelativePath(graph: *Graph, sub_path: []const u8) LazyPath {
        return @This().path(graph, .cwd, sub_path);
    }

    /// 相对于给定基目录的路径,其各分量和内容会在
    /// `Step` 解析期间的某个时刻确定。
    pub fn path(graph: *Graph, base: Configuration.LazyPath.Relative.Base, sub_path: []const u8) LazyPath {
        assert(base != .build_root);
        return .{ .relative = .{
            .base = base,
            .sub_path = @This().dupePath(graph, sub_path),
        } };
    }

    /// 使用进程全局区域分配器分配;
    /// 分配失败时使构建失败。
    pub fn alloc(graph: *const Graph, comptime T: type, n: usize) []T {
        return graph.arena.allocAdvancedWithRetAddr(T, null, n, @returnAddress()) catch @panic("OOM");
    }

    /// 使用进程全局区域分配器分配;
    /// 分配失败时使构建失败。
    pub fn create(graph: *const Graph, comptime T: type) *T {
        return @ptrCast(graph.arena.allocBytesAligned(.of(T), @sizeOf(T), @returnAddress()) catch @panic("OOM"));
    }

    pub fn addBytesList(graph: *Graph, bytes_list: []const []const u8) []const Configuration.Bytes {
        const result = graph.alloc(Configuration.Bytes, bytes_list.len);
        for (result, bytes_list) |*d, s| d.* = addBytes(graph, s);
        return result;
    }

    pub fn addBytes(graph: *Graph, bytes: []const u8) Configuration.Bytes {
        const wc = &graph.wip_configuration;
        return wc.addBytes(bytes) catch @panic("OOM");
    }

    pub fn addString(graph: *Graph, bytes: []const u8) Configuration.String {
        const wc = &graph.wip_configuration;
        return wc.addString(bytes) catch @panic("OOM");
    }

    /// 表示配置逻辑产生了副作用,或者执行了缓存系统无法跟踪的操作。
    ///
    /// 详情参见 `CachePoison` 文档。
    ///
    /// 可考虑使用以下接口替代此函数:
    /// * `dependOnFileContents`
    ///
    pub fn poisonCache(graph: *Graph) void {
        switch (graph.cache_poison) {
            .pure => graph.cache_poison = .poisoned,
            .poisoned => return,
            .disallowed => @panic("cache poisoned"),
            .ignored => log.warn("ignoring cache poisoning", .{}),
        }
    }
};

const AvailableDeps = []const struct { []const u8, []const u8 };

pub const SystemLibraryMode = enum {
    /// 用户要求禁用该库。
    /// 构建运行器尚未确认是否识别此设置。
    user_disabled,
    /// 用户要求启用该库。
    /// 构建运行器尚未确认是否识别此设置。
    user_enabled,
    /// 构建运行器已确认识别此设置。
    /// 此库的系统集成已确定为关闭。
    declared_disabled,
    /// 构建运行器已确认识别此设置。
    /// 与此库的系统集成已确定为开启。
    declared_enabled,
};

const PackageInstanceMap = std.array_hash_map.Custom(PackageInstanceKey, *Dependency, struct {
    pub fn hash(_: @This(), k: PackageInstanceKey) u32 {
        var hasher = std.hash.Wyhash.init(0);
        hasher.update(k.pkg_hash);
        for (k.options.keys(), k.options.values()) |option_key, option_value| {
            hasher.update(option_key);
            option_value.hash(&hasher);
        }
        return @truncate(hasher.final());
    }

    pub fn eql(_: @This(), a: PackageInstanceKey, b: PackageInstanceKey, _: usize) bool {
        if (!mem.eql(u8, a.pkg_hash, b.pkg_hash)) return false;
        if (a.options.count() != b.options.count()) return false;
        for (
            a.options.keys(),
            b.options.keys(),
            a.options.values(),
            b.options.values(),
        ) |a_key, b_key, a_val, b_val| {
            if (!mem.eql(u8, a_key, b_key)) return false;
            if (!a_val.eql(b_val)) return false;
        }
        return true;
    }
}, true);

const PackageInstanceKey = struct {
    pkg_hash: []const u8,
    options: *const PackageOptions.Map,
};

/// 构建系统实现细节。
pub const PackageOptions = struct {
    pub const Map = std.array_hash_map.String(UserProvided);

    pub const UserProvided = union(enum) {
        flag: void,
        scalar: []const u8,
        list: std.ArrayList([]const u8),
        map: std.array_hash_map.String(*const UserProvided),
        lazy_path: LazyPath,
        lazy_path_list: std.ArrayList(LazyPath),

        fn eql(a: UserProvided, b: UserProvided) bool {
            if (std.meta.activeTag(a) != b) return false;
            return switch (a) {
                .flag => true,
                .scalar => |a_scalar| return mem.eql(u8, a_scalar, b.scalar),
                .list => |a_list| {
                    if (a_list.items.len != b.list.items.len) return false;
                    for (a_list.items, b.list.items) |a_elem, b_elem| {
                        if (!mem.eql(u8, a_elem, b_elem))
                            return false;
                    }
                    return true;
                },
                .map => |a_map| {
                    if (a_map.count() != b.map.count()) return false;
                    for (a_map.keys(), a_map.values(), b.map.keys(), b.map.values()) |a_key, a_val, b_key, b_val| {
                        if (!mem.eql(u8, a_key, b_key)) return false;
                        if (!a_val.eql(b_val.*)) return false;
                    }
                    return true;
                },
                .lazy_path => |a_lazy_path| return a_lazy_path.eql(b.lazy_path),
                .lazy_path_list => |a_lazy_path_list| {
                    if (a_lazy_path_list.items.len != b.lazy_path_list.items.len) return false;
                    for (a_lazy_path_list.items, b.lazy_path_list.items) |a_lp, b_lp| {
                        if (!a_lp.eql(b_lp)) return false;
                    }
                    return true;
                },
            };
        }

        fn hash(a: UserProvided, hasher: *std.hash.Wyhash) void {
            hasher.update(&mem.toBytes(std.meta.activeTag(a)));
            switch (a) {
                .flag => {},
                .scalar => |scalar| hasher.update(scalar),
                .list => |*list| for (list.items) |elem| hasher.update(elem),
                .map => |*map| for (map.keys(), map.values()) |key, val| {
                    hasher.update(key);
                    val.hash(hasher);
                },
                .lazy_path => |lp| lp.hash(hasher),
                .lazy_path_list => |*list| for (list.items) |lp| lp.hash(hasher),
            }
        }
    };

    fn fromArgs(arena: Allocator, map: *PackageOptions.Map, args: anytype) void {
        const args_info = @typeInfo(@TypeOf(args)).@"struct";
        inline for (args_info.field_names, args_info.field_types) |field_name, field_type| {
            if (field_type == @TypeOf(null)) continue;
            addPackageOptionFromArg(arena, map, field_name, field_type, @field(args, field_name));
        }
    }

    pub fn sort(map: *Map) void {
        map.sortUnstable(@as(struct {
            keys: []const []const u8,
            pub fn lessThan(this: @This(), a_index: usize, b_index: usize) bool {
                return mem.lessThan(u8, this.keys[a_index], this.keys[b_index]);
            }
        }, .{ .keys = map.keys() }));
    }
};

const AvailableOption = struct {
    type_id: Configuration.AvailableOption.Type,
    description: []const u8,
    /// 若 `type_id` 为 `enum` 或 `enum_list`,则提供枚举选项列表
    enum_options: ?[]const []const u8,
};

/// 构建系统实现细节。
pub fn create(
    graph: *Graph,
    root: Cache.Path,
    available_deps: AvailableDeps,
) error{OutOfMemory}!*Build {
    const arena = graph.arena;

    const b = try arena.create(Build);
    b.* = .{
        .graph = graph,
        .root = root,
        .invalid_user_input = false,
        .allocator = arena,
        .user_input_options = .empty,
        .top_level_steps = .{},
        .default_step = undefined,
        .install_tls = .{
            .step = .init(.{
                .tag = .top_level,
                .name = "install",
                .owner = b,
            }),
            .description = "Copy build artifacts to prefix path",
        },
        .uninstall_tls = .{
            .step = .init(.{
                .tag = .top_level,
                .name = "uninstall",
                .owner = b,
            }),
            .description = "Remove build artifacts from prefix path",
        },
        .modules = .empty,
        .named_writefiles = .empty,
        .named_lazy_paths = .empty,
        .pkg_hash = "",
        .available_deps = available_deps,
    };
    try b.top_level_steps.put(arena, b.install_tls.step.name, &b.install_tls);
    try b.top_level_steps.put(arena, b.uninstall_tls.step.name, &b.uninstall_tls);
    b.default_step = &b.install_tls.step;
    return b;
}

fn createChild(
    parent: *Build,
    dep_name: []const u8,
    root: Cache.Path,
    pkg_hash: []const u8,
    pkg_deps: AvailableDeps,
    user_input_options: PackageOptions.Map,
) error{OutOfMemory}!*Build {
    const arena = parent.graph.arena;
    const child = try arena.create(Build);
    child.* = .{
        .graph = parent.graph,
        .root = root,
        .allocator = arena,
        .install_tls = .{
            .step = .init(.{
                .tag = .top_level,
                .name = "install",
                .owner = child,
            }),
            .description = "Copy build artifacts to prefix path",
        },
        .uninstall_tls = .{
            .step = .init(.{
                .tag = .top_level,
                .name = "uninstall",
                .owner = child,
            }),
            .description = "Remove build artifacts from prefix path",
        },
        .user_input_options = user_input_options,
        .invalid_user_input = false,
        .default_step = undefined,
        .top_level_steps = .{},
        .debug_log_scopes = parent.debug_log_scopes,
        .dep_prefix = parent.fmt("{s}{s}.", .{ parent.dep_prefix, dep_name }),
        .modules = .empty,
        .named_writefiles = .empty,
        .named_lazy_paths = .empty,
        .pkg_hash = pkg_hash,
        .available_deps = pkg_deps,
    };
    try child.top_level_steps.put(arena, child.install_tls.step.name, &child.install_tls);
    try child.top_level_steps.put(arena, child.uninstall_tls.step.name, &child.uninstall_tls);
    child.default_step = &child.install_tls.step;
    return child;
}

fn addPackageOptionFromArg(
    arena: Allocator,
    map: *PackageOptions.Map,
    field_name: [:0]const u8,
    comptime T: type,
    /// 若为 null,则不添加该值,但仍会对 `T` 进行类型检查。
    maybe_value: ?T,
) void {
    map.ensureUnusedCapacity(arena, 2) catch @panic("OOM");
    switch (T) {
        Target.Query => return if (maybe_value) |v| {
            map.putAssumeCapacity(field_name, .{ .scalar = v.zigTriple(arena) catch @panic("OOM") });
            map.putAssumeCapacity("cpu", .{ .scalar = v.serializeCpuAlloc(arena) catch @panic("OOM") });
        },
        ResolvedTarget => return if (maybe_value) |v| {
            map.putAssumeCapacity(field_name, .{ .scalar = v.query.zigTriple(arena) catch @panic("OOM") });
            map.putAssumeCapacity("cpu", .{ .scalar = v.query.serializeCpuAlloc(arena) catch @panic("OOM") });
        },
        std.zig.BuildId => return if (maybe_value) |v| {
            map.putAssumeCapacity(field_name, .{
                .scalar = std.fmt.allocPrint(arena, "{f}", .{v}) catch @panic("OOM"),
            });
        },
        LazyPath => return if (maybe_value) |v| {
            map.putAssumeCapacity(field_name, .{ .lazy_path = v.dupeInner(arena) });
        },
        []const LazyPath => return if (maybe_value) |v| {
            var list: std.ArrayList(LazyPath) = .empty;
            const elems = list.addManyAsSlice(arena, v.len) catch @panic("OOM");
            for (v, elems) |lp, *elem| elem.* = lp.dupeInner(arena);
            map.putAssumeCapacity(field_name, .{ .lazy_path_list = list });
        },
        []const u8 => return if (maybe_value) |v| {
            map.putAssumeCapacity(field_name, .{ .scalar = arena.dupe(u8, v) catch @panic("OOM") });
        },
        []const []const u8 => return if (maybe_value) |v| {
            var list: std.ArrayList([]const u8) = .empty;
            const elems = list.addManyAsSlice(arena, v.len) catch @panic("OOM");
            for (v, elems) |s, *elem| elem.* = arena.dupe(u8, s) catch @panic("OOM");
            map.putAssumeCapacity(field_name, .{ .list = list });
        },
        else => switch (@typeInfo(T)) {
            .bool => return if (maybe_value) |v| {
                map.putAssumeCapacity(field_name, .{ .scalar = if (v) "true" else "false" });
            },
            .@"enum", .enum_literal => return if (maybe_value) |v| {
                map.putAssumeCapacity(field_name, .{ .scalar = @tagName(v) });
            },
            .comptime_int, .int => return if (maybe_value) |v| {
                map.putAssumeCapacity(field_name, .{
                    .scalar = std.fmt.allocPrint(arena, "{d}", .{v}) catch @panic("OOM"),
                });
            },
            .comptime_float, .float => return if (maybe_value) |v| {
                map.putAssumeCapacity(field_name, .{
                    .scalar = std.fmt.allocPrint(arena, "{x}", .{v}) catch @panic("OOM"),
                });
            },
            .pointer => |ptr_info| switch (ptr_info.size) {
                .one => switch (@typeInfo(ptr_info.child)) {
                    .array => |array_info| return addPackageOptionFromArg(
                        arena,
                        map,
                        field_name,
                        @Pointer(.slice, .{ .@"const" = true }, array_info.child, null),
                        maybe_value orelse null,
                    ),
                    else => {},
                },
                .slice => switch (@typeInfo(ptr_info.child)) {
                    .@"enum" => return if (maybe_value) |v| {
                        var list: std.ArrayList([]const u8) = .empty;
                        const elems = list.addManyAsSlice(arena, v.len) catch @panic("OOM");
                        for (elems, v) |*elem, tag| elem.* = @tagName(tag);
                        map.putAssumeCapacity(field_name, .{ .list = list });
                    },
                    else => return addPackageOptionFromArg(
                        arena,
                        map,
                        field_name,
                        @Pointer(ptr_info.size, .{ .@"const" = true }, ptr_info.child, null),
                        maybe_value orelse null,
                    ),
                },
                else => {},
            },
            .null => unreachable,
            .optional => |info| switch (@typeInfo(info.child)) {
                .optional => {},
                else => return addPackageOptionFromArg(arena, map, field_name, info.child, maybe_value orelse null),
            },
            else => {},
        },
    }
    @compileError("option '" ++ field_name ++ "' has unsupported type: " ++ @typeName(T));
}

/// 创建一组键值对,可将其转换为 Zig 源文件,
/// 随后插入 Zig 编译的模块表以供导入。
///
/// 由此可通过 `@import` 向 Zig 源码暴露 build.zig 中的值。
/// 相关接口:`Module.addOptions`。
pub fn addOptions(b: *Build) *Step.Options {
    return Step.Options.create(b);
}

pub const ExecutableOptions = struct {
    name: []const u8,
    root_module: *Module,
    version: ?std.SemanticVersion = null,
    linkage: ?std.builtin.LinkMode = null,
    max_rss: u64 = 0,
    use_llvm: ?bool = null,
    use_lld: ?bool = null,
    zig_lib_dir: ?LazyPath = null,
    /// 已弃用。此功能将移至外部包:
    /// https://codeberg.org/ziglang/rc
    ///
    /// 若目标文件格式支持,在编译结果中嵌入 `.manifest` 文件。
    /// https://learn.microsoft.com/en-us/windows/win32/sbscs/manifest-files-reference
    /// 清单文件必须具有 `.manifest` 扩展名。
    /// 无论目标为何均可设置。若目标文件格式不支持嵌入清单,则忽略 `.manifest` 文件。
    ///
    win32_manifest: ?LazyPath = null,
};

pub fn addExecutable(b: *Build, options: ExecutableOptions) *Step.Compile {
    return .create(b, .{
        .name = options.name,
        .root_module = options.root_module,
        .version = options.version,
        .kind = .exe,
        .linkage = options.linkage,
        .max_rss = options.max_rss,
        .use_llvm = options.use_llvm,
        .use_lld = options.use_lld,
        .zig_lib_dir = options.zig_lib_dir,
        .win32_manifest = options.win32_manifest,
    });
}

pub const ObjectOptions = struct {
    name: []const u8,
    root_module: *Module,
    max_rss: u64 = 0,
    use_llvm: ?bool = null,
    use_lld: ?bool = null,
    zig_lib_dir: ?LazyPath = null,
};

pub fn addObject(b: *Build, options: ObjectOptions) *Step.Compile {
    return .create(b, .{
        .name = options.name,
        .root_module = options.root_module,
        .kind = .obj,
        .max_rss = options.max_rss,
        .use_llvm = options.use_llvm,
        .use_lld = options.use_lld,
        .zig_lib_dir = options.zig_lib_dir,
    });
}

pub const LibraryOptions = struct {
    linkage: std.builtin.LinkMode = .static,
    name: []const u8,
    root_module: *Module,
    version: ?std.SemanticVersion = null,
    max_rss: u64 = 0,
    use_llvm: ?bool = null,
    use_lld: ?bool = null,
    zig_lib_dir: ?LazyPath = null,
    /// 已弃用。此功能将移至外部包:
    /// https://codeberg.org/ziglang/rc
    ///
    /// 若目标文件格式支持,在编译结果中嵌入 `.manifest` 文件。
    /// https://learn.microsoft.com/en-us/windows/win32/sbscs/manifest-files-reference
    /// 清单文件必须具有 `.manifest` 扩展名。
    /// 无论目标为何均可设置。若目标文件格式不支持嵌入清单,则忽略 `.manifest` 文件。
    ///
    win32_manifest: ?LazyPath = null,
    /// Win32 模块定义文件(.def)。
    win32_module_definition: ?LazyPath = null,
};

pub fn addLibrary(b: *Build, options: LibraryOptions) *Step.Compile {
    return .create(b, .{
        .name = options.name,
        .root_module = options.root_module,
        .kind = .lib,
        .linkage = options.linkage,
        .version = options.version,
        .max_rss = options.max_rss,
        .use_llvm = options.use_llvm,
        .use_lld = options.use_lld,
        .zig_lib_dir = options.zig_lib_dir,
        .win32_manifest = options.win32_manifest,
        .win32_module_definition = options.win32_module_definition,
    });
}

pub const TestOptions = struct {
    name: []const u8 = "test",
    root_module: *Module,
    max_rss: u64 = 0,
    filters: []const []const u8 = &.{},
    test_runner: ?Step.Compile.TestRunner = null,
    use_llvm: ?bool = null,
    use_lld: ?bool = null,
    zig_lib_dir: ?LazyPath = null,
    /// 输出目标文件而不是测试二进制文件。
    /// 目标文件必须单独链接。
    /// 通常与自定义 `test_runner` 配合使用。
    emit_object: bool = false,
};

/// 创建包含单元测试的可执行文件。
///
/// 等同于执行命令 `zig test --test-no-exec ...`。
///
/// **此步骤不运行单元测试**。通常会将此
/// 函数的结果传给 `addRunArtifact`,创建 `Step.Run`。
/// 将这两个步骤分开,是因为它们独立配置和
/// 缓存。
pub fn addTest(b: *Build, options: TestOptions) *Step.Compile {
    return .create(b, .{
        .name = options.name,
        .kind = if (options.emit_object) .test_obj else .@"test",
        .root_module = options.root_module,
        .max_rss = options.max_rss,
        .filters = b.graph.dupeStrings(options.filters),
        .test_runner = options.test_runner,
        .use_llvm = options.use_llvm,
        .use_lld = options.use_lld,
        .zig_lib_dir = options.zig_lib_dir,
    });
}

pub const AssemblyOptions = struct {
    name: []const u8,
    source_file: LazyPath,
    /// 要选择与构建程序包的计算机相同的目标,请传入
    /// 程序包 `Build` 实例的 `host` 字段。
    target: ResolvedTarget,
    optimize: std.builtin.Optimize,
    max_rss: u64 = 0,
    zig_lib_dir: ?LazyPath = null,
};

/// 此函数创建模块并将其加入包的模块集合,
/// 使依赖当前包的其他包可以使用该模块。
/// 若要创建私有模块,可改用 `createModule`。
pub fn addModule(b: *Build, name: []const u8, options: Module.CreateOptions) *Module {
    const graph = b.graph;
    const arena = graph.arena;
    const module = Module.create(b, options);
    const gop = b.modules.getOrPutValue(
        arena,
        graph.dupeString(name),
        module,
    ) catch @panic("OOM");
    if (gop.found_existing) {
        panic("A module with the name {q} has already been added to the package. Consider creating a private module with std.Build.createModule", .{name});
    }
    return module;
}

/// 创建供当前包使用的私有模块,
/// 但不向依赖本包的其他包暴露。
/// 若要创建公共模块,可改用 `addModule`。
pub fn createModule(b: *Build, options: Module.CreateOptions) *Module {
    return Module.create(b, options);
}

/// 创建在主机系统上执行进程的步骤。
///
/// `argv` 是传递给被执行进程的一个或多个命令行
/// 参数。第一个元素是要运行的可执行程序名称。
/// 可使用 `Step.Run` 的方法添加更多命令行参数,例如:
/// * `Step.Run.addArgs`
/// * `Step.Run.addArtifactArg`
/// * `Step.Run.addFileArg`
/// * `Step.Run.addOutputFileArg`
///
/// 此函数引入系统依赖,影响可复现性,
/// 并使配置用于从源码构建项目的
/// 计算机环境更加困难。
///
/// 另请参见:
/// * `addRunArtifact`
/// * `addRunFile`
pub fn addSystemCommand(b: *Build, argv: []const []const u8) *Step.Run {
    assert(argv.len >= 1);
    const run_step = Step.Run.create(b, b.fmt("run {s}", .{argv[0]}));
    run_step.addArgs(argv);
    return run_step;
}

/// 创建 `Step.Run`,使用通过 `addExecutable` 构建的可执行程序。
/// 使用 `Step.Run` 的方法添加命令行参数。
///
/// 目标不必是主机。在某些情况下,
/// 交叉编译的二进制文件也可执行。
///
/// 此操作是声明式的:构造一个构建步骤,是否实际运行
/// 取决于用户传给构建命令的选项。
///
/// 另请参见:
/// * `addSystemCommand`
/// * `addRunFile`
pub fn addRunArtifact(b: *Build, exe: *Step.Compile) *Step.Run {
    // 避免步骤名称形如 "run test test" 的常见情况。
    const step_name = if (exe.kind.isTest() and mem.eql(u8, exe.name, "test"))
        b.fmt("run {t}", .{exe.kind})
    else
        b.fmt("run {t} {s}", .{ exe.kind, exe.name });

    const run_step = Step.Run.create(b, step_name);
    run_step.producer = exe;
    run_step.addArtifactArg(exe);
    if (exe.kind == .@"test") {
        const test_server_mode: bool = s: {
            if (exe.test_runner) |r| break :s r.mode == .server;
            if (exe.use_llvm == false) {
                // 若所选后端尚不成熟,无法支持服务器协议,默认测试运行器
                // 就不使用该协议。请使此逻辑与默认测试运行器实现中的
                // `need_simple` 保持一致。
                switch (exe.rootModuleTarget().cpu.arch) {
                    // stage2_aarch64
                    .aarch64,
                    .aarch64_be,
                    // stage2_powerpc
                    .powerpc,
                    .powerpcle,
                    .powerpc64,
                    .powerpc64le,
                    // stage2_riscv64
                    .riscv64,
                    => break :s false,

                    else => {},
                }
            }
            break :s true;
        };
        if (test_server_mode) {
            run_step.enableTestRunnerMode();
        } else if (exe.test_runner == null) {
            // 测试运行器若不使用 `std.zig.Server` 协议,
            // 可改用退出码报告失败。
            run_step.expectExitCode(0);
        }
    }

    return run_step;
}

/// 创建执行所提供文件的步骤。
///
/// 通过 `Step.Run` 的方法添加更多命令行参数。
///
/// 另见:
/// * `addSystemCommand`
/// * `addRunArtifact`
pub fn addRunFile(b: *Build, executable: LazyPath) *Step.Run {
    const run_step = Step.Run.create(b, b.fmt("run {f}", .{executable}));
    run_step.addFileArg(executable);
    return run_step;
}

/// 使用提供的 `values` 生成 C 头文件,可以基于
/// 模板输入文件,例如 config.h.in。
/// 提供输入模板文件时,如果 `values` 包含输入文件中没有的
/// 选项,或 `values` 缺少输入文件中存在的
/// 选项,此函数会使构建失败。
pub fn addConfigHeader(
    b: *Build,
    options: Step.ConfigHeader.Options,
    values: anytype,
) *Step.ConfigHeader {
    var options_copy = options;
    if (options_copy.first_ret_addr == null)
        options_copy.first_ret_addr = @returnAddress();

    const config_header_step = Step.ConfigHeader.create(b, options_copy);
    config_header_step.addValues(values);
    return config_header_step;
}

/// 已弃用,请改为调用 `Graph.dupeString`。
pub fn dupe(b: *Build, bytes: []const u8) []const u8 {
    return b.graph.dupeString(bytes);
}

/// 已弃用,改为调用 `Graph.dupeStrings`。
pub fn dupeStrings(b: *Build, strings: []const []const u8) []const []const u8 {
    return b.graph.dupeStrings(strings);
}

/// 已弃用,改为调用 `Graph.dupePath`。
pub fn dupePath(b: *Build, bytes: []const u8) []const u8 {
    return b.graph.dupePath(bytes);
}

pub fn addWriteFile(b: *Build, file_path: []const u8, data: []const u8) *Step.WriteFile {
    const write_file_step = b.addWriteFiles();
    _ = write_file_step.add(file_path, data);
    return write_file_step;
}

pub fn addNamedWriteFiles(b: *Build, name: []const u8) *Step.WriteFile {
    const graph = b.graph;
    const wf = Step.WriteFile.create(b);
    const gop = b.named_writefiles.getOrPutValue(
        graph.arena,
        graph.dupeString(name),
        wf,
    ) catch @panic("OOM");
    if (gop.found_existing) {
        panic(
            "A WriteFile step with the name {q} has already been added to the package. Consider creating a private WriteFile step with std.Build.addWriteFiles",
            .{name},
        );
    }
    return wf;
}

pub fn addNamedLazyPath(b: *Build, name: []const u8, lp: LazyPath) void {
    const graph = b.graph;
    const gop = b.named_lazy_paths.getOrPutValue(
        graph.arena,
        graph.dupeString(name),
        lp.dupe(graph),
    ) catch @panic("OOM");
    if (gop.found_existing) {
        panic("A LazyPath with the name {q} has already been added to the package.", .{name});
    }
}

/// 创建一个步骤,用于修改延迟创建的临时目录内的文件;
/// 构建成功后自动清理该目录。
///
/// 目录放置于 "tmp" 而不是 "o" 内,且不使用
/// 缓存。在 `make` 阶段,此步骤始终执行所有文件
/// 系统操作;构建成功完成后,此目录将
/// 与其他 tmp 目录一同删除。因此,其他步骤
/// 可以使用此目录进行修改操作。
///
/// 另请参见:
/// * `addWriteFiles`
/// * `addMutateFiles`
pub fn addTempFiles(b: *Build) *Step.WriteFile {
    const wf = addWriteFiles(b);
    wf.mode = .tmp;
    return wf;
}

/// 创建用于修改通过 `addTempFiles` 创建的临时目录的步骤。
///
/// 也可考虑 `addWriteFiles`,它用于创建可缓存的文件目录,
/// 供后续操作使用。
///
/// 此函数只能与通过 `addTempFiles` 或
/// `tmpPath` 获得的 `tmp_path` 配合使用。
pub fn addMutateFiles(b: *Build, tmp_path: LazyPath) *Step.WriteFile {
    const wf = addWriteFiles(b);
    wf.mode = .{ .mutate = tmp_path };
    tmp_path.addStepDependencies(&wf.step);
    return wf;
}

pub fn addWriteFiles(b: *Build) *Step.WriteFile {
    return Step.WriteFile.create(b);
}

/// 创建一个步骤,向相对于构建根目录的路径写入数据,
/// 修改项目源码文件。
///
/// 此构建步骤不用于常规构建
/// 过程,而是供开发者主动运行的工具,
/// 用于更新随后将提交到版本控制的源码文件。
///
/// 使用场景示例:
/// * 预编译纳入版本控制的资源
/// * 快照测试
pub fn addUpdateSourceFiles(b: *Build) *Step.UpdateSourceFiles {
    return Step.UpdateSourceFiles.create(b);
}

pub fn addFail(b: *Build, error_msg: []const u8) *Step.Fail {
    return Step.Fail.create(b, error_msg);
}

pub fn addFmt(b: *Build, options: Step.Fmt.Options) *Step.Fmt {
    return Step.Fmt.create(b, options);
}

pub fn addTranslateC(b: *Build, options: Step.TranslateC.Options) *Step.TranslateC {
    return Step.TranslateC.create(b, options);
}

pub fn getInstallStep(b: *Build) *Step {
    return &b.install_tls.step;
}

pub fn getUninstallStep(b: *Build) *Step {
    return &b.uninstall_tls.step;
}

/// 创建传给 build.zig 脚本的配置选项。
/// 用户直接运行 `zig build` 时,可以通过 `-D` 参数设置。
/// 项目依赖某个 Zig 包时,在将依赖的 build.zig
/// 脚本作为函数调用时,以编程方式设置这些选项。
/// 选项保留默认值时返回 `null`。
pub fn option(b: *Build, comptime T: type, name_raw: []const u8, description_raw: []const u8) ?T {
    const graph = b.graph;
    const arena = graph.arena;
    const name = graph.dupeString(name_raw);
    const description = graph.dupeString(description_raw);
    const type_id = comptime typeToEnum(T);
    const available_option: AvailableOption = .{
        .type_id = type_id,
        .description = description,
        .enum_options = if (type_id == .@"enum" or type_id == .enum_list) blk: {
            const E = if (type_id == .enum_list) @typeInfo(T).pointer.child else T;
            break :blk @typeInfo(E).@"enum".field_names;
        } else null,
    };
    if ((b.available_options_map.fetchPut(arena, name, available_option) catch @panic("OOM")) != null) {
        panic("option {q} declared twice", .{name});
    }
    const user_provided = b.user_input_options.get(name) orelse return null;
    switch (type_id) {
        .bool => switch (user_provided) {
            .flag => return true,
            .scalar => |s| {
                if (mem.eql(u8, s, "true")) {
                    return true;
                } else if (mem.eql(u8, s, "false")) {
                    return false;
                } else {
                    log.err("expected -D{s} to be a boolean; received: {s}", .{ name, s });
                    b.markInvalidUserInput();
                    return null;
                }
            },
            .list, .map, .lazy_path, .lazy_path_list => {
                log.err("expected -D{s} to be a boolean; received: {t}", .{ name, user_provided });
                b.markInvalidUserInput();
                return null;
            },
        },
        .int => switch (user_provided) {
            .flag, .list, .map, .lazy_path, .lazy_path_list => {
                log.err("expected -D{s} to be an integer; received: {t}", .{ name, user_provided });
                b.markInvalidUserInput();
                return null;
            },
            .scalar => |s| {
                const n = std.fmt.parseInt(T, s, 10) catch |err| switch (err) {
                    error.Overflow => {
                        log.err("-D{s} value {s} cannot fit into type {s}", .{ name, s, @typeName(T) });
                        b.markInvalidUserInput();
                        return null;
                    },
                    else => {
                        log.err("expected -D{s} to be an integer of type {s}", .{ name, @typeName(T) });
                        b.markInvalidUserInput();
                        return null;
                    },
                };
                return n;
            },
        },
        .float => switch (user_provided) {
            .flag, .map, .list, .lazy_path, .lazy_path_list => {
                log.err("expected -D{s} to be a float; received: {t}", .{ name, user_provided });
                b.markInvalidUserInput();
                return null;
            },
            .scalar => |s| {
                const n = std.fmt.parseFloat(T, s) catch {
                    log.err("expected -D{s} to be a float of type {s}", .{ name, @typeName(T) });
                    b.markInvalidUserInput();
                    return null;
                };
                return n;
            },
        },
        .@"enum" => switch (user_provided) {
            .flag, .map, .list, .lazy_path, .lazy_path_list => {
                log.err("expected -D{s} to be an enum; received: {t}.", .{ name, user_provided });
                b.markInvalidUserInput();
                return null;
            },
            .scalar => |s| {
                if (T == std.lang.Optimize) {
                    if (std.lang.Optimize.fromString(s)) |tag| {
                        return tag;
                    }
                } else if (std.meta.stringToEnum(T, s)) |tag| {
                    return tag;
                }
                log.err("expected -D{s} to be of type {q}", .{ name, @typeName(T) });
                b.markInvalidUserInput();
                return null;
            },
        },
        .string => switch (user_provided) {
            .flag, .list, .map, .lazy_path, .lazy_path_list => {
                log.err("expected -D{s} to be a string; received: {t}", .{ name, user_provided });
                b.markInvalidUserInput();
                return null;
            },
            .scalar => |s| return s,
        },
        .build_id => switch (user_provided) {
            .flag, .map, .list, .lazy_path, .lazy_path_list => {
                log.err("expected -D{s} to be an enum; received: {t}.", .{ name, user_provided });
                b.markInvalidUserInput();
                return null;
            },
            .scalar => |s| {
                if (std.zig.BuildId.parse(s)) |build_id| {
                    return build_id;
                } else |err| {
                    log.err("failed to parse option -D{s}: {t}", .{ name, err });
                    b.markInvalidUserInput();
                    return null;
                }
            },
        },
        .list => switch (user_provided) {
            .flag, .map, .lazy_path, .lazy_path_list => {
                log.err("expected -D{s} to be a list; received: {t}", .{ name, user_provided });
                b.markInvalidUserInput();
                return null;
            },
            .scalar => |s| {
                return arena.dupe([]const u8, &[_][]const u8{s}) catch @panic("OOM");
            },
            .list => |lst| return lst.items,
        },
        .enum_list => switch (user_provided) {
            .flag, .map, .lazy_path, .lazy_path_list => {
                log.err("expected -D{s} to be a list; received: {t}", .{ name, user_provided });
                b.markInvalidUserInput();
                return null;
            },
            .scalar => |s| {
                const Child = @typeInfo(T).pointer.child;
                if (Child == std.lang.Optimize) {
                    if (std.lang.Optimize.fromString(s)) |tag| {
                        return arena.dupe(Child, &.{tag}) catch @panic("OOM");
                    }
                } else {
                    if (std.meta.stringToEnum(Child, s)) |tag| {
                        return arena.dupe(Child, &.{tag}) catch @panic("OOM");
                    }
                }
                log.err("expected -D{s} to be of type {q}", .{ name, @typeName(Child) });
                b.markInvalidUserInput();
                return null;
            },
            .list => |lst| {
                const Child = @typeInfo(T).pointer.child;
                const new_list = graph.alloc(Child, lst.items.len);
                for (new_list, lst.items) |*new_item, str| {
                    if (Child == std.lang.Optimize) {
                        if (std.lang.Optimize.fromString(str)) |tag| {
                            new_item.* = tag;
                            continue;
                        }
                    }
                    if (std.meta.stringToEnum(Child, str)) |tag| {
                        new_item.* = tag;
                        continue;
                    }
                    log.err("expected -D{s} to be of type {q}", .{ name, @typeName(Child) });
                    b.markInvalidUserInput();
                    return null;
                }
                return new_list;
            },
        },
        .lazy_path => switch (user_provided) {
            .scalar => |s| return .{ .cwd_relative = s },
            .lazy_path => |lp| return lp,
            .flag, .map, .list, .lazy_path_list => {
                log.err("expected -D{s} to be a path; received: {t}", .{ name, user_provided });
                b.markInvalidUserInput();
                return null;
            },
        },
        .lazy_path_list => switch (user_provided) {
            .scalar => |s| return arena.dupe(LazyPath, &[_]LazyPath{.{ .cwd_relative = s }}) catch @panic("OOM"),
            .lazy_path => |lp| return arena.dupe(LazyPath, &[_]LazyPath{lp}) catch @panic("OOM"),
            .list => |lst| {
                const new_list = graph.alloc(LazyPath, lst.items.len);
                for (new_list, lst.items) |*new_item, str| {
                    new_item.* = .{ .cwd_relative = str };
                }
                return new_list;
            },
            .lazy_path_list => |lp_list| return lp_list.items,
            .flag, .map => {
                log.err("expected -D{s} to be a path; received: {t}", .{ name, user_provided });
                b.markInvalidUserInput();
                return null;
            },
        },
    }
}

/// 创建顶层构建步骤,向命令行用户公开,
/// 并在 "--help" 菜单中列出。
pub fn step(b: *Build, name: []const u8, description: []const u8) *Step {
    const graph = b.graph;
    const arena = graph.arena;
    const step_info = arena.create(Step.TopLevel) catch @panic("OOM");
    step_info.* = .{
        .step = .init(.{
            .tag = .top_level,
            .name = name,
            .owner = b,
        }),
        .description = graph.dupeString(description),
    };
    const gop = b.top_level_steps.getOrPut(arena, name) catch @panic("OOM");
    if (gop.found_existing) panic("A top-level step with name \"{s}\" already exists", .{name});

    gop.key_ptr.* = step_info.step.name;
    gop.value_ptr.* = step_info;

    return &step_info.step;
}

pub const StandardOptimizeOptionOptions = struct {
    preferred_optimize_mode: ?std.builtin.Optimize = null,
};

pub fn standardOptimizeOption(b: *Build, options: StandardOptimizeOptionOptions) std.builtin.Optimize {
    const graph = b.graph;

    if (options.preferred_optimize_mode) |mode| {
        if (b.option(bool, "release", "optimize for end users") orelse (graph.release_mode != .off)) {
            return mode;
        } else {
            return .debug;
        }
    }

    if (b.option(
        std.builtin.Optimize,
        "optimize",
        "Prioritize performance, safety, or binary size",
    )) |mode| {
        return mode;
    }

    return switch (graph.release_mode) {
        .off => .debug,
        .any => {
            std.debug.print("the project does not declare a preferred optimization mode. choose: --release=fast, --release=safe, or --release=small\n", .{});
            process.exit(1);
        },
        .fast => .fast,
        .safe => .safe,
        .small => .small,
    };
}

pub const StandardTargetOptionsArgs = struct {
    whitelist: ?[]const Target.Query = null,
    default_target: Target.Query = .{},
};

/// 提供用于选择目标的标准 `zig build` 选项,
/// 并额外解析目标查询。
pub fn standardTargetOptions(b: *Build, args: StandardTargetOptionsArgs) ResolvedTarget {
    const query = b.standardTargetOptionsQueryOnly(args);
    return b.resolveTargetQuery(query);
}

/// 从字符串获取目标查询;若解析失败,则将诊断信息输出到标准错误。
/// 断言 `options` 的 `diagnostics` 字段为 `null`。如需此用例,
/// 应改为直接调用 `std.Target.Query.parse`。
///
pub fn parseTargetQuery(options: std.Target.Query.ParseOptions) error{ParseFailed}!std.Target.Query {
    assert(options.diagnostics == null);
    var diags: Target.Query.ParseOptions.Diagnostics = .{};
    var opts_copy = options;
    opts_copy.diagnostics = &diags;
    return std.Target.Query.parse(opts_copy) catch |err| switch (err) {
        error.UnknownCpuModel => {
            std.debug.print("unknown CPU: {q}\navailable CPUs for architecture {t}:\n", .{
                diags.cpu_name.?, diags.arch.?,
            });
            for (diags.arch.?.allCpuModels()) |cpu| {
                std.debug.print(" {s}\n", .{cpu.name});
            }
            return error.ParseFailed;
        },
        error.UnknownCpuFeature => {
            std.debug.print(
                \\unknown CPU feature: {q}
                \\available CPU features for architecture '{t}':
                \\
            , .{
                diags.unknown_feature_name.?, diags.arch.?,
            });
            for (diags.arch.?.allFeaturesList()) |feature| {
                std.debug.print(" {s}: {s}\n", .{ feature.name, feature.description });
            }
            return error.ParseFailed;
        },
        error.UnknownOperatingSystem => {
            std.debug.print(
                \\unknown OS: {q}
                \\available operating systems:
                \\
            , .{diags.os_name.?});
            inline for (@typeInfo(Target.Os.Tag).@"enum".field_names) |field_name| {
                std.debug.print(" {s}\n", .{field_name});
            }
            return error.ParseFailed;
        },
        else => |e| {
            std.debug.print("unable to parse target {q}: {t}\n", .{ options.arch_os_abi, e });
            return error.ParseFailed;
        },
    };
}

/// 提供用于选择目标的标准 `zig build` 选项。
pub fn standardTargetOptionsQueryOnly(b: *Build, args: StandardTargetOptionsArgs) Target.Query {
    const graph = b.graph;
    const arena = graph.arena;

    const maybe_triple = b.option(
        []const u8,
        "target",
        "The CPU architecture, OS, and ABI to build for",
    );
    const mcpu = b.option(
        []const u8,
        "cpu",
        "Target CPU features to add or subtract",
    );
    const ofmt = b.option(
        []const u8,
        "ofmt",
        "Target object format",
    );
    const dynamic_linker = b.option(
        []const u8,
        "dynamic-linker",
        "Path to interpreter on the target system",
    );

    if (maybe_triple == null and mcpu == null and ofmt == null and dynamic_linker == null)
        return args.default_target;

    const triple = maybe_triple orelse "native";

    const selected_target = parseTargetQuery(.{
        .arch_os_abi = triple,
        .cpu_features = mcpu,
        .object_format = ofmt,
        .dynamic_linker = dynamic_linker,
    }) catch |err| switch (err) {
        error.ParseFailed => {
            b.markInvalidUserInput();
            return args.default_target;
        },
    };

    const whitelist = args.whitelist orelse return selected_target;

    // 确保与列表中的某一项匹配。
    for (whitelist) |q| {
        if (q.eql(selected_target))
            return selected_target;
    }

    for (whitelist) |q| {
        log.info("allowed target: -Dtarget={s} -Dcpu={s}", .{
            q.zigTriple(arena) catch @panic("OOM"),
            q.serializeCpuAlloc(arena) catch @panic("OOM"),
        });
    }
    log.err("chosen target {q} does not match one of the allowed targets", .{
        selected_target.zigTriple(arena) catch @panic("OOM"),
    });
    b.markInvalidUserInput();
    return args.default_target;
}

/// 构建系统实现细节。
pub fn addUserInputOption(b: *Build, name: []const u8, value_raw: []const u8) error{OutOfMemory}!bool {
    const graph = b.graph;
    const arena = graph.arena;
    const value = graph.dupeString(value_raw);
    const gop = try b.user_input_options.getOrPut(arena, name);

    if (!gop.found_existing) {
        gop.key_ptr.* = graph.dupeString(name);
        gop.value_ptr.* = .{ .scalar = value };
        return false;
    }

    // 选项已存在。
    switch (gop.value_ptr.*) {
        .scalar => |s| {
            // 将其转换为列表。
            var list: std.ArrayList([]const u8) = .empty;
            (try list.addManyAsArray(arena, 2)).* = .{ s, value };
            gop.value_ptr.* = .{ .list = list };
        },
        .list => |*list| try list.append(arena, value),
        .flag => {
            log.err("option -D{s}={s} conflicts with flag -D{s}", .{ name, value, name });
            return true;
        },
        .map => |*map| {
            _ = map;
            unreachable; // TODO 实现将映射作为命令行参数传入
        },
        .lazy_path => unreachable,
        .lazy_path_list => unreachable,
    }
    return false;
}

/// 构建系统实现细节。
pub fn addUserInputFlag(b: *Build, name: []const u8) error{OutOfMemory}!bool {
    const graph = b.graph;
    const arena = graph.arena;
    const gop = try b.user_input_options.getOrPut(arena, name);
    if (!gop.found_existing) {
        gop.key_ptr.* = graph.dupeString(name);
        gop.value_ptr.* = .{ .flag = {} };
        return false;
    }
    // 选项已存在。
    switch (gop.value_ptr.*) {
        .scalar => |s| {
            log.err("flag -D{s} conflicts with option -D{s}={s}", .{ name, name, s });
            return true;
        },
        .list, .map, .lazy_path_list => {
            log.err("flag -D{s} conflicts with multiple options of the same name", .{name});
            return true;
        },
        .lazy_path => |lp| {
            log.err("flag -D{s} conflicts with option -D{s}={f}", .{ name, name, lp });
            return true;
        },

        .flag => {},
    }
    return false;
}

fn typeToEnum(comptime T: type) Configuration.AvailableOption.Type {
    return switch (T) {
        std.zig.BuildId => .build_id,
        LazyPath => .lazy_path,
        else => return switch (@typeInfo(T)) {
            .int => .int,
            .float => .float,
            .bool => .bool,
            .@"enum" => .@"enum",
            .pointer => |pointer| switch (pointer.child) {
                u8 => .string,
                []const u8 => .list,
                LazyPath => .lazy_path_list,
                else => switch (@typeInfo(pointer.child)) {
                    .@"enum" => .enum_list,
                    else => @compileError("Unsupported type: " ++ @typeName(T)),
                },
            },
            else => @compileError("Unsupported type: " ++ @typeName(T)),
        },
    };
}

fn markInvalidUserInput(b: *Build) void {
    b.invalid_user_input = true;
}

fn validateUserInputDidItFail(b: *Build) bool {
    for (b.user_input_options.keys()) |name| {
        if (!b.available_options_map.contains(name)) {
            for (b.available_options_map.keys(), b.available_options_map.values()) |available_name, *available| {
                log.info("available option: {q}: {s}", .{ available_name, available.description });
            }
            log.err("invalid option: {q}", .{name});
            b.markInvalidUserInput();
        }
    }
    return b.invalid_user_input;
}

/// 使用所有默认选项创建安装步骤,并将其加入
/// 顶层安装步骤的依赖。
/// 如需更灵活的函数,请参见 `addInstallArtifact`。
pub fn installArtifact(b: *Build, artifact: *Step.Compile) void {
    b.getInstallStep().dependOn(&b.addInstallArtifact(artifact, .{}).step);
}

/// 这只创建步骤;不会将其添加到
/// 顶层安装步骤的依赖中。
pub fn addInstallArtifact(
    b: *Build,
    artifact: *Step.Compile,
    options: Step.InstallArtifact.Options,
) *Step.InstallArtifact {
    return Step.InstallArtifact.create(b, artifact, options);
}

/// `dest_rel_path` 相对于前缀路径
pub fn installFile(b: *Build, src_path: []const u8, dest_rel_path: []const u8) void {
    b.getInstallStep().dependOn(&b.addInstallFileWithDir(b.path(src_path), .prefix, dest_rel_path).step);
}

pub fn installDirectory(b: *Build, options: Step.InstallDir.Options) void {
    b.getInstallStep().dependOn(&b.addInstallDirectory(options).step);
}

/// `dest_rel_path` 相对于 bin 路径
pub fn installBinFile(b: *Build, src_path: []const u8, dest_rel_path: []const u8) void {
    b.getInstallStep().dependOn(&b.addInstallFileWithDir(b.path(src_path), .bin, dest_rel_path).step);
}

/// `dest_rel_path` 相对于库路径
pub fn installLibFile(b: *Build, src_path: []const u8, dest_rel_path: []const u8) void {
    b.getInstallStep().dependOn(&b.addInstallFileWithDir(b.path(src_path), .lib, dest_rel_path).step);
}

pub fn addObjCopy(b: *Build, source: LazyPath, options: Step.ObjCopy.Options) *Step.ObjCopy {
    return Step.ObjCopy.create(b, source, options);
}

/// `dest_rel_path` 相对于安装前缀路径。
pub fn addInstallFile(b: *Build, source: LazyPath, dest_rel_path: []const u8) *Step.InstallFile {
    return b.addInstallFileWithDir(source, .prefix, dest_rel_path);
}

/// `dest_rel_path` 相对于 bin 路径
pub fn addInstallBinFile(b: *Build, source: LazyPath, dest_rel_path: []const u8) *Step.InstallFile {
    return b.addInstallFileWithDir(source, .bin, dest_rel_path);
}

/// `dest_rel_path` 相对于库路径
pub fn addInstallLibFile(b: *Build, source: LazyPath, dest_rel_path: []const u8) *Step.InstallFile {
    return b.addInstallFileWithDir(source, .lib, dest_rel_path);
}

/// `dest_rel_path` 相对于头文件路径
pub fn addInstallHeaderFile(b: *Build, source: LazyPath, dest_rel_path: []const u8) *Step.InstallFile {
    return b.addInstallFileWithDir(source, .header, dest_rel_path);
}

pub fn addInstallFileWithDir(
    b: *Build,
    source: LazyPath,
    install_dir: InstallDir,
    dest_rel_path: []const u8,
) *Step.InstallFile {
    return Step.InstallFile.create(b, source, install_dir, dest_rel_path);
}

pub fn addInstallDirectory(b: *Build, options: Step.InstallDir.Options) *Step.InstallDir {
    return Step.InstallDir.create(b, options);
}

pub fn addCheckFile(
    b: *Build,
    file_source: LazyPath,
    options: Step.CheckFile.Options,
) *Step.CheckFile {
    return Step.CheckFile.create(b, file_source, options);
}

/// 引用相对于源码根目录的文件或目录。
pub fn path(b: *Build, sub_path: []const u8) LazyPath {
    if (fs.path.isAbsolute(sub_path)) {
        panic("sub_path is expected to be relative to the build root, but was this absolute path: {q}. Absolute paths can cause problems but can be created via Graph.cwdRelativePath", .{sub_path});
    }
    return .{ .src_path = .{
        .owner = b,
        .sub_path = sub_path,
    } };
}

/// 创建相对于源根目录的文件和/或目录列表。
pub fn pathList(b: *Build, sub_paths: []const []const u8) []const LazyPath {
    const graph = b.graph;
    const result = graph.alloc(LazyPath, sub_paths.len);
    for (result, sub_paths) |*d, s| d.* = path(b, s);
    return result;
}

pub fn pathJoin(b: *Build, paths: []const []const u8) []u8 {
    const graph = b.graph;
    const arena = graph.arena;
    return fs.path.join(arena, paths) catch @panic("OOM");
}

pub fn pathResolve(b: *Build, paths: []const []const u8) []u8 {
    const graph = b.graph;
    const arena = graph.arena;
    return fs.path.resolve(arena, paths) catch @panic("OOM");
}

pub fn fmt(b: *Build, comptime format: []const u8, args: anytype) []u8 {
    const graph = b.graph;
    const arena = graph.arena;
    return std.fmt.allocPrint(arena, format, args) catch @panic("OOM");
}

/// 创建一个匿名的 `Step`,用于在主机上搜索名称不止一种的可执行文件。
///
/// 返回找到的可执行文件的 `LazyPath`。仅当依赖该路径的 `Step` 会使用该 `LazyPath` 时,才执行搜索。
///
/// 以下情况适合使用此 API:
/// * 不同系统上的二进制文件名称不一致(例如 "python" 和 "python3")。
/// * 二进制文件可能由源码构建,而不是全局安装,因此可能位于某个搜索前缀路径中。
///
/// 按顺序搜索名称:先检查搜索前缀,再检查 PATH 环境变量。
///
/// Windows 文件名扩展名会根据 PATHEXT 环境变量自动搜索,因此无需将扩展名包含在此列表中。
/// 不过,即使在 Windows 上,也会先检查不追加扩展名的名称,因此可以用它们设置优先级。
///
/// 另见:
/// * `findProgram`
///
///
///
///
///
///
///
///
pub fn findProgramLazy(b: *Build, options: Step.FindProgram.Options) LazyPath {
    return .{ .generated = .{ .index = Step.FindProgram.create(b, options).found_path } };
}

pub const FindProgramOptions = Step.FindProgram.Options;

/// 立即在配置阶段查找主机上的可执行程序,
/// 该程序可以有多个候选名称。
///
/// 调用此函数会使配置缓存失效,因此仅适用于
/// 配置逻辑确实需要观察程序是否存在
/// 或其输出的情况。更多信息参见
/// `Graph.CachePoison` 文档。
///
/// 按给定名称的顺序搜索,先检查搜索前缀,
/// 再检查 PATH 环境变量。
///
/// Windows 文件扩展名会根据 PATHEXT 环境变量
/// 自动搜索,无需在列表中提供。
/// 但即使在 Windows 上,也会先检查不追加
/// 扩展名的名称,因此可以借此设置优先级。
///
/// 另请参见:
/// * `findProgramLazy`
pub fn findProgram(b: *Build, options: FindProgramOptions) ?[]const u8 {
    const graph = b.graph;

    // 因为它会观察搜索前缀以及 PATH 中目录的内容。
    graph.poisonCache();

    for (options.names) |name| {
        if (Io.Dir.path.isAbsolute(name)) {
            if (tryFindProgram(b, name)) |found| return found;
        }
        for (graph.search_prefixes.items) |search_prefix| {
            const full_path = b.pathJoin(&.{ search_prefix, "bin", name });
            if (tryFindProgram(b, full_path)) |found| return found;
        }
    }

    if (b.graph.environ_map.get("PATH")) |PATH| {
        for (options.names) |name| {
            var it = mem.tokenizeScalar(u8, PATH, Io.Dir.path.delimiter);
            while (it.next()) |p| {
                const full_path = b.pathJoin(&.{ p, name });
                if (tryFindProgram(b, full_path)) |found| return found;
            }
        }
    }

    return null;
}

fn supportedWindowsProgramExtension(ext: []const u8) bool {
    inline for (@typeInfo(std.process.WindowsExtension).@"enum".field_names) |field_name| {
        if (std.ascii.eqlIgnoreCase(ext, "." ++ field_name)) return true;
    }
    return false;
}

fn tryFindProgram(b: *Build, full_path: []const u8) ?[]const u8 {
    const graph = b.graph;
    const io = graph.io;
    const arena = graph.arena;

    if (Io.Dir.cwd().access(io, full_path, .{ .execute = true })) |_| {
        return full_path;
    } else |err| switch (err) {
        error.FileNotFound, error.AccessDenied, error.PermissionDenied => |e| {
            if (graph.verbose) log.info("searched: {t} {s}", .{ e, full_path });
        },
        else => |e| return panic("failed accessing {s}: {t}", .{ full_path, e }),
    }

    if (builtin.os.tag == .windows) {
        if (b.graph.environ_map.get("PATHEXT")) |PATHEXT| {
            var it = mem.tokenizeScalar(u8, PATHEXT, fs.path.delimiter);

            const extended_path_buf = arena.alloc(u8, full_path.len + 1 + std.process.WindowsExtension.max_len) catch @panic("OOM");
            @memcpy(extended_path_buf[0..full_path.len], full_path);

            while (it.next()) |ext| {
                if (!supportedWindowsProgramExtension(ext)) continue;

                @memcpy(extended_path_buf[full_path.len..][0..ext.len], ext);
                const extended_path = extended_path_buf[0 .. full_path.len + ext.len];

                if (Io.Dir.cwd().access(io, extended_path, .{ .execute = true })) |_| {
                    return extended_path;
                } else |err| switch (err) {
                    error.FileNotFound, error.AccessDenied, error.PermissionDenied => |e| {
                        if (graph.verbose) log.info("searched: {t} {s}", .{ e, extended_path });
                    },
                    else => |e| return panic("failed accessing {s}: {t}", .{ extended_path, e }),
                }
            }
        }
    }

    return null;
}

/// 已弃用;使用 `runFallible`。
pub fn runAllowFail(
    b: *Build,
    argv: []const []const u8,
    exit_code: *u8,
    stderr_behavior: process.SpawnOptions.StdIo,
) anyerror![]u8 {
    if (!process.can_spawn) return error.ExecNotSupported;
    switch (runFallible(b, argv, .{
        .stderr_behavior = stderr_behavior,
    })) {
        .success => |stdout| return stdout,
        .spawn_failed => |err| return err,
        .bad_exit_code => |code| {
            exit_code.* = code;
            return error.ExitCodeFailure;
        },
        .crashed => {
            exit_code.* = 255;
            return error.ProcessTerminated;
        },
    }
}

pub const RunOptions = struct {
    stderr_behavior: process.SpawnOptions.StdIo = .inherit,
    /// 若标准输出大于此值,使配置失败。
    stdout_limit: Io.Limit = .limited(1_000_000),
    /// 设置后,在派生子进程时更改当前工作
    /// 目录。
    cwd: process.Child.Cwd = .inherit,
    /// 提供时替换子进程环境。此处的 PATH 值
    /// 不用于解析 `argv[0]`;该解析始终使用父进程环境。
    ///
    environ_map: ?*const process.Environ.Map = null,
    expand_arg0: process.ArgExpansion = .no_expand,
};

pub const RunResult = union(enum) {
    /// 子进程以退出码 0 退出,并写出此标准输出。
    success: []u8,
    /// 无法创建子进程。
    spawn_failed: process.SpawnError,
    /// 子进程报告执行失败。
    bad_exit_code: u8,
    /// 子进程异常终止。
    crashed,
};

/// 立即执行所提供的命令,允许失败。
///
/// 若程序成功退出,返回 stdout。否则,返回
/// 失败指示。
///
/// 另见:
/// * `run`。
pub fn runFallible(b: *Build, argv: []const []const u8, options: RunOptions) RunResult {
    assert(argv.len != 0);

    const graph = b.graph;
    const io = graph.io;
    const arena = graph.arena;

    const print_opts: std.zig.AllocPrintCmdOptions = .{
        .cwd = switch (options.cwd) {
            .inherit => null,
            .path => |p| p,
            .dir => null, // 不改变 runFallible 的函数签名就无法得知。
        },
        .child_env = options.environ_map,
        .parent_env = &graph.environ_map,
    };

    if (graph.verbose) {
        const text = std.zig.allocPrintCmd(arena, argv, print_opts) catch @panic("OOM");
        std.log.scoped(.verbose).info("{s}", .{text});
    }

    var child = process.spawn(io, .{
        .argv = argv,
        .stdin = .ignore,
        .stdout = .pipe,
        .stderr = options.stderr_behavior,
        .cwd = options.cwd,
        .environ_map = &graph.environ_map,
        .expand_arg0 = options.expand_arg0,
    }) catch |err| return .{ .spawn_failed = err };

    var stdout_reader = child.stdout.?.readerStreaming(io, &.{});
    const stdout = stdout_reader.interface.allocRemaining(arena, options.stdout_limit) catch |err| switch (err) {
        error.ReadFailed => panic("failed to read from child: {t}", .{stdout_reader.err.?}),
        else => |e| panic("failed to read from child: {t}", .{e}),
    };

    const term = child.wait(io) catch @panic("unexpected");

    return switch (term) {
        .exited => |code| switch (code) {
            0 => .{ .success = stdout },
            else => .{ .bad_exit_code = code },
        },
        .signal, .stopped, .unknown => .crashed,
    };
}

/// 立即执行所提供的命令。
///
/// 若程序成功退出,则返回 stdout。否则,使构建失败,
/// 并提供有助于排查的消息。
///
/// 另见:
/// * `runFallible`。
pub fn run(b: *Build, argv: []const []const u8) []u8 {
    const graph = b.graph;
    const arena = graph.arena;
    switch (b.runFallible(argv, .{
        .stderr_behavior = .inherit,
    })) {
        .success => |stdout| return stdout,
        .spawn_failed => |err| fatal("the following command failed with {t}:\n{s}", .{
            err, std.zig.allocPrintCmd(arena, argv, .{}) catch @panic("OOM"),
        }),
        .bad_exit_code => |code| fatal("the following command exited with code {d}:\n{s}", .{
            code, std.zig.allocPrintCmd(arena, argv, .{}) catch @panic("OOM"),
        }),
        .crashed => fatal("the following command crashed:\n{s}", .{
            std.zig.allocPrintCmd(arena, argv, .{}) catch @panic("OOM"),
        }),
    }
}

/// 添加额外路径,等同于用户提供的 `--search-prefix`
/// 参数。此函数添加的路径优先级低于
/// 用户在命令行指定的路径。
///
/// 通常最佳实践是避免调用此函数,而是
/// 由用户通过标准构建系统接口
/// 提供这些路径。但与其他构建系统集成时,用户可能
/// 已将信息提供给另一个构建系统,因此
/// 应复用相同信息,避免要求用户
/// 再次提供。
pub fn addSearchPrefix(b: *Build, search_prefix: []const u8) void {
    if (b.isRoot()) {
        const graph = b.graph;
        const wc = &graph.wip_configuration;
        const string = wc.addString(search_prefix) catch @panic("OOM");
        wc.search_prefixes.append(wc.gpa, string) catch @panic("OOM");
    }
}

pub fn isRoot(b: *const Build) bool {
    return b.pkg_hash.len == 0;
}

pub const Dependency = struct {
    builder: *Build,

    pub fn artifact(d: *Dependency, name: []const u8) *Step.Compile {
        var found: ?*Step.Compile = null;
        for (d.builder.install_tls.step.dependencies.items) |dep_step| {
            const inst = dep_step.cast(Step.InstallArtifact) orelse continue;
            if (mem.eql(u8, inst.artifact.name, name)) {
                if (found != null) panic("artifact name {q} is ambiguous", .{name});
                found = inst.artifact;
            }
        }
        return found orelse {
            if (d.builder.graph.needed_lazy_dependencies.count() != 0) {
                d.builder.serializeConfigurationExiting();
            }
            for (d.builder.install_tls.step.dependencies.items) |dep_step| {
                const inst = dep_step.cast(Step.InstallArtifact) orelse continue;
                log.info("available artifact: {q}", .{inst.artifact.name});
            }
            panic("unable to find artifact {q}", .{name});
        };
    }

    pub fn module(d: *Dependency, name: []const u8) *Module {
        return d.builder.modules.get(name) orelse {
            if (d.builder.graph.needed_lazy_dependencies.count() != 0) {
                d.builder.serializeConfigurationExiting();
            }
            panic("unable to find module {q}", .{name});
        };
    }

    pub fn namedWriteFiles(d: *Dependency, name: []const u8) *Step.WriteFile {
        return d.builder.named_writefiles.get(name) orelse {
            if (d.builder.graph.needed_lazy_dependencies.count() != 0) {
                d.builder.serializeConfigurationExiting();
            }
            panic("unable to find named writefiles {q}", .{name});
        };
    }

    pub fn namedLazyPath(d: *Dependency, name: []const u8) LazyPath {
        return d.builder.named_lazy_paths.get(name) orelse {
            if (d.builder.graph.needed_lazy_dependencies.count() != 0) {
                d.builder.serializeConfigurationExiting();
            }
            panic("unable to find named lazypath {q}", .{name});
        };
    }

    pub fn path(d: *Dependency, sub_path: []const u8) LazyPath {
        return .{
            .dependency = .{
                .dependency = d,
                .sub_path = sub_path,
            },
        };
    }
};

fn findPkgHashOrFatal(b: *Build, name: []const u8) []const u8 {
    for (b.available_deps) |dep| {
        if (mem.eql(u8, dep[0], name)) return dep[1];
    }
    log.info("all dependencies used by build.zig must be declared in corresponding build.zig.zon", .{});
    if (b.pkg_hash.len == 0) panic("no dependency named {s}", .{name});
    panic("no dependency named {s} in {s} ({s})", .{ name, b.dep_prefix, b.pkg_hash });
}

inline fn findImportPkgHashOrFatal(b: *Build, comptime asking_build_zig: type, comptime dep_name: []const u8) []const u8 {
    const build_runner = @import("root");
    const deps = build_runner.dependencies;
    const arena = b.graph.arena;

    const b_pkg_hash, const b_pkg_deps = comptime for (@typeInfo(deps.packages).@"struct".decl_names) |pkg_hash| {
        const pkg = @field(deps.packages, pkg_hash);
        if (@hasDecl(pkg, "build_zig") and pkg.build_zig == asking_build_zig) break .{ pkg_hash, pkg.deps };
    } else .{ "", deps.root_deps };
    if (!mem.eql(u8, b_pkg_hash, b.pkg_hash)) {
        const build_zig_path = b.root.join(arena, "build.zig") catch @panic("OOM");
        panic("{} is not the struct that corresponds to {f}", .{
            asking_build_zig, build_zig_path,
        });
    }
    comptime for (b_pkg_deps) |dep| {
        if (mem.eql(u8, dep[0], dep_name)) return dep[1];
    };

    const full_path = b.root.join(arena, "build.zig.zon") catch @panic("OOM");
    panic("no dependency named {s} in {f}. All packages used in build.zig must be declared in this file", .{
        dep_name, full_path,
    });
}

fn markNeededLazyDep(b: *Build, pkg_hash: []const u8) void {
    b.graph.needed_lazy_dependencies.put(b.graph.arena, pkg_hash, {}) catch @panic("OOM");
}

/// 已弃用,请改用 `dependencyLazy`。
pub fn lazyDependency(b: *Build, name: []const u8, args: anytype) ?*Dependency {
    return dependencyLazy(b, name, args) catch |err| switch (err) {
        error.LazyDependencyNeeded => null,
    };
}

/// 声明当前配置确实需要某个可能采用
/// 惰性获取的依赖。
///
/// 若依赖已获取,则返回该依赖。但如果
/// 依赖尚未获取,构建脚本运行
/// 结束后,工具链不会进入实际构建阶段;
/// 父进程会额外获取运行构建脚本时
/// 实际需要的所有惰性依赖,重新编译构建脚本,
/// 再运行一次。换言之,若此函数返回
/// `error.LazyDependencyNeeded`,则完成当前配置阶段的唯一目的
/// 是找出还需要哪些其他惰性依赖。
/// 此时必须将错误一路向上传播,
/// 并从主构建函数返回。
///
/// 对于非惰性依赖,此操作始终成功。
pub fn dependencyLazy(b: *Build, name: []const u8, args: anytype) error{LazyDependencyNeeded}!*Dependency {
    const pkg_hash = findPkgHashOrFatal(b, name);
    const entry = package_map.get(pkg_hash) orelse unreachable;
    if (!entry.available) {
        markNeededLazyDep(b, pkg_hash);
        return error.LazyDependencyNeeded;
    }
    var map: PackageOptions.Map = .empty;
    PackageOptions.fromArgs(b.graph.arena, &map, args);
    return dependencyResolved(b, name, entry, &map);
}

pub const PackageEntry = struct {
    hash: []const u8,
    available: bool,
    build_root: []const u8,
    deps: AvailableDeps,
    run_build: ?*const fn (*Build) void,
};

/// 构建系统实现细节。
pub const package_map: std.StaticStringMap(PackageEntry) = blk: {
    const deps = @import("root").dependencies;
    const decl_names = @typeInfo(deps.packages).@"struct".decl_names;
    var kvs: [decl_names.len]struct { []const u8, PackageEntry } = undefined;
    for (decl_names, 0..) |decl_name, i| {
        const pkg = @field(deps.packages, decl_name);
        const available = !@hasDecl(pkg, "available") or pkg.available;
        kvs[i] = .{ decl_name, .{
            .hash = decl_name,
            .available = available,
            .build_root = if (available) pkg.build_root else "",
            .deps = if (available) pkg.deps else &.{},
            .run_build = if (available and @hasDecl(pkg, "build_zig")) &struct {
                fn run(sb: *Build) void {
                    sb.runPackageScript(pkg.build_zig);
                }
            }.run else null,
        } };
    }
    const frozen = kvs;
    break :blk .initComptime(&frozen);
};

/// 声明当前配置确实需要某个可能采用惰性获取的依赖。
///
/// 若已取得该依赖,则返回它;否则退出配置阶段,以获取此惰性依赖并重新执行配置脚本。
///
/// 若调用者此时已知还需要其他惰性依赖,改用 `dependencyLazy` 可以节省时间:以适当方式处理 `error.LazyDependencyNeeded`,在最终从顶层构建函数返回该错误之前,先将多个可能惰性获取的依赖标记为必需。
///
///
///
///
///
///
///
pub fn dependency(b: *Build, name: []const u8, args: anytype) *Dependency {
    return dependencyLazy(b, name, args) catch |err| switch (err) {
        error.LazyDependencyNeeded => {
            assert(b.graph.needed_lazy_dependencies.count() != 0);
            serializeConfigurationExiting(b);
        },
    };
}

/// 在 build.zig 中,此函数之于 `@import`,相当于 `lazyDependency` 之于 `dependency`。
/// 若依赖为惰性依赖且尚未获取,通知父进程在构建脚本运行结束后
/// 获取该依赖,然后返回 `null`。
/// 若依赖为已获取的惰性依赖,或为非惰性依赖,
/// 则如普通 `@import` 一样返回该依赖的 build.zig 结构体。
pub inline fn lazyImport(
    b: *Build,
    /// 导入依赖项的包的 build.zig 结构体。
    /// 从 build.zig 文件的 `build` 函数调用此函数时,通常传入 `@This()`。
    ///
    comptime asking_build_zig: type,
    comptime dep_name: []const u8,
) ?type {
    const build_runner = @import("root");
    const deps = build_runner.dependencies;
    const pkg_hash = findImportPkgHashOrFatal(b, asking_build_zig, dep_name);

    inline for (@typeInfo(deps.packages).@"struct".decl_names) |decl_name| {
        if (comptime mem.eql(u8, decl_name, pkg_hash)) {
            const pkg = @field(deps.packages, decl_name);
            const available = !@hasDecl(pkg, "available") or pkg.available;
            if (!available) {
                markNeededLazyDep(b, pkg_hash);
                return null;
            }
            return if (@hasDecl(pkg, "build_zig"))
                pkg.build_zig
            else
                @compileError("dependency '" ++ dep_name ++ "' does not have a build.zig");
        }
    }

    comptime unreachable; // @dependencies 来源错误
}

inline fn pkgHashFromBuildZig(comptime build_zig: type) ?[]const u8 {
    comptime {
        const deps = @import("root").dependencies;
        return for (@typeInfo(deps.packages).@"struct".decl_names) |pkg_hash| {
            const pkg = @field(deps.packages, pkg_hash);
            if (@hasDecl(pkg, "build_zig") and pkg.build_zig == build_zig) break pkg_hash;
        } else null;
    }
}

/// 构建系统实现细节。
pub fn dependencyFromBuildZig(
    b: *Build,
    /// 依赖项的 build.zig 结构体,通常通过 `@import` 该依赖项获得。
    /// 若在 build.zig 文件自身调用,则用 `@This` 获取该结构体的引用。
    comptime build_zig: type,
    args: anytype,
) *Dependency {
    const arena = b.graph.arena;

    find_dep: {
        const pkg_hash = pkgHashFromBuildZig(build_zig) orelse break :find_dep;
        const dep_name = for (b.available_deps) |dep| {
            if (mem.eql(u8, dep[1], pkg_hash)) break dep[1];
        } else break :find_dep;
        const entry = package_map.get(pkg_hash) orelse break :find_dep;
        var map: PackageOptions.Map = .empty;
        PackageOptions.fromArgs(arena, &map, args);
        return dependencyResolved(b, dep_name, entry, &map);
    }

    const full_path = b.root.join(arena, "build.zig.zon") catch @panic("OOM");
    panic("{} is not a build.zig struct of a dependency in {f}", .{ build_zig, full_path });
}

/// 接管 `package_options` 的所有权;其可能尚未排序。
fn dependencyResolved(
    b: *Build,
    name: []const u8,
    entry: PackageEntry,
    package_options: *PackageOptions.Map,
) *Dependency {
    const graph = b.graph;
    const io = graph.io;
    const arena = graph.arena;

    PackageOptions.sort(package_options);

    if (graph.dependency_cache.getContext(.{
        .pkg_hash = entry.hash,
        .options = package_options,
    }, .{})) |dep| return dep;

    const dep_root: Cache.Path = .{
        .root_dir = .{
            .path = entry.build_root,
            .handle = Io.Dir.cwd().openDir(io, entry.build_root, .{}) catch |err|
                fatal("failed to open {q}: {t}", .{ entry.build_root, err }),
        },
    };

    const sub_builder = b.createChild(name, dep_root, entry.hash, entry.deps, package_options.*) catch @panic("OOM");
    if (entry.run_build) |run_build| {
        run_build(sub_builder);

        if (sub_builder.validateUserInputDidItFail()) {
            std.debug.dumpCurrentStackTrace(.{ .first_address = @returnAddress() });
        }
    }

    const dep = graph.create(Dependency);
    dep.* = .{ .builder = sub_builder };

    graph.dependency_cache.putContext(arena, .{
        .pkg_hash = entry.hash,
        .options = &sub_builder.user_input_options,
    }, dep, .{}) catch @panic("OOM");
    return dep;
}

/// 构建系统实现细节。
pub inline fn runPackageScript(b: *Build, comptime build_zig: anytype) void {
    const result: anyerror!void = build_zig.build(b);
    result catch |err| switch (err) {
        error.LazyDependencyNeeded => assert(b.graph.needed_lazy_dependencies.count() != 0),
        else => {
            if (b.dep_prefix.len == 0) {
                log.err("package {q} configuration failed: {t}", .{ b.dep_prefix, err });
            } else {
                log.err("configuration failed: {t}", .{err});
            }
            if (@errorReturnTrace()) |trace| std.debug.dumpErrorReturnTrace(trace);
            const lazy_count = b.graph.needed_lazy_dependencies.count();
            if (lazy_count == 0) process.exit(1);
            log.info("{d} lazy dependencies detected; fetching and retrying configuration", .{lazy_count});
        },
    };
}

// dirnameAllowEmpty 是 fs.path.dirname 的变体,允许对相对路径使用“”表示根。
//
// 作为背景,dirname("foo") 和 dirname("") 都返回 null。
// 但对于相对路径,希望 dirname("foo") 返回“”,以便与其他路径拼接,例如构建根目录、缓存根目录等。
//
// dirname("") 仍应返回 null,因为已无法继续向上。
//
//
fn dirnameAllowEmpty(full_path: []const u8) ?[]const u8 {
    return fs.path.dirname(full_path) orelse {
        if (fs.path.isAbsolute(full_path) or full_path.len == 0) return null;

        return "";
    };
}

test dirnameAllowEmpty {
    try std.testing.expectEqualStrings(
        "foo",
        dirnameAllowEmpty("foo" ++ fs.path.sep_str ++ "bar") orelse @panic("unexpected null"),
    );

    try std.testing.expectEqualStrings(
        "",
        dirnameAllowEmpty("foo") orelse @panic("unexpected null"),
    );

    try std.testing.expect(dirnameAllowEmpty("") == null);
}

/// 对现有路径或未来路径的引用。
pub const LazyPath = union(enum) {
    /// 相对于构建根目录的源文件路径。
    src_path: struct {
        owner: *std.Build,
        sub_path: []const u8,
    },

    generated: struct {
        index: Configuration.GeneratedFileIndex,

        /// 向上遍历父目录的数量。
        /// 0 表示生成文件自身。
        /// 1 表示生成文件所在目录。
        /// 2 表示该目录的父目录,依此类推。
        up: usize = 0,

        /// 在 `up` 之后应用。
        sub_path: []const u8 = "",
    },

    /// 已弃用;请改用 `Graph.cwdRelativePath`。
    cwd_relative: []const u8,

    dependency: struct {
        dependency: *Dependency,
        sub_path: []const u8,
    },

    relative: struct {
        base: Configuration.LazyPath.Relative.Base,
        sub_path: []const u8 = "",

        pub fn eql(a: @This(), b: @This()) bool {
            return a.base == b.base and mem.eql(u8, a.sub_path, b.sub_path);
        }
    },

    /// 执行“zig build”所使用的 Zig 可执行文件路径。
    pub const zig_exe: LazyPath = .{ .relative = .{ .base = .zig_exe } };
    /// 用于执行 "zig build" 的 Zig 安装中的
    /// "lib/" 目录路径。
    pub const zig_lib: LazyPath = .{ .relative = .{ .base = .zig_lib } };
    /// 项目本地缓存目录的路径(通常名为 ".zig-cache")。
    pub const cache_root: LazyPath = .{ .relative = .{ .base = .local_cache } };

    /// 返回指向包含此路径的目录的延迟路径。
    ///
    /// 目录名不得越出底层路径的
    /// 逻辑根。例如,如果路径相对于构建根目录,
    /// 则目录名不得遍历到构建根目录之外。
    /// 同样,如果路径为 zig-cache 内生成的文件,
    /// 则目录名不得遍历到 zig-cache 之外。
    pub fn dirname(lazy_path: LazyPath) LazyPath {
        return switch (lazy_path) {
            .src_path => |sp| .{ .src_path = .{
                .owner = sp.owner,
                .sub_path = dirnameAllowEmpty(sp.sub_path) orelse {
                    dumpBadDirnameHelp(null, null, "dirname() attempted to traverse outside the build root\n", .{}) catch {};
                    @panic("misconfigured build script");
                },
            } },
            .generated => |generated| .{ .generated = if (dirnameAllowEmpty(generated.sub_path)) |sub_dirname| .{
                .index = generated.index,
                .up = generated.up,
                .sub_path = sub_dirname,
            } else .{
                .index = generated.index,
                .up = generated.up + 1,
                .sub_path = "",
            } },
            .cwd_relative => |rel_path| .{
                .cwd_relative = dirnameAllowEmpty(rel_path) orelse {
                    // 若得到 null,则有两种可能:
                    // - rel_path 原为绝对路径,现在已到根目录
                    // - rel_path 原为相对路径,现在已成为“”
                    // 无论哪种情况,都表示构建脚本试图越过边界,
                    // 应触发 panic。
                    if (fs.path.isAbsolute(rel_path)) {
                        dumpBadDirnameHelp(null, null,
                            \\dirname() attempted to traverse outside the root.
                            \\No more directories left to go up.
                            \\
                        , .{}) catch {};
                        @panic("misconfigured build script");
                    } else {
                        dumpBadDirnameHelp(null, null,
                            \\dirname() attempted to traverse outside the current working directory.
                            \\
                        , .{}) catch {};
                        @panic("misconfigured build script");
                    }
                },
            },
            .relative => |r| .{ .relative = .{
                .base = r.base,
                .sub_path = dirnameAllowEmpty(r.sub_path) orelse {
                    dumpBadDirnameHelp(null, null, "dirname() attempted to traverse outside the base path\n", .{}) catch {};
                    @panic("misconfigured build script");
                },
            } },
            .dependency => |dep| .{ .dependency = .{
                .dependency = dep.dependency,
                .sub_path = dirnameAllowEmpty(dep.sub_path) orelse {
                    dumpBadDirnameHelp(null, null,
                        \\dirname() attempted to traverse outside the dependency root.
                        \\
                    , .{}) catch {};
                    @panic("misconfigured build script");
                },
            } },
        };
    }

    pub fn path(lazy_path: LazyPath, b: *Build, sub_path: []const u8) LazyPath {
        const graph = b.graph;
        const arena = graph.arena;
        return lazy_path.join(arena, sub_path) catch @panic("OOM");
    }

    pub fn join(lazy_path: LazyPath, arena: Allocator, sub_path: []const u8) Allocator.Error!LazyPath {
        return switch (lazy_path) {
            .src_path => |src| .{ .src_path = .{
                .owner = src.owner,
                .sub_path = try fs.path.resolve(arena, &.{ src.sub_path, sub_path }),
            } },
            .generated => |gen| .{ .generated = .{
                .index = gen.index,
                .up = gen.up,
                .sub_path = try fs.path.resolve(arena, &.{ gen.sub_path, sub_path }),
            } },
            .cwd_relative => |cwd_relative| .{
                .cwd_relative = try fs.path.resolve(arena, &.{ cwd_relative, sub_path }),
            },
            .relative => |r| .{ .relative = .{
                .base = r.base,
                .sub_path = try fs.path.resolve(arena, &.{ r.sub_path, sub_path }),
            } },
            .dependency => |dep| .{ .dependency = .{
                .dependency = dep.dependency,
                .sub_path = try fs.path.resolve(arena, &.{ dep.sub_path, sub_path }),
            } },
        };
    }

    /// 已弃用,改用 `format`。
    pub fn getDisplayName(lazy_path: LazyPath) []const u8 {
        return switch (lazy_path) {
            .src_path => |sp| sp.sub_path,
            .cwd_relative => |p| p,
            .generated => "generated",
            .dependency => "dependency",
            .relative => |r| @tagName(r.base),
        };
    }

    pub fn format(lp: LazyPath, w: *Io.Writer) Io.Writer.Error!void {
        switch (lp) {
            .src_path => |sp| try w.writeAll(sp.sub_path),
            .cwd_relative => |p| try w.writeAll(p),
            .generated => try w.writeAll("generated"),
            .dependency => try w.writeAll("dependency"),
            .relative => |r| try w.print("{t} {s}", .{ r.base, r.sub_path }),
        }
    }

    /// 将此文件来源隐含的依赖项添加到给定步骤。
    pub fn addStepDependencies(lazy_path: LazyPath, other_step: *Step) void {
        switch (lazy_path) {
            .src_path, .cwd_relative, .relative, .dependency => {},
            .generated => |gen| {
                const graph = other_step.owner.graph;
                const generated_owner_step = graph.generated_files.items[@backingInt(gen.index)];
                other_step.dependOn(generated_owner_step);
            },
        }
    }

    /// 复制内部字符串。
    ///
    /// `graph` 参数仅用于全局区域分配器。
    pub fn dupe(lazy_path: LazyPath, graph: *const Graph) LazyPath {
        return dupeInner(lazy_path, graph.arena);
    }

    /// 复制路径切片及其中全部内部字符串。
    ///
    /// `graph` 参数仅用于全局 arena 分配器。
    pub fn dupeList(lazy_paths: []const LazyPath, graph: *const Graph) []const LazyPath {
        const arena = graph.arena;
        const result = graph.alloc(LazyPath, lazy_paths.len);
        for (result, lazy_paths) |*d, s| d.* = dupeInner(s, arena);
        return result;
    }

    fn dupeInner(lazy_path: LazyPath, arena: Allocator) LazyPath {
        return switch (lazy_path) {
            .src_path => |sp| .{ .src_path = .{
                .owner = sp.owner,
                .sub_path = sp.owner.graph.dupePath(sp.sub_path),
            } },
            .cwd_relative => |p| .{ .cwd_relative = Graph.dupePathInner(arena, p) },
            .relative => |r| .{ .relative = r },
            .generated => |gen| .{ .generated = .{
                .index = gen.index,
                .up = gen.up,
                .sub_path = Graph.dupePathInner(arena, gen.sub_path),
            } },
            .dependency => |dep| .{ .dependency = .{
                .dependency = dep.dependency,
                .sub_path = Graph.dupePathInner(arena, dep.sub_path),
            } },
        };
    }

    fn eql(a: LazyPath, b: LazyPath) bool {
        if (std.meta.activeTag(a) != b) return false;
        switch (a) {
            .src_path => |a_sp| {
                const b_sp = b.src_path;
                if (a_sp.owner != b_sp.owner) return false;
                if (mem.eql(u8, a_sp.sub_path, b_sp.sub_path)) return false;
            },
            .generated => |*a_gen| {
                const b_gen = &b.generated;
                if (a_gen.index != b_gen.index) return false;
                if (a_gen.up != b_gen.up) return false;
                if (mem.eql(u8, a_gen.sub_path, b_gen.sub_path)) return false;
            },
            .cwd_relative => |a_rel_path| {
                const b_rel_path = b.cwd_relative;
                if (!mem.eql(u8, a_rel_path, b_rel_path)) return false;
            },
            .relative => |a_relative| return a_relative.eql(b.relative),
            .dependency => |a_dep| {
                const b_dep = b.dependency;
                if (a_dep.dependency != b_dep.dependency) return false;
                if (!mem.eql(u8, a_dep.sub_path, b_dep.sub_path)) return false;
            },
        }
        return true;
    }

    fn hash(lp: LazyPath, hasher: *std.hash.Wyhash) void {
        switch (lp) {
            .src_path => |sp| {
                hasher.update(sp.owner.pkg_hash);
                hasher.update(sp.sub_path);
            },
            .generated => |gen| {
                hasher.update(@ptrCast(&gen.index));
                hasher.update(@ptrCast(&gen.up));
                hasher.update(gen.sub_path);
            },
            .cwd_relative => |rel_path| {
                hasher.update(rel_path);
            },
            .relative => |r| {
                hasher.update(@ptrCast(&r.base));
                hasher.update(@ptrCast(&r.sub_path));
            },
            .dependency => |dep| {
                hasher.update(dep.dependency.builder.pkg_hash);
                hasher.update(dep.sub_path);
            },
        }
    }
};

fn dumpBadDirnameHelp(
    fail_step: ?*Step,
    asking_step: ?*Step,
    comptime msg: []const u8,
    args: anytype,
) anyerror!void {
    const stderr = std.debug.lockStderr(&.{}).terminal();
    defer std.debug.unlockStderr();
    const w = stderr.writer;

    try w.print(msg, args);

    if (fail_step) |s| {
        stderr.setColor(.red) catch {};
        try w.writeAll("    The step was created by this stack trace:\n");
        stderr.setColor(.reset) catch {};

        s.dump(stderr);
    }

    if (asking_step) |as| {
        stderr.setColor(.red) catch {};
        try w.print("    The step {q} that is missing a dependency on the above step was created by this stack trace:\n", .{as.name});
        stderr.setColor(.reset) catch {};

        as.dump(stderr);
    }

    stderr.setColor(.red) catch {};
    try w.writeAll("    Proceeding to panic.\n");
    stderr.setColor(.reset) catch {};
}

pub const InstallDir = union(enum) {
    prefix: void,
    lib: void,
    bin: void,
    header: void,
    /// 相对于前缀的路径
    custom: []const u8,

    /// 复制安装目录;若设为自定义目录,则包含路径。
    pub fn dupe(dir: InstallDir, graph: *const Graph) InstallDir {
        if (dir == .custom) {
            return .{ .custom = graph.dupeString(dir.custom) };
        } else {
            return dir;
        }
    }
};

/// 创建指向本地缓存“tmp”子目录内目录的路径。
/// 目录按需创建,并在构建成功后
/// 由构建运行器清理。
pub fn tmpPath(b: *Build) LazyPath {
    const wf = b.addTempFiles();
    return wf.getDirectory();
}

/// 由目标查询和完全解析后的目标构成的一对。
/// 需要接收目标的构建系统 API 通常要求此类型。
/// 保留查询是因为 Zig 工具链需要知道目标的哪些部分
/// 为“本机”,可能适用于 CPU、操作系统,甚至 ABI。
pub const ResolvedTarget = struct {
    query: Target.Query,
    result: Target,
};

/// 将目标查询转换为完全解析的目标,可传给
/// API 的各个部分。
pub fn resolveTargetQuery(b: *Build, query: Target.Query) ResolvedTarget {
    if (query.isNative()) {
        // 热点路径。比重新查询本机 CPU 和操作系统更快。
        return b.graph.host;
    }
    const io = b.graph.io;
    return .{
        .query = query,
        .result = std.zig.system.resolveTargetQuery(io, query) catch
            @panic("unable to resolve target query"),
    };
}

pub fn wantSharedLibSymLinks(target: Target) bool {
    return target.os.tag != .windows;
}

pub const SystemIntegrationOptionConfig = struct {
    /// 若保留为 null,则默认值取决于 system_package_mode。
    default: ?bool = null,
};

pub fn systemIntegrationOption(
    b: *Build,
    name: []const u8,
    config: SystemIntegrationOptionConfig,
) bool {
    const graph = b.graph;
    const arena = graph.arena;
    const gop = graph.system_integration_options.getOrPut(arena, name) catch @panic("OOM");
    if (gop.found_existing) switch (gop.value_ptr.*) {
        .user_disabled => {
            gop.value_ptr.* = .declared_disabled;
            return false;
        },
        .user_enabled => {
            gop.value_ptr.* = .declared_enabled;
            return true;
        },
        .declared_disabled => return false,
        .declared_enabled => return true,
    } else {
        gop.key_ptr.* = graph.dupeString(name);
        if (config.default orelse graph.system_package_mode) {
            gop.value_ptr.* = .declared_enabled;
            return true;
        } else {
            gop.value_ptr.* = .declared_disabled;
            return false;
        }
    }
}

/// 表示 build.zig 逻辑依赖某个文件的内容。
///
/// 若文件被创建、删除或内容发生变化,将重新执行配置阶段。若 inode 或修改时间变化,但内容不变,则不会重新执行配置逻辑。
///
/// 这是 `Graph.poisonCache` 的替代方案,避免每次调用 `zig build` 都造成缓存未命中。
///
/// 仅支持部分 `LazyPath`:
/// - 相对于当前工作目录。
/// - 相对于任意包根目录。
/// - 相对于 Zig 缓存或 Zig 安装目录。
///
/// 若文件位于某个搜索前缀内部,则无法跟踪依赖;此时必须改用 `Graph.poisonCache`。
///
///
///
///
pub fn dependOnFileContents(b: *Build, lazy_path: LazyPath) void {
    validateConfigureDependency(lazy_path);
    const graph = b.graph;
    graph.configure_dependencies.append(graph.arena, .{
        .lazy_path = lazy_path.dupe(graph),
        .is_directory = false,
        .metadata_only = false,
    }) catch @panic("OOM");
}

/// 表示 build.zig 逻辑依赖某个文件的大小、
/// inode、修改时间和内容。
///
/// 如果文件被创建、删除、内容改变,或 inode
/// 改变,或修改时间改变,则重新执行配置阶段。
///
/// 这是 `Graph.poisonCache` 的替代方案,可避免每次
/// 调用 `zig build` 都导致缓存未命中。
///
/// 仅支持 `LazyPath` 的以下子集:
/// - 相对于当前工作目录
/// - 相对于任意软件包根目录
/// - 相对于 Zig 缓存或 Zig 安装目录
///
/// 如果该文件位于某个搜索前缀内,则无法跟踪此依赖;
/// 必须改用 `Graph.poisonCache`。
pub fn dependOnFileMetadata(b: *Build, lazy_path: LazyPath) void {
    validateConfigureDependency(lazy_path);
    const graph = b.graph;
    graph.configure_dependencies.append(graph.arena, .{
        .lazy_path = lazy_path.dupe(graph),
        .is_directory = false,
        .metadata_only = true,
    }) catch @panic("OOM");
}

/// 表示 build.zig 逻辑依赖某个目录中的条目。
///
/// 这是 `Graph.poisonCache` 的替代方案,可避免每次
/// 调用 `zig build` 都导致缓存未命中。
///
/// 如果在该目录中创建、删除或重命名文件,使其条目的
/// 存在状态和命名相对于上次配置发生变化,
/// 则会重新执行配置阶段。
///
/// 仅支持 `LazyPath` 的以下子集:
/// - 相对于当前工作目录
/// - 相对于任意软件包根目录
/// - 相对于 Zig 缓存或 Zig 安装目录
///
/// 如果该目录位于某个搜索前缀内,则无法跟踪此依赖;
/// 必须改用 `Graph.poisonCache`。
///
/// 不递归。
pub fn dependOnDirectoryContents(b: *Build, lazy_path: LazyPath) void {
    validateConfigureDependency(lazy_path);
    const graph = b.graph;
    graph.configure_dependencies.append(graph.arena, .{
        .lazy_path = lazy_path.dupe(graph),
        .is_directory = true,
        .metadata_only = false,
    }) catch @panic("OOM");
}

/// 表示 build.zig 逻辑依赖特定目录的最后修改时间。
///
/// 这是 `Graph.poisonCache` 的替代方案,避免每次调用 `zig build` 都造成缓存未命中。
///
/// 若此目录内有任何文件被创建、删除或重命名,将重新执行配置阶段。
///
/// 仅支持部分 `LazyPath`:
/// - 相对于当前工作目录。
/// - 相对于任意包根目录。
/// - 相对于 Zig 缓存或 Zig 安装目录。
///
/// 若目录位于某个搜索前缀内部,则无法跟踪依赖;此时必须改用 `Graph.poisonCache`。
///
/// 不递归。
///
///
///
///
pub fn dependOnDirectoryMetadata(b: *Build, lazy_path: LazyPath) void {
    validateConfigureDependency(lazy_path);
    const graph = b.graph;
    graph.configure_dependencies.append(graph.arena, .{
        .lazy_path = lazy_path.dupe(graph),
        .is_directory = true,
        .metadata_only = true,
    }) catch @panic("OOM");
}

fn validateConfigureDependency(lazy_path: LazyPath) void {
    switch (lazy_path) {
        .src_path, .cwd_relative, .dependency => {}, // 正常
        .generated => @panic("configure phase cannot depend on files generated during make phase"),
        .relative => |relative| switch (relative.base) {
            .cwd, .build_root, .local_cache, .global_cache, .zig_lib => {}, // 正常
            .zig_exe => if (relative.sub_path.len > 0) @panic("file base cannot have a sub path"),
            .install_prefix,
            .install_lib,
            .install_bin,
            .install_include,
            .deployed_prefix,
            .deployed_lib,
            .deployed_bin,
            .deployed_include,
            => @panic("configure phase cannot depend on files installed during make phase"),
            .libc_runtimes,
            => @panic("configure phase cannot depend on directory known only during make phase"),
        },
    }
}

/// 构建系统实现细节。
pub fn serializeConfigurationExiting(b: *Build) noreturn {
    const graph = b.graph;
    const io = graph.io;

    var stdout_buffer: [1024]u8 = undefined;
    var file_writer = Io.File.stdout().writerStreaming(io, &stdout_buffer);
    Serialize.write(b, &graph.wip_configuration, &file_writer.interface) catch |err| switch (err) {
        error.WriteFailed => fatal("failed to write configuration output: {t}", .{file_writer.err.?}),
        error.OutOfMemory => @panic("OOM"),
    };
    file_writer.flush() catch |err| fatal("failed to write configuration output: {t}", .{err});

    // 此可执行程序运行时间短,且以 Debug 模式运行,因此相比在用户的
    // build.zig 脚本(说实话,包括此配置执行器本身)中捕获资源泄漏,
    // 我们更希望 `zig build` 运行更快,所以此处直接调用
    // exit,而非 cleanExit。
    process.exit(0);
}

test {
    _ = Cache;
    _ = Configuration;
    _ = Module;
    _ = Step;
    _ = Configuration;
    _ = &findProgram;
    _ = abi;
}