blob: 5e02b9ecbca730456fa8095edf08cb65e02778b6 [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 {
Marcel van Lohuizen08a0ef22019-03-28 09:12:19 +0100115 if a := r.lookup(v.ctx(), label); a.val() != nil {
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100116 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:
Marcel van Lohuizen08a0ef22019-03-28 09:12:19 +0100255 opt := n.Optional != token.NoPos
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100256 switch x := n.Label.(type) {
257 case *ast.Interpolation:
258 yielder := &yield{baseValue: newNode(x)}
Marcel van Lohuizen66db9202018-12-17 19:02:08 +0100259 fc := &fieldComprehension{
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100260 baseValue: newDecl(n),
261 clauses: yielder,
262 }
263 yielder.key = v.walk(x)
264 yielder.value = v.walk(n.Value)
Marcel van Lohuizen08a0ef22019-03-28 09:12:19 +0100265 yielder.opt = opt
Marcel van Lohuizen66db9202018-12-17 19:02:08 +0100266 v.object.comprehensions = append(v.object.comprehensions, fc)
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100267
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100268 case *ast.TemplateLabel:
269 f := v.label(x.Ident.Name, true)
270
271 sig := &params{}
272 sig.add(f, &basicType{newNode(n.Label), stringKind})
273 template := &lambdaExpr{newExpr(n.Value), sig, nil}
274
275 v.setScope(n, template)
276 template.value = v.walk(n.Value)
277
278 if v.object.template == nil {
279 v.object.template = template
280 } else {
281 v.object.template = mkBin(v.ctx(), token.NoPos, opUnify, v.object.template, template)
282 }
283
284 case *ast.BasicLit, *ast.Ident:
Marcel van Lohuizenb9b62d32019-03-14 23:50:15 +0100285 attrs, err := createAttrs(v.ctx(), newNode(n), n.Attrs)
286 if err != nil {
287 return err
288 }
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100289 f, ok := v.nodeLabel(x)
290 if !ok {
291 return v.error(n.Label, "invalid field name: %v", n.Label)
292 }
293 if f != 0 {
Marcel van Lohuizen08a0ef22019-03-28 09:12:19 +0100294 v.object.insertValue(v.ctx(), f, opt, v.walk(n.Value), attrs)
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100295 }
296
297 default:
298 panic("cue: unknown label type")
299 }
300
301 case *ast.Alias:
302 // parsed verbatim at reference.
303
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100304 case *ast.ListComprehension:
305 yielder := &yield{baseValue: newExpr(n.Expr)}
306 lc := &listComprehension{
307 newExpr(n),
308 wrapClauses(v, yielder, n.Clauses),
309 }
310 // we don't support key for lists (yet?)
311 yielder.value = v.walk(n.Expr)
312 return lc
313
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100314 // Expressions
315 case *ast.Ident:
316 if n.Node == nil {
317 if value = v.resolve(n); value != nil {
318 break
319 }
320
321 switch n.Name {
322 case "_":
323 return &top{newExpr(n)}
324 case "string":
325 return &basicType{newExpr(n), stringKind}
326 case "bytes":
327 return &basicType{newExpr(n), bytesKind}
328 case "bool":
329 return &basicType{newExpr(n), boolKind}
330 case "int":
331 return &basicType{newExpr(n), intKind}
332 case "float":
333 return &basicType{newExpr(n), floatKind}
334 case "number":
335 return &basicType{newExpr(n), numKind}
336 case "duration":
337 return &basicType{newExpr(n), durationKind}
338
339 case "len":
340 return lenBuiltin
341 }
342 if r, ok := predefinedRanges[n.Name]; ok {
343 return r
344 }
345
346 value = v.error(n, "reference %q not found", n.Name)
347 break
348 }
349
350 if a, ok := n.Node.(*ast.Alias); ok {
351 value = v.walk(a.Expr)
352 break
353 }
354
355 label := v.label(n.Name, true)
356 if n.Scope != nil {
357 n2 := v.mapScope(n.Scope)
358 value = &nodeRef{baseValue: newExpr(n), node: n2}
359 value = &selectorExpr{newExpr(n), value, label}
360 } else {
361 n2 := v.mapScope(n.Node)
362 value = &nodeRef{baseValue: newExpr(n), node: n2}
363 }
364
365 case *ast.BottomLit:
366 value = v.error(n, "from source")
367
368 case *ast.BadDecl:
369 // nothing to do
370
371 case *ast.BadExpr:
372 value = v.error(n, "invalid expression")
373
374 case *ast.BasicLit:
375 value = v.litParser.parse(n)
376
377 case *ast.Interpolation:
378 if len(n.Elts) == 0 {
379 return v.error(n, "invalid interpolation")
380 }
381 first, ok1 := n.Elts[0].(*ast.BasicLit)
382 last, ok2 := n.Elts[len(n.Elts)-1].(*ast.BasicLit)
383 if !ok1 || !ok2 {
384 return v.error(n, "invalid interpolation")
385 }
386 if len(n.Elts) == 1 {
387 value = v.walk(n.Elts[0])
388 break
389 }
390 lit := &interpolation{baseValue: newExpr(n), k: stringKind}
391 value = lit
Marcel van Lohuizen6ceb6012019-02-18 18:30:38 +0100392 info, prefixLen, _, err := literal.ParseQuotes(first.Value, last.Value)
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100393 if err != nil {
394 return v.error(n, "invalid interpolation: %v", err)
395 }
Marcel van Lohuizen369e4232019-02-15 10:59:29 +0400396 prefix := ""
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100397 for i := 0; i < len(n.Elts); i += 2 {
398 l, ok := n.Elts[i].(*ast.BasicLit)
399 if !ok {
400 return v.error(n, "invalid interpolation")
401 }
Marcel van Lohuizen369e4232019-02-15 10:59:29 +0400402 s := l.Value
403 if !strings.HasPrefix(s, prefix) {
404 return v.error(l, "invalid interpolation: unmatched ')'")
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100405 }
Marcel van Lohuizen369e4232019-02-15 10:59:29 +0400406 s = l.Value[prefixLen:]
407 x := parseString(v.ctx(), l, info, s)
408 lit.parts = append(lit.parts, x)
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100409 if i+1 < len(n.Elts) {
Marcel van Lohuizen369e4232019-02-15 10:59:29 +0400410 lit.parts = append(lit.parts, v.walk(n.Elts[i+1]))
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100411 }
412 prefix = ")"
Marcel van Lohuizen369e4232019-02-15 10:59:29 +0400413 prefixLen = 1
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100414 }
415
416 case *ast.ListLit:
417 list := &list{baseValue: newExpr(n)}
418 for _, e := range n.Elts {
419 list.a = append(list.a, v.walk(e))
420 }
421 list.initLit()
422 if n.Ellipsis != token.NoPos || n.Type != nil {
Marcel van Lohuizen7d0797b2019-02-07 18:35:28 +0100423 list.len = &bound{list.baseValue, opGeq, list.len}
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100424 if n.Type != nil {
425 list.typ = v.walk(n.Type)
426 }
427 }
428 value = list
429
430 case *ast.ParenExpr:
431 value = v.walk(n.X)
432
433 case *ast.SelectorExpr:
434 v.inSelector++
435 value = &selectorExpr{
436 newExpr(n),
437 v.walk(n.X),
438 v.label(n.Sel.Name, true),
439 }
440 v.inSelector--
441
442 case *ast.IndexExpr:
443 value = &indexExpr{newExpr(n), v.walk(n.X), v.walk(n.Index)}
444
445 case *ast.SliceExpr:
446 slice := &sliceExpr{baseValue: newExpr(n), x: v.walk(n.X)}
447 if n.Low != nil {
448 slice.lo = v.walk(n.Low)
449 }
450 if n.High != nil {
451 slice.hi = v.walk(n.High)
452 }
453 value = slice
454
455 case *ast.CallExpr:
456 call := &callExpr{baseValue: newExpr(n), x: v.walk(n.Fun)}
457 for _, a := range n.Args {
458 call.args = append(call.args, v.walk(a))
459 }
460 value = call
461
462 case *ast.UnaryExpr:
Marcel van Lohuizen7d0797b2019-02-07 18:35:28 +0100463 switch n.Op {
464 case token.NOT, token.ADD, token.SUB:
465 value = &unaryExpr{
466 newExpr(n),
467 tokenMap[n.Op],
468 v.walk(n.X),
469 }
Marcel van Lohuizen706e69c2019-02-11 18:21:14 +0100470 case token.GEQ, token.GTR, token.LSS, token.LEQ,
471 token.NEQ, token.MAT, token.NMAT:
Marcel van Lohuizen7d0797b2019-02-07 18:35:28 +0100472 value = &bound{
473 newExpr(n),
474 tokenMap[n.Op],
475 v.walk(n.X),
476 }
477
478 case token.MUL:
Marcel van Lohuizenc9b3cb22019-01-30 11:32:41 +0100479 return v.error(n, "preference mark not allowed at this position")
Marcel van Lohuizen7d0797b2019-02-07 18:35:28 +0100480 default:
481 return v.error(n, "unsupported unary operator %q", n.Op)
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100482 }
483
484 case *ast.BinaryExpr:
485 switch n.Op {
Marcel van Lohuizenbedcf0c2019-02-22 18:00:00 +0100486 case token.OR:
Marcel van Lohuizenc9b3cb22019-01-30 11:32:41 +0100487 d := &disjunction{baseValue: newExpr(n)}
488 v.addDisjunctionElem(d, n.X, false)
489 v.addDisjunctionElem(d, n.Y, false)
490 value = d
Marcel van Lohuizen7d0797b2019-02-07 18:35:28 +0100491
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100492 default:
493 value = &binaryExpr{
494 newExpr(n),
495 tokenMap[n.Op], // op
496 v.walk(n.X), // left
497 v.walk(n.Y), // right
498 }
499 }
500
501 // nothing to do
502 // case *syntax.EmitDecl:
503 default:
504 // TODO: unhandled node.
505 // value = ctx.mkErr(n, "unknown node type %T", n)
506 panic(fmt.Sprintf("unimplemented %T", n))
507
508 }
509 return value
510}
511
Marcel van Lohuizenc9b3cb22019-01-30 11:32:41 +0100512func (v *astVisitor) addDisjunctionElem(d *disjunction, n ast.Node, mark bool) {
513 switch x := n.(type) {
514 case *ast.BinaryExpr:
Marcel van Lohuizenbedcf0c2019-02-22 18:00:00 +0100515 if x.Op == token.OR {
Marcel van Lohuizenc9b3cb22019-01-30 11:32:41 +0100516 v.addDisjunctionElem(d, x.X, mark)
517 v.addDisjunctionElem(d, x.Y, mark)
518 return
519 }
520 case *ast.UnaryExpr:
521 if x.Op == token.MUL {
522 mark = true
523 n = x.X
524 }
525 }
526 d.values = append(d.values, dValue{v.walk(n), mark})
527}
528
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100529func wrapClauses(v *astVisitor, y yielder, clauses []ast.Clause) yielder {
530 for _, c := range clauses {
531 if n, ok := c.(*ast.ForClause); ok {
532 params := &params{}
533 fn := &lambdaExpr{newExpr(n.Source), params, nil}
534 v.setScope(n, fn)
535 }
536 }
537 for i := len(clauses) - 1; i >= 0; i-- {
538 switch n := clauses[i].(type) {
539 case *ast.ForClause:
540 fn := v.mapScope(n).(*lambdaExpr)
541 fn.value = y
542
543 key := "_"
544 if n.Key != nil {
545 key = n.Key.Name
546 }
547 f := v.label(key, true)
548 fn.add(f, &basicType{newExpr(n.Key), stringKind | intKind})
549
550 f = v.label(n.Value.Name, true)
551 fn.add(f, &top{})
552
553 y = &feed{newExpr(n.Source), v.walk(n.Source), fn}
554
555 case *ast.IfClause:
556 y = &guard{newExpr(n.Condition), v.walk(n.Condition), y}
557 }
558 }
559 return y
560}