zig.vim icon indicating copy to clipboard operation
zig.vim copied to clipboard

"Lone" else lines are not properly indented

Open yohannd1 opened this issue 2 years ago • 4 comments

By "lone" else lines, I mean lines in if statements that only have whitespace and the else keyword. They're usually around when there is a multi-line if condition that isn't directly made up of blocks.

For an actual example on what is happening - I typed this code from top to bottom using automatic indentation:

const a = if (cond)
    val1
    else
    val2;

pub fn main() void {
    const b = if (cond)
        val1
        else
            val2;
}

What I expect to happen is the following:

const a = if (cond)
    val1
else
    val2;

pub fn main() void {
    const b = if (cond)
        val1
    else
        val2;
}

NOTE: I was previously working on this under the #59 PR, but got stuck and don't really know where to go anymore, so I'm leaving it up for anyone who may be able to tackle this in a better way.

yohannd1 avatar Mar 16 '22 23:03 yohannd1

Lone statements in an if else are grammar/parser errors, if on different lines For example, I get on writing

fn somefn(num: c_int) void {
    if (num < 10)
        return 1;
    else
        return 2;
}
min.zig|4 col 5| : error: expected statement, found 'else'

This line neither works (only resolved types can be written into one line):

fn somefn(num: c_int) void {
    if (num < 10) return 1; else return 2;
}

Suggestion to close this.

UPDATE: Mention type resolving as working.

matu3ba avatar Dec 26 '22 22:12 matu3ba

Is it fair to say that a lone else should always be de-indented? Is there a time when it should never be de-indented?

talcynon avatar Jan 02 '23 16:01 talcynon

@matu3ba I think the issue is limited to if expressions. (An if statement would always start on its own line.) For example, this is a valid Zig program:

pub fn main() u8 {
    const retval = if (true)
        0
    else
        1;
    return retval;
}

talcynon avatar Jan 02 '23 16:01 talcynon

Ah, now I do understand the problem. I think a proper solution requires a parser to distinguish expressions from statements, since those can be arbitrarily nested.

I can tell you that nvim-treesitter indent is broken for Zig and helix has also not implemented indentation based on treesitter yet.

matu3ba avatar Jan 02 '23 16:01 matu3ba