Skip to content

Commit c7d548a

Browse files
Fix multi-variable init (#7244)
1 parent a92c847 commit c7d548a

3 files changed

Lines changed: 34 additions & 7 deletions

File tree

rewrite-go/rewrite/pkg/parser/go_parser.go

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -393,18 +393,28 @@ func (ctx *parseContext) mapValueSpec(spec *ast.ValueSpec, prefix tree.Space, ke
393393
}
394394

395395
// Then initializers (after type and `=` in source)
396+
// In Go, multi-value declarations use a single `=` followed by comma-separated values:
397+
// var a, b = val1, val2
396398
var variables []tree.RightPadded[*tree.VariableDeclarator]
397399
for i, nameIdent := range nameIdents {
398400
var init *tree.LeftPadded[tree.Expression]
399401
if i < len(spec.Values) {
400-
eqOff := ctx.findNext('=')
401-
var eqPrefix tree.Space
402-
if eqOff >= 0 {
403-
eqPrefix = ctx.prefix(ctx.file.Pos(eqOff))
404-
ctx.skip(1) // "="
402+
var sepPrefix tree.Space
403+
if i == 0 {
404+
eqOff := ctx.findNext('=')
405+
if eqOff >= 0 {
406+
sepPrefix = ctx.prefix(ctx.file.Pos(eqOff))
407+
ctx.skip(1) // "="
408+
}
409+
} else {
410+
commaOff := ctx.findNext(',')
411+
if commaOff >= 0 {
412+
sepPrefix = ctx.prefix(ctx.file.Pos(commaOff))
413+
ctx.skip(1) // ","
414+
}
405415
}
406416
val := ctx.mapExpr(spec.Values[i])
407-
lp := tree.LeftPadded[tree.Expression]{Before: eqPrefix, Element: val}
417+
lp := tree.LeftPadded[tree.Expression]{Before: sepPrefix, Element: val}
408418
init = &lp
409419
}
410420

rewrite-go/rewrite/pkg/printer/go_printer.go

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -332,10 +332,16 @@ func (p *GoPrinter) VisitVariableDeclarations(vd *tree.VariableDeclarations, par
332332
p.Visit(tag.Tag, out)
333333
}
334334
// Then initializers
335+
firstInit := true
335336
for _, v := range vd.Variables {
336337
if v.Element.Initializer != nil {
337338
p.visitSpace(v.Element.Initializer.Before, out)
338-
out.Append("=")
339+
if firstInit {
340+
out.Append("=")
341+
firstInit = false
342+
} else {
343+
out.Append(",")
344+
}
339345
p.Visit(v.Element.Initializer.Element, out)
340346
}
341347
}

rewrite-go/rewrite/test/var_test.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,17 @@ func TestParseGroupedConst(t *testing.T) {
114114
`))
115115
}
116116

117+
func TestParseMultiVarWithCompositeLiterals(t *testing.T) {
118+
NewRecipeSpec().RewriteRun(t,
119+
Golang(`
120+
package main
121+
122+
func f() {
123+
var a, b = []int{}, []int{}
124+
}
125+
`))
126+
}
127+
117128
func TestParseGroupedVarWithInit(t *testing.T) {
118129
NewRecipeSpec().RewriteRun(t,
119130
Golang(`

0 commit comments

Comments
 (0)