cmd/cue/cmd: add fix command for new-style definitions

This adds a new fix command. As converting configurations to
new-style defintions can no longer be done syntactically and is
not guaranteed to succeed, this could no longer be piggybacked
on fmt.

This changes adds the implementation of converting new-style
definitions. The conversion is not complete. Firstly, not all
old configurations can be converted to new-style definitions.
The converter detects this and suggests changes to the user.

Also, due to API limitations, not all convertable cases are
handled by the converter. These cases are also detected and
reported.

Change-Id: I88c4010b15ea07250dc456fd84b2603b473ae5c1
Reviewed-on: https://cue-review.googlesource.com/c/cue/+/6067
Reviewed-by: Marcel van Lohuizen <mpvl@golang.org>
diff --git a/cmd/cue/cmd/fix.go b/cmd/cue/cmd/fix.go
index 99d87cd..be53700 100644
--- a/cmd/cue/cmd/fix.go
+++ b/cmd/cue/cmd/fix.go
@@ -16,15 +16,120 @@
 
 import (
 	"fmt"
+	"io/ioutil"
+	"os"
+	"path/filepath"
 	"strings"
 
 	"cuelang.org/go/cue/ast"
 	"cuelang.org/go/cue/ast/astutil"
+	"cuelang.org/go/cue/errors"
+	"cuelang.org/go/cue/format"
+	"cuelang.org/go/cue/load"
 	"cuelang.org/go/cue/parser"
 	"cuelang.org/go/cue/token"
 	"cuelang.org/go/internal"
+	"github.com/spf13/cobra"
 )
 
