golang / go

The Go programming language
https://go.dev
BSD 3-Clause "New" or "Revised" License
123.04k stars 17.54k forks source link

text/template: incorrect error line number reporting after multiline comments #69526

Open mkideal opened 4 days ago

mkideal commented 4 days ago

Go version

go version go1.23.0 darwin/amd64

Output of go env in your module/workspace:

GO111MODULE=''
GOARCH='arm64'
GOBIN=''
GOCACHE='/Users/dev/Library/Caches/go-build'
GOENV='/Users/dev/Library/Application Support/go/env'
GOEXE=''
GOEXPERIMENT=''
GOFLAGS=''
GOHOSTARCH='amd64'
GOHOSTOS='darwin'
GOMODCACHE='/Users/dev/pkg/mod'
GOOS='darwin'
GOPATH='/Users/dev'
GOPROXY='https://goproxy.cn,direct'
GOROOT='/usr/local/go'
GOSUMDB='sum.golang.org'
GOTMPDIR=''
GOTOOLCHAIN='auto'
GOTOOLDIR='/usr/local/go/pkg/tool/darwin_amd64'
GOVCS=''
GOVERSION='go1.23.0'
GODEBUG='gotypesalias=1'
GOTELEMETRY='local'
GOTELEMETRYDIR='/Users/dev/Library/Application Support/go/telemetry'
GCCGO='gccgo'
GOARM64='v8.0'
AR='ar'
CC='clang'
CXX='clang++'
CGO_ENABLED='0'
GOWORK=''
CGO_CFLAGS='-O2 -g'
CGO_CPPFLAGS=''
CGO_CXXFLAGS='-O2 -g'
CGO_FFLAGS='-O2 -g'
CGO_LDFLAGS='-O2 -g'
PKG_CONFIG='pkg-config'
GOGCCFLAGS='-fPIC -arch arm64 -fno-caret-diagnostics -Qunused-arguments -fmessage-length=0 -ffile-prefix-map=/var/folders/2f/7bsk573j6bd1b949y1mq2stm0000gn/T/go-build3492055087=/tmp/go-build -gno-record-gcc-switches -fno-common'

What did you do?

I encountered a problem with incorrect error line number reporting when using the text/template package. Specifically, if a template has a multiline comment (e.g., {{/* ... */}}), and an error occurs (such as an undefined function) on a line immediately after the comment, the reported error line is incorrect and points to the start of the comment block or earlier.

Example code https://go.dev/play/p/YVbgdA-Sj1Z:

package main

import (
    "os"
    "text/template"
    "log"
)

func main() {
    tmpl := `{{/*
This is a multiline comment.
It spans multiple lines.
*/}}
{{undefinedFunction "test"}}
`
    t, err := template.New("test").Parse(tmpl)
    if err != nil {
        log.Fatalf("Template parse error: %v", err)
    }
    err = t.Execute(os.Stdout, nil)
    if err != nil {
        log.Printf("Template execution error: %v", err)
    }
}

What did you see happen?

The error reported the wrong line number):

Template parse error: template: test:2: function "undefinedFunction" not defined

What did you expect to see?

I expected the error to report the correct line where the undefined function is used:

Template parse error: template: test:5: function "undefinedFunction" not defined

gabyhelp commented 4 days ago

Related Issues and Documentation

(Emoji vote if this was helpful or unhelpful; more detailed feedback welcome in this discussion.)

gopherbot commented 4 days ago

Change https://go.dev/cl/614375 mentions this issue: template:fix line number is wrong in error info

cagedmantis commented 3 days ago

cc @robpike @mvdan