diff --git a/changelog.d/+argparse-native-exact-parity-test.misc.md b/changelog.d/+argparse-native-exact-parity-test.misc.md new file mode 100644 index 0000000..1eeb860 --- /dev/null +++ b/changelog.d/+argparse-native-exact-parity-test.misc.md @@ -0,0 +1 @@ +Add differential parity fuzz tests covering variadic intermixed positionals (`parse_intermixed_args`) plus `Policy.native_exact` with `SpecialActionMode.prescan` and `CommandSpec.mutually_exclusive` alongside `PositionalSpec.ignore_empty` and `ErrorKind`. diff --git a/changelog.d/+argparse-native-exact-policy.feature.md b/changelog.d/+argparse-native-exact-policy.feature.md new file mode 100644 index 0000000..2d3ecf8 --- /dev/null +++ b/changelog.d/+argparse-native-exact-policy.feature.md @@ -0,0 +1 @@ +Add `Policy.native_exact` with `NegativeNumberMode.any` and `SpecialActionMode.prescan` plus `Policy.fail_fast` and `CommandSpec.mutually_exclusive` alongside `OptionSpec.allow_empty` / `allow_dash_value` in `zig_common.argparse`. diff --git a/changelog.d/+argparse-usage-error-kind.feature.md b/changelog.d/+argparse-usage-error-kind.feature.md new file mode 100644 index 0000000..6d5cd60 --- /dev/null +++ b/changelog.d/+argparse-usage-error-kind.feature.md @@ -0,0 +1 @@ +Add structured `ErrorKind` classification on `UsageError` in `zig_common.argparse` so callers can render native diagnostics without parsing `UsageError.message`. diff --git a/changelog.d/+argparse-variadic-positional-unknown.feature.md b/changelog.d/+argparse-variadic-positional-unknown.feature.md new file mode 100644 index 0000000..2a5bb8d --- /dev/null +++ b/changelog.d/+argparse-variadic-positional-unknown.feature.md @@ -0,0 +1 @@ +Add `PositionalArity.zero_or_more` and `PositionalArity.one_or_more` alongside `PositionalSpec.ignore_empty` and `UnknownMode.positional` in `zig_common.argparse`. diff --git a/src/argparse.zig b/src/argparse.zig index 4c69bdb..f363647 100644 --- a/src/argparse.zig +++ b/src/argparse.zig @@ -23,6 +23,9 @@ pub const UnknownMode = enum { collect, /// Ignore unknown options and extra tokens without error. ignore, + /// Treat unrecognized option-like tokens as positional arguments while + /// still rejecting positionals past the declared slots. + positional, }; /// How a bare `--` token is treated while scanning options. @@ -41,6 +44,10 @@ pub const NegativeNumberMode = enum { /// Every token starting with `-` is option-like (never consumed as a /// space-separated value). never, + /// Consume any token following a value option (including dash-prefixed + /// tokens such as `-5` or `--foo`) while keeping standalone dash tokens + /// option-like. + any, }; /// How `-h`/`--help` and `--version` actions behave during parsing. @@ -49,10 +56,13 @@ pub const SpecialActionMode = enum { immediate_exit, /// Record `help_requested` / `version_requested` on `Parsed` and keep scanning. record, + /// Scan the full argument vector for `-h`/`--help` or `--version` before + /// parsing options and return `ParseOutcome.action_done` immediately if found. + prescan, }; -/// Parser behaviour policy controlling strict Python 3.14 parity vs. lenient -/// TaskProlog parsing. +/// Parser behaviour policy controlling strict Python 3.14 parity, lenient +/// TaskProlog parsing, and exact-match native Zig CLIs. pub const Policy = struct { allow_abbrev: bool = true, unknown: UnknownMode = .collect, @@ -60,6 +70,15 @@ pub const Policy = struct { negative_numbers: NegativeNumberMode = .py314, short_clusters: bool = true, special_action: SpecialActionMode = .immediate_exit, + /// Treat `--flag=val` on a boolean flag (and `--help=val` / `--version=val`) + /// as an unrecognized option-like token instead of an `ignored explicit argument` error. + flag_explicit_as_unknown: bool = false, + /// Report unrecognized options and excess positionals before missing required + /// options, positionals, or subcommands. + unknown_before_required: bool = false, + /// Return immediately on the first unrecognized option, excess positional, + /// or mutually exclusive conflict encountered during left-to-right scanning. + fail_fast: bool = false, write_stdout: WriteFn = defaultStdout, write_stderr: WriteFn = defaultStderr, @@ -85,6 +104,23 @@ pub const Policy = struct { .short_clusters = false, .special_action = .record, }; + + /// Exact-match policy for native Zig CLIs: no abbreviations, no short + /// clustering, `--` is not a special separator, any token following a value + /// option is consumed as its value, `--flag=val` is treated as an unknown + /// option, unknown tokens are reported before missing required arguments, + /// and scan-time errors fail fast left-to-right. + pub const native_exact: Policy = .{ + .allow_abbrev = false, + .unknown = .collect, + .double_dash = .ignore, + .negative_numbers = .any, + .short_clusters = false, + .special_action = .immediate_exit, + .flag_explicit_as_unknown = true, + .unknown_before_required = true, + .fail_fast = true, + }; }; /// Result returned by a typed option validator callback. @@ -133,6 +169,12 @@ pub const OptionSpec = struct { choices: ?[]const []const u8 = null, /// Optional eager value validator; runs on every occurrence as it is parsed. validate: ?ValidatorFn = null, + /// Allow an empty string value (`--opt=` or `--opt ""`). When `false`, + /// an empty value is rejected as a missing option argument. + allow_empty: bool = true, + /// Allow a value starting with `-` (including `--opt=-val`). When `false`, + /// a leading-dash value is rejected as a missing option argument. + allow_dash_value: bool = true, }; /// Arity of a positional argument. @@ -141,6 +183,10 @@ pub const PositionalArity = enum { required_one, /// Zero or one optional positional argument (`nargs="?"`). optional_one, + /// Zero or more positional arguments, intermixed with options (`nargs="*"`). + zero_or_more, + /// One or more positional arguments, intermixed with options (`nargs="+"`). + one_or_more, /// Capture `--` or the first non-option token and everything after (`argparse.REMAINDER`). remainder, }; @@ -153,6 +199,8 @@ pub const PositionalSpec = struct { arity: PositionalArity = .required_one, /// Optional static set of allowed values, validated eagerly on parse. choices: ?[]const []const u8 = null, + /// Skip empty (`""`) positional tokens instead of filling this slot. + ignore_empty: bool = false, }; /// Subcommand binding a command name to its own `CommandSpec`. @@ -163,6 +211,12 @@ pub const SubcommandSpec = struct { command: *const CommandSpec, }; +/// Group of option long names that cannot appear together on the same invocation. +pub const MutexGroup = struct { + /// Long option names (without leading `--`) belonging to this group. + options: []const []const u8, +}; + /// Declarative specification for a parser (top-level or subcommand). pub const CommandSpec = struct { /// Program or subcommand name printed before `: error: `. @@ -179,6 +233,8 @@ pub const CommandSpec = struct { policy: Policy = .python314, /// Options in registration order (used for ambiguity listings and missing-argument errors). options: []const OptionSpec = &.{}, + /// Mutually exclusive option groups for this parser. + mutually_exclusive: []const MutexGroup = &.{}, /// Positional arguments in declaration order. positionals: []const PositionalSpec = &.{}, /// Optional subcommand dispatch table. @@ -270,13 +326,61 @@ pub const ActionDone = struct { stdout_text: []const u8, }; +/// Machine-readable classification of a `UsageError` so callers can render +/// native diagnostics without parsing `UsageError.message`. +pub const ErrorKind = union(enum) { + /// A required subcommand was omitted. + missing_subcommand, + /// An unrecognized subcommand token was supplied. + unknown_subcommand: []const u8, + /// An unrecognized option-like token was supplied (first offending token). + unknown_option: []const u8, + /// A positional token exceeded the declared positional slots (first offending token). + extra_positional: []const u8, + /// A value option was missing its argument (option long name without `--`), + /// or received an empty or leading-dash value disallowed by its `OptionSpec`. + missing_value: []const u8, + /// A boolean flag, `-h`/`--help`, or `--version` received an explicit `=value`. + unexpected_value: struct { + /// Option long name without `--` (`"help"`, `"version"`, or `OptionSpec.name`). + option: []const u8, + /// Explicit value slice after `=` or attached short-cluster tail. + value: []const u8, + }, + /// An abbreviated long option matched more than one option (raw token). + ambiguous_option: []const u8, + /// One or more required options or positionals were omitted (first missing + /// option long name without `--`, or positional `name`). + missing_required: []const u8, + /// A choice check or `OptionSpec.validate` callback rejected a value. + invalid_value: struct { + /// Option long name without `--`, or positional `name`. + name: []const u8, + /// Rejected raw value. + value: []const u8, + }, + /// Two options from a `MutexGroup` were supplied together. + mutually_exclusive: struct { + /// Option long name without `--` that triggered the conflict. + option: []const u8, + /// Previously seen conflicting option long name without `--`. + conflict: []const u8, + }, +}; + /// Formatted argparse usage error (exit code 2). +/// +/// All heap memory owned by a `UsageError` is stored in `message` (any token +/// slices stored in `kind` borrow either `argv`, `CommandSpec`, or `message`), +/// and `deinit` releases it in one call. pub const UsageError = struct { usage: []const u8, prog: []const u8, message: []u8, + kind: ErrorKind, exit_code: u8 = cli.usage_exit, + /// Release all heap memory owned by this `UsageError`. pub fn deinit(self: *UsageError, gpa: Allocator) void { gpa.free(self.message); } @@ -305,10 +409,11 @@ pub const ParseOutcome = union(enum) { /// Whether `arg` looks like an option under `mode`. /// Under `.py314`, mirrors Python 3.14 `_parse_optional`: starts with `-`, has /// length >= 2, contains no ASCII space, and is not a negative number (`-DIGIT` -/// or `-.DIGIT`). Under `.never`, any token starting with `-` is option-like. +/// or `-.DIGIT`). Under `.never` and `.any`, any token starting with `-` is +/// option-like when standing alone. pub fn optionLike(arg: []const u8, mode: NegativeNumberMode) bool { switch (mode) { - .never => return arg.len >= 1 and arg[0] == '-', + .never, .any => return arg.len >= 1 and arg[0] == '-', .py314 => { if (arg.len < 2 or arg[0] != '-') return false; if (std.mem.findScalar(u8, arg, ' ') != null) return false; @@ -524,12 +629,41 @@ pub const types = struct { // ---- pure parser implementation ------------------------------------------- -fn makeError(gpa: Allocator, spec: *const CommandSpec, comptime fmt: []const u8, args: anytype) Allocator.Error!ParseOutcome { +fn makeError( + gpa: Allocator, + spec: *const CommandSpec, + kind: ErrorKind, + comptime fmt: []const u8, + args: anytype, +) Allocator.Error!ParseOutcome { const msg = try std.fmt.allocPrint(gpa, fmt, args); return .{ .usage_error = .{ .usage = spec.usage, .prog = spec.prog, .message = msg, + .kind = kind, + } }; +} + +fn makeUnrecognizedError( + gpa: Allocator, + spec: *const CommandSpec, + joined: []const u8, + first_len: usize, + is_positional: bool, +) Allocator.Error!ParseOutcome { + const prefix = "unrecognized arguments: "; + const msg = try std.fmt.allocPrint(gpa, prefix ++ "{s}", .{joined}); + const tok_slice = msg[prefix.len .. prefix.len + first_len]; + const kind: ErrorKind = if (is_positional) + .{ .extra_positional = tok_slice } + else + .{ .unknown_option = tok_slice }; + return .{ .usage_error = .{ + .usage = spec.usage, + .prog = spec.prog, + .message = msg, + .kind = kind, } }; } @@ -540,6 +674,20 @@ fn formatOptionDisplay(gpa: Allocator, opt: OptionSpec) Allocator.Error![]u8 { return std.fmt.allocPrint(gpa, "--{s}", .{opt.name}); } +fn checkOptionValueAllowed( + gpa: Allocator, + spec: *const CommandSpec, + opt: OptionSpec, + val: []const u8, +) Allocator.Error!?ParseOutcome { + if ((!opt.allow_empty and val.len == 0) or (!opt.allow_dash_value and val.len > 0 and val[0] == '-')) { + const disp = try formatOptionDisplay(gpa, opt); + defer gpa.free(disp); + return try makeError(gpa, spec, .{ .missing_value = opt.name }, "argument {s}: expected one argument", .{disp}); + } + return null; +} + fn validateOptionValue( gpa: Allocator, spec: *const CommandSpec, @@ -554,7 +702,7 @@ fn validateOptionValue( defer gpa.free(detail); const disp = try formatOptionDisplay(gpa, opt); defer gpa.free(disp); - return try makeError(gpa, spec, "argument {s}: {s}", .{ disp, detail }); + return try makeError(gpa, spec, .{ .invalid_value = .{ .name = opt.name, .value = val } }, "argument {s}: {s}", .{ disp, detail }); }, } } @@ -566,7 +714,24 @@ fn validateOptionValue( defer gpa.free(disp); const detail = try types.formatChoicesDetail(gpa, val, allowed); defer gpa.free(detail); - return try makeError(gpa, spec, "argument {s}: {s}", .{ disp, detail }); + return try makeError(gpa, spec, .{ .invalid_value = .{ .name = opt.name, .value = val } }, "argument {s}: {s}", .{ disp, detail }); + } + return null; +} + +fn positionalSpecAt(spec: *const CommandSpec, pos_index: usize) ?PositionalSpec { + var slot: usize = 0; + for (spec.positionals) |p| { + switch (p.arity) { + .remainder => continue, + .zero_or_more, .one_or_more => { + if (pos_index >= slot) return p; + }, + .required_one, .optional_one => { + if (pos_index == slot) return p; + slot += 1; + }, + } } return null; } @@ -577,15 +742,14 @@ fn validatePositionalChoice( pos_index: usize, val: []const u8, ) Allocator.Error!?ParseOutcome { - if (pos_index >= spec.positionals.len) return null; - const p = spec.positionals[pos_index]; + const p = positionalSpecAt(spec, pos_index) orelse return null; const allowed = p.choices orelse return null; for (allowed) |c| { if (std.mem.eql(u8, c, val)) return null; } const detail = try types.formatChoicesDetail(gpa, val, allowed); defer gpa.free(detail); - return try makeError(gpa, spec, "argument {s}: {s}", .{ p.name, detail }); + return try makeError(gpa, spec, .{ .invalid_value = .{ .name = p.name, .value = val } }, "argument {s}: {s}", .{ p.name, detail }); } fn formatAmbiguous(gpa: Allocator, spec: *const CommandSpec, prefix: []const u8) Allocator.Error![]u8 { @@ -664,7 +828,7 @@ fn matchShortChar(spec: *const CommandSpec, c: u8) ?ShortTarget { } fn isOptionToken(spec: *const CommandSpec, arg: []const u8) bool { - if (spec.policy.negative_numbers == .never) { + if (spec.policy.negative_numbers == .never or spec.policy.negative_numbers == .any) { return arg.len >= 1 and arg[0] == '-'; } if (arg.len < 2 or arg[0] != '-') return false; @@ -683,6 +847,11 @@ fn isOptionToken(spec: *const CommandSpec, arg: []const u8) bool { return optionLike(arg, spec.policy.negative_numbers); } +fn canConsumeNextValue(spec: *const CommandSpec, next_arg: []const u8) bool { + if (spec.policy.negative_numbers == .any) return true; + return !isOptionToken(spec, next_arg); +} + const ClusterItem = struct { target: ShortTarget, explicit: ?[]const u8 = null, @@ -693,6 +862,24 @@ fn hasRemainder(spec: *const CommandSpec) bool { return false; } +fn hasVariadicPositional(spec: *const CommandSpec) bool { + for (spec.positionals) |p| { + if (p.arity == .zero_or_more or p.arity == .one_or_more) return true; + } + return false; +} + +fn ignoresEmptyAt(spec: *const CommandSpec, pos_index: usize) bool { + var slot: usize = 0; + for (spec.positionals) |p| { + if (p.arity == .remainder) return false; + if (p.arity == .zero_or_more or p.arity == .one_or_more) return p.ignore_empty; + if (slot == pos_index) return p.ignore_empty; + slot += 1; + } + return false; +} + fn nonRemainderPositionals(spec: *const CommandSpec) usize { var n: usize = 0; for (spec.positionals) |p| if (p.arity != .remainder) { @@ -701,6 +888,49 @@ fn nonRemainderPositionals(spec: *const CommandSpec) usize { return n; } +fn findMutexConflict(spec: *const CommandSpec, opt_seen: []const bool, opt_idx: usize) ?usize { + const name = spec.options[opt_idx].name; + for (spec.mutually_exclusive) |group| { + var in_group = false; + for (group.options) |member| { + if (std.mem.eql(u8, member, name)) { + in_group = true; + break; + } + } + if (!in_group) continue; + for (group.options) |member| { + if (std.mem.eql(u8, member, name)) continue; + for (spec.options, 0..) |o, oi| { + if (std.mem.eql(u8, o.name, member) and opt_seen[oi]) return oi; + } + } + } + return null; +} + +fn makeMutexError( + gpa: Allocator, + spec: *const CommandSpec, + opt_idx: usize, + conflict_idx: usize, +) Allocator.Error!ParseOutcome { + const disp_opt = try formatOptionDisplay(gpa, spec.options[opt_idx]); + defer gpa.free(disp_opt); + const disp_conflict = try formatOptionDisplay(gpa, spec.options[conflict_idx]); + defer gpa.free(disp_conflict); + return try makeError( + gpa, + spec, + .{ .mutually_exclusive = .{ + .option = spec.options[opt_idx].name, + .conflict = spec.options[conflict_idx].name, + } }, + "argument {s}: not allowed with argument {s}", + .{ disp_opt, disp_conflict }, + ); +} + fn checkUnrecognized( gpa: Allocator, top_spec: *const CommandSpec, @@ -708,11 +938,15 @@ fn checkUnrecognized( leftovers: []const Leftover, consumed_positionals: usize, keep_separator: bool, + variadic: bool, ) Allocator.Error!?ParseOutcome { var all: std.ArrayList([]const u8) = .empty; defer all.deinit(gpa); try all.appendSlice(gpa, top_extra); + var first_tok: ?[]const u8 = if (top_extra.len > 0) top_extra[0] else null; + var first_is_pos = false; + var consumed = consumed_positionals; var last_consumed_argv: ?usize = null; var dropped = keep_separator; @@ -725,17 +959,21 @@ fn checkUnrecognized( if (item.is_separator and !dropped) { const adjacent_after = last_consumed_argv != null and item.argv_index == last_consumed_argv.? + 1; const optional_empty = consumed_positionals == 0 and !keep_separator and last_consumed_argv == null; - if (consumed > 0 or adjacent_after or optional_empty) { + if (variadic or consumed > 0 or adjacent_after or optional_empty) { dropped = true; continue; } } + if (first_tok == null) { + first_tok = item.token; + first_is_pos = item.is_positional; + } try all.append(gpa, item.token); } if (all.items.len == 0) return null; const joined = try std.mem.join(gpa, " ", all.items); defer gpa.free(joined); - return try makeError(gpa, top_spec, "unrecognized arguments: {s}", .{joined}); + return try makeUnrecognizedError(gpa, top_spec, joined, first_tok.?.len, first_is_pos); } fn buildParsedState( @@ -817,8 +1055,26 @@ fn parseCommand( const is_remainder = hasRemainder(spec); const has_subs = spec.subcommands.len > 0; + const max_fixed_pos: ?usize = if (is_remainder or hasVariadicPositional(spec)) null else nonRemainderPositionals(spec); var sub_index: ?usize = null; + if (spec.policy.special_action == .prescan) { + for (argv) |a| { + if (spec.add_help and (std.mem.eql(u8, a, "-h") or std.mem.eql(u8, a, "--help"))) { + gpa.free(opt_seen); + gpa.free(opt_values); + own_state = false; + return .{ .action_done = .{ .exit_code = 0, .stdout_text = spec.help } }; + } + if (spec.version != null and std.mem.eql(u8, a, "--version")) { + gpa.free(opt_seen); + gpa.free(opt_values); + own_state = false; + return .{ .action_done = .{ .exit_code = 0, .stdout_text = spec.version.? } }; + } + } + } + var i: usize = 0; while (i < argv.len) : (i += 1) { const arg = argv[i]; @@ -835,6 +1091,15 @@ fn parseCommand( } try leftovers.append(gpa, .{ .token = "--", .is_positional = false, .is_separator = true, .argv_index = i }); for (argv[i + 1 ..], 0..) |p, pi| { + if (p.len == 0 and ignoresEmptyAt(spec, pos.items.len)) continue; + if (spec.policy.fail_fast and spec.policy.unknown != .ignore) { + if (max_fixed_pos) |max_p| if (pos.items.len >= max_p) { + gpa.free(opt_seen); + gpa.free(opt_values); + own_state = false; + return try makeUnrecognizedError(gpa, top_spec, p, p.len, true); + }; + } if (try validatePositionalChoice(gpa, spec, pos.items.len, p)) |err_out| { gpa.free(opt_seen); gpa.free(opt_values); @@ -893,7 +1158,11 @@ fn parseCommand( .option => |k| try formatOptionDisplay(gpa, spec.options[k]), }; defer gpa.free(disp); - cluster_err = try makeError(gpa, spec, "argument {s}: ignored explicit argument {s}", .{ disp, q }); + const opt_name: []const u8 = switch (target) { + .help => "help", + .option => |k| spec.options[k].name, + }; + cluster_err = try makeError(gpa, spec, .{ .unexpected_value = .{ .option = opt_name, .value = bad_val } }, "argument {s}: ignored explicit argument {s}", .{ disp, q }); break; } try items.append(gpa, .{ .target = target }); @@ -923,16 +1192,27 @@ fn parseCommand( }, .option => |k| { const o = spec.options[k]; - opt_seen[k] = true; - if (o.kind == .flag) continue; + if (o.kind == .flag) { + if (findMutexConflict(spec, opt_seen, k)) |conflict_idx| { + if (unknown_tail) |t| gpa.free(t); + gpa.free(opt_seen); + gpa.free(opt_values); + own_state = false; + return try makeMutexError(gpa, spec, k, conflict_idx); + } + opt_seen[k] = true; + continue; + } var val: []const u8 = undefined; + var supplied_val = true; if (it.explicit) |ev| { val = ev; - } else if (i + 1 < argv.len and !isOptionToken(spec, argv[i + 1])) { + } else if (i + 1 < argv.len and canConsumeNextValue(spec, argv[i + 1])) { i += 1; val = argv[i]; } else if (o.kind == .optional_value) { val = ""; + supplied_val = false; } else { if (unknown_tail) |t| gpa.free(t); const disp = try formatOptionDisplay(gpa, o); @@ -940,7 +1220,16 @@ fn parseCommand( gpa.free(opt_seen); gpa.free(opt_values); own_state = false; - return try makeError(gpa, spec, "argument {s}: expected one argument", .{disp}); + return try makeError(gpa, spec, .{ .missing_value = o.name }, "argument {s}: expected one argument", .{disp}); + } + if (supplied_val) { + if (try checkOptionValueAllowed(gpa, spec, o, val)) |err_out| { + if (unknown_tail) |t| gpa.free(t); + gpa.free(opt_seen); + gpa.free(opt_values); + own_state = false; + return err_out; + } } if (try validateOptionValue(gpa, spec, o, val)) |err_out| { if (unknown_tail) |t| gpa.free(t); @@ -949,6 +1238,14 @@ fn parseCommand( own_state = false; return err_out; } + if (findMutexConflict(spec, opt_seen, k)) |conflict_idx| { + if (unknown_tail) |t| gpa.free(t); + gpa.free(opt_seen); + gpa.free(opt_values); + own_state = false; + return try makeMutexError(gpa, spec, k, conflict_idx); + } + opt_seen[k] = true; if (o.kind == .append) { try opt_lists[k].append(gpa, val); } else { @@ -958,6 +1255,13 @@ fn parseCommand( } } if (unknown_tail) |t| { + if (spec.policy.fail_fast and spec.policy.unknown == .collect) { + defer gpa.free(t); + gpa.free(opt_seen); + gpa.free(opt_values); + own_state = false; + return try makeUnrecognizedError(gpa, top_spec, t, t.len, false); + } try scratch.append(gpa, t); try leftovers.append(gpa, .{ .token = t, .is_positional = false, .argv_index = i }); } @@ -977,19 +1281,36 @@ fn parseCommand( }, .option => |k| { const o = spec.options[k]; - opt_seen[k] = true; - if (o.kind != .flag) { + if (o.kind == .flag) { + if (findMutexConflict(spec, opt_seen, k)) |conflict_idx| { + gpa.free(opt_seen); + gpa.free(opt_values); + own_state = false; + return try makeMutexError(gpa, spec, k, conflict_idx); + } + opt_seen[k] = true; + } else { var val: []const u8 = ""; - if (i + 1 < argv.len and !isOptionToken(spec, argv[i + 1])) { + var supplied_val = false; + if (i + 1 < argv.len and canConsumeNextValue(spec, argv[i + 1])) { i += 1; val = argv[i]; + supplied_val = true; } else if (o.kind != .optional_value) { const disp = try formatOptionDisplay(gpa, o); defer gpa.free(disp); gpa.free(opt_seen); gpa.free(opt_values); own_state = false; - return try makeError(gpa, spec, "argument {s}: expected one argument", .{disp}); + return try makeError(gpa, spec, .{ .missing_value = o.name }, "argument {s}: expected one argument", .{disp}); + } + if (supplied_val) { + if (try checkOptionValueAllowed(gpa, spec, o, val)) |err_out| { + gpa.free(opt_seen); + gpa.free(opt_values); + own_state = false; + return err_out; + } } if (try validateOptionValue(gpa, spec, o, val)) |err_out| { gpa.free(opt_seen); @@ -997,6 +1318,13 @@ fn parseCommand( own_state = false; return err_out; } + if (findMutexConflict(spec, opt_seen, k)) |conflict_idx| { + gpa.free(opt_seen); + gpa.free(opt_values); + own_state = false; + return try makeMutexError(gpa, spec, k, conflict_idx); + } + opt_seen[k] = true; if (o.kind == .append) { try opt_lists[k].append(gpa, val); } else { @@ -1011,6 +1339,7 @@ fn parseCommand( } // 3. Long options ("--name", "--name=val", unique prefixes when allow_abbrev). + var force_unknown = false; if (std.mem.startsWith(u8, arg, "--") and (arg.len > 2)) { const eq = std.mem.findScalar(u8, arg, '='); const name = arg[2 .. eq orelse arg.len]; @@ -1021,99 +1350,140 @@ fn parseCommand( gpa.free(opt_seen); gpa.free(opt_values); own_state = false; - return try makeError(gpa, spec, "ambiguous option: {s} could match {s}", .{ arg, amb }); + return try makeError(gpa, spec, .{ .ambiguous_option = arg }, "ambiguous option: {s} could match {s}", .{ arg, amb }); }, .help => { if (eq) |e| { - if (spec.policy.unknown == .ignore) continue; - const q = try reprToken(gpa, arg[e + 1 ..]); - defer gpa.free(q); - gpa.free(opt_seen); - gpa.free(opt_values); - own_state = false; - return try makeError(gpa, spec, "argument -h/--help: ignored explicit argument {s}", .{q}); - } - if (spec.policy.special_action == .immediate_exit) { - gpa.free(opt_seen); - gpa.free(opt_values); - own_state = false; - return .{ .action_done = .{ .exit_code = 0, .stdout_text = spec.help } }; + if (spec.policy.flag_explicit_as_unknown) { + force_unknown = true; + } else { + if (spec.policy.unknown == .ignore) continue; + const val = arg[e + 1 ..]; + const q = try reprToken(gpa, val); + defer gpa.free(q); + gpa.free(opt_seen); + gpa.free(opt_values); + own_state = false; + return try makeError(gpa, spec, .{ .unexpected_value = .{ .option = "help", .value = val } }, "argument -h/--help: ignored explicit argument {s}", .{q}); + } + } else { + if (spec.policy.special_action == .immediate_exit) { + gpa.free(opt_seen); + gpa.free(opt_values); + own_state = false; + return .{ .action_done = .{ .exit_code = 0, .stdout_text = spec.help } }; + } + help_requested = true; + continue; } - help_requested = true; - continue; }, .version => { if (eq) |e| { - if (spec.policy.unknown == .ignore) continue; - const q = try reprToken(gpa, arg[e + 1 ..]); - defer gpa.free(q); - gpa.free(opt_seen); - gpa.free(opt_values); - own_state = false; - return try makeError(gpa, spec, "argument --version: ignored explicit argument {s}", .{q}); - } - if (spec.policy.special_action == .immediate_exit) { - gpa.free(opt_seen); - gpa.free(opt_values); - own_state = false; - return .{ .action_done = .{ .exit_code = 0, .stdout_text = spec.version.? } }; + if (spec.policy.flag_explicit_as_unknown) { + force_unknown = true; + } else { + if (spec.policy.unknown == .ignore) continue; + const val = arg[e + 1 ..]; + const q = try reprToken(gpa, val); + defer gpa.free(q); + gpa.free(opt_seen); + gpa.free(opt_values); + own_state = false; + return try makeError(gpa, spec, .{ .unexpected_value = .{ .option = "version", .value = val } }, "argument --version: ignored explicit argument {s}", .{q}); + } + } else { + if (spec.policy.special_action == .immediate_exit) { + gpa.free(opt_seen); + gpa.free(opt_values); + own_state = false; + return .{ .action_done = .{ .exit_code = 0, .stdout_text = spec.version.? } }; + } + version_requested = true; + continue; } - version_requested = true; - continue; }, .option => |k| { const o = spec.options[k]; if (o.kind == .flag) { if (eq) |e| { - if (spec.policy.unknown == .ignore) continue; + if (spec.policy.flag_explicit_as_unknown) { + force_unknown = true; + } else { + if (spec.policy.unknown == .ignore) continue; + const val = arg[e + 1 ..]; + const disp = try formatOptionDisplay(gpa, o); + defer gpa.free(disp); + const q = try reprToken(gpa, val); + defer gpa.free(q); + gpa.free(opt_seen); + gpa.free(opt_values); + own_state = false; + return try makeError(gpa, spec, .{ .unexpected_value = .{ .option = o.name, .value = val } }, "argument {s}: ignored explicit argument {s}", .{ disp, q }); + } + } else { + if (findMutexConflict(spec, opt_seen, k)) |conflict_idx| { + gpa.free(opt_seen); + gpa.free(opt_values); + own_state = false; + return try makeMutexError(gpa, spec, k, conflict_idx); + } + opt_seen[k] = true; + continue; + } + } else { + var val: []const u8 = undefined; + var supplied_val = true; + if (eq) |e| { + val = arg[e + 1 ..]; + } else if (i + 1 < argv.len and canConsumeNextValue(spec, argv[i + 1])) { + i += 1; + val = argv[i]; + } else if (o.kind == .optional_value) { + val = ""; + supplied_val = false; + } else { const disp = try formatOptionDisplay(gpa, o); defer gpa.free(disp); - const q = try reprToken(gpa, arg[e + 1 ..]); - defer gpa.free(q); gpa.free(opt_seen); gpa.free(opt_values); own_state = false; - return try makeError(gpa, spec, "argument {s}: ignored explicit argument {s}", .{ disp, q }); + return try makeError(gpa, spec, .{ .missing_value = o.name }, "argument {s}: expected one argument", .{disp}); + } + if (supplied_val) { + if (try checkOptionValueAllowed(gpa, spec, o, val)) |err_out| { + gpa.free(opt_seen); + gpa.free(opt_values); + own_state = false; + return err_out; + } + } + if (try validateOptionValue(gpa, spec, o, val)) |err_out| { + gpa.free(opt_seen); + gpa.free(opt_values); + own_state = false; + return err_out; + } + if (findMutexConflict(spec, opt_seen, k)) |conflict_idx| { + gpa.free(opt_seen); + gpa.free(opt_values); + own_state = false; + return try makeMutexError(gpa, spec, k, conflict_idx); } opt_seen[k] = true; + if (o.kind == .append) { + try opt_lists[k].append(gpa, val); + } else { + opt_values[k] = val; + } continue; } - opt_seen[k] = true; - var val: []const u8 = undefined; - if (eq) |e| { - val = arg[e + 1 ..]; - } else if (i + 1 < argv.len and !isOptionToken(spec, argv[i + 1])) { - i += 1; - val = argv[i]; - } else if (o.kind == .optional_value) { - val = ""; - } else { - const disp = try formatOptionDisplay(gpa, o); - defer gpa.free(disp); - gpa.free(opt_seen); - gpa.free(opt_values); - own_state = false; - return try makeError(gpa, spec, "argument {s}: expected one argument", .{disp}); - } - if (try validateOptionValue(gpa, spec, o, val)) |err_out| { - gpa.free(opt_seen); - gpa.free(opt_values); - own_state = false; - return err_out; - } - if (o.kind == .append) { - try opt_lists[k].append(gpa, val); - } else { - opt_values[k] = val; - } - continue; }, .none => {}, } } // 4. Non-option token: subcommand, remainder start, or positional. - if (!optionLike(arg, spec.policy.negative_numbers)) { + if (!force_unknown and !optionLike(arg, spec.policy.negative_numbers)) { if (has_subs) { sub_index = i; break; @@ -1122,6 +1492,15 @@ fn parseCommand( remainder = argv[i..]; break; } + if (arg.len == 0 and ignoresEmptyAt(spec, pos.items.len)) continue; + if (spec.policy.fail_fast and spec.policy.unknown != .ignore) { + if (max_fixed_pos) |max_p| if (pos.items.len >= max_p) { + gpa.free(opt_seen); + gpa.free(opt_values); + own_state = false; + return try makeUnrecognizedError(gpa, top_spec, arg, arg.len, true); + }; + } if (try validatePositionalChoice(gpa, spec, pos.items.len, arg)) |err_out| { gpa.free(opt_seen); gpa.free(opt_values); @@ -1134,6 +1513,31 @@ fn parseCommand( } // 5. Unrecognized option-like token. + if (spec.policy.unknown == .positional) { + if (spec.policy.fail_fast) { + if (max_fixed_pos) |max_p| if (pos.items.len >= max_p) { + gpa.free(opt_seen); + gpa.free(opt_values); + own_state = false; + return try makeUnrecognizedError(gpa, top_spec, arg, arg.len, true); + }; + } + if (try validatePositionalChoice(gpa, spec, pos.items.len, arg)) |err_out| { + gpa.free(opt_seen); + gpa.free(opt_values); + own_state = false; + return err_out; + } + try pos.append(gpa, arg); + try leftovers.append(gpa, .{ .token = arg, .is_positional = true, .argv_index = i }); + continue; + } + if (spec.policy.fail_fast and spec.policy.unknown == .collect) { + gpa.free(opt_seen); + gpa.free(opt_values); + own_state = false; + return try makeUnrecognizedError(gpa, top_spec, arg, arg.len, false); + } try leftovers.append(gpa, .{ .token = arg, .is_positional = false, .argv_index = i }); } @@ -1141,10 +1545,18 @@ fn parseCommand( if (has_subs) { const idx = sub_index orelse argv.len; if (idx >= argv.len) { + if (spec.policy.unknown_before_required and spec.policy.unknown != .ignore and leftovers.items.len > 0) { + if (try checkUnrecognized(gpa, top_spec, top_extra, leftovers.items, 0, true, false)) |err_out| { + gpa.free(opt_seen); + gpa.free(opt_values); + own_state = false; + return err_out; + } + } gpa.free(opt_seen); gpa.free(opt_values); own_state = false; - return try makeError(gpa, spec, "the following arguments are required: {s}", .{spec.subcommand_dest}); + return try makeError(gpa, spec, .missing_subcommand, "the following arguments are required: {s}", .{spec.subcommand_dest}); } const cmd_name = argv[idx]; var matched_sub: ?SubcommandSpec = null; @@ -1168,7 +1580,7 @@ fn parseCommand( gpa.free(opt_seen); gpa.free(opt_values); own_state = false; - return try makeError(gpa, spec, "argument {s}: invalid choice: {s} (choose from {s})", .{ spec.subcommand_dest, qcmd, choices_buf.items }); + return try makeError(gpa, spec, .{ .unknown_subcommand = cmd_name }, "argument {s}: invalid choice: {s} (choose from {s})", .{ spec.subcommand_dest, qcmd, choices_buf.items }); }; var top_unknowns: std.ArrayList([]const u8) = .empty; @@ -1200,21 +1612,39 @@ fn parseCommand( } } + // When unknown_before_required is enabled, report unknown options and excess + // positionals before missing required arguments. + if (spec.policy.unknown_before_required and spec.policy.unknown != .ignore) { + const variadic = hasVariadicPositional(spec); + const pos_slots = nonRemainderPositionals(spec); + const consumed_pos = if (variadic) pos.items.len else @min(pos.items.len, pos_slots); + const keep_sep = !variadic and pos_slots == 0 and !is_remainder; + if (try checkUnrecognized(gpa, top_spec, top_extra, leftovers.items, consumed_pos, keep_sep, variadic)) |err_out| { + gpa.free(opt_seen); + gpa.free(opt_values); + own_state = false; + return err_out; + } + } + // Check required options and required positionals (in registration order). var missing_names: std.ArrayList([]u8) = .empty; defer { for (missing_names.items) |m| gpa.free(m); missing_names.deinit(gpa); } + var first_missing: ?[]const u8 = null; for (spec.options, 0..) |o, idx| { if (o.required and !o.has_default and !opt_seen[idx]) { + if (first_missing == null) first_missing = o.name; try missing_names.append(gpa, try formatOptionDisplay(gpa, o)); } } var req_pos_count: usize = 0; for (spec.positionals) |p| { - if (p.arity == .required_one) { + if (p.arity == .required_one or p.arity == .one_or_more) { if (pos.items.len <= req_pos_count) { + if (first_missing == null) first_missing = p.name; try missing_names.append(gpa, try gpa.dupe(u8, p.name)); } req_pos_count += 1; @@ -1230,15 +1660,17 @@ fn parseCommand( gpa.free(opt_seen); gpa.free(opt_values); own_state = false; - return try makeError(gpa, spec, "the following arguments are required: {s}", .{joined.items}); + return try makeError(gpa, spec, .{ .missing_required = first_missing.? }, "the following arguments are required: {s}", .{joined.items}); } - // Check merged unrecognized arguments unless unknown tokens are ignored. - if (spec.policy.unknown == .collect) { + // Check merged unrecognized arguments unless unknown tokens are ignored + // (or already checked above). + if (!spec.policy.unknown_before_required and spec.policy.unknown != .ignore) { + const variadic = hasVariadicPositional(spec); const pos_slots = nonRemainderPositionals(spec); - const consumed_pos = @min(pos.items.len, pos_slots); - const keep_sep = pos_slots == 0 and !is_remainder; - if (try checkUnrecognized(gpa, top_spec, top_extra, leftovers.items, consumed_pos, keep_sep)) |err_out| { + const consumed_pos = if (variadic) pos.items.len else @min(pos.items.len, pos_slots); + const keep_sep = !variadic and pos_slots == 0 and !is_remainder; + if (try checkUnrecognized(gpa, top_spec, top_extra, leftovers.items, consumed_pos, keep_sep, variadic)) |err_out| { gpa.free(opt_seen); gpa.free(opt_values); own_state = false; diff --git a/src/argparse_test.zig b/src/argparse_test.zig index adeeade..2a0bab2 100644 --- a/src/argparse_test.zig +++ b/src/argparse_test.zig @@ -493,3 +493,479 @@ test "differential regressions: registered short option with spaces and non-adja try std.testing.expectEqualStrings("unrecognized arguments: -- --", out.usage_error.message); } } + +test "variadic positional arities zero_or_more and one_or_more" { + const gpa = std.testing.allocator; + + const star_spec: argparse.CommandSpec = .{ + .prog = "star", + .usage = "usage: star [--json] [files ...]\n", + .help = "usage: star\n", + .options = &.{.{ .name = "json", .kind = .flag }}, + .positionals = &.{.{ .name = "files", .arity = .zero_or_more }}, + }; + const plus_spec: argparse.CommandSpec = .{ + .prog = "plus", + .usage = "usage: plus [--json] first rest...\n", + .help = "usage: plus\n", + .options = &.{.{ .name = "json", .kind = .flag }}, + .positionals = &.{ + .{ .name = "first", .arity = .required_one }, + .{ .name = "rest", .arity = .one_or_more, .choices = &.{ "a", "b", "c" } }, + }, + }; + + // zero_or_more accepts zero, one, or many intermixed with flags and -- + { + var out = try argparse.parse(gpa, &star_spec, &.{}); + defer out.deinit(gpa); + try std.testing.expectEqual(@as(usize, 0), out.ok.positionals.len); + } + { + var out = try argparse.parse(gpa, &star_spec, &.{ "f1", "--json", "f2", "--", "--flag" }); + defer out.deinit(gpa); + try std.testing.expect(out.ok.seen("json")); + try std.testing.expectEqual(@as(usize, 3), out.ok.positionals.len); + try std.testing.expectEqualStrings("f1", out.ok.positionals[0]); + try std.testing.expectEqualStrings("f2", out.ok.positionals[1]); + try std.testing.expectEqualStrings("--flag", out.ok.positionals[2]); + } + { + var out = try argparse.parse(gpa, &star_spec, &.{ "f1", "--json", "--" }); + defer out.deinit(gpa); + try std.testing.expect(out.ok.seen("json")); + try std.testing.expectEqual(@as(usize, 1), out.ok.positionals.len); + try std.testing.expectEqualStrings("f1", out.ok.positionals[0]); + } + + // required_one + one_or_more requires at least two positionals and validates choices on all variadic slots + { + var out = try argparse.parse(gpa, &plus_spec, &.{}); + defer out.deinit(gpa); + try std.testing.expectEqualStrings("the following arguments are required: first, rest", out.usage_error.message); + } + { + var out = try argparse.parse(gpa, &plus_spec, &.{"x"}); + defer out.deinit(gpa); + try std.testing.expectEqualStrings("the following arguments are required: rest", out.usage_error.message); + } + { + var out = try argparse.parse(gpa, &plus_spec, &.{ "x", "a", "--json", "c" }); + defer out.deinit(gpa); + try std.testing.expect(out.ok.seen("json")); + try std.testing.expectEqual(@as(usize, 3), out.ok.positionals.len); + try std.testing.expectEqualStrings("x", out.ok.positionals[0]); + try std.testing.expectEqualStrings("a", out.ok.positionals[1]); + try std.testing.expectEqualStrings("c", out.ok.positionals[2]); + } + { + var out = try argparse.parse(gpa, &plus_spec, &.{ "x", "a", "bad" }); + defer out.deinit(gpa); + try std.testing.expectEqualStrings("argument rest: invalid choice: 'bad' (choose from 'a', 'b', 'c')", out.usage_error.message); + } +} + +test "UnknownMode.positional routes unknown dash tokens to positionals and rejects overflow" { + const gpa = std.testing.allocator; + + const failed_spec: argparse.CommandSpec = .{ + .prog = "tool failed", + .usage = "usage: tool failed [--syslog TARGET] STATUS NAME LOGDIR [TMP]\n", + .help = "usage: tool failed\n", + .add_help = false, + .policy = .{ + .allow_abbrev = false, + .unknown = .positional, + .double_dash = .ignore, + .negative_numbers = .never, + .short_clusters = false, + }, + .options = &.{ + .{ .name = "syslog", .kind = .value }, + }, + .positionals = &.{ + .{ .name = "STATUS", .arity = .required_one }, + .{ .name = "NAME", .arity = .required_one }, + .{ .name = "LOGDIR", .arity = .required_one }, + .{ .name = "TMP", .arity = .optional_one }, + }, + }; + + // Unknown dash tokens like -1 and --bogus become positionals. + { + var out = try argparse.parse(gpa, &failed_spec, &.{ "-1", "Foo", "--bogus", "--syslog", "udp://127.0.0.1:514" }); + defer out.deinit(gpa); + try std.testing.expectEqualStrings("udp://127.0.0.1:514", out.ok.value("syslog").?); + try std.testing.expectEqual(@as(usize, 3), out.ok.positionals.len); + try std.testing.expectEqualStrings("-1", out.ok.positionals[0]); + try std.testing.expectEqualStrings("Foo", out.ok.positionals[1]); + try std.testing.expectEqualStrings("--bogus", out.ok.positionals[2]); + } + // Positionals beyond the four declared slots are still rejected. + { + var out = try argparse.parse(gpa, &failed_spec, &.{ "1", "Foo", "dir", "tmp", "--extra" }); + defer out.deinit(gpa); + try std.testing.expectEqualStrings("unrecognized arguments: --extra", out.usage_error.message); + } +} + +test "argparse: PositionalSpec.ignore_empty skips empty tokens only while slot is unfilled" { + const gpa = std.testing.allocator; + const spec: argparse.CommandSpec = .{ + .prog = "tool", + .usage = "usage: tool FILE\n", + .help = "usage: tool FILE\n", + .add_help = false, + .positionals = &.{ + .{ .name = "FILE", .arity = .required_one, .ignore_empty = true }, + }, + }; + { + var out = try argparse.parse(gpa, &spec, &.{ "", "a.log" }); + defer out.deinit(gpa); + try std.testing.expectEqualStrings("a.log", out.ok.positional(0).?); + } + { + var out = try argparse.parse(gpa, &spec, &.{""}); + defer out.deinit(gpa); + try std.testing.expectEqualStrings("the following arguments are required: FILE", out.usage_error.message); + } + { + var out = try argparse.parse(gpa, &spec, &.{ "a.log", "" }); + defer out.deinit(gpa); + try std.testing.expectEqualStrings("unrecognized arguments: ", out.usage_error.message); + } +} + +test "Policy.native_exact, NegativeNumberMode.any, and allow_empty/allow_dash_value" { + const gpa = std.testing.allocator; + + try std.testing.expect(argparse.optionLike("-", .any)); + try std.testing.expect(argparse.optionLike("-5", .any)); + try std.testing.expect(!argparse.optionLike("5", .any)); + + const rotate_spec: argparse.CommandSpec = .{ + .prog = "tool rotate", + .usage = "usage: tool rotate\n", + .help = "usage: tool rotate\n", + .add_help = false, + .policy = .native_exact, + .options = &.{ + .{ .name = "dry-run", .kind = .flag }, + .{ .name = "compress-after", .kind = .value }, + .{ .name = "target", .kind = .value, .allow_empty = false }, + .{ .name = "module", .kind = .value, .allow_empty = false, .allow_dash_value = false }, + }, + .positionals = &.{.{ .name = "ROOT", .arity = .required_one }}, + }; + + // NegativeNumberMode.any consumes any next token for value options (even -5 or --foo) + // and allow_empty=true allows empty --compress-after=. + { + var out = try argparse.parse(gpa, &rotate_spec, &.{ "--compress-after", "-5", "--target", "-x", "logs" }); + defer out.deinit(gpa); + try std.testing.expectEqualStrings("-5", out.ok.value("compress-after").?); + try std.testing.expectEqualStrings("-x", out.ok.value("target").?); + try std.testing.expectEqualStrings("logs", out.ok.positional(0).?); + } + { + var out = try argparse.parse(gpa, &rotate_spec, &.{ "--compress-after=", "logs" }); + defer out.deinit(gpa); + try std.testing.expectEqualStrings("", out.ok.value("compress-after").?); + } + + // allow_empty=false rejects --target= and --target "" as missing value. + { + var out = try argparse.parse(gpa, &rotate_spec, &.{ "--target=", "logs" }); + defer out.deinit(gpa); + try std.testing.expectEqualStrings("argument --target: expected one argument", out.usage_error.message); + } + { + var out = try argparse.parse(gpa, &rotate_spec, &.{ "--target", "", "logs" }); + defer out.deinit(gpa); + try std.testing.expectEqualStrings("argument --target: expected one argument", out.usage_error.message); + } + + // allow_dash_value=false rejects both --module -x and --module=-x as missing value. + { + var out = try argparse.parse(gpa, &rotate_spec, &.{ "--module", "-x", "logs" }); + defer out.deinit(gpa); + try std.testing.expectEqualStrings("argument --module: expected one argument", out.usage_error.message); + } + { + var out = try argparse.parse(gpa, &rotate_spec, &.{ "--module=-x", "logs" }); + defer out.deinit(gpa); + try std.testing.expectEqualStrings("argument --module: expected one argument", out.usage_error.message); + } + + // flag_explicit_as_unknown treats --dry-run=1 (even with spaces) as unknown option, + // and fail_fast / unknown_before_required report it before later errors or missing ROOT. + { + var out = try argparse.parse(gpa, &rotate_spec, &.{"--dry-run=1"}); + defer out.deinit(gpa); + try std.testing.expectEqualStrings("unrecognized arguments: --dry-run=1", out.usage_error.message); + } + { + var out = try argparse.parse(gpa, &rotate_spec, &.{"--dry-run=a b"}); + defer out.deinit(gpa); + try std.testing.expectEqualStrings("unrecognized arguments: --dry-run=a b", out.usage_error.message); + } + { + var out = try argparse.parse(gpa, &rotate_spec, &.{ "--bogus", "--target" }); + defer out.deinit(gpa); + try std.testing.expectEqualStrings("unrecognized arguments: --bogus", out.usage_error.message); + } + { + var out = try argparse.parse(gpa, &rotate_spec, &.{ "logs", "extra", "--target" }); + defer out.deinit(gpa); + try std.testing.expectEqualStrings("unrecognized arguments: extra", out.usage_error.message); + } + // Missing required ROOT is reported when no unknown tokens are present. + { + var out = try argparse.parse(gpa, &rotate_spec, &.{"--dry-run"}); + defer out.deinit(gpa); + try std.testing.expectEqualStrings("the following arguments are required: ROOT", out.usage_error.message); + } + // With fail_fast and immediate_exit, --bogus fails before --help; with prescan, --help wins. + const help_native: argparse.CommandSpec = .{ + .prog = "tool why", + .usage = "usage: tool why\n", + .help = "why help\n", + .version = "1.0\n", + .policy = .native_exact, + .positionals = &.{.{ .name = "RUN", .arity = .required_one }}, + }; + { + var out = try argparse.parse(gpa, &help_native, &.{ "--bogus", "--help" }); + defer out.deinit(gpa); + try std.testing.expectEqualStrings("unrecognized arguments: --bogus", out.usage_error.message); + } + { + var out = try argparse.parse(gpa, &help_native, &.{"--help=1"}); + defer out.deinit(gpa); + try std.testing.expectEqualStrings("unrecognized arguments: --help=1", out.usage_error.message); + } + { + var out = try argparse.parse(gpa, &help_native, &.{"--version=1"}); + defer out.deinit(gpa); + try std.testing.expectEqualStrings("unrecognized arguments: --version=1", out.usage_error.message); + } +} + +test "argparse: SpecialActionMode.prescan handles help and version before option errors" { + const gpa = std.testing.allocator; + var prescan_pol = argparse.Policy.native_exact; + prescan_pol.special_action = .prescan; + const spec: argparse.CommandSpec = .{ + .prog = "tool why", + .usage = "usage: tool why\n", + .help = "why help\n", + .version = "1.2.3\n", + .policy = prescan_pol, + .options = &.{.{ .name = "target", .kind = .value }}, + .positionals = &.{.{ .name = "RUN", .arity = .required_one }}, + }; + { + var out = try argparse.parse(gpa, &spec, &.{ "--bogus", "-h" }); + defer out.deinit(gpa); + try std.testing.expectEqualStrings("why help\n", out.action_done.stdout_text); + } + { + var out = try argparse.parse(gpa, &spec, &.{ "--target", "--help" }); + defer out.deinit(gpa); + try std.testing.expectEqualStrings("why help\n", out.action_done.stdout_text); + } + { + var out = try argparse.parse(gpa, &spec, &.{ "--bogus", "--version" }); + defer out.deinit(gpa); + try std.testing.expectEqualStrings("1.2.3\n", out.action_done.stdout_text); + } +} + +test "argparse: mutually_exclusive rejects conflicting options in scan order" { + const gpa = std.testing.allocator; + const spec: argparse.CommandSpec = .{ + .prog = "tool usage", + .usage = "usage: tool usage\n", + .help = "usage help\n", + .add_help = false, + .policy = .native_exact, + .options = &.{ + .{ .name = "unused", .kind = .flag }, + .{ .name = "active", .kind = .flag }, + .{ .name = "json", .kind = .flag }, + }, + .mutually_exclusive = &.{.{ .options = &.{ "unused", "active" } }}, + .positionals = &.{.{ .name = "FILE", .arity = .one_or_more }}, + }; + { + var out = try argparse.parse(gpa, &spec, &.{ "--unused", "--active", "--bogus" }); + defer out.deinit(gpa); + try std.testing.expectEqualStrings("argument --active: not allowed with argument --unused", out.usage_error.message); + } + { + var out = try argparse.parse(gpa, &spec, &.{ "--active", "--unused", "a.log" }); + defer out.deinit(gpa); + try std.testing.expectEqualStrings("argument --unused: not allowed with argument --active", out.usage_error.message); + } + { + var out = try argparse.parse(gpa, &spec, &.{ "--bogus", "--unused", "--active" }); + defer out.deinit(gpa); + try std.testing.expectEqualStrings("unrecognized arguments: --bogus", out.usage_error.message); + } + { + var out = try argparse.parse(gpa, &spec, &.{ "--unused", "--json", "a.log" }); + defer out.deinit(gpa); + try std.testing.expect(out.ok.seen("unused")); + try std.testing.expect(!out.ok.seen("active")); + try std.testing.expect(out.ok.seen("json")); + } +} + +test "UsageError.kind classifies all ten error kinds without leaks" { + const gpa = std.testing.allocator; + + // 1. missing_subcommand + { + var out = try argparse.parse(gpa, &top_spec, &.{}); + defer out.deinit(gpa); + try std.testing.expect(out.usage_error.kind == .missing_subcommand); + } + // 2. unknown_subcommand + { + var out = try argparse.parse(gpa, &top_spec, &.{"bogus"}); + defer out.deinit(gpa); + try std.testing.expectEqualStrings("bogus", out.usage_error.kind.unknown_subcommand); + } + // 3. unknown_option (including synthetic short-cluster tail "-zb") + { + var out = try argparse.parse(gpa, &short_spec, &.{"-azb"}); + defer out.deinit(gpa); + try std.testing.expectEqualStrings("-zb", out.usage_error.kind.unknown_option); + } + // 4. extra_positional (ordered before any later unknown option) + { + var out = try argparse.parse(gpa, &top_spec, &.{ "resolve", "a", "b", "--bogus" }); + defer out.deinit(gpa); + try std.testing.expectEqualStrings("b", out.usage_error.kind.extra_positional); + } + // 5. missing_value (missing trailing arg) + { + var out = try argparse.parse(gpa, &top_spec, &.{ "probe", "--path" }); + defer out.deinit(gpa); + try std.testing.expectEqualStrings("path", out.usage_error.kind.missing_value); + } + // 6. unexpected_value (long flag and short cluster) + { + var out = try argparse.parse(gpa, &top_spec, &.{ "probe", "--json=1" }); + defer out.deinit(gpa); + try std.testing.expectEqualStrings("json", out.usage_error.kind.unexpected_value.option); + try std.testing.expectEqualStrings("1", out.usage_error.kind.unexpected_value.value); + } + { + var out = try argparse.parse(gpa, &short_spec, &.{"-ab=yes"}); + defer out.deinit(gpa); + try std.testing.expectEqualStrings("beta", out.usage_error.kind.unexpected_value.option); + try std.testing.expectEqualStrings("yes", out.usage_error.kind.unexpected_value.value); + } + // 7. ambiguous_option + { + var out = try argparse.parse(gpa, &top_spec, &.{"--=foo"}); + defer out.deinit(gpa); + try std.testing.expectEqualStrings("--=foo", out.usage_error.kind.ambiguous_option); + } + // 8. missing_required (option and positional) + { + var out = try argparse.parse(gpa, &top_spec, &.{"status"}); + defer out.deinit(gpa); + try std.testing.expectEqualStrings("state-root", out.usage_error.kind.missing_required); + } + { + var out = try argparse.parse(gpa, &top_spec, &.{"resolve"}); + defer out.deinit(gpa); + try std.testing.expectEqualStrings("module", out.usage_error.kind.missing_required); + } + // 9. invalid_value (option validator and positional choices) + { + var out = try argparse.parse(gpa, &validated_spec, &.{ "--lock-timeout", "bad" }); + defer out.deinit(gpa); + try std.testing.expectEqualStrings("lock-timeout", out.usage_error.kind.invalid_value.name); + try std.testing.expectEqualStrings("bad", out.usage_error.kind.invalid_value.value); + } + { + var out = try argparse.parse(gpa, &validated_spec, &.{"badmode"}); + defer out.deinit(gpa); + try std.testing.expectEqualStrings("mode", out.usage_error.kind.invalid_value.name); + try std.testing.expectEqualStrings("badmode", out.usage_error.kind.invalid_value.value); + } + // 10. mutually_exclusive + const mutex_spec: argparse.CommandSpec = .{ + .prog = "tool usage", + .usage = "usage: tool usage\n", + .help = "usage: tool usage\n", + .add_help = false, + .policy = .native_exact, + .options = &.{ + .{ .name = "unused", .kind = .flag }, + .{ .name = "active", .kind = .flag }, + }, + .mutually_exclusive = &.{.{ .options = &.{ "unused", "active" } }}, + }; + { + var out = try argparse.parse(gpa, &mutex_spec, &.{ "--unused", "--active" }); + defer out.deinit(gpa); + try std.testing.expectEqualStrings("active", out.usage_error.kind.mutually_exclusive.option); + try std.testing.expectEqualStrings("unused", out.usage_error.kind.mutually_exclusive.conflict); + } + // Top-level unknown option under native_exact reports unknown_option instead of missing_subcommand. + const native_top: argparse.CommandSpec = .{ + .prog = "tool", + .usage = "usage: tool\n", + .help = "usage: tool\n", + .policy = .native_exact, + .subcommands = &.{.{ .name = "probe", .command = &probe_spec }}, + }; + { + var out = try argparse.parse(gpa, &native_top, &.{"--bogus"}); + defer out.deinit(gpa); + try std.testing.expectEqualStrings("--bogus", out.usage_error.kind.unknown_option); + } + { + var out = try argparse.parse(gpa, &native_top, &.{}); + defer out.deinit(gpa); + try std.testing.expect(out.usage_error.kind == .missing_subcommand); + } +} + +test "UsageError.deinit and freeing message directly do not leak under std.testing.allocator" { + const gpa = std.testing.allocator; + + // Synthetic short-cluster tail freed via UsageError.deinit. + { + const out = try argparse.parse(gpa, &short_spec, &.{"-azb"}); + var uerr = out.usage_error; + try std.testing.expectEqualStrings("-zb", uerr.kind.unknown_option); + uerr.deinit(gpa); + } + // Synthetic short-cluster tail freed via fail_fast + UsageError.deinit. + var ff_short = short_spec; + ff_short.policy.fail_fast = true; + { + const out = try argparse.parse(gpa, &ff_short, &.{"-azb"}); + var uerr = out.usage_error; + try std.testing.expectEqualStrings("-zb", uerr.kind.unknown_option); + uerr.deinit(gpa); + } + // Caller freeing only UsageError.message still leaks nothing because token slices + // alias message rather than a separate heap buffer. + { + const out = try argparse.parse(gpa, &short_spec, &.{"-azb"}); + try std.testing.expectEqualStrings("-zb", out.usage_error.kind.unknown_option); + gpa.free(out.usage_error.message); + } + { + const out = try argparse.parse(gpa, &ff_short, &.{"-azb"}); + try std.testing.expectEqualStrings("-zb", out.usage_error.kind.unknown_option); + gpa.free(out.usage_error.message); + } +} diff --git a/tests/argparse_parity_probe.zig b/tests/argparse_parity_probe.zig index 0e73f79..acbbcff 100644 --- a/tests/argparse_parity_probe.zig +++ b/tests/argparse_parity_probe.zig @@ -179,6 +179,148 @@ const prolog_spec: argparse.CommandSpec = .{ }, }; +const intermixed_spec: argparse.CommandSpec = .{ + .prog = "imix", + .usage = "usage: imix [-h] [--json] [--prefix PREFIX] first files [files ...]\n", + .help = + \\usage: imix [-h] [--json] [--prefix PREFIX] first files [files ...] + \\ + \\positional arguments: + \\ first + \\ files + \\ + \\options: + \\ -h, --help show this help message and exit + \\ --json + \\ --prefix PREFIX + \\ + , + .options = &.{ + .{ .name = "json", .kind = .flag }, + .{ .name = "prefix", .kind = .value }, + }, + .positionals = &.{ + .{ .name = "first", .arity = .required_one }, + .{ .name = "files", .arity = .one_or_more }, + }, +}; + +const native_rotate_spec: argparse.CommandSpec = .{ + .prog = "native rotate", + .usage = "usage: native rotate\n", + .help = "usage: native rotate\n", + .add_help = false, + .policy = .native_exact, + .options = &.{ + .{ .name = "dry-run", .kind = .flag }, + .{ .name = "compress-after", .kind = .value }, + .{ .name = "target", .kind = .value, .allow_empty = false }, + .{ .name = "module", .kind = .value, .allow_empty = false, .allow_dash_value = false }, + }, + .positionals = &.{ + .{ .name = "ROOT", .arity = .required_one }, + }, +}; + +const native_failed_spec: argparse.CommandSpec = .{ + .prog = "native failed", + .usage = "usage: native failed\n", + .help = "usage: native failed\n", + .add_help = false, + .policy = .{ + .allow_abbrev = false, + .unknown = .positional, + .double_dash = .ignore, + .negative_numbers = .any, + .short_clusters = false, + .special_action = .immediate_exit, + .flag_explicit_as_unknown = true, + .unknown_before_required = true, + .fail_fast = true, + }, + .options = &.{ + .{ .name = "syslog", .kind = .value }, + }, + .positionals = &.{ + .{ .name = "STATUS", .arity = .required_one }, + .{ .name = "NAME", .arity = .required_one }, + .{ .name = "LOGDIR", .arity = .required_one }, + .{ .name = "TMP", .arity = .optional_one }, + }, +}; + +const native_used_spec: argparse.CommandSpec = .{ + .prog = "native used", + .usage = "usage: native used\n", + .help = "usage: native used\n", + .add_help = false, + .policy = .native_exact, + .options = &.{ + .{ .name = "json", .kind = .flag }, + .{ .name = "prefix", .kind = .value, .required = true, .allow_empty = false, .allow_dash_value = false }, + }, + .positionals = &.{ + .{ .name = "FILE", .arity = .one_or_more }, + }, +}; + +const native_prescan_spec: argparse.CommandSpec = .{ + .prog = "native prescan", + .usage = "usage: native prescan\n", + .help = "prescan help\n", + .version = "prescan 1.0\n", + .add_help = true, + .policy = .{ + .allow_abbrev = false, + .unknown = .collect, + .double_dash = .ignore, + .negative_numbers = .any, + .short_clusters = false, + .special_action = .prescan, + .flag_explicit_as_unknown = true, + .unknown_before_required = true, + .fail_fast = true, + }, + .options = &.{ + .{ .name = "format", .kind = .value, .allow_empty = false }, + }, + .positionals = &.{ + .{ .name = "RUN", .arity = .required_one, .ignore_empty = true }, + }, +}; + +const native_mutex_spec: argparse.CommandSpec = .{ + .prog = "native mutex", + .usage = "usage: native mutex\n", + .help = "usage: native mutex\n", + .add_help = false, + .policy = .native_exact, + .options = &.{ + .{ .name = "unused", .kind = .flag }, + .{ .name = "active", .kind = .flag }, + .{ .name = "json", .kind = .flag }, + }, + .mutually_exclusive = &.{.{ .options = &.{ "unused", "active" } }}, + .positionals = &.{ + .{ .name = "FILE", .arity = .one_or_more }, + }, +}; + +const native_spec: argparse.CommandSpec = .{ + .prog = "native", + .usage = "usage: native\n", + .help = "native help\n", + .version = "native 1.0\n", + .policy = .native_exact, + .subcommands = &.{ + .{ .name = "rotate", .command = &native_rotate_spec }, + .{ .name = "failed", .command = &native_failed_spec }, + .{ .name = "used", .command = &native_used_spec }, + .{ .name = "prescan", .command = &native_prescan_spec }, + .{ .name = "mutex", .command = &native_mutex_spec }, + }, +}; + fn appendHex(out: *std.ArrayList(u8), gpa: std.mem.Allocator, bytes: []const u8) !void { const digits = "0123456789abcdef"; try out.append(gpa, '"'); @@ -278,6 +420,95 @@ fn formatParsedProlog(out: *std.ArrayList(u8), gpa: std.mem.Allocator, p: *const try out.appendSlice(gpa, "}\n"); } +fn formatParsedIntermixed(out: *std.ArrayList(u8), gpa: std.mem.Allocator, p: *const argparse.Parsed) !void { + try out.print(gpa, "{{\"kind\":\"ok\",\"json\":{s},\"prefix\":", .{if (p.seen("json")) "true" else "false"}); + try appendOptHex(out, gpa, p.value("prefix")); + try out.appendSlice(gpa, ",\"first\":"); + try appendOptHex(out, gpa, p.positional(0)); + try out.appendSlice(gpa, ",\"files\":"); + const rest: []const []const u8 = if (p.positionals.len > 1) p.positionals[1..] else &.{}; + try appendHexList(out, gpa, rest); + try out.appendSlice(gpa, "}\n"); +} + +fn formatParsedNative(out: *std.ArrayList(u8), gpa: std.mem.Allocator, p: *const argparse.Parsed) !void { + const sub_name = p.subcommand_name orelse ""; + const sub = p.subcommand().?; + try out.print(gpa, "{{\"kind\":\"ok\",\"command\":\"{s}\"", .{sub_name}); + if (std.mem.eql(u8, sub_name, "rotate")) { + try out.print(gpa, ",\"dry_run\":{s},\"compress_after\":", .{if (sub.seen("dry-run")) "true" else "false"}); + try appendOptHex(out, gpa, sub.value("compress-after")); + try out.appendSlice(gpa, ",\"target\":"); + try appendOptHex(out, gpa, sub.value("target")); + try out.appendSlice(gpa, ",\"module\":"); + try appendOptHex(out, gpa, sub.value("module")); + try out.appendSlice(gpa, ",\"root\":"); + try appendOptHex(out, gpa, sub.positional(0)); + } else if (std.mem.eql(u8, sub_name, "failed")) { + try out.appendSlice(gpa, ",\"syslog\":"); + try appendOptHex(out, gpa, sub.value("syslog")); + try out.appendSlice(gpa, ",\"pos\":"); + try appendHexList(out, gpa, sub.positionals); + } else if (std.mem.eql(u8, sub_name, "used")) { + try out.print(gpa, ",\"json\":{s},\"prefix\":", .{if (sub.seen("json")) "true" else "false"}); + try appendOptHex(out, gpa, sub.value("prefix")); + try out.appendSlice(gpa, ",\"files\":"); + try appendHexList(out, gpa, sub.positionals); + } else if (std.mem.eql(u8, sub_name, "prescan")) { + try out.appendSlice(gpa, ",\"format\":"); + try appendOptHex(out, gpa, sub.value("format")); + try out.appendSlice(gpa, ",\"run\":"); + try appendOptHex(out, gpa, sub.positional(0)); + } else if (std.mem.eql(u8, sub_name, "mutex")) { + try out.print(gpa, ",\"unused\":{s},\"active\":{s},\"json\":{s},\"files\":", .{ + if (sub.seen("unused")) "true" else "false", + if (sub.seen("active")) "true" else "false", + if (sub.seen("json")) "true" else "false", + }); + try appendHexList(out, gpa, sub.positionals); + } + try out.appendSlice(gpa, "}\n"); +} + +fn formatNativeError(out: *std.ArrayList(u8), gpa: std.mem.Allocator, uerr: *const argparse.UsageError) !void { + try out.print(gpa, "{{\"kind\":\"usage_error\",\"exit_code\":{d},\"err_kind\":\"{s}\"", .{ + uerr.exit_code, + @tagName(uerr.kind), + }); + switch (uerr.kind) { + .missing_subcommand => {}, + .unknown_subcommand, + .unknown_option, + .extra_positional, + .missing_value, + .ambiguous_option, + .missing_required, + => |tok| { + try out.appendSlice(gpa, ",\"token\":"); + try appendHex(out, gpa, tok); + }, + .unexpected_value => |uv| { + try out.appendSlice(gpa, ",\"option\":"); + try appendHex(out, gpa, uv.option); + try out.appendSlice(gpa, ",\"value\":"); + try appendHex(out, gpa, uv.value); + }, + .invalid_value => |iv| { + try out.appendSlice(gpa, ",\"name\":"); + try appendHex(out, gpa, iv.name); + try out.appendSlice(gpa, ",\"value\":"); + try appendHex(out, gpa, iv.value); + }, + .mutually_exclusive => |me| { + try out.appendSlice(gpa, ",\"option\":"); + try appendHex(out, gpa, me.option); + try out.appendSlice(gpa, ",\"conflict\":"); + try appendHex(out, gpa, me.conflict); + }, + } + try out.appendSlice(gpa, "}\n"); +} + fn readAllStdin(gpa: std.mem.Allocator) ![]u8 { var data: std.ArrayList(u8) = .empty; errdefer data.deinit(gpa); @@ -340,7 +571,16 @@ pub fn main(init: std.process.Init) !void { } const is_prolog = std.mem.eql(u8, mode, "prolog"); - const spec = if (is_prolog) &prolog_spec else &py314_spec; + const is_intermixed = std.mem.eql(u8, mode, "intermixed"); + const is_native = std.mem.eql(u8, mode, "native"); + const spec = if (is_prolog) + &prolog_spec + else if (is_intermixed) + &intermixed_spec + else if (is_native) + &native_spec + else + &py314_spec; var outcome = try argparse.parse(gpa, spec, argv.items); defer outcome.deinit(gpa); @@ -348,6 +588,10 @@ pub fn main(init: std.process.Init) !void { .ok => |*p| { if (is_prolog) { try formatParsedProlog(&out, gpa, p); + } else if (is_intermixed) { + try formatParsedIntermixed(&out, gpa, p); + } else if (is_native) { + try formatParsedNative(&out, gpa, p); } else { try formatParsedPy314(&out, gpa, p); } @@ -358,11 +602,15 @@ pub fn main(init: std.process.Init) !void { try out.appendSlice(gpa, "}\n"); }, .usage_error => |*uerr| { - const stderr_txt = try uerr.formatStderr(gpa); - defer gpa.free(stderr_txt); - try out.print(gpa, "{{\"kind\":\"usage_error\",\"exit_code\":{d},\"stderr\":", .{uerr.exit_code}); - try appendHex(&out, gpa, stderr_txt); - try out.appendSlice(gpa, "}\n"); + if (is_native) { + try formatNativeError(&out, gpa, uerr); + } else { + const stderr_txt = try uerr.formatStderr(gpa); + defer gpa.free(stderr_txt); + try out.print(gpa, "{{\"kind\":\"usage_error\",\"exit_code\":{d},\"stderr\":", .{uerr.exit_code}); + try appendHex(&out, gpa, stderr_txt); + try out.appendSlice(gpa, "}\n"); + } }, } } diff --git a/tests/test_argparse_parity.py b/tests/test_argparse_parity.py index 6cddae9..e5e3592 100644 --- a/tests/test_argparse_parity.py +++ b/tests/test_argparse_parity.py @@ -559,6 +559,365 @@ def generate_prolog_cases(rng, count=500): return cases +def run_python_intermixed(argv_bytes): + argv_str = [a.decode("utf-8", "surrogateescape") for a in argv_bytes] + kwargs = {"prog": "imix"} + if IS_PY314: + kwargs["color"] = False + p = argparse.ArgumentParser(**kwargs) + p.add_argument("--json", action="store_true") + p.add_argument("--prefix") + p.add_argument("first") + p.add_argument("files", nargs="+") + + out_buf = io.StringIO() + err_buf = io.StringIO() + with contextlib.redirect_stdout(out_buf), contextlib.redirect_stderr(err_buf): + try: + ns = p.parse_intermixed_args(argv_str) + except SystemExit as exc: + code = exc.code if isinstance(exc.code, int) else 1 + if code == 0: + return {"kind": "action_done", "exit_code": 0, "stdout": bhex(out_buf.getvalue())} + return {"kind": "usage_error", "exit_code": code, "stderr": bhex(err_buf.getvalue())} + + return { + "kind": "ok", + "json": bool(ns.json), + "prefix": bhex(ns.prefix), + "first": bhex(ns.first), + "files": [bhex(x) for x in ns.files], + } + + +def generate_intermixed_cases(rng, count=400): + tokens = [ + b"-h", + b"--help", + b"--json", + b"--json=1", + b"--prefix", + b"--prefix=/opt", + b"--prefix=", + b"--", + b"--bogus", + b"-1", + b"f1", + b"f2", + b"f3", + ] + cases = [ + [], + [b"a"], + [b"a", b"b"], + [b"a", b"--json", b"b", b"--prefix", b"/p", b"c"], + [b"a", b"--json", b"--", b"--bogus", b"-h"], + [b"--json", b"--", b"a", b"b"], + [b"a", b"b", b"--json", b"--"], + ] + while len(cases) < count: + n = rng.randrange(0, 8) + cases.append([rng.choice(tokens) for _ in range(n)]) + return cases + + +def run_python_native(argv_bytes): + """Reference parser matching Policy.native_exact, UnknownMode.positional, prescan, ignore_empty, mutex, and ErrorKind.""" + sub_idx = None + for i, a in enumerate(argv_bytes): + if a in (b"-h", b"--help"): + return {"kind": "action_done", "exit_code": 0, "stdout": bhex(b"native help\n")} + if a == b"--version": + return {"kind": "action_done", "exit_code": 0, "stdout": bhex(b"native 1.0\n")} + if a.startswith(b"-"): + return {"kind": "usage_error", "exit_code": 2, "err_kind": "unknown_option", "token": bhex(a)} + sub_idx = i + break + + if sub_idx is None: + return {"kind": "usage_error", "exit_code": 2, "err_kind": "missing_subcommand"} + + cmd = argv_bytes[sub_idx] + rest = argv_bytes[sub_idx + 1 :] + if cmd not in (b"rotate", b"failed", b"used", b"prescan", b"mutex"): + return {"kind": "usage_error", "exit_code": 2, "err_kind": "unknown_subcommand", "token": bhex(cmd)} + + def parse_val(args, idx, name, allow_empty=True, allow_dash=True): + a = args[idx] + prefix = b"--" + name + b"=" + if a.startswith(prefix): + val = a[len(prefix) :] + else: + if idx + 1 >= len(args): + return None, idx, {"kind": "usage_error", "exit_code": 2, "err_kind": "missing_value", "token": bhex(name)} + idx += 1 + val = args[idx] + if (not allow_empty and len(val) == 0) or (not allow_dash and val.startswith(b"-")): + return None, idx, {"kind": "usage_error", "exit_code": 2, "err_kind": "missing_value", "token": bhex(name)} + return val, idx, None + + if cmd == b"rotate": + dry_run = False + compress_after = None + target = None + module = None + pos = [] + i = 0 + while i < len(rest): + a = rest[i] + if a == b"--dry-run": + dry_run = True + elif a == b"--compress-after" or a.startswith(b"--compress-after="): + val, i, err = parse_val(rest, i, b"compress-after", True, True) + if err: + return err + compress_after = val + elif a == b"--target" or a.startswith(b"--target="): + val, i, err = parse_val(rest, i, b"target", False, True) + if err: + return err + target = val + elif a == b"--module" or a.startswith(b"--module="): + val, i, err = parse_val(rest, i, b"module", False, False) + if err: + return err + module = val + elif a.startswith(b"-"): + return {"kind": "usage_error", "exit_code": 2, "err_kind": "unknown_option", "token": bhex(a)} + else: + if len(pos) >= 1: + return {"kind": "usage_error", "exit_code": 2, "err_kind": "extra_positional", "token": bhex(a)} + pos.append(a) + i += 1 + if len(pos) < 1: + return {"kind": "usage_error", "exit_code": 2, "err_kind": "missing_required", "token": bhex(b"ROOT")} + return { + "kind": "ok", + "command": "rotate", + "dry_run": dry_run, + "compress_after": bhex(compress_after), + "target": bhex(target), + "module": bhex(module), + "root": bhex(pos[0]), + } + + if cmd == b"failed": + syslog = None + pos = [] + i = 0 + while i < len(rest): + a = rest[i] + if a == b"--syslog" or a.startswith(b"--syslog="): + val, i, err = parse_val(rest, i, b"syslog", True, True) + if err: + return err + syslog = val + else: + if len(pos) >= 4: + return {"kind": "usage_error", "exit_code": 2, "err_kind": "extra_positional", "token": bhex(a)} + pos.append(a) + i += 1 + req_names = [b"STATUS", b"NAME", b"LOGDIR"] + if len(pos) < 3: + return {"kind": "usage_error", "exit_code": 2, "err_kind": "missing_required", "token": bhex(req_names[len(pos)])} + return {"kind": "ok", "command": "failed", "syslog": bhex(syslog), "pos": [bhex(x) for x in pos]} + + if cmd == b"prescan": + for a in rest: + if a in (b"-h", b"--help"): + return {"kind": "action_done", "exit_code": 0, "stdout": bhex(b"prescan help\n")} + if a == b"--version": + return {"kind": "action_done", "exit_code": 0, "stdout": bhex(b"prescan 1.0\n")} + fmt = None + pos = [] + i = 0 + while i < len(rest): + a = rest[i] + if a == b"--format" or a.startswith(b"--format="): + val, i, err = parse_val(rest, i, b"format", False, True) + if err: + return err + fmt = val + elif a.startswith(b"-"): + return {"kind": "usage_error", "exit_code": 2, "err_kind": "unknown_option", "token": bhex(a)} + else: + if len(a) == 0 and len(pos) == 0: + i += 1 + continue + if len(pos) >= 1: + return {"kind": "usage_error", "exit_code": 2, "err_kind": "extra_positional", "token": bhex(a)} + pos.append(a) + i += 1 + if len(pos) < 1: + return {"kind": "usage_error", "exit_code": 2, "err_kind": "missing_required", "token": bhex(b"RUN")} + return {"kind": "ok", "command": "prescan", "format": bhex(fmt), "run": bhex(pos[0])} + + if cmd == b"mutex": + unused = False + active = False + json_flag = False + pos = [] + for a in rest: + if a == b"--unused": + if active: + return {"kind": "usage_error", "exit_code": 2, "err_kind": "mutually_exclusive", "option": bhex(b"unused"), "conflict": bhex(b"active")} + unused = True + elif a == b"--active": + if unused: + return {"kind": "usage_error", "exit_code": 2, "err_kind": "mutually_exclusive", "option": bhex(b"active"), "conflict": bhex(b"unused")} + active = True + elif a == b"--json": + json_flag = True + elif a.startswith(b"-"): + return {"kind": "usage_error", "exit_code": 2, "err_kind": "unknown_option", "token": bhex(a)} + else: + pos.append(a) + if len(pos) < 1: + return {"kind": "usage_error", "exit_code": 2, "err_kind": "missing_required", "token": bhex(b"FILE")} + return {"kind": "ok", "command": "mutex", "unused": unused, "active": active, "json": json_flag, "files": [bhex(x) for x in pos]} + + # cmd == b"used" + json_flag = False + prefix = None + pos = [] + i = 0 + while i < len(rest): + a = rest[i] + if a == b"--json": + json_flag = True + elif a == b"--prefix" or a.startswith(b"--prefix="): + val, i, err = parse_val(rest, i, b"prefix", False, False) + if err: + return err + prefix = val + elif a.startswith(b"-"): + return {"kind": "usage_error", "exit_code": 2, "err_kind": "unknown_option", "token": bhex(a)} + else: + pos.append(a) + i += 1 + if prefix is None: + return {"kind": "usage_error", "exit_code": 2, "err_kind": "missing_required", "token": bhex(b"prefix")} + if len(pos) < 1: + return {"kind": "usage_error", "exit_code": 2, "err_kind": "missing_required", "token": bhex(b"FILE")} + return {"kind": "ok", "command": "used", "json": json_flag, "prefix": bhex(prefix), "files": [bhex(x) for x in pos]} + + +def generate_native_cases(rng, count=600): + top_toks = [b"-h", b"--help", b"--help=1", b"--version", b"--version=1", b"--bogus", b"nope"] + sub_pools = { + b"rotate": [ + b"--dry-run", + b"--dry-run=1", + b"--compress-after", + b"--compress-after=", + b"--compress-after=-5", + b"--target", + b"--target=", + b"--target=-x", + b"--module", + b"--module=", + b"--module=-x", + b"--module=GCC", + b"--bogus", + b"-1", + b"", + b"logs", + b"extra", + ], + b"failed": [ + b"--syslog", + b"--syslog=", + b"--syslog=-x", + b"--bogus", + b"-1", + b"1", + b"Foo", + b"logdir", + b"tmpdir", + b"extra", + ], + b"used": [ + b"--json", + b"--json=1", + b"--prefix", + b"--prefix=", + b"--prefix=-x", + b"--prefix=/opt", + b"--bogus", + b"a.json", + b"b.json", + b"c.json", + ], + b"prescan": [ + b"-h", + b"--help", + b"--help=1", + b"--version", + b"--version=1", + b"--format", + b"--format=", + b"--format=json", + b"--bogus", + b"", + b"run1", + b"run2", + ], + b"mutex": [ + b"--unused", + b"--unused=1", + b"--active", + b"--active=1", + b"--json", + b"--bogus", + b"a.log", + b"b.log", + ], + } + cases = [ + [], + [b"--bogus"], + [b"--help"], + [b"--help=1"], + [b"--version"], + [b"--version=1"], + [b"nope"], + [b"rotate", b"--bogus"], + [b"rotate", b"--bogus", b"--target"], + [b"rotate", b"--dry-run=1", b"logs"], + [b"rotate", b"--compress-after", b"-5", b"logs"], + [b"rotate", b"--target=", b"logs"], + [b"rotate", b"--module=-x", b"logs"], + [b"failed", b"-1", b"Foo", b"--bogus"], + [b"failed", b"1", b"Foo", b"dir", b"tmp", b"extra"], + [b"used", b"a.json", b"--prefix", b"/opt", b"--json", b"b.json"], + [b"prescan", b"--bogus", b"-h"], + [b"prescan", b"--format", b"--help"], + [b"prescan", b"--bogus", b"--version"], + [b"prescan", b"", b"run1"], + [b"prescan", b"run1", b""], + [b"prescan", b""], + [b"mutex", b"--unused", b"--active", b"--bogus"], + [b"mutex", b"--bogus", b"--unused", b"--active"], + [b"mutex", b"--active", b"--unused", b"a.log"], + [b"mutex", b"--unused", b"--json", b"a.log"], + ] + subs = [b"rotate", b"failed", b"used", b"prescan", b"mutex"] + while len(cases) < count: + if rng.random() < 0.15: + cases.append([rng.choice(top_toks) for _ in range(rng.randrange(0, 3))]) + continue + argv = [] + if rng.random() < 0.1: + argv.append(rng.choice([b"--bogus", b"--help=1"])) + sub = rng.choice(subs) + argv.append(sub) + pool = sub_pools[sub] + for _ in range(rng.randrange(0, 7)): + argv.append(rng.choice(pool)) + cases.append(argv) + return cases + + def run_probe_batch(mode, cases): lines = [] for argv in cases: @@ -645,6 +1004,56 @@ def test_prolog_lenient_differential_fuzz(self): if mismatches: self.fail(f"seed={SEED}: prolog mismatches: {mismatches[:5]!r}") + @unittest.skipUnless(IS_PY314, "parse_intermixed_args differential parity requires Python 3.14+") + def test_intermixed_variadic_differential_fuzz(self): + cases = generate_intermixed_cases(self.rng, count=400) + zig_results = run_probe_batch("intermixed", cases) + + mismatches = [] + counts = {"ok": 0, "action_done": 0, "usage_error": 0} + for argv, zig_res in zip(cases, zig_results): + py_res = run_python_intermixed(argv) + counts[py_res["kind"]] = counts.get(py_res["kind"], 0) + 1 + if zig_res != py_res: + mismatches.append((argv, py_res, zig_res)) + if len(mismatches) >= 10: + break + if mismatches: + lines = [f"seed={SEED}: intermixed mismatches:"] + for argv, py_res, zig_res in mismatches[:5]: + py_s = dict(py_res) + zig_s = dict(zig_res) + for d in (py_s, zig_s): + for k in ("stdout", "stderr"): + if k in d and d[k] is not None: + d[k] = bytes.fromhex(d[k]).decode("utf-8", "replace") + lines.append(f" argv={argv!r}\n py ={py_s!r}\n zig={zig_s!r}") + self.fail("\n".join(lines)) + + self.assertGreater(counts["ok"], 20) + self.assertGreater(counts["action_done"], 20) + self.assertGreater(counts["usage_error"], 50) + + def test_native_exact_differential_fuzz(self): + cases = generate_native_cases(self.rng, count=500) + zig_results = run_probe_batch("native", cases) + + mismatches = [] + counts = {"ok": 0, "action_done": 0, "usage_error": 0} + for argv, zig_res in zip(cases, zig_results): + py_res = run_python_native(argv) + counts[py_res["kind"]] = counts.get(py_res["kind"], 0) + 1 + if zig_res != py_res: + mismatches.append((argv, py_res, zig_res)) + if len(mismatches) >= 10: + break + if mismatches: + self.fail(f"seed={SEED}: native_exact mismatches: {mismatches[:5]!r}") + + self.assertGreater(counts["ok"], 20) + self.assertGreater(counts["action_done"], 10) + self.assertGreater(counts["usage_error"], 100) + @unittest.skipUnless(IS_PY314, "Policy.python314 subprocess parity requires Python 3.14+") def test_parse_or_exit_subprocess_codes_and_streams(self): probe = probe_path()