Debian Codegraph @

interpreter/planner.go

raw
1 // Copyright 2018 Google LLC
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 interpreter
16
17 import (
18 "fmt"
19 "strings"
20
21 "github.com/google/cel-go/common/ast"
22 "github.com/google/cel-go/common/containers"
23 "github.com/google/cel-go/common/functions"
24 "github.com/google/cel-go/common/operators"
25 "github.com/google/cel-go/common/types"
26 )
27
28 // newPlanner creates an interpretablePlanner which references a Dispatcher, TypeProvider,
29 // TypeAdapter, Container, and CheckedExpr value. These pieces of data are used to resolve
30 // functions, types, and namespaced identifiers at plan time rather than at runtime since
31 // it only needs to be done once and may be semi-expensive to compute.
32 func newPlanner(disp Dispatcher,
33 provider types.Provider,
34 adapter types.Adapter,
35 attrFactory AttributeFactory,
36 cont *containers.Container,
37 exprAST *ast.AST) *planner {
38 return &planner{
39 disp: disp,
40 provider: provider,
41 adapter: adapter,
42 attrFactory: attrFactory,
43 container: cont,
44 refMap: exprAST.ReferenceMap(),
45 typeMap: exprAST.TypeMap(),
46 decorators: make([]InterpretableDecorator, 0),
47 observers: make([]StatefulObserver, 0),
48 }
49 }
50
51 // planner is an implementation of the interpretablePlanner interface.
52 type planner struct {
53 disp Dispatcher
54 provider types.Provider
55 adapter types.Adapter
56 attrFactory AttributeFactory
57 container *containers.Container
58 refMap map[int64]*ast.ReferenceInfo
59 typeMap map[int64]*types.Type
60 decorators []InterpretableDecorator
61 observers []StatefulObserver
62 }
63
64 type planBuilder struct {
65 *planner
66
67 localVars map[string]int
68 }
69
70 // Plan implements the interpretablePlanner interface. This implementation of the Plan method also
71 // applies decorators to each Interpretable generated as part of the overall plan. Decorators are
72 // useful for layering functionality into the evaluation that is not natively understood by CEL,
73 // such as state-tracking, expression re-write, and possibly efficient thread-safe memoization of
74 // repeated expressions.
75 func (p *planner) Plan(expr ast.Expr) (Interpretable, error) {
76 pb := &planBuilder{planner: p, localVars: make(map[string]int)}
77 i, err := pb.plan(expr)
78 if err != nil {
79 return nil, err
80 }
81 if len(p.observers) == 0 {
82 return i, nil
83 }
84 return &ObservableInterpretable{Interpretable: i, observers: p.observers}, nil
85 }
86
87 func (p *planBuilder) plan(expr ast.Expr) (Interpretable, error) {
88 switch expr.Kind() {
89 case ast.CallKind:
90 return p.decorate(p.planCall(expr))
91 case ast.IdentKind:
92 return p.decorate(p.planIdent(expr))
93 case ast.LiteralKind:
94 return p.decorate(p.planConst(expr))
95 case ast.SelectKind:
96 return p.decorate(p.planSelect(expr))
97 case ast.ListKind:
98 return p.decorate(p.planCreateList(expr))
99 case ast.MapKind:
100 return p.decorate(p.planCreateMap(expr))
101 case ast.StructKind:
102 return p.decorate(p.planCreateStruct(expr))
103 case ast.ComprehensionKind:
104 return p.decorate(p.planComprehension(expr))
105 }
106 return nil, fmt.Errorf("unsupported expr: %v", expr)
107 }
108
109 // decorate applies the InterpretableDecorator functions to the given Interpretable.
110 // Both the Interpretable and error generated by a Plan step are accepted as arguments
111 // for convenience.
112 func (p *planBuilder) decorate(i Interpretable, err error) (Interpretable, error) {
113 if err != nil {
114 return nil, err
115 }
116 for _, dec := range p.decorators {
117 i, err = dec(i)
118 if err != nil {
119 return nil, err
120 }
121 }
122 return i, nil
123 }
124
125 // planIdent creates an Interpretable that resolves an identifier from an Activation.
126 func (p *planBuilder) planIdent(expr ast.Expr) (Interpretable, error) {
127 // Establish whether the identifier is in the reference map.
128 if identRef, found := p.refMap[expr.ID()]; found {
129 return p.planCheckedIdent(expr.ID(), identRef)
130 }
131 // Create the possible attribute list for the unresolved reference.
132 ident := expr.AsIdent()
133 if p.isLocalVar(ident) {
134 return &evalAttr{
135 adapter: p.adapter,
136 attr: p.attrFactory.AbsoluteAttribute(expr.ID(), ident),
137 }, nil
138 }
139 return &evalAttr{
140 adapter: p.adapter,
141 attr: p.attrFactory.MaybeAttribute(expr.ID(), ident),
142 }, nil
143 }
144
145 func (p *planBuilder) planCheckedIdent(id int64, identRef *ast.ReferenceInfo) (Interpretable, error) {
146 // Plan a constant reference if this is the case for this simple identifier.
147 if identRef.Value != nil {
148 return NewConstValue(id, identRef.Value), nil
149 }
150
151 // Check to see whether the type map indicates this is a type name. All types should be
152 // registered with the provider.
153 cType := p.typeMap[id]
154 if cType.Kind() == types.TypeKind {
155 cVal, found := p.provider.FindIdent(identRef.Name)
156 if !found {
157 return nil, fmt.Errorf("reference to undefined type: %s", identRef.Name)
158 }
159 return NewConstValue(id, cVal), nil
160 }
161
162 // Otherwise, return the attribute for the resolved identifier name.
163 return &evalAttr{
164 adapter: p.adapter,
165 attr: p.attrFactory.AbsoluteAttribute(id, identRef.Name),
166 }, nil
167 }
168
169 // planSelect creates an Interpretable with either:
170 //
171 // a) selects a field from a map or proto.
172 // b) creates a field presence test for a select within a has() macro.
173 // c) resolves the select expression to a namespaced identifier.
174 func (p *planBuilder) planSelect(expr ast.Expr) (Interpretable, error) {
175 // If the Select id appears in the reference map from the CheckedExpr proto then it is either
176 // a namespaced identifier or enum value.
177 if identRef, found := p.refMap[expr.ID()]; found {
178 return p.planCheckedIdent(expr.ID(), identRef)
179 }
180
181 sel := expr.AsSelect()
182 // Plan the operand evaluation.
183 op, err := p.plan(sel.Operand())
184 if err != nil {
185 return nil, err
186 }
187 opType := p.typeMap[sel.Operand().ID()]
188
189 // If the Select was marked TestOnly, this is a presence test.
190 //
191 // Note: presence tests are defined for structured (e.g. proto) and dynamic values (map, json)
192 // as follows:
193 // - True if the object field has a non-default value, e.g. obj.str != ""
194 // - True if the dynamic value has the field defined, e.g. key in map
195 //
196 // However, presence tests are not defined for qualified identifier names with primitive types.
197 // If a string named 'a.b.c' is declared in the environment and referenced within `has(a.b.c)`,
198 // it is not clear whether has should error or follow the convention defined for structured
199 // values.
200
201 // Establish the attribute reference.
202 attr, isAttr := op.(InterpretableAttribute)
203 if !isAttr {
204 attr, err = p.relativeAttr(op.ID(), op, false)
205 if err != nil {
206 return nil, err
207 }
208 }
209
210 // Build a qualifier for the attribute.
211 qual, err := p.attrFactory.NewQualifier(opType, expr.ID(), sel.FieldName(), false)
212 if err != nil {
213 return nil, err
214 }
215 // Modify the attribute to be test-only.
216 if sel.IsTestOnly() {
217 attr = &evalTestOnly{
218 id: expr.ID(),
219 InterpretableAttribute: attr,
220 }
221 }
222 // Append the qualifier on the attribute.
223 _, err = attr.AddQualifier(qual)
224 return attr, err
225 }
226
227 // planCall creates a callable Interpretable while specializing for common functions and invocation
228 // patterns. Specifically, conditional operators &&, ||, ?:, and (in)equality functions result in
229 // optimized Interpretable values.
230 func (p *planBuilder) planCall(expr ast.Expr) (Interpretable, error) {
231 call := expr.AsCall()
232 target, fnName, oName := p.resolveFunction(expr)
233 argCount := len(call.Args())
234 var offset int
235 if target != nil {
236 argCount++
237 offset++
238 }
239
240 args := make([]Interpretable, argCount)
241 if target != nil {
242 arg, err := p.plan(target)
243 if err != nil {
244 return nil, err
245 }
246 args[0] = arg
247 }
248 for i, argExpr := range call.Args() {
249 arg, err := p.plan(argExpr)
250 if err != nil {
251 return nil, err
252 }
253 args[i+offset] = arg
254 }
255
256 // Generate specialized Interpretable operators by function name if possible.
257 switch fnName {
258 case operators.LogicalAnd:
259 return p.planCallLogicalAnd(expr, args)
260 case operators.LogicalOr:
261 return p.planCallLogicalOr(expr, args)
262 case operators.Conditional:
263 return p.planCallConditional(expr, args)
264 case operators.Equals:
265 return p.planCallEqual(expr, args)
266 case operators.NotEquals:
267 return p.planCallNotEqual(expr, args)
268 case operators.Index:
269 return p.planCallIndex(expr, args, false)
270 case operators.OptSelect, operators.OptIndex:
271 return p.planCallIndex(expr, args, true)
272 }
273
274 // Otherwise, generate Interpretable calls specialized by argument count.
275 // Try to find the specific function by overload id.
276 var fnDef *functions.Overload
277 if oName != "" {
278 fnDef, _ = p.disp.FindOverload(oName)
279 }
280 // If the overload id couldn't resolve the function, try the simple function name.
281 if fnDef == nil {
282 fnDef, _ = p.disp.FindOverload(fnName)
283 }
284 switch argCount {
285 case 0:
286 return p.planCallZero(expr, fnName, oName, fnDef)
287 case 1:
288 // If the FunctionOp has been used, then use it as it may exist for the purposes
289 // of dynamic dispatch within a singleton function implementation.
290 if fnDef != nil && fnDef.Unary == nil && fnDef.Function != nil {
291 return p.planCallVarArgs(expr, fnName, oName, fnDef, args)
292 }
293 return p.planCallUnary(expr, fnName, oName, fnDef, args)
294 case 2:
295 // If the FunctionOp has been used, then use it as it may exist for the purposes
296 // of dynamic dispatch within a singleton function implementation.
297 if fnDef != nil && fnDef.Binary == nil && fnDef.Function != nil {
298 return p.planCallVarArgs(expr, fnName, oName, fnDef, args)
299 }
300 return p.planCallBinary(expr, fnName, oName, fnDef, args)
301 default:
302 return p.planCallVarArgs(expr, fnName, oName, fnDef, args)
303 }
304 }
305
306 // planCallZero generates a zero-arity callable Interpretable.
307 func (p *planBuilder) planCallZero(expr ast.Expr,
308 function string,
309 overload string,
310 impl *functions.Overload) (Interpretable, error) {
311 if impl == nil || impl.Function == nil {
312 return nil, fmt.Errorf("no such overload: %s()", function)
313 }
314 return &evalZeroArity{
315 id: expr.ID(),
316 function: function,
317 overload: overload,
318 impl: impl.Function,
319 }, nil
320 }
321
322 // planCallUnary generates a unary callable Interpretable.
323 func (p *planBuilder) planCallUnary(expr ast.Expr,
324 function string,
325 overload string,
326 impl *functions.Overload,
327 args []Interpretable) (Interpretable, error) {
328 var fn functions.UnaryOp
329 var trait int
330 var nonStrict bool
331 if impl != nil {
332 if impl.Unary == nil {
333 return nil, fmt.Errorf("no such overload: %s(arg)", function)
334 }
335 fn = impl.Unary
336 trait = impl.OperandTrait
337 nonStrict = impl.NonStrict
338 }
339 return &evalUnary{
340 id: expr.ID(),
341 function: function,
342 overload: overload,
343 arg: args[0],
344 trait: trait,
345 impl: fn,
346 nonStrict: nonStrict,
347 }, nil
348 }
349
350 // planCallBinary generates a binary callable Interpretable.
351 func (p *planBuilder) planCallBinary(expr ast.Expr,
352 function string,
353 overload string,
354 impl *functions.Overload,
355 args []Interpretable) (Interpretable, error) {
356 var fn functions.BinaryOp
357 var trait int
358 var nonStrict bool
359 if impl != nil {
360 if impl.Binary == nil {
361 return nil, fmt.Errorf("no such overload: %s(lhs, rhs)", function)
362 }
363 fn = impl.Binary
364 trait = impl.OperandTrait
365 nonStrict = impl.NonStrict
366 }
367 return &evalBinary{
368 id: expr.ID(),
369 function: function,
370 overload: overload,
371 lhs: args[0],
372 rhs: args[1],
373 trait: trait,
374 impl: fn,
375 nonStrict: nonStrict,
376 }, nil
377 }
378
379 // planCallVarArgs generates a variable argument callable Interpretable.
380 func (p *planBuilder) planCallVarArgs(expr ast.Expr,
381 function string,
382 overload string,
383 impl *functions.Overload,
384 args []Interpretable) (Interpretable, error) {
385 var fn functions.FunctionOp
386 var trait int
387 var nonStrict bool
388 if impl != nil {
389 if impl.Function == nil {
390 return nil, fmt.Errorf("no such overload: %s(...)", function)
391 }
392 fn = impl.Function
393 trait = impl.OperandTrait
394 nonStrict = impl.NonStrict
395 }
396 return &evalVarArgs{
397 id: expr.ID(),
398 function: function,
399 overload: overload,
400 args: args,
401 trait: trait,
402 impl: fn,
403 nonStrict: nonStrict,
404 }, nil
405 }
406
407 // planCallEqual generates an equals (==) Interpretable.
408 func (p *planBuilder) planCallEqual(expr ast.Expr, args []Interpretable) (Interpretable, error) {
409 return &evalEq{
410 id: expr.ID(),
411 lhs: args[0],
412 rhs: args[1],
413 }, nil
414 }
415
416 // planCallNotEqual generates a not equals (!=) Interpretable.
417 func (p *planBuilder) planCallNotEqual(expr ast.Expr, args []Interpretable) (Interpretable, error) {
418 return &evalNe{
419 id: expr.ID(),
420 lhs: args[0],
421 rhs: args[1],
422 }, nil
423 }
424
425 // planCallLogicalAnd generates a logical and (&&) Interpretable.
426 func (p *planBuilder) planCallLogicalAnd(expr ast.Expr, args []Interpretable) (Interpretable, error) {
427 return &evalAnd{
428 id: expr.ID(),
429 terms: args,
430 }, nil
431 }
432
433 // planCallLogicalOr generates a logical or (||) Interpretable.
434 func (p *planBuilder) planCallLogicalOr(expr ast.Expr, args []Interpretable) (Interpretable, error) {
435 return &evalOr{
436 id: expr.ID(),
437 terms: args,
438 }, nil
439 }
440
441 // planCallConditional generates a conditional / ternary (c ? t : f) Interpretable.
442 func (p *planBuilder) planCallConditional(expr ast.Expr, args []Interpretable) (Interpretable, error) {
443 cond := args[0]
444 t := args[1]
445 var tAttr Attribute
446 truthyAttr, isTruthyAttr := t.(InterpretableAttribute)
447 if isTruthyAttr {
448 tAttr = truthyAttr.Attr()
449 } else {
450 tAttr = p.attrFactory.RelativeAttribute(t.ID(), t)
451 }
452
453 f := args[2]
454 var fAttr Attribute
455 falsyAttr, isFalsyAttr := f.(InterpretableAttribute)
456 if isFalsyAttr {
457 fAttr = falsyAttr.Attr()
458 } else {
459 fAttr = p.attrFactory.RelativeAttribute(f.ID(), f)
460 }
461
462 return &evalAttr{
463 adapter: p.adapter,
464 attr: p.attrFactory.ConditionalAttribute(expr.ID(), cond, tAttr, fAttr),
465 }, nil
466 }
467
468 // planCallIndex either extends an attribute with the argument to the index operation, or creates
469 // a relative attribute based on the return of a function call or operation.
470 func (p *planBuilder) planCallIndex(expr ast.Expr, args []Interpretable, optional bool) (Interpretable, error) {
471 op := args[0]
472 ind := args[1]
473 opType := p.typeMap[op.ID()]
474
475 // Establish the attribute reference.
476 var err error
477 attr, isAttr := op.(InterpretableAttribute)
478 if !isAttr {
479 attr, err = p.relativeAttr(op.ID(), op, false)
480 if err != nil {
481 return nil, err
482 }
483 }
484
485 // Construct the qualifier type.
486 var qual Qualifier
487 switch ind := ind.(type) {
488 case InterpretableConst:
489 qual, err = p.attrFactory.NewQualifier(opType, expr.ID(), ind.Value(), optional)
490 case InterpretableAttribute:
491 qual, err = p.attrFactory.NewQualifier(opType, expr.ID(), ind, optional)
492 default:
493 qual, err = p.relativeAttr(expr.ID(), ind, optional)
494 }
495 if err != nil {
496 return nil, err
497 }
498
499 // Add the qualifier to the attribute
500 _, err = attr.AddQualifier(qual)
501 return attr, err
502 }
503
504 // planCreateList generates a list construction Interpretable.
505 func (p *planBuilder) planCreateList(expr ast.Expr) (Interpretable, error) {
506 list := expr.AsList()
507 optionalIndices := list.OptionalIndices()
508 elements := list.Elements()
509 optionals := make([]bool, len(elements))
510 for _, index := range optionalIndices {
511 if index < 0 || index >= int32(len(elements)) {
512 return nil, fmt.Errorf("optional index %d out of element bounds [0, %d]", index, len(elements))
513 }
514 optionals[index] = true
515 }
516 elems := make([]Interpretable, len(elements))
517 for i, elem := range elements {
518 elemVal, err := p.plan(elem)
519 if err != nil {
520 return nil, err
521 }
522 elems[i] = elemVal
523 }
524 return &evalList{
525 id: expr.ID(),
526 elems: elems,
527 optionals: optionals,
528 hasOptionals: len(optionalIndices) != 0,
529 adapter: p.adapter,
530 }, nil
531 }
532
533 // planCreateStruct generates a map or object construction Interpretable.
534 func (p *planBuilder) planCreateMap(expr ast.Expr) (Interpretable, error) {
535 m := expr.AsMap()
536 entries := m.Entries()
537 optionals := make([]bool, len(entries))
538 keys := make([]Interpretable, len(entries))
539 vals := make([]Interpretable, len(entries))
540 hasOptionals := false
541 for i, e := range entries {
542 entry := e.AsMapEntry()
543 keyVal, err := p.plan(entry.Key())
544 if err != nil {
545 return nil, err
546 }
547 keys[i] = keyVal
548
549 valVal, err := p.plan(entry.Value())
550 if err != nil {
551 return nil, err
552 }
553 vals[i] = valVal
554 optionals[i] = entry.IsOptional()
555 hasOptionals = hasOptionals || entry.IsOptional()
556 }
557 return &evalMap{
558 id: expr.ID(),
559 keys: keys,
560 vals: vals,
561 optionals: optionals,
562 hasOptionals: hasOptionals,
563 adapter: p.adapter,
564 }, nil
565 }
566
567 // planCreateObj generates an object construction Interpretable.
568 func (p *planBuilder) planCreateStruct(expr ast.Expr) (Interpretable, error) {
569 obj := expr.AsStruct()
570 typeName, defined := p.resolveTypeName(obj.TypeName())
571 if !defined {
572 return nil, fmt.Errorf("unknown type: %s", obj.TypeName())
573 }
574 objFields := obj.Fields()
575 optionals := make([]bool, len(objFields))
576 fields := make([]string, len(objFields))
577 vals := make([]Interpretable, len(objFields))
578 hasOptionals := false
579 for i, f := range objFields {
580 field := f.AsStructField()
581 fields[i] = field.Name()
582 val, err := p.plan(field.Value())
583 if err != nil {
584 return nil, err
585 }
586 vals[i] = val
587 optionals[i] = field.IsOptional()
588 hasOptionals = hasOptionals || field.IsOptional()
589 }
590 return &evalObj{
591 id: expr.ID(),
592 typeName: typeName,
593 fields: fields,
594 vals: vals,
595 optionals: optionals,
596 hasOptionals: hasOptionals,
597 provider: p.provider,
598 }, nil
599 }
600
601 // planComprehension generates an Interpretable fold operation.
602 func (p *planBuilder) planComprehension(expr ast.Expr) (Interpretable, error) {
603 fold := expr.AsComprehension()
604 accu, err := p.plan(fold.AccuInit())
605 if err != nil {
606 return nil, err
607 }
608 iterRange, err := p.plan(fold.IterRange())
609 if err != nil {
610 return nil, err
611 }
612 p.pushLocalVars(fold.AccuVar(), fold.IterVar(), fold.IterVar2())
613 cond, err := p.plan(fold.LoopCondition())
614 if err != nil {
615 return nil, err
616 }
617 step, err := p.plan(fold.LoopStep())
618 if err != nil {
619 return nil, err
620 }
621 p.popLocalVars(fold.IterVar(), fold.IterVar2())
622 result, err := p.plan(fold.Result())
623 if err != nil {
624 return nil, err
625 }
626 p.popLocalVars(fold.AccuVar())
627 return &evalFold{
628 id: expr.ID(),
629 accuVar: fold.AccuVar(),
630 accu: accu,
631 iterVar: fold.IterVar(),
632 iterVar2: fold.IterVar2(),
633 iterRange: iterRange,
634 cond: cond,
635 step: step,
636 result: result,
637 adapter: p.adapter,
638 }, nil
639 }
640
641 // planConst generates a constant valued Interpretable.
642 func (p *planBuilder) planConst(expr ast.Expr) (Interpretable, error) {
643 return NewConstValue(expr.ID(), expr.AsLiteral()), nil
644 }
645
646 // resolveTypeName takes a qualified string constructed at parse time, applies the proto
647 // namespace resolution rules to it in a scan over possible matching types in the TypeProvider.
648 func (p *planBuilder) resolveTypeName(typeName string) (string, bool) {
649 for _, qualifiedTypeName := range p.container.ResolveCandidateNames(typeName) {
650 if _, found := p.provider.FindStructType(qualifiedTypeName); found {
651 return qualifiedTypeName, true
652 }
653 }
654 return "", false
655 }
656
657 // resolveFunction determines the call target, function name, and overload name from a given Expr
658 // value.
659 //
660 // The resolveFunction resolves ambiguities where a function may either be a receiver-style
661 // invocation or a qualified global function name.
662 // - The target expression may only consist of ident and select expressions.
663 // - The function is declared in the environment using its fully-qualified name.
664 // - The fully-qualified function name matches the string serialized target value.
665 func (p *planBuilder) resolveFunction(expr ast.Expr) (ast.Expr, string, string) {
666 // Note: similar logic exists within the `checker/checker.go`. If making changes here
667 // please consider the impact on checker.go and consolidate implementations or mirror code
668 // as appropriate.
669 call := expr.AsCall()
670 var target ast.Expr = nil
671 if call.IsMemberFunction() {
672 target = call.Target()
673 }
674 fnName := call.FunctionName()
675
676 // Checked expressions always have a reference map entry, and _should_ have the fully qualified
677 // function name as the fnName value.
678 oRef, hasOverload := p.refMap[expr.ID()]
679 if hasOverload {
680 if len(oRef.OverloadIDs) == 1 {
681 return target, fnName, oRef.OverloadIDs[0]
682 }
683 // Note, this namespaced function name will not appear as a fully qualified name in ASTs
684 // built and stored before cel-go v0.5.0; however, this functionality did not work at all
685 // before the v0.5.0 release.
686 return target, fnName, ""
687 }
688
689 // Parse-only expressions need to handle the same logic as is normally performed at check time,
690 // but with potentially much less information. The only reliable source of information about
691 // which functions are configured is the dispatcher.
692 if target == nil {
693 // If the user has a parse-only expression, then it should have been configured as such in
694 // the interpreter dispatcher as it may have been omitted from the checker environment.
695 for _, qualifiedName := range p.container.ResolveCandidateNames(fnName) {
696 _, found := p.disp.FindOverload(qualifiedName)
697 if found {
698 return nil, qualifiedName, ""
699 }
700 }
701 // It's possible that the overload was not found, but this situation is accounted for in
702 // the planCall phase; however, the leading dot used for denoting fully-qualified
703 // namespaced identifiers must be stripped, as all declarations already use fully-qualified
704 // names. This stripping behavior is handled automatically by the ResolveCandidateNames
705 // call.
706 return target, strings.TrimPrefix(fnName, "."), ""
707 }
708
709 // Handle the situation where the function target actually indicates a qualified function name.
710 qualifiedPrefix, maybeQualified := p.toQualifiedName(target)
711 if maybeQualified {
712 maybeQualifiedName := qualifiedPrefix + "." + fnName
713 for _, qualifiedName := range p.container.ResolveCandidateNames(maybeQualifiedName) {
714 _, found := p.disp.FindOverload(qualifiedName)
715 if found {
716 // Clear the target to ensure the proper arity is used for finding the
717 // implementation.
718 return nil, qualifiedName, ""
719 }
720 }
721 }
722 // In the default case, the function is exactly as it was advertised: a receiver call on with
723 // an expression-based target with the given simple function name.
724 return target, fnName, ""
725 }
726
727 // relativeAttr indicates that the attribute in this case acts as a qualifier and as such needs to
728 // be observed to ensure that it's evaluation value is properly recorded for state tracking.
729 func (p *planBuilder) relativeAttr(id int64, eval Interpretable, opt bool) (InterpretableAttribute, error) {
730 eAttr, ok := eval.(InterpretableAttribute)
731 if !ok {
732 eAttr = &evalAttr{
733 adapter: p.adapter,
734 attr: p.attrFactory.RelativeAttribute(id, eval),
735 optional: opt,
736 }
737 }
738 // This looks like it should either decorate the new evalAttr node, or early return the InterpretableAttribute
739 decAttr, err := p.decorate(eAttr, nil)
740 if err != nil {
741 return nil, err
742 }
743 eAttr, ok = decAttr.(InterpretableAttribute)
744 if !ok {
745 return nil, fmt.Errorf("invalid attribute decoration: %v(%T)", decAttr, decAttr)
746 }
747 return eAttr, nil
748 }
749
750 // toQualifiedName converts an expression AST into a qualified name if possible, with a boolean
751 // 'found' value that indicates if the conversion is successful.
752 func (p *planBuilder) toQualifiedName(operand ast.Expr) (string, bool) {
753 // If the checker identified the expression as an attribute by the type-checker, then it can't
754 // possibly be part of qualified name in a namespace.
755 _, isAttr := p.refMap[operand.ID()]
756 if isAttr {
757 return "", false
758 }
759 // Since functions cannot be both namespaced and receiver functions, if the operand is not an
760 // qualified variable name, return the (possibly) qualified name given the expressions.
761 switch operand.Kind() {
762 case ast.IdentKind:
763 id := operand.AsIdent()
764 return id, true
765 case ast.SelectKind:
766 sel := operand.AsSelect()
767 // Test only expressions are not valid as qualified names.
768 if sel.IsTestOnly() {
769 return "", false
770 }
771 if qual, found := p.toQualifiedName(sel.Operand()); found {
772 return qual + "." + sel.FieldName(), true
773 }
774 }
775 return "", false
776 }
777
778 func (p *planBuilder) pushLocalVars(names ...string) {
779 for _, name := range names {
780 if name == "" {
781 continue
782 }
783 if cnt, found := p.localVars[name]; found {
784 p.localVars[name] = cnt + 1
785 } else {
786 p.localVars[name] = 1
787 }
788 }
789 }
790
791 func (p *planBuilder) popLocalVars(names ...string) {
792 for _, name := range names {
793 if name == "" {
794 continue
795 }
796 if cnt, found := p.localVars[name]; found {
797 if cnt == 1 {
798 delete(p.localVars, name)
799 } else {
800 p.localVars[name] = cnt - 1
801 }
802 }
803 }
804 }
805
806 func (p *planBuilder) isLocalVar(name string) bool {
807 _, found := p.localVars[name]
808 return found
809 }