/proc/self/cwd/eval/compiler/flat_expr_builder.cc
Line | Count | Source |
1 | | /* |
2 | | * Copyright 2021 Google LLC |
3 | | * |
4 | | * Licensed under the Apache License, Version 2.0 (the "License"); |
5 | | * you may not use this file except in compliance with the License. |
6 | | * You may obtain a copy of the License at |
7 | | * |
8 | | * https://www.apache.org/licenses/LICENSE-2.0 |
9 | | * |
10 | | * Unless required by applicable law or agreed to in writing, software |
11 | | * distributed under the License is distributed on an "AS IS" BASIS, |
12 | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
13 | | * See the License for the specific language governing permissions and |
14 | | * limitations under the License. |
15 | | */ |
16 | | |
17 | | #include "eval/compiler/flat_expr_builder.h" |
18 | | |
19 | | #include <algorithm> |
20 | | #include <cstddef> |
21 | | #include <cstdint> |
22 | | #include <deque> |
23 | | #include <iterator> |
24 | | #include <limits> |
25 | | #include <memory> |
26 | | #include <optional> |
27 | | #include <stack> |
28 | | #include <string> |
29 | | #include <type_traits> |
30 | | #include <utility> |
31 | | #include <vector> |
32 | | |
33 | | #include "absl/algorithm/container.h" |
34 | | #include "absl/base/nullability.h" |
35 | | #include "absl/cleanup/cleanup.h" |
36 | | #include "absl/container/flat_hash_map.h" |
37 | | #include "absl/container/flat_hash_set.h" |
38 | | #include "absl/container/node_hash_map.h" |
39 | | #include "absl/functional/any_invocable.h" |
40 | | #include "absl/log/absl_check.h" |
41 | | #include "absl/log/check.h" |
42 | | #include "absl/status/status.h" |
43 | | #include "absl/status/statusor.h" |
44 | | #include "absl/strings/match.h" |
45 | | #include "absl/strings/numbers.h" |
46 | | #include "absl/strings/str_cat.h" |
47 | | #include "absl/strings/string_view.h" |
48 | | #include "absl/strings/strip.h" |
49 | | #include "absl/types/span.h" |
50 | | #include "absl/types/variant.h" |
51 | | #include "base/ast.h" |
52 | | #include "base/builtins.h" |
53 | | #include "base/type_provider.h" |
54 | | #include "common/ast.h" |
55 | | #include "common/ast_traverse.h" |
56 | | #include "common/ast_visitor.h" |
57 | | #include "common/constant.h" |
58 | | #include "common/expr.h" |
59 | | #include "common/kind.h" |
60 | | #include "common/type.h" |
61 | | #include "common/value.h" |
62 | | #include "eval/compiler/check_ast_extensions.h" |
63 | | #include "eval/compiler/flat_expr_builder_extensions.h" |
64 | | #include "eval/compiler/resolver.h" |
65 | | #include "eval/eval/comprehension_step.h" |
66 | | #include "eval/eval/container_access_step.h" |
67 | | #include "eval/eval/create_list_step.h" |
68 | | #include "eval/eval/create_map_step.h" |
69 | | #include "eval/eval/create_struct_step.h" |
70 | | #include "eval/eval/evaluator_core.h" |
71 | | #include "eval/eval/expression_step_logic.h" |
72 | | #include "eval/eval/function_step.h" |
73 | | #include "eval/eval/ident_step.h" |
74 | | #include "eval/eval/optional_or_step.h" |
75 | | #include "eval/eval/select_step.h" |
76 | | #include "eval/eval/shadowable_value_step.h" |
77 | | #include "eval/eval/ternary_step.h" |
78 | | #include "internal/status_macros.h" |
79 | | #include "runtime/internal/convert_constant.h" |
80 | | #include "runtime/internal/issue_collector.h" |
81 | | #include "runtime/runtime_issue.h" |
82 | | #include "runtime/runtime_options.h" |
83 | | #include "runtime/type_registry.h" |
84 | | #include "google/protobuf/arena.h" |
85 | | |
86 | | namespace google::api::expr::runtime { |
87 | | |
88 | | namespace { |
89 | | |
90 | | using ::cel::Ast; |
91 | | using ::cel::AstTraverse; |
92 | | using ::cel::RuntimeIssue; |
93 | | using ::cel::Value; |
94 | | using ::cel::runtime_internal::ConvertConstant; |
95 | | using ::cel::runtime_internal::GetLegacyRuntimeTypeProvider; |
96 | | using ::cel::runtime_internal::GetRuntimeTypeProvider; |
97 | | using ::cel::runtime_internal::IssueCollector; |
98 | | |
99 | | constexpr absl::string_view kOptionalOrFn = "or"; |
100 | | constexpr absl::string_view kOptionalOrValueFn = "orValue"; |
101 | | constexpr absl::string_view kBlock = "cel.@block"; |
102 | | |
103 | | // Forward declare to resolve circular dependency for short_circuiting visitors. |
104 | | class FlatExprVisitor; |
105 | | |
106 | | // Helper for bookkeeping variables mapped to indexes. |
107 | | class IndexManager { |
108 | | public: |
109 | | IndexManager() |
110 | 19.6k | : next_free_slot_(0), |
111 | 19.6k | max_slot_count_(0), |
112 | 19.6k | iter_stack_count_(0), |
113 | 19.6k | max_iter_stack_count_(0), |
114 | 19.6k | lazy_iter_stack_count_(0) {} |
115 | | |
116 | 19.7k | size_t ReserveSlots(size_t n) { |
117 | 19.7k | size_t result = next_free_slot_; |
118 | 19.7k | next_free_slot_ += n; |
119 | 19.7k | if (next_free_slot_ > max_slot_count_) { |
120 | 18.8k | max_slot_count_ = next_free_slot_; |
121 | 18.8k | } |
122 | 19.7k | return result; |
123 | 19.7k | } |
124 | | |
125 | 18.0k | size_t ReleaseSlots(size_t n) { |
126 | 18.0k | next_free_slot_ -= n; |
127 | 18.0k | return next_free_slot_; |
128 | 18.0k | } |
129 | | |
130 | 19.7k | void ReserveIterStack() { |
131 | 19.7k | ++iter_stack_count_; |
132 | 19.7k | max_iter_stack_count_ = std::max(max_iter_stack_count_, iter_stack_count_); |
133 | 19.7k | } |
134 | 18.0k | void ReleaseIterStack() { --iter_stack_count_; } |
135 | 0 | void AddLazyIterStack() { ++lazy_iter_stack_count_; } |
136 | | |
137 | 18.9k | size_t max_slot_count() const { return max_slot_count_; } |
138 | | |
139 | | // Returns the maximum number of iterator stack slots required to evaluate the |
140 | | // expression by tracking the maximum comprehension nesting in the main |
141 | | // expression and dedicating a slot for any comprehensions evaluated lazily. |
142 | | // This is not as tight as possible, but is a correct upper bound estimate and |
143 | | // is tight for small expressions. |
144 | 18.9k | size_t IterStackRequirement() const { |
145 | 18.9k | return max_iter_stack_count_ + lazy_iter_stack_count_; |
146 | 18.9k | } |
147 | | |
148 | | private: |
149 | | size_t next_free_slot_; |
150 | | size_t max_slot_count_; |
151 | | size_t iter_stack_count_; |
152 | | size_t max_iter_stack_count_; |
153 | | size_t lazy_iter_stack_count_; |
154 | | }; |
155 | | |
156 | | // Helper for computing jump offsets. |
157 | | // |
158 | | // Jumps should be self-contained to a single expression node -- jumping |
159 | | // outside that range is a bug. |
160 | | struct ProgramStepIndex { |
161 | | int index; |
162 | | ProgramBuilder::Subexpression* subexpression; |
163 | | }; |
164 | | |
165 | | // A convenience wrapper for offset-calculating logic. |
166 | | class Jump { |
167 | | public: |
168 | | static absl::StatusOr<int> CalculateOffset(ProgramStepIndex base, |
169 | 124k | ProgramStepIndex target) { |
170 | 124k | if (target.subexpression != base.subexpression) { |
171 | 0 | return absl::InternalError( |
172 | 0 | "Jump target must be contained in the parent" |
173 | 0 | "subexpression"); |
174 | 0 | } |
175 | | |
176 | 124k | int offset = base.subexpression->CalculateOffset(base.index, target.index); |
177 | | |
178 | | // The offset may be packed into a 31-bit int field. Technically, the offset |
179 | | // could be larger for a well-formed expression with more than 2**30 steps, |
180 | | // but such a case is unlikely to exist at this time. |
181 | 124k | constexpr int kMaxJumpOffset = (1 << 30) - 1; |
182 | 124k | constexpr int kMinJumpOffset = -(1 << 30); |
183 | | |
184 | 124k | if (offset < kMinJumpOffset || offset > kMaxJumpOffset) { |
185 | 0 | return absl::InternalError("Jump offset exceeds supported range: " + |
186 | 0 | absl::StrCat(offset)); |
187 | 0 | } |
188 | 124k | return offset; |
189 | 124k | } |
190 | | }; |
191 | | |
192 | | class CondVisitor { |
193 | | public: |
194 | 8.73k | virtual ~CondVisitor() = default; |
195 | | virtual void PreVisit(const cel::Expr* expr) = 0; |
196 | | virtual void PostVisitArg(int arg_num, const cel::Expr* expr) = 0; |
197 | | virtual void PostVisit(const cel::Expr* expr) = 0; |
198 | 0 | virtual void PostVisitTarget(const cel::Expr* expr) {} |
199 | | }; |
200 | | |
201 | | // Visitor managing the "&&" and "||" (boolean logic) operations. |
202 | | // Implements short-circuiting if enabled. |
203 | | // |
204 | | // With short-circuiting enabled, generates a program like: |
205 | | // +-------------+------------------------+-----------------------+ |
206 | | // | PC | Step | Stack | |
207 | | // +-------------+------------------------+-----------------------+ |
208 | | // | i + 0 | <Arg1> | arg1 | |
209 | | // | i + 1 | ConditionalJump i + 4 | arg1 | |
210 | | // | i + 2 | <Arg2> | arg1, arg2 | |
211 | | // | i + 3 | BooleanOperator | Op(arg1, arg2) | |
212 | | // | i + 4 | <rest of program> | arg1 | Op(arg1, arg2) | |
213 | | // +-------------+------------------------+------------------------+ |
214 | | class LogicalCondVisitor : public CondVisitor { |
215 | | public: |
216 | | explicit LogicalCondVisitor(FlatExprVisitor* visitor, bool is_or, |
217 | | bool short_circuiting) |
218 | 4.60k | : visitor_(visitor), is_or_(is_or), short_circuiting_(short_circuiting) {} |
219 | | |
220 | | void PreVisit(const cel::Expr* expr) override; |
221 | | void PostVisitArg(int arg_num, const cel::Expr* expr) override; |
222 | | void PostVisit(const cel::Expr* expr) override; |
223 | | |
224 | | private: |
225 | | FlatExprVisitor* visitor_; |
226 | | const bool is_or_; |
227 | | std::vector<ProgramStepIndex> jump_steps_; |
228 | | bool short_circuiting_; |
229 | | }; |
230 | | |
231 | | // Visitor managing optional "or" and "orValue" operations. |
232 | | // Implements short-circuiting if enabled. |
233 | | class OptionalOrCondVisitor : public CondVisitor { |
234 | | public: |
235 | | explicit OptionalOrCondVisitor(FlatExprVisitor* visitor, bool is_or_value, |
236 | | bool short_circuiting) |
237 | 0 | : visitor_(visitor), |
238 | 0 | is_or_value_(is_or_value), |
239 | 0 | short_circuiting_(short_circuiting) {} |
240 | | |
241 | | void PreVisit(const cel::Expr* expr) override; |
242 | 0 | void PostVisitArg(int arg_num, const cel::Expr* expr) override {} |
243 | | void PostVisitTarget(const cel::Expr* expr) override; |
244 | | void PostVisit(const cel::Expr* expr) override; |
245 | | |
246 | | private: |
247 | | FlatExprVisitor* visitor_; |
248 | | const bool is_or_value_; |
249 | | OptionalHasValueJumpStep* jump_step_ = nullptr; |
250 | | ProgramStepIndex jump_step_pos_{-1, nullptr}; |
251 | | bool short_circuiting_; |
252 | | }; |
253 | | |
254 | | class TernaryCondVisitor : public CondVisitor { |
255 | | public: |
256 | 4.12k | explicit TernaryCondVisitor(FlatExprVisitor* visitor) : visitor_(visitor) {} |
257 | | |
258 | | void PreVisit(const cel::Expr* expr) override; |
259 | | void PostVisitArg(int arg_num, const cel::Expr* expr) override; |
260 | | void PostVisit(const cel::Expr* expr) override; |
261 | | |
262 | | private: |
263 | | FlatExprVisitor* visitor_; |
264 | | std::optional<ProgramStepIndex> cond_jump_pos_; |
265 | | std::optional<ProgramStepIndex> jump_after_first_pos_; |
266 | | }; |
267 | | |
268 | | class ExhaustiveTernaryCondVisitor : public CondVisitor { |
269 | | public: |
270 | | explicit ExhaustiveTernaryCondVisitor(FlatExprVisitor* visitor) |
271 | 0 | : visitor_(visitor) {} |
272 | | |
273 | | void PreVisit(const cel::Expr* expr) override; |
274 | 0 | void PostVisitArg(int arg_num, const cel::Expr* expr) override {} |
275 | | void PostVisit(const cel::Expr* expr) override; |
276 | | |
277 | | private: |
278 | | FlatExprVisitor* visitor_; |
279 | | }; |
280 | | |
281 | | // Returns a hint for the number of program nodes (steps or subexpressions) that |
282 | | // will be created for this expr. |
283 | 502k | size_t SizeHint(const cel::Expr& expr) { |
284 | 502k | switch (expr.kind_case()) { |
285 | 167k | case cel::ExprKindCase::kConstant: |
286 | 167k | return 1; |
287 | 102k | case cel::ExprKindCase::kIdentExpr: |
288 | 102k | return 1; |
289 | 18.8k | case cel::ExprKindCase::kSelectExpr: |
290 | 18.8k | return 2; |
291 | 127k | case cel::ExprKindCase::kCallExpr: |
292 | 127k | return expr.call_expr().args().size() + |
293 | 127k | (expr.call_expr().has_target() ? 2 : 1); |
294 | 58.8k | case cel::ExprKindCase::kListExpr: |
295 | 58.8k | return expr.list_expr().elements().size() + 1; |
296 | 3.42k | case cel::ExprKindCase::kStructExpr: |
297 | 3.42k | return expr.struct_expr().fields().size() + 1; |
298 | 4.24k | case cel::ExprKindCase::kMapExpr: |
299 | 4.24k | return 2 * expr.struct_expr().fields().size() + 1; |
300 | 19.7k | default: |
301 | 19.7k | return 1; |
302 | 502k | } |
303 | 0 | return 0; |
304 | 502k | } |
305 | | |
306 | | // Returns whether this comprehension appears to be a standard map/filter |
307 | | // macro implementation. It is not exhaustive, so it is unsafe to use with |
308 | | // custom comprehensions outside of the standard macros or hand crafted ASTs. |
309 | | bool IsOptimizableListAppend(const cel::ComprehensionExpr* comprehension, |
310 | | bool enable_comprehension_list_append, |
311 | 19.7k | bool short_circuiting = true) { |
312 | 19.7k | if (!enable_comprehension_list_append) { |
313 | 19.7k | return false; |
314 | 19.7k | } |
315 | 0 | absl::string_view accu_var = comprehension->accu_var(); |
316 | 0 | if (accu_var.empty() || !absl::StartsWith(accu_var, "@") || |
317 | 0 | !comprehension->has_result() || |
318 | 0 | !comprehension->result().has_ident_expr() || |
319 | 0 | comprehension->result().ident_expr().name() != accu_var) { |
320 | 0 | return false; |
321 | 0 | } |
322 | 0 | if (!comprehension->accu_init().has_list_expr() || |
323 | 0 | !comprehension->accu_init().list_expr().elements().empty()) { |
324 | 0 | return false; |
325 | 0 | } |
326 | | |
327 | 0 | if (!comprehension->loop_step().has_call_expr()) { |
328 | 0 | return false; |
329 | 0 | } |
330 | | |
331 | | // Macro loop_step for a filter() will contain a ternary: |
332 | | // filter ? accu_var + [elem] : accu_var |
333 | | // Macro loop_step for a map() will contain a list concat operation: |
334 | | // accu_var + [elem] |
335 | 0 | const auto* call_expr = &comprehension->loop_step().call_expr(); |
336 | |
|
337 | 0 | if (call_expr->function() == cel::builtin::kTernary && |
338 | 0 | call_expr->args().size() == 3) { |
339 | 0 | if (!short_circuiting || !call_expr->args()[1].has_call_expr() || |
340 | 0 | !call_expr->args()[2].has_ident_expr() || |
341 | 0 | call_expr->args()[2].ident_expr().name() != accu_var) { |
342 | 0 | return false; |
343 | 0 | } |
344 | 0 | call_expr = &(call_expr->args()[1].call_expr()); |
345 | 0 | } |
346 | | |
347 | 0 | return !call_expr->has_target() && |
348 | 0 | call_expr->function() == cel::builtin::kAdd && |
349 | 0 | call_expr->args().size() == 2 && |
350 | 0 | call_expr->args()[0].has_ident_expr() && |
351 | 0 | call_expr->args()[0].ident_expr().name() == accu_var && |
352 | 0 | call_expr->args()[1].has_list_expr() && |
353 | 0 | call_expr->args()[1].list_expr().elements().size() == 1 && |
354 | 0 | !call_expr->args()[1].list_expr().elements()[0].optional(); |
355 | 0 | } |
356 | | |
357 | | // Assuming `IsOptimizableListAppend()` return true, return a pointer to the |
358 | | // call `accu_var + [elem]`. |
359 | | const cel::CallExpr* GetOptimizableListAppendCall( |
360 | 0 | const cel::ComprehensionExpr* comprehension) { |
361 | 0 | ABSL_DCHECK(IsOptimizableListAppend( |
362 | 0 | comprehension, /*enable_comprehension_list_append=*/true)); |
363 | | |
364 | | // Macro loop_step for a filter() will contain a ternary: |
365 | | // filter ? accu_var + [elem] : accu_var |
366 | | // Macro loop_step for a map() will contain a list concat operation: |
367 | | // accu_var + [elem] |
368 | 0 | const auto* call_expr = &comprehension->loop_step().call_expr(); |
369 | |
|
370 | 0 | if (call_expr->function() == cel::builtin::kTernary && |
371 | 0 | call_expr->args().size() == 3) { |
372 | 0 | call_expr = &(call_expr->args()[1].call_expr()); |
373 | 0 | } |
374 | 0 | return call_expr; |
375 | 0 | } |
376 | | |
377 | | // Assuming `IsOptimizableListAppend()` return true, return a pointer to the |
378 | | // node `[elem]`. |
379 | | const cel::Expr* GetOptimizableListAppendOperand( |
380 | 0 | const cel::ComprehensionExpr* comprehension) { |
381 | 0 | return &GetOptimizableListAppendCall(comprehension)->args()[1]; |
382 | 0 | } |
383 | | |
384 | | // Returns whether this comprehension appears to be a macro implementation for |
385 | | // map transformations. It is not exhaustive, so it is unsafe to use with custom |
386 | | // comprehensions outside of the standard macros or hand crafted ASTs. |
387 | | bool IsOptimizableMapInsert(const cel::ComprehensionExpr* comprehension, |
388 | | bool enable_comprehension_mutable_map, |
389 | 19.7k | bool short_circuiting = true) { |
390 | 19.7k | if (!enable_comprehension_mutable_map) { |
391 | 19.7k | return false; |
392 | 19.7k | } |
393 | 0 | if (comprehension->iter_var().empty() || comprehension->iter_var2().empty()) { |
394 | 0 | return false; |
395 | 0 | } |
396 | 0 | absl::string_view accu_var = comprehension->accu_var(); |
397 | 0 | if (accu_var.empty() || !absl::StartsWith(accu_var, "@") || |
398 | 0 | !comprehension->has_result() || |
399 | 0 | !comprehension->result().has_ident_expr() || |
400 | 0 | comprehension->result().ident_expr().name() != accu_var) { |
401 | 0 | return false; |
402 | 0 | } |
403 | 0 | if (!comprehension->accu_init().has_map_expr() || |
404 | 0 | !comprehension->accu_init().map_expr().entries().empty()) { |
405 | 0 | return false; |
406 | 0 | } |
407 | 0 | if (!comprehension->loop_step().has_call_expr()) { |
408 | 0 | return false; |
409 | 0 | } |
410 | 0 | const auto* call_expr = &comprehension->loop_step().call_expr(); |
411 | |
|
412 | 0 | if (call_expr->function() == cel::builtin::kTernary && |
413 | 0 | call_expr->args().size() == 3) { |
414 | 0 | if (!short_circuiting || !call_expr->args()[1].has_call_expr() || |
415 | 0 | !call_expr->args()[2].has_ident_expr() || |
416 | 0 | call_expr->args()[2].ident_expr().name() != accu_var) { |
417 | 0 | return false; |
418 | 0 | } |
419 | 0 | call_expr = &(call_expr->args()[1].call_expr()); |
420 | 0 | } |
421 | 0 | return !call_expr->has_target() && |
422 | 0 | call_expr->function() == "cel.@mapInsert" && |
423 | 0 | (call_expr->args().size() == 2 || call_expr->args().size() == 3) && |
424 | 0 | call_expr->args()[0].has_ident_expr() && |
425 | 0 | call_expr->args()[0].ident_expr().name() == accu_var; |
426 | 0 | } |
427 | | |
428 | 19.7k | bool IsBind(const cel::ComprehensionExpr* comprehension) { |
429 | 19.7k | static constexpr absl::string_view kUnusedIterVar = "#unused"; |
430 | | |
431 | 19.7k | return comprehension->loop_condition().const_expr().has_bool_value() && |
432 | 19.6k | comprehension->loop_condition().const_expr().bool_value() == false && |
433 | 0 | comprehension->iter_var() == kUnusedIterVar && |
434 | 0 | comprehension->iter_var2().empty() && |
435 | 0 | comprehension->iter_range().has_list_expr() && |
436 | 0 | comprehension->iter_range().list_expr().elements().empty(); |
437 | 19.7k | } |
438 | | |
439 | 118k | bool IsBlock(const cel::CallExpr* call) { return call->function() == kBlock; } |
440 | | |
441 | | // Visitor for Comprehension expressions. |
442 | | class ComprehensionVisitor { |
443 | | public: |
444 | | explicit ComprehensionVisitor(FlatExprVisitor* visitor, bool is_trivial, |
445 | | size_t iter_slot, size_t iter2_slot, |
446 | | size_t accu_slot) |
447 | 19.7k | : visitor_(visitor), |
448 | 19.7k | is_trivial_(is_trivial), |
449 | 19.7k | accu_init_extracted_(false), |
450 | 19.7k | iter_slot_(iter_slot), |
451 | 19.7k | iter2_slot_(iter2_slot), |
452 | 19.7k | accu_slot_(accu_slot) {} |
453 | | |
454 | | void PreVisit(const cel::Expr* expr); |
455 | | absl::Status PostVisitArg(cel::ComprehensionArg arg_num, |
456 | 90.2k | const cel::Expr* comprehension_expr) { |
457 | 90.2k | if (is_trivial_) { |
458 | 0 | PostVisitArgTrivial(arg_num, comprehension_expr); |
459 | 0 | return absl::OkStatus(); |
460 | 90.2k | } else { |
461 | 90.2k | return PostVisitArgDefault(arg_num, comprehension_expr); |
462 | 90.2k | } |
463 | 90.2k | } |
464 | | void PostVisit(const cel::Expr* expr); |
465 | | |
466 | 0 | void MarkAccuInitExtracted() { accu_init_extracted_ = true; } |
467 | | |
468 | | private: |
469 | | void PostVisitArgTrivial(cel::ComprehensionArg arg_num, |
470 | | const cel::Expr* comprehension_expr); |
471 | | |
472 | | absl::Status PostVisitArgDefault(cel::ComprehensionArg arg_num, |
473 | | const cel::Expr* comprehension_expr); |
474 | | |
475 | | ComprehensionInitStepInfo* absl_nullable GetInitStep(); |
476 | | ComprehensionCondStepInfo* absl_nullable GetCondStep(); |
477 | | ComprehensionNextStepInfo* absl_nullable GetNextStep(); |
478 | | |
479 | | FlatExprVisitor* visitor_; |
480 | | std::optional<ProgramStepIndex> init_step_pos_; |
481 | | std::optional<ProgramStepIndex> next_step_pos_; |
482 | | std::optional<ProgramStepIndex> cond_step_pos_; |
483 | | bool is_trivial_; |
484 | | bool accu_init_extracted_; |
485 | | size_t iter_slot_; |
486 | | size_t iter2_slot_; |
487 | | size_t accu_slot_; |
488 | | }; |
489 | | |
490 | | absl::flat_hash_set<int32_t> MakeOptionalIndicesSet( |
491 | 3.05k | const cel::StructExpr& create_struct_expr) { |
492 | 3.05k | absl::flat_hash_set<int32_t> optional_indices; |
493 | 4.58k | for (size_t i = 0; i < create_struct_expr.fields().size(); ++i) { |
494 | 1.52k | if (create_struct_expr.fields()[i].optional()) { |
495 | 0 | optional_indices.insert(static_cast<int32_t>(i)); |
496 | 0 | } |
497 | 1.52k | } |
498 | 3.05k | return optional_indices; |
499 | 3.05k | } |
500 | | |
501 | | absl::flat_hash_set<int32_t> MakeOptionalIndicesSet( |
502 | 4.53k | const cel::MapExpr& map_expr) { |
503 | 4.53k | absl::flat_hash_set<int32_t> optional_indices; |
504 | 9.40k | for (size_t i = 0; i < map_expr.entries().size(); ++i) { |
505 | 4.87k | if (map_expr.entries()[i].optional()) { |
506 | 0 | optional_indices.insert(static_cast<int32_t>(i)); |
507 | 0 | } |
508 | 4.87k | } |
509 | 4.53k | return optional_indices; |
510 | 4.53k | } |
511 | | |
512 | | absl::flat_hash_set<size_t> MakeOptionalIndicesSet( |
513 | 58.7k | const cel::ListExpr& list_expr) { |
514 | 58.7k | absl::flat_hash_set<size_t> optional_indices; |
515 | 175k | for (size_t i = 0; i < list_expr.elements().size(); ++i) { |
516 | 117k | if (list_expr.elements()[i].optional()) { |
517 | 0 | optional_indices.insert(i); |
518 | 0 | } |
519 | 117k | } |
520 | 58.7k | return optional_indices; |
521 | 58.7k | } |
522 | | |
523 | | class FlatExprVisitor : public cel::AstVisitor { |
524 | | public: |
525 | | enum class CallHandlerResult { |
526 | | // The call was intercepted, no additional processing is needed. |
527 | | kIntercepted, |
528 | | // The call was not intercepted, continue with the default processing. |
529 | | kNotIntercepted, |
530 | | }; |
531 | | |
532 | | // Handler for functions with builtin implementations. |
533 | | // This is used to replace the usual dispatcher step that applies |
534 | | // the arguments to a candidate function from the function registry. |
535 | | using CallHandler = absl::AnyInvocable<CallHandlerResult( |
536 | | const cel::Expr&, const cel::CallExpr&)>; |
537 | | |
538 | | FlatExprVisitor( |
539 | | const Resolver& resolver, const cel::RuntimeOptions& options, |
540 | | std::vector<std::unique_ptr<ProgramOptimizer>> program_optimizers, |
541 | | const absl::flat_hash_map<int64_t, cel::TypeSpec>& type_map, |
542 | | const cel::TypeProvider& type_provider, IssueCollector& issue_collector, |
543 | | ProgramBuilder& program_builder, PlannerContext& extension_context, |
544 | | bool enable_optional_types) |
545 | 19.6k | : resolver_(resolver), |
546 | 19.6k | type_provider_(type_provider), |
547 | 19.6k | progress_status_(absl::OkStatus()), |
548 | 19.6k | resolved_select_expr_(nullptr), |
549 | 19.6k | options_(options), |
550 | 19.6k | program_optimizers_(std::move(program_optimizers)), |
551 | 19.6k | type_map_(type_map), |
552 | 19.6k | issue_collector_(issue_collector), |
553 | 19.6k | program_builder_(program_builder), |
554 | 19.6k | extension_context_(extension_context), |
555 | 19.6k | enable_optional_types_(enable_optional_types) { |
556 | 19.6k | constexpr size_t kCallHandlerSizeHint = 11; |
557 | 19.6k | call_handlers_.reserve(kCallHandlerSizeHint); |
558 | 19.6k | call_handlers_[cel::builtin::kIndex] = [this](const cel::Expr& expr, |
559 | 19.6k | const cel::CallExpr& call) { |
560 | 3.17k | return HandleIndex(expr, call); |
561 | 3.17k | }; |
562 | 19.6k | call_handlers_[kBlock] = [this](const cel::Expr& expr, |
563 | 19.6k | const cel::CallExpr& call) { |
564 | 0 | return HandleBlock(expr, call); |
565 | 0 | }; |
566 | 19.6k | call_handlers_[cel::builtin::kAdd] = [this](const cel::Expr& expr, |
567 | 23.7k | const cel::CallExpr& call) { |
568 | 23.7k | return HandleListAppend(expr, call); |
569 | 23.7k | }; |
570 | 19.6k | if (options_.enable_fast_builtins) { |
571 | 19.6k | call_handlers_[cel::builtin::kNotStrictlyFalse] = |
572 | 19.6k | [this](const cel::Expr& expr, const cel::CallExpr& call) { |
573 | 126 | return HandleNotStrictlyFalse(expr, call); |
574 | 126 | }; |
575 | 19.6k | call_handlers_[cel::builtin::kNotStrictlyFalseDeprecated] = |
576 | 19.6k | [this](const cel::Expr& expr, const cel::CallExpr& call) { |
577 | 0 | return HandleNotStrictlyFalse(expr, call); |
578 | 0 | }; |
579 | 19.6k | call_handlers_[cel::builtin::kNot] = [this](const cel::Expr& expr, |
580 | 19.6k | const cel::CallExpr& call) { |
581 | 1.19k | return HandleNot(expr, call); |
582 | 1.19k | }; |
583 | 19.6k | if (options_.enable_heterogeneous_equality) { |
584 | 19.6k | for (const auto& in_op : |
585 | 19.6k | {cel::builtin::kIn, cel::builtin::kInDeprecated, |
586 | 58.8k | cel::builtin::kInFunction}) { |
587 | 58.8k | call_handlers_[in_op] = [this](const cel::Expr& expr, |
588 | 58.8k | const cel::CallExpr& call) { |
589 | 1.82k | return HandleHeterogeneousEqualityIn(expr, call); |
590 | 1.82k | }; |
591 | 58.8k | } |
592 | | // Try to detect if the environment is setup with a custom equality |
593 | | // implementation. |
594 | 19.6k | if (resolver_ |
595 | 19.6k | .FindOverloads(cel::builtin::kEqual, |
596 | 19.6k | /*receiver_style=*/false, |
597 | 19.6k | {cel::Kind::kAny, cel::Kind::kAny}) |
598 | 19.6k | .empty()) { |
599 | 19.6k | call_handlers_[cel::builtin::kEqual] = |
600 | 19.6k | [this](const cel::Expr& expr, const cel::CallExpr& call) { |
601 | 9.21k | return HandleHeterogeneousEquality(expr, call, |
602 | 9.21k | /*inequality=*/false); |
603 | 9.21k | }; |
604 | 19.6k | call_handlers_[cel::builtin::kInequal] = |
605 | 19.6k | [this](const cel::Expr& expr, const cel::CallExpr& call) { |
606 | 446 | return HandleHeterogeneousEquality(expr, call, |
607 | 446 | /*inequality=*/true); |
608 | 446 | }; |
609 | 19.6k | } |
610 | 19.6k | } |
611 | 19.6k | } |
612 | 19.6k | } |
613 | | |
614 | 524k | void PreVisitExpr(const cel::Expr& expr) override { |
615 | 524k | ValidateOrError(!absl::holds_alternative<cel::UnspecifiedExpr>(expr.kind()), |
616 | 524k | "Invalid empty expression"); |
617 | 524k | if (!progress_status_.ok()) { |
618 | 22.1k | return; |
619 | 22.1k | } |
620 | 502k | if (resume_from_suppressed_branch_ == nullptr && |
621 | 502k | suppressed_branches_.find(&expr) != suppressed_branches_.end()) { |
622 | 0 | resume_from_suppressed_branch_ = &expr; |
623 | 0 | } |
624 | | |
625 | 502k | if (extension_context_.resolve_types()) { |
626 | 502k | MaybeResolveType(expr); |
627 | 502k | } |
628 | | |
629 | 502k | if (block_.has_value()) { |
630 | 0 | BlockInfo& block = *block_; |
631 | 0 | if (block.in && block.bindings_set.contains(&expr)) { |
632 | 0 | block.current_binding = &expr; |
633 | 0 | } |
634 | 0 | } |
635 | | |
636 | 502k | auto* subexpression = |
637 | 502k | program_builder_.EnterSubexpression(&expr, SizeHint(expr)); |
638 | 502k | if (subexpression == nullptr) { |
639 | 0 | progress_status_.Update( |
640 | 0 | absl::InternalError("same CEL expr visited twice")); |
641 | 0 | return; |
642 | 0 | } |
643 | | |
644 | 502k | for (const std::unique_ptr<ProgramOptimizer>& optimizer : |
645 | 502k | program_optimizers_) { |
646 | 0 | absl::Status status = optimizer->OnPreVisit(extension_context_, expr); |
647 | 0 | if (!status.ok()) { |
648 | 0 | SetProgressStatusIfError(status); |
649 | 0 | } |
650 | 0 | } |
651 | 502k | } |
652 | | |
653 | 524k | void PostVisitExpr(const cel::Expr& expr) override { |
654 | 524k | if (!progress_status_.ok()) { |
655 | 27.0k | return; |
656 | 27.0k | } |
657 | 497k | if (&expr == resume_from_suppressed_branch_) { |
658 | 0 | resume_from_suppressed_branch_ = nullptr; |
659 | 0 | } |
660 | | |
661 | 497k | for (const std::unique_ptr<ProgramOptimizer>& optimizer : |
662 | 497k | program_optimizers_) { |
663 | 0 | absl::Status status = optimizer->OnPostVisit(extension_context_, expr); |
664 | 0 | if (!status.ok()) { |
665 | 0 | SetProgressStatusIfError(status); |
666 | 0 | return; |
667 | 0 | } |
668 | 0 | } |
669 | | |
670 | 497k | program_builder_.ExitSubexpression(&expr); |
671 | | |
672 | 497k | if (!comprehension_stack_.empty() && |
673 | 346k | comprehension_stack_.back().is_optimizable_bind && |
674 | 0 | (&comprehension_stack_.back().comprehension->accu_init() == &expr)) { |
675 | 0 | SetProgressStatusIfError( |
676 | 0 | MaybeExtractSubexpression(&expr, comprehension_stack_.back())); |
677 | 0 | } |
678 | | |
679 | 497k | if (block_.has_value()) { |
680 | 0 | BlockInfo& block = *block_; |
681 | 0 | if (block.current_binding == &expr) { |
682 | 0 | int index = program_builder_.ExtractSubexpression(&expr); |
683 | 0 | if (index == -1) { |
684 | 0 | SetProgressStatusIfError( |
685 | 0 | absl::InvalidArgumentError("failed to extract subexpression")); |
686 | 0 | return; |
687 | 0 | } |
688 | 0 | block.subexpressions[block.current_index++] = index; |
689 | 0 | block.current_binding = nullptr; |
690 | 0 | } |
691 | 0 | } |
692 | 497k | } |
693 | | |
694 | | void PostVisitConst(const cel::Expr& expr, |
695 | 169k | const cel::Constant& const_expr) override { |
696 | 169k | if (!progress_status_.ok()) { |
697 | 2.41k | return; |
698 | 2.41k | } |
699 | | |
700 | 167k | absl::StatusOr<cel::Value> converted_value = |
701 | 167k | ConvertConstant(const_expr, extension_context_.MutableArena()); |
702 | | |
703 | 167k | if (!converted_value.ok()) { |
704 | 0 | SetProgressStatusIfError(converted_value.status()); |
705 | 0 | return; |
706 | 0 | } |
707 | | |
708 | 167k | AddStep(ExpressionStep::MakeConstant(std::move(converted_value).value(), |
709 | 167k | expr.id())); |
710 | 167k | } |
711 | | |
712 | | struct SlotLookupResult { |
713 | | int slot; |
714 | | int subexpression; |
715 | | }; |
716 | | |
717 | | // Helper to lookup a variable mapped to a slot. |
718 | | // |
719 | | // If lazy evaluation enabled and ided as a lazy expression, |
720 | | // subexpression and slot will be set. |
721 | 102k | SlotLookupResult LookupSlot(absl::string_view path) { |
722 | | // If there's a leading dot, it cannot resolve to a local variable. |
723 | 102k | if (absl::StartsWith(path, ".")) { |
724 | 802 | return {-1, -1}; |
725 | 802 | } |
726 | 101k | if (block_.has_value()) { |
727 | 0 | const BlockInfo& block = *block_; |
728 | 0 | if (block.in) { |
729 | 0 | absl::string_view index_suffix = path; |
730 | 0 | if (absl::ConsumePrefix(&index_suffix, "@index")) { |
731 | 0 | size_t index; |
732 | 0 | if (!absl::SimpleAtoi(index_suffix, &index)) { |
733 | 0 | SetProgressStatusIfError( |
734 | 0 | issue_collector_.AddIssue(RuntimeIssue::CreateError( |
735 | 0 | absl::InvalidArgumentError("bad @index")))); |
736 | 0 | return {-1, -1}; |
737 | 0 | } |
738 | 0 | if (index >= block.size) { |
739 | 0 | SetProgressStatusIfError( |
740 | 0 | issue_collector_.AddIssue(RuntimeIssue::CreateError( |
741 | 0 | absl::InvalidArgumentError(absl::StrCat( |
742 | 0 | "invalid @index greater than number of bindings: ", |
743 | 0 | index, " >= ", block.size))))); |
744 | 0 | return {-1, -1}; |
745 | 0 | } |
746 | 0 | if (index >= block.current_index) { |
747 | 0 | SetProgressStatusIfError( |
748 | 0 | issue_collector_.AddIssue(RuntimeIssue::CreateError( |
749 | 0 | absl::InvalidArgumentError(absl::StrCat( |
750 | 0 | "@index references current or future binding: ", index, |
751 | 0 | " >= ", block.current_index))))); |
752 | 0 | return {-1, -1}; |
753 | 0 | } |
754 | 0 | return {static_cast<int>(block.index + index), |
755 | 0 | block.subexpressions[index]}; |
756 | 0 | } |
757 | 0 | } |
758 | 0 | } |
759 | 101k | if (!comprehension_stack_.empty()) { |
760 | 320k | for (int i = comprehension_stack_.size() - 1; i >= 0; i--) { |
761 | 294k | const ComprehensionStackRecord& record = comprehension_stack_[i]; |
762 | 294k | if (record.iter_var_in_scope && |
763 | 67.4k | record.comprehension->iter_var() == path) { |
764 | 4.97k | if (record.is_optimizable_bind) { |
765 | 0 | SetProgressStatusIfError(issue_collector_.AddIssue( |
766 | 0 | RuntimeIssue::CreateWarning(absl::InvalidArgumentError( |
767 | 0 | "Unexpected iter_var access in trivial comprehension")))); |
768 | 0 | return {-1, -1}; |
769 | 0 | } |
770 | 4.97k | return {static_cast<int>(record.iter_slot), -1}; |
771 | 4.97k | } |
772 | 289k | if (record.iter_var2_in_scope && |
773 | 62.4k | record.comprehension->iter_var2() == path) { |
774 | 0 | return {static_cast<int>(record.iter2_slot), -1}; |
775 | 0 | } |
776 | 289k | if (record.accu_var_in_scope && |
777 | 80.4k | record.comprehension->accu_var() == path) { |
778 | 40.0k | int slot = record.accu_slot; |
779 | 40.0k | int subexpression = -1; |
780 | 40.0k | if (record.is_optimizable_bind) { |
781 | 0 | subexpression = record.subexpression; |
782 | 0 | } |
783 | 40.0k | return {slot, subexpression}; |
784 | 40.0k | } |
785 | 289k | } |
786 | 71.0k | } |
787 | 56.6k | if (absl::StartsWith(path, "@it:") || absl::StartsWith(path, "@it2:") || |
788 | 56.6k | absl::StartsWith(path, "@ac:")) { |
789 | | // If we see a CSE generated comprehension variable that was not |
790 | | // resolvable through the normal comprehension scope resolution, reject it |
791 | | // now rather than surfacing errors at activation time. |
792 | 0 | SetProgressStatusIfError( |
793 | 0 | issue_collector_.AddIssue(RuntimeIssue::CreateError( |
794 | 0 | absl::InvalidArgumentError("out of scope reference to CSE " |
795 | 0 | "generated comprehension variable")))); |
796 | 0 | } |
797 | 56.6k | return {-1, -1}; |
798 | 101k | } |
799 | | |
800 | | // Ident node handler. |
801 | | // Invoked after child nodes are processed. |
802 | | void PostVisitIdent(const cel::Expr& expr, |
803 | 112k | const cel::IdentExpr& ident_expr) override { |
804 | 112k | if (!progress_status_.ok()) { |
805 | 9.63k | return; |
806 | 9.63k | } |
807 | 102k | absl::string_view path = ident_expr.name(); |
808 | 102k | if (!ValidateOrError( |
809 | 102k | !path.empty(), |
810 | 102k | "Invalid expression: identifier 'name' must not be empty")) { |
811 | 0 | return; |
812 | 0 | } |
813 | | |
814 | | // Check if this is a local variable first (since it should shadow most |
815 | | // other interpretations). |
816 | 102k | SlotLookupResult slot = LookupSlot(path); |
817 | | |
818 | 102k | if (slot.subexpression >= 0) { |
819 | 0 | const ProgramBuilder::Subexpression* subexpression = |
820 | 0 | program_builder_.GetExtractedSubexpression(slot.subexpression); |
821 | 0 | if (subexpression == nullptr) { |
822 | 0 | SetProgressStatusIfError( |
823 | 0 | absl::InternalError("bad subexpression reference")); |
824 | 0 | return; |
825 | 0 | } |
826 | 0 | if (options_.enable_subexpression_inlining) { |
827 | 0 | if (std::optional<ExpressionStep> inlined_step = |
828 | 0 | subexpression->MaybeInline(expr.id()); |
829 | 0 | inlined_step.has_value()) { |
830 | 0 | AddStep(*std::move(inlined_step)); |
831 | 0 | return; |
832 | 0 | } |
833 | 0 | } |
834 | | // Off by one since mainline expression will be index 0. |
835 | 0 | AddStep(ExpressionStep::MakeLazyInitStep( |
836 | 0 | slot.slot, slot.subexpression + 1, expr.id())); |
837 | 0 | return; |
838 | 102k | } else if (slot.slot >= 0) { |
839 | 45.0k | AddStep(ExpressionStep::MakeReadSlotStep(slot.slot, expr.id())); |
840 | 45.0k | return; |
841 | 45.0k | } |
842 | | |
843 | | // Attempt to resolve a select expression as a namespaced identifier for an |
844 | | // enum or type constant value. |
845 | 57.4k | std::optional<cel::Value> const_value; |
846 | 57.4k | int64_t select_root_id = -1; |
847 | 57.4k | std::string path_candidate; |
848 | | |
849 | 67.5k | while (!namespace_stack_.empty()) { |
850 | 10.1k | const auto& select_node = namespace_stack_.front(); |
851 | | // Generate path in format "<ident>.<field 0>.<field 1>...". |
852 | 10.1k | const cel::Expr* select_expr = select_node.first; |
853 | 10.1k | path_candidate = absl::StrCat(path, ".", select_node.second); |
854 | | |
855 | | // Attempt to find a constant enum or type value which matches the |
856 | | // qualified path present in the expression. Whether the identifier |
857 | | // can be resolved to a type instance depends on whether the option to |
858 | | // 'enable_qualified_type_identifiers' is set to true. |
859 | 10.1k | const_value = resolver_.FindConstant(path_candidate, select_expr->id()); |
860 | 10.1k | if (const_value) { |
861 | 54 | resolved_select_expr_ = select_expr; |
862 | 54 | select_root_id = select_expr->id(); |
863 | 54 | path = path_candidate; |
864 | 54 | namespace_stack_.clear(); |
865 | 54 | break; |
866 | 54 | } |
867 | 10.0k | namespace_stack_.pop_front(); |
868 | 10.0k | } |
869 | | |
870 | 57.4k | if (!const_value) { |
871 | | // Attempt to resolve a simple identifier as an enum or type constant |
872 | | // value. |
873 | 57.3k | const_value = resolver_.FindConstant(path, expr.id()); |
874 | 57.3k | select_root_id = expr.id(); |
875 | 57.3k | } |
876 | | |
877 | | // TODO(issues/97): Need to add support for resolving packaged names at |
878 | | // runtime if Parse-only. For checked, checker should have reported the |
879 | | // expected interpretation. |
880 | 57.4k | if (const_value) { |
881 | | // If the path starts with a dot, strip it. |
882 | 729 | absl::string_view name = absl::StripPrefix(path, "."); |
883 | 729 | AddStep(CreateShadowableValueStep(name, std::move(const_value).value()), |
884 | 729 | select_root_id); |
885 | 729 | return; |
886 | 729 | } |
887 | | |
888 | 56.7k | if (PlanningSuppressed()) { |
889 | 0 | return; |
890 | 0 | } |
891 | 56.7k | absl::string_view ident_name = absl::StripPrefix(ident_expr.name(), "."); |
892 | 56.7k | size_t ident_index = AddOrUpdateIdentifier(ident_name); |
893 | 56.7k | AddStep(ExpressionStep::MakeIdentifierStep(ident_index, expr.id())); |
894 | 56.7k | } |
895 | | |
896 | | void PreVisitSelect(const cel::Expr& expr, |
897 | 19.4k | const cel::SelectExpr& select_expr) override { |
898 | 19.4k | if (!progress_status_.ok()) { |
899 | 600 | return; |
900 | 600 | } |
901 | 18.8k | if (!ValidateOrError( |
902 | 18.8k | !select_expr.field().empty(), |
903 | 18.8k | "invalid expression: select 'field' must not be empty")) { |
904 | 0 | return; |
905 | 0 | } |
906 | 18.8k | if (!ValidateOrError( |
907 | 18.8k | select_expr.has_operand() && |
908 | 18.8k | select_expr.operand().kind_case() != |
909 | 18.8k | cel::ExprKindCase::kUnspecifiedExpr, |
910 | 18.8k | "invalid expression: select must specify an operand")) { |
911 | 0 | return; |
912 | 0 | } |
913 | | |
914 | | // Not exactly the cleanest solution - we peek into child of |
915 | | // select_expr. |
916 | | // Chain of multiple SELECT ending with IDENT can represent namespaced |
917 | | // entity. |
918 | 18.8k | if (!select_expr.test_only() && (select_expr.operand().has_ident_expr() || |
919 | 17.3k | select_expr.operand().has_select_expr())) { |
920 | | // select expressions are pushed in reverse order: |
921 | | // google.type.Expr is pushed as: |
922 | | // - field: 'Expr' |
923 | | // - field: 'type' |
924 | | // - id: 'google' |
925 | | // |
926 | | // The search order though is as follows: |
927 | | // - id: 'google.type.Expr' |
928 | | // - id: 'google.type', field: 'Expr' |
929 | | // - id: 'google', field: 'type', field: 'Expr' |
930 | 687k | for (size_t i = 0; i < namespace_stack_.size(); i++) { |
931 | 673k | auto ns = namespace_stack_[i]; |
932 | 673k | namespace_stack_[i] = { |
933 | 673k | ns.first, absl::StrCat(select_expr.field(), ".", ns.second)}; |
934 | 673k | } |
935 | 13.7k | namespace_stack_.push_back({&expr, select_expr.field()}); |
936 | 13.7k | } else { |
937 | 5.10k | namespace_stack_.clear(); |
938 | 5.10k | } |
939 | 18.8k | } |
940 | | |
941 | | // Select node handler. |
942 | | // Invoked after child nodes are processed. |
943 | | void PostVisitSelect(const cel::Expr& expr, |
944 | 19.4k | const cel::SelectExpr& select_expr) override { |
945 | 19.4k | if (!progress_status_.ok()) { |
946 | 861 | return; |
947 | 861 | } |
948 | | |
949 | | // Check if we are "in the middle" of namespaced name. |
950 | | // This is currently enum specific. Constant expression that corresponds |
951 | | // to resolved enum value has been already created, thus preceding chain |
952 | | // of selects is no longer relevant. |
953 | 18.5k | if (resolved_select_expr_) { |
954 | 162 | if (&expr == resolved_select_expr_) { |
955 | 54 | resolved_select_expr_ = nullptr; |
956 | 54 | } |
957 | 162 | return; |
958 | 162 | } |
959 | | |
960 | 18.4k | std::string field = select_expr.field(); |
961 | 18.4k | std::optional<cel::StructType> struct_type; |
962 | 18.4k | std::optional<cel::StructTypeField> field_type; |
963 | 18.4k | if (options_.enable_typed_field_access) { |
964 | 18.4k | std::optional<cel::Type> operand_type = |
965 | 18.4k | extension_context_.GetResolvedType(select_expr.operand().id()); |
966 | 18.4k | if (operand_type.has_value() && operand_type->IsStruct()) { |
967 | 0 | struct_type = operand_type->GetStruct(); |
968 | 0 | if (struct_type.has_value()) { |
969 | 0 | auto field_lookup = |
970 | 0 | extension_context_.type_reflector().FindStructTypeFieldByName( |
971 | 0 | *struct_type, select_expr.field()); |
972 | | // Swallow error to fallback to duck typing behavior. |
973 | 0 | if (field_lookup.ok() && field_lookup->has_value()) { |
974 | 0 | field_type = *std::move(field_lookup); |
975 | 0 | } |
976 | 0 | } |
977 | 0 | } |
978 | 18.4k | } |
979 | | |
980 | 18.4k | if (field_type.has_value()) { |
981 | 0 | AddStep( |
982 | 0 | CreateTypedSelectStep(std::move(field), *struct_type, |
983 | 0 | *std::move(field_type), select_expr.test_only(), |
984 | 0 | options_.enable_empty_wrapper_null_unboxing, |
985 | 0 | enable_optional_types_), |
986 | 0 | expr.id(), /*stack_delta=*/0); |
987 | 0 | return; |
988 | 0 | } |
989 | 18.4k | AddStep(CreateSelectStep(std::move(field), select_expr.test_only(), |
990 | 18.4k | options_.enable_empty_wrapper_null_unboxing, |
991 | 18.4k | enable_optional_types_), |
992 | 18.4k | expr.id(), /*stack_delta=*/0); |
993 | 18.4k | } |
994 | | |
995 | | // Call node handler group. |
996 | | // We provide finer granularity for Call node callbacks to allow special |
997 | | // handling for short-circuiting |
998 | | // PreVisitCall is invoked before child nodes are processed. |
999 | | void PreVisitCall(const cel::Expr& expr, |
1000 | 131k | const cel::CallExpr& call_expr) override { |
1001 | 131k | if (!progress_status_.ok()) { |
1002 | 4.28k | return; |
1003 | 4.28k | } |
1004 | | |
1005 | 127k | std::unique_ptr<CondVisitor> cond_visitor; |
1006 | 127k | if (call_expr.function() == cel::builtin::kAnd) { |
1007 | 1.20k | cond_visitor = std::make_unique<LogicalCondVisitor>( |
1008 | 1.20k | this, /*is_or=*/false, options_.short_circuiting); |
1009 | 126k | } else if (call_expr.function() == cel::builtin::kOr) { |
1010 | 3.40k | cond_visitor = std::make_unique<LogicalCondVisitor>( |
1011 | 3.40k | this, /*is_or=*/true, options_.short_circuiting); |
1012 | 122k | } else if (call_expr.function() == cel::builtin::kTernary) { |
1013 | 4.12k | if (options_.short_circuiting) { |
1014 | 4.12k | cond_visitor = std::make_unique<TernaryCondVisitor>(this); |
1015 | 4.12k | } else { |
1016 | 0 | cond_visitor = std::make_unique<ExhaustiveTernaryCondVisitor>(this); |
1017 | 0 | } |
1018 | 118k | } else if (enable_optional_types_ && |
1019 | 0 | call_expr.function() == kOptionalOrFn && |
1020 | 0 | call_expr.has_target() && call_expr.args().size() == 1) { |
1021 | 0 | cond_visitor = std::make_unique<OptionalOrCondVisitor>( |
1022 | 0 | this, /*is_or_value=*/false, options_.short_circuiting); |
1023 | 118k | } else if (enable_optional_types_ && |
1024 | 0 | call_expr.function() == kOptionalOrValueFn && |
1025 | 0 | call_expr.has_target() && call_expr.args().size() == 1) { |
1026 | 0 | cond_visitor = std::make_unique<OptionalOrCondVisitor>( |
1027 | 0 | this, /*is_or_value=*/true, options_.short_circuiting); |
1028 | 118k | } else if (IsBlock(&call_expr)) { |
1029 | | // cel.@block |
1030 | 0 | if (block_.has_value()) { |
1031 | | // There can only be one for now. |
1032 | 0 | SetProgressStatusIfError( |
1033 | 0 | absl::InvalidArgumentError("multiple cel.@block are not allowed")); |
1034 | 0 | return; |
1035 | 0 | } |
1036 | 0 | block_ = BlockInfo(); |
1037 | 0 | BlockInfo& block = *block_; |
1038 | 0 | block.in = true; |
1039 | 0 | if (call_expr.args().empty()) { |
1040 | 0 | SetProgressStatusIfError(absl::InvalidArgumentError( |
1041 | 0 | "malformed cel.@block: missing list of bound expressions")); |
1042 | 0 | return; |
1043 | 0 | } |
1044 | 0 | if (call_expr.args().size() != 2) { |
1045 | 0 | SetProgressStatusIfError(absl::InvalidArgumentError( |
1046 | 0 | "malformed cel.@block: missing bound expression")); |
1047 | 0 | return; |
1048 | 0 | } |
1049 | 0 | if (!call_expr.args()[0].has_list_expr()) { |
1050 | 0 | SetProgressStatusIfError( |
1051 | 0 | absl::InvalidArgumentError("malformed cel.@block: first argument " |
1052 | 0 | "is not a list of bound expressions")); |
1053 | 0 | return; |
1054 | 0 | } |
1055 | 0 | const auto& list_expr = call_expr.args().front().list_expr(); |
1056 | 0 | block.size = list_expr.elements().size(); |
1057 | |
|
1058 | 0 | block.bindings_set.reserve(block.size); |
1059 | 0 | for (const auto& list_expr_element : list_expr.elements()) { |
1060 | 0 | if (list_expr_element.optional()) { |
1061 | 0 | SetProgressStatusIfError( |
1062 | 0 | absl::InvalidArgumentError("malformed cel.@block: list of bound " |
1063 | 0 | "expressions contains an optional")); |
1064 | 0 | return; |
1065 | 0 | } |
1066 | 0 | block.bindings_set.insert(&list_expr_element.expr()); |
1067 | 0 | } |
1068 | 0 | block.index = index_manager().ReserveSlots(block.size); |
1069 | 0 | block.slot_count = block.size; |
1070 | 0 | block.expr = &expr; |
1071 | 0 | block.bindings = &call_expr.args()[0]; |
1072 | 0 | block.bound = &call_expr.args()[1]; |
1073 | 0 | block.subexpressions.resize(block.size, -1); |
1074 | 118k | } else { |
1075 | 118k | return; |
1076 | 118k | } |
1077 | | |
1078 | 8.73k | if (cond_visitor) { |
1079 | 8.73k | cond_visitor->PreVisit(&expr); |
1080 | 8.73k | cond_visitor_stack_.push({&expr, std::move(cond_visitor)}); |
1081 | 8.73k | } |
1082 | 8.73k | } |
1083 | | |
1084 | | // Invoked after all child nodes are processed. |
1085 | | void PostVisitCall(const cel::Expr& expr, |
1086 | 131k | const cel::CallExpr& call_expr) override { |
1087 | 131k | if (!progress_status_.ok()) { |
1088 | 6.42k | return; |
1089 | 6.42k | } |
1090 | | |
1091 | 125k | auto cond_visitor = FindCondVisitor(&expr); |
1092 | 125k | if (cond_visitor) { |
1093 | 8.55k | cond_visitor->PostVisit(&expr); |
1094 | 8.55k | cond_visitor_stack_.pop(); |
1095 | 8.55k | return; |
1096 | 8.55k | } |
1097 | | |
1098 | | // Check if the call is intercepted by a custom handler. |
1099 | 116k | if (auto handler = call_handlers_.find(call_expr.function()); |
1100 | 116k | handler != call_handlers_.end()) { |
1101 | 39.7k | CallHandlerResult result = handler->second(expr, call_expr); |
1102 | 39.7k | if (result == CallHandlerResult::kIntercepted) { |
1103 | 15.9k | return; |
1104 | 15.9k | } // otherwise, apply default function handling. |
1105 | 39.7k | } |
1106 | | |
1107 | 100k | AddResolvedFunctionStep(&call_expr, &expr, call_expr.function()); |
1108 | 100k | } |
1109 | | |
1110 | | void PreVisitComprehension( |
1111 | | const cel::Expr& expr, |
1112 | 20.1k | const cel::ComprehensionExpr& comprehension) override { |
1113 | 20.1k | if (!progress_status_.ok()) { |
1114 | 393 | return; |
1115 | 393 | } |
1116 | 19.7k | if (!ValidateOrError(options_.enable_comprehension, |
1117 | 19.7k | "Comprehension support is disabled")) { |
1118 | 0 | return; |
1119 | 0 | } |
1120 | 19.7k | const auto& accu_var = comprehension.accu_var(); |
1121 | 19.7k | const auto& iter_var = comprehension.iter_var(); |
1122 | 19.7k | const auto& iter_var2 = comprehension.iter_var2(); |
1123 | 19.7k | ValidateOrError(!accu_var.empty(), |
1124 | 19.7k | "Invalid comprehension: 'accu_var' must not be empty"); |
1125 | 19.7k | ValidateOrError(!iter_var.empty(), |
1126 | 19.7k | "Invalid comprehension: 'iter_var' must not be empty"); |
1127 | 19.7k | ValidateOrError( |
1128 | 19.7k | accu_var != iter_var, |
1129 | 19.7k | "Invalid comprehension: 'accu_var' must not be the same as 'iter_var'"); |
1130 | 19.7k | ValidateOrError(accu_var != iter_var2, |
1131 | 19.7k | "Invalid comprehension: 'accu_var' must not be the same as " |
1132 | 19.7k | "'iter_var2'"); |
1133 | 19.7k | ValidateOrError(iter_var2 != iter_var, |
1134 | 19.7k | "Invalid comprehension: 'iter_var2' must not be the same " |
1135 | 19.7k | "as 'iter_var'"); |
1136 | 19.7k | ValidateOrError(comprehension.has_accu_init(), |
1137 | 19.7k | "Invalid comprehension: 'accu_init' must be set"); |
1138 | 19.7k | ValidateOrError(comprehension.has_loop_condition(), |
1139 | 19.7k | "Invalid comprehension: 'loop_condition' must be set"); |
1140 | 19.7k | ValidateOrError(comprehension.has_loop_step(), |
1141 | 19.7k | "Invalid comprehension: 'loop_step' must be set"); |
1142 | 19.7k | ValidateOrError(comprehension.has_result(), |
1143 | 19.7k | "Invalid comprehension: 'result' must be set"); |
1144 | | |
1145 | 19.7k | size_t iter_slot, iter2_slot, accu_slot, slot_count; |
1146 | 19.7k | bool is_bind = IsBind(&comprehension); |
1147 | | |
1148 | 19.7k | if (is_bind) { |
1149 | 0 | accu_slot = iter_slot = iter2_slot = index_manager_.ReserveSlots(1); |
1150 | 0 | slot_count = 1; |
1151 | 19.7k | } else if (comprehension.iter_var2().empty()) { |
1152 | 19.7k | iter_slot = iter2_slot = index_manager_.ReserveSlots(2); |
1153 | 19.7k | accu_slot = iter_slot + 1; |
1154 | 19.7k | slot_count = 2; |
1155 | 19.7k | } else { |
1156 | 0 | iter_slot = index_manager_.ReserveSlots(3); |
1157 | 0 | iter2_slot = iter_slot + 1; |
1158 | 0 | accu_slot = iter2_slot + 1; |
1159 | 0 | slot_count = 3; |
1160 | 0 | } |
1161 | | |
1162 | 19.7k | if (block_.has_value()) { |
1163 | 0 | BlockInfo& block = *block_; |
1164 | 0 | if (block.in) { |
1165 | 0 | block.slot_count += slot_count; |
1166 | 0 | slot_count = 0; |
1167 | 0 | } |
1168 | 0 | } |
1169 | | |
1170 | | // If this is in the scope of an optimized bind accu-init, account the slots |
1171 | | // to the outermost bind-init scope. |
1172 | | // |
1173 | | // The init expression is effectively inlined at the first usage in the |
1174 | | // critical path (which is unknown at plan time), so the used slots need to |
1175 | | // be dedicated for the entire scope of that bind. |
1176 | 19.7k | bool in_bind_init = false; |
1177 | 156k | for (ComprehensionStackRecord& record : comprehension_stack_) { |
1178 | 156k | if (record.in_accu_init && record.is_optimizable_bind) { |
1179 | 0 | record.slot_count += slot_count; |
1180 | 0 | slot_count = 0; |
1181 | 0 | in_bind_init = true; |
1182 | 0 | break; |
1183 | 0 | } |
1184 | | // If no bind init subexpression, account normally. |
1185 | 156k | } |
1186 | | |
1187 | | // Iterator frames are releasable if not in a bind (no iterator push), and |
1188 | | // not in a lazy subexpression (which may evaluate in different implicit |
1189 | | // scopes). |
1190 | 19.7k | const bool is_stack_releasable = |
1191 | 19.7k | !is_bind && !in_bind_init && (!block_.has_value() || !block_->in); |
1192 | | |
1193 | 19.7k | if (is_stack_releasable) { |
1194 | 19.7k | index_manager_.ReserveIterStack(); |
1195 | 19.7k | } else if (!is_bind) { |
1196 | 0 | index_manager_.AddLazyIterStack(); |
1197 | 0 | } |
1198 | | |
1199 | 19.7k | comprehension_stack_.push_back( |
1200 | 19.7k | {&expr, &comprehension, iter_slot, iter2_slot, accu_slot, slot_count, |
1201 | 19.7k | /*subexpression=*/-1, |
1202 | | /*.is_optimizable_list_append=*/ |
1203 | 19.7k | IsOptimizableListAppend(&comprehension, |
1204 | 19.7k | options_.enable_comprehension_list_append, |
1205 | 19.7k | options_.short_circuiting), |
1206 | | /*.is_optimizable_map_insert=*/ |
1207 | 19.7k | IsOptimizableMapInsert(&comprehension, |
1208 | 19.7k | options_.enable_comprehension_mutable_map, |
1209 | 19.7k | options_.short_circuiting), |
1210 | 19.7k | /*.is_optimizable_bind=*/is_bind, |
1211 | 19.7k | /*.is_stack_releasable=*/is_stack_releasable, |
1212 | 19.7k | /*.iter_var_in_scope=*/false, |
1213 | 19.7k | /*.iter_var2_in_scope=*/false, |
1214 | 19.7k | /*.accu_var_in_scope=*/false, |
1215 | 19.7k | /*.in_accu_init=*/false, |
1216 | 19.7k | std::make_unique<ComprehensionVisitor>(this, is_bind, iter_slot, |
1217 | 19.7k | iter2_slot, accu_slot)}); |
1218 | 19.7k | comprehension_stack_.back().visitor->PreVisit(&expr); |
1219 | 19.7k | } |
1220 | | |
1221 | | // Invoked after all child nodes are processed. |
1222 | | void PostVisitComprehension( |
1223 | | const cel::Expr& expr, |
1224 | 20.1k | const cel::ComprehensionExpr& comprehension_expr) override { |
1225 | 20.1k | if (!progress_status_.ok()) { |
1226 | 2.13k | return; |
1227 | 2.13k | } |
1228 | | |
1229 | 18.0k | ComprehensionStackRecord& record = comprehension_stack_.back(); |
1230 | 18.0k | if (comprehension_stack_.empty() || |
1231 | 18.0k | record.comprehension != &comprehension_expr) { |
1232 | 0 | return; |
1233 | 0 | } |
1234 | | |
1235 | 18.0k | record.visitor->PostVisit(&expr); |
1236 | | |
1237 | 18.0k | index_manager_.ReleaseSlots(record.slot_count); |
1238 | 18.0k | if (record.is_stack_releasable) { |
1239 | 18.0k | ABSL_DCHECK(!record.is_optimizable_bind); |
1240 | 18.0k | index_manager_.ReleaseIterStack(); |
1241 | 18.0k | } |
1242 | 18.0k | comprehension_stack_.pop_back(); |
1243 | 18.0k | } |
1244 | | |
1245 | | void PreVisitComprehensionSubexpression( |
1246 | | const cel::Expr& expr, const cel::ComprehensionExpr& compr, |
1247 | 100k | cel::ComprehensionArg comprehension_arg) override { |
1248 | 100k | if (!progress_status_.ok()) { |
1249 | 8.76k | return; |
1250 | 8.76k | } |
1251 | | |
1252 | 91.9k | if (comprehension_stack_.empty() || |
1253 | 91.9k | comprehension_stack_.back().comprehension != &compr) { |
1254 | 0 | return; |
1255 | 0 | } |
1256 | | |
1257 | 91.9k | ComprehensionStackRecord& record = comprehension_stack_.back(); |
1258 | | |
1259 | 91.9k | switch (comprehension_arg) { |
1260 | 19.7k | case cel::ITER_RANGE: { |
1261 | 19.7k | record.in_accu_init = false; |
1262 | 19.7k | record.iter_var_in_scope = false; |
1263 | 19.7k | record.iter_var2_in_scope = false; |
1264 | 19.7k | record.accu_var_in_scope = false; |
1265 | 19.7k | break; |
1266 | 0 | } |
1267 | 18.0k | case cel::ACCU_INIT: { |
1268 | 18.0k | record.in_accu_init = true; |
1269 | 18.0k | record.iter_var_in_scope = false; |
1270 | 18.0k | record.iter_var2_in_scope = false; |
1271 | 18.0k | record.accu_var_in_scope = false; |
1272 | 18.0k | break; |
1273 | 0 | } |
1274 | 18.0k | case cel::LOOP_CONDITION: { |
1275 | 18.0k | record.in_accu_init = false; |
1276 | 18.0k | record.iter_var_in_scope = true; |
1277 | 18.0k | record.iter_var2_in_scope = true; |
1278 | 18.0k | record.accu_var_in_scope = true; |
1279 | 18.0k | break; |
1280 | 0 | } |
1281 | 18.0k | case cel::LOOP_STEP: { |
1282 | 18.0k | record.in_accu_init = false; |
1283 | 18.0k | record.iter_var_in_scope = true; |
1284 | 18.0k | record.iter_var2_in_scope = true; |
1285 | 18.0k | record.accu_var_in_scope = true; |
1286 | 18.0k | break; |
1287 | 0 | } |
1288 | 18.0k | case cel::RESULT: { |
1289 | 18.0k | record.in_accu_init = false; |
1290 | 18.0k | record.iter_var_in_scope = false; |
1291 | 18.0k | record.iter_var2_in_scope = false; |
1292 | 18.0k | record.accu_var_in_scope = true; |
1293 | 18.0k | break; |
1294 | 0 | } |
1295 | 91.9k | } |
1296 | 91.9k | } |
1297 | | |
1298 | | void PostVisitComprehensionSubexpression( |
1299 | | const cel::Expr& expr, const cel::ComprehensionExpr& compr, |
1300 | 100k | cel::ComprehensionArg comprehension_arg) override { |
1301 | 100k | if (!progress_status_.ok()) { |
1302 | 10.5k | return; |
1303 | 10.5k | } |
1304 | | |
1305 | 90.2k | if (comprehension_stack_.empty() || |
1306 | 90.2k | comprehension_stack_.back().comprehension != &compr) { |
1307 | 0 | return; |
1308 | 0 | } |
1309 | | |
1310 | 90.2k | SetProgressStatusIfError(comprehension_stack_.back().visitor->PostVisitArg( |
1311 | 90.2k | comprehension_arg, comprehension_stack_.back().expr)); |
1312 | 90.2k | } |
1313 | | |
1314 | | // Invoked after each argument node processed. |
1315 | 251k | void PostVisitArg(const cel::Expr& expr, int arg_num) override { |
1316 | 251k | if (!progress_status_.ok()) { |
1317 | 12.1k | return; |
1318 | 12.1k | } |
1319 | 239k | auto cond_visitor = FindCondVisitor(&expr); |
1320 | 239k | if (cond_visitor) { |
1321 | 21.3k | cond_visitor->PostVisitArg(arg_num, &expr); |
1322 | 21.3k | } |
1323 | 239k | } |
1324 | | |
1325 | 804 | void PostVisitTarget(const cel::Expr& expr) override { |
1326 | 804 | if (!progress_status_.ok()) { |
1327 | 501 | return; |
1328 | 501 | } |
1329 | 303 | auto cond_visitor = FindCondVisitor(&expr); |
1330 | 303 | if (cond_visitor) { |
1331 | 0 | cond_visitor->PostVisitTarget(&expr); |
1332 | 0 | } |
1333 | 303 | } |
1334 | | |
1335 | | // CreateList node handler. |
1336 | | // Invoked after child nodes are processed. |
1337 | | void PostVisitList(const cel::Expr& expr, |
1338 | 63.0k | const cel::ListExpr& list_expr) override { |
1339 | 63.0k | if (!progress_status_.ok()) { |
1340 | 4.28k | return; |
1341 | 4.28k | } |
1342 | | |
1343 | 58.7k | if (block_.has_value()) { |
1344 | 0 | BlockInfo& block = *block_; |
1345 | 0 | if (block.bindings == &expr) { |
1346 | | // Do nothing, this is the cel.@block bindings list. |
1347 | 0 | return; |
1348 | 0 | } |
1349 | 0 | } |
1350 | | |
1351 | 58.7k | if (!comprehension_stack_.empty()) { |
1352 | 54.7k | const ComprehensionStackRecord& comprehension = |
1353 | 54.7k | comprehension_stack_.back(); |
1354 | 54.7k | if (comprehension.is_optimizable_list_append) { |
1355 | 0 | if (&(comprehension.comprehension->accu_init()) == &expr) { |
1356 | 0 | AddStep(ExpressionStep::MakeNewMutableListStep(expr.id())); |
1357 | 0 | return; |
1358 | 0 | } |
1359 | 0 | if (GetOptimizableListAppendOperand(comprehension.comprehension) == |
1360 | 0 | &expr) { |
1361 | | // Avoid wrapping the appended element in a create list step. |
1362 | 0 | return; |
1363 | 0 | } |
1364 | 0 | } |
1365 | 54.7k | } |
1366 | 58.7k | absl::flat_hash_set<size_t> optional_indices = |
1367 | 58.7k | MakeOptionalIndicesSet(list_expr); |
1368 | 58.7k | for (size_t index : optional_indices) { |
1369 | 0 | if (!ValidateOrError(index < list_expr.elements().size(), |
1370 | 0 | "Optional index out of range: ", index, |
1371 | 0 | ", list size: ", list_expr.elements().size())) { |
1372 | 0 | return; |
1373 | 0 | } |
1374 | 0 | } |
1375 | 58.7k | AddStep(CreateCreateListStep(list_expr.elements().size(), |
1376 | 58.7k | std::move(optional_indices), expr.id())); |
1377 | 58.7k | } |
1378 | | |
1379 | | // CreateStruct node handler. |
1380 | | // Invoked after child nodes are processed. |
1381 | | void PostVisitStruct(const cel::Expr& expr, |
1382 | 3.78k | const cel::StructExpr& struct_expr) override { |
1383 | 3.78k | if (!progress_status_.ok()) { |
1384 | 428 | return; |
1385 | 428 | } |
1386 | | |
1387 | 3.35k | auto status_or_resolved_fields = |
1388 | 3.35k | ResolveCreateStructFields(struct_expr, expr.id()); |
1389 | 3.35k | if (!status_or_resolved_fields.ok()) { |
1390 | 302 | SetProgressStatusIfError(status_or_resolved_fields.status()); |
1391 | 302 | return; |
1392 | 302 | } |
1393 | 3.05k | std::string resolved_name = |
1394 | 3.05k | std::move(status_or_resolved_fields.value().first); |
1395 | 3.05k | std::vector<std::string> fields = |
1396 | 3.05k | std::move(status_or_resolved_fields.value().second); |
1397 | | |
1398 | 3.05k | size_t num_fields = fields.size(); |
1399 | 3.05k | int64_t stack_delta = |
1400 | 3.05k | num_fields <= static_cast<size_t>(std::numeric_limits<int64_t>::max()) |
1401 | 3.05k | ? 1 - static_cast<int64_t>(num_fields) |
1402 | 3.05k | : std::numeric_limits<int16_t>::max(); |
1403 | 3.05k | AddStep(CreateCreateStructStep(std::move(resolved_name), std::move(fields), |
1404 | 3.05k | MakeOptionalIndicesSet(struct_expr)), |
1405 | 3.05k | expr.id(), stack_delta); |
1406 | 3.05k | } |
1407 | | |
1408 | | void PostVisitMap(const cel::Expr& expr, |
1409 | 4.53k | const cel::MapExpr& map_expr) override { |
1410 | 4.87k | for (const auto& entry : map_expr.entries()) { |
1411 | 4.87k | ValidateOrError(entry.has_key(), "Map entry missing key"); |
1412 | 4.87k | ValidateOrError(entry.has_value(), "Map entry missing value"); |
1413 | 4.87k | } |
1414 | | |
1415 | 4.53k | if (!comprehension_stack_.empty()) { |
1416 | 2.70k | const ComprehensionStackRecord& comprehension = |
1417 | 2.70k | comprehension_stack_.back(); |
1418 | 2.70k | if (comprehension.is_optimizable_map_insert) { |
1419 | 0 | if (&(comprehension.comprehension->accu_init()) == &expr) { |
1420 | 0 | AddStep(CreateMutableMapStep(), expr.id()); |
1421 | 0 | return; |
1422 | 0 | } |
1423 | 0 | } |
1424 | 2.70k | } |
1425 | | |
1426 | 4.53k | size_t num_entries = map_expr.entries().size(); |
1427 | 4.53k | int64_t stack_delta = |
1428 | 4.53k | num_entries <= |
1429 | 4.53k | static_cast<size_t>(std::numeric_limits<int64_t>::max() / 2) |
1430 | 4.53k | ? 1 - 2 * static_cast<int64_t>(num_entries) |
1431 | 4.53k | : std::numeric_limits<int16_t>::max(); |
1432 | 4.53k | AddStep(CreateCreateStructStepForMap(num_entries, |
1433 | 4.53k | MakeOptionalIndicesSet(map_expr)), |
1434 | 4.53k | expr.id(), stack_delta); |
1435 | 4.53k | } |
1436 | | |
1437 | 20.2k | absl::Status progress_status() const { return progress_status_; } |
1438 | | |
1439 | | // Mark a branch as suppressed. The visitor will continue as normal, but |
1440 | | // any emitted program steps are ignored. |
1441 | | // |
1442 | | // Only applies to branches that have not yet been visited (pre-order). |
1443 | 0 | void SuppressBranch(const cel::Expr* expr) { |
1444 | 0 | suppressed_branches_.insert(expr); |
1445 | 0 | } |
1446 | | |
1447 | | void AddResolvedFunctionStep(const cel::CallExpr* call_expr, |
1448 | | const cel::Expr* expr, |
1449 | 100k | absl::string_view function) { |
1450 | | // Establish the search criteria for a given function. |
1451 | 100k | bool receiver_style = call_expr->has_target(); |
1452 | 100k | size_t num_args = call_expr->args().size() + (receiver_style ? 1 : 0); |
1453 | | |
1454 | | // First, search for lazily defined function overloads. |
1455 | | // Lazy functions shadow eager functions with the same signature. |
1456 | 100k | auto lazy_overloads = resolver_.FindLazyOverloads( |
1457 | 100k | function, call_expr->has_target(), num_args, expr->id()); |
1458 | 100k | if (!lazy_overloads.empty()) { |
1459 | 0 | AddStep(ExpressionStep::MakeLazyFunctionStep( |
1460 | 0 | CreateLazyFunctionStep(*call_expr, expr->id(), |
1461 | 0 | std::move(lazy_overloads)), |
1462 | 0 | expr->id())); |
1463 | 0 | return; |
1464 | 0 | } |
1465 | | |
1466 | | // Second, search for eagerly defined function overloads. |
1467 | 100k | auto overloads = |
1468 | 100k | resolver_.FindOverloads(function, receiver_style, num_args, expr->id()); |
1469 | 100k | if (overloads.empty()) { |
1470 | | // Create a warning that the overload could not be found. Depending on the |
1471 | | // builder_warnings configuration, this could result in termination of the |
1472 | | // CelExpression creation or an inspectable warning for use within runtime |
1473 | | // logging. |
1474 | 299 | auto status = issue_collector_.AddIssue(RuntimeIssue::CreateWarning( |
1475 | 299 | absl::InvalidArgumentError( |
1476 | 299 | "No overloads provided for FunctionStep creation"), |
1477 | 299 | RuntimeIssue::ErrorCode::kNoMatchingOverload)); |
1478 | 299 | if (!status.ok()) { |
1479 | 299 | SetProgressStatusIfError(status); |
1480 | 299 | return; |
1481 | 299 | } |
1482 | 299 | } |
1483 | | |
1484 | 100k | AddStep(ExpressionStep::MakeEagerFunctionStep( |
1485 | 100k | CreateFunctionStep(*call_expr, expr->id(), std::move(overloads)), |
1486 | 100k | expr->id())); |
1487 | 100k | } |
1488 | | |
1489 | | // Add a step to the program, taking ownership. If successful, returns the |
1490 | | // pointer to the step. Otherwise, returns nullptr. |
1491 | | // |
1492 | | // Note: the pointer is only guaranteed to stay valid until the parent |
1493 | | // subexpression is finalized. Optimizers may modify the program plan which |
1494 | | // may free the step at that point. |
1495 | | template <typename T> |
1496 | | std::enable_if_t<std::is_base_of_v<ExpressionStepLogic, T>, T*> AddStep( |
1497 | 29.8k | std::unique_ptr<T> step, int64_t expr_id = -1, int64_t stack_delta = 1) { |
1498 | 29.8k | if (progress_status_.ok() && !PlanningSuppressed()) { |
1499 | 29.5k | T* ptr = step.get(); |
1500 | 29.5k | program_builder_.AddStep(ExpressionStep::MakeGenericStep( |
1501 | 29.5k | std::move(step), expr_id, stack_delta)); |
1502 | 29.5k | return ptr; |
1503 | 29.5k | } |
1504 | 300 | return nullptr; |
1505 | 29.8k | } flat_expr_builder.cc:_ZN6google3api4expr7runtime12_GLOBAL__N_115FlatExprVisitor7AddStepINS2_19ExpressionStepLogicEEENSt3__19enable_ifIXsr3stdE12is_base_of_vIS6_T_EEPS9_E4typeENS7_10unique_ptrIS9_NS7_14default_deleteIS9_EEEEll Line | Count | Source | 1497 | 29.8k | std::unique_ptr<T> step, int64_t expr_id = -1, int64_t stack_delta = 1) { | 1498 | 29.8k | if (progress_status_.ok() && !PlanningSuppressed()) { | 1499 | 29.5k | T* ptr = step.get(); | 1500 | 29.5k | program_builder_.AddStep(ExpressionStep::MakeGenericStep( | 1501 | 29.5k | std::move(step), expr_id, stack_delta)); | 1502 | 29.5k | return ptr; | 1503 | 29.5k | } | 1504 | 300 | return nullptr; | 1505 | 29.8k | } |
Unexecuted instantiation: flat_expr_builder.cc:_ZN6google3api4expr7runtime12_GLOBAL__N_115FlatExprVisitor7AddStepINS2_24OptionalHasValueJumpStepEEENSt3__19enable_ifIXsr3stdE12is_base_of_vINS2_19ExpressionStepLogicET_EEPSA_E4typeENS7_10unique_ptrISA_NS7_14default_deleteISA_EEEEll |
1506 | | |
1507 | | template <typename T> |
1508 | | std::enable_if_t<std::is_base_of_v<ExpressionStepLogic, T>, T*> AddStep( |
1509 | | absl::StatusOr<std::unique_ptr<T>> step, int64_t expr_id = -1, |
1510 | 26.8k | int64_t stack_delta = 1) { |
1511 | 26.8k | if (step.ok()) { |
1512 | 26.8k | return AddStep(*std::move(step), expr_id, stack_delta); |
1513 | 26.8k | } else { |
1514 | 0 | SetProgressStatusIfError(step.status()); |
1515 | 0 | } |
1516 | 0 | return nullptr; |
1517 | 26.8k | } |
1518 | | |
1519 | 548k | ExpressionStep* AddStep(ExpressionStep step) { |
1520 | 548k | if (progress_status_.ok() && !PlanningSuppressed()) { |
1521 | 548k | return program_builder_.AddStep(std::move(step)); |
1522 | 548k | } |
1523 | 0 | return nullptr; |
1524 | 548k | } |
1525 | | |
1526 | 90.8k | void SetProgressStatusIfError(const absl::Status& status) { |
1527 | 90.8k | if (progress_status_.ok() && !status.ok()) { |
1528 | 610 | progress_status_ = status; |
1529 | 610 | } |
1530 | 90.8k | } |
1531 | | |
1532 | | // Index of the next step to be inserted, in terms of the current |
1533 | | // subexpression |
1534 | 191k | ProgramStepIndex GetCurrentIndex() const { |
1535 | | // Nonnull while active -- nullptr indicates logic error in the builder. |
1536 | 191k | ABSL_DCHECK(program_builder_.current() != nullptr); |
1537 | 191k | return {static_cast<int>(program_builder_.current()->elements().size()), |
1538 | 191k | program_builder_.current()}; |
1539 | 191k | } |
1540 | | |
1541 | 364k | CondVisitor* FindCondVisitor(const cel::Expr* expr) const { |
1542 | 364k | if (cond_visitor_stack_.empty()) { |
1543 | 264k | return nullptr; |
1544 | 264k | } |
1545 | | |
1546 | 100k | const auto& latest = cond_visitor_stack_.top(); |
1547 | | |
1548 | 100k | return (latest.first == expr) ? latest.second.get() : nullptr; |
1549 | 364k | } |
1550 | | |
1551 | 0 | IndexManager& index_manager() { return index_manager_; } |
1552 | | |
1553 | 18.9k | size_t slot_count() const { return index_manager_.max_slot_count(); } |
1554 | | |
1555 | 18.9k | size_t iter_stack_count() const { |
1556 | 18.9k | return index_manager_.IterStackRequirement(); |
1557 | 18.9k | } |
1558 | | |
1559 | 18.9k | IdentifierTable BuildIdentifierTable(size_t& total_slot_count) && { |
1560 | 18.9k | IdentifierTable table; |
1561 | 18.9k | table.reserve(identifiers_.size()); |
1562 | 22.9k | for (std::string& name : identifiers_) { |
1563 | 22.9k | table.push_back(Identifier{std::move(name), total_slot_count++}); |
1564 | 22.9k | } |
1565 | 18.9k | return table; |
1566 | 18.9k | } |
1567 | | |
1568 | 0 | void AddOptimizer(std::unique_ptr<ProgramOptimizer> optimizer) { |
1569 | 0 | program_optimizers_.push_back(std::move(optimizer)); |
1570 | 0 | } |
1571 | | |
1572 | | // Tests the boolean predicate, and if false produces an InvalidArgumentError |
1573 | | // which concatenates the error_message and any optional message_parts as the |
1574 | | // error status message. |
1575 | | template <typename... MP> |
1576 | | bool ValidateOrError(bool valid_expression, absl::string_view error_message, |
1577 | 908k | MP... message_parts) { |
1578 | 908k | if (valid_expression) { |
1579 | 908k | return true; |
1580 | 908k | } |
1581 | 9 | SetProgressStatusIfError(absl::InvalidArgumentError( |
1582 | 9 | absl::StrCat(error_message, message_parts...))); |
1583 | 9 | return false; |
1584 | 908k | } flat_expr_builder.cc:bool google::api::expr::runtime::(anonymous namespace)::FlatExprVisitor::ValidateOrError<>(bool, std::__1::basic_string_view<char, std::__1::char_traits<char> >) Line | Count | Source | 1577 | 908k | MP... message_parts) { | 1578 | 908k | if (valid_expression) { | 1579 | 908k | return true; | 1580 | 908k | } | 1581 | 9 | SetProgressStatusIfError(absl::InvalidArgumentError( | 1582 | 9 | absl::StrCat(error_message, message_parts...))); | 1583 | 9 | return false; | 1584 | 908k | } |
Unexecuted instantiation: flat_expr_builder.cc:bool google::api::expr::runtime::(anonymous namespace)::FlatExprVisitor::ValidateOrError<unsigned long, char const*, unsigned long>(bool, std::__1::basic_string_view<char, std::__1::char_traits<char> >, unsigned long, char const*, unsigned long) |
1585 | | |
1586 | | private: |
1587 | | struct ComprehensionStackRecord { |
1588 | | const cel::Expr* expr; |
1589 | | const cel::ComprehensionExpr* comprehension; |
1590 | | size_t iter_slot; |
1591 | | size_t iter2_slot; |
1592 | | size_t accu_slot; |
1593 | | size_t slot_count; |
1594 | | // -1 indicates this shouldn't be used. |
1595 | | int subexpression; |
1596 | | bool is_optimizable_list_append; |
1597 | | bool is_optimizable_map_insert; |
1598 | | bool is_optimizable_bind; |
1599 | | bool is_stack_releasable; |
1600 | | bool iter_var_in_scope; |
1601 | | bool iter_var2_in_scope; |
1602 | | bool accu_var_in_scope; |
1603 | | bool in_accu_init; |
1604 | | std::unique_ptr<ComprehensionVisitor> visitor; |
1605 | | }; |
1606 | | |
1607 | | struct BlockInfo { |
1608 | | // True if we are currently visiting the `cel.@block` node or any of its |
1609 | | // children. |
1610 | | bool in = false; |
1611 | | // Pointer to the `cel.@block` node. |
1612 | | const cel::Expr* expr = nullptr; |
1613 | | // Pointer to the `cel.@block` bindings, that is the first argument to the |
1614 | | // function. |
1615 | | const cel::Expr* bindings = nullptr; |
1616 | | // Set of pointers to the elements of `bindings` above. |
1617 | | absl::flat_hash_set<const cel::Expr*> bindings_set; |
1618 | | // Pointer to the `cel.@block` bound expression, that is the second argument |
1619 | | // to the function. |
1620 | | const cel::Expr* bound = nullptr; |
1621 | | // The number of entries in the `cel.@block`. |
1622 | | size_t size = 0; |
1623 | | // Starting slot index for `cel.@block`. We occupy he slot indices `index` |
1624 | | // through `index + size + (var_size * 2)`. |
1625 | | size_t index = 0; |
1626 | | // The total number of slots needed for evaluating the bound expressions. |
1627 | | size_t slot_count = 0; |
1628 | | // The current slot index we are processing, any index references must be |
1629 | | // less than this to be valid. |
1630 | | size_t current_index = 0; |
1631 | | // Pointer to the current `cel.@block` being processed, that is one of the |
1632 | | // elements within the first argument. |
1633 | | const cel::Expr* current_binding = nullptr; |
1634 | | // Mapping between block indices and their subexpressions, fixed size with |
1635 | | // exactly `size` elements. Unprocessed indices are set to `-1`. |
1636 | | std::vector<int> subexpressions; |
1637 | | }; |
1638 | | |
1639 | 634k | bool PlanningSuppressed() const { |
1640 | 634k | return resume_from_suppressed_branch_ != nullptr; |
1641 | 634k | } |
1642 | | |
1643 | | absl::Status MaybeExtractSubexpression(const cel::Expr* expr, |
1644 | 0 | ComprehensionStackRecord& record) { |
1645 | 0 | if (!record.is_optimizable_bind) { |
1646 | 0 | return absl::OkStatus(); |
1647 | 0 | } |
1648 | | |
1649 | 0 | int index = program_builder_.ExtractSubexpression(expr); |
1650 | 0 | if (index == -1) { |
1651 | 0 | return absl::InternalError("Failed to extract subexpression"); |
1652 | 0 | } |
1653 | | |
1654 | 0 | record.subexpression = index; |
1655 | |
|
1656 | 0 | record.visitor->MarkAccuInitExtracted(); |
1657 | |
|
1658 | 0 | return absl::OkStatus(); |
1659 | 0 | } |
1660 | | |
1661 | | // Resolve the name of the message type being created and the names of set |
1662 | | // fields. |
1663 | | absl::StatusOr<std::pair<std::string, std::vector<std::string>>> |
1664 | | ResolveCreateStructFields(const cel::StructExpr& create_struct_expr, |
1665 | 3.35k | int64_t expr_id) { |
1666 | 3.35k | absl::string_view ast_name = create_struct_expr.name(); |
1667 | | |
1668 | 3.35k | std::optional<std::pair<std::string, cel::Type>> type; |
1669 | 3.35k | CEL_ASSIGN_OR_RETURN(type, resolver_.FindType(ast_name, expr_id)); |
1670 | | |
1671 | 3.35k | if (!type.has_value()) { |
1672 | 256 | return absl::InvalidArgumentError(absl::StrCat( |
1673 | 256 | "Invalid struct creation: missing type info for '", ast_name, "'")); |
1674 | 256 | } |
1675 | | |
1676 | 3.10k | std::string resolved_name = std::move(type).value().first; |
1677 | | |
1678 | 3.10k | std::vector<std::string> fields; |
1679 | 3.10k | fields.reserve(create_struct_expr.fields().size()); |
1680 | 3.10k | for (const auto& entry : create_struct_expr.fields()) { |
1681 | 1.57k | if (entry.name().empty()) { |
1682 | 0 | return absl::InvalidArgumentError("Struct field missing name"); |
1683 | 0 | } |
1684 | 1.57k | if (!entry.has_value()) { |
1685 | 0 | return absl::InvalidArgumentError("Struct field missing value"); |
1686 | 0 | } |
1687 | 3.14k | CEL_ASSIGN_OR_RETURN(auto field, type_provider_.FindStructTypeFieldByName( |
1688 | 3.14k | resolved_name, entry.name())); |
1689 | 3.14k | if (!field.has_value()) { |
1690 | 46 | return absl::InvalidArgumentError( |
1691 | 46 | absl::StrCat("Invalid message creation: field '", entry.name(), |
1692 | 46 | "' not found in '", resolved_name, "'")); |
1693 | 46 | } |
1694 | 1.52k | fields.push_back(entry.name()); |
1695 | 1.52k | } |
1696 | | |
1697 | 3.05k | return std::make_pair(std::move(resolved_name), std::move(fields)); |
1698 | 3.10k | } |
1699 | | |
1700 | | CallHandlerResult HandleIndex(const cel::Expr& expr, |
1701 | | const cel::CallExpr& call); |
1702 | | CallHandlerResult HandleBlock(const cel::Expr& expr, |
1703 | | const cel::CallExpr& call); |
1704 | | CallHandlerResult HandleListAppend(const cel::Expr& expr, |
1705 | | const cel::CallExpr& call); |
1706 | | CallHandlerResult HandleNot(const cel::Expr& expr, const cel::CallExpr& call); |
1707 | | CallHandlerResult HandleNotStrictlyFalse(const cel::Expr& expr, |
1708 | | const cel::CallExpr& call); |
1709 | | |
1710 | | CallHandlerResult HandleHeterogeneousEquality(const cel::Expr& expr, |
1711 | | const cel::CallExpr& call, |
1712 | | bool inequality); |
1713 | | |
1714 | | CallHandlerResult HandleHeterogeneousEqualityIn(const cel::Expr& expr, |
1715 | | const cel::CallExpr& call); |
1716 | | |
1717 | | void MaybeResolveType(const cel::Expr& expr); |
1718 | | |
1719 | | size_t AddOrUpdateIdentifier(absl::string_view name); |
1720 | | |
1721 | | const Resolver& resolver_; |
1722 | | const cel::TypeProvider& type_provider_; |
1723 | | absl::Status progress_status_; |
1724 | | absl::flat_hash_map<std::string, CallHandler> call_handlers_; |
1725 | | |
1726 | | std::stack<std::pair<const cel::Expr*, std::unique_ptr<CondVisitor>>> |
1727 | | cond_visitor_stack_; |
1728 | | |
1729 | | // Tracks SELECT-...SELECT-IDENT chains. |
1730 | | std::deque<std::pair<const cel::Expr*, std::string>> namespace_stack_; |
1731 | | |
1732 | | // When multiple SELECT-...SELECT-IDENT chain is resolved as namespace, this |
1733 | | // field is used as marker suppressing CelExpression creation for SELECTs. |
1734 | | const cel::Expr* resolved_select_expr_; |
1735 | | |
1736 | | const cel::RuntimeOptions& options_; |
1737 | | |
1738 | | std::vector<ComprehensionStackRecord> comprehension_stack_; |
1739 | | absl::flat_hash_set<const cel::Expr*> suppressed_branches_; |
1740 | | const cel::Expr* resume_from_suppressed_branch_ = nullptr; |
1741 | | std::vector<std::unique_ptr<ProgramOptimizer>> program_optimizers_; |
1742 | | const absl::flat_hash_map<int64_t, cel::TypeSpec>& type_map_; |
1743 | | IssueCollector& issue_collector_; |
1744 | | |
1745 | | ProgramBuilder& program_builder_; |
1746 | | PlannerContext& extension_context_; |
1747 | | IndexManager index_manager_; |
1748 | | std::vector<std::string> identifiers_; |
1749 | | absl::flat_hash_map<std::string, size_t> identifier_map_; |
1750 | | |
1751 | | bool enable_optional_types_; |
1752 | | std::optional<FlatExprVisitor::BlockInfo> block_; |
1753 | | }; |
1754 | | |
1755 | | FlatExprVisitor::CallHandlerResult FlatExprVisitor::HandleIndex( |
1756 | 3.17k | const cel::Expr& expr, const cel::CallExpr& call_expr) { |
1757 | 3.17k | ABSL_DCHECK(call_expr.function() == cel::builtin::kIndex); |
1758 | 3.17k | if (!ValidateOrError( |
1759 | 3.17k | (call_expr.args().size() == 2 && !call_expr.has_target()) || |
1760 | | // TODO(uncreated-issue/79): A few clients use the index operator with a |
1761 | | // target in custom ASTs. |
1762 | 0 | (call_expr.args().size() == 1 && call_expr.has_target()), |
1763 | 3.17k | "unexpected number of args for builtin index operator")) { |
1764 | 0 | return CallHandlerResult::kIntercepted; |
1765 | 0 | } |
1766 | | |
1767 | 3.17k | AddStep(CreateContainerAccessStep(call_expr, enable_optional_types_), |
1768 | 3.17k | expr.id(), /*stack_delta=*/-1); |
1769 | 3.17k | return CallHandlerResult::kIntercepted; |
1770 | 3.17k | } |
1771 | | |
1772 | | FlatExprVisitor::CallHandlerResult FlatExprVisitor::HandleNot( |
1773 | 1.19k | const cel::Expr& expr, const cel::CallExpr& call_expr) { |
1774 | 1.19k | ABSL_DCHECK(call_expr.function() == cel::builtin::kNot); |
1775 | | |
1776 | 1.19k | if (!ValidateOrError(call_expr.args().size() == 1 && !call_expr.has_target(), |
1777 | 1.19k | "unexpected number of args for builtin not operator")) { |
1778 | 0 | return CallHandlerResult::kIntercepted; |
1779 | 0 | } |
1780 | | |
1781 | 1.19k | AddStep(ExpressionStep::MakeBooleanNotStep(expr.id())); |
1782 | 1.19k | return CallHandlerResult::kIntercepted; |
1783 | 1.19k | } |
1784 | | |
1785 | | FlatExprVisitor::CallHandlerResult FlatExprVisitor::HandleNotStrictlyFalse( |
1786 | 126 | const cel::Expr& expr, const cel::CallExpr& call_expr) { |
1787 | 126 | if (!ValidateOrError(call_expr.args().size() == 1 && !call_expr.has_target(), |
1788 | 126 | "unexpected number of args for builtin " |
1789 | 126 | "not_strictly_false operator")) { |
1790 | 0 | return CallHandlerResult::kIntercepted; |
1791 | 0 | } |
1792 | | |
1793 | 126 | AddStep(ExpressionStep::MakeNotStrictlyFalseStep(expr.id())); |
1794 | 126 | return CallHandlerResult::kIntercepted; |
1795 | 126 | } |
1796 | | |
1797 | | FlatExprVisitor::CallHandlerResult FlatExprVisitor::HandleBlock( |
1798 | 0 | const cel::Expr& expr, const cel::CallExpr& call_expr) { |
1799 | 0 | ABSL_DCHECK(call_expr.function() == kBlock); |
1800 | 0 | if (!block_.has_value() || block_->expr != &expr || |
1801 | 0 | call_expr.args().size() != 2 || call_expr.has_target()) { |
1802 | 0 | SetProgressStatusIfError( |
1803 | 0 | absl::InvalidArgumentError("unexpected call to internal cel.@block")); |
1804 | 0 | return CallHandlerResult::kIntercepted; |
1805 | 0 | } |
1806 | | |
1807 | 0 | BlockInfo& block = *block_; |
1808 | 0 | block.in = false; |
1809 | 0 | index_manager().ReleaseSlots(block.slot_count); |
1810 | | |
1811 | | // Otherwise, iterative plan. |
1812 | 0 | if (block.slot_count > 0) { |
1813 | 0 | AddStep(ExpressionStep::MakeClearSlotsStep(block.index, block.slot_count, |
1814 | 0 | expr.id())); |
1815 | 0 | } |
1816 | |
|
1817 | 0 | return CallHandlerResult::kIntercepted; |
1818 | 0 | } |
1819 | | |
1820 | | FlatExprVisitor::CallHandlerResult FlatExprVisitor::HandleListAppend( |
1821 | 23.7k | const cel::Expr& expr, const cel::CallExpr& call_expr) { |
1822 | 23.7k | ABSL_DCHECK(call_expr.function() == cel::builtin::kAdd); |
1823 | | |
1824 | | // Check to see if this is a special case of add that should really be |
1825 | | // treated as a list append |
1826 | 23.7k | if (!comprehension_stack_.empty() && |
1827 | 20.6k | comprehension_stack_.back().is_optimizable_list_append) { |
1828 | | // Already checked that this is an optimizeable comprehension, |
1829 | | // check that this is the correct list append node. |
1830 | 0 | const cel::ComprehensionExpr* comprehension = |
1831 | 0 | comprehension_stack_.back().comprehension; |
1832 | 0 | const cel::Expr& loop_step = comprehension->loop_step(); |
1833 | | |
1834 | | // Macro loop_step for a map() will contain a list concat operation: |
1835 | | // accu_var + [elem] |
1836 | 0 | const bool is_map_loop_step = &loop_step == &expr; |
1837 | | |
1838 | | // Macro loop_step for a filter() will contain a ternary: |
1839 | | // filter ? accu_var + [elem] : accu_var |
1840 | 0 | const bool is_filter_loop_step = |
1841 | 0 | loop_step.has_call_expr() && |
1842 | 0 | loop_step.call_expr().function() == cel::builtin::kTernary && |
1843 | 0 | loop_step.call_expr().args().size() == 3 && |
1844 | 0 | &(loop_step.call_expr().args()[1]) == &expr; |
1845 | 0 | if (is_map_loop_step || is_filter_loop_step) { |
1846 | 0 | AddStep(ExpressionStep::MakeMutableListAppendStep(expr.id())); |
1847 | 0 | return CallHandlerResult::kIntercepted; |
1848 | 0 | } |
1849 | 0 | } |
1850 | | |
1851 | 23.7k | return CallHandlerResult::kNotIntercepted; |
1852 | 23.7k | } |
1853 | | |
1854 | | FlatExprVisitor::CallHandlerResult FlatExprVisitor::HandleHeterogeneousEquality( |
1855 | 9.66k | const cel::Expr& expr, const cel::CallExpr& call, bool inequality) { |
1856 | 9.66k | if (!ValidateOrError( |
1857 | 9.66k | call.args().size() == 2 && !call.has_target(), |
1858 | 9.66k | "unexpected number of args for builtin equality operator")) { |
1859 | 0 | return CallHandlerResult::kIntercepted; |
1860 | 0 | } |
1861 | | |
1862 | 9.66k | AddStep(inequality ? ExpressionStep::MakeFastNotEqualStep(expr.id()) |
1863 | 9.66k | : ExpressionStep::MakeFastEqualStep(expr.id())); |
1864 | 9.66k | return CallHandlerResult::kIntercepted; |
1865 | 9.66k | } |
1866 | | |
1867 | | FlatExprVisitor::CallHandlerResult |
1868 | | FlatExprVisitor::HandleHeterogeneousEqualityIn(const cel::Expr& expr, |
1869 | 1.82k | const cel::CallExpr& call) { |
1870 | 1.82k | if (!ValidateOrError(call.args().size() == 2 && !call.has_target(), |
1871 | 1.82k | "unexpected number of args for builtin 'in' operator")) { |
1872 | 9 | return CallHandlerResult::kIntercepted; |
1873 | 9 | } |
1874 | | |
1875 | 1.81k | AddStep(ExpressionStep::MakeFastInStep(expr.id())); |
1876 | 1.81k | return CallHandlerResult::kIntercepted; |
1877 | 1.82k | } |
1878 | | |
1879 | 502k | void FlatExprVisitor::MaybeResolveType(const cel::Expr& expr) { |
1880 | | // Try to resolve the type from the type map, but don't fail if it's not |
1881 | | // there. This permits cases where the runtime type is compatible but not |
1882 | | // the same as the type checked type. |
1883 | 502k | auto it = type_map_.find(expr.id()); |
1884 | 502k | if (it == type_map_.end()) { |
1885 | 502k | return; |
1886 | 502k | } |
1887 | 0 | extension_context_.TryResolveType(expr.id(), it->second); |
1888 | 0 | } |
1889 | | |
1890 | 56.7k | size_t FlatExprVisitor::AddOrUpdateIdentifier(absl::string_view name) { |
1891 | 56.7k | auto it = identifier_map_.find(name); |
1892 | 56.7k | if (it == identifier_map_.end()) { |
1893 | 24.2k | size_t index = identifiers_.size(); |
1894 | 24.2k | it = identifier_map_.emplace(name, index).first; |
1895 | 24.2k | identifiers_.push_back(std::string(name)); |
1896 | 24.2k | } |
1897 | 56.7k | return it->second; |
1898 | 56.7k | } |
1899 | | |
1900 | 4.60k | void LogicalCondVisitor::PreVisit(const cel::Expr* expr) { |
1901 | 4.60k | visitor_->ValidateOrError( |
1902 | 4.60k | !expr->call_expr().has_target() && expr->call_expr().args().size() >= 2, |
1903 | 4.60k | "Invalid argument count for a binary function call."); |
1904 | 4.60k | } |
1905 | | |
1906 | 9.06k | void LogicalCondVisitor::PostVisitArg(int arg_num, const cel::Expr* expr) { |
1907 | 9.06k | const int last_arg_index = expr->call_expr().args().size() - 1; |
1908 | 9.06k | const size_t num_args = expr->call_expr().args().size(); |
1909 | 9.06k | if (arg_num == last_arg_index) { |
1910 | 4.52k | if (is_or_) { |
1911 | 3.34k | visitor_->AddStep( |
1912 | 3.34k | ExpressionStep::MakeBooleanOrStep(num_args, expr->id())); |
1913 | 3.34k | } else { |
1914 | 1.18k | visitor_->AddStep( |
1915 | 1.18k | ExpressionStep::MakeBooleanAndStep(num_args, expr->id())); |
1916 | 1.18k | } |
1917 | 4.52k | if (short_circuiting_ && !jump_steps_.empty()) { |
1918 | 4.52k | ProgramStepIndex target = visitor_->GetCurrentIndex(); |
1919 | 4.52k | for (const ProgramStepIndex& jump_pos : jump_steps_) { |
1920 | 4.52k | absl::StatusOr<int> offset = Jump::CalculateOffset(jump_pos, target); |
1921 | 4.52k | if (!offset.ok()) { |
1922 | 0 | visitor_->SetProgressStatusIfError(offset.status()); |
1923 | 0 | continue; |
1924 | 0 | } |
1925 | 4.52k | ExpressionStep* step = |
1926 | 4.52k | jump_pos.subexpression->GetIfExpressionStep(jump_pos.index); |
1927 | 4.52k | BoolJumpStepInfo* jump_info = GetIfBoolJumpStep(step); |
1928 | 4.52k | if (jump_info != nullptr) { |
1929 | 4.52k | jump_info->set = true; |
1930 | 4.52k | jump_info->offset = *offset; |
1931 | 4.52k | } |
1932 | 4.52k | } |
1933 | 4.52k | } |
1934 | 4.52k | } |
1935 | 9.06k | if (short_circuiting_ && arg_num < last_arg_index) { |
1936 | 4.53k | ProgramStepIndex index = visitor_->GetCurrentIndex(); |
1937 | 4.53k | visitor_->AddStep(is_or_ ? ExpressionStep::MakeBooleanOrJumpStep( |
1938 | 3.35k | /*arg_count=*/arg_num + 1) |
1939 | 4.53k | : ExpressionStep::MakeBooleanAndJumpStep( |
1940 | 1.18k | /*arg_count=*/arg_num + 1)); |
1941 | 4.53k | jump_steps_.push_back(index); |
1942 | 4.53k | } |
1943 | 9.06k | } |
1944 | | |
1945 | 4.52k | void LogicalCondVisitor::PostVisit(const cel::Expr* expr) { |
1946 | 4.52k | } |
1947 | | |
1948 | 0 | void OptionalOrCondVisitor::PreVisit(const cel::Expr* expr) { |
1949 | 0 | visitor_->ValidateOrError( |
1950 | 0 | expr->call_expr().has_target() && expr->call_expr().args().size() == 1, |
1951 | 0 | "Invalid argument count for or/orValue call."); |
1952 | 0 | } |
1953 | | |
1954 | 0 | void OptionalOrCondVisitor::PostVisitTarget(const cel::Expr* expr) { |
1955 | 0 | if (!short_circuiting_) { |
1956 | 0 | return; |
1957 | 0 | } |
1958 | | |
1959 | | // Keep a pointer to the jump step so we can update the target after |
1960 | | // planning the second argument. |
1961 | 0 | jump_step_pos_ = visitor_->GetCurrentIndex(); |
1962 | 0 | jump_step_ = visitor_->AddStep(CreateOptionalHasValueJumpStep(is_or_value_)); |
1963 | 0 | } |
1964 | | |
1965 | 0 | void OptionalOrCondVisitor::PostVisit(const cel::Expr* expr) { |
1966 | 0 | visitor_->AddStep(CreateOptionalOrStep(is_or_value_), expr->id()); |
1967 | 0 | if (!short_circuiting_) { |
1968 | 0 | return; |
1969 | 0 | } |
1970 | | |
1971 | 0 | ABSL_DCHECK(jump_step_ != nullptr) |
1972 | 0 | << "OptionalOrCondVisitor::PostVisit: jump_step_ is null"; |
1973 | 0 | absl::StatusOr<int> offset = |
1974 | 0 | Jump::CalculateOffset(jump_step_pos_, visitor_->GetCurrentIndex()); |
1975 | 0 | if (!offset.ok()) { |
1976 | 0 | visitor_->SetProgressStatusIfError(offset.status()); |
1977 | 0 | return; |
1978 | 0 | } |
1979 | | |
1980 | 0 | jump_step_->set_jump_offset(*offset); |
1981 | 0 | } |
1982 | | |
1983 | 4.12k | void TernaryCondVisitor::PreVisit(const cel::Expr* expr) { |
1984 | 4.12k | visitor_->ValidateOrError( |
1985 | 4.12k | !expr->call_expr().has_target() && expr->call_expr().args().size() == 3, |
1986 | 4.12k | "Invalid argument count for a ternary function call."); |
1987 | 4.12k | } |
1988 | | |
1989 | 12.2k | void TernaryCondVisitor::PostVisitArg(int arg_num, const cel::Expr* expr) { |
1990 | | // Ternary operator "_?_:_" requires a special handing. |
1991 | | // In contrary to regular function call, its execution affects the control |
1992 | | // flow of the overall CEL expression. |
1993 | | // If condition value (argument 0) is True, then control flow is unaffected |
1994 | | // as it is passed to the first conditional branch. Then, at the end of this |
1995 | | // branch, the jump is performed over the second conditional branch. |
1996 | | // If condition value is False, then jump is performed and control is passed |
1997 | | // to the beginning of the second conditional branch. |
1998 | | // If condition value is Error, then jump is peformed to bypass both |
1999 | | // conditional branches and provide Error as result of ternary operation. |
2000 | | |
2001 | | // condition argument for ternary operator |
2002 | 12.2k | if (arg_num == 0) { |
2003 | | // Jump in case of error or non-bool, or jump to the second branch of |
2004 | | // execution if false. |
2005 | 4.12k | cond_jump_pos_ = visitor_->GetCurrentIndex(); |
2006 | 4.12k | visitor_->AddStep(ExpressionStep::MakeTernaryJumpStep()); |
2007 | 8.13k | } else if (arg_num == 1) { |
2008 | | // Jump after the first and over the second branch of execution. |
2009 | 4.10k | jump_after_first_pos_ = visitor_->GetCurrentIndex(); |
2010 | 4.10k | visitor_->AddStep(ExpressionStep::MakeFixedJumpStep()); |
2011 | | |
2012 | 4.10k | ExpressionStep* cond_step = |
2013 | 4.10k | cond_jump_pos_.has_value() |
2014 | 4.10k | ? cond_jump_pos_->subexpression->GetIfExpressionStep( |
2015 | 4.10k | cond_jump_pos_->index) |
2016 | 4.10k | : nullptr; |
2017 | 4.10k | TernaryJumpStepInfo* ternary_info = GetIfTernaryJumpStep(cond_step); |
2018 | 4.10k | if (!visitor_->ValidateOrError( |
2019 | 4.10k | ternary_info != nullptr, |
2020 | 4.10k | "Error configuring ternary operator: jump_to_second_ is null")) { |
2021 | 0 | return; |
2022 | 0 | } |
2023 | | |
2024 | 4.10k | absl::StatusOr<int> offset = |
2025 | 4.10k | Jump::CalculateOffset(*cond_jump_pos_, visitor_->GetCurrentIndex()); |
2026 | 4.10k | if (!offset.ok()) { |
2027 | 0 | visitor_->SetProgressStatusIfError(offset.status()); |
2028 | 0 | return; |
2029 | 0 | } |
2030 | | |
2031 | 4.10k | ternary_info->jump_to_second_offset = *offset; |
2032 | 4.10k | } |
2033 | | // Code executed after traversing the final branch of execution |
2034 | | // (arg_num == 2) is placed in PostVisitCall, to make this method less |
2035 | | // clattered. |
2036 | 12.2k | } |
2037 | | |
2038 | 4.03k | void TernaryCondVisitor::PostVisit(const cel::Expr* expr) { |
2039 | | // Determine and set jump offset in jump instruction. |
2040 | 4.03k | ExpressionStep* cond_step = |
2041 | 4.03k | cond_jump_pos_.has_value() |
2042 | 4.03k | ? cond_jump_pos_->subexpression->GetIfExpressionStep( |
2043 | 4.03k | cond_jump_pos_->index) |
2044 | 4.03k | : nullptr; |
2045 | 4.03k | TernaryJumpStepInfo* ternary_info = GetIfTernaryJumpStep(cond_step); |
2046 | 4.03k | if (visitor_->ValidateOrError( |
2047 | 4.03k | ternary_info != nullptr, |
2048 | 4.03k | "Error configuring ternary operator: error_jump_ is null")) { |
2049 | 4.03k | absl::StatusOr<int> offset = |
2050 | 4.03k | Jump::CalculateOffset(*cond_jump_pos_, visitor_->GetCurrentIndex()); |
2051 | 4.03k | if (!offset.ok()) { |
2052 | 0 | visitor_->SetProgressStatusIfError(offset.status()); |
2053 | 4.03k | } else { |
2054 | 4.03k | ternary_info->set = true; |
2055 | 4.03k | ternary_info->error_offset = *offset; |
2056 | 4.03k | } |
2057 | 4.03k | } |
2058 | 4.03k | ExpressionStep* jump_after_first_step = |
2059 | 4.03k | jump_after_first_pos_.has_value() |
2060 | 4.03k | ? jump_after_first_pos_->subexpression->GetIfExpressionStep( |
2061 | 4.03k | jump_after_first_pos_->index) |
2062 | 4.03k | : nullptr; |
2063 | 4.03k | FixedJumpStepInfo* fixed_info = GetIfFixedJumpStep(jump_after_first_step); |
2064 | 4.03k | if (visitor_->ValidateOrError( |
2065 | 4.03k | fixed_info != nullptr, |
2066 | 4.03k | "Error configuring ternary operator: jump_after_first_ is null")) { |
2067 | 4.03k | absl::StatusOr<int> offset = Jump::CalculateOffset( |
2068 | 4.03k | *jump_after_first_pos_, visitor_->GetCurrentIndex()); |
2069 | 4.03k | if (!offset.ok()) { |
2070 | 0 | visitor_->SetProgressStatusIfError(offset.status()); |
2071 | 4.03k | } else { |
2072 | 4.03k | fixed_info->set = true; |
2073 | 4.03k | fixed_info->offset = *offset; |
2074 | 4.03k | } |
2075 | 4.03k | } |
2076 | 4.03k | } |
2077 | | |
2078 | 0 | void ExhaustiveTernaryCondVisitor::PreVisit(const cel::Expr* expr) { |
2079 | 0 | visitor_->ValidateOrError( |
2080 | 0 | !expr->call_expr().has_target() && expr->call_expr().args().size() == 3, |
2081 | 0 | "Invalid argument count for a ternary function call."); |
2082 | 0 | } |
2083 | | |
2084 | 0 | void ExhaustiveTernaryCondVisitor::PostVisit(const cel::Expr* expr) { |
2085 | 0 | visitor_->AddStep(CreateTernaryStep(), expr->id(), /*stack_delta=*/-2); |
2086 | 0 | } |
2087 | | |
2088 | 19.7k | void ComprehensionVisitor::PreVisit(const cel::Expr* expr) { |
2089 | 19.7k | if (is_trivial_) { |
2090 | 0 | visitor_->SuppressBranch(&expr->comprehension_expr().iter_range()); |
2091 | 0 | visitor_->SuppressBranch(&expr->comprehension_expr().loop_condition()); |
2092 | 0 | visitor_->SuppressBranch(&expr->comprehension_expr().loop_step()); |
2093 | 0 | } |
2094 | 19.7k | } |
2095 | | |
2096 | 18.0k | ComprehensionInitStepInfo* absl_nullable ComprehensionVisitor::GetInitStep() { |
2097 | 18.0k | if (!init_step_pos_) { |
2098 | 0 | return nullptr; |
2099 | 0 | } |
2100 | 18.0k | ExpressionStep* step = |
2101 | 18.0k | init_step_pos_->subexpression->GetIfExpressionStep(init_step_pos_->index); |
2102 | 18.0k | if (!step) { |
2103 | 0 | return nullptr; |
2104 | 0 | } |
2105 | 18.0k | return GetIfComprehensionInitStep(*step); |
2106 | 18.0k | } |
2107 | | |
2108 | 36.0k | ComprehensionCondStepInfo* absl_nullable ComprehensionVisitor::GetCondStep() { |
2109 | 36.0k | if (!cond_step_pos_) { |
2110 | 0 | return nullptr; |
2111 | 0 | } |
2112 | 36.0k | ExpressionStep* step = |
2113 | 36.0k | cond_step_pos_->subexpression->GetIfExpressionStep(cond_step_pos_->index); |
2114 | 36.0k | if (!step) { |
2115 | 0 | return nullptr; |
2116 | 0 | } |
2117 | 36.0k | return GetIfComprehensionCondStep(*step); |
2118 | 36.0k | } |
2119 | | |
2120 | 36.0k | ComprehensionNextStepInfo* absl_nullable ComprehensionVisitor::GetNextStep() { |
2121 | 36.0k | if (!next_step_pos_) { |
2122 | 0 | return nullptr; |
2123 | 0 | } |
2124 | 36.0k | ExpressionStep* step = |
2125 | 36.0k | next_step_pos_->subexpression->GetIfExpressionStep(next_step_pos_->index); |
2126 | 36.0k | if (!step) { |
2127 | 0 | return nullptr; |
2128 | 0 | } |
2129 | 36.0k | return GetIfComprehensionNextStep(*step); |
2130 | 36.0k | } |
2131 | | |
2132 | | absl::Status ComprehensionVisitor::PostVisitArgDefault( |
2133 | 90.2k | cel::ComprehensionArg arg_num, const cel::Expr* expr) { |
2134 | 90.2k | switch (arg_num) { |
2135 | 18.0k | case cel::ITER_RANGE: { |
2136 | 18.0k | init_step_pos_ = visitor_->GetCurrentIndex(); |
2137 | 18.0k | if (iter_slot_ != iter2_slot_) { |
2138 | 0 | ABSL_DCHECK_EQ(iter2_slot_, iter_slot_ + 1); |
2139 | 0 | ABSL_DCHECK_EQ(accu_slot_, iter2_slot_ + 1); |
2140 | 0 | visitor_->AddStep(ExpressionStep::MakeComprehensionInitStep( |
2141 | 0 | static_cast<uint32_t>(iter_slot_), ComprehensionVersion::kV2)); |
2142 | 18.0k | } else { |
2143 | 18.0k | ABSL_DCHECK_EQ(accu_slot_, iter_slot_ + 1); |
2144 | 18.0k | visitor_->AddStep(ExpressionStep::MakeComprehensionInitStep( |
2145 | 18.0k | static_cast<uint32_t>(iter_slot_), ComprehensionVersion::kV1)); |
2146 | 18.0k | } |
2147 | 18.0k | break; |
2148 | 0 | } |
2149 | 18.0k | case cel::ACCU_INIT: { |
2150 | 18.0k | next_step_pos_ = visitor_->GetCurrentIndex(); |
2151 | 18.0k | if (iter_slot_ != iter2_slot_) { |
2152 | 0 | visitor_->AddStep(ExpressionStep::MakeComprehensionNext2Step()); |
2153 | 18.0k | } else { |
2154 | 18.0k | visitor_->AddStep(ExpressionStep::MakeComprehensionNextStep()); |
2155 | 18.0k | } |
2156 | 18.0k | break; |
2157 | 0 | } |
2158 | 18.0k | case cel::LOOP_CONDITION: { |
2159 | 18.0k | cond_step_pos_ = visitor_->GetCurrentIndex(); |
2160 | 18.0k | if (iter_slot_ != iter2_slot_) { |
2161 | 0 | visitor_->AddStep(ExpressionStep::MakeComprehensionCond2Step()); |
2162 | 18.0k | } else { |
2163 | 18.0k | visitor_->AddStep(ExpressionStep::MakeComprehensionCondStep()); |
2164 | 18.0k | } |
2165 | 18.0k | break; |
2166 | 0 | } |
2167 | 18.0k | case cel::LOOP_STEP: { |
2168 | 18.0k | ProgramStepIndex index = visitor_->GetCurrentIndex(); |
2169 | 18.0k | ExpressionStep* jump_step = |
2170 | 18.0k | visitor_->AddStep(ExpressionStep::MakeFixedJumpStep()); |
2171 | 18.0k | FixedJumpStepInfo* fixed_info = GetIfFixedJumpStep(jump_step); |
2172 | 18.0k | if (fixed_info == nullptr) { |
2173 | | // either an error occurred earlier or planning is suppressed. |
2174 | 0 | break; |
2175 | 0 | } |
2176 | 36.0k | CEL_ASSIGN_OR_RETURN(int offset, |
2177 | 36.0k | Jump::CalculateOffset(index, *next_step_pos_)); |
2178 | 36.0k | fixed_info->set = true; |
2179 | 36.0k | fixed_info->offset = offset; |
2180 | | |
2181 | | // Set offsets jumping to the result step. |
2182 | 36.0k | if (auto* cond_step = GetCondStep(); cond_step != nullptr) { |
2183 | 18.0k | CEL_ASSIGN_OR_RETURN(int jump_from_cond, |
2184 | 18.0k | Jump::CalculateOffset( |
2185 | 18.0k | *cond_step_pos_, visitor_->GetCurrentIndex())); |
2186 | 18.0k | cond_step->set_jump_offset(jump_from_cond); |
2187 | 18.0k | } else { |
2188 | 0 | return absl::InvalidArgumentError("Comprehension is malformed"); |
2189 | 0 | } |
2190 | | |
2191 | 18.0k | if (auto* next_step = GetNextStep(); next_step != nullptr) { |
2192 | 18.0k | CEL_ASSIGN_OR_RETURN(int jump_from_next, |
2193 | 18.0k | Jump::CalculateOffset( |
2194 | 18.0k | *next_step_pos_, visitor_->GetCurrentIndex())); |
2195 | | |
2196 | 18.0k | next_step->set_jump_offset(jump_from_next); |
2197 | 18.0k | } else { |
2198 | 0 | return absl::InvalidArgumentError("Comprehension is malformed"); |
2199 | 0 | } |
2200 | 18.0k | break; |
2201 | 18.0k | } |
2202 | 18.0k | case cel::RESULT: { |
2203 | 18.0k | if (!init_step_pos_ || !next_step_pos_ || !cond_step_pos_) { |
2204 | | // Encountered an error earlier. Can't determine where to jump. |
2205 | 0 | break; |
2206 | 0 | } |
2207 | 18.0k | visitor_->AddStep( |
2208 | 18.0k | ExpressionStep::MakeComprehensionFinishStep(accu_slot_, expr->id())); |
2209 | | // Set offsets jumping past the result step in case of errors. |
2210 | 18.0k | if (auto* init_step = GetInitStep(); init_step != nullptr) { |
2211 | 18.0k | CEL_ASSIGN_OR_RETURN(int jump_from_init, |
2212 | 18.0k | Jump::CalculateOffset( |
2213 | 18.0k | *init_step_pos_, visitor_->GetCurrentIndex())); |
2214 | 18.0k | init_step->set_error_jump_offset(jump_from_init); |
2215 | 18.0k | } else { |
2216 | 0 | return absl::InvalidArgumentError("Comprehension is malformed"); |
2217 | 0 | } |
2218 | | |
2219 | 18.0k | if (auto* next_step = GetNextStep(); next_step != nullptr) { |
2220 | 18.0k | CEL_ASSIGN_OR_RETURN(int jump_from_next, |
2221 | 18.0k | Jump::CalculateOffset( |
2222 | 18.0k | *next_step_pos_, visitor_->GetCurrentIndex())); |
2223 | 18.0k | next_step->set_error_jump_offset(jump_from_next); |
2224 | 18.0k | } else { |
2225 | 0 | return absl::InvalidArgumentError("Comprehension is malformed"); |
2226 | 0 | } |
2227 | | |
2228 | 18.0k | if (auto* cond_step = GetCondStep(); cond_step != nullptr) { |
2229 | 18.0k | CEL_ASSIGN_OR_RETURN(int jump_from_cond, |
2230 | 18.0k | Jump::CalculateOffset( |
2231 | 18.0k | *cond_step_pos_, visitor_->GetCurrentIndex())); |
2232 | 18.0k | cond_step->set_error_jump_offset(jump_from_cond); |
2233 | 18.0k | } else { |
2234 | 0 | return absl::InvalidArgumentError("Comprehension is malformed"); |
2235 | 0 | } |
2236 | 18.0k | break; |
2237 | 18.0k | } |
2238 | 90.2k | } |
2239 | 90.2k | return absl::OkStatus(); |
2240 | 90.2k | } |
2241 | | |
2242 | | void ComprehensionVisitor::PostVisitArgTrivial(cel::ComprehensionArg arg_num, |
2243 | 0 | const cel::Expr* expr) { |
2244 | 0 | switch (arg_num) { |
2245 | 0 | case cel::ITER_RANGE: { |
2246 | 0 | break; |
2247 | 0 | } |
2248 | 0 | case cel::ACCU_INIT: { |
2249 | 0 | if (!accu_init_extracted_) { |
2250 | 0 | visitor_->AddStep(ExpressionStep::MakeAssignSlotAndPopStep(accu_slot_)); |
2251 | 0 | } |
2252 | 0 | break; |
2253 | 0 | } |
2254 | 0 | case cel::LOOP_CONDITION: { |
2255 | 0 | break; |
2256 | 0 | } |
2257 | 0 | case cel::LOOP_STEP: { |
2258 | 0 | break; |
2259 | 0 | } |
2260 | 0 | case cel::RESULT: { |
2261 | 0 | visitor_->AddStep( |
2262 | 0 | ExpressionStep::MakeClearSlotStep(accu_slot_, expr->id())); |
2263 | 0 | break; |
2264 | 0 | } |
2265 | 0 | } |
2266 | 0 | } |
2267 | | |
2268 | 18.0k | void ComprehensionVisitor::PostVisit(const cel::Expr* expr) { |
2269 | 18.0k | } |
2270 | | |
2271 | | // Flattens the expression table into the end of the mainline expression vector |
2272 | | // and returns an index to the individual sub expressions. |
2273 | | std::vector<ExecutionPathView> FlattenExpressionTable( |
2274 | 18.9k | ProgramBuilder& program_builder, ExecutionPath& main) { |
2275 | 18.9k | std::vector<std::pair<size_t, size_t>> ranges; |
2276 | 18.9k | main = program_builder.FlattenMain(); |
2277 | 18.9k | ranges.push_back(std::make_pair(0, main.size())); |
2278 | | |
2279 | 18.9k | std::vector<ExecutionPath> subexpressions = |
2280 | 18.9k | program_builder.FlattenSubexpressions(); |
2281 | 18.9k | for (auto& subexpression : subexpressions) { |
2282 | 0 | ranges.push_back(std::make_pair(main.size(), subexpression.size())); |
2283 | 0 | absl::c_move(subexpression, std::back_inserter(main)); |
2284 | 0 | } |
2285 | | |
2286 | 18.9k | std::vector<ExecutionPathView> subexpression_indexes; |
2287 | 18.9k | subexpression_indexes.reserve(ranges.size()); |
2288 | 18.9k | for (const auto& range : ranges) { |
2289 | 18.9k | subexpression_indexes.push_back( |
2290 | 18.9k | absl::MakeSpan(main).subspan(range.first, range.second)); |
2291 | 18.9k | } |
2292 | 18.9k | return subexpression_indexes; |
2293 | 18.9k | } |
2294 | | |
2295 | | std::optional<int64_t> CheckedDeltaAdd(int64_t current, |
2296 | 547k | std::optional<int64_t> delta) { |
2297 | 547k | if (!delta.has_value()) { |
2298 | 0 | return std::nullopt; |
2299 | 0 | } |
2300 | 547k | if (*delta > 0 && current > std::numeric_limits<int64_t>::max() - *delta) { |
2301 | 0 | return std::nullopt; |
2302 | 0 | } |
2303 | 547k | if (*delta < 0 && current < std::numeric_limits<int64_t>::min() - *delta) { |
2304 | 0 | return std::nullopt; |
2305 | 0 | } |
2306 | 547k | current += *delta; |
2307 | 547k | if (current < 0) { |
2308 | 0 | return std::nullopt; |
2309 | 0 | } |
2310 | 547k | return current; |
2311 | 547k | } |
2312 | | |
2313 | | // Conservative estimate of the maximum value stack size needed for the given |
2314 | | // subexpressions. |
2315 | | // |
2316 | | // If overflow occurs, returns fallback_size, which is the total number of |
2317 | | // steps in the program. |
2318 | | size_t EstimateMaxStackSize(absl::Span<const ExecutionPathView> subexpressions, |
2319 | 18.9k | size_t fallback_size) { |
2320 | 18.9k | size_t total_max_stack = 0; |
2321 | 18.9k | for (ExecutionPathView path : subexpressions) { |
2322 | 18.9k | int64_t current = 0; |
2323 | 18.9k | int64_t max_depth = 0; |
2324 | 547k | for (const ExpressionStep& step : path) { |
2325 | 547k | std::optional<int64_t> next = CheckedDeltaAdd(current, step.StackDelta()); |
2326 | 547k | if (!next.has_value()) { |
2327 | 0 | return fallback_size; |
2328 | 0 | } |
2329 | 547k | current = *next; |
2330 | 547k | max_depth = std::max(max_depth, current); |
2331 | 547k | } |
2332 | 18.9k | if (static_cast<uint64_t>(max_depth) > |
2333 | 18.9k | std::numeric_limits<size_t>::max() - total_max_stack) { |
2334 | 0 | return fallback_size; |
2335 | 0 | } |
2336 | 18.9k | total_max_stack += static_cast<size_t>(max_depth); |
2337 | 18.9k | } |
2338 | 18.9k | return total_max_stack; |
2339 | 18.9k | } |
2340 | | |
2341 | | absl::Status CheckAstExtensions( |
2342 | | const std::vector<cel::ExtensionSpec>& extensions, |
2343 | 19.6k | bool enable_select_optimization) { |
2344 | 19.6k | for (const cel::ExtensionSpec& extension : extensions) { |
2345 | 0 | if (extension.id() == "cel_block" && extension.version().major() == 1) { |
2346 | | // cel_block v1 is always supported. |
2347 | 0 | continue; |
2348 | 0 | } |
2349 | 0 | if (extension.id() == "select_optimization" && |
2350 | 0 | extension.version().major() == 1 && enable_select_optimization) { |
2351 | 0 | continue; |
2352 | 0 | } |
2353 | | |
2354 | | // TODO(uncreated-issue/89): Add support for json field names. |
2355 | 0 | return absl::InvalidArgumentError(absl::StrCat( |
2356 | 0 | "unsupported CEL extension: ", extension.id(), "@", |
2357 | 0 | extension.version().major(), ".", extension.version().minor())); |
2358 | 0 | } |
2359 | 19.6k | return absl::OkStatus(); |
2360 | 19.6k | } |
2361 | | |
2362 | | } // namespace |
2363 | | |
2364 | | absl::StatusOr<FlatExpression> FlatExprBuilder::CreateExpressionImpl( |
2365 | 19.6k | std::unique_ptr<Ast> ast, std::vector<RuntimeIssue>* issues) const { |
2366 | 19.6k | if (absl::StartsWith(container_, ".") || absl::EndsWith(container_, ".")) { |
2367 | 0 | return absl::InvalidArgumentError( |
2368 | 0 | absl::StrCat("Invalid expression container: '", container_, "'")); |
2369 | 0 | } |
2370 | | |
2371 | 19.6k | RuntimeIssue::Severity max_severity = options_.fail_on_warnings |
2372 | 19.6k | ? RuntimeIssue::Severity::kWarning |
2373 | 19.6k | : RuntimeIssue::Severity::kError; |
2374 | 19.6k | IssueCollector issue_collector(max_severity); |
2375 | 19.6k | auto record_issues = absl::MakeCleanup([issues, &issue_collector] { |
2376 | 19.6k | if (issues == nullptr) { |
2377 | 19.6k | return; |
2378 | 19.6k | } |
2379 | 0 | *issues = issue_collector.ExtractIssues(); |
2380 | 0 | }); |
2381 | | |
2382 | 19.6k | absl::StatusOr<std::vector<cel::ExtensionSpec>> runtime_extensions = |
2383 | 19.6k | ExtractAndValidateRuntimeExtensions(*ast); |
2384 | | |
2385 | 19.6k | if (!runtime_extensions.ok()) { |
2386 | 0 | CEL_RETURN_IF_ERROR(issue_collector.AddIssue( |
2387 | 0 | RuntimeIssue::CreateError(runtime_extensions.status()))); |
2388 | 19.6k | } else { |
2389 | 19.6k | absl::Status status = |
2390 | 19.6k | CheckAstExtensions(*runtime_extensions, enable_select_optimization_); |
2391 | 19.6k | if (!status.ok()) { |
2392 | 0 | CEL_RETURN_IF_ERROR( |
2393 | 0 | issue_collector.AddIssue(RuntimeIssue::CreateError(status))); |
2394 | 0 | } |
2395 | 19.6k | } |
2396 | | |
2397 | 19.6k | Resolver resolver(container_, function_registry_, type_registry_, |
2398 | 19.6k | GetTypeProvider(), |
2399 | 19.6k | options_.enable_qualified_type_identifiers); |
2400 | | |
2401 | 19.6k | std::shared_ptr<google::protobuf::Arena> arena; |
2402 | 19.6k | ProgramBuilder program_builder; |
2403 | 19.6k | PlannerContext extension_context(env_, resolver, options_, GetTypeProvider(), |
2404 | 19.6k | issue_collector, program_builder, arena); |
2405 | | |
2406 | 19.6k | for (const std::unique_ptr<AstTransform>& transform : ast_transforms_) { |
2407 | 19.6k | CEL_RETURN_IF_ERROR(transform->UpdateAst(extension_context, *ast)); |
2408 | 19.6k | } |
2409 | | |
2410 | 19.6k | std::vector<std::unique_ptr<ProgramOptimizer>> optimizers; |
2411 | 19.6k | for (const ProgramOptimizerFactory& optimizer_factory : program_optimizers_) { |
2412 | 0 | CEL_ASSIGN_OR_RETURN(auto optimizer, |
2413 | 0 | optimizer_factory(extension_context, *ast)); |
2414 | 0 | if (optimizer != nullptr) { |
2415 | 0 | optimizers.push_back(std::move(optimizer)); |
2416 | 0 | } |
2417 | 0 | } |
2418 | | |
2419 | | // These objects are expected to remain scoped to one build call -- references |
2420 | | // to them shouldn't be persisted in any part of the result expression. |
2421 | 19.6k | FlatExprVisitor visitor(resolver, options_, std::move(optimizers), |
2422 | 19.6k | ast->type_map(), GetTypeProvider(), issue_collector, |
2423 | 19.6k | program_builder, extension_context, |
2424 | 19.6k | enable_optional_types_); |
2425 | | |
2426 | 19.6k | cel::TraversalOptions opts; |
2427 | 19.6k | opts.use_comprehension_callbacks = true; |
2428 | 19.6k | AstTraverse(ast->root_expr(), visitor, opts); |
2429 | | |
2430 | 19.6k | if (!visitor.progress_status().ok()) { |
2431 | 610 | return visitor.progress_status(); |
2432 | 610 | } |
2433 | | |
2434 | 18.9k | size_t total_slot_count = visitor.slot_count(); |
2435 | 18.9k | size_t iterator_stack_size = visitor.iter_stack_count(); |
2436 | 18.9k | IdentifierTable identifiers = |
2437 | 18.9k | std::move(visitor).BuildIdentifierTable(total_slot_count); |
2438 | | |
2439 | 18.9k | if (total_slot_count > std::numeric_limits<uint32_t>::max() || |
2440 | 18.9k | program_builder.ExtractedSubexpressionCount() > |
2441 | 18.9k | std::numeric_limits<uint32_t>::max()) { |
2442 | | // Impractical to trigger (we'd run out of memory first), but assuming this |
2443 | | // allows us to pack references to slots and subexpressions. |
2444 | 0 | return absl::InternalError( |
2445 | 0 | "Expression too large to be executed, exceeds uint32_t limits."); |
2446 | 0 | } |
2447 | | |
2448 | 18.9k | ExecutionPath execution_path; |
2449 | 18.9k | std::vector<ExecutionPathView> subexpressions = |
2450 | 18.9k | FlattenExpressionTable(program_builder, execution_path); |
2451 | 18.9k | size_t value_stack_size = |
2452 | 18.9k | EstimateMaxStackSize(subexpressions, execution_path.size()); |
2453 | | |
2454 | | // Iterate over execution path and update identifier steps with resolved slot. |
2455 | | // TODO(b/572083203): Should invert this so the local slots are stored |
2456 | | // after the global ones. |
2457 | 547k | for (ExpressionStep& step : execution_path) { |
2458 | 547k | if (IdentStepInfo* ident_step = GetIfIdentStep(step); |
2459 | 547k | ident_step != nullptr) { |
2460 | 50.7k | ident_step->slot_index = static_cast<uint32_t>( |
2461 | 50.7k | identifiers[ident_step->ident_index].slot_index); |
2462 | 50.7k | } |
2463 | 547k | } |
2464 | | |
2465 | 18.9k | return FlatExpression(std::move(execution_path), std::move(subexpressions), |
2466 | 18.9k | total_slot_count, iterator_stack_size, |
2467 | 18.9k | GetTypeProvider(), options_, std::move(arena), |
2468 | 18.9k | std::move(identifiers), value_stack_size); |
2469 | 18.9k | } |
2470 | 77.7k | const cel::TypeProvider& FlatExprBuilder::GetTypeProvider() const { |
2471 | 77.7k | return use_legacy_type_provider_ |
2472 | 77.7k | ? static_cast<const cel::TypeProvider&>( |
2473 | 77.7k | GetLegacyRuntimeTypeProvider(type_registry_)) |
2474 | 77.7k | : GetRuntimeTypeProvider(type_registry_); |
2475 | 77.7k | } |
2476 | | |
2477 | | } // namespace google::api::expr::runtime |