+func newFixCmd(c *Command) *cobra.Command {
+	cmd := &cobra.Command{
+		Use:   "fix [packages]",
+		Short: "rewrite packages to latest standards",
+		Long: `Fix finds CUE programs that use old syntax and old APIs and rewrites them to use newer ones.
+After you update to a new CUE release, fix helps make the necessary changes
+to your program.
+
+Without any packages, fix applies to all files within a module.
+`,
+		RunE: mkRunE(c, runFixAll),
+	}
+
+	cmd.Flags().BoolP(string(flagForce), "f", false,
+		"rewrite even when there are errors")
+
+	return cmd
+}
+
+func runFixAll(cmd *Command, args []string) error {
+	dir, err := os.Getwd()
+	if err != nil {
+		return err
+	}
+
+	if len(args) == 0 {
+		args = []string{"./..."}
+
+		for {
+			if fi, err := os.Stat(filepath.Join(dir, "cue.mod")); err == nil {
+				if fi.IsDir() {
+					args = appendDirs(args, filepath.Join(dir, "cue.mod", "gen"))
+					args = appendDirs(args, filepath.Join(dir, "cue.mod", "pkg"))
+					args = appendDirs(args, filepath.Join(dir, "cue.mod", "usr"))
+				} else {
+					args = appendDirs(args, filepath.Join(dir, "pkg"))
+				}
+				break
+			}
+
+			dir = filepath.Dir(dir)
+			if info, _ := os.Stat(dir); !info.IsDir() {
+				return errors.Newf(token.NoPos, "no module root found")
+			}
+		}
+	}
+
+	instances := load.Instances(args, &load.Config{})
+
+	for _, i := range instances {
+		if i.Err != nil {
+			return i.Err
+		}
+	}
+
+	errs := fixAll(instances)
+
+	if errs != nil && flagForce.Bool(cmd) {
+		return errs
+	}
+
+	done := map[*ast.File]bool{}
+
+	for _, i := range instances {
+		for _, f := range i.Files {
+			if done[f] || !strings.HasSuffix(f.Filename, ".cue") {
+				continue
+			}
+			done[f] = true
+
+			b, err := format.Node(f)
+			if err != nil {
+				errs = errors.Append(errs, errors.Promote(err, "format"))
+			}
+
+			err = ioutil.WriteFile(f.Filename, b, 0644)
+			if err != nil {
+				errs = errors.Append(errs, errors.Promote(err, "write"))
+			}
+		}
+	}
+
+	return errs
+}
+
+func appendDirs(a []string, base string) []string {
+	_ = filepath.Walk(base, func(path string, fi os.FileInfo, err error) error {
+		if err == nil && fi.IsDir() && path != base {
+			short := filepath.ToSlash(path[len(base)+1:])
+			if strings.ContainsAny(short, "/") {
+				a = append(a, short)
+			}
+		}
+		return nil
+	})
+	return a
+}
+
 func fix(f *ast.File) *ast.File {
 	// Isolate bulk optional fields into a single struct.
 	ast.Walk(f, func(n ast.Node) bool {
diff --git a/cmd/cue/cmd/fixall.go b/cmd/cue/cmd/fixall.go
new file mode 100644
index 0000000..87df949
--- /dev/null
+++ b/cmd/cue/cmd/fixall.go
@@ -0,0 +1,299 @@
+// Copyright 2020 CUE Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package cmd
+
+import (
+	"fmt"
+	"hash/fnv"
+	"strings"
+
+	"cuelang.org/go/cue"
+	"cuelang.org/go/cue/ast"
+	"cuelang.org/go/cue/ast/astutil"
+	"cuelang.org/go/cue/build"
+	"cuelang.org/go/cue/errors"
+	"cuelang.org/go/cue/format"
+	"cuelang.org/go/cue/token"
+	"cuelang.org/go/internal"
+)
+
+func fixAll(a []*build.Instance) errors.Error {
+	// Collect all
+	p := processor{
+		instances: a,
+
+		done:      map[ast.Node]bool{},
+		rename:    map[*ast.Ident]string{},
+		ambiguous: map[string][]token.Pos{},
+	}
+
+	p.visitAll(func(f *ast.File) { fix(f) })
+
+	instances := cue.Build(a)
+	p.updateValues(instances)
+	p.visitAll(p.tagAmbiguous)
+	p.rewriteIdents()
+	p.visitAll(p.renameFields)
+
+	return p.err
+}
+
+type processor struct {
+	instances []*build.Instance
+
+	done map[ast.Node]bool
+	// Evidence for rewrites. Rewrite in a later pass.
+	rename    map[*ast.Ident]string
+	ambiguous map[string][]token.Pos
+
+	stack []cue.Value
+
+	err errors.Error
+}
+
+func (p *processor) updateValues(instances []*cue.Instance) {
+	for _, inst := range instances {
+		inst.Value().Walk(p.visit, nil)
+	}
+}
+
+func (p *processor) visit(v cue.Value) bool {
+	if e, ok := v.Elem(); ok {
+		p.updateValue(e)
+		p.visit(e)
+	}
+
+	if v.Kind() != cue.StructKind {
+		p.updateValue(v)
+		return true
+	}
+
+	p.stack = append(p.stack, v)
+	defer func() { p.stack = p.stack[:len(p.stack)-1] }()
+
+	for it, _ := v.Fields(cue.All()); it.Next(); {
+		p.updateValue(it.Value())
+		p.visit(it.Value())
+	}
+
+	for _, kv := range v.BulkOptionals() {
+		p.updateValue(kv[0])
+		p.visit(kv[0])
+		p.updateValue(kv[1])
+		p.visit(kv[1])
+	}
+
+	return false
+}
+
+func (p *processor) updateValue(v cue.Value) cue.Value {
+	switch op, a := v.Expr(); op {
+	case cue.NoOp:
+		return v
+
+	case cue.SelectorOp:
+		v := p.updateValue(a[0])
+
+		switch x := a[1].Source().(type) {
+		case *ast.SelectorExpr:
+			return p.lookup(v, x.Sel)
+
+		case *ast.Ident:
+			v := p.updateValue(a[0])
+			return p.lookup(v, x)
+		}
+
+	default:
+		for _, v := range a {
+			p.updateValue(v)
+		}
+	}
+	return v
+}
+
+func (p *processor) lookup(v cue.Value, l ast.Expr) cue.Value {
+	label, ok := l.(ast.Label)
+	if !ok {
+		return cue.Value{}
+	}
+
+	name, isIdent, err := ast.LabelName(label)
+	if err != nil {
+		return cue.Value{}
+	}
+	f, err := v.FieldByName(name, isIdent)
+	if err != nil {
+		f := v.Template()
+		if f == nil {
+			return cue.Value{}
+		}
+		return v.Template()(name)
+	}
+
+	switch {
+	case !p.done[l]:
+		p.done[l] = true
+
+		if !f.IsDefinition {
+			break
+		}
+
+		if !ast.IsValidIdent(name) {
+			p.err = errors.Append(p.err, errors.Newf(
+				l.Pos(),
+				"cannot convert reference to definition with invalid identifier %q",
+				name))
+			break
+		}
+
+		if ident, ok := l.(*ast.Ident); ok && !internal.IsDef(name) {
+			p.rename[ident] = "#" + name
+		}
+	}
+
+	return f.Value
+}
+
+// tagAmbiguous marks identifier fields were not handled by the previous pass.
+// These can be identifiers within unused templates, for instance. It is
+// possible to do further resolution within templates, but for now we will
+// punt on this.
+func (p *processor) tagAmbiguous(f *ast.File) {
+	ast.Walk(f, p.tagRef, nil)
+}
+
+func (p *processor) tagRef(n ast.Node) bool {
+	switch x := n.(type) {
+	case *ast.Field:
+		ast.Walk(x.Value, p.tagRef, nil)
+
+		lab := x.Label
+		if a, ok := x.Label.(*ast.Alias); ok {
+			lab, _ = a.Expr.(ast.Label)
+		}
+
+		switch lab.(type) {
+		case *ast.Ident, *ast.BasicLit:
+		default: // list, paren, or interpolation
+			ast.Walk(lab, p.tagRef, nil)
+		}
+
+		return false
+
+	case *ast.Ident:
+		if _, ok := p.done[x]; !ok {
+			p.ambiguous[x.Name] = append(p.ambiguous[x.Name], x.Pos())
+		}
+		return false
+	}
+	return true
+}
+
+func (p *processor) rewriteIdents() {
+	for x, name := range p.rename {
+		x.Name = name
+	}
+}
+
+func (p *processor) renameFields(f *ast.File) {
+	hasErr := false
+	_ = astutil.Apply(f, func(c astutil.Cursor) bool {
+		switch x := c.Node().(type) {
+		case *ast.Field:
+			if x.Token != token.ISA {
+				return true
+			}
+
+			label, isIdent, err := ast.LabelName(x.Label)
+			if err != nil {
+				b, _ := format.Node(x.Label)
+				hasErr = true
+				p.err = errors.Append(p.err, errors.Newf(x.Pos(),
+					`cannot convert dynamic definition for '%s'`, string(b)))
+				return false
+			}
+
+			if !isIdent && !ast.IsValidIdent(label) {
+				hasErr = true
+				p.err = errors.Append(p.err, errors.Newf(x.Pos(),
+					`invalid identifier %q; definition must be valid label`, label))
+				return false
+			}
+
+			if refs, ok := p.ambiguous[label]; ok {
+				h := fnv.New32()
+				_, _ = h.Write([]byte(label))
+				opt := fmt.Sprintf("@tmpNoExportNewDef(%x)", h.Sum32()&0xffff)
+
+				f := &ast.Field{
+					Label: ast.NewIdent(label),
+					Value: ast.NewIdent("#" + label),
+					Attrs: []*ast.Attribute{{Text: opt}},
+				}
+				c.InsertAfter(f)
+
+				b := &strings.Builder{}
+				fmt.Fprintln(b, "Possible references to this location:")
+				for _, p := range refs {
+					fmt.Fprintf(b, "\t%s\n", p)
+				}
+
+				cg := internal.NewComment(true, b.String())
+				astutil.CopyPosition(cg, c.Node())
+				ast.AddComment(c.Node(), cg)
+			}
+
+			x.Label = ast.NewIdent("#" + label)
+			x.Token = token.COLON
+		}
+
+		return true
+	}, nil)
+
+	if hasErr {
+		p.err = errors.Append(p.err, errors.Newf(token.NoPos, `Incompatible definitions detected:
+
+A trick that can be used is to rename this to a regular identifier and then
+move the definition to a sub field. For instance, rewrite
+
+			"foo-bar" :: baz
+			"foo\(bar)" :: baz
+
+		to
+
+			#defmap: "foo-bar": baz
+			#defmap: "foo\(bar)": baz
+
+Errors:`))
+	}
+}
+
+func (p *processor) visitAll(fn func(f *ast.File)) {
+	if p.err != nil {
+		return
+	}
+
+	done := map[*ast.File]bool{}
+
+	for _, b := range p.instances {
+		for _, f := range b.Files {
+			if done[f] {
+				continue
+			}
+			done[f] = true
+			fn(f)
+		}
+	}
+}
diff --git a/cmd/cue/cmd/fixall_test.go b/cmd/cue/cmd/fixall_test.go
new file mode 100644
index 0000000..83f2d14
--- /dev/null
+++ b/cmd/cue/cmd/fixall_test.go
@@ -0,0 +1,44 @@
+// Copyright 2020 CUE Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package cmd
+
+import (
+	"fmt"
+	"testing"
+
+	"cuelang.org/go/cue/format"
+	"cuelang.org/go/internal/cuetxtar"
+)
+
+func TestFixAll(t *testing.T) {
+	test := cuetxtar.TxTarTest{
+		Root:   "./testdata/fix",
+		Name:   "fixmod",
+		Update: *update,
+	}
+
+	test.Run(t, func(t *cuetxtar.Test) {
+		a := t.ValidInstances("./...")
+		err := fixAll(a)
+		t.WriteErrors(err)
+		for _, b := range a {
+			for _, f := range b.Files {
+				b, _ := format.Node(f)
+				fmt.Fprintln(t, "---", t.Rel(f.Filename))
+				fmt.Fprintln(t, string(b))
+			}
+		}
+	})
+}
diff --git a/cmd/cue/cmd/root.go b/cmd/cue/cmd/root.go
index ff3773a..f7497dd 100644
--- a/cmd/cue/cmd/root.go
+++ b/cmd/cue/cmd/root.go
@@ -91,6 +91,7 @@
 		newEvalCmd(c),
 		newDefCmd(c),
 		newExportCmd(c),
+		newFixCmd(c),
 		newFmtCmd(c),
 		newGetCmd(c),
 		newImportCmd(c),
diff --git a/cmd/cue/cmd/testdata/fix/alias.txtar b/cmd/cue/cmd/testdata/fix/alias.txtar
new file mode 100644
index 0000000..2e5a133
--- /dev/null
+++ b/cmd/cue/cmd/testdata/fix/alias.txtar
@@ -0,0 +1,21 @@
+
+-- cue.mod/module.cue --
+module: "acme.com"
+
+-- bar/bar.cue --
+package bar
+
+a: [X=b.c]: int
+a: Y=[X=b.c]: int
+
+b: c :: int
+
+-- out/fixmod --
+--- bar/bar.cue
+package bar
+
+a: [X=b.#c]:   int
+a: Y=[X=b.#c]: int
+
+b: #c: int
+
diff --git a/cmd/cue/cmd/testdata/fix/basic.txtar b/cmd/cue/cmd/testdata/fix/basic.txtar
new file mode 100644
index 0000000..49c6aef
--- /dev/null
+++ b/cmd/cue/cmd/testdata/fix/basic.txtar
@@ -0,0 +1,61 @@
+-- cue.mod/module.cue --
+module: "acme.com"
+
+-- bar/bar.cue --
+package bar
+
+import "acme.com/foo"
+
+A :: foo.Def & {
+    a: >10
+
+    B :: { c: int }
+}
+
+b: A & { a: 11 }
+
+c: foo.Def & { a: 11 }
+
+d: A.B.c
+e: [...A.B.c]
+
+-- foo/foo.cue --
+package foo
+
+Def :: {
+    a: int
+    b: string
+}
+
+a: Def
+c: [Def.b]: int
+
+-- out/fixmod --
+--- bar/bar.cue
+package bar
+
+import "acme.com/foo"
+
+#A: foo.#Def & {
+	a: >10
+	#B: {c: int}
+}
+
+b: #A & {a: 11}
+
+c: foo.#Def & {a: 11}
+
+d: #A.#B.c
+e: [...#A.#B.c]
+
+--- foo/foo.cue
+package foo
+
+#Def: {
+	a: int
+	b: string
+}
+
+a: #Def
+c: [#Def.b]: int
+
diff --git a/cmd/cue/cmd/testdata/fix/incompatible.txtar b/cmd/cue/cmd/testdata/fix/incompatible.txtar
new file mode 100644
index 0000000..e773453
--- /dev/null
+++ b/cmd/cue/cmd/testdata/fix/incompatible.txtar
@@ -0,0 +1,38 @@
+Things currently possible not supported by new-style
+definitions.
+
+-- foo/bar.cue --
+package bar
+
+"\(foo)" :: int
+foo: string
+
+"foo-bar" :: int
+
+-- out/fixmod --
+Incompatible definitions detected:
+
+A trick that can be used is to rename this to a regular identifier and then
+move the definition to a sub field. For instance, rewrite
+
+			"foo-bar" :: baz
+			"foo\(bar)" :: baz
+
+		to
+
+			#defmap: "foo-bar": baz
+			#defmap: "foo\(bar)": baz
+
+Errors:
+cannot convert dynamic definition for '"\(foo)"':
+    ./foo/bar.cue:3:1
+invalid identifier "foo-bar"; definition must be valid label:
+    ./foo/bar.cue:6:1
+--- foo/bar.cue
+package bar
+
+"\(foo)" :: int
+foo:        string
+
+"foo-bar" :: int
+
diff --git a/cmd/cue/cmd/testdata/fix/invalid.txtar b/cmd/cue/cmd/testdata/fix/invalid.txtar
new file mode 100644
index 0000000..a5beffb
--- /dev/null
+++ b/cmd/cue/cmd/testdata/fix/invalid.txtar
@@ -0,0 +1 @@
+#skip
\ No newline at end of file
diff --git a/cmd/cue/cmd/testdata/fix/template.txtar b/cmd/cue/cmd/testdata/fix/template.txtar
new file mode 100644
index 0000000..3b987da
--- /dev/null
+++ b/cmd/cue/cmd/testdata/fix/template.txtar
@@ -0,0 +1,74 @@
+-- cue.mod/module.cue --
+module: "acme.com"
+
+-- bar/bar.cue --
+package bar
+
+A :: {
+    foo: [string]: {
+        B :: {
+            foo: int
+        }
+
+        bar: {
+            C :: { D :: int }
+        }
+
+        c: B.foo
+        d: B
+        e: B & { foo: 3 }
+        f: bar.C
+        g: bar.C.D
+    }
+
+    used: [=~"Foo"]: {
+        C :: {}
+        c: C
+    }
+    used: "FooBar": {}
+
+    unused: [=~"Foo"]: {
+        X :: {
+
+        }
+        x: X
+    }
+}
+
+-- out/fixmod --
+--- bar/bar.cue
+package bar
+
+#A: {
+	foo: [string]: {
+		#B: {
+			foo: int
+		}
+
+		bar: {
+			#C: {
+				#D: int
+			}
+		}
+
+		c: #B.foo
+		d: #B
+		e: #B & {foo: 3}
+		f: bar.#C
+		g: bar.#C.#D
+	}
+
+	used: [=~"Foo"]: {
+		#C: {}
+		c: #C
+	}
+	used: "FooBar": {}
+
+	unused: [=~"Foo"]: {
+		#X: {
+
+		}
+		x: #X
+	}
+}
+
diff --git a/cmd/cue/cmd/testdata/fix/unsupported.txtar b/cmd/cue/cmd/testdata/fix/unsupported.txtar
new file mode 100644
index 0000000..26518d2
--- /dev/null
+++ b/cmd/cue/cmd/testdata/fix/unsupported.txtar
@@ -0,0 +1,34 @@
+This file contains cases that could be supported but aren't,
+as the cost for supporting them is likely too high.
+
+-- cue.mod/module.cue --
+module: "acme.com"
+
+
+-- foo/foo.cue --
+package foo
+
+Def :: {
+    a: int
+    b: "foo"
+}
+
+"\(Def.b)": int
+b: "\(Def.b)": int
+
+-- out/fixmod --
+--- foo/foo.cue
+package foo
+
+// Possible references to this location:
+// /Users/mpvl/Cloud/dev/cue/cmd/cue/cmd/testdata/fix/foo/foo.cue:8:4
+// /Users/mpvl/Cloud/dev/cue/cmd/cue/cmd/testdata/fix/foo/foo.cue:9:7
+#Def: {
+	a: int
+	b: "foo"
+}
+Def: #Def @tmpNoExportNewDef(7aca)
+
+"\(Def.b)": int
+b: "\(Def.b)": int
+
diff --git a/cmd/cue/cmd/testdata/fix/unused.txtar b/cmd/cue/cmd/testdata/fix/unused.txtar
new file mode 100644
index 0000000..2eaefec
--- /dev/null
+++ b/cmd/cue/cmd/testdata/fix/unused.txtar
@@ -0,0 +1,22 @@
+-- cue.mod/module.cue --
+module: "acme.com"
+
+-- bar/bar.cue --
+package bar
+
+a: [string]: {
+    D :: int
+}
+
+b: a.str.D
+
+-- out/fixmod --
+--- bar/bar.cue
+package bar
+
+a: [string]: {
+	#D: int
+}
+
+b: a.str.#D
+
diff --git a/cmd/cue/cmd/testdata/script/fix.txt b/cmd/cue/cmd/testdata/script/fix.txt
new file mode 100644
index 0000000..5f663aa
--- /dev/null
+++ b/cmd/cue/cmd/testdata/script/fix.txt
@@ -0,0 +1,96 @@
+cue fix
+
+cmp foo/foo.cue expect/foo/foo_cue
+cmp bar/bar.cue expect/bar/bar_cue
+cmp cue.mod/pkg/foobar.org/notimported/notimported.cue expect/cue.mod/pkg/foobar.org/notimported/notimported.cue
+cmp cue.mod/gen/foobar.org/imported/imported.cue expect/cue.mod/gen/foobar.org/imported/imported.cue
+
+-- cue.mod/module.cue --
+module: "acme.com"
+-- cue.mod/pkg/foobar.org/notimported/notimported.cue --
+package notimported
+
+Foo :: {
+    x: int
+}
+a: Foo
+-- cue.mod/gen/foobar.org/imported/imported.cue --
+package imported
+
+Bar :: {
+    x: int
+}
+-- bar/bar.cue --
+package bar
+
+import (
+    "acme.com/foo"
+    "foobar.org/imported"
+)
+
+A :: foo.Def & {
+    a: >10
+
+    B :: { c: int }
+}
+
+b: A & { a: 11 }
+
+c: imported.Bar & { a: 11 }
+
+d: A.B.c
+e: [...A.B.c]
+
+-- foo/foo.cue --
+package foo
+
+Def :: {
+    a: int
+    b: string
+}
+
+a: Def
+c: [Def.b]: int
+
+-- expect/bar/bar_cue --
+package bar
+
+import (
+	"acme.com/foo"
+	"foobar.org/imported"
+)
+
+#A: foo.#Def & {
+	a: >10
+	#B: {c: int}
+}
+
+b: #A & {a: 11}
+
+c: imported.#Bar & {a: 11}
+
+d: #A.#B.c
+e: [...#A.#B.c]
+-- expect/foo/foo_cue --
+package foo
+
+#Def: {
+	a: int
+	b: string
+}
+
+a: #Def
+c: [#Def.b]: int
+-- expect/cue.mod/pkg/foobar.org/notimported/notimported.cue --
+package notimported
+
+#Foo: {
+	x: int
+}
+a: #Foo
+-- expect/cue.mod/gen/foobar.org/imported/imported.cue --
+package imported
+
+#Bar: {
+	x: int
+}
\ No newline at end of file
diff --git a/cmd/cue/cmd/testdata/script/fix_files.txt b/cmd/cue/cmd/testdata/script/fix_files.txt
new file mode 100644
index 0000000..53068ef
--- /dev/null
+++ b/cmd/cue/cmd/testdata/script/fix_files.txt
@@ -0,0 +1,87 @@
+cue fix ./foo/foo.cue ./bar/bar.cue
+
+cmp foo/foo.cue expect/foo/foo_cue
+cmp bar/bar.cue expect/bar/bar_cue
+cmp cue.mod/pkg/foobar.org/notimported/notimported.cue expect/cue.mod/pkg/foobar.org/notimported/notimported.cue
+cmp cue.mod/gen/foobar.org/imported/imported.cue expect/cue.mod/gen/foobar.org/imported/imported.cue
+
+-- cue.mod/module.cue --
+module: "acme.com"
+-- cue.mod/pkg/foobar.org/notimported/notimported.cue --
+package notimported
+
+Foo :: {
+    x: int
+}
+a: Foo
+-- cue.mod/gen/foobar.org/imported/imported.cue --
+package imported
+
+Bar :: {
+    x: int
+}
+-- bar/bar.cue --
+package bar
+
+import (
+    "foobar.org/imported"
+)
+
+A :: {
+    B :: { c: int }
+}
+
+b: A & { a: 11 }
+
+d: imported.Bar & { a: 11 }
+
+d: A.B.c
+e: [...A.B.c]
+
+-- foo/foo.cue --
+Def :: {
+    a: int
+    b: string
+}
+
+a: Def
+c: [Def.b]: int
+
+-- expect/bar/bar_cue --
+package bar
+
+import (
+	"foobar.org/imported"
+)
+
+#A: {
+	#B: {c: int}
+}
+
+b: #A & {a: 11}
+
+d: imported.#Bar & {a: 11}
+
+d: #A.#B.c
+e: [...#A.#B.c]
+-- expect/foo/foo_cue --
+#Def: {
+	a: int
+	b: string
+}
+
+a: #Def
+c: [#Def.b]: int
+-- expect/cue.mod/pkg/foobar.org/notimported/notimported.cue --
+package notimported
+
+Foo :: {
+    x: int
+}
+a: Foo
+-- expect/cue.mod/gen/foobar.org/imported/imported.cue --
+package imported
+
+Bar :: {
+    x: int
+}
\ No newline at end of file
diff --git a/cmd/cue/cmd/testdata/script/fix_pkg.txt b/cmd/cue/cmd/testdata/script/fix_pkg.txt
new file mode 100644
index 0000000..bd7796a
--- /dev/null
+++ b/cmd/cue/cmd/testdata/script/fix_pkg.txt
@@ -0,0 +1,97 @@
+cue fix ./bar foobar.org/notimported
+
+cmp foo/foo.cue expect/foo/foo_cue
+cmp bar/bar.cue expect/bar/bar_cue
+cmp cue.mod/pkg/foobar.org/notimported/notimported.cue expect/cue.mod/pkg/foobar.org/notimported/notimported.cue
+cmp cue.mod/gen/foobar.org/imported/imported.cue expect/cue.mod/gen/foobar.org/imported/imported.cue
+
+-- cue.mod/module.cue --
+module: "acme.com"
+-- cue.mod/pkg/foobar.org/notimported/notimported.cue --
+package notimported
+
+Foo :: {
+    x: int
+}
+a: Foo
+-- cue.mod/gen/foobar.org/imported/imported.cue --
+package imported
+
+Bar :: {
+    x: int
+}
+-- bar/bar.cue --
+package bar
+
+import (
+    "acme.com/foo"
+    "foobar.org/imported"
+)
+
+A :: foo.Def & {
+    a: >10
+
+    B :: { c: int }
+}
+
+b: A & { a: 11 }
+
+c: imported.Bar & { a: 11 }
+
+d: A.B.c
+e: [...A.B.c]
+
+-- foo/foo.cue --
+package foo
+
+Def :: {
+    a: int
+    b: string
+}
+
+a: Def
+c: [Def.b]: int
+
+-- expect/bar/bar_cue --
+package bar
+
+import (
+	"acme.com/foo"
+	"foobar.org/imported"
+)
+
+#A: foo.#Def & {
+	a: >10
+	#B: {c: int}
+}
+
+b: #A & {a: 11}
+
+c: imported.#Bar & {a: 11}
+
+d: #A.#B.c
+e: [...#A.#B.c]
+-- expect/foo/foo_cue --
+package foo
+
+Def :: {
+    a: int
+    b: string
+}
+
+a: Def
+c: [Def.b]: int
+
+-- expect/cue.mod/pkg/foobar.org/notimported/notimported.cue --
+package notimported
+
+#Foo: {
+	x: int
+}
+a: #Foo
+-- expect/cue.mod/gen/foobar.org/imported/imported.cue --
+package imported
+
+Bar :: {
+    x: int
+}
\ No newline at end of file
diff --git a/cue/build/import.go b/cue/build/import.go
index f8eea93..996edb0 100644
--- a/cue/build/import.go
+++ b/cue/build/import.go
@@ -105,7 +105,7 @@
 					continue
 				}
 				if imp.Err != nil {
-					return imp.Err
+					return errors.Wrapf(imp.Err, pos, "import failed")
 				}
 				imp.ImportPath = path
 				// imp.parent = inst
