blob: 9bfc98ec09ca6a505150bb0ed968ff908156ca4d [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:
283 f, ok := v.nodeLabel(x)
284 if !ok {
285 return v.error(n.Label, "invalid field name: %v", n.Label)
286 }
287 if f != 0 {
288 v.object.insertValue(v.ctx(), f, v.walk(n.Value))
289 }
290
291 default:
292 panic("cue: unknown label type")
293 }
294
295 case *ast.Alias:
296 // parsed verbatim at reference.
297
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100298 case *ast.ListComprehension:
299 yielder := &yield{baseValue: newExpr(n.Expr)}
300 lc := &listComprehension{
301 newExpr(n),
302 wrapClauses(v, yielder, n.Clauses),
303 }
304 // we don't support key for lists (yet?)
305 yielder.value = v.walk(n.Expr)
306 return lc
307
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100308 // Expressions
309 case *ast.Ident:
310 if n.Node == nil {
311 if value = v.resolve(n); value != nil {
312 break
313 }
314
315 switch n.Name {
316 case "_":
317 return &top{newExpr(n)}
318 case "string":
319 return &basicType{newExpr(n), stringKind}
320 case "bytes":
321 return &basicType{newExpr(n), bytesKind}
322 case "bool":
323 return &basicType{newExpr(n), boolKind}
324 case "int":
325 return &basicType{newExpr(n), intKind}
326 case "float":
327 return &basicType{newExpr(n), floatKind}
328 case "number":
329 return &basicType{newExpr(n), numKind}
330 case "duration":
331 return &basicType{newExpr(n), durationKind}
332
333 case "len":
334 return lenBuiltin
335 }
336 if r, ok := predefinedRanges[n.Name]; ok {
337 return r
338 }
339
340 value = v.error(n, "reference %q not found", n.Name)
341 break
342 }
343
344 if a, ok := n.Node.(*ast.Alias); ok {
345 value = v.walk(a.Expr)
346 break
347 }
348
349 label := v.label(n.Name, true)
350 if n.Scope != nil {
351 n2 := v.mapScope(n.Scope)
352 value = &nodeRef{baseValue: newExpr(n), node: n2}
353 value = &selectorExpr{newExpr(n), value, label}
354 } else {
355 n2 := v.mapScope(n.Node)
356 value = &nodeRef{baseValue: newExpr(n), node: n2}
357 }
358
359 case *ast.BottomLit:
360 value = v.error(n, "from source")
361
362 case *ast.BadDecl:
363 // nothing to do
364
365 case *ast.BadExpr:
366 value = v.error(n, "invalid expression")
367
368 case *ast.BasicLit:
369 value = v.litParser.parse(n)
370
371 case *ast.Interpolation:
372 if len(n.Elts) == 0 {
373 return v.error(n, "invalid interpolation")
374 }
375 first, ok1 := n.Elts[0].(*ast.BasicLit)
376 last, ok2 := n.Elts[len(n.Elts)-1].(*ast.BasicLit)
377 if !ok1 || !ok2 {
378 return v.error(n, "invalid interpolation")
379 }
380 if len(n.Elts) == 1 {
381 value = v.walk(n.Elts[0])
382 break
383 }
384 lit := &interpolation{baseValue: newExpr(n), k: stringKind}
385 value = lit
Marcel van Lohuizen6ceb6012019-02-18 18:30:38 +0100386 info, prefixLen, _, err := literal.ParseQuotes(first.Value, last.Value)
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100387 if err != nil {
388 return v.error(n, "invalid interpolation: %v", err)
389 }
Marcel van Lohuizen369e4232019-02-15 10:59:29 +0400390 prefix := ""
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100391 for i := 0; i < len(n.Elts); i += 2 {
392 l, ok := n.Elts[i].(*ast.BasicLit)
393 if !ok {
394 return v.error(n, "invalid interpolation")
395 }
Marcel van Lohuizen369e4232019-02-15 10:59:29 +0400396 s := l.Value
397 if !strings.HasPrefix(s, prefix) {
398 return v.error(l, "invalid interpolation: unmatched ')'")
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100399 }
Marcel van Lohuizen369e4232019-02-15 10:59:29 +0400400 s = l.Value[prefixLen:]
401 x := parseString(v.ctx(), l, info, s)
402 lit.parts = append(lit.parts, x)
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100403 if i+1 < len(n.Elts) {
Marcel van Lohuizen369e4232019-02-15 10:59:29 +0400404 lit.parts = append(lit.parts, v.walk(n.Elts[i+1]))
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100405 }
406 prefix = ")"
Marcel van Lohuizen369e4232019-02-15 10:59:29 +0400407 prefixLen = 1
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100408 }
409
410 case *ast.ListLit:
411 list := &list{baseValue: newExpr(n)}
412 for _, e := range n.Elts {
413 list.a = append(list.a, v.walk(e))
414 }
415 list.initLit()
416 if n.Ellipsis != token.NoPos || n.Type != nil {
Marcel van Lohuizen7d0797b2019-02-07 18:35:28 +0100417 list.len = &bound{list.baseValue, opGeq, list.len}
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100418 if n.Type != nil {
419 list.typ = v.walk(n.Type)
420 }
421 }
422 value = list
423
424 case *ast.ParenExpr:
425 value = v.walk(n.X)
426
427 case *ast.SelectorExpr:
428 v.inSelector++
429 value = &selectorExpr{
430 newExpr(n),
431 v.walk(n.X),
432 v.label(n.Sel.Name, true),
433 }
434 v.inSelector--
435
436 case *ast.IndexExpr:
437 value = &indexExpr{newExpr(n), v.walk(n.X), v.walk(n.Index)}
438
439 case *ast.SliceExpr:
440 slice := &sliceExpr{baseValue: newExpr(n), x: v.walk(n.X)}
441 if n.Low != nil {
442 slice.lo = v.walk(n.Low)
443 }
444 if n.High != nil {
445 slice.hi = v.walk(n.High)
446 }
447 value = slice
448
449 case *ast.CallExpr:
450 call := &callExpr{baseValue: newExpr(n), x: v.walk(n.Fun)}
451 for _, a := range n.Args {
452 call.args = append(call.args, v.walk(a))
453 }
454 value = call
455
456 case *ast.UnaryExpr:
Marcel van Lohuizen7d0797b2019-02-07 18:35:28 +0100457 switch n.Op {
458 case token.NOT, token.ADD, token.SUB:
459 value = &unaryExpr{
460 newExpr(n),
461 tokenMap[n.Op],
462 v.walk(n.X),
463 }
Marcel van Lohuizen706e69c2019-02-11 18:21:14 +0100464 case token.GEQ, token.GTR, token.LSS, token.LEQ,
465 token.NEQ, token.MAT, token.NMAT:
Marcel van Lohuizen7d0797b2019-02-07 18:35:28 +0100466 value = &bound{
467 newExpr(n),
468 tokenMap[n.Op],
469 v.walk(n.X),
470 }
471
472 case token.MUL:
Marcel van Lohuizenc9b3cb22019-01-30 11:32:41 +0100473 return v.error(n, "preference mark not allowed at this position")
Marcel van Lohuizen7d0797b2019-02-07 18:35:28 +0100474 default:
475 return v.error(n, "unsupported unary operator %q", n.Op)
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100476 }
477
478 case *ast.BinaryExpr:
479 switch n.Op {
Marcel van Lohuizenbedcf0c2019-02-22 18:00:00 +0100480 case token.OR:
Marcel van Lohuizenc9b3cb22019-01-30 11:32:41 +0100481 d := &disjunction{baseValue: newExpr(n)}
482 v.addDisjunctionElem(d, n.X, false)
483 v.addDisjunctionElem(d, n.Y, false)
484 value = d
Marcel van Lohuizen7d0797b2019-02-07 18:35:28 +0100485
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100486 default:
487 value = &binaryExpr{
488 newExpr(n),
489 tokenMap[n.Op], // op
490 v.walk(n.X), // left
491 v.walk(n.Y), // right
492 }
493 }
494
495 // nothing to do
496 // case *syntax.EmitDecl:
497 default:
498 // TODO: unhandled node.
499 // value = ctx.mkErr(n, "unknown node type %T", n)
500 panic(fmt.Sprintf("unimplemented %T", n))
501
502 }
503 return value
504}
505
Marcel van Lohuizenc9b3cb22019-01-30 11:32:41 +0100506func (v *astVisitor) addDisjunctionElem(d *disjunction, n ast.Node, mark bool) {
507 switch x := n.(type) {
508 case *ast.BinaryExpr:
Marcel van Lohuizenbedcf0c2019-02-22 18:00:00 +0100509 if x.Op == token.OR {
Marcel van Lohuizenc9b3cb22019-01-30 11:32:41 +0100510 v.addDisjunctionElem(d, x.X, mark)
511 v.addDisjunctionElem(d, x.Y, mark)
512 return
513 }
514 case *ast.UnaryExpr:
515 if x.Op == token.MUL {
516 mark = true
517 n = x.X
518 }
519 }
520 d.values = append(d.values, dValue{v.walk(n), mark})
521}
522
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100523func wrapClauses(v *astVisitor, y yielder, clauses []ast.Clause) yielder {
524 for _, c := range clauses {
525 if n, ok := c.(*ast.ForClause); ok {
526 params := &params{}
527 fn := &lambdaExpr{newExpr(n.Source), params, nil}
528 v.setScope(n, fn)
529 }
530 }
531 for i := len(clauses) - 1; i >= 0; i-- {
532 switch n := clauses[i].(type) {
533 case *ast.ForClause:
534 fn := v.mapScope(n).(*lambdaExpr)
535 fn.value = y
536
537 key := "_"
538 if n.Key != nil {
539 key = n.Key.Name
540 }
541 f := v.label(key, true)
542 fn.add(f, &basicType{newExpr(n.Key), stringKind | intKind})
543
544 f = v.label(n.Value.Name, true)
545 fn.add(f, &top{})
546
547 y = &feed{newExpr(n.Source), v.walk(n.Source), fn}
548
549 case *ast.IfClause:
550 y = &guard{newExpr(n.Condition), v.walk(n.Condition), y}
551 }
552 }
553 return y
554}