字段
vector: Vector
std.process.Args.Allocator
别名
别名目标 std.mem.Allocator
std.process.Args.Args
别名
别名目标 std.process.Args
std.process.Args.assert
别名
别名目标 std.debug.assert
std.process.Args.builtin
常量
std.process.Args.iterate
函数
保存命令行参数,程序名称为第一项。
跨平台代码请使用 iterateAllocator。
pub fn iterate(a: Args) Iterator
参数
a: Args
std.process.Args.iterateAllocator
函数
使用完毕后,必须调用 deinit 反初始化迭代器的内部
缓冲区。
pub fn iterateAllocator(a: Args, gpa: Allocator) Iterator.InitError!Iterator
参数
std.process.Args.Iterator
容器
跨平台访问命令行,每次获取一个参数。
字段
inner: Inner
std.process.Args.Iterator.deinit
函数
若迭代器使用 initAllocator 函数初始化,
则必须调用此方法释放资源。
pub fn deinit(it: *Iterator) void
参数
it: *Iterator
std.process.Args.Iterator.init
函数
初始化参数迭代器。为兼容跨平台,
请考虑改用 initAllocator。
pub fn init(a: Args) Iterator
参数
a: Args
std.process.Args.Iterator.initAllocator
函数
使用完毕后,必须调用 deinit 反初始化迭代器的内部缓冲区。
pub fn initAllocator(a: Args, gpa: Allocator) InitError!Iterator
参数
std.process.Args.Iterator.InitError
常量
std.process.Args.Iterator.Inner
类型
std.process.Args.Iterator.next
函数
返回后续参数;若已无剩余参数,返回 null。
返回切片指向迭代器内部缓冲区。 Windows 上,结果采用 WTF-8 编码。 其他平台上,结果是不透明的字节序列,没有特定编码。
pub fn next(it: *Iterator) ?[:0]const u8
参数
it: *Iterator
std.process.Args.Iterator.Posix
容器
字段
remaining: Vector
std.process.Args.Iterator.Posix.init
函数
pub fn init(a: Args) Posix
参数
a: Args
std.process.Args.Iterator.Posix.InitError
错误集合
std.process.Args.Iterator.Posix.next
函数
pub fn next(it: *Posix) ?[:0]const u8
参数
it: *Posix
std.process.Args.Iterator.Posix.skip
函数
pub fn skip(it: *Posix) bool
参数
it: *Posix
std.process.Args.Iterator.skip
函数
解析并越过一个参数,不捕获它。
跳过参数时返回 true,到达末尾时返回 false。
pub fn skip(it: *Iterator) bool
参数
it: *Iterator
std.process.Args.Iterator.Wasi
容器
字段
std.process.Args.Iterator.Wasi.deinit
函数
调用以释放迭代器的内部缓冲区。
pub fn deinit(self: *Wasi) void
参数
self: *Wasi
std.process.Args.Iterator.Wasi.init
函数
使用完毕后,必须调用 deinit 释放迭代器的内部缓冲区。
pub fn init(allocator: Allocator) Wasi.InitError!Wasi
参数
allocator: Allocator
错误
- OutOfMemory
- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
std.process.Args.Iterator.Wasi.InitError
错误集合
错误
- OutOfMemory
- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
std.process.Args.Iterator.Wasi.internalInit
函数
fn internalInit(allocator: Allocator) Wasi.InitError![][:0]u8
参数
allocator: Allocator
错误
- OutOfMemory
- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
std.process.Args.Iterator.Wasi.next
函数
pub fn next(self: *Wasi) ?[:0]const u8
参数
self: *Wasi
std.process.Args.Iterator.Wasi.skip
函数
pub fn skip(self: *Wasi) bool
参数
self: *Wasi
std.process.Args.Iterator.Windows
容器
实现 Windows 命令行解析算法的迭代器。
此实现旨在兼容 2008 年之后的 C 运行时,但不以兼容 CommandLineToArgvW 为目标,因为 CommandLineToArgvW 使用 2008 年之前的解析规则。
除一个例外外,此迭代器忠实实现了从 C 运行时观察到的解析行为:若命令行字符串为空,迭代器立即结束,不返回任何参数;而 C 运行时会返回单个参数,表示当前可执行文件的名称。
微软文档描述了算法的核心部分:
David Deley 详细解释了一些额外的、未记载于官方文档的特殊行为:
字段
allocator: Allocator
cmd_line: []const u16编码为 WTF-16 LE。
index: usize = 0
buffer: []u8由迭代器拥有。足够长,可连续存储每个参数以 WTF-8 编码、 以 NUL 终止的切片。
start: usize = 0
end: usize = 0
std.process.Args.Iterator.Windows.deinit
函数
释放迭代器持有的命令行字符串副本,以及此前返回的 所有参数切片。
pub fn deinit(self: *Windows) void
参数
self: *Windows
std.process.Args.Iterator.Windows.init
函数
cmd_line_w 必须是 WTF16-LE 编码的字符串。
迭代器会存储并使用 cmd_line_w,因此其内存至少必须
在返回的 Windows 对象存活期间保持有效。
pub fn init(gpa: Allocator, cmd_line_w: []const u16) Windows.InitError!Windows
参数
gpa: Allocator
cmd_line_w: []const u16
错误
- OutOfMemory
std.process.Args.Iterator.Windows.InitError
错误集合
错误
- OutOfMemory
std.process.Args.Iterator.Windows.next
函数
返回下一个参数,并推进迭代器。如果已到命令行字符串末尾,则返回 null。
返回切片由迭代器拥有。
结果采用 WTF-8 编码。
pub fn next(self: *Windows) ?[:0]const u8
参数
self: *Windows
std.process.Args.Iterator.Windows.next_strategy
命名空间
std.process.Args.Iterator.Windows.next_strategy.emitBackslashes
函数
若发出了任何反斜杠,则返回 '',否则返回 last_emitted_code_unit。
fn emitBackslashes(self: *Windows, count: usize, last_emitted_code_unit: ?u16) ?u16
参数
std.process.Args.Iterator.Windows.next_strategy.emitCharacter
函数
若 last_emitted_code_unit 与 code_unit 构成代理对,
则用该代理对编码的码点覆盖
先前已输出的高位代理项,并返回 null。
否则,输出并返回 code_unit。
fn emitCharacter(self: *Windows, code_unit: u16, last_emitted_code_unit: ?u16) ?u16
参数
std.process.Args.Iterator.Windows.next_strategy.eof
原始类型
std.process.Args.Iterator.Windows.next_strategy.T
类型
std.process.Args.Iterator.Windows.next_strategy.yieldArg
函数
fn yieldArg(self: *Windows) [:0]const u8
参数
self: *Windows
std.process.Args.Iterator.Windows.nextWithStrategy
函数
fn nextWithStrategy(self: *Windows, comptime strategy: type) strategy.T
参数
self: *Windows
strategy: type
std.process.Args.Iterator.Windows.skip
函数
跳过下一个参数并推进迭代器。跳过参数时返回 true;
位于命令行字符串末尾时返回 false。
pub fn skip(self: *Windows) bool
参数
self: *Windows
std.process.Args.Iterator.Windows.skip_strategy
命名空间
std.process.Args.Iterator.Windows.skip_strategy.emitBackslashes
函数
fn emitBackslashes(_: *Windows, _: usize, last_emitted_code_unit: ?u16) ?u16
参数
std.process.Args.Iterator.Windows.skip_strategy.emitCharacter
函数
fn emitCharacter(_: *Windows, _: u16, last_emitted_code_unit: ?u16) ?u16
参数
std.process.Args.Iterator.Windows.skip_strategy.eof
原始类型
std.process.Args.Iterator.Windows.skip_strategy.T
类型
std.process.Args.Iterator.Windows.skip_strategy.yieldArg
函数
fn yieldArg(_: *Windows) bool
参数
_: *Windows
std.process.Args.IteratorGeneral
类型函数
将字符串解析为一组参数的通用迭代器。
pub fn IteratorGeneral(comptime options: IteratorGeneralOptions) type
参数
options: IteratorGeneralOptions
字段
allocator: Allocator
index: usize = 0
cmd_line: []const u8
free_cmd_line_on_deinit: bool是否应在 deinit() 时使用分配器释放 cmd_line 字段?
buffer: []u8buffer 必须足够长,以容纳 cmd_line 和空终止符。 deinit() 时将(使用分配器)释放 buffer
start: usize = 0
end: usize = 0
std.process.Args.IteratorGeneral.deinit
函数
调用以释放迭代器的内部缓冲区。
pub fn deinit(self: *Self) void
参数
self: *Self
std.process.Args.IteratorGeneral.emitBackslashes
函数
fn emitBackslashes(self: *Self, emit_count: usize) void
参数
self: *Self
emit_count: usize
std.process.Args.IteratorGeneral.emitCharacter
函数
fn emitCharacter(self: *Self, char: u8) void
参数
self: *Self
char: u8
std.process.Args.IteratorGeneral.init
函数
使用此实例期间,cmd_line_utf8 必须保持有效且不变
pub fn init(allocator: Allocator, cmd_line_utf8: []const u8) InitError!Self
参数
allocator: Allocator
cmd_line_utf8: []const u8
错误
- OutOfMemory
std.process.Args.IteratorGeneral.InitError
错误集合
错误
- OutOfMemory
std.process.Args.IteratorGeneral.initTakeOwnership
函数
cmd_line_utf8 将在 deinit() 中(通过该分配器)释放
pub fn initTakeOwnership(allocator: Allocator, cmd_line_utf8: []const u8) InitError!Self
参数
allocator: Allocator
cmd_line_utf8: []const u8
错误
- OutOfMemory
std.process.Args.IteratorGeneral.next
函数
返回内部缓冲区中包含下一个参数的切片。 到达末尾时返回 null。
pub fn next(self: *Self) ?[:0]const u8
参数
self: *Self
std.process.Args.IteratorGeneral.Self
别名
std.process.Args.IteratorGeneral.skip
函数
pub fn skip(self: *Self) bool
参数
self: *Self
std.process.Args.IteratorGeneral.skipWhitespace
函数
fn skipWhitespace(self: *Self) bool
参数
self: *Self
std.process.Args.IteratorGeneralOptions
容器
IteratorGeneral 的可选参数
字段
comments: bool = false
single_quotes: bool = false
std.process.Args.native_os
常量
std.process.Args.std
别名
别名目标 std
std.process.Args.testGeneralCmdLine
函数
fn testGeneralCmdLine(input_cmd_line: []const u8, expected_args: []const []const u8) !void
参数
input_cmd_line: []const u8
expected_args: []const []const u8
std.process.Args.testing
别名
别名目标 std.testing
std.process.Args.testIteratorWindows
函数
fn testIteratorWindows(cmd_line: []const u8, expected_args: []const []const u8) !void
参数
cmd_line: []const u8
expected_args: []const []const u8
std.process.Args.testResponseFileCmdLine
函数
fn testResponseFileCmdLine(input_cmd_line: []const u8, expected_args: []const []const u8) !void
参数
input_cmd_line: []const u8
expected_args: []const []const u8
std.process.Args.toSlice
函数
pub fn toSlice(a: Args, arena: Allocator) ToSliceError![]const [:0]const u8
参数
错误
- OutOfMemory InitError
- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
std.process.Args.ToSliceError
错误集合
错误
- OutOfMemory InitError
- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
std.process.Args.Vector
类型
不使用 libc 的 WASI 上为 void,因为必须在运行时
查询环境并在堆上分配。
源码
std/process/Args.zig
const Args = @This();
const builtin = @import("builtin");
const native_os = builtin.os.tag;
const std = @import("../std.zig");
const Allocator = std.mem.Allocator;
const assert = std.debug.assert;
const testing = std.testing;
vector: Vector,
/// 不使用 libc 的 WASI 上为 `void`,因为必须在运行时
/// 查询环境并在堆上分配。
pub const Vector = switch (native_os) {
.windows => []const u16, // 使用 WTF-16 编码
.wasi => switch (builtin.link_libc) {
false => void,
true => []const [*:0]const u8,
},
.freestanding, .other => void,
else => []const [*:0]const u8,
};
/// 跨平台访问命令行,每次获取一个参数。
pub const Iterator = struct {
const Inner = switch (native_os) {
.windows => Windows,
.wasi => if (builtin.link_libc) Posix else Wasi,
else => Posix,
};
inner: Inner,
/// 初始化参数迭代器。为兼容跨平台,
/// 请考虑改用 `initAllocator`。
pub fn init(a: Args) Iterator {
if (native_os == .wasi) @compileError("In WASI, use initAllocator instead.");
if (native_os == .windows) @compileError("In Windows, use initAllocator instead.");
return .{ .inner = .init(a) };
}
pub const InitError = Inner.InitError;
/// 使用完毕后,必须调用 `deinit` 反初始化迭代器的内部缓冲区。
pub fn initAllocator(a: Args, gpa: Allocator) InitError!Iterator {
if (native_os == .wasi and !builtin.link_libc) {
return .{ .inner = try .init(gpa) };
}
if (native_os == .windows) {
return .{ .inner = try .init(gpa, a.vector) };
}
return .{ .inner = .init(a) };
}
/// 返回后续参数;若已无剩余参数,返回 `null`。
///
/// 返回切片指向迭代器内部缓冲区。
/// Windows 上,结果采用 [WTF-8](https://wtf-8.codeberg.page/) 编码。
/// 其他平台上,结果是不透明的字节序列,没有特定编码。
pub fn next(it: *Iterator) ?[:0]const u8 {
return it.inner.next();
}
/// 解析并越过一个参数,不捕获它。
/// 跳过参数时返回 `true`,到达末尾时返回 `false`。
pub fn skip(it: *Iterator) bool {
return it.inner.skip();
}
/// 若迭代器使用 `initAllocator` 函数初始化,
/// 则必须调用此方法释放资源。
pub fn deinit(it: *Iterator) void {
// 除非目标为 WASI 或 Windows,否则不执行任何操作。
if (native_os == .wasi and !builtin.link_libc) it.inner.deinit();
if (native_os == .windows) it.inner.deinit();
}
/// 实现 Windows 命令行解析算法的迭代器。
///
/// 此实现旨在兼容 2008 年之后的 C 运行时,但不以兼容 `CommandLineToArgvW` 为目标,因为 `CommandLineToArgvW` 使用 2008 年之前的解析规则。
///
/// 除一个例外外,此迭代器忠实实现了从 C 运行时观察到的解析行为:若命令行字符串为空,迭代器立即结束,不返回任何参数;而 C 运行时会返回单个参数,表示当前可执行文件的名称。
///
/// 微软文档描述了算法的核心部分:
///
/// - https://learn.microsoft.com/en-us/cpp/cpp/main-function-command-line-args?view=msvc-170#parsing-c-command-line-arguments
///
/// David Deley 详细解释了一些额外的、未记载于官方文档的特殊行为:
///
/// - https://daviddeley.com/autohotkey/parameters/parameters.htm#WINCRULES
///
///
///
///
///
pub const Windows = struct {
allocator: Allocator,
/// 编码为 WTF-16 LE。
cmd_line: []const u16,
index: usize = 0,
/// 由迭代器拥有。足够长,可连续存储每个参数以 WTF-8 编码、
/// 以 NUL 终止的切片。
buffer: []u8,
start: usize = 0,
end: usize = 0,
pub const InitError = error{OutOfMemory};
/// `cmd_line_w` *必须*是 WTF16-LE 编码的字符串。
///
/// 迭代器会存储并使用 `cmd_line_w`,因此其内存至少必须
/// 在返回的 Windows 对象存活期间保持有效。
pub fn init(gpa: Allocator, cmd_line_w: []const u16) Windows.InitError!Windows {
const wtf8_len = std.unicode.calcWtf8Len(cmd_line_w);
// 此缓冲区必须足够大,以连续保存每个参数
// 对应的 NUL 终止切片。
// - 解析过程中,已解析参数的长度始终小于或等于
// 其未解析长度。
// - 第一个参数需要额外分配一个字节,用于 NUL
// 终止符;对于后续参数,参数之间必需的
// 空白字符保证了其 NUL 终止符所需空间。
const buffer = try gpa.alloc(u8, wtf8_len + 1);
errdefer gpa.free(buffer);
return .{
.allocator = gpa,
.cmd_line = cmd_line_w,
.buffer = buffer,
};
}
/// 返回下一个参数,并推进迭代器。如果已到命令行字符串末尾,则返回 `null`。
/// 返回切片由迭代器拥有。
/// 结果采用 [WTF-8](https://wtf-8.codeberg.page/) 编码。
pub fn next(self: *Windows) ?[:0]const u8 {
return self.nextWithStrategy(next_strategy);
}
/// 跳过下一个参数并推进迭代器。跳过参数时返回 `true`;
/// 位于命令行字符串末尾时返回 `false`。
pub fn skip(self: *Windows) bool {
return self.nextWithStrategy(skip_strategy);
}
const next_strategy = struct {
const T = ?[:0]const u8;
const eof = null;
/// 若发出了任何反斜杠,则返回 '\',否则返回 `last_emitted_code_unit`。
fn emitBackslashes(self: *Windows, count: usize, last_emitted_code_unit: ?u16) ?u16 {
for (0..count) |_| {
self.buffer[self.end] = '\\';
self.end += 1;
}
return if (count != 0) '\\' else last_emitted_code_unit;
}
/// 若 `last_emitted_code_unit` 与 `code_unit` 构成代理对,
/// 则用该代理对编码的码点覆盖
/// 先前已输出的高位代理项,并返回 `null`。
/// 否则,输出并返回 `code_unit`。
fn emitCharacter(self: *Windows, code_unit: u16, last_emitted_code_unit: ?u16) ?u16 {
// 由于输出 WTF-8,为确保输出始终是结构良好的 WTF-8,需要检查是否输出了两个连续代理码点,且它们构成有效代理项对(https://wtf-8.codeberg.page/#concatenating)。
//
// 若确实存在有效代理项对,就需要输出它们所编码码点的 UTF-8 序列,而不是分别输出两个代理项的 WTF-8 编码。
//
// 处理如下 WTF-16 编码命令行时,这一点尤其重要:
// "<0xD801>"<0xDC37>
// 按通常方式解析并转换为 WTF-8 会得到:
// <0xED><0xA0><0x81><0xED><0xB0><0xB7>
// 但应当识别出代理项对,并输出其编码的码点。此例中为 U+10437(𐐷),其 UTF-8 编码为:
// <0xF0><0x90><0x90><0xB7>
//
//
//
//
//
//
//
//
//
//
if (last_emitted_code_unit != null and
std.unicode.utf16IsLowSurrogate(code_unit) and
std.unicode.utf16IsHighSurrogate(last_emitted_code_unit.?))
{
const codepoint = std.unicode.utf16DecodeSurrogatePair(&.{ last_emitted_code_unit.?, code_unit }) catch unreachable;
// 未配对的代理项占 3 个字节
const dest = self.buffer[self.end - 3 ..];
const len = std.unicode.utf8Encode(codepoint, dest) catch unreachable;
// 所有需要代理对的码点(> U+FFFF)都编码为 4 字节
assert(len == 4);
self.end += 1;
return null;
}
const wtf8_len = std.unicode.wtf8Encode(code_unit, self.buffer[self.end..]) catch unreachable;
self.end += wtf8_len;
return code_unit;
}
fn yieldArg(self: *Windows) [:0]const u8 {
self.buffer[self.end] = 0;
const arg = self.buffer[self.start..self.end :0];
self.end += 1;
self.start = self.end;
return arg;
}
};
const skip_strategy = struct {
const T = bool;
const eof = false;
fn emitBackslashes(_: *Windows, _: usize, last_emitted_code_unit: ?u16) ?u16 {
return last_emitted_code_unit;
}
fn emitCharacter(_: *Windows, _: u16, last_emitted_code_unit: ?u16) ?u16 {
return last_emitted_code_unit;
}
fn yieldArg(_: *Windows) bool {
return true;
}
};
fn nextWithStrategy(self: *Windows, comptime strategy: type) strategy.T {
var last_emitted_code_unit: ?u16 = null;
// 首个参数(可执行文件名称)使用不同的解析规则。
if (self.index == 0) {
if (self.cmd_line.len == 0 or self.cmd_line[0] == 0) {
// 立即结束迭代器。
// C 运行库会在此处返回当前可执行文件的名称。
return strategy.eof;
}
var inside_quotes = false;
while (true) : (self.index += 1) {
const char = if (self.index != self.cmd_line.len)
std.mem.littleToNative(u16, self.cmd_line[self.index])
else
0;
switch (char) {
0 => {
return strategy.yieldArg(self);
},
'"' => {
inside_quotes = !inside_quotes;
},
' ', '\t' => {
if (inside_quotes) {
last_emitted_code_unit = strategy.emitCharacter(self, char, last_emitted_code_unit);
} else {
self.index += 1;
return strategy.yieldArg(self);
}
},
else => {
last_emitted_code_unit = strategy.emitCharacter(self, char, last_emitted_code_unit);
},
}
}
}
// 跳过空格和制表符。若此处到达字符串末尾,则迭代结束。
while (true) : (self.index += 1) {
const char = if (self.index != self.cmd_line.len)
std.mem.littleToNative(u16, self.cmd_line[self.index])
else
0;
switch (char) {
0 => return strategy.eof,
' ', '\t' => continue,
else => break,
}
}
// 后续参数的解析规则:
//
// - 字符串结束始终终止当前参数。
// - 不处于“inside_quotes”模式时,空格或制表符终止当前参数。
// - 2n 个反斜杠后跟一个引号时,输出 n 个反斜杠,注意 n 可以为零。若处于“inside_quotes”模式,且该引号紧接着另一个引号,则输出一个引号并跳过另一个;否则跳过该引号,并切换“inside_quotes”状态。
// - 2n + 1 个反斜杠后跟一个引号时,输出 n 个反斜杠,再输出一个引号。
// - n 个反斜杠后未跟引号时,输出 n 个反斜杠。
//
//
//
var backslash_count: usize = 0;
var inside_quotes = false;
while (true) : (self.index += 1) {
const char = if (self.index != self.cmd_line.len)
std.mem.littleToNative(u16, self.cmd_line[self.index])
else
0;
switch (char) {
0 => {
last_emitted_code_unit = strategy.emitBackslashes(self, backslash_count, last_emitted_code_unit);
return strategy.yieldArg(self);
},
' ', '\t' => {
last_emitted_code_unit = strategy.emitBackslashes(self, backslash_count, last_emitted_code_unit);
backslash_count = 0;
if (inside_quotes) {
last_emitted_code_unit = strategy.emitCharacter(self, char, last_emitted_code_unit);
} else return strategy.yieldArg(self);
},
'"' => {
const char_is_escaped_quote = backslash_count % 2 != 0;
last_emitted_code_unit = strategy.emitBackslashes(self, backslash_count / 2, last_emitted_code_unit);
backslash_count = 0;
if (char_is_escaped_quote) {
last_emitted_code_unit = strategy.emitCharacter(self, '"', last_emitted_code_unit);
} else {
if (inside_quotes and
self.index + 1 != self.cmd_line.len and
std.mem.littleToNative(u16, self.cmd_line[self.index + 1]) == '"')
{
last_emitted_code_unit = strategy.emitCharacter(self, '"', last_emitted_code_unit);
self.index += 1;
} else {
inside_quotes = !inside_quotes;
}
}
},
'\\' => {
backslash_count += 1;
},
else => {
last_emitted_code_unit = strategy.emitBackslashes(self, backslash_count, last_emitted_code_unit);
backslash_count = 0;
last_emitted_code_unit = strategy.emitCharacter(self, char, last_emitted_code_unit);
},
}
}
}
/// 释放迭代器持有的命令行字符串副本,以及此前返回的
/// 所有参数切片。
pub fn deinit(self: *Windows) void {
self.allocator.free(self.buffer);
}
};
pub const Posix = struct {
remaining: Vector,
pub const InitError = error{};
pub fn init(a: Args) Posix {
return .{ .remaining = a.vector };
}
pub fn next(it: *Posix) ?[:0]const u8 {
if (it.remaining.len == 0) return null;
const arg = it.remaining[0];
it.remaining = it.remaining[1..];
return std.mem.sliceTo(arg, 0);
}
pub fn skip(it: *Posix) bool {
if (it.remaining.len == 0) return false;
it.remaining = it.remaining[1..];
return true;
}
};
pub const Wasi = struct {
allocator: Allocator,
index: usize,
args: [][:0]u8,
pub const InitError = error{OutOfMemory} || std.posix.UnexpectedError;
/// 使用完毕后,必须调用 deinit
/// 释放迭代器的内部缓冲区。
pub fn init(allocator: Allocator) Wasi.InitError!Wasi {
const fetched_args = try Wasi.internalInit(allocator);
return Wasi{
.allocator = allocator,
.index = 0,
.args = fetched_args,
};
}
fn internalInit(allocator: Allocator) Wasi.InitError![][:0]u8 {
var count: usize = undefined;
var buf_size: usize = undefined;
switch (std.os.wasi.args_sizes_get(&count, &buf_size)) {
.SUCCESS => {},
else => |err| return std.posix.unexpectedErrno(err),
}
if (count == 0) {
return &[_][:0]u8{};
}
const argv = try allocator.alloc([*:0]u8, count);
defer allocator.free(argv);
const argv_buf = try allocator.alloc(u8, buf_size);
switch (std.os.wasi.args_get(argv.ptr, argv_buf.ptr)) {
.SUCCESS => {},
else => |err| return std.posix.unexpectedErrno(err),
}
var result_args = try allocator.alloc([:0]u8, count);
var i: usize = 0;
while (i < count) : (i += 1) {
result_args[i] = std.mem.sliceTo(argv[i], 0);
}
return result_args;
}
pub fn next(self: *Wasi) ?[:0]const u8 {
if (self.index == self.args.len) return null;
const arg = self.args[self.index];
self.index += 1;
return arg;
}
pub fn skip(self: *Wasi) bool {
if (self.index == self.args.len) return false;
self.index += 1;
return true;
}
/// 调用以释放迭代器的内部缓冲区。
pub fn deinit(self: *Wasi) void {
// 没有参数时不分配任何内存
if (self.args.len == 0) return;
const last_item = self.args[self.args.len - 1];
const last_byte_addr = @intFromPtr(last_item.ptr) + last_item.len + 1; // 以空字符终止
const first_item_ptr = self.args[0].ptr;
const len = last_byte_addr - @intFromPtr(first_item_ptr);
self.allocator.free(first_item_ptr[0..len]);
self.allocator.free(self.args);
}
};
};
/// 保存命令行参数,程序名称为第一项。
/// 跨平台代码请使用 `iterateAllocator`。
pub fn iterate(a: Args) Iterator {
return .init(a);
}
/// 使用完毕后,必须调用 `deinit` 反初始化迭代器的内部
/// 缓冲区。
pub fn iterateAllocator(a: Args, gpa: Allocator) Iterator.InitError!Iterator {
return .initAllocator(a, gpa);
}
pub const ToSliceError = Iterator.Windows.InitError || Iterator.Wasi.InitError;
/// 返回值可能引用多次分配,并可能指向 `a` 内部。
/// 因此必须使用 arena 风格的分配器。
///
/// * Windows 上,结果编码为
/// [WTF-8](https://wtf-8.codeberg.page/)。
/// * 其他平台上,结果是不规定编码的
/// 不透明字节序列。
///
/// 另请参见:
/// * `iterate`
/// * `iterateAllocator`
pub fn toSlice(a: Args, arena: Allocator) ToSliceError![]const [:0]const u8 {
if (native_os == .windows) {
var it = try a.iterateAllocator(arena);
var contents: std.ArrayList(u8) = .empty;
var slice_list: std.ArrayList(usize) = .empty;
while (it.next()) |arg| {
try contents.appendSlice(arena, arg[0 .. arg.len + 1]);
try slice_list.append(arena, arg.len);
}
const contents_slice = contents.items;
const slice_sizes = slice_list.items;
const slice_list_bytes = std.math.mul(usize, @sizeOf([]u8), slice_sizes.len) catch return error.OutOfMemory;
const total_bytes = std.math.add(usize, slice_list_bytes, contents_slice.len) catch return error.OutOfMemory;
const buf = try arena.alignedAlloc(u8, .of([]u8), total_bytes);
errdefer arena.free(buf);
const result_slice_list = std.mem.bytesAsSlice([:0]u8, buf[0..slice_list_bytes]);
const result_contents = buf[slice_list_bytes..];
@memcpy(result_contents[0..contents_slice.len], contents_slice);
var contents_index: usize = 0;
for (slice_sizes, 0..) |len, i| {
const new_index = contents_index + len;
result_slice_list[i] = result_contents[contents_index..new_index :0];
contents_index = new_index + 1;
}
return result_slice_list;
} else if (native_os == .wasi and !builtin.link_libc) {
var count: usize = undefined;
var buf_size: usize = undefined;
switch (std.os.wasi.args_sizes_get(&count, &buf_size)) {
.SUCCESS => {},
else => |err| return std.posix.unexpectedErrno(err),
}
if (count == 0) return &.{};
const argv = try arena.alloc([*:0]u8, count);
const argv_buf = try arena.alloc(u8, buf_size);
switch (std.os.wasi.args_get(argv.ptr, argv_buf.ptr)) {
.SUCCESS => {},
else => |err| return std.posix.unexpectedErrno(err),
}
const args = try arena.alloc([:0]const u8, count);
for (args, argv) |*dst, src| dst.* = std.mem.sliceTo(src, 0);
return args;
} else {
const args = try arena.alloc([:0]const u8, a.vector.len);
for (args, a.vector) |*dst, src| dst.* = std.mem.sliceTo(src, 0);
return args;
}
}
test "Iterator.Windows" {
const t = testIteratorWindows;
try t(
\\"C:\Program Files\zig\zig.exe" run .\src\main.zig -target x86_64-windows-gnu -O safe -- --emoji=🗿 --eval="new Regex(\"Dwayne \\\"The Rock\\\" Johnson\")"
, &.{
\\C:\Program Files\zig\zig.exe
,
\\run
,
\\.\src\main.zig
,
\\-target
,
\\x86_64-windows-gnu
,
\\-O
,
\\safe
,
\\--
,
\\--emoji=🗿
,
\\--eval=new Regex("Dwayne \"The Rock\" Johnson")
,
});
// 空
try t("", &.{});
// 分隔符
try t("aa bb cc", &.{ "aa", "bb", "cc" });
try t("aa\tbb\tcc", &.{ "aa", "bb", "cc" });
try t("aa\nbb\ncc", &.{"aa\nbb\ncc"});
try t("aa\r\nbb\r\ncc", &.{"aa\r\nbb\r\ncc"});
try t("aa\rbb\rcc", &.{"aa\rbb\rcc"});
try t("aa\x07bb\x07cc", &.{"aa\x07bb\x07cc"});
try t("aa\x7Fbb\x7Fcc", &.{"aa\x7Fbb\x7Fcc"});
try t("aa🦎bb🦎cc", &.{"aa🦎bb🦎cc"});
// 前导/尾随空白字符
try t(" ", &.{""});
try t(" aa bb ", &.{ "", "aa", "bb" });
try t("\t\t", &.{""});
try t("\t\taa\t\tbb\t\t", &.{ "", "aa", "bb" });
try t("\n\n", &.{"\n\n"});
try t("\n\naa\n\nbb\n\n", &.{"\n\naa\n\nbb\n\n"});
// 含引号或反斜杠的可执行文件名
try t("\"aa bb\tcc\ndd\"", &.{"aa bb\tcc\ndd"});
try t("\"", &.{""});
try t("\"\"", &.{""});
try t("\"\"\"", &.{""});
try t("\"\"\"\"", &.{""});
try t("\"\"\"\"\"", &.{""});
try t("aa\"bb\"cc\"dd", &.{"aabbccdd"});
try t("aa\"bb cc\"dd", &.{"aabb ccdd"});
try t("\"aa\\\"bb\"", &.{"aa\\bb"});
try t("\"aa\\\\\"", &.{"aa\\\\"});
try t("aa\\\"bb", &.{"aa\\bb"});
try t("aa\\\\\"bb", &.{"aa\\\\bb"});
// 带引号/反斜杠的参数
try t(". \"aa bb\tcc\ndd\"", &.{ ".", "aa bb\tcc\ndd" });
try t(". aa\" \"bb\"\t\"cc\"\n\"dd\"", &.{ ".", "aa bb\tcc\ndd" });
try t(". ", &.{"."});
try t(". \"", &.{ ".", "" });
try t(". \"\"", &.{ ".", "" });
try t(". \"\"\"", &.{ ".", "\"" });
try t(". \"\"\"\"", &.{ ".", "\"" });
try t(". \"\"\"\"\"", &.{ ".", "\"\"" });
try t(". \"\"\"\"\"\"", &.{ ".", "\"\"" });
try t(". \" \"", &.{ ".", " " });
try t(". \" \"\"", &.{ ".", " \"" });
try t(". \" \"\"\"", &.{ ".", " \"" });
try t(". \" \"\"\"\"", &.{ ".", " \"\"" });
try t(". \" \"\"\"\"\"", &.{ ".", " \"\"" });
try t(". \" \"\"\"\"\"\"", &.{ ".", " \"\"\"" });
try t(". \\\"", &.{ ".", "\"" });
try t(". \\\"\"", &.{ ".", "\"" });
try t(". \\\"\"\"", &.{ ".", "\"" });
try t(". \\\"\"\"\"", &.{ ".", "\"\"" });
try t(". \\\"\"\"\"\"", &.{ ".", "\"\"" });
try t(". \\\"\"\"\"\"\"", &.{ ".", "\"\"\"" });
try t(". \" \\\"", &.{ ".", " \"" });
try t(". \" \\\"\"", &.{ ".", " \"" });
try t(". \" \\\"\"\"", &.{ ".", " \"\"" });
try t(". \" \\\"\"\"\"", &.{ ".", " \"\"" });
try t(". \" \\\"\"\"\"\"", &.{ ".", " \"\"\"" });
try t(". \" \\\"\"\"\"\"\"", &.{ ".", " \"\"\"" });
try t(". aa\\bb\\\\cc\\\\\\dd", &.{ ".", "aa\\bb\\\\cc\\\\\\dd" });
try t(". \\\\\\\"aa bb\"", &.{ ".", "\\\"aa", "bb" });
try t(". \\\\\\\\\"aa bb\"", &.{ ".", "\\\\aa bb" });
// 来源:https://learn.microsoft.com/en-us/cpp/cpp/main-function-command-line-args#results-of-parsing-command-lines
try t(
\\foo.exe "abc" d e
, &.{ "foo.exe", "abc", "d", "e" });
try t(
\\foo.exe a\\b d"e f"g h
, &.{ "foo.exe", "a\\\\b", "de fg", "h" });
try t(
\\foo.exe a\\\"b c d
, &.{ "foo.exe", "a\\\"b", "c", "d" });
try t(
\\foo.exe a\\\\"b c" d e
, &.{ "foo.exe", "a\\\\b c", "d", "e" });
try t(
\\foo.exe a"b"" c d
, &.{ "foo.exe", "ab\" c d" });
// 来源:https://daviddeley.com/autohotkey/parameters/parameters.htm#WINCRULESEX
try t("foo.exe CallMeIshmael", &.{ "foo.exe", "CallMeIshmael" });
try t("foo.exe \"Call Me Ishmael\"", &.{ "foo.exe", "Call Me Ishmael" });
try t("foo.exe Cal\"l Me I\"shmael", &.{ "foo.exe", "Call Me Ishmael" });
try t("foo.exe CallMe\\\"Ishmael", &.{ "foo.exe", "CallMe\"Ishmael" });
try t("foo.exe \"CallMe\\\"Ishmael\"", &.{ "foo.exe", "CallMe\"Ishmael" });
try t("foo.exe \"Call Me Ishmael\\\\\"", &.{ "foo.exe", "Call Me Ishmael\\" });
try t("foo.exe \"CallMe\\\\\\\"Ishmael\"", &.{ "foo.exe", "CallMe\\\"Ishmael" });
try t("foo.exe a\\\\\\b", &.{ "foo.exe", "a\\\\\\b" });
try t("foo.exe \"a\\\\\\b\"", &.{ "foo.exe", "a\\\\\\b" });
// 用引号分隔的 𐐷 代理对编码。
// 编码为 WTF-16:
// "<0xD801>"<0xDC37>
// 编码为 WTF-8:
// "<0xED><0xA0><0x81>"<0xED><0xB0><0xB7>
// 解析时,引号被移除,代理对最终
// 应编码为其正常的 UTF-8 表示。
try t("foo.exe \"\xed\xa0\x81\"\xed\xb0\xb7", &.{ "foo.exe", "𐐷" });
}
fn testIteratorWindows(cmd_line: []const u8, expected_args: []const []const u8) !void {
const cmd_line_w = try std.unicode.wtf8ToWtf16LeAllocZ(testing.allocator, cmd_line);
defer testing.allocator.free(cmd_line_w);
// 下一个
{
var it = try Iterator.Windows.init(testing.allocator, cmd_line_w);
defer it.deinit();
for (expected_args) |expected| {
if (it.next()) |actual| {
try testing.expectEqualStrings(expected, actual);
} else {
return error.TestUnexpectedResult;
}
}
try testing.expect(it.next() == null);
}
// 跳过
{
var it = try Iterator.Windows.init(testing.allocator, cmd_line_w);
defer it.deinit();
for (0..expected_args.len) |_| {
try testing.expect(it.skip());
}
try testing.expect(!it.skip());
}
}
test "general parsing" {
try testGeneralCmdLine("a b\tc d", &.{ "a", "b", "c", "d" });
try testGeneralCmdLine("\"abc\" d e", &.{ "abc", "d", "e" });
try testGeneralCmdLine("a\\\\\\b d\"e f\"g h", &.{ "a\\\\\\b", "de fg", "h" });
try testGeneralCmdLine("a\\\\\\\"b c d", &.{ "a\\\"b", "c", "d" });
try testGeneralCmdLine("a\\\\\\\\\"b c\" d e", &.{ "a\\\\b c", "d", "e" });
try testGeneralCmdLine("a b\tc \"d f", &.{ "a", "b", "c", "d f" });
try testGeneralCmdLine("j k l\\", &.{ "j", "k", "l\\" });
try testGeneralCmdLine("\"\" x y z\\\\", &.{ "", "x", "y", "z\\\\" });
try testGeneralCmdLine("\".\\..\\zig-cache\\build\" \"bin\\zig.exe\" \".\\..\" \".\\..\\zig-cache\" \"--help\"", &.{
".\\..\\zig-cache\\build",
"bin\\zig.exe",
".\\..",
".\\..\\zig-cache",
"--help",
});
try testGeneralCmdLine(
\\ 'foo' "bar"
, &.{ "'foo'", "bar" });
}
fn testGeneralCmdLine(input_cmd_line: []const u8, expected_args: []const []const u8) !void {
var it = try IteratorGeneral(.{}).init(std.testing.allocator, input_cmd_line);
defer it.deinit();
for (expected_args) |expected_arg| {
const arg = it.next().?;
try testing.expectEqualStrings(expected_arg, arg);
}
try testing.expect(it.next() == null);
}
/// `IteratorGeneral` 的可选参数
pub const IteratorGeneralOptions = struct {
comments: bool = false,
single_quotes: bool = false,
};
/// 将字符串解析为一组参数的通用迭代器。
pub fn IteratorGeneral(comptime options: IteratorGeneralOptions) type {
return struct {
allocator: Allocator,
index: usize = 0,
cmd_line: []const u8,
/// 是否应在 deinit() 时使用分配器释放 cmd_line 字段?
free_cmd_line_on_deinit: bool,
/// buffer 必须足够长,以容纳 cmd_line 和空终止符。
/// deinit() 时将(使用分配器)释放 buffer
buffer: []u8,
start: usize = 0,
end: usize = 0,
const Self = @This();
pub const InitError = error{OutOfMemory};
/// 使用此实例期间,cmd_line_utf8 必须保持有效且不变
pub fn init(allocator: Allocator, cmd_line_utf8: []const u8) InitError!Self {
const buffer = try allocator.alloc(u8, cmd_line_utf8.len + 1);
errdefer allocator.free(buffer);
return Self{
.allocator = allocator,
.cmd_line = cmd_line_utf8,
.free_cmd_line_on_deinit = false,
.buffer = buffer,
};
}
/// cmd_line_utf8 将在 deinit() 中(通过该分配器)释放
pub fn initTakeOwnership(allocator: Allocator, cmd_line_utf8: []const u8) InitError!Self {
const buffer = try allocator.alloc(u8, cmd_line_utf8.len + 1);
errdefer allocator.free(buffer);
return Self{
.allocator = allocator,
.cmd_line = cmd_line_utf8,
.free_cmd_line_on_deinit = true,
.buffer = buffer,
};
}
// 跳过 cmd_line 中的空白。
// 若到达终止哨兵,则返回 false,否则返回 true。
// 也会跳过注释(如果支持)。
fn skipWhitespace(self: *Self) bool {
while (true) : (self.index += 1) {
const character = if (self.index != self.cmd_line.len) self.cmd_line[self.index] else 0;
switch (character) {
0 => return false,
' ', '\t', '\r', '\n' => continue,
'#' => {
if (options.comments) {
while (true) : (self.index += 1) {
switch (self.cmd_line[self.index]) {
'\n' => break,
0 => return false,
else => continue,
}
}
continue;
} else {
break;
}
},
else => break,
}
}
return true;
}
pub fn skip(self: *Self) bool {
if (!self.skipWhitespace()) {
return false;
}
var backslash_count: usize = 0;
var in_quote = false;
while (true) : (self.index += 1) {
const character = if (self.index != self.cmd_line.len) self.cmd_line[self.index] else 0;
switch (character) {
0 => return true,
'"', '\'' => {
if (!options.single_quotes and character == '\'') {
backslash_count = 0;
continue;
}
const quote_is_real = backslash_count % 2 == 0;
if (quote_is_real) {
in_quote = !in_quote;
}
},
'\\' => {
backslash_count += 1;
},
' ', '\t', '\r', '\n' => {
if (!in_quote) {
return true;
}
backslash_count = 0;
},
else => {
backslash_count = 0;
continue;
},
}
}
}
/// 返回内部缓冲区中包含下一个参数的切片。
/// 到达末尾时返回 null。
pub fn next(self: *Self) ?[:0]const u8 {
if (!self.skipWhitespace()) {
return null;
}
var backslash_count: usize = 0;
var in_quote = false;
while (true) : (self.index += 1) {
const character = if (self.index != self.cmd_line.len) self.cmd_line[self.index] else 0;
switch (character) {
0 => {
self.emitBackslashes(backslash_count);
self.buffer[self.end] = 0;
const token = self.buffer[self.start..self.end :0];
self.end += 1;
self.start = self.end;
return token;
},
'"', '\'' => {
if (!options.single_quotes and character == '\'') {
self.emitBackslashes(backslash_count);
backslash_count = 0;
self.emitCharacter(character);
continue;
}
const quote_is_real = backslash_count % 2 == 0;
self.emitBackslashes(backslash_count / 2);
backslash_count = 0;
if (quote_is_real) {
in_quote = !in_quote;
} else {
self.emitCharacter('"');
}
},
'\\' => {
backslash_count += 1;
},
' ', '\t', '\r', '\n' => {
self.emitBackslashes(backslash_count);
backslash_count = 0;
if (in_quote) {
self.emitCharacter(character);
} else {
self.buffer[self.end] = 0;
const token = self.buffer[self.start..self.end :0];
self.end += 1;
self.start = self.end;
return token;
}
},
else => {
self.emitBackslashes(backslash_count);
backslash_count = 0;
self.emitCharacter(character);
},
}
}
}
fn emitBackslashes(self: *Self, emit_count: usize) void {
var i: usize = 0;
while (i < emit_count) : (i += 1) {
self.emitCharacter('\\');
}
}
fn emitCharacter(self: *Self, char: u8) void {
self.buffer[self.end] = char;
self.end += 1;
}
/// 调用以释放迭代器的内部缓冲区。
pub fn deinit(self: *Self) void {
self.allocator.free(self.buffer);
if (self.free_cmd_line_on_deinit) {
self.allocator.free(self.cmd_line);
}
}
};
}
test "response file arg parsing" {
try testResponseFileCmdLine(
\\a b
\\c d\
, &.{ "a", "b", "c", "d\\" });
try testResponseFileCmdLine("a b c d\\", &.{ "a", "b", "c", "d\\" });
try testResponseFileCmdLine(
\\j
\\ k l # this is a comment \\ \\\ \\\\ "none" "\\" "\\\"
\\ "m" #another comment
\\
, &.{ "j", "k", "l", "m" });
try testResponseFileCmdLine(
\\ "" q ""
\\ "r s # t" "u\" v" #another comment
\\
, &.{ "", "q", "", "r s # t", "u\" v" });
try testResponseFileCmdLine(
\\ -l"advapi32" a# b#c d#
\\e\\\
, &.{ "-ladvapi32", "a#", "b#c", "d#", "e\\\\\\" });
try testResponseFileCmdLine(
\\ 'foo' "bar"
, &.{ "foo", "bar" });
}
fn testResponseFileCmdLine(input_cmd_line: []const u8, expected_args: []const []const u8) !void {
var it = try IteratorGeneral(.{ .comments = true, .single_quotes = true })
.init(std.testing.allocator, input_cmd_line);
defer it.deinit();
for (expected_args) |expected_arg| {
const arg = it.next().?;
try testing.expectEqualStrings(expected_arg, arg);
}
try testing.expect(it.next() == null);
}