elves / elvish

Powerful scripting language & versatile interactive shell
https://elv.sh/
BSD 2-Clause "Simplified" License
5.65k stars 299 forks source link

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

Open krader1961 opened 7 months ago

krader1961 commented 7 months ago

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.

marco-m commented 6 months ago

@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).