cue/ast: add NewList helper
Also changes some existing code as an example.
Change-Id: Ia865365db5fbec940a713175dc1495cb93cdd866
Reviewed-on: https://cue-review.googlesource.com/c/cue/+/3840
Reviewed-by: Marcel van Lohuizen <mpvl@golang.org>
diff --git a/cue/ast/ast.go b/cue/ast/ast.go
index 864fe2f..96bc0c6 100644
--- a/cue/ast/ast.go
+++ b/cue/ast/ast.go
@@ -411,7 +411,7 @@
// NewString creates a new BasicLit with a string value without position.
// It quotes the given string.
-// Useful for ASTs generated by code other than the Go
+// Useful for ASTs generated by code other than the CUE parser.
func NewString(str string) *BasicLit {
// TODO: use CUE quoting.
str = strconv.Quote(str)
@@ -451,6 +451,12 @@
expr
}
+// NewList creates a list of Expressions.
+// Useful for ASTs generated by code other than the CUE parser.
+func NewList(exprs ...Expr) *ListLit {
+ return &ListLit{Elts: exprs}
+}
+
type Ellipsis struct {
Ellipsis token.Pos // open list if set
Type Expr // type for the remaining elements
@@ -514,7 +520,7 @@
}
// NewSel creates a sequence of selectors.
-// Useful for ASTs generated by code other than the Go
+// Useful for ASTs generated by code other than the CUE parser.
func NewSel(x Expr, sel ...string) Expr {
for _, s := range sel {
x = &SelectorExpr{X: x, Sel: NewIdent(s)}
@@ -557,7 +563,7 @@
}
// NewCall creates a new CallExpr.
-// Useful for ASTs generated by code other than the Go
+// Useful for ASTs generated by code other than the CUE parser.
func NewCall(fun Expr, args ...Expr) *CallExpr {
return &CallExpr{Fun: fun, Args: args}
}
@@ -667,7 +673,7 @@
// Convenience functions for Idents
// NewIdent creates a new Ident without position.
-// Useful for ASTs generated by code other than the Go
+// Useful for ASTs generated by code other than the CUE parser.
func NewIdent(name string) *Ident {
return &Ident{token.NoPos, name, nil, nil, comments{}, label{}, expr{}}
}
diff --git a/cue/build_test.go b/cue/build_test.go
index cd89e92..10f8336 100644
--- a/cue/build_test.go
+++ b/cue/build_test.go
@@ -32,10 +32,10 @@
expr: ast.NewString("Hello"),
out: `"Hello"`,
}, {
- expr: &ast.ListLit{Elts: []ast.Expr{
+ expr: ast.NewList(
ast.NewString("Hello"),
ast.NewString("World"),
- }},
+ ),
out: `["Hello","World"]`,
}}
for _, tc := range testCases {
diff --git a/cue/export.go b/cue/export.go
index 0604457..83a1922 100644
--- a/cue/export.go
+++ b/cue/export.go
@@ -601,9 +601,7 @@
X: &ast.BinaryExpr{
X: p.expr(x.len),
Op: token.MUL,
- Y: &ast.ListLit{Elts: []ast.Expr{
- p.expr(x.typ),
- }},
+ Y: ast.NewList(p.expr(x.typ)),
},
Op: token.AND,
Y: list,