| 1 | // Copyright 2020 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 ext |
| 16 | |
| 17 | import ( |
| 18 | "github.com/google/cel-go/common/ast" |
| 19 | "github.com/google/cel-go/common/types" |
| 20 | "github.com/google/cel-go/common/types/ref" |
| 21 | ) |
| 22 | |
| 23 | // function invocation guards for common call signatures within extension functions. |
| 24 | |
| 25 | func intOrError(i int64, err error) ref.Val { |
| 26 | if err != nil { |
| 27 | return types.NewErrFromString(err.Error()) |
| 28 | } |
| 29 | return types.Int(i) |
| 30 | } |
| 31 | |
| 32 | func bytesOrError(bytes []byte, err error) ref.Val { |
| 33 | if err != nil { |
| 34 | return types.NewErrFromString(err.Error()) |
| 35 | } |
| 36 | return types.Bytes(bytes) |
| 37 | } |
| 38 | |
| 39 | func stringOrError(str string, err error) ref.Val { |
| 40 | if err != nil { |
| 41 | return types.NewErrFromString(err.Error()) |
| 42 | } |
| 43 | return types.String(str) |
| 44 | } |
| 45 | |
| 46 | func listStringOrError(strs []string, err error) ref.Val { |
| 47 | if err != nil { |
| 48 | return types.NewErrFromString(err.Error()) |
| 49 | } |
| 50 | return types.DefaultTypeAdapter.NativeToValue(strs) |
| 51 | } |
| 52 | |
| 53 | func extractIdent(target ast.Expr) (string, bool) { |
| 54 | switch target.Kind() { |
| 55 | case ast.IdentKind: |
| 56 | return target.AsIdent(), true |
| 57 | default: |
| 58 | return "", false |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | func macroTargetMatchesNamespace(ns string, target ast.Expr) bool { |
| 63 | if id, found := extractIdent(target); found { |
| 64 | return id == ns |
| 65 | } |
| 66 | return false |
| 67 | } |