diff --git a/cue/load/errors.go b/cue/load/errors.go
index 2b0041c..a431282 100644
--- a/cue/load/errors.go
+++ b/cue/load/errors.go
@@ -51,7 +51,7 @@
 
 func (p *PackageError) Position() token.Pos         { return p.Pos }
 func (p *PackageError) InputPositions() []token.Pos { return nil }
-func (p *PackageError) Path() []string              { return nil }
+func (p *PackageError) Path() []string              { return p.ImportStack }
 
 func (l *loader) errPkgf(importPos []token.Pos, format string, args ...interface{}) *PackageError {
 	err := &PackageError{
diff --git a/cue/load/loader_test.go b/cue/load/loader_test.go
index 4a05f0c..f3c4ec0 100644
--- a/cue/load/loader_test.go
+++ b/cue/load/loader_test.go
@@ -86,7 +86,7 @@
 		cfg:  dirCfg,
 		args: args("./other/..."),
 		want: `
-err:    relative import paths not allowed ("./file")
+err:    import failed: relative import paths not allowed ("./file")
 path:   ""
 module: example.org/test
 root:   $CWD/testdata
@@ -108,7 +108,7 @@
 		cfg:  dirCfg,
 		args: args("./other"),
 		want: `
-err:    relative import paths not allowed ("./file")
+err:    import failed: relative import paths not allowed ("./file")
 path:   example.org/test/other:main
 module: example.org/test
 root:   $CWD/testdata
diff --git a/cue/types.go b/cue/types.go
index 8a05140..179b133 100644
--- a/cue/types.go
+++ b/cue/types.go
@@ -1194,6 +1194,38 @@
 	return Value{}, false
 }
 
+// BulkOptionals returns all bulk optional fields as key-value pairs.
+// See also Elem and Template.
+func (v Value) BulkOptionals() [][2]Value {
+	x, ok := v.path.cache.(*structLit)
+	if !ok {
+		return nil
+	}
+	return v.appendBulk(nil, x.optionals)
+}
+
+func (v Value) appendBulk(a [][2]Value, x *optionals) [][2]Value {
+	if x == nil {
+		return a
+	}
+	a = v.appendBulk(a, x.left)
+	a = v.appendBulk(a, x.right)
+	for _, set := range x.fields {
+		if set.key != nil {
+			ctx := v.ctx()
+			fn, ok := ctx.manifest(set.value).(*lambdaExpr)
+			if !ok {
+				// create error
+				continue
+			}
+			x := fn.call(ctx, set.value, &basicType{k: stringKind})
+
+			a = append(a, [2]Value{v.makeElem(set.key), v.makeElem(x)})
+		}
+	}
+	return a
+}
+
 // List creates an iterator over the values of a list or reports an error if
 // v is not a list.
 func (v Value) List() (Iterator, error) {
@@ -1581,6 +1613,9 @@
 // given its name.
 func (v Value) Template() func(label string) Value {
 	// TODO: rename to optional.
+	if v.path == nil {
+		return nil
+	}
 
 	ctx := v.ctx()
 	x, ok := v.path.cache.(*structLit)
diff --git a/internal/cuetxtar/txtar.go b/internal/cuetxtar/txtar.go
new file mode 100644
index 0000000..0164605
--- /dev/null
+++ b/internal/cuetxtar/txtar.go
@@ -0,0 +1,260 @@
+// Copyright 2020 CUE Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package cuetxtar
+
+import (
+	"bufio"
+	"bytes"
+	"io/ioutil"
+	"os"
+	"path"
+	"path/filepath"
+	"strings"
+	"testing"
+
+	"cuelang.org/go/cue/build"
+	"cuelang.org/go/cue/errors"
+	"cuelang.org/go/cue/load"
+	"github.com/google/go-cmp/cmp"
+	"github.com/rogpeppe/testscript/txtar"
+)
+
+// A TxTarTest represents a test run that process all CUE tests in the txtar
+// format rooted in a given directory.
+type TxTarTest struct {
+	// Run TxTarTest on this directory.
+	Root string
+
+	// Name is a unique name for this test. The golden file for this test is
+	// derived from the out/<name> file in the .txtar file.
+	//
+	// TODO: by default derive from the current base directory name.
+	Name string
+
+	// If Update is true, TestTxTar will update the out/Name file if it differs
+	// from the original input. The user must set the output in Gold for this
+	// to be detected.
+	Update bool
+
+	// Skip is a map of tests to skip to their skip message.
+	Skip map[string]string
+
+	// ToDo is a map of tests that should be skipped now, but should be fixed.
+	ToDo map[string]string
+}
+
+// A Test represents a single test based on a .txtar file.
+//
+// A Test embeds *testing.T and should be used to report errors.
+//
+// A Test also embeds a *bytes.Buffer which is used to report test results,
+// which are compared against the golden file for the test in the TxTar archive.
+// If the test fails and the update flag is set to true, the Archive will be
+// updated and written to disk.
+type Test struct {
+	// Allow Test to be used as a T.
+	*testing.T
+
+	// Buffer is used to write the test results that will be compared to the
+	// golden file.
+	*bytes.Buffer
+
+	Archive *txtar.Archive
+
+	// The absolute path of the current test directory.
+	Dir string
+
+	hasGold bool
+}
+
+func (t *Test) HasTag(key string) bool {
+	prefix := []byte("#" + key)
+	s := bufio.NewScanner(bytes.NewReader(t.Archive.Comment))
+	for s.Scan() {
+		b := s.Bytes()
+		if bytes.Equal(bytes.TrimSpace(b), prefix) {
+			return true
+		}
+	}
+	return false
+}
+
+func (t *Test) Value(key string) (value string, ok bool) {
+	prefix := []byte("#" + key + ":")
+	s := bufio.NewScanner(bytes.NewReader(t.Archive.Comment))
+	for s.Scan() {
+		b := s.Bytes()
+		if bytes.HasPrefix(b, prefix) {
+			return string(bytes.TrimSpace(b[len(prefix):])), true
+		}
+	}
+	return "", false
+}
+
+// Bool searchs for a line starting with #key: value in the comment and
+// returns true if the key exists and the value is true.
+func (t *Test) Bool(key string) bool {
+	s, ok := t.Value(key)
+	return ok && s == "true"
+}
+
+// Rel converts filename to a normalized form so that it will given the same
+// output across different runs and OSes.
+func (t *Test) Rel(filename string) string {
+	rel, err := filepath.Rel(t.Dir, filename)
+	if err != nil {
+		return filepath.Base(filename)
+	}
+	return rel
+}
+
+// WriteErrors writes strings and
+func (t *Test) WriteErrors(err errors.Error) {
+	if err != nil {
+		errors.Print(t, err, &errors.Config{
+			Cwd:     t.Dir,
+			ToSlash: true,
+		})
+	}
+}
+
+// ValidInstances returns the valid instances for this .txtar file or skips the
+// test if there is an error loading the instances.
+func (t *Test) ValidInstances(args ...string) []*build.Instance {
+	a := t.RawInstances(args...)
+	for _, i := range a {
+		if i.Err != nil {
+			if t.hasGold {
+				t.Fatal("Parse error: ", i.Err)
+			}
+			t.Skip("Parse error: ", i.Err)
+		}
+	}
+	return a
+}
+
+// RawInstances returns the intstances represented by this .txtar file. The
+// returned instances are not checked for errors.
+func (t *Test) RawInstances(args ...string) []*build.Instance {
+	if len(args) == 0 {
+		args = []string{"in.cue"}
+	}
+	overlay := map[string]load.Source{}
+	for _, f := range t.Archive.Files {
+		overlay[filepath.Join(t.Dir, f.Name)] = load.FromBytes(f.Data)
+	}
+
+	cfg := &load.Config{
+		Dir:     t.Dir,
+		Overlay: overlay,
+	}
+
+	return load.Instances(args, cfg)
+}
+
+// Run runs tests defined in txtar files in root or its subdirectories.
+// Only tests for which an `old/name` test output file exists are run.
+func (x *TxTarTest) Run(t *testing.T, f func(tc *Test)) {
+	dir, err := os.Getwd()
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	root := x.Root
+
+	err = filepath.Walk(root, func(fullpath string, info os.FileInfo, err error) error {
+		if err != nil {
+			t.Fatal(err)
+		}
+
+		if info.IsDir() || filepath.Ext(fullpath) != ".txtar" {
+			return nil
+		}
+
+		a, err := txtar.ParseFile(fullpath)
+		if err != nil {
+			t.Fatalf("error parsing txtar file: %v", err)
+		}
+
+		p := strings.Index(fullpath, "/testdata/")
+		testName := fullpath[p+len("/testdata/") : len(fullpath)-len(".txtar")]
+
+		t.Run(testName, func(t *testing.T) {
+			outFile := path.Join("out", x.Name)
+
+			var gold *txtar.File
+			for i, f := range a.Files {
+				if f.Name == outFile {
+					gold = &a.Files[i]
+				}
+			}
+
+			tc := &Test{
+				T:       t,
+				Buffer:  &bytes.Buffer{},
+				Archive: a,
+				Dir:     filepath.Dir(filepath.Join(dir, fullpath)),
+
+				hasGold: gold != nil,
+			}
+
+			if tc.HasTag("skip") {
+				t.Skip()
+			}
+
+			if msg, ok := x.Skip[testName]; ok {
+				t.Skip(msg)
+			}
+			if msg, ok := x.ToDo[testName]; ok {
+				t.Skip(msg)
+			}
+
+			f(tc)
+
+			result := tc.Bytes()
+			if len(result) == 0 {
+				return
+			}
+
+			if gold == nil {
+				a.Files = append(a.Files, txtar.File{Name: outFile})
+				gold = &a.Files[len(a.Files)-1]
+			}
+
+			if bytes.Equal(gold.Data, result) {
+				return
+			}
+
+			if !x.Update {
+				t.Fatal(cmp.Diff(string(gold.Data), string(result)))
+			}
+
+			gold.Data = result
+
+			// Update and write file.
+
+			err := ioutil.WriteFile(fullpath, txtar.Format(a), 0644)
+			if err != nil {
+				t.Fatal(err)
+			}
+		})
+
+		return nil
+	})
+
+	if err != nil {
+		t.Fatal(err)
+	}
+}