golang / go

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

cmd/compile: bad error message when defining a variable for a parenthesized type #68589

Open iwahbe opened 1 month ago

iwahbe commented 1 month ago

Go version

go version go1.22.4 darwin/arm64

Output of go env in your module/workspace:

GO111MODULE=''
GOARCH='arm64'
GOBIN='/Users/ianwahbe/go/bin'
GOCACHE='/Users/ianwahbe/Library/Caches/go-build'
GOENV='/Users/ianwahbe/Library/Application Support/go/env'
GOEXE=''
GOEXPERIMENT=''
GOFLAGS=''
GOHOSTARCH='arm64'
GOHOSTOS='darwin'
GOINSECURE=''
GOMODCACHE='/Users/ianwahbe/go/pkg/mod'
GONOPROXY=''
GONOSUMDB=''
GOOS='darwin'
GOPATH='/Users/ianwahbe/go'
GOPRIVATE=''
GOPROXY='https://proxy.golang.org,direct'
GOROOT='/opt/homebrew/Cellar/go/1.22.4/libexec'
GOSUMDB='sum.golang.org'
GOTMPDIR=''
GOTOOLCHAIN='auto'
GOTOOLDIR='/opt/homebrew/Cellar/go/1.22.4/libexec/pkg/tool/darwin_arm64'
GOVCS=''
GOVERSION='go1.22.4'
GCCGO='gccgo'
AR='ar'
CC='cc'
CXX='c++'
CGO_ENABLED='1'
GOMOD='/dev/null'
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 -pthread -fno-caret-diagnostics -Qunused-arguments -fmessage-length=0 -ffile-prefix-map=/var/folders/fg/_1q36r4j6yx0rwz2fbhjd5y40000gn/T/go-build3467175502=/tmp/go-build -gno-record-gcc-switches -fno-common'

What did you do?

I tried to compile this code (link):

var key (type keyType struct{})

What did you see happen?

The compilation errors with:

./prog.go:3:10: syntax error: unexpected type, expected type

I wasn't sure if the above was valid Go code, but the compiler should give a better error message.

What did you expect to see?

An improved error message like:

./prog.go:3:16: syntax error: type declarations cannot be used as expressions
gabyhelp commented 1 month ago

Related Issues and Documentation

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

ianlancetaylor commented 1 month ago

CC @griesemer @golang/compiler

griesemer commented 1 month ago

This is rather unusual code not typically encountered once a basic familiarity with Go has been established (at least that's the first time something like this has come to our attention in 15 years). It's also non-trivial to recognize that the parenthesized code is a type declaration in order to provide the desired error message; the effort doesn't seem justified given that this is just a rare situation.

It perhaps makes sense to report something like "unexpected keyword type, expected type expression" to distinguish the two kinds of types. That would only incur a cost in case of an error (rare).