blob: dcb8d1cb2a3ac6898e7808665cdba9dc3a0577bf [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"
19 "strconv"
20
21 "cuelang.org/go/cue/ast"
22 "cuelang.org/go/cue/build"
23 "cuelang.org/go/cue/token"
24)
25
26// insertFile inserts the given file at the root of the instance.
27//
28// The contents will be merged (unified) with any pre-existing value. In this
29// case an error may be reported, but only if the merge failed at the top-level.
30// Other errors will be recorded at the respective values in the tree.
31//
32// There should be no unresolved identifiers in file, meaning the Node field
33// of all identifiers should be set to a non-nil value.
34func (inst *Instance) insertFile(f *ast.File) error {
35 // TODO: insert by converting to value first so that the trim command can
36 // also remove top-level fields.
37 // First process single file.
38 v := newVisitor(inst.index, inst.inst, inst.rootStruct, inst.scope)
39 v.astState.astMap[f] = inst.rootStruct
40 result := v.walk(f)
41 if isBottom(result) {
42 return result.(*bottom)
43 }
44
45 for _, c := range v.comprehensions {
46 inst.rootValue = mkBin(v.ctx(), token.NoPos, opUnify, inst.rootValue, c)
47 }
48
49 return nil
50}
51
52type astVisitor struct {
53 *astState
54 object *structLit
55 comprehensions []*structComprehension
56
57 inSelector int
58}
59
60func (v *astVisitor) ctx() *context {
61 return v.astState.ctx
62}
63
64type astState struct {
65 ctx *context
66 *index
67 inst *build.Instance
68
69 litParser *litParser
70 resolveRoot *structLit
71
72 // make unique per level to avoid reuse of structs being an issue.
73 astMap map[ast.Node]scope
74}
75
76func (s *astState) mapScope(n ast.Node) (m scope) {
77 if m = s.astMap[n]; m == nil {
78 m = newStruct(newNode(n))
79 s.astMap[n] = m
80 }
81 return m
82}
83
84func (s *astState) setScope(n ast.Node, v scope) {
85 if m, ok := s.astMap[n]; ok && m != v {
86 panic("already defined")
87 }
88 s.astMap[n] = v
89}
90
91func newVisitor(idx *index, inst *build.Instance, obj, resolveRoot *structLit) *astVisitor {
92 ctx := idx.newContext()
93 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 }
134 path, err := strconv.Unquote(imp.Path.Value)
135 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 }
167 for _, c := range v1.comprehensions {
168 v.comprehensions = append(v.comprehensions, c)
169 }
170 value = obj
171
172 case *ast.ImportDecl:
173 for _, s := range n.Specs {
174 v.walk(s)
175 }
176
177 case *ast.ImportSpec:
178 val := v.loadImport(n)
179 if !isBottom(val) {
180 v.setScope(n, val.(*structLit))
181 }
182
183 case *ast.StructLit:
184 obj := v.mapScope(n).(*structLit)
185 v1 := &astVisitor{
186 astState: v.astState,
187 object: obj,
188 }
189 for _, e := range n.Elts {
190 switch x := e.(type) {
191 case *ast.EmitDecl:
192 // Only allowed at top-level.
193 v1.error(x, "emitting values is only allowed at top level")
194 case *ast.Field, *ast.Alias:
195 v1.walk(e)
196 case *ast.ComprehensionDecl:
197 v1.walk(x)
198 }
199 }
200 value = obj
201 for i, c := range v1.comprehensions {
202 if i == 0 && obj.template == nil && len(obj.arcs) == 0 {
203 value = c
204 continue
205 }
206 value = mkBin(v.ctx(), token.NoPos, opUnify, value, c)
207 }
208
209 case *ast.ComprehensionDecl:
210 yielder := &yield{baseValue: newExpr(n.Field.Value)}
211 sc := &structComprehension{
212 baseValue: newDecl(n),
213 clauses: wrapClauses(v, yielder, n.Clauses),
214 }
215 field := n.Field
216 switch x := field.Label.(type) {
217 case *ast.Interpolation:
218 yielder.key = v.walk(x)
219 yielder.value = v.walk(field.Value)
220
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100221 case *ast.TemplateLabel:
222 f := v.label(x.Ident.Name, true)
223
224 sig := &params{}
225 sig.add(f, &basicType{newNode(field.Label), stringKind})
226 template := &lambdaExpr{newExpr(field.Value), sig, nil}
227
228 v.setScope(field, template)
229 template.value = v.walk(field.Value)
230 yielder.value = template
231 sc.isTemplate = true
232
233 case *ast.BasicLit, *ast.Ident:
234 name, ok := ast.LabelName(x)
235 if !ok {
236 return v.error(x, "invalid field name: %v", x)
237 }
238 if name != "" {
239 yielder.key = &stringLit{newNode(x), name}
240 yielder.value = v.walk(field.Value)
241 }
242
243 default:
244 panic("cue: unknown label type")
245 }
246 // yielder.key = v.walk(n.Field.Label)
247 // yielder.value = v.walk(n.Field.Value)
248 v.comprehensions = append(v.comprehensions, sc)
249
250 case *ast.Field:
251 switch x := n.Label.(type) {
252 case *ast.Interpolation:
253 yielder := &yield{baseValue: newNode(x)}
254 sc := &structComprehension{
255 baseValue: newDecl(n),
256 clauses: yielder,
257 }
258 yielder.key = v.walk(x)
259 yielder.value = v.walk(n.Value)
260 v.comprehensions = append(v.comprehensions, sc)
261
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100262 case *ast.TemplateLabel:
263 f := v.label(x.Ident.Name, true)
264
265 sig := &params{}
266 sig.add(f, &basicType{newNode(n.Label), stringKind})
267 template := &lambdaExpr{newExpr(n.Value), sig, nil}
268
269 v.setScope(n, template)
270 template.value = v.walk(n.Value)
271
272 if v.object.template == nil {
273 v.object.template = template
274 } else {
275 v.object.template = mkBin(v.ctx(), token.NoPos, opUnify, v.object.template, template)
276 }
277
278 case *ast.BasicLit, *ast.Ident:
279 f, ok := v.nodeLabel(x)
280 if !ok {
281 return v.error(n.Label, "invalid field name: %v", n.Label)
282 }
283 if f != 0 {
284 v.object.insertValue(v.ctx(), f, v.walk(n.Value))
285 }
286
287 default:
288 panic("cue: unknown label type")
289 }
290
291 case *ast.Alias:
292 // parsed verbatim at reference.
293
294 case *ast.LambdaExpr:
295 sig := &params{}
296 lambda := &lambdaExpr{newExpr(n), sig, nil}
297 v.setScope(n, lambda)
298
299 for _, p := range n.Params {
300 f, _ := v.nodeLabel(p.Label)
301 if p.Value != nil {
302 sig.add(f, v.walk(p.Value))
303 } else {
304 src := &ast.Ident{NamePos: p.Pos(), Name: "_"}
305 sig.add(f, &top{baseValue: newExpr(src)})
306 }
307 }
308 lambda.value = v.walk(n.Expr)
309 return lambda
310
311 case *ast.ListComprehension:
312 yielder := &yield{baseValue: newExpr(n.Expr)}
313 lc := &listComprehension{
314 newExpr(n),
315 wrapClauses(v, yielder, n.Clauses),
316 }
317 // we don't support key for lists (yet?)
318 yielder.value = v.walk(n.Expr)
319 return lc
320
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100321 // Expressions
322 case *ast.Ident:
323 if n.Node == nil {
324 if value = v.resolve(n); value != nil {
325 break
326 }
327
328 switch n.Name {
329 case "_":
330 return &top{newExpr(n)}
331 case "string":
332 return &basicType{newExpr(n), stringKind}
333 case "bytes":
334 return &basicType{newExpr(n), bytesKind}
335 case "bool":
336 return &basicType{newExpr(n), boolKind}
337 case "int":
338 return &basicType{newExpr(n), intKind}
339 case "float":
340 return &basicType{newExpr(n), floatKind}
341 case "number":
342 return &basicType{newExpr(n), numKind}
343 case "duration":
344 return &basicType{newExpr(n), durationKind}
345
346 case "len":
347 return lenBuiltin
348 }
349 if r, ok := predefinedRanges[n.Name]; ok {
350 return r
351 }
352
353 value = v.error(n, "reference %q not found", n.Name)
354 break
355 }
356
357 if a, ok := n.Node.(*ast.Alias); ok {
358 value = v.walk(a.Expr)
359 break
360 }
361
362 label := v.label(n.Name, true)
363 if n.Scope != nil {
364 n2 := v.mapScope(n.Scope)
365 value = &nodeRef{baseValue: newExpr(n), node: n2}
366 value = &selectorExpr{newExpr(n), value, label}
367 } else {
368 n2 := v.mapScope(n.Node)
369 value = &nodeRef{baseValue: newExpr(n), node: n2}
370 }
371
372 case *ast.BottomLit:
373 value = v.error(n, "from source")
374
375 case *ast.BadDecl:
376 // nothing to do
377
378 case *ast.BadExpr:
379 value = v.error(n, "invalid expression")
380
381 case *ast.BasicLit:
382 value = v.litParser.parse(n)
383
384 case *ast.Interpolation:
385 if len(n.Elts) == 0 {
386 return v.error(n, "invalid interpolation")
387 }
388 first, ok1 := n.Elts[0].(*ast.BasicLit)
389 last, ok2 := n.Elts[len(n.Elts)-1].(*ast.BasicLit)
390 if !ok1 || !ok2 {
391 return v.error(n, "invalid interpolation")
392 }
393 if len(n.Elts) == 1 {
394 value = v.walk(n.Elts[0])
395 break
396 }
397 lit := &interpolation{baseValue: newExpr(n), k: stringKind}
398 value = lit
399 quote, err := stringType(first.Value)
400 if err != nil {
401 return v.error(n, "invalid interpolation: %v", err)
402 }
403 if quote[0] == '\'' {
404 return v.error(n, "interpolation not implemented for bytes: %v", err)
405 }
406 ws, err := wsPrefix(last.Value, quote)
407 if err != nil {
408 return v.error(n, "invalid interpolation: %v", err)
409 }
410 prefix := quote
411 multi := len(quote) == 3
412 p := v.litParser
413 for i := 0; i < len(n.Elts); i += 2 {
414 l, ok := n.Elts[i].(*ast.BasicLit)
415 if !ok {
416 return v.error(n, "invalid interpolation")
417 }
418 if err := p.init(l); err != nil {
419 return v.error(n, "invalid interpolation: %v", err)
420 }
421 if i+1 < len(n.Elts) {
422 x := p.parseString(prefix, `\(`, ws, multi, quote[0])
423 lit.parts = append(lit.parts, x, v.walk(n.Elts[i+1]))
424 } else {
425 x := p.parseString(prefix, quote, ws, multi, quote[0])
426 lit.parts = append(lit.parts, x)
427 }
428 prefix = ")"
429 }
430
431 case *ast.ListLit:
432 list := &list{baseValue: newExpr(n)}
433 for _, e := range n.Elts {
434 list.a = append(list.a, v.walk(e))
435 }
436 list.initLit()
437 if n.Ellipsis != token.NoPos || n.Type != nil {
438 list.len = &rangeLit{list.baseValue, list.len, &top{list.baseValue}}
439 if n.Type != nil {
440 list.typ = v.walk(n.Type)
441 }
442 }
443 value = list
444
445 case *ast.ParenExpr:
446 value = v.walk(n.X)
447
448 case *ast.SelectorExpr:
449 v.inSelector++
450 value = &selectorExpr{
451 newExpr(n),
452 v.walk(n.X),
453 v.label(n.Sel.Name, true),
454 }
455 v.inSelector--
456
457 case *ast.IndexExpr:
458 value = &indexExpr{newExpr(n), v.walk(n.X), v.walk(n.Index)}
459
460 case *ast.SliceExpr:
461 slice := &sliceExpr{baseValue: newExpr(n), x: v.walk(n.X)}
462 if n.Low != nil {
463 slice.lo = v.walk(n.Low)
464 }
465 if n.High != nil {
466 slice.hi = v.walk(n.High)
467 }
468 value = slice
469
470 case *ast.CallExpr:
471 call := &callExpr{baseValue: newExpr(n), x: v.walk(n.Fun)}
472 for _, a := range n.Args {
473 call.args = append(call.args, v.walk(a))
474 }
475 value = call
476
477 case *ast.UnaryExpr:
478 value = &unaryExpr{
479 newExpr(n),
480 tokenMap[n.Op],
481 v.walk(n.X),
482 }
483
484 case *ast.BinaryExpr:
485 switch n.Op {
486 case token.DISJUNCTION:
487 value = makeDisjunction(v.ctx(), n, v.walk(n.X), v.walk(n.Y))
488 case token.RANGE:
489 value = &rangeLit{
490 newExpr(n),
491 v.walk(n.X), // from
492 v.walk(n.Y), // to
493 }
494 default:
495 value = &binaryExpr{
496 newExpr(n),
497 tokenMap[n.Op], // op
498 v.walk(n.X), // left
499 v.walk(n.Y), // right
500 }
501 }
502
503 // nothing to do
504 // case *syntax.EmitDecl:
505 default:
506 // TODO: unhandled node.
507 // value = ctx.mkErr(n, "unknown node type %T", n)
508 panic(fmt.Sprintf("unimplemented %T", n))
509
510 }
511 return value
512}
513
514func wrapClauses(v *astVisitor, y yielder, clauses []ast.Clause) yielder {
515 for _, c := range clauses {
516 if n, ok := c.(*ast.ForClause); ok {
517 params := &params{}
518 fn := &lambdaExpr{newExpr(n.Source), params, nil}
519 v.setScope(n, fn)
520 }
521 }
522 for i := len(clauses) - 1; i >= 0; i-- {
523 switch n := clauses[i].(type) {
524 case *ast.ForClause:
525 fn := v.mapScope(n).(*lambdaExpr)
526 fn.value = y
527
528 key := "_"
529 if n.Key != nil {
530 key = n.Key.Name
531 }
532 f := v.label(key, true)
533 fn.add(f, &basicType{newExpr(n.Key), stringKind | intKind})
534
535 f = v.label(n.Value.Name, true)
536 fn.add(f, &top{})
537
538 y = &feed{newExpr(n.Source), v.walk(n.Source), fn}
539
540 case *ast.IfClause:
541 y = &guard{newExpr(n.Condition), v.walk(n.Condition), y}
542 }
543 }
544 return y
545}