elves / elvish

Powerful scripting language & versatile interactive shell

Home Page:https://elv.sh/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Convert `for` loops to `range $int` when Go 1.22 becomes the minimum acceptable version

krader1961 opened this issue · comments

When Go version 1.22 becomes the minimum acceptable version (probably when Go 1.23 is released) it would be nice to run something like the following over the code base and commit the resulting changes to take advantage of the simpler range syntax for iterating over a sequence of integers from zero to n:

perl -pi -e 's/for (\w+) := 0; \1 < ([\w()]+); \1\+\+/for \1 := range \2/' (git grep -l for)

It is important that every change created by the above command be carefully reviewed. If the loop body modifies the loop var or the value tested against the loop var the transformation may be invalid. Here is a contrived, silly, example that illustrates both pitfalls:

var done int = 10
for i := 0; i < done; i += 1 {
    if i+2 > done {
        i -= 1
        done += 1
    }
}

I couldn't find any Elvish code that modifies either loop value in the loop body at the time I opened this issue but each change still needs to be carefully evaluated when this transformation is made.

@krader1961 FYI gofmt allows automatic rewrite with full syntax tree awareness, see https://go.dev/blog/gofmt#mechanical-source-transformation (and, mentioned in the same place, gofix).