blob: 37b92dc53310fe6b1899dfa2f4e9584eb303c883 [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
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +010045 return nil
46}
47
48type astVisitor struct {
49 *astState
Marcel van Lohuizen66db9202018-12-17 19:02:08 +010050 object *structLit
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +010051
52 inSelector int
53}
54
55func (v *astVisitor) ctx() *context {
56 return v.astState.ctx
57}
58
59type astState struct {
60 ctx *context
61 *index
62 inst *build.Instance
63
64 litParser *litParser
65 resolveRoot *structLit
66
67 // make unique per level to avoid reuse of structs being an issue.
68 astMap map[ast.Node]scope
69}
70
71func (s *astState) mapScope(n ast.Node) (m scope) {
72 if m = s.astMap[n]; m == nil {
73 m = newStruct(newNode(n))
74 s.astMap[n] = m
75 }
76 return m
77}
78
79func (s *astState) setScope(n ast.Node, v scope) {
80 if m, ok := s.astMap[n]; ok && m != v {
81 panic("already defined")
82 }
83 s.astMap[n] = v
84}
85
86func newVisitor(idx *index, inst *build.Instance, obj, resolveRoot *structLit) *astVisitor {
87 ctx := idx.newContext()
88 v := &astVisitor{
89 object: obj,
90 }
91 v.astState = &astState{
92 ctx: ctx,
93 index: ctx.index,
94 inst: inst,
95 litParser: &litParser{ctx: ctx},
96 resolveRoot: resolveRoot,
97 astMap: map[ast.Node]scope{},
98 }
99 return v
100}
101
102func (v *astVisitor) error(n ast.Node, args ...interface{}) value {
103 return v.mkErr(newNode(n), args...)
104}
105
106func (v *astVisitor) resolve(n *ast.Ident) value {
107 ctx := v.ctx()
108 label := v.label(n.Name, true)
109 if r := v.resolveRoot; r != nil {
110 if value, _ := r.lookup(v.ctx(), label); value != nil {
111 return &selectorExpr{newExpr(n),
112 &nodeRef{baseValue: newExpr(n), node: r}, label}
113 }
114 if v.inSelector > 0 {
115 if p := getBuiltinShorthandPkg(ctx, n.Name); p != nil {
116 return &nodeRef{baseValue: newExpr(n), node: p}
117 }
118 }
119 }
120 return nil
121}
122
123func (v *astVisitor) loadImport(imp *ast.ImportSpec) evaluated {
124 ctx := v.ctx()
125 val := lookupBuiltinPkg(ctx, imp)
126 if !isBottom(val) {
127 return val
128 }
129 path, err := strconv.Unquote(imp.Path.Value)
130 if err != nil {
131 return ctx.mkErr(newNode(imp), "illformed import spec")
132 }
133 bimp := v.inst.LookupImport(path)
134 if bimp == nil {
135 return ctx.mkErr(newNode(imp), "package %q not found", path)
136 }
137 impInst := v.index.loadInstance(bimp)
138 return impInst.rootValue.evalPartial(ctx)
139}
140
141// We probably don't need to call Walk.s
142func (v *astVisitor) walk(astNode ast.Node) (value value) {
143 switch n := astNode.(type) {
144 case *ast.File:
145 obj := v.object
146 v1 := &astVisitor{
147 astState: v.astState,
148 object: obj,
149 }
150 for _, e := range n.Decls {
151 switch x := e.(type) {
152 case *ast.EmitDecl:
153 if v1.object.emit == nil {
154 v1.object.emit = v1.walk(x.Expr)
155 } else {
156 v1.object.emit = mkBin(v.ctx(), token.NoPos, opUnify, v1.object.emit, v1.walk(x.Expr))
157 }
158 default:
159 v1.walk(e)
160 }
161 }
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100162 value = obj
163
164 case *ast.ImportDecl:
165 for _, s := range n.Specs {
166 v.walk(s)
167 }
168
169 case *ast.ImportSpec:
170 val := v.loadImport(n)
171 if !isBottom(val) {
172 v.setScope(n, val.(*structLit))
173 }
174
175 case *ast.StructLit:
176 obj := v.mapScope(n).(*structLit)
177 v1 := &astVisitor{
178 astState: v.astState,
179 object: obj,
180 }
181 for _, e := range n.Elts {
182 switch x := e.(type) {
183 case *ast.EmitDecl:
184 // Only allowed at top-level.
185 v1.error(x, "emitting values is only allowed at top level")
186 case *ast.Field, *ast.Alias:
187 v1.walk(e)
188 case *ast.ComprehensionDecl:
189 v1.walk(x)
190 }
191 }
192 value = obj
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100193
194 case *ast.ComprehensionDecl:
195 yielder := &yield{baseValue: newExpr(n.Field.Value)}
Marcel van Lohuizen66db9202018-12-17 19:02:08 +0100196 fc := &fieldComprehension{
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100197 baseValue: newDecl(n),
198 clauses: wrapClauses(v, yielder, n.Clauses),
199 }
200 field := n.Field
201 switch x := field.Label.(type) {
202 case *ast.Interpolation:
203 yielder.key = v.walk(x)
204 yielder.value = v.walk(field.Value)
205
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100206 case *ast.TemplateLabel:
207 f := v.label(x.Ident.Name, true)
208
209 sig := &params{}
210 sig.add(f, &basicType{newNode(field.Label), stringKind})
211 template := &lambdaExpr{newExpr(field.Value), sig, nil}
212
213 v.setScope(field, template)
214 template.value = v.walk(field.Value)
215 yielder.value = template
Marcel van Lohuizen66db9202018-12-17 19:02:08 +0100216 fc.isTemplate = true
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100217
218 case *ast.BasicLit, *ast.Ident:
219 name, ok := ast.LabelName(x)
220 if !ok {
221 return v.error(x, "invalid field name: %v", x)
222 }
223 if name != "" {
224 yielder.key = &stringLit{newNode(x), name}
225 yielder.value = v.walk(field.Value)
226 }
227
228 default:
229 panic("cue: unknown label type")
230 }
231 // yielder.key = v.walk(n.Field.Label)
232 // yielder.value = v.walk(n.Field.Value)
Marcel van Lohuizen66db9202018-12-17 19:02:08 +0100233 v.object.comprehensions = append(v.object.comprehensions, fc)
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100234
235 case *ast.Field:
236 switch x := n.Label.(type) {
237 case *ast.Interpolation:
238 yielder := &yield{baseValue: newNode(x)}
Marcel van Lohuizen66db9202018-12-17 19:02:08 +0100239 fc := &fieldComprehension{
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100240 baseValue: newDecl(n),
241 clauses: yielder,
242 }
243 yielder.key = v.walk(x)
244 yielder.value = v.walk(n.Value)
Marcel van Lohuizen66db9202018-12-17 19:02:08 +0100245 v.object.comprehensions = append(v.object.comprehensions, fc)
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100246
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100247 case *ast.TemplateLabel:
248 f := v.label(x.Ident.Name, true)
249
250 sig := &params{}
251 sig.add(f, &basicType{newNode(n.Label), stringKind})
252 template := &lambdaExpr{newExpr(n.Value), sig, nil}
253
254 v.setScope(n, template)
255 template.value = v.walk(n.Value)
256
257 if v.object.template == nil {
258 v.object.template = template
259 } else {
260 v.object.template = mkBin(v.ctx(), token.NoPos, opUnify, v.object.template, template)
261 }
262
263 case *ast.BasicLit, *ast.Ident:
264 f, ok := v.nodeLabel(x)
265 if !ok {
266 return v.error(n.Label, "invalid field name: %v", n.Label)
267 }
268 if f != 0 {
269 v.object.insertValue(v.ctx(), f, v.walk(n.Value))
270 }
271
272 default:
273 panic("cue: unknown label type")
274 }
275
276 case *ast.Alias:
277 // parsed verbatim at reference.
278
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100279 case *ast.ListComprehension:
280 yielder := &yield{baseValue: newExpr(n.Expr)}
281 lc := &listComprehension{
282 newExpr(n),
283 wrapClauses(v, yielder, n.Clauses),
284 }
285 // we don't support key for lists (yet?)
286 yielder.value = v.walk(n.Expr)
287 return lc
288
Marcel van Lohuizen17157ea2018-12-11 10:41:10 +0100289 // Expressions
290 case *ast.Ident:
291 if n.Node == nil {
292 if value = v.resolve(n); value != nil {
293 break
294 }
295
296 switch n.Name {
297 case "_":
298 return &top{newExpr(n)}
299 case "string":
300 return &basicType{newExpr(n), stringKind}
301 case "bytes":
302 return &basicType{newExpr(n), bytesKind}
303 case "bool":
304 return &basicType{newExpr(n), boolKind}
305 case "int":
306 return &basicType{newExpr(n), intKind}
307 case "float":
308 return &basicType{newExpr(n), floatKind}
309 case "number":
310 return &basicType{newExpr(n), numKind}
311 case "duration":
312 return &basicType{newExpr(n), durationKind}
313
314 case "len":
315 return lenBuiltin
316 }
317 if r, ok := predefinedRanges[n.Name]; ok {
318 return r
319 }
320
321 value = v.error(n, "reference %q not found", n.Name)
322 break
323 }
324
325 if a, ok := n.Node.(*ast.Alias); ok {
326 value = v.walk(a.Expr)
327 break
328 }
329
330 label := v.label(n.Name, true)
331 if n.Scope != nil {
332 n2 := v.mapScope(n.Scope)
333 value = &nodeRef{baseValue: newExpr(n), node: n2}
334 value = &selectorExpr{newExpr(n), value, label}
335 } else {
336 n2 := v.mapScope(n.Node)
337 value = &nodeRef{baseValue: newExpr(n), node: n2}
338 }
339
340 case *ast.BottomLit:
341 value = v.error(n, "from source")
342
343 case *ast.BadDecl:
344 // nothing to do
345
346 case *ast.BadExpr:
347 value = v.error(n, "invalid expression")
348
349 case *ast.BasicLit:
350 value = v.litParser.parse(n)
351
352 case *ast.Interpolation:
353 if len(n.Elts) == 0 {
354 return v.error(n, "invalid interpolation")
355 }
356 first, ok1 := n.Elts[0].(*ast.BasicLit)
357 last, ok2 := n.Elts[len(n.Elts)-1].(*ast.BasicLit)
358 if !ok1 || !ok2 {
359 return v.error(n, "invalid interpolation")
360 }
361 if len(n.Elts) == 1 {
362 value = v.walk(n.Elts[0])
363 break
364 }
365 lit := &interpolation{baseValue: newExpr(n), k: stringKind}
366 value = lit
367 quote, err := stringType(first.Value)
368 if err != nil {
369 return v.error(n, "invalid interpolation: %v", err)
370 }
371 if quote[0] == '\'' {
372 return v.error(n, "interpolation not implemented for bytes: %v", err)
373 }
374 ws, err := wsPrefix(last.Value, quote)
375 if err != nil {
376 return v.error(n, "invalid interpolation: %v", err)
377 }
378 prefix := quote
379 multi := len(quote) == 3
380 p := v.litParser
381 for i := 0; i < len(n.Elts); i += 2 {
382 l, ok := n.Elts[i].(*ast.BasicLit)
383 if !ok {
384 return v.error(n, "invalid interpolation")
385 }
386 if err := p.init(l); err != nil {
387 return v.error(n, "invalid interpolation: %v", err)
388 }
389 if i+1 < len(n.Elts) {
390 x := p.parseString(prefix, `\(`, ws, multi, quote[0])
391 lit.parts = append(lit.parts, x, v.walk(n.Elts[i+1]))
392 } else {
393 x := p.parseString(prefix, quote, ws, multi, quote[0])
394 lit.parts = append(lit.parts, x)
395 }
396 prefix = ")"
397 }
398
399 case *ast.ListLit:
400 list := &list{baseValue: newExpr(n)}
401 for _, e := range n.Elts {
402 list.a = append(list.a, v.walk(e))
403 }
404 list.initLit()
405 if n.Ellipsis != token.NoPos || n.Type != nil {
406 list.len = &rangeLit{list.baseValue, list.len, &top{list.baseValue}}
407 if n.Type != nil {
408 list.typ = v.walk(n.Type)
409 }
410 }
411 value = list
412
413 case *ast.ParenExpr:
414 value = v.walk(n.X)
415
416 case *ast.SelectorExpr:
417 v.inSelector++
418 value = &selectorExpr{
419 newExpr(n),
420 v.walk(n.X),
421 v.label(n.Sel.Name, true),
422 }
423 v.inSelector--
424
425 case *ast.IndexExpr:
426 value = &indexExpr{newExpr(n), v.walk(n.X), v.walk(n.Index)}
427
428 case *ast.SliceExpr:
429 slice := &sliceExpr{baseValue: newExpr(n), x: v.walk(n.X)}
430 if n.Low != nil {
431 slice.lo = v.walk(n.Low)
432 }
433 if n.High != nil {
434 slice.hi = v.walk(n.High)
435 }
436 value = slice
437
438 case *ast.CallExpr:
439 call := &callExpr{baseValue: newExpr(n), x: v.walk(n.Fun)}
440 for _, a := range n.Args {
441 call.args = append(call.args, v.walk(a))
442 }
443 value = call
444
445 case *ast.UnaryExpr:
446 value = &unaryExpr{
447 newExpr(n),
448 tokenMap[n.Op],
449 v.walk(n.X),
450 }
451
452 case *ast.BinaryExpr:
453 switch n.Op {
454 case token.DISJUNCTION:
455 value = makeDisjunction(v.ctx(), n, v.walk(n.X), v.walk(n.Y))
456 case token.RANGE:
457 value = &rangeLit{
458 newExpr(n),
459 v.walk(n.X), // from
460 v.walk(n.Y), // to
461 }
462 default:
463 value = &binaryExpr{
464 newExpr(n),
465 tokenMap[n.Op], // op
466 v.walk(n.X), // left
467 v.walk(n.Y), // right
468 }
469 }
470
471 // nothing to do
472 // case *syntax.EmitDecl:
473 default:
474 // TODO: unhandled node.
475 // value = ctx.mkErr(n, "unknown node type %T", n)
476 panic(fmt.Sprintf("unimplemented %T", n))
477
478 }
479 return value
480}
481
482func wrapClauses(v *astVisitor, y yielder, clauses []ast.Clause) yielder {
483 for _, c := range clauses {
484 if n, ok := c.(*ast.ForClause); ok {
485 params := &params{}
486 fn := &lambdaExpr{newExpr(n.Source), params, nil}
487 v.setScope(n, fn)
488 }
489 }
490 for i := len(clauses) - 1; i >= 0; i-- {
491 switch n := clauses[i].(type) {
492 case *ast.ForClause:
493 fn := v.mapScope(n).(*lambdaExpr)
494 fn.value = y
495
496 key := "_"
497 if n.Key != nil {
498 key = n.Key.Name
499 }
500 f := v.label(key, true)
501 fn.add(f, &basicType{newExpr(n.Key), stringKind | intKind})
502
503 f = v.label(n.Value.Name, true)
504 fn.add(f, &top{})
505
506 y = &feed{newExpr(n.Source), v.walk(n.Source), fn}
507
508 case *ast.IfClause:
509 y = &guard{newExpr(n.Condition), v.walk(n.Condition), y}
510 }
511 }
512 return y
513}