Skip to content

Commit

Permalink
text/template: correct assignment, not declaration, in range
Browse files Browse the repository at this point in the history
We were mishandling {{range $i = .}}, treating it as though it were
{{range $i := .}}. That happened to work if $i were the most recently
declared variable, but not otherwise.

Fixes #56490

Change-Id: I222a009d671d86c06a980a54388e05f12101c00b
Reviewed-on: https://go-review.googlesource.com/c/go/+/446795
Run-TryBot: Ian Lance Taylor <iant@google.com>
Reviewed-by: Ian Lance Taylor <iant@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Rob Pike <r@golang.org>
Run-TryBot: Ian Lance Taylor <iant@golang.org>
Reviewed-by: Bryan Mills <bcmills@google.com>
Auto-Submit: Ian Lance Taylor <iant@google.com>
  • Loading branch information
ianlancetaylor authored and gopherbot committed Nov 2, 2022
1 parent c53390b commit be7068f
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 2 deletions.
12 changes: 10 additions & 2 deletions src/text/template/exec.go
Original file line number Diff line number Diff line change
Expand Up @@ -363,11 +363,19 @@ func (s *state) walkRange(dot reflect.Value, r *parse.RangeNode) {
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 {
s.setTopVar(1, elem)
if r.Pipe.IsAssign {
s.setVar(r.Pipe.Decl[0].Ident[0], elem)
} else {
s.setTopVar(1, elem)
}
}
// Set next var (lexically the first if there are two) to the index.
if len(r.Pipe.Decl) > 1 {
s.setTopVar(2, index)
if r.Pipe.IsAssign {
s.setVar(r.Pipe.Decl[1].Ident[0], index)
} else {
s.setTopVar(2, index)
}
}
defer s.pop(mark)
defer func() {
Expand Down
2 changes: 2 additions & 0 deletions src/text/template/exec_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -692,6 +692,8 @@ var execTests = []execTest{
{"bug18a", "{{eq . '.'}}", "true", '.', true},
{"bug18b", "{{eq . 'e'}}", "true", 'e', true},
{"bug18c", "{{eq . 'P'}}", "true", 'P', true},

{"issue56490", "{{$i := 0}}{{$x := 0}}{{range $i = .AI}}{{end}}{{$i}}", "5", tVal, true},
}

func zeroArgs() string {
Expand Down

0 comments on commit be7068f

Please sign in to comment.