Marcel van Lohuizen | 17157ea | 2018-12-11 10:41:10 +0100 | [diff] [blame] | 1 | // 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 | |
| 15 | package cue |
| 16 | |
| 17 | import ( |
| 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. |
| 34 | func (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 | |
| 52 | type astVisitor struct { |
| 53 | *astState |
| 54 | object *structLit |
| 55 | comprehensions []*structComprehension |
| 56 | |
| 57 | inSelector int |
| 58 | } |
| 59 | |
| 60 | func (v *astVisitor) ctx() *context { |
| 61 | return v.astState.ctx |
| 62 | } |
| 63 | |
| 64 | type 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 | |
| 76 | func (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 | |
| 84 | func (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 | |
| 91 | func 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 | |
| 107 | func (v *astVisitor) error(n ast.Node, args ...interface{}) value { |
| 108 | return v.mkErr(newNode(n), args...) |
| 109 | } |
| 110 | |
| 111 | func (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 | |
| 128 | func (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 |
| 147 | func (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 Lohuizen | 17157ea | 2018-12-11 10:41:10 +0100 | [diff] [blame] | 221 | case *ast.TemplateLabel: |
| 222 | f := v.label(x.Ident.Name, true) |
| 223 | |
| 224 | sig := ¶ms{} |
| 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 Lohuizen | 17157ea | 2018-12-11 10:41:10 +0100 | [diff] [blame] | 262 | case *ast.TemplateLabel: |
| 263 | f := v.label(x.Ident.Name, true) |
| 264 | |
| 265 | sig := ¶ms{} |
| 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 | |
Marcel van Lohuizen | 17157ea | 2018-12-11 10:41:10 +0100 | [diff] [blame] | 294 | case *ast.ListComprehension: |
| 295 | yielder := &yield{baseValue: newExpr(n.Expr)} |
| 296 | lc := &listComprehension{ |
| 297 | newExpr(n), |
| 298 | wrapClauses(v, yielder, n.Clauses), |
| 299 | } |
| 300 | // we don't support key for lists (yet?) |
| 301 | yielder.value = v.walk(n.Expr) |
| 302 | return lc |
| 303 | |
Marcel van Lohuizen | 17157ea | 2018-12-11 10:41:10 +0100 | [diff] [blame] | 304 | // Expressions |
| 305 | case *ast.Ident: |
| 306 | if n.Node == nil { |
| 307 | if value = v.resolve(n); value != nil { |
| 308 | break |
| 309 | } |
| 310 | |
| 311 | switch n.Name { |
| 312 | case "_": |
| 313 | return &top{newExpr(n)} |
| 314 | case "string": |
| 315 | return &basicType{newExpr(n), stringKind} |
| 316 | case "bytes": |
| 317 | return &basicType{newExpr(n), bytesKind} |
| 318 | case "bool": |
| 319 | return &basicType{newExpr(n), boolKind} |
| 320 | case "int": |
| 321 | return &basicType{newExpr(n), intKind} |
| 322 | case "float": |
| 323 | return &basicType{newExpr(n), floatKind} |
| 324 | case "number": |
| 325 | return &basicType{newExpr(n), numKind} |
| 326 | case "duration": |
| 327 | return &basicType{newExpr(n), durationKind} |
| 328 | |
| 329 | case "len": |
| 330 | return lenBuiltin |
| 331 | } |
| 332 | if r, ok := predefinedRanges[n.Name]; ok { |
| 333 | return r |
| 334 | } |
| 335 | |
| 336 | value = v.error(n, "reference %q not found", n.Name) |
| 337 | break |
| 338 | } |
| 339 | |
| 340 | if a, ok := n.Node.(*ast.Alias); ok { |
| 341 | value = v.walk(a.Expr) |
| 342 | break |
| 343 | } |
| 344 | |
| 345 | label := v.label(n.Name, true) |
| 346 | if n.Scope != nil { |
| 347 | n2 := v.mapScope(n.Scope) |
| 348 | value = &nodeRef{baseValue: newExpr(n), node: n2} |
| 349 | value = &selectorExpr{newExpr(n), value, label} |
| 350 | } else { |
| 351 | n2 := v.mapScope(n.Node) |
| 352 | value = &nodeRef{baseValue: newExpr(n), node: n2} |
| 353 | } |
| 354 | |
| 355 | case *ast.BottomLit: |
| 356 | value = v.error(n, "from source") |
| 357 | |
| 358 | case *ast.BadDecl: |
| 359 | // nothing to do |
| 360 | |
| 361 | case *ast.BadExpr: |
| 362 | value = v.error(n, "invalid expression") |
| 363 | |
| 364 | case *ast.BasicLit: |
| 365 | value = v.litParser.parse(n) |
| 366 | |
| 367 | case *ast.Interpolation: |
| 368 | if len(n.Elts) == 0 { |
| 369 | return v.error(n, "invalid interpolation") |
| 370 | } |
| 371 | first, ok1 := n.Elts[0].(*ast.BasicLit) |
| 372 | last, ok2 := n.Elts[len(n.Elts)-1].(*ast.BasicLit) |
| 373 | if !ok1 || !ok2 { |
| 374 | return v.error(n, "invalid interpolation") |
| 375 | } |
| 376 | if len(n.Elts) == 1 { |
| 377 | value = v.walk(n.Elts[0]) |
| 378 | break |
| 379 | } |
| 380 | lit := &interpolation{baseValue: newExpr(n), k: stringKind} |
| 381 | value = lit |
| 382 | quote, err := stringType(first.Value) |
| 383 | if err != nil { |
| 384 | return v.error(n, "invalid interpolation: %v", err) |
| 385 | } |
| 386 | if quote[0] == '\'' { |
| 387 | return v.error(n, "interpolation not implemented for bytes: %v", err) |
| 388 | } |
| 389 | ws, err := wsPrefix(last.Value, quote) |
| 390 | if err != nil { |
| 391 | return v.error(n, "invalid interpolation: %v", err) |
| 392 | } |
| 393 | prefix := quote |
| 394 | multi := len(quote) == 3 |
| 395 | p := v.litParser |
| 396 | 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 | } |
| 401 | if err := p.init(l); err != nil { |
| 402 | return v.error(n, "invalid interpolation: %v", err) |
| 403 | } |
| 404 | if i+1 < len(n.Elts) { |
| 405 | x := p.parseString(prefix, `\(`, ws, multi, quote[0]) |
| 406 | lit.parts = append(lit.parts, x, v.walk(n.Elts[i+1])) |
| 407 | } else { |
| 408 | x := p.parseString(prefix, quote, ws, multi, quote[0]) |
| 409 | lit.parts = append(lit.parts, x) |
| 410 | } |
| 411 | prefix = ")" |
| 412 | } |
| 413 | |
| 414 | case *ast.ListLit: |
| 415 | list := &list{baseValue: newExpr(n)} |
| 416 | for _, e := range n.Elts { |
| 417 | list.a = append(list.a, v.walk(e)) |
| 418 | } |
| 419 | list.initLit() |
| 420 | if n.Ellipsis != token.NoPos || n.Type != nil { |
| 421 | list.len = &rangeLit{list.baseValue, list.len, &top{list.baseValue}} |
| 422 | if n.Type != nil { |
| 423 | list.typ = v.walk(n.Type) |
| 424 | } |
| 425 | } |
| 426 | value = list |
| 427 | |
| 428 | case *ast.ParenExpr: |
| 429 | value = v.walk(n.X) |
| 430 | |
| 431 | case *ast.SelectorExpr: |
| 432 | v.inSelector++ |
| 433 | value = &selectorExpr{ |
| 434 | newExpr(n), |
| 435 | v.walk(n.X), |
| 436 | v.label(n.Sel.Name, true), |
| 437 | } |
| 438 | v.inSelector-- |
| 439 | |
| 440 | case *ast.IndexExpr: |
| 441 | value = &indexExpr{newExpr(n), v.walk(n.X), v.walk(n.Index)} |
| 442 | |
| 443 | case *ast.SliceExpr: |
| 444 | slice := &sliceExpr{baseValue: newExpr(n), x: v.walk(n.X)} |
| 445 | if n.Low != nil { |
| 446 | slice.lo = v.walk(n.Low) |
| 447 | } |
| 448 | if n.High != nil { |
| 449 | slice.hi = v.walk(n.High) |
| 450 | } |
| 451 | value = slice |
| 452 | |
| 453 | case *ast.CallExpr: |
| 454 | call := &callExpr{baseValue: newExpr(n), x: v.walk(n.Fun)} |
| 455 | for _, a := range n.Args { |
| 456 | call.args = append(call.args, v.walk(a)) |
| 457 | } |
| 458 | value = call |
| 459 | |
| 460 | case *ast.UnaryExpr: |
| 461 | value = &unaryExpr{ |
| 462 | newExpr(n), |
| 463 | tokenMap[n.Op], |
| 464 | v.walk(n.X), |
| 465 | } |
| 466 | |
| 467 | case *ast.BinaryExpr: |
| 468 | switch n.Op { |
| 469 | case token.DISJUNCTION: |
| 470 | value = makeDisjunction(v.ctx(), n, v.walk(n.X), v.walk(n.Y)) |
| 471 | case token.RANGE: |
| 472 | value = &rangeLit{ |
| 473 | newExpr(n), |
| 474 | v.walk(n.X), // from |
| 475 | v.walk(n.Y), // to |
| 476 | } |
| 477 | default: |
| 478 | value = &binaryExpr{ |
| 479 | newExpr(n), |
| 480 | tokenMap[n.Op], // op |
| 481 | v.walk(n.X), // left |
| 482 | v.walk(n.Y), // right |
| 483 | } |
| 484 | } |
| 485 | |
| 486 | // nothing to do |
| 487 | // case *syntax.EmitDecl: |
| 488 | default: |
| 489 | // TODO: unhandled node. |
| 490 | // value = ctx.mkErr(n, "unknown node type %T", n) |
| 491 | panic(fmt.Sprintf("unimplemented %T", n)) |
| 492 | |
| 493 | } |
| 494 | return value |
| 495 | } |
| 496 | |
| 497 | func wrapClauses(v *astVisitor, y yielder, clauses []ast.Clause) yielder { |
| 498 | for _, c := range clauses { |
| 499 | if n, ok := c.(*ast.ForClause); ok { |
| 500 | params := ¶ms{} |
| 501 | fn := &lambdaExpr{newExpr(n.Source), params, nil} |
| 502 | v.setScope(n, fn) |
| 503 | } |
| 504 | } |
| 505 | for i := len(clauses) - 1; i >= 0; i-- { |
| 506 | switch n := clauses[i].(type) { |
| 507 | case *ast.ForClause: |
| 508 | fn := v.mapScope(n).(*lambdaExpr) |
| 509 | fn.value = y |
| 510 | |
| 511 | key := "_" |
| 512 | if n.Key != nil { |
| 513 | key = n.Key.Name |
| 514 | } |
| 515 | f := v.label(key, true) |
| 516 | fn.add(f, &basicType{newExpr(n.Key), stringKind | intKind}) |
| 517 | |
| 518 | f = v.label(n.Value.Name, true) |
| 519 | fn.add(f, &top{}) |
| 520 | |
| 521 | y = &feed{newExpr(n.Source), v.walk(n.Source), fn} |
| 522 | |
| 523 | case *ast.IfClause: |
| 524 | y = &guard{newExpr(n.Condition), v.walk(n.Condition), y} |
| 525 | } |
| 526 | } |
| 527 | return y |
| 528 | } |