blob: 4c5ece597c1d754e1cdb239bd0258d23dba6d8fe [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()
Marcel van Lohuizen6ceb6012019-02-18 18:30:38 +0100130 path, err := literal.Unquote(imp.Path.Value)
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100131 if err != nil {
132 return ctx.mkErr(newNode(imp), "illformed import spec")
133 }
Marcel van Lohuizen8bc02e52019-04-01 13:14:07 +0200134 if p := getBuiltinPkg(ctx, path); p != nil {
135 return p
136 }
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100137 bimp := v.inst.LookupImport(path)
138 if bimp == nil {
139 return ctx.mkErr(newNode(imp), "package %q not found", path)
140 }
141 impInst := v.index.loadInstance(bimp)
142 return impInst.rootValue.evalPartial(ctx)
143}
144
145// We probably don't need to call Walk.s
146func (v *astVisitor) walk(astNode ast.Node) (value value) {
147 switch n := astNode.(type) {
148 case *ast.File:
149 obj := v.object
150 v1 := &astVisitor{
151 astState: v.astState,
152 object: obj,
153 }
154 for _, e := range n.Decls {
155 switch x := e.(type) {
156 case *ast.EmitDecl:
157 if v1.object.emit == nil {
158 v1.object.emit = v1.walk(x.Expr)
159 } else {
160 v1.object.emit = mkBin(v.ctx(), token.NoPos, opUnify, v1.object.emit, v1.walk(x.Expr))
161 }
162 default:
163 v1.walk(e)
164 }
165 }
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100166 value = obj
167
168 case *ast.ImportDecl:
169 for _, s := range n.Specs {
170 v.walk(s)
171 }
172
173 case *ast.ImportSpec:
174 val := v.loadImport(n)
175 if !isBottom(val) {
176 v.setScope(n, val.(*structLit))
177 }
178
179 case *ast.StructLit:
180 obj := v.mapScope(n).(*structLit)
181 v1 := &astVisitor{
182 astState: v.astState,
183 object: obj,
184 }
185 for _, e := range n.Elts {
186 switch x := e.(type) {
187 case *ast.EmitDecl:
188 // Only allowed at top-level.
189 v1.error(x, "emitting values is only allowed at top level")
190 case *ast.Field, *ast.Alias:
191 v1.walk(e)
192 case *ast.ComprehensionDecl:
193 v1.walk(x)
194 }
195 }
196 value = obj
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100197
198 case *ast.ComprehensionDecl:
199 yielder := &yield{baseValue: newExpr(n.Field.Value)}
Marcel van Lohuizen66db9202018-12-17 19:02:08 +0100200 fc := &fieldComprehension{
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100201 baseValue: newDecl(n),
202 clauses: wrapClauses(v, yielder, n.Clauses),
203 }
204 field := n.Field
205 switch x := field.Label.(type) {
206 case *ast.Interpolation:
207 yielder.key = v.walk(x)
208 yielder.value = v.walk(field.Value)
209
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100210 case *ast.TemplateLabel:
211 f := v.label(x.Ident.Name, true)
212
213 sig := &params{}
214 sig.add(f, &basicType{newNode(field.Label), stringKind})
215 template := &lambdaExpr{newExpr(field.Value), sig, nil}
216
217 v.setScope(field, template)
218 template.value = v.walk(field.Value)
219 yielder.value = template
Marcel van Lohuizen66db9202018-12-17 19:02:08 +0100220 fc.isTemplate = true
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100221
222 case *ast.BasicLit, *ast.Ident:
223 name, ok := ast.LabelName(x)
224 if !ok {
225 return v.error(x, "invalid field name: %v", x)
226 }
Marcel van Lohuizenf23fbff2018-12-20 12:23:16 +0100227
228 // TODO: if the clauses do not contain a guard, we know that this
229 // field will always be added and we can move the comprehension one
230 // level down. This, in turn, has the advantage that it is more
231 // likely that the cross-reference limitation for field
232 // comprehensions is not violated. To ensure compatibility between
233 // implementations, though, we should relax the spec as well.
234 // The cross-reference rule is simple and this relaxation seems a
235 // bit more complex.
236
237 // TODO: for now we can also consider making this an error if
238 // the list of clauses does not contain if and make a suggestion
239 // to rewrite it.
240
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100241 if name != "" {
242 yielder.key = &stringLit{newNode(x), name}
243 yielder.value = v.walk(field.Value)
244 }
245
246 default:
247 panic("cue: unknown label type")
248 }
249 // yielder.key = v.walk(n.Field.Label)
250 // yielder.value = v.walk(n.Field.Value)
Marcel van Lohuizen66db9202018-12-17 19:02:08 +0100251 v.object.comprehensions = append(v.object.comprehensions, fc)
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100252
253 case *ast.Field:
Marcel van Lohuizen08a0ef22019-03-28 09:12:19 +0100254 opt := n.Optional != token.NoPos
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100255 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 Lohuizen08a0ef22019-03-28 09:12:19 +0100264 yielder.opt = opt
Marcel van Lohuizen66db9202018-12-17 19:02:08 +0100265 v.object.comprehensions = append(v.object.comprehensions, fc)
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100266
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100267 case *ast.TemplateLabel:
268 f := v.label(x.Ident.Name, true)
269
270 sig := &params{}
271 sig.add(f, &basicType{newNode(n.Label), stringKind})
272 template := &lambdaExpr{newExpr(n.Value), sig, nil}
273
274 v.setScope(n, template)
275 template.value = v.walk(n.Value)
276
277 if v.object.template == nil {
278 v.object.template = template
279 } else {
280 v.object.template = mkBin(v.ctx(), token.NoPos, opUnify, v.object.template, template)
281 }
282
283 case *ast.BasicLit, *ast.Ident:
Marcel van Lohuizenb9b62d32019-03-14 23:50:15 +0100284 attrs, err := createAttrs(v.ctx(), newNode(n), n.Attrs)
285 if err != nil {
286 return err
287 }
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100288 f, ok := v.nodeLabel(x)
289 if !ok {
290 return v.error(n.Label, "invalid field name: %v", n.Label)
291 }
292 if f != 0 {
Marcel van Lohuizen08a0ef22019-03-28 09:12:19 +0100293 v.object.insertValue(v.ctx(), f, opt, v.walk(n.Value), attrs)
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100294 }
295
296 default:
297 panic("cue: unknown label type")
298 }
299
300 case *ast.Alias:
301 // parsed verbatim at reference.
302
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100303 case *ast.ListComprehension:
304 yielder := &yield{baseValue: newExpr(n.Expr)}
305 lc := &listComprehension{
306 newExpr(n),
307 wrapClauses(v, yielder, n.Clauses),
308 }
309 // we don't support key for lists (yet?)
310 yielder.value = v.walk(n.Expr)
311 return lc
312
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100313 // Expressions
314 case *ast.Ident:
315 if n.Node == nil {
316 if value = v.resolve(n); value != nil {
317 break
318 }
319
320 switch n.Name {
321 case "_":
322 return &top{newExpr(n)}
323 case "string":
324 return &basicType{newExpr(n), stringKind}
325 case "bytes":
326 return &basicType{newExpr(n), bytesKind}
327 case "bool":
328 return &basicType{newExpr(n), boolKind}
329 case "int":
330 return &basicType{newExpr(n), intKind}
331 case "float":
332 return &basicType{newExpr(n), floatKind}
333 case "number":
334 return &basicType{newExpr(n), numKind}
335 case "duration":
336 return &basicType{newExpr(n), durationKind}
337
338 case "len":
339 return lenBuiltin
340 }
341 if r, ok := predefinedRanges[n.Name]; ok {
342 return r
343 }
344
345 value = v.error(n, "reference %q not found", n.Name)
346 break
347 }
348
349 if a, ok := n.Node.(*ast.Alias); ok {
350 value = v.walk(a.Expr)
351 break
352 }
353
354 label := v.label(n.Name, true)
355 if n.Scope != nil {
356 n2 := v.mapScope(n.Scope)
357 value = &nodeRef{baseValue: newExpr(n), node: n2}
358 value = &selectorExpr{newExpr(n), value, label}
359 } else {
360 n2 := v.mapScope(n.Node)
361 value = &nodeRef{baseValue: newExpr(n), node: n2}
362 }
363
364 case *ast.BottomLit:
365 value = v.error(n, "from source")
366
367 case *ast.BadDecl:
368 // nothing to do
369
370 case *ast.BadExpr:
371 value = v.error(n, "invalid expression")
372
373 case *ast.BasicLit:
374 value = v.litParser.parse(n)
375
376 case *ast.Interpolation:
377 if len(n.Elts) == 0 {
378 return v.error(n, "invalid interpolation")
379 }
380 first, ok1 := n.Elts[0].(*ast.BasicLit)
381 last, ok2 := n.Elts[len(n.Elts)-1].(*ast.BasicLit)
382 if !ok1 || !ok2 {
383 return v.error(n, "invalid interpolation")
384 }
385 if len(n.Elts) == 1 {
386 value = v.walk(n.Elts[0])
387 break
388 }
389 lit := &interpolation{baseValue: newExpr(n), k: stringKind}
390 value = lit
Marcel van Lohuizen6ceb6012019-02-18 18:30:38 +0100391 info, prefixLen, _, err := literal.ParseQuotes(first.Value, last.Value)
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100392 if err != nil {
393 return v.error(n, "invalid interpolation: %v", err)
394 }
Marcel van Lohuizen369e4232019-02-15 10:59:29 +0400395 prefix := ""
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100396 for i := 0; i < len(n.Elts); i += 2 {
397 l, ok := n.Elts[i].(*ast.BasicLit)
398 if !ok {
399 return v.error(n, "invalid interpolation")
400 }
Marcel van Lohuizen369e4232019-02-15 10:59:29 +0400401 s := l.Value
402 if !strings.HasPrefix(s, prefix) {
403 return v.error(l, "invalid interpolation: unmatched ')'")
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100404 }
Marcel van Lohuizen369e4232019-02-15 10:59:29 +0400405 s = l.Value[prefixLen:]
406 x := parseString(v.ctx(), l, info, s)
407 lit.parts = append(lit.parts, x)
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100408 if i+1 < len(n.Elts) {
Marcel van Lohuizen369e4232019-02-15 10:59:29 +0400409 lit.parts = append(lit.parts, v.walk(n.Elts[i+1]))
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100410 }
411 prefix = ")"
Marcel van Lohuizen369e4232019-02-15 10:59:29 +0400412 prefixLen = 1
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100413 }
414
415 case *ast.ListLit:
416 list := &list{baseValue: newExpr(n)}
417 for _, e := range n.Elts {
418 list.a = append(list.a, v.walk(e))
419 }
420 list.initLit()
421 if n.Ellipsis != token.NoPos || n.Type != nil {
Marcel van Lohuizen7d0797b2019-02-07 18:35:28 +0100422 list.len = &bound{list.baseValue, opGeq, list.len}
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100423 if n.Type != nil {
424 list.typ = v.walk(n.Type)
425 }
426 }
427 value = list
428
429 case *ast.ParenExpr:
430 value = v.walk(n.X)
431
432 case *ast.SelectorExpr:
433 v.inSelector++
434 value = &selectorExpr{
435 newExpr(n),
436 v.walk(n.X),
437 v.label(n.Sel.Name, true),
438 }
439 v.inSelector--
440
441 case *ast.IndexExpr:
442 value = &indexExpr{newExpr(n), v.walk(n.X), v.walk(n.Index)}
443
444 case *ast.SliceExpr:
445 slice := &sliceExpr{baseValue: newExpr(n), x: v.walk(n.X)}
446 if n.Low != nil {
447 slice.lo = v.walk(n.Low)
448 }
449 if n.High != nil {
450 slice.hi = v.walk(n.High)
451 }
452 value = slice
453
454 case *ast.CallExpr:
455 call := &callExpr{baseValue: newExpr(n), x: v.walk(n.Fun)}
456 for _, a := range n.Args {
457 call.args = append(call.args, v.walk(a))
458 }
459 value = call
460
461 case *ast.UnaryExpr:
Marcel van Lohuizen7d0797b2019-02-07 18:35:28 +0100462 switch n.Op {
463 case token.NOT, token.ADD, token.SUB:
464 value = &unaryExpr{
465 newExpr(n),
466 tokenMap[n.Op],
467 v.walk(n.X),
468 }
Marcel van Lohuizen706e69c2019-02-11 18:21:14 +0100469 case token.GEQ, token.GTR, token.LSS, token.LEQ,
470 token.NEQ, token.MAT, token.NMAT:
Marcel van Lohuizen7d0797b2019-02-07 18:35:28 +0100471 value = &bound{
472 newExpr(n),
473 tokenMap[n.Op],
474 v.walk(n.X),
475 }
476
477 case token.MUL:
Marcel van Lohuizenc9b3cb22019-01-30 11:32:41 +0100478 return v.error(n, "preference mark not allowed at this position")
Marcel van Lohuizen7d0797b2019-02-07 18:35:28 +0100479 default:
480 return v.error(n, "unsupported unary operator %q", n.Op)
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100481 }
482
483 case *ast.BinaryExpr:
484 switch n.Op {
Marcel van Lohuizenbedcf0c2019-02-22 18:00:00 +0100485 case token.OR:
Marcel van Lohuizenc9b3cb22019-01-30 11:32:41 +0100486 d := &disjunction{baseValue: newExpr(n)}
487 v.addDisjunctionElem(d, n.X, false)
488 v.addDisjunctionElem(d, n.Y, false)
489 value = d
Marcel van Lohuizen7d0797b2019-02-07 18:35:28 +0100490
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100491 default:
492 value = &binaryExpr{
493 newExpr(n),
494 tokenMap[n.Op], // op
495 v.walk(n.X), // left
496 v.walk(n.Y), // right
497 }
498 }
499
500 // nothing to do
501 // case *syntax.EmitDecl:
502 default:
503 // TODO: unhandled node.
504 // value = ctx.mkErr(n, "unknown node type %T", n)
505 panic(fmt.Sprintf("unimplemented %T", n))
506
507 }
508 return value
509}
510
Marcel van Lohuizenc9b3cb22019-01-30 11:32:41 +0100511func (v *astVisitor) addDisjunctionElem(d *disjunction, n ast.Node, mark bool) {
512 switch x := n.(type) {
513 case *ast.BinaryExpr:
Marcel van Lohuizenbedcf0c2019-02-22 18:00:00 +0100514 if x.Op == token.OR {
Marcel van Lohuizenc9b3cb22019-01-30 11:32:41 +0100515 v.addDisjunctionElem(d, x.X, mark)
516 v.addDisjunctionElem(d, x.Y, mark)
517 return
518 }
519 case *ast.UnaryExpr:
520 if x.Op == token.MUL {
521 mark = true
522 n = x.X
523 }
524 }
525 d.values = append(d.values, dValue{v.walk(n), mark})
526}
527
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100528func wrapClauses(v *astVisitor, y yielder, clauses []ast.Clause) yielder {
529 for _, c := range clauses {
530 if n, ok := c.(*ast.ForClause); ok {
531 params := &params{}
532 fn := &lambdaExpr{newExpr(n.Source), params, nil}
533 v.setScope(n, fn)
534 }
535 }
536 for i := len(clauses) - 1; i >= 0; i-- {
537 switch n := clauses[i].(type) {
538 case *ast.ForClause:
539 fn := v.mapScope(n).(*lambdaExpr)
540 fn.value = y
541
542 key := "_"
543 if n.Key != nil {
544 key = n.Key.Name
545 }
546 f := v.label(key, true)
547 fn.add(f, &basicType{newExpr(n.Key), stringKind | intKind})
548
549 f = v.label(n.Value.Name, true)
550 fn.add(f, &top{})
551
552 y = &feed{newExpr(n.Source), v.walk(n.Source), fn}
553
554 case *ast.IfClause:
555 y = &guard{newExpr(n.Condition), v.walk(n.Condition), y}
556 }
557 }
558 return y
559}