tools/trim: prevent nil-pointer panic

Fixes #1087

Change-Id: I471969c6f75361e39f706083eb23a0b005be92ad
Signed-off-by: Marcel van Lohuizen <mpvl@golang.org>
Reviewed-on: https://review.gerrithub.io/c/cue-lang/cue/+/532314
Unity-Result: CUEcueckoo <cueckoo@cuelang.org>
TryBot-Result: CUEcueckoo <cueckoo@cuelang.org>
Reviewed-by: Marcel van Lohuizen <mpvl@gmail.com>
diff --git a/tools/trim/testdata/issue1087.txtar b/tools/trim/testdata/issue1087.txtar
new file mode 100644
index 0000000..d33bc00
--- /dev/null
+++ b/tools/trim/testdata/issue1087.txtar
@@ -0,0 +1,28 @@
+#Issue: 1087
+-- in.cue --
+configs: {
+	key: 123
+}
+
+shared: {
+	param: string
+	derived: configs[param]
+}
+
+a: shared & {
+	param: "key"
+}
+-- out/trim --
+== in.cue
+configs: {
+	key: 123
+}
+
+shared: {
+	param:   string
+	derived: configs[param]
+}
+
+a: shared & {
+	param: "key"
+}
diff --git a/tools/trim/trim.go b/tools/trim/trim.go
index cff7543..67b5c95 100644
--- a/tools/trim/trim.go
+++ b/tools/trim/trim.go
@@ -216,7 +216,7 @@
 			if r, ok := c.Expr().(adt.Resolver); ok {
 				x, _ := t.ctx.Resolve(c.Env, r)
 				// Even if this is not a dominator now, descendants will be.
-				if x.Label.IsDef() {
+				if x != nil && x.Label.IsDef() {
 					for _, c := range x.Conjuncts {
 						doms.AddConjunct(c)
 					}