]> Cypherpunks.ru repositories - gostls13.git/blobdiff - src/cmd/compile/internal/types2/resolver.go
go/types, types2: introduce _Alias type node
[gostls13.git] / src / cmd / compile / internal / types2 / resolver.go
index b116888bf239115acc5d6c3712adadd235d5838c..e074b7548c05c0a5ac8bcdb48b88ffe445bfaa0b 100644 (file)
@@ -1,4 +1,3 @@
-// UNREVIEWED
 // Copyright 2013 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.
@@ -9,6 +8,7 @@ import (
        "cmd/compile/internal/syntax"
        "fmt"
        "go/constant"
+       . "internal/types/errors"
        "sort"
        "strconv"
        "strings"
@@ -17,12 +17,13 @@ import (
 
 // A declInfo describes a package-level const, type, var, or func declaration.
 type declInfo struct {
-       file  *Scope           // scope of file containing this declaration
-       lhs   []*Var           // lhs of n:1 variable declarations, or nil
-       vtyp  syntax.Expr      // type, or nil (for const and var declarations only)
-       init  syntax.Expr      // init/orig expression, or nil (for const and var declarations only)
-       tdecl *syntax.TypeDecl // type declaration, or nil
-       fdecl *syntax.FuncDecl // func declaration, or nil
+       file      *Scope           // scope of file containing this declaration
+       lhs       []*Var           // lhs of n:1 variable declarations, or nil
+       vtyp      syntax.Expr      // type, or nil (for const and var declarations only)
+       init      syntax.Expr      // init/orig expression, or nil (for const and var declarations only)
+       inherited bool             // if set, the init expression is inherited from a previous constant declaration
+       tdecl     *syntax.TypeDecl // type declaration, or nil
+       fdecl     *syntax.FuncDecl // func declaration, or nil
 
        // The deps field tracks initialization expression dependencies.
        deps map[Object]bool // lazily initialized
@@ -52,17 +53,18 @@ func (check *Checker) arity(pos syntax.Pos, names []*syntax.Name, inits []syntax
        l := len(names)
        r := len(inits)
 
+       const code = WrongAssignCount
        switch {
        case l < r:
                n := inits[l]
                if inherited {
-                       check.errorf(pos, "extra init expr at %s", n.Pos())
+                       check.errorf(pos, code, "extra init expr at %s", n.Pos())
                } else {
-                       check.errorf(n, "extra init expr %s", n)
+                       check.errorf(n, code, "extra init expr %s", n)
                }
        case l > r && (constDecl || r != 1): // if r == 1 it may be a multi-valued function and we can't say anything yet
                n := names[r]
-               check.errorf(n, "missing init expr for %s", n.Value)
+               check.errorf(n, code, "missing init expr for %s", n.Value)
        }
 }
 
@@ -91,14 +93,14 @@ func (check *Checker) declarePkgObj(ident *syntax.Name, obj Object, d *declInfo)
        // spec: "A package-scope or file-scope identifier with name init
        // may only be declared to be a function with this (func()) signature."
        if ident.Value == "init" {
-               check.errorf(ident, "cannot declare init - must be func")
+               check.error(ident, InvalidInitDecl, "cannot declare init - must be func")
                return
        }
 
        // spec: "The main package must have package name main and declare
        // a function main that takes no arguments and returns no value."
        if ident.Value == "main" && check.pkg.name == "main" {
-               check.errorf(ident, "cannot declare main - must be func")
+               check.error(ident, InvalidMainDecl, "cannot declare main - must be func")
                return
        }
 
@@ -158,7 +160,7 @@ func (check *Checker) importPackage(pos syntax.Pos, path, dir string) *Package {
                        imp = nil // create fake package below
                }
                if err != nil {
-                       check.errorf(pos, "could not import %s (%s)", path, err)
+                       check.errorf(pos, BrokenImport, "could not import %s (%s)", path, err)
                        if imp == nil {
                                // create a new fake package
                                // come up with a sensible package name (heuristic)
@@ -179,7 +181,12 @@ func (check *Checker) importPackage(pos syntax.Pos, path, dir string) *Package {
        // package should be complete or marked fake, but be cautious
        if imp.complete || imp.fake {
                check.impMap[key] = imp
-               check.pkgCnt[imp.name]++
+               // Once we've formatted an error message, keep the pkgPathMap
+               // up-to-date on subsequent imports. It is used for package
+               // qualification in error messages.
+               if check.pkgPathMap != nil {
+                       check.markImports(imp)
+               }
                return imp
        }
 
@@ -216,7 +223,7 @@ func (check *Checker) collectObjects() {
                // but there is no corresponding package object.
                check.recordDef(file.PkgName, nil)
 
-               fileScope := NewScope(check.pkg.scope, startPos(file), endPos(file), check.filename(fileNo))
+               fileScope := NewScope(pkg.scope, syntax.StartPos(file), syntax.EndPos(file), check.filename(fileNo))
                fileScopes = append(fileScopes, fileScope)
                check.recordScope(file, fileScope)
 
@@ -235,9 +242,12 @@ func (check *Checker) collectObjects() {
                        switch s := decl.(type) {
                        case *syntax.ImportDecl:
                                // import package
+                               if s.Path == nil || s.Path.Bad {
+                                       continue // error reported during parsing
+                               }
                                path, err := validatedImportPath(s.Path.Value)
                                if err != nil {
-                                       check.errorf(s.Path, "invalid import path (%s)", err)
+                                       check.errorf(s.Path, BadImportPath, "invalid import path (%s)", err)
                                        continue
                                }
 
@@ -246,72 +256,84 @@ func (check *Checker) collectObjects() {
                                        continue
                                }
 
-                               // add package to list of explicit imports
-                               // (this functionality is provided as a convenience
-                               // for clients; it is not needed for type-checking)
-                               if !pkgImports[imp] {
-                                       pkgImports[imp] = true
-                                       pkg.imports = append(pkg.imports, imp)
-                               }
-
                                // local name overrides imported package name
                                name := imp.name
                                if s.LocalPkgName != nil {
                                        name = s.LocalPkgName.Value
                                        if path == "C" {
-                                               // match cmd/compile (not prescribed by spec)
-                                               check.errorf(s.LocalPkgName, `cannot rename import "C"`)
-                                               continue
-                                       }
-                                       if name == "init" {
-                                               check.errorf(s.LocalPkgName, "cannot declare init - must be func")
+                                               // match 1.17 cmd/compile (not prescribed by spec)
+                                               check.error(s.LocalPkgName, ImportCRenamed, `cannot rename import "C"`)
                                                continue
                                        }
                                }
 
-                               obj := NewPkgName(s.Pos(), pkg, name, imp)
+                               if name == "init" {
+                                       check.error(s, InvalidInitDecl, "cannot import package as init - init must be a func")
+                                       continue
+                               }
+
+                               // add package to list of explicit imports
+                               // (this functionality is provided as a convenience
+                               // for clients; it is not needed for type-checking)
+                               if !pkgImports[imp] {
+                                       pkgImports[imp] = true
+                                       pkg.imports = append(pkg.imports, imp)
+                               }
+
+                               pkgName := NewPkgName(s.Pos(), pkg, name, imp)
                                if s.LocalPkgName != nil {
                                        // in a dot-import, the dot represents the package
-                                       check.recordDef(s.LocalPkgName, obj)
+                                       check.recordDef(s.LocalPkgName, pkgName)
                                } else {
-                                       check.recordImplicit(s, obj)
+                                       check.recordImplicit(s, pkgName)
                                }
 
-                               if path == "C" {
-                                       // match cmd/compile (not prescribed by spec)
-                                       obj.used = true
+                               if imp.fake {
+                                       // match 1.17 cmd/compile (not prescribed by spec)
+                                       pkgName.used = true
                                }
 
                                // add import to file scope
+                               check.imports = append(check.imports, pkgName)
                                if name == "." {
+                                       // dot-import
+                                       if check.dotImportMap == nil {
+                                               check.dotImportMap = make(map[dotImportKey]*PkgName)
+                                       }
                                        // merge imported scope with file scope
-                                       for _, obj := range imp.scope.elems {
+                                       for name, obj := range imp.scope.elems {
+                                               // Note: Avoid eager resolve(name, obj) here, so we only
+                                               // resolve dot-imported objects as needed.
+
                                                // A package scope may contain non-exported objects,
                                                // do not import them!
-                                               if obj.Exported() {
+                                               if isExported(name) {
                                                        // declare dot-imported object
                                                        // (Do not use check.declare because it modifies the object
                                                        // via Object.setScopePos, which leads to a race condition;
                                                        // the object may be imported into more than one file scope
-                                                       // concurrently. See issue #32154.)
-                                                       if alt := fileScope.Insert(obj); alt != nil {
-                                                               check.errorf(s.LocalPkgName, "%s redeclared in this block", obj.Name())
-                                                               check.reportAltDecl(alt)
+                                                       // concurrently. See go.dev/issue/32154.)
+                                                       if alt := fileScope.Lookup(name); alt != nil {
+                                                               var err error_
+                                                               err.code = DuplicateDecl
+                                                               err.errorf(s.LocalPkgName, "%s redeclared in this block", alt.Name())
+                                                               err.recordAltDecl(alt)
+                                                               check.report(&err)
+                                                       } else {
+                                                               fileScope.insert(name, obj)
+                                                               check.dotImportMap[dotImportKey{fileScope, name}] = pkgName
                                                        }
                                                }
                                        }
-                                       // add position to set of dot-import positions for this file
-                                       // (this is only needed for "imported but not used" errors)
-                                       check.addUnusedDotImport(fileScope, imp, s.Pos())
                                } else {
                                        // declare imported package object in file scope
                                        // (no need to provide s.LocalPkgName since we called check.recordDef earlier)
-                                       check.declare(fileScope, nil, obj, nopos)
+                                       check.declare(fileScope, nil, pkgName, nopos)
                                }
 
                        case *syntax.ConstDecl:
                                // iota is the index of the current constDecl within the group
-                               if first < 0 || file.DeclList[index-1].(*syntax.ConstDecl).Group != s.Group {
+                               if first < 0 || s.Group == nil || file.DeclList[index-1].(*syntax.ConstDecl).Group != s.Group {
                                        first = index
                                        last = nil
                                }
@@ -329,7 +351,7 @@ func (check *Checker) collectObjects() {
                                }
 
                                // declare all constants
-                               values := unpackExpr(last.Values)
+                               values := syntax.UnpackListExpr(last.Values)
                                for i, name := range s.NameList {
                                        obj := NewConst(name.Pos(), pkg, name.Value, nil, iota)
 
@@ -338,7 +360,7 @@ func (check *Checker) collectObjects() {
                                                init = values[i]
                                        }
 
-                                       d := &declInfo{file: fileScope, vtyp: last.Type, init: init}
+                                       d := &declInfo{file: fileScope, vtyp: last.Type, init: init, inherited: inherited}
                                        check.declarePkgObj(name, obj, d)
                                }
 
@@ -360,7 +382,7 @@ func (check *Checker) collectObjects() {
                                }
 
                                // declare all variables
-                               values := unpackExpr(s.Values)
+                               values := syntax.UnpackListExpr(s.Values)
                                for i, name := range s.NameList {
                                        obj := NewVar(name.Pos(), pkg, name.Value, nil)
                                        lhs[i] = obj
@@ -384,51 +406,55 @@ func (check *Checker) collectObjects() {
                                }
 
                        case *syntax.TypeDecl:
+                               _ = len(s.TParamList) != 0 && check.verifyVersionf(s.TParamList[0], go1_18, "type parameter")
                                obj := NewTypeName(s.Name.Pos(), pkg, s.Name.Value, nil)
                                check.declarePkgObj(s.Name, obj, &declInfo{file: fileScope, tdecl: s})
 
                        case *syntax.FuncDecl:
-                               d := s // TODO(gri) get rid of this
-                               name := d.Name.Value
-                               obj := NewFunc(d.Name.Pos(), pkg, name, nil)
-                               if d.Recv == nil {
+                               name := s.Name.Value
+                               obj := NewFunc(s.Name.Pos(), pkg, name, nil)
+                               hasTParamError := false // avoid duplicate type parameter errors
+                               if s.Recv == nil {
                                        // regular function
-                                       if name == "init" {
-                                               if d.TParamList != nil {
-                                                       //check.softErrorf(d.TParamList.Pos(), "func init must have no type parameters")
-                                                       check.softErrorf(d.Name, "func init must have no type parameters")
+                                       if name == "init" || name == "main" && pkg.name == "main" {
+                                               code := InvalidInitDecl
+                                               if name == "main" {
+                                                       code = InvalidMainDecl
                                                }
-                                               if t := d.Type; len(t.ParamList) != 0 || len(t.ResultList) != 0 {
-                                                       check.softErrorf(d, "func init must have no arguments and no return values")
+                                               if len(s.TParamList) != 0 {
+                                                       check.softErrorf(s.TParamList[0], code, "func %s must have no type parameters", name)
+                                                       hasTParamError = true
                                                }
-                                               // don't declare init functions in the package scope - they are invisible
+                                               if t := s.Type; len(t.ParamList) != 0 || len(t.ResultList) != 0 {
+                                                       check.softErrorf(s.Name, code, "func %s must have no arguments and no return values", name)
+                                               }
+                                       }
+                                       // don't declare init functions in the package scope - they are invisible
+                                       if name == "init" {
                                                obj.parent = pkg.scope
-                                               check.recordDef(d.Name, obj)
+                                               check.recordDef(s.Name, obj)
                                                // init functions must have a body
-                                               if d.Body == nil {
+                                               if s.Body == nil {
                                                        // TODO(gri) make this error message consistent with the others above
-                                                       check.softErrorf(obj.pos, "missing function body")
+                                                       check.softErrorf(obj.pos, MissingInitBody, "missing function body")
                                                }
                                        } else {
-                                               check.declare(pkg.scope, d.Name, obj, nopos)
+                                               check.declare(pkg.scope, s.Name, obj, nopos)
                                        }
                                } else {
                                        // method
                                        // d.Recv != nil
-                                       if !methodTypeParamsOk && len(d.TParamList) != 0 {
-                                               //check.invalidASTf(d.TParamList.Pos(), "method must have no type parameters")
-                                               check.invalidASTf(d, "method must have no type parameters")
-                                       }
-                                       ptr, recv, _ := check.unpackRecv(d.Recv.Type, false)
-                                       // (Methods with invalid receiver cannot be associated to a type, and
+                                       ptr, recv, _ := check.unpackRecv(s.Recv.Type, false)
+                                       // Methods with invalid receiver cannot be associated to a type, and
                                        // methods with blank _ names are never found; no need to collect any
-                                       // of them. They will still be type-checked with all the other functions.)
+                                       // of them. They will still be type-checked with all the other functions.
                                        if recv != nil && name != "_" {
                                                methods = append(methods, methodInfo{obj, ptr, recv})
                                        }
-                                       check.recordDef(d.Name, obj)
+                                       check.recordDef(s.Name, obj)
                                }
-                               info := &declInfo{file: fileScope, fdecl: d}
+                               _ = len(s.TParamList) != 0 && !hasTParamError && check.verifyVersionf(s.TParamList[0], go1_18, "type parameter")
+                               info := &declInfo{file: fileScope, fdecl: s}
                                // Methods are not package-level objects but we still track them in the
                                // object map so that we can handle them like regular functions (if the
                                // receiver is invalid); also we need their fdecl info when associating
@@ -437,23 +463,27 @@ func (check *Checker) collectObjects() {
                                obj.setOrder(uint32(len(check.objMap)))
 
                        default:
-                               check.invalidASTf(s, "unknown syntax.Decl node %T", s)
+                               check.errorf(s, InvalidSyntaxTree, "unknown syntax.Decl node %T", s)
                        }
                }
        }
 
        // verify that objects in package and file scopes have different names
        for _, scope := range fileScopes {
-               for _, obj := range scope.elems {
-                       if alt := pkg.scope.Lookup(obj.Name()); alt != nil {
+               for name, obj := range scope.elems {
+                       if alt := pkg.scope.Lookup(name); alt != nil {
+                               obj = resolve(name, obj)
+                               var err error_
+                               err.code = DuplicateDecl
                                if pkg, ok := obj.(*PkgName); ok {
-                                       check.errorf(alt, "%s already declared through import of %s", alt.Name(), pkg.Imported())
-                                       check.reportAltDecl(pkg)
+                                       err.errorf(alt, "%s already declared through import of %s", alt.Name(), pkg.Imported())
+                                       err.recordAltDecl(pkg)
                                } else {
-                                       check.errorf(alt, "%s already declared through dot-import of %s", alt.Name(), obj.Pkg())
-                                       // TODO(gri) dot-imported objects don't have a position; reportAltDecl won't print anything
-                                       check.reportAltDecl(obj)
+                                       err.errorf(alt, "%s already declared through dot-import of %s", alt.Name(), obj.Pkg())
+                                       // TODO(gri) dot-imported objects don't have a position; recordAltDecl won't print anything
+                                       err.recordAltDecl(obj)
                                }
+                               check.report(&err)
                        }
                }
        }
@@ -467,9 +497,9 @@ func (check *Checker) collectObjects() {
                for i := range methods {
                        m := &methods[i]
                        // Determine the receiver base type and associate m with it.
-                       ptr, base := check.resolveBaseTypeName(m.ptr, m.recv)
+                       ptr, base := check.resolveBaseTypeName(m.ptr, m.recv, fileScopes)
                        if base != nil {
-                               m.obj.hasPtrRecv = ptr
+                               m.obj.hasPtrRecv_ = ptr
                                check.methods[base] = append(check.methods[base], m.obj)
                        }
                }
@@ -491,11 +521,13 @@ L: // unpack receiver type
                case *syntax.ParenExpr:
                        rtyp = t.X
                // case *ast.StarExpr:
+               //      ptr = true
                //      rtyp = t.X
                case *syntax.Operation:
                        if t.Op != syntax.Mul || t.Y != nil {
                                break
                        }
+                       ptr = true
                        rtyp = t.X
                default:
                        break L
@@ -506,7 +538,7 @@ L: // unpack receiver type
        if ptyp, _ := rtyp.(*syntax.IndexExpr); ptyp != nil {
                rtyp = ptyp.X
                if unpackParams {
-                       for _, arg := range unpackExpr(ptyp.Index) {
+                       for _, arg := range syntax.UnpackListExpr(ptyp.Index) {
                                var par *syntax.Name
                                switch arg := arg.(type) {
                                case *syntax.Name:
@@ -514,12 +546,12 @@ L: // unpack receiver type
                                case *syntax.BadExpr:
                                        // ignore - error already reported by parser
                                case nil:
-                                       check.invalidASTf(ptyp, "parameterized receiver contains nil parameters")
+                                       check.error(ptyp, InvalidSyntaxTree, "parameterized receiver contains nil parameters")
                                default:
-                                       check.errorf(arg, "receiver type parameter %s must be an identifier", arg)
+                                       check.errorf(arg, BadDecl, "receiver type parameter %s must be an identifier", arg)
                                }
                                if par == nil {
-                                       par = newName(arg.Pos(), "_")
+                                       par = syntax.NewName(arg.Pos(), "_")
                                }
                                tparams = append(tparams, par)
                        }
@@ -539,7 +571,7 @@ L: // unpack receiver type
 // there was a pointer indirection to get to it. The base type name must be declared
 // in package scope, and there can be at most one pointer indirection. If no such type
 // name exists, the returned base is nil.
-func (check *Checker) resolveBaseTypeName(seenPtr bool, typ syntax.Expr) (ptr bool, base *TypeName) {
+func (check *Checker) resolveBaseTypeName(seenPtr bool, typ syntax.Expr, fileScopes []*Scope) (ptr bool, base *TypeName) {
        // Algorithm: Starting from a type expression, which may be a name,
        // we follow that type through alias declarations until we reach a
        // non-alias type name. If we encounter anything but pointer types or
@@ -548,8 +580,6 @@ func (check *Checker) resolveBaseTypeName(seenPtr bool, typ syntax.Expr) (ptr bo
        ptr = seenPtr
        var seen map[*TypeName]bool
        for {
-               typ = unparen(typ)
-
                // check if we have a pointer type
                // if pexpr, _ := typ.(*ast.StarExpr); pexpr != nil {
                if pexpr, _ := typ.(*syntax.Operation); pexpr != nil && pexpr.Op == syntax.Mul && pexpr.Y == nil {
@@ -558,18 +588,46 @@ func (check *Checker) resolveBaseTypeName(seenPtr bool, typ syntax.Expr) (ptr bo
                                return false, nil
                        }
                        ptr = true
-                       typ = unparen(pexpr.X) // continue with pointer base type
+                       typ = syntax.Unparen(pexpr.X) // continue with pointer base type
                }
 
-               // typ must be a name
-               name, _ := typ.(*syntax.Name)
-               if name == nil {
+               // typ must be a name, or a C.name cgo selector.
+               var name string
+               switch typ := typ.(type) {
+               case *syntax.Name:
+                       name = typ.Value
+               case *syntax.SelectorExpr:
+                       // C.struct_foo is a valid type name for packages using cgo.
+                       //
+                       // Detect this case, and adjust name so that the correct TypeName is
+                       // resolved below.
+                       if ident, _ := typ.X.(*syntax.Name); ident != nil && ident.Value == "C" {
+                               // Check whether "C" actually resolves to an import of "C", by looking
+                               // in the appropriate file scope.
+                               var obj Object
+                               for _, scope := range fileScopes {
+                                       if scope.Contains(ident.Pos()) {
+                                               obj = scope.Lookup(ident.Value)
+                                       }
+                               }
+                               // If Config.go115UsesCgo is set, the typechecker will resolve Cgo
+                               // selectors to their cgo name. We must do the same here.
+                               if pname, _ := obj.(*PkgName); pname != nil {
+                                       if pname.imported.cgo { // only set if Config.go115UsesCgo is set
+                                               name = "_Ctype_" + typ.Sel.Value
+                                       }
+                               }
+                       }
+                       if name == "" {
+                               return false, nil
+                       }
+               default:
                        return false, nil
                }
 
                // name must denote an object found in the current package scope
                // (note that dot-imported objects are not in the package scope!)
-               obj := check.pkg.scope.Lookup(name.Value)
+               obj := check.pkg.scope.Lookup(name)
                if obj == nil {
                        return false, nil
                }
@@ -619,26 +677,39 @@ func (check *Checker) packageObjects() {
                }
        }
 
-       // We process non-alias declarations first, in order to avoid situations where
-       // the type of an alias declaration is needed before it is available. In general
-       // this is still not enough, as it is possible to create sufficiently convoluted
-       // recursive type definitions that will cause a type alias to be needed before it
-       // is available (see issue #25838 for examples).
-       // As an aside, the cmd/compiler suffers from the same problem (#25838).
-       var aliasList []*TypeName
-       // phase 1
-       for _, obj := range objList {
-               // If we have a type alias, collect it for the 2nd phase.
-               if tname, _ := obj.(*TypeName); tname != nil && check.objMap[tname].tdecl.Alias {
-                       aliasList = append(aliasList, tname)
-                       continue
+       if check.conf._EnableAlias {
+               // With _Alias nodes we can process declarations in any order.
+               for _, obj := range objList {
+                       check.objDecl(obj, nil)
+               }
+       } else {
+               // Without _Alias nodes, we process non-alias type declarations first, followed by
+               // alias declarations, and then everything else. This appears to avoid most situations
+               // where the type of an alias is needed before it is available.
+               // There may still be cases where this is not good enough (see also go.dev/issue/25838).
+               // In those cases Checker.ident will report an error ("invalid use of type alias").
+               var aliasList []*TypeName
+               var othersList []Object // everything that's not a type
+               // phase 1: non-alias type declarations
+               for _, obj := range objList {
+                       if tname, _ := obj.(*TypeName); tname != nil {
+                               if check.objMap[tname].tdecl.Alias {
+                                       aliasList = append(aliasList, tname)
+                               } else {
+                                       check.objDecl(obj, nil)
+                               }
+                       } else {
+                               othersList = append(othersList, obj)
+                       }
+               }
+               // phase 2: alias type declarations
+               for _, obj := range aliasList {
+                       check.objDecl(obj, nil)
+               }
+               // phase 3: all other declarations
+               for _, obj := range othersList {
+                       check.objDecl(obj, nil)
                }
-
-               check.objDecl(obj, nil)
-       }
-       // phase 2
-       for _, obj := range aliasList {
-               check.objDecl(obj, nil)
        }
 
        // At this point we may have a non-empty check.methods map; this means that not all
@@ -657,7 +728,7 @@ func (a inSourceOrder) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
 
 // unusedImports checks for unused imports.
 func (check *Checker) unusedImports() {
-       // if function bodies are not checked, packages' uses are likely missing - don't check
+       // If function bodies are not checked, packages' uses are likely missing - don't check.
        if check.conf.IgnoreFuncBodies {
                return
        }
@@ -666,39 +737,30 @@ func (check *Checker) unusedImports() {
        // any of its exported identifiers. To import a package solely for its side-effects
        // (initialization), use the blank identifier as explicit package name."
 
-       // check use of regular imported packages
-       for _, scope := range check.pkg.scope.children /* file scopes */ {
-               for _, obj := range scope.elems {
-                       if obj, ok := obj.(*PkgName); ok {
-                               // Unused "blank imports" are automatically ignored
-                               // since _ identifiers are not entered into scopes.
-                               if !obj.used {
-                                       path := obj.imported.path
-                                       base := pkgName(path)
-                                       if obj.name == base {
-                                               check.softErrorf(obj.pos, "%q imported but not used", path)
-                                       } else {
-                                               check.softErrorf(obj.pos, "%q imported but not used as %s", path, obj.name)
-                                       }
-                               }
-                       }
-               }
-       }
-
-       // check use of dot-imported packages
-       for _, unusedDotImports := range check.unusedDotImports {
-               for pkg, pos := range unusedDotImports {
-                       check.softErrorf(pos, "%q imported but not used", pkg.path)
+       for _, obj := range check.imports {
+               if !obj.used && obj.name != "_" {
+                       check.errorUnusedPkg(obj)
                }
        }
 }
 
-// pkgName returns the package name (last element) of an import path.
-func pkgName(path string) string {
-       if i := strings.LastIndex(path, "/"); i >= 0 {
-               path = path[i+1:]
+func (check *Checker) errorUnusedPkg(obj *PkgName) {
+       // If the package was imported with a name other than the final
+       // import path element, show it explicitly in the error message.
+       // Note that this handles both renamed imports and imports of
+       // packages containing unconventional package declarations.
+       // Note that this uses / always, even on Windows, because Go import
+       // paths always use forward slashes.
+       path := obj.imported.path
+       elem := path
+       if i := strings.LastIndex(elem, "/"); i >= 0 {
+               elem = elem[i+1:]
+       }
+       if obj.name == "" || obj.name == "." || obj.name == elem {
+               check.softErrorf(obj, UnusedImport, "%q imported and not used", path)
+       } else {
+               check.softErrorf(obj, UnusedImport, "%q imported as %s and not used", path, obj.name)
        }
-       return path
 }
 
 // dir makes a good-faith attempt to return the directory