Skip to content

Commit 0306310

Browse files
ianlancetaylorIan Lance Taylor
authored and
Ian Lance Taylor
committed
[release-branch.go1.20] text/template: set variables correctly in range assignment
I unintentionally flipped them in CL 446795. For #56490 For #60801 Fixes #60802 Change-Id: I57586bec052e1b2cc61513870ce24dd6ce17e56b Reviewed-on: https://go-review.googlesource.com/c/go/+/503576 TryBot-Result: Gopher Robot <[email protected]> Run-TryBot: Ian Lance Taylor <[email protected]> Reviewed-by: Bryan Mills <[email protected]>
1 parent d51e322 commit 0306310

File tree

2 files changed

+13
-4
lines changed

2 files changed

+13
-4
lines changed

src/text/template/exec.go

+12-4
Original file line numberDiff line numberDiff line change
@@ -361,19 +361,27 @@ func (s *state) walkRange(dot reflect.Value, r *parse.RangeNode) {
361361
// mark top of stack before any variables in the body are pushed.
362362
mark := s.mark()
363363
oneIteration := func(index, elem reflect.Value) {
364-
// Set top var (lexically the second if there are two) to the element.
365364
if len(r.Pipe.Decl) > 0 {
366365
if r.Pipe.IsAssign {
367-
s.setVar(r.Pipe.Decl[0].Ident[0], elem)
366+
// With two variables, index comes first.
367+
// With one, we use the element.
368+
if len(r.Pipe.Decl) > 1 {
369+
s.setVar(r.Pipe.Decl[0].Ident[0], index)
370+
} else {
371+
s.setVar(r.Pipe.Decl[0].Ident[0], elem)
372+
}
368373
} else {
374+
// Set top var (lexically the second if there
375+
// are two) to the element.
369376
s.setTopVar(1, elem)
370377
}
371378
}
372-
// Set next var (lexically the first if there are two) to the index.
373379
if len(r.Pipe.Decl) > 1 {
374380
if r.Pipe.IsAssign {
375-
s.setVar(r.Pipe.Decl[1].Ident[0], index)
381+
s.setVar(r.Pipe.Decl[1].Ident[0], elem)
376382
} else {
383+
// Set next var (lexically the first if there
384+
// are two) to the index.
377385
s.setTopVar(2, index)
378386
}
379387
}

src/text/template/exec_test.go

+1
Original file line numberDiff line numberDiff line change
@@ -694,6 +694,7 @@ var execTests = []execTest{
694694
{"bug18c", "{{eq . 'P'}}", "true", 'P', true},
695695

696696
{"issue56490", "{{$i := 0}}{{$x := 0}}{{range $i = .AI}}{{end}}{{$i}}", "5", tVal, true},
697+
{"issue60801", "{{$k := 0}}{{$v := 0}}{{range $k, $v = .AI}}{{$k}}={{$v}} {{end}}", "0=3 1=4 2=5 ", tVal, true},
697698
}
698699

699700
func zeroArgs() string {

0 commit comments

Comments
 (0)