internal/fetch: fix remove-nodes check for builtin

We want to remove unused AST nodes for every package except
"builtin". But we had the test reversed: we were removing
only "builtin".

This caused a bug to surface in AST encoding.

Change-Id: I5d2ac5a81f3c753ec72eb1f22312774fd79185cb
Reviewed-on: https://go-review.googlesource.com/c/pkgsite/+/260517
Trust: Jonathan Amsterdam <jba@google.com>
Run-TryBot: Jonathan Amsterdam <jba@google.com>
Reviewed-by: Julie Qiu <julie@golang.org>
diff --git a/internal/fetch/load.go b/internal/fetch/load.go
index d210bb8..3a19924 100644
--- a/internal/fetch/load.go
+++ b/internal/fetch/load.go
@@ -114,7 +114,7 @@
 			removeNodes = true
 			// Don't strip the seemingly unexported functions from the builtin package;
 			// they are actually Go builtins like make, new, etc.
-			if !(modulePath == stdlib.ModulePath && innerPath == "builtin") {
+			if modulePath == stdlib.ModulePath && innerPath == "builtin" {
 				removeNodes = false
 			}
 		}
diff --git a/internal/godoc/encode.go b/internal/godoc/encode.go
index d0c7c32..639710b 100644
--- a/internal/godoc/encode.go
+++ b/internal/godoc/encode.go
@@ -208,11 +208,15 @@
 		if !ok {
 			panic(fmt.Sprintf("no number for Object %v", id.Obj))
 		}
-		d, ok := declNums[id.Obj.Decl]
-		if !ok && isRelevantDecl(id.Obj.Decl) {
-			panic(fmt.Sprintf("no number for Decl %v", id.Obj.Decl))
+		if d, ok := declNums[id.Obj.Decl]; ok {
+			id.Obj.Decl = d
+		} else {
+			// We may not have seen this Ident's Decl because the definition was
+			// removed from the AST, even though references remain. For example,
+			// an exported var initialized to a call of an unexported function.
+			// Ignore those by setting the Decl field to -1.
+			id.Obj.Decl = -1
 		}
-		id.Obj.Decl = d
 		return true
 	})
 
@@ -283,7 +287,10 @@
 		case num == len(objs):
 			// A new object; fix it up and remember it.
 			if obj.Decl != nil {
-				obj.Decl = decls[obj.Decl.(int)]
+				num := obj.Decl.(int)
+				if num >= 0 {
+					obj.Decl = decls[num]
+				}
 			}
 			objs = append(objs, obj)
 		case num > len(objs):
diff --git a/internal/godoc/testdata/p/p.go b/internal/godoc/testdata/p/p.go
index 8c873aa..5893256 100644
--- a/internal/godoc/testdata/p/p.go
+++ b/internal/godoc/testdata/p/p.go
@@ -15,7 +15,7 @@
 const C = 1
 
 // var
-var V = 2
+var V = unexp()
 
 // exported func
 func F(t time.Time) {