szn

Bug 516 — numeric choice options are unsettable

516. coerceValue never converts a .number into a .choice

Severity: MEDIUM Status: ✅ FIXED Files: src/options.zig:152-167, src/cfg.zig:256-260, src/options.zig:99

Problem

The config/command layer turns any bare numeric token into a .number:

// src/cfg.zig:256-260
if (s.len > 0 and (s[0] == '-' or std.ascii.isDigit(s[0]))) {
    if (std.fmt.parseInt(i64, s, 10)) |n| return OptionValue{ .number = n };
}

Options.coerceValue is supposed to normalise that against the definition, but its .choice arm has no .number case:

// src/options.zig:152-167
.choice => {
    switch (value) {
        .flag => |b| return OptionValue{ .choice = if (b) "on" else "off" },
        .string => |s| {
            if (def.choices) |choices| {
                for (choices) |c| {
                    if (std.mem.eql(u8, s, c)) return OptionValue{ .choice = s };
                }
            }
            return value;
        },
        else => return value,   // .number arrives here unchanged
    }
},

Options.set then runs try validateType(def, coerced) (options.zig:99) with a .number payload against a .choice definition and rejects it.

Consequences:

Proposed Fix

In the .choice arm, format a .number to its decimal string and match it against def.choices, returning a .choice on a hit and an explicit error.InvalidChoice on a miss (rather than silently passing the wrong tag through to validateType):

.number => |n| {
    var buf: [24]u8 = undefined;
    const s = std.fmt.bufPrint(&buf, "{d}", .{n}) catch return error.InvalidChoice;
    if (def.choices) |choices| {
        for (choices) |c| if (std.mem.eql(u8, s, c)) return OptionValue{ .choice = s };
    }
    return error.InvalidChoice;
},

Fix

// src/options.zig — coerceValue, .choice arm
.number => |n| {
    var buf: [24]u8 = undefined;
    const s = std.fmt.bufPrint(&buf, "{d}", .{n}) catch return value;
    if (def.choices) |choices| {
        for (choices) |c| {
            if (std.mem.eql(u8, s, c)) return OptionValue{ .choice = s };
        }
    }
    return value;
},

A numeric value is now formatted to its decimal string and matched against the definition’s choices, exactly as the .string arm already did. A value outside the set still falls through unchanged, so validateType rejects it as before — this only makes the valid numeric choices reachable.

Regression test

numeric-valued choice options are settable — bug #516 (src/cmd/cmd.zig) asserts set-option -g status 2 and set-option -g clock-mode-style 24 both succeed, and that set-option -g status 9 is still rejected. Before the fix the first two returned .err.

Verified with the full suite on Zig 0.16.0 and 0.17.0: 1054/1054 passing on both.

Bug #116 (choice values not cloned/freed) and bug #415 (config scope/flag surface parsed but discarded) touched adjacent option plumbing.