| 60 | } // namespace |
| 61 | |
| 62 | absl::StatusOr<std::string> ParseAndEvaluate(absl::string_view cel_expr) { |
| 63 | // === Start Codelab === |
| 64 | // Setup a default environment for building expressions. |
| 65 | InterpreterOptions options; |
| 66 | std::unique_ptr<CelExpressionBuilder> builder = |
| 67 | CreateCelExpressionBuilder(options); |
| 68 | |
| 69 | CEL_RETURN_IF_ERROR( |
| 70 | RegisterBuiltinFunctions(builder->GetRegistry(), options)); |
| 71 | |
| 72 | // Parse the expression. This is fine for codelabs, but this skips the type |
| 73 | // checking phase. It won't check that functions and variables are available |
| 74 | // in the environment, and it won't handle certain ambiguous identifier |
| 75 | // expressions (e.g. container lookup vs namespaced name, packaged function |
| 76 | // vs. receiver call style function). |
| 77 | ParsedExpr parsed_expr; |
| 78 | CEL_ASSIGN_OR_RETURN(parsed_expr, Parse(cel_expr)); |
| 79 | |
| 80 | // The evaluator uses a proto Arena for incidental allocations during |
| 81 | // evaluation. |
| 82 | google::protobuf::Arena arena; |
| 83 | // The activation provides variables and functions that are bound into the |
| 84 | // expression environment. In this example, there's no context expected, so |
| 85 | // we just provide an empty one to the evaluator. |
| 86 | Activation activation; |
| 87 | |
| 88 | // Build the expression plan. This assumes that the source expression AST and |
| 89 | // the expression builder outlive the CelExpression object. |
| 90 | CEL_ASSIGN_OR_RETURN(std::unique_ptr<CelExpression> expression_plan, |
| 91 | builder->CreateExpression(&parsed_expr.expr(), |
| 92 | &parsed_expr.source_info())); |
| 93 | |
| 94 | // Actually run the expression plan. We don't support any environment |
| 95 | // variables at the moment so just use an empty activation. |
| 96 | CEL_ASSIGN_OR_RETURN(CelValue result, |
| 97 | expression_plan->Evaluate(activation, &arena)); |
| 98 | |
| 99 | // Convert the result to a c++ string. CelValues may reference instances from |
| 100 | // either the input expression, or objects allocated on the arena, so we need |
| 101 | // to pass ownership (in this case by copying to a new instance and returning |
| 102 | // that). |
| 103 | return ConvertResult(result); |
| 104 | // === End Codelab === |
| 105 | } |
| 106 | |
| 107 | } // namespace cel_codelab |
nothing calls this directly
no test coverage detected