From: Ian Lance Taylor Date: Mon, 31 Oct 2022 22:58:06 +0000 (-0700) Subject: text/template: correct assignment, not declaration, in range X-Git-Tag: go1.20rc1~456 X-Git-Url: http://www.git.cypherpunks.su/?a=commitdiff_plain;h=be7068fb0804f661515c678bee9224b90b32869a;p=gostls13.git text/template: correct assignment, not declaration, in range 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 Reviewed-by: Ian Lance Taylor TryBot-Result: Gopher Robot Reviewed-by: Rob Pike Run-TryBot: Ian Lance Taylor Reviewed-by: Bryan Mills Auto-Submit: Ian Lance Taylor --- diff --git a/src/text/template/exec.go b/src/text/template/exec.go index 66cb535c47..fb60c17931 100644 --- a/src/text/template/exec.go +++ b/src/text/template/exec.go @@ -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() { diff --git a/src/text/template/exec_test.go b/src/text/template/exec_test.go index 6bfae3d319..6b163f0ae1 100644 --- a/src/text/template/exec_test.go +++ b/src/text/template/exec_test.go @@ -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 {