| 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 checker |
| 16 | |
| 17 | import ( |
| 18 | "sort" |
| 19 | |
| 20 | "github.com/google/cel-go/common/ast" |
| 21 | "github.com/google/cel-go/common/debug" |
| 22 | ) |
| 23 | |
| 24 | type semanticAdorner struct { |
| 25 | checked *ast.AST |
| 26 | } |
| 27 | |
| 28 | var _ debug.Adorner = &semanticAdorner{} |
| 29 | |
| 30 | func (a *semanticAdorner) GetMetadata(elem any) string { |
| 31 | result := "" |
| 32 | e, isExpr := elem.(ast.Expr) |
| 33 | if !isExpr { |
| 34 | return result |
| 35 | } |
| 36 | t := a.checked.TypeMap()[e.ID()] |
| 37 | if t != nil { |
| 38 | result += "~" |
| 39 | result += FormatCELType(t) |
| 40 | } |
| 41 | |
| 42 | switch e.Kind() { |
| 43 | case ast.IdentKind, |
| 44 | ast.CallKind, |
| 45 | ast.ListKind, |
| 46 | ast.StructKind, |
| 47 | ast.SelectKind: |
| 48 | if ref, found := a.checked.ReferenceMap()[e.ID()]; found { |
| 49 | if len(ref.OverloadIDs) == 0 { |
| 50 | result += "^" + ref.Name |
| 51 | } else { |
| 52 | sort.Strings(ref.OverloadIDs) |
| 53 | for i, overload := range ref.OverloadIDs { |
| 54 | if i == 0 { |
| 55 | result += "^" |
| 56 | } else { |
| 57 | result += "|" |
| 58 | } |
| 59 | result += overload |
| 60 | } |
| 61 | } |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | return result |
| 66 | } |
| 67 | |
| 68 | // Print returns a string representation of the Expr message, |
| 69 | // annotated with types from the CheckedExpr. The Expr must |
| 70 | // be a sub-expression embedded in the CheckedExpr. |
| 71 | func Print(e ast.Expr, checked *ast.AST) string { |
| 72 | a := &semanticAdorner{checked: checked} |
| 73 | return debug.ToAdornedDebugString(e, a) |
| 74 | } |