blob: b6924b4b159d9e9dd4e4146f9f0b7bd93f8b2641 [file] [log] [blame]
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +01001// Copyright 2018 The CUE Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package cue
16
17import (
18 "fmt"
Marcel van Lohuizen369e4232019-02-15 10:59:29 +040019 "strings"
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +010020
21 "cuelang.org/go/cue/ast"
22 "cuelang.org/go/cue/build"
Marcel van Lohuizen6ceb6012019-02-18 18:30:38 +010023 "cuelang.org/go/cue/literal"
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +010024 "cuelang.org/go/cue/token"
25)
26
27// insertFile inserts the given file at the root of the instance.
28//
29// The contents will be merged (unified) with any pre-existing value. In this
30// case an error may be reported, but only if the merge failed at the top-level.
31// Other errors will be recorded at the respective values in the tree.
32//
33// There should be no unresolved identifiers in file, meaning the Node field
34// of all identifiers should be set to a non-nil value.
35func (inst *Instance) insertFile(f *ast.File) error {
36 // TODO: insert by converting to value first so that the trim command can
37 // also remove top-level fields.
38 // First process single file.
39 v := newVisitor(inst.index, inst.inst, inst.rootStruct, inst.scope)
40 v.astState.astMap[f] = inst.rootStruct
41 result := v.walk(f)
42 if isBottom(result) {
43 return result.(*bottom)
44 }
45
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +010046 return nil
47}
48
49type astVisitor struct {
50 *astState
Marcel van Lohuizen66db9202018-12-17 19:02:08 +010051 object *structLit
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +010052
53 inSelector int
54}
55
56func (v *astVisitor) ctx() *context {
57 return v.astState.ctx
58}
59
60type astState struct {
61 ctx *context
62 *index
63 inst *build.Instance
64
65 litParser *litParser
66 resolveRoot *structLit
67
68 // make unique per level to avoid reuse of structs being an issue.
69 astMap map[ast.Node]scope
70}
71
72func (s *astState) mapScope(n ast.Node) (m scope) {
73 if m = s.astMap[n]; m == nil {
74 m = newStruct(newNode(n))
75 s.astMap[n] = m
76 }
77 return m
78}
79
80func (s *astState) setScope(n ast.Node, v scope) {
81 if m, ok := s.astMap[n]; ok && m != v {
82 panic("already defined")
83 }
84 s.astMap[n] = v
85}
86
87func newVisitor(idx *index, inst *build.Instance, obj, resolveRoot *structLit) *astVisitor {
88 ctx := idx.newContext()
Marcel van Lohuizend4847d92019-02-18 23:27:34 +010089 return newVisitorCtx(ctx, inst, obj, resolveRoot)
90}
91
92func newVisitorCtx(ctx *context, inst *build.Instance, obj, resolveRoot *structLit) *astVisitor {
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +010093 v := &astVisitor{
94 object: obj,
95 }
96 v.astState = &astState{
97 ctx: ctx,
98 index: ctx.index,
99 inst: inst,
100 litParser: &litParser{ctx: ctx},
101 resolveRoot: resolveRoot,
102 astMap: map[ast.Node]scope{},
103 }
104 return v
105}
106
107func (v *astVisitor) error(n ast.Node, args ...interface{}) value {
108 return v.mkErr(newNode(n), args...)
109}
110
111func (v *astVisitor) resolve(n *ast.Ident) value {
112 ctx := v.ctx()
113 label := v.label(n.Name, true)
114 if r := v.resolveRoot; r != nil {
115 if value, _ := r.lookup(v.ctx(), label); value != nil {
116 return &selectorExpr{newExpr(n),
117 &nodeRef{baseValue: newExpr(n), node: r}, label}
118 }
119 if v.inSelector > 0 {
120 if p := getBuiltinShorthandPkg(ctx, n.Name); p != nil {
121 return &nodeRef{baseValue: newExpr(n), node: p}
122 }
123 }
124 }
125 return nil
126}
127
128func (v *astVisitor) loadImport(imp *ast.ImportSpec) evaluated {
129 ctx := v.ctx()
130 val := lookupBuiltinPkg(ctx, imp)
131 if !isBottom(val) {
132 return val
133 }
Marcel van Lohuizen6ceb6012019-02-18 18:30:38 +0100134 path, err := literal.Unquote(imp.Path.Value)
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100135 if err != nil {
136 return ctx.mkErr(newNode(imp), "illformed import spec")
137 }
138 bimp := v.inst.LookupImport(path)
139 if bimp == nil {
140 return ctx.mkErr(newNode(imp), "package %q not found", path)
141 }
142 impInst := v.index.loadInstance(bimp)
143 return impInst.rootValue.evalPartial(ctx)
144}
145
146// We probably don't need to call Walk.s
147func (v *astVisitor) walk(astNode ast.Node) (value value) {
148 switch n := astNode.(type) {
149 case *ast.File:
150 obj := v.object
151 v1 := &astVisitor{
152 astState: v.astState,
153 object: obj,
154 }
155 for _, e := range n.Decls {
156 switch x := e.(type) {
157 case *ast.EmitDecl:
158 if v1.object.emit == nil {
159 v1.object.emit = v1.walk(x.Expr)
160 } else {
161 v1.object.emit = mkBin(v.ctx(), token.NoPos, opUnify, v1.object.emit, v1.walk(x.Expr))
162 }
163 default:
164 v1.walk(e)
165 }
166 }
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100167 value = obj
168
169 case *ast.ImportDecl:
170 for _, s := range n.Specs {
171 v.walk(s)
172 }
173
174 case *ast.ImportSpec:
175 val := v.loadImport(n)
176 if !isBottom(val) {
177 v.setScope(n, val.(*structLit))
178 }
179
180 case *ast.StructLit:
181 obj := v.mapScope(n).(*structLit)
182 v1 := &astVisitor{
183 astState: v.astState,
184 object: obj,
185 }
186 for _, e := range n.Elts {
187 switch x := e.(type) {
188 case *ast.EmitDecl:
189 // Only allowed at top-level.
190 v1.error(x, "emitting values is only allowed at top level")
191 case *ast.Field, *ast.Alias:
192 v1.walk(e)
193 case *ast.ComprehensionDecl:
194 v1.walk(x)
195 }
196 }
197 value = obj
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100198
199 case *ast.ComprehensionDecl:
200 yielder := &yield{baseValue: newExpr(n.Field.Value)}
Marcel van Lohuizen66db9202018-12-17 19:02:08 +0100201 fc := &fieldComprehension{
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100202 baseValue: newDecl(n),
203 clauses: wrapClauses(v, yielder, n.Clauses),
204 }
205 field := n.Field
206 switch x := field.Label.(type) {
207 case *ast.Interpolation:
208 yielder.key = v.walk(x)
209 yielder.value = v.walk(field.Value)
210
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100211 case *ast.TemplateLabel:
212 f := v.label(x.Ident.Name, true)
213
214 sig := &params{}
215 sig.add(f, &basicType{newNode(field.Label), stringKind})
216 template := &lambdaExpr{newExpr(field.Value), sig, nil}
217
218 v.setScope(field, template)
219 template.value = v.walk(field.Value)
220 yielder.value = template
Marcel van Lohuizen66db9202018-12-17 19:02:08 +0100221 fc.isTemplate = true
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100222
223 case *ast.BasicLit, *ast.Ident:
224 name, ok := ast.LabelName(x)
225 if !ok {
226 return v.error(x, "invalid field name: %v", x)
227 }
Marcel van Lohuizenf23fbff2018-12-20 12:23:16 +0100228
229 // TODO: if the clauses do not contain a guard, we know that this
230 // field will always be added and we can move the comprehension one
231 // level down. This, in turn, has the advantage that it is more
232 // likely that the cross-reference limitation for field
233 // comprehensions is not violated. To ensure compatibility between
234 // implementations, though, we should relax the spec as well.
235 // The cross-reference rule is simple and this relaxation seems a
236 // bit more complex.
237
238 // TODO: for now we can also consider making this an error if
239 // the list of clauses does not contain if and make a suggestion
240 // to rewrite it.
241
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100242 if name != "" {
243 yielder.key = &stringLit{newNode(x), name}
244 yielder.value = v.walk(field.Value)
245 }
246
247 default:
248 panic("cue: unknown label type")
249 }
250 // yielder.key = v.walk(n.Field.Label)
251 // yielder.value = v.walk(n.Field.Value)
Marcel van Lohuizen66db9202018-12-17 19:02:08 +0100252 v.object.comprehensions = append(v.object.comprehensions, fc)
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100253
254 case *ast.Field:
255 switch x := n.Label.(type) {
256 case *ast.Interpolation:
257 yielder := &yield{baseValue: newNode(x)}
Marcel van Lohuizen66db9202018-12-17 19:02:08 +0100258 fc := &fieldComprehension{
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100259 baseValue: newDecl(n),
260 clauses: yielder,
261 }
262 yielder.key = v.walk(x)
263 yielder.value = v.walk(n.Value)
Marcel van Lohuizen66db9202018-12-17 19:02:08 +0100264 v.object.comprehensions = append(v.object.comprehensions, fc)
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100265
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100266 case *ast.TemplateLabel:
267 f := v.label(x.Ident.Name, true)
268
269 sig := &params{}
270 sig.add(f, &basicType{newNode(n.Label), stringKind})
271 template := &lambdaExpr{newExpr(n.Value), sig, nil}
272
273 v.setScope(n, template)
274 template.value = v.walk(n.Value)
275
276 if v.object.template == nil {
277 v.object.template = template
278 } else {
279 v.object.template = mkBin(v.ctx(), token.NoPos, opUnify, v.object.template, template)
280 }
281
282 case *ast.BasicLit, *ast.Ident:
Marcel van Lohuizenb9b62d32019-03-14 23:50:15 +0100283 attrs, err := createAttrs(v.ctx(), newNode(n), n.Attrs)
284 if err != nil {
285 return err
286 }
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100287 f, ok := v.nodeLabel(x)
288 if !ok {
289 return v.error(n.Label, "invalid field name: %v", n.Label)
290 }
291 if f != 0 {
Marcel van Lohuizenb9b62d32019-03-14 23:50:15 +0100292 v.object.insertValue(v.ctx(), f, v.walk(n.Value), attrs)
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100293 }
294
295 default:
296 panic("cue: unknown label type")
297 }
298
299 case *ast.Alias:
300 // parsed verbatim at reference.
301
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100302 case *ast.ListComprehension:
303 yielder := &yield{baseValue: newExpr(n.Expr)}
304 lc := &listComprehension{
305 newExpr(n),
306 wrapClauses(v, yielder, n.Clauses),
307 }
308 // we don't support key for lists (yet?)
309 yielder.value = v.walk(n.Expr)
310 return lc
311
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100312 // Expressions
313 case *ast.Ident:
314 if n.Node == nil {
315 if value = v.resolve(n); value != nil {
316 break
317 }
318
319 switch n.Name {
320 case "_":
321 return &top{newExpr(n)}
322 case "string":
323 return &basicType{newExpr(n), stringKind}
324 case "bytes":
325 return &basicType{newExpr(n), bytesKind}
326 case "bool":
327 return &basicType{newExpr(n), boolKind}
328 case "int":
329 return &basicType{newExpr(n), intKind}
330 case "float":
331 return &basicType{newExpr(n), floatKind}
332 case "number":
333 return &basicType{newExpr(n), numKind}
334 case "duration":
335 return &basicType{newExpr(n), durationKind}
336
337 case "len":
338 return lenBuiltin
339 }
340 if r, ok := predefinedRanges[n.Name]; ok {
341 return r
342 }
343
344 value = v.error(n, "reference %q not found", n.Name)
345 break
346 }
347
348 if a, ok := n.Node.(*ast.Alias); ok {
349 value = v.walk(a.Expr)
350 break
351 }
352
353 label := v.label(n.Name, true)
354 if n.Scope != nil {
355 n2 := v.mapScope(n.Scope)
356 value = &nodeRef{baseValue: newExpr(n), node: n2}
357 value = &selectorExpr{newExpr(n), value, label}
358 } else {
359 n2 := v.mapScope(n.Node)
360 value = &nodeRef{baseValue: newExpr(n), node: n2}
361 }
362
363 case *ast.BottomLit:
364 value = v.error(n, "from source")
365
366 case *ast.BadDecl:
367 // nothing to do
368
369 case *ast.BadExpr:
370 value = v.error(n, "invalid expression")
371
372 case *ast.BasicLit:
373 value = v.litParser.parse(n)
374
375 case *ast.Interpolation:
376 if len(n.Elts) == 0 {
377 return v.error(n, "invalid interpolation")
378 }
379 first, ok1 := n.Elts[0].(*ast.BasicLit)
380 last, ok2 := n.Elts[len(n.Elts)-1].(*ast.BasicLit)
381 if !ok1 || !ok2 {
382 return v.error(n, "invalid interpolation")
383 }
384 if len(n.Elts) == 1 {
385 value = v.walk(n.Elts[0])
386 break
387 }
388 lit := &interpolation{baseValue: newExpr(n), k: stringKind}
389 value = lit
Marcel van Lohuizen6ceb6012019-02-18 18:30:38 +0100390 info, prefixLen, _, err := literal.ParseQuotes(first.Value, last.Value)
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100391 if err != nil {
392 return v.error(n, "invalid interpolation: %v", err)
393 }
Marcel van Lohuizen369e4232019-02-15 10:59:29 +0400394 prefix := ""
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100395 for i := 0; i < len(n.Elts); i += 2 {
396 l, ok := n.Elts[i].(*ast.BasicLit)
397 if !ok {
398 return v.error(n, "invalid interpolation")
399 }
Marcel van Lohuizen369e4232019-02-15 10:59:29 +0400400 s := l.Value
401 if !strings.HasPrefix(s, prefix) {
402 return v.error(l, "invalid interpolation: unmatched ')'")
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100403 }
Marcel van Lohuizen369e4232019-02-15 10:59:29 +0400404 s = l.Value[prefixLen:]
405 x := parseString(v.ctx(), l, info, s)
406 lit.parts = append(lit.parts, x)
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100407 if i+1 < len(n.Elts) {
Marcel van Lohuizen369e4232019-02-15 10:59:29 +0400408 lit.parts = append(lit.parts, v.walk(n.Elts[i+1]))
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100409 }
410 prefix = ")"
Marcel van Lohuizen369e4232019-02-15 10:59:29 +0400411 prefixLen = 1
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100412 }
413
414 case *ast.ListLit:
415 list := &list{baseValue: newExpr(n)}
416 for _, e := range n.Elts {
417 list.a = append(list.a, v.walk(e))
418 }
419 list.initLit()
420 if n.Ellipsis != token.NoPos || n.Type != nil {
Marcel van Lohuizen7d0797b2019-02-07 18:35:28 +0100421 list.len = &bound{list.baseValue, opGeq, list.len}
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100422 if n.Type != nil {
423 list.typ = v.walk(n.Type)
424 }
425 }
426 value = list
427
428 case *ast.ParenExpr:
429 value = v.walk(n.X)
430
431 case *ast.SelectorExpr:
432 v.inSelector++
433 value = &selectorExpr{
434 newExpr(n),
435 v.walk(n.X),
436 v.label(n.Sel.Name, true),
437 }
438 v.inSelector--
439
440 case *ast.IndexExpr:
441 value = &indexExpr{newExpr(n), v.walk(n.X), v.walk(n.Index)}
442
443 case *ast.SliceExpr:
444 slice := &sliceExpr{baseValue: newExpr(n), x: v.walk(n.X)}
445 if n.Low != nil {
446 slice.lo = v.walk(n.Low)
447 }
448 if n.High != nil {
449 slice.hi = v.walk(n.High)
450 }
451 value = slice
452
453 case *ast.CallExpr:
454 call := &callExpr{baseValue: newExpr(n), x: v.walk(n.Fun)}
455 for _, a := range n.Args {
456 call.args = append(call.args, v.walk(a))
457 }
458 value = call
459
460 case *ast.UnaryExpr:
Marcel van Lohuizen7d0797b2019-02-07 18:35:28 +0100461 switch n.Op {
462 case token.NOT, token.ADD, token.SUB:
463 value = &unaryExpr{
464 newExpr(n),
465 tokenMap[n.Op],
466 v.walk(n.X),
467 }
Marcel van Lohuizen706e69c2019-02-11 18:21:14 +0100468 case token.GEQ, token.GTR, token.LSS, token.LEQ,
469 token.NEQ, token.MAT, token.NMAT:
Marcel van Lohuizen7d0797b2019-02-07 18:35:28 +0100470 value = &bound{
471 newExpr(n),
472 tokenMap[n.Op],
473 v.walk(n.X),
474 }
475
476 case token.MUL:
Marcel van Lohuizenc9b3cb22019-01-30 11:32:41 +0100477 return v.error(n, "preference mark not allowed at this position")
Marcel van Lohuizen7d0797b2019-02-07 18:35:28 +0100478 default:
479 return v.error(n, "unsupported unary operator %q", n.Op)
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100480 }
481
482 case *ast.BinaryExpr:
483 switch n.Op {
Marcel van Lohuizenbedcf0c2019-02-22 18:00:00 +0100484 case token.OR:
Marcel van Lohuizenc9b3cb22019-01-30 11:32:41 +0100485 d := &disjunction{baseValue: newExpr(n)}
486 v.addDisjunctionElem(d, n.X, false)
487 v.addDisjunctionElem(d, n.Y, false)
488 value = d
Marcel van Lohuizen7d0797b2019-02-07 18:35:28 +0100489
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100490 default:
491 value = &binaryExpr{
492 newExpr(n),
493 tokenMap[n.Op], // op
494 v.walk(n.X), // left
495 v.walk(n.Y), // right
496 }
497 }
498
499 // nothing to do
500 // case *syntax.EmitDecl:
501 default:
502 // TODO: unhandled node.
503 // value = ctx.mkErr(n, "unknown node type %T", n)
504 panic(fmt.Sprintf("unimplemented %T", n))
505
506 }
507 return value
508}
509
Marcel van Lohuizenc9b3cb22019-01-30 11:32:41 +0100510func (v *astVisitor) addDisjunctionElem(d *disjunction, n ast.Node, mark bool) {
511 switch x := n.(type) {
512 case *ast.BinaryExpr:
Marcel van Lohuizenbedcf0c2019-02-22 18:00:00 +0100513 if x.Op == token.OR {
Marcel van Lohuizenc9b3cb22019-01-30 11:32:41 +0100514 v.addDisjunctionElem(d, x.X, mark)
515 v.addDisjunctionElem(d, x.Y, mark)
516 return
517 }
518 case *ast.UnaryExpr:
519 if x.Op == token.MUL {
520 mark = true
521 n = x.X
522 }
523 }
524 d.values = append(d.values, dValue{v.walk(n), mark})
525}
526
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100527func wrapClauses(v *astVisitor, y yielder, clauses []ast.Clause) yielder {
528 for _, c := range clauses {
529 if n, ok := c.(*ast.ForClause); ok {
530 params := &params{}
531 fn := &lambdaExpr{newExpr(n.Source), params, nil}
532 v.setScope(n, fn)
533 }
534 }
535 for i := len(clauses) - 1; i >= 0; i-- {
536 switch n := clauses[i].(type) {
537 case *ast.ForClause:
538 fn := v.mapScope(n).(*lambdaExpr)
539 fn.value = y
540
541 key := "_"
542 if n.Key != nil {
543 key = n.Key.Name
544 }
545 f := v.label(key, true)
546 fn.add(f, &basicType{newExpr(n.Key), stringKind | intKind})
547
548 f = v.label(n.Value.Name, true)
549 fn.add(f, &top{})
550
551 y = &feed{newExpr(n.Source), v.walk(n.Source), fn}
552
553 case *ast.IfClause:
554 y = &guard{newExpr(n.Condition), v.walk(n.Condition), y}
555 }
556 }
557 return y
558}