// Anonymous functions are considered part of the
// init expression/func declaration which contains
// them: use existing package-level declaration info.
+ //
+ // TODO(gri) We delay type-checking of regular (top-level)
+ // function bodies until later. Why don't we do
+ // it for closures of top-level expressions?
+ // (We can't easily do it for local closures
+ // because the surrounding scopes must reflect
+ // the exact position where the closure appears
+ // in the source; e.g., variables declared below
+ // must not be visible).
check.funcBody(check.decl, "", sig, e.Body)
x.mode = value
x.typ = sig
elems map[string]Object // lazily allocated
pos, end token.Pos // scope extent; may be invalid
comment string // for debugging only
+ isFunc bool // set if this is a function scope (internal use only)
}
// NewScope returns a new, empty scope contained in the given parent
// scope, if any. The comment is for debugging only.
func NewScope(parent *Scope, pos, end token.Pos, comment string) *Scope {
- s := &Scope{parent, nil, nil, pos, end, comment}
+ s := &Scope{parent, nil, nil, pos, end, comment, false}
// don't add children to Universe scope!
if parent != nil && parent != Universe {
parent.children = append(parent.children, s)
}
for _, scope := range scope.children {
- check.usage(scope)
+ // Don't go inside closure scopes a second time;
+ // they are handled explicitly by funcBody.
+ if !scope.isFunc {
+ check.usage(scope)
+ }
}
}
return
}
+// Unused variables in closures must lead to only one error (issue #22524).
+func _() {
+ _ = func() {
+ var x /* ERROR declared but not used */ int
+ }
+}
+
// Invalid (unused) expressions must not lead to spurious "declared but not used errors"
func _() {
var a, b, c int
// funcType type-checks a function or method type.
func (check *Checker) funcType(sig *Signature, recvPar *ast.FieldList, ftyp *ast.FuncType) {
scope := NewScope(check.scope, token.NoPos, token.NoPos, "function")
+ scope.isFunc = true
check.recordScope(ftyp, scope)
recvList, _ := check.collectParams(scope, recvPar, false)