Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

cmd/compile: if expression having parenthesis produces compilation error #49996

Closed
pkositsyn opened this issue Dec 6, 2021 · 1 comment
Closed

Comments

@pkositsyn
Copy link
Contributor

What version of Go are you using (go version)?

$ go version go1.16.4 linux/amd64
and
$ go version go1.17.4 linux/amd64

What did you do?

https://go.dev/play/p/eIJEXrkKD8m

package main

import "log"

func main() {
	if T{}.Name() == "T" {
		log.Println("T")
	}
}

type T struct {}

func (t T) Name() string { return "T" }

I'd like to mention, that compiling with new(T) or extra parenthesis around T{}.Name() was successful. Seems to me that if T{ was parsed as beginning of the if scope.

At a first glance seems like two situations can be distinguished by having/not having a method call after parenthesis is closed

What did you expect to see?

Code compiled successfully

What did you see instead?

./prog.go:6:8: syntax error: unexpected . at end of statement
./prog.go:9:1: syntax error: non-declaration statement outside function body
@ALTree
Copy link
Member

ALTree commented Dec 6, 2021

A parsing ambiguity arises when a composite literal using the TypeName form of the LiteralType appears as an operand between the keyword and the opening brace of the block of an "if", "for", or "switch" statement, and the composite literal is not enclosed in parentheses, square brackets, or curly braces. In this rare case, the opening brace of the literal is erroneously parsed as the one introducing the block of statements. To resolve the ambiguity, the composite literal must appear within parentheses.

if x == (T{a,b,c}[i]) { … }
if (x == T{a,b,c}[i]) { … }

https://go.dev/ref/spec#Composite_literals

@ALTree ALTree closed this as completed Dec 6, 2021
@golang golang locked and limited conversation to collaborators Dec 6, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

3 participants