go/packages: add a workaround for different import stacks between go versions

Go 1.15+, as of CL 224660, puts the importing package on the top of the stack
(because it makes more sense in the errors). Look there by default and fall
back to second from top position if top of stack is the package itself.

Updates golang/go#36173

Change-Id: I1681089b4a18af9e535661668329ad32b1ba1936
Reviewed-on: https://go-review.googlesource.com/c/tools/+/225677
Run-TryBot: Michael Matloob <matloob@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Bryan C. Mills <bcmills@google.com>
Reviewed-by: Rebecca Stambler <rstambler@golang.org>
diff --git a/go/packages/golist.go b/go/packages/golist.go
index b4a13ef..f378242 100644
--- a/go/packages/golist.go
+++ b/go/packages/golist.go
@@ -502,10 +502,19 @@
 					errkind = "use of internal package not allowed"
 				}
 				if errkind != "" {
-					if len(old.Error.ImportStack) < 2 {
-						return nil, fmt.Errorf(`internal error: go list gave a %q error with an import stack with fewer than two elements`, errkind)
+					if len(old.Error.ImportStack) < 1 {
+						return nil, fmt.Errorf(`internal error: go list gave a %q error with empty import stack`, errkind)
 					}
-					importingPkg := old.Error.ImportStack[len(old.Error.ImportStack)-2]
+					importingPkg := old.Error.ImportStack[len(old.Error.ImportStack)-1]
+					if importingPkg == old.ImportPath {
+						// Using an older version of Go which put this package itself on top of import
+						// stack, instead of the importer. Look for importer in second from top
+						// position.
+						if len(old.Error.ImportStack) < 2 {
+							return nil, fmt.Errorf(`internal error: go list gave a %q error with an import stack without importing package`, errkind)
+						}
+						importingPkg = old.Error.ImportStack[len(old.Error.ImportStack)-2]
+					}
 					additionalErrors[importingPkg] = append(additionalErrors[importingPkg], Error{
 						Pos:  old.Error.Pos,
 						Msg:  old.Error.Err,