cue: fix crash related to package name
commit 3908dac7f8b inadvertently
tried to resolve the package name
as an identifier.
This resulted in a crash if there was an
imported package with the same name.
Also catch duplicate package declarations
as an error, which previous went unreported.
Change-Id: I4fcd5f2144d434f4fa4850d4987b75f7d85f13ad
Reviewed-on: https://cue-review.googlesource.com/c/cue/+/2878
Reviewed-by: Marcel van Lohuizen <mpvl@golang.org>
diff --git a/cue/ast.go b/cue/ast.go
index 4c2dcf7..3bf6798 100644
--- a/cue/ast.go
+++ b/cue/ast.go
@@ -205,7 +205,8 @@
ret = obj
case *ast.Package:
- v.walk(n.Name)
+ // NOTE: Do NOT walk the identifier of the package here, as it is not
+ // supposed to resolve to anything.
case *ast.ImportDecl:
for _, s := range n.Specs {
diff --git a/cue/ast_test.go b/cue/ast_test.go
index 5fa74fb..0719f1b 100644
--- a/cue/ast_test.go
+++ b/cue/ast_test.go
@@ -16,6 +16,7 @@
import (
"bytes"
+ "strings"
"testing"
"cuelang.org/go/cue/errors"
@@ -381,3 +382,54 @@
})
}
}
+
+func TestResolution(t *testing.T) {
+ testCases := []struct {
+ name string
+ in string
+ err string
+ }{{
+ name: "package name identifier should not resolve to anything",
+ in: `package time
+
+ import "time"
+
+ a: time.Time
+ `,
+ }, {
+ name: "duplicate_imports.cue",
+ in: `
+ import "time"
+ import time "math"
+
+ t: time.Time
+ `,
+ err: "time redeclared as imported package name",
+ }, {
+ name: "unused_import",
+ in: `
+ import "time"
+ `,
+ err: `imported and not used: "time"`,
+ }, {
+ name: "nonexisting import package",
+ in: `import "doesnotexist"`,
+ err: `package "doesnotexist" not found`,
+ }}
+ for _, tc := range testCases {
+ t.Run(tc.name, func(t *testing.T) {
+ var r Runtime
+ _, err := r.Compile(tc.name, tc.in)
+ got := err == nil
+ want := tc.err == ""
+ if got != want {
+ t.Fatalf("got %v; want %v", err, tc.err)
+ }
+ if err != nil {
+ if s := err.Error(); !strings.Contains(s, tc.err) {
+ t.Errorf("got %v; want %v", err, tc.err)
+ }
+ }
+ })
+ }
+}
diff --git a/cue/build.go b/cue/build.go
index c527847..356046d 100644
--- a/cue/build.go
+++ b/cue/build.go
@@ -391,6 +391,7 @@
"%s redeclared as imported package name\n"+
"\tprevious declaration at %v", name, lineStr(idx, n))
}
+ fields[name] = spec
used := false
for _, u := range index[name] {
used = true