From: Emmanuel Odeke Date: Sun, 1 Jan 2017 10:08:48 +0000 (-0700) Subject: cmd/compile: improve error message if init is directly invoked X-Git-Tag: go1.9beta1~1792 X-Git-Url: http://www.git.cypherpunks.su/?a=commitdiff_plain;h=cb6e0639fb090ea0e129b1ddb956a7e645cff285;p=gostls13.git cmd/compile: improve error message if init is directly invoked Fixes #8481. Inform the user that init functions cannot be directly invoked in user code, as mandated by the spec at: http://golang.org/ref/spec#Program_initialization_and_execution. Change-Id: Ib12c0c08718ffd48b76b6f9b13c76bb6612d2e7b Reviewed-on: https://go-review.googlesource.com/34790 Reviewed-by: Keith Randall Reviewed-by: Matthew Dempsky Run-TryBot: Matthew Dempsky TryBot-Result: Gobot Gobot --- diff --git a/src/cmd/compile/internal/gc/typecheck.go b/src/cmd/compile/internal/gc/typecheck.go index 51fc7fd442..ee4eb0353e 100644 --- a/src/cmd/compile/internal/gc/typecheck.go +++ b/src/cmd/compile/internal/gc/typecheck.go @@ -3648,11 +3648,19 @@ func typecheckdef(n *Node) *Node { lineno = n.Pos } - // Note: adderrorname looks for this string and - // adds context about the outer expression - yyerror("undefined: %v", n.Sym) + switch n.Sym.Name { + case "init": + // As per the spec at: + // https://golang.org/ref/spec#Program_initialization_and_execution + // init cannot be referred to in usercode. + // See https://golang.org/issues/8481. + yyerror("cannot refer to init functions") + default: + // Note: adderrorname looks for this string and + // adds context about the outer expression + yyerror("undefined: %v", n.Sym) + } } - return n } diff --git a/test/fixedbugs/issue8481.go b/test/fixedbugs/issue8481.go new file mode 100644 index 0000000000..a69296687a --- /dev/null +++ b/test/fixedbugs/issue8481.go @@ -0,0 +1,14 @@ +// errorcheck + +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +func init() { +} + +func main() { + init() // ERROR "cannot refer to init functions" +} diff --git a/test/init.go b/test/init.go index f4689443cf..1855b4ff56 100644 --- a/test/init.go +++ b/test/init.go @@ -15,7 +15,7 @@ func init() { } func main() { - init() // ERROR "undefined.*init" + init() // ERROR "cannot refer to init functions" runtime.init() // ERROR "unexported.*runtime\.init" - var _ = init // ERROR "undefined.*init" + var _ = init // ERROR "cannot refer to init functions" }