golang / go

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

cmd/compile: declaration order of types affects cycle detection #68025

Open richardwilkes opened 1 week ago

richardwilkes commented 1 week ago

Go version

go version go1.22.3 darwin/amd64

Output of go env in your module/workspace:

GO111MODULE=''
GOARCH='amd64'
GOBIN=''
GOCACHE='/Users/rich/Library/Caches/go-build'
GOENV='/Users/rich/Library/Application Support/go/env'
GOEXE=''
GOEXPERIMENT=''
GOFLAGS=''
GOHOSTARCH='amd64'
GOHOSTOS='darwin'
GOINSECURE=''
GOMODCACHE='/Users/rich/go/pkg/mod'
GONOPROXY=''
GONOSUMDB=''
GOOS='darwin'
GOPATH='/Users/rich/go'
GOPRIVATE=''
GOPROXY='https://proxy.golang.org,direct'
GOROOT='/Users/rich/go/pkg/mod/golang.org/toolchain@v0.0.1-go1.22.3.darwin-amd64'
GOSUMDB='sum.golang.org'
GOTMPDIR=''
GOTOOLCHAIN='auto'
GOTOOLDIR='/Users/rich/go/pkg/mod/golang.org/toolchain@v0.0.1-go1.22.3.darwin-amd64/pkg/tool/darwin_amd64'
GOVCS=''
GOVERSION='go1.22.3'
GCCGO='gccgo'
GOAMD64='v1'
AR='ar'
CC='clang'
CXX='clang++'
CGO_ENABLED='1'
GOMOD='/Users/rich/code/gcs/go.mod'
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 x86_64 -m64 -pthread -fno-caret-diagnostics -Qunused-arguments -fmessage-length=0 -ffile-prefix-map=/var/folders/s9/9s3fk2mx5f936dkcp66ltwsc0000gn/T/go-build2527957728=/tmp/go-build -gno-record-gcc-switches -fno-common'

What did you do?

I found that this will not compile: https://go.dev/play/p/X-_09aV9wYj While just moving the declaration of the interface to after the struct definitions causes it to compile fine: https://go.dev/play/p/xic2fqhfmTi

What did you see happen?

./prog.go:3:6: invalid recursive type A
    ./prog.go:3:6: A refers to
    ./prog.go:7:6: B refers to
    ./prog.go:11:6: C refers to
    ./prog.go:3:6: A

Go build failed.

What did you expect to see?

I expected both versions of the code to compile and run without error.

gabyhelp commented 1 week ago

Similar Issues

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

richardwilkes commented 1 week ago

I should note that while rearranging the code fixes the problem, if the definitions are in different files (which happens to be the case for my real code, since a bunch of different types are used in the interface definition, i.e. something more like:

type A interface {
    *B | *D | *E | *F | *G | *H
}

then it sometimes fails and sometimes doesn't. I've yet to figure out exactly what is determining the order in that case.

ianlancetaylor commented 1 week ago

CC @griesemer

griesemer commented 1 week ago

Thanks for the report. Our cycle detection algorithm could use some love. cc: @timothy-king