cmd/cue/cmd: fmt rewrites alias to let clauses
Issue #339
Change-Id: I0bcb634251e54300f8d84f8a822c2081902a85dd
Reviewed-on: https://cue-review.googlesource.com/c/cue/+/5685
Reviewed-by: Marcel van Lohuizen <mpvl@golang.org>
diff --git a/cmd/cue/cmd/fix.go b/cmd/cue/cmd/fix.go
index 87bbf4e..d8b05fe 100644
--- a/cmd/cue/cmd/fix.go
+++ b/cmd/cue/cmd/fix.go
@@ -25,6 +25,29 @@
)
func fix(f *ast.File) *ast.File {
+ // Rewrite an old-style alias to a let clause.
+ ast.Walk(f, func(n ast.Node) bool {
+ var decls []ast.Decl
+ switch x := n.(type) {
+ case *ast.StructLit:
+ decls = x.Elts
+ case *ast.File:
+ decls = x.Decls
+ }
+ for i, d := range decls {
+ if a, ok := d.(*ast.Alias); ok {
+ x := &ast.LetClause{
+ Ident: a.Ident,
+ Equal: a.Equal,
+ Expr: a.Expr,
+ }
+ astutil.CopyMeta(x, a)
+ decls[i] = x
+ }
+ }
+ return true
+ }, nil)
+
// Rewrite block comments to regular comments.
ast.Walk(f, func(n ast.Node) bool {
switch x := n.(type) {
diff --git a/cmd/cue/cmd/fix_test.go b/cmd/cue/cmd/fix_test.go
index 26c0cb2..259362d 100644
--- a/cmd/cue/cmd/fix_test.go
+++ b/cmd/cue/cmd/fix_test.go
@@ -62,6 +62,13 @@
out: `y: [1, 2, 3, 4]
a: [ for x in y { x } ]
`,
+ }, {
+ in: `
+ y = foo
+ `,
+ out: `
+let y = foo
+`,
// }, {
// name: "slice",
// in: `package foo
diff --git a/cmd/cue/cmd/testdata/script/legacy.txt b/cmd/cue/cmd/testdata/script/legacy.txt
index 8fee102..18d4cab 100644
--- a/cmd/cue/cmd/testdata/script/legacy.txt
+++ b/cmd/cue/cmd/testdata/script/legacy.txt
@@ -11,6 +11,10 @@
-- foo.cue --
a: [1]
b: [ x for x in a ]
+
+X = foo
-- bar.cue --
a: [1]
b: [ for x in a { x } ]
+
+let X = foo
\ No newline at end of file