Skip to content

Commit

Permalink
text/template: set variables correctly in range assignment
Browse files Browse the repository at this point in the history
I unintentionally flipped them in CL 446795.

For #56490
Fixes #60801

Change-Id: I57586bec052e1b2cc61513870ce24dd6ce17e56b
Reviewed-on: https://go-review.googlesource.com/c/go/+/503575
Reviewed-by: Ian Lance Taylor <iant@google.com>
Run-TryBot: Ian Lance Taylor <iant@golang.org>
Reviewed-by: Rob Pike <r@golang.org>
TryBot-Result: Gopher Robot <gobot@golang.org>
Auto-Submit: Ian Lance Taylor <iant@google.com>
Run-TryBot: Ian Lance Taylor <iant@google.com>
Reviewed-by: Bryan Mills <bcmills@google.com>
  • Loading branch information
ianlancetaylor authored and gopherbot committed Jun 15, 2023
1 parent c546321 commit befec5d
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 4 deletions.
16 changes: 12 additions & 4 deletions src/text/template/exec.go
Original file line number Diff line number Diff line change
Expand Up @@ -361,19 +361,27 @@ func (s *state) walkRange(dot reflect.Value, r *parse.RangeNode) {
// mark top of stack before any variables in the body are pushed.
mark := s.mark()
oneIteration := func(index, elem reflect.Value) {
// Set top var (lexically the second if there are two) to the element.
if len(r.Pipe.Decl) > 0 {
if r.Pipe.IsAssign {
s.setVar(r.Pipe.Decl[0].Ident[0], elem)
// With two variables, index comes first.
// With one, we use the element.
if len(r.Pipe.Decl) > 1 {
s.setVar(r.Pipe.Decl[0].Ident[0], index)
} else {
s.setVar(r.Pipe.Decl[0].Ident[0], elem)
}
} else {
// Set top var (lexically the second if there
// are two) to the element.
s.setTopVar(1, elem)
}
}
// Set next var (lexically the first if there are two) to the index.
if len(r.Pipe.Decl) > 1 {
if r.Pipe.IsAssign {
s.setVar(r.Pipe.Decl[1].Ident[0], index)
s.setVar(r.Pipe.Decl[1].Ident[0], elem)
} else {
// Set next var (lexically the first if there
// are two) to the index.
s.setTopVar(2, index)
}
}
Expand Down
1 change: 1 addition & 0 deletions src/text/template/exec_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -694,6 +694,7 @@ var execTests = []execTest{
{"bug18c", "{{eq . 'P'}}", "true", 'P', true},

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

func zeroArgs() string {
Expand Down

0 comments on commit befec5d

Please sign in to comment.