Zig Fmt: Always allow for control-flow statements to be the first thing on a line

Here are a couple things I wish zig fmt would allow pertaining to the idea that control-flow statements should be the first thing on a line:

// example 1
const user_index =
    if (std.mem.eql(u8, user.discriminator, "0"))
        user.id.timestamp % 6
    else if (user.discriminator.len > 1) blk: {
        const discrim = std.fmt.parseInt(u32, user.discriminator, 10) catch return error.InvalidDiscriminator;
        break :blk discrim % 5;
    } else {
        std.log.err("invalid discriminator: '{s}'", .{user.discriminator});
        return error.InvalidDiscriminator;
    };

// example 2:
doAFunctionCallWithManyParams(param1, param2, param3, param4, param5)
    catch |err| switch (err) {
        error.Case1 => ...,
        error.Case2 => ...,
    };

// example 3 (also would be nice for `orelse`):
const another_variable = std.fmt.parseInt(u64, my_variable_name, 10)
    catch 0;

Currently, these collapse to:

// example 1
const user_index = if (std.mem.eql(u8, user.discriminator, "0"))
    user.id.timestamp % 6
else if (user.discriminator.len > 1) blk: {
    const discrim = std.fmt.parseInt(u32, user.discriminator, 10) catch return error.InvalidDiscriminator;
    break :blk discrim % 5;
} else {
    std.log.err("invalid discriminator: '{s}'", .{user.discriminator});
    return error.InvalidDiscriminator;
};

// example 2
doAFunctionCallWithManyParams(param1, param2, param3, param4, param5) catch |err| switch (err) {
    error.Case1 => ...,
    error.Case2 => ...,
};

// example 3 (also would be nice for `orelse`)
const another_variable = std.fmt.parseInt(u64, my_variable_name, 10) catch
    0;

One thing I really appreciated about go fmt is that it always forced control flow statements to be the first thing of each line. While I don’t necessarily agree that all control flow should be forced to the beginning of the line, I’d appreciate being able to at least allow this for many cases.

5 Likes

Much more readable your way. I agree.

(In general, I think zig’s chattery syntax should invite more consideration about means of control of eye movement over the text. it’s too zig-zaggy, in my experience).

3 Likes

I do the same thing and agree it’d be nice if zig fmt was a bit more lax in this regard.

Knowing that the status quo is unlikely to change, I can point you to potential alternatives like zift which may be open to including this as an option.

1 Like