Coverage Report

Created: 2026-11-21 06:12

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/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
17.7k
      : next_free_slot_(0),
111
17.7k
        max_slot_count_(0),
112
17.7k
        iter_stack_count_(0),
113
17.7k
        max_iter_stack_count_(0),
114
17.7k
        lazy_iter_stack_count_(0) {}
115
116
17.4k
  size_t ReserveSlots(size_t n) {
117
17.4k
    size_t result = next_free_slot_;
118
17.4k
    next_free_slot_ += n;
119
17.4k
    if (next_free_slot_ > max_slot_count_) {
120
16.8k
      max_slot_count_ = next_free_slot_;
121
16.8k
    }
122
17.4k
    return result;
123
17.4k
  }
124
125
16.0k
  size_t ReleaseSlots(size_t n) {
126
16.0k
    next_free_slot_ -= n;
127
16.0k
    return next_free_slot_;
128
16.0k
  }
129
130
17.4k
  void ReserveIterStack() {
131
17.4k
    ++iter_stack_count_;
132
17.4k
    max_iter_stack_count_ = std::max(max_iter_stack_count_, iter_stack_count_);
133
17.4k
  }
134
16.0k
  void ReleaseIterStack() { --iter_stack_count_; }
135
0
  void AddLazyIterStack() { ++lazy_iter_stack_count_; }
136
137
17.0k
  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
17.0k
  size_t IterStackRequirement() const {
145
17.0k
    return max_iter_stack_count_ + lazy_iter_stack_count_;
146
17.0k
  }
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
109k
                                             ProgramStepIndex target) {
170
109k
    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
109k
    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
109k
    constexpr int kMaxJumpOffset = (1 << 30) - 1;
182
109k
    constexpr int kMinJumpOffset = -(1 << 30);
183
184
109k
    if (offset < kMinJumpOffset || offset > kMaxJumpOffset) {
185
0
      return absl::InternalError("Jump offset exceeds supported range: " +
186
0
                                 absl::StrCat(offset));
187
0
    }
188
109k
    return offset;
189
109k
  }
190
};
191
192
class CondVisitor {
193
 public:
194
6.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
3.40k
      : 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
3.33k
  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
472k
size_t SizeHint(const cel::Expr& expr) {
284
472k
  switch (expr.kind_case()) {
285
157k
    case cel::ExprKindCase::kConstant:
286
157k
      return 1;
287
97.1k
    case cel::ExprKindCase::kIdentExpr:
288
97.1k
      return 1;
289
18.4k
    case cel::ExprKindCase::kSelectExpr:
290
18.4k
      return 2;
291
122k
    case cel::ExprKindCase::kCallExpr:
292
122k
      return expr.call_expr().args().size() +
293
122k
             (expr.call_expr().has_target() ? 2 : 1);
294
52.1k
    case cel::ExprKindCase::kListExpr:
295
52.1k
      return expr.list_expr().elements().size() + 1;
296
3.03k
    case cel::ExprKindCase::kStructExpr:
297
3.03k
      return expr.struct_expr().fields().size() + 1;
298
4.02k
    case cel::ExprKindCase::kMapExpr:
299
4.02k
      return 2 * expr.struct_expr().fields().size() + 1;
300
17.4k
    default:
301
17.4k
      return 1;
302
472k
  }
303
0
  return 0;
304
472k
}
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
17.4k
                             bool short_circuiting = true) {
312
17.4k
  if (!enable_comprehension_list_append) {
313
17.4k
    return false;
314
17.4k
  }
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
17.4k
                            bool short_circuiting = true) {
390
17.4k
  if (!enable_comprehension_mutable_map) {
391
17.4k
    return false;
392
17.4k
  }
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
17.4k
bool IsBind(const cel::ComprehensionExpr* comprehension) {
429
17.4k
  static constexpr absl::string_view kUnusedIterVar = "#unused";
430
431
17.4k
  return comprehension->loop_condition().const_expr().has_bool_value() &&
432
17.3k
         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
17.4k
}
438
439
116k
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
17.4k
      : visitor_(visitor),
448
17.4k
        is_trivial_(is_trivial),
449
17.4k
        accu_init_extracted_(false),
450
17.4k
        iter_slot_(iter_slot),
451
17.4k
        iter2_slot_(iter2_slot),
452
17.4k
        accu_slot_(accu_slot) {}
453
454
  void PreVisit(const cel::Expr* expr);
455
  absl::Status PostVisitArg(cel::ComprehensionArg arg_num,
456
80.3k
                            const cel::Expr* comprehension_expr) {
457
80.3k
    if (is_trivial_) {
458
0
      PostVisitArgTrivial(arg_num, comprehension_expr);
459
0
      return absl::OkStatus();
460
80.3k
    } else {
461
80.3k
      return PostVisitArgDefault(arg_num, comprehension_expr);
462
80.3k
    }
463
80.3k
  }
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
2.67k
    const cel::StructExpr& create_struct_expr) {
492
2.67k
  absl::flat_hash_set<int32_t> optional_indices;
493
3.99k
  for (size_t i = 0; i < create_struct_expr.fields().size(); ++i) {
494
1.32k
    if (create_struct_expr.fields()[i].optional()) {
495
0
      optional_indices.insert(static_cast<int32_t>(i));
496
0
    }
497
1.32k
  }
498
2.67k
  return optional_indices;
499
2.67k
}
500
501
absl::flat_hash_set<int32_t> MakeOptionalIndicesSet(
502
4.26k
    const cel::MapExpr& map_expr) {
503
4.26k
  absl::flat_hash_set<int32_t> optional_indices;
504
9.25k
  for (size_t i = 0; i < map_expr.entries().size(); ++i) {
505
4.98k
    if (map_expr.entries()[i].optional()) {
506
0
      optional_indices.insert(static_cast<int32_t>(i));
507
0
    }
508
4.98k
  }
509
4.26k
  return optional_indices;
510
4.26k
}
511
512
absl::flat_hash_set<size_t> MakeOptionalIndicesSet(
513
52.0k
    const cel::ListExpr& list_expr) {
514
52.0k
  absl::flat_hash_set<size_t> optional_indices;
515
160k
  for (size_t i = 0; i < list_expr.elements().size(); ++i) {
516
108k
    if (list_expr.elements()[i].optional()) {
517
0
      optional_indices.insert(i);
518
0
    }
519
108k
  }
520
52.0k
  return optional_indices;
521
52.0k
}
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
17.7k
      : resolver_(resolver),
546
17.7k
        type_provider_(type_provider),
547
17.7k
        progress_status_(absl::OkStatus()),
548
17.7k
        resolved_select_expr_(nullptr),
549
17.7k
        options_(options),
550
17.7k
        program_optimizers_(std::move(program_optimizers)),
551
17.7k
        type_map_(type_map),
552
17.7k
        issue_collector_(issue_collector),
553
17.7k
        program_builder_(program_builder),
554
17.7k
        extension_context_(extension_context),
555
17.7k
        enable_optional_types_(enable_optional_types) {
556
17.7k
    constexpr size_t kCallHandlerSizeHint = 11;
557
17.7k
    call_handlers_.reserve(kCallHandlerSizeHint);
558
17.7k
    call_handlers_[cel::builtin::kIndex] = [this](const cel::Expr& expr,
559
17.7k
                                                  const cel::CallExpr& call) {
560
2.85k
      return HandleIndex(expr, call);
561
2.85k
    };
562
17.7k
    call_handlers_[kBlock] = [this](const cel::Expr& expr,
563
17.7k
                                    const cel::CallExpr& call) {
564
0
      return HandleBlock(expr, call);
565
0
    };
566
17.7k
    call_handlers_[cel::builtin::kAdd] = [this](const cel::Expr& expr,
567
20.5k
                                                const cel::CallExpr& call) {
568
20.5k
      return HandleListAppend(expr, call);
569
20.5k
    };
570
17.7k
    if (options_.enable_fast_builtins) {
571
17.7k
      call_handlers_[cel::builtin::kNotStrictlyFalse] =
572
17.7k
          [this](const cel::Expr& expr, const cel::CallExpr& call) {
573
125
            return HandleNotStrictlyFalse(expr, call);
574
125
          };
575
17.7k
      call_handlers_[cel::builtin::kNotStrictlyFalseDeprecated] =
576
17.7k
          [this](const cel::Expr& expr, const cel::CallExpr& call) {
577
0
            return HandleNotStrictlyFalse(expr, call);
578
0
          };
579
17.7k
      call_handlers_[cel::builtin::kNot] = [this](const cel::Expr& expr,
580
17.7k
                                                  const cel::CallExpr& call) {
581
668
        return HandleNot(expr, call);
582
668
      };
583
17.7k
      if (options_.enable_heterogeneous_equality) {
584
17.7k
        for (const auto& in_op :
585
17.7k
             {cel::builtin::kIn, cel::builtin::kInDeprecated,
586
53.1k
              cel::builtin::kInFunction}) {
587
53.1k
          call_handlers_[in_op] = [this](const cel::Expr& expr,
588
53.1k
                                         const cel::CallExpr& call) {
589
1.58k
            return HandleHeterogeneousEqualityIn(expr, call);
590
1.58k
          };
591
53.1k
        }
592
        // Try to detect if the environment is setup with a custom equality
593
        // implementation.
594
17.7k
        if (resolver_
595
17.7k
                .FindOverloads(cel::builtin::kEqual,
596
17.7k
                               /*receiver_style=*/false,
597
17.7k
                               {cel::Kind::kAny, cel::Kind::kAny})
598
17.7k
                .empty()) {
599
17.7k
          call_handlers_[cel::builtin::kEqual] =
600
17.7k
              [this](const cel::Expr& expr, const cel::CallExpr& call) {
601
7.91k
                return HandleHeterogeneousEquality(expr, call,
602
7.91k
                                                   /*inequality=*/false);
603
7.91k
              };
604
17.7k
          call_handlers_[cel::builtin::kInequal] =
605
17.7k
              [this](const cel::Expr& expr, const cel::CallExpr& call) {
606
419
                return HandleHeterogeneousEquality(expr, call,
607
419
                                                   /*inequality=*/true);
608
419
              };
609
17.7k
        }
610
17.7k
      }
611
17.7k
    }
612
17.7k
  }
613
614
489k
  void PreVisitExpr(const cel::Expr& expr) override {
615
489k
    ValidateOrError(!absl::holds_alternative<cel::UnspecifiedExpr>(expr.kind()),
616
489k
                    "Invalid empty expression");
617
489k
    if (!progress_status_.ok()) {
618
17.2k
      return;
619
17.2k
    }
620
472k
    if (resume_from_suppressed_branch_ == nullptr &&
621
472k
        suppressed_branches_.find(&expr) != suppressed_branches_.end()) {
622
0
      resume_from_suppressed_branch_ = &expr;
623
0
    }
624
625
472k
    if (extension_context_.resolve_types()) {
626
472k
      MaybeResolveType(expr);
627
472k
    }
628
629
472k
    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
472k
    auto* subexpression =
637
472k
        program_builder_.EnterSubexpression(&expr, SizeHint(expr));
638
472k
    if (subexpression == nullptr) {
639
0
      progress_status_.Update(
640
0
          absl::InternalError("same CEL expr visited twice"));
641
0
      return;
642
0
    }
643
644
472k
    for (const std::unique_ptr<ProgramOptimizer>& optimizer :
645
472k
         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
472k
  }
652
653
489k
  void PostVisitExpr(const cel::Expr& expr) override {
654
489k
    if (!progress_status_.ok()) {
655
22.1k
      return;
656
22.1k
    }
657
467k
    if (&expr == resume_from_suppressed_branch_) {
658
0
      resume_from_suppressed_branch_ = nullptr;
659
0
    }
660
661
467k
    for (const std::unique_ptr<ProgramOptimizer>& optimizer :
662
467k
         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
467k
    program_builder_.ExitSubexpression(&expr);
671
672
467k
    if (!comprehension_stack_.empty() &&
673
319k
        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
467k
    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
467k
  }
693
694
  void PostVisitConst(const cel::Expr& expr,
695
159k
                      const cel::Constant& const_expr) override {
696
159k
    if (!progress_status_.ok()) {
697
2.07k
      return;
698
2.07k
    }
699
700
157k
    absl::StatusOr<cel::Value> converted_value =
701
157k
        ConvertConstant(const_expr, extension_context_.MutableArena());
702
703
157k
    if (!converted_value.ok()) {
704
0
      SetProgressStatusIfError(converted_value.status());
705
0
      return;
706
0
    }
707
708
157k
    AddStep(ExpressionStep::MakeConstant(std::move(converted_value).value(),
709
157k
                                         expr.id()));
710
157k
  }
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
97.1k
  SlotLookupResult LookupSlot(absl::string_view path) {
722
    // If there's a leading dot, it cannot resolve to a local variable.
723
97.1k
    if (absl::StartsWith(path, ".")) {
724
748
      return {-1, -1};
725
748
    }
726
96.4k
    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
96.4k
    if (!comprehension_stack_.empty()) {
760
269k
      for (int i = comprehension_stack_.size() - 1; i >= 0; i--) {
761
246k
        const ComprehensionStackRecord& record = comprehension_stack_[i];
762
246k
        if (record.iter_var_in_scope &&
763
61.6k
            record.comprehension->iter_var() == path) {
764
4.86k
          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.86k
          return {static_cast<int>(record.iter_slot), -1};
771
4.86k
        }
772
241k
        if (record.iter_var2_in_scope &&
773
56.7k
            record.comprehension->iter_var2() == path) {
774
0
          return {static_cast<int>(record.iter2_slot), -1};
775
0
        }
776
241k
        if (record.accu_var_in_scope &&
777
72.7k
            record.comprehension->accu_var() == path) {
778
35.2k
          int slot = record.accu_slot;
779
35.2k
          int subexpression = -1;
780
35.2k
          if (record.is_optimizable_bind) {
781
0
            subexpression = record.subexpression;
782
0
          }
783
35.2k
          return {slot, subexpression};
784
35.2k
        }
785
241k
      }
786
63.1k
    }
787
56.2k
    if (absl::StartsWith(path, "@it:") || absl::StartsWith(path, "@it2:") ||
788
56.2k
        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.2k
    return {-1, -1};
798
96.4k
  }
799
800
  // Ident node handler.
801
  // Invoked after child nodes are processed.
802
  void PostVisitIdent(const cel::Expr& expr,
803
104k
                      const cel::IdentExpr& ident_expr) override {
804
104k
    if (!progress_status_.ok()) {
805
7.40k
      return;
806
7.40k
    }
807
97.1k
    absl::string_view path = ident_expr.name();
808
97.1k
    if (!ValidateOrError(
809
97.1k
            !path.empty(),
810
97.1k
            "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
97.1k
    SlotLookupResult slot = LookupSlot(path);
817
818
97.1k
    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
97.1k
    } else if (slot.slot >= 0) {
839
40.1k
        AddStep(ExpressionStep::MakeReadSlotStep(slot.slot, expr.id()));
840
40.1k
      return;
841
40.1k
    }
842
843
    // Attempt to resolve a select expression as a namespaced identifier for an
844
    // enum or type constant value.
845
57.0k
    std::optional<cel::Value> const_value;
846
57.0k
    int64_t select_root_id = -1;
847
57.0k
    std::string path_candidate;
848
849
67.1k
    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
59
        resolved_select_expr_ = select_expr;
862
59
        select_root_id = select_expr->id();
863
59
        path = path_candidate;
864
59
        namespace_stack_.clear();
865
59
        break;
866
59
      }
867
10.1k
      namespace_stack_.pop_front();
868
10.1k
    }
869
870
57.0k
    if (!const_value) {
871
      // Attempt to resolve a simple identifier as an enum or type constant
872
      // value.
873
56.9k
      const_value = resolver_.FindConstant(path, expr.id());
874
56.9k
      select_root_id = expr.id();
875
56.9k
    }
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.0k
    if (const_value) {
881
      // If the path starts with a dot, strip it.
882
582
      absl::string_view name = absl::StripPrefix(path, ".");
883
582
      AddStep(CreateShadowableValueStep(name, std::move(const_value).value()),
884
582
              select_root_id);
885
582
      return;
886
582
    }
887
888
56.4k
    if (PlanningSuppressed()) {
889
0
      return;
890
0
    }
891
56.4k
    absl::string_view ident_name = absl::StripPrefix(ident_expr.name(), ".");
892
56.4k
    size_t ident_index = AddOrUpdateIdentifier(ident_name);
893
56.4k
    AddStep(ExpressionStep::MakeIdentifierStep(ident_index, expr.id()));
894
56.4k
  }
895
896
  void PreVisitSelect(const cel::Expr& expr,
897
18.7k
                      const cel::SelectExpr& select_expr) override {
898
18.7k
    if (!progress_status_.ok()) {
899
351
      return;
900
351
    }
901
18.4k
    if (!ValidateOrError(
902
18.4k
            !select_expr.field().empty(),
903
18.4k
            "invalid expression: select 'field' must not be empty")) {
904
0
      return;
905
0
    }
906
18.4k
    if (!ValidateOrError(
907
18.4k
            select_expr.has_operand() &&
908
18.4k
                select_expr.operand().kind_case() !=
909
18.4k
                    cel::ExprKindCase::kUnspecifiedExpr,
910
18.4k
            "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.4k
    if (!select_expr.test_only() && (select_expr.operand().has_ident_expr() ||
919
16.7k
                                     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
671k
      for (size_t i = 0; i < namespace_stack_.size(); i++) {
931
658k
        auto ns = namespace_stack_[i];
932
658k
        namespace_stack_[i] = {
933
658k
            ns.first, absl::StrCat(select_expr.field(), ".", ns.second)};
934
658k
      }
935
13.5k
      namespace_stack_.push_back({&expr, select_expr.field()});
936
13.5k
    } else {
937
4.87k
      namespace_stack_.clear();
938
4.87k
    }
939
18.4k
  }
940
941
  // Select node handler.
942
  // Invoked after child nodes are processed.
943
  void PostVisitSelect(const cel::Expr& expr,
944
18.7k
                       const cel::SelectExpr& select_expr) override {
945
18.7k
    if (!progress_status_.ok()) {
946
619
      return;
947
619
    }
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.1k
    if (resolved_select_expr_) {
954
177
      if (&expr == resolved_select_expr_) {
955
59
        resolved_select_expr_ = nullptr;
956
59
      }
957
177
      return;
958
177
    }
959
960
17.9k
    std::string field = select_expr.field();
961
17.9k
    std::optional<cel::StructType> struct_type;
962
17.9k
    std::optional<cel::StructTypeField> field_type;
963
17.9k
    if (options_.enable_typed_field_access) {
964
17.9k
      std::optional<cel::Type> operand_type =
965
17.9k
          extension_context_.GetResolvedType(select_expr.operand().id());
966
17.9k
      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
17.9k
    }
979
980
17.9k
    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
17.9k
    AddStep(CreateSelectStep(std::move(field), select_expr.test_only(),
990
17.9k
                             options_.enable_empty_wrapper_null_unboxing,
991
17.9k
                             enable_optional_types_),
992
17.9k
            expr.id(), /*stack_delta=*/0);
993
17.9k
  }
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
125k
                    const cel::CallExpr& call_expr) override {
1001
125k
    if (!progress_status_.ok()) {
1002
3.03k
      return;
1003
3.03k
    }
1004
1005
122k
    std::unique_ptr<CondVisitor> cond_visitor;
1006
122k
    if (call_expr.function() == cel::builtin::kAnd) {
1007
1.00k
      cond_visitor = std::make_unique<LogicalCondVisitor>(
1008
1.00k
          this, /*is_or=*/false, options_.short_circuiting);
1009
121k
    } else if (call_expr.function() == cel::builtin::kOr) {
1010
2.40k
      cond_visitor = std::make_unique<LogicalCondVisitor>(
1011
2.40k
          this, /*is_or=*/true, options_.short_circuiting);
1012
119k
    } else if (call_expr.function() == cel::builtin::kTernary) {
1013
3.33k
      if (options_.short_circuiting) {
1014
3.33k
        cond_visitor = std::make_unique<TernaryCondVisitor>(this);
1015
3.33k
      } else {
1016
0
        cond_visitor = std::make_unique<ExhaustiveTernaryCondVisitor>(this);
1017
0
      }
1018
116k
    } 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
116k
    } 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
116k
    } 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
116k
    } else {
1075
116k
      return;
1076
116k
    }
1077
1078
6.73k
    if (cond_visitor) {
1079
6.73k
      cond_visitor->PreVisit(&expr);
1080
6.73k
      cond_visitor_stack_.push({&expr, std::move(cond_visitor)});
1081
6.73k
    }
1082
6.73k
  }
1083
1084
  // Invoked after all child nodes are processed.
1085
  void PostVisitCall(const cel::Expr& expr,
1086
125k
                     const cel::CallExpr& call_expr) override {
1087
125k
    if (!progress_status_.ok()) {
1088
5.37k
      return;
1089
5.37k
    }
1090
1091
120k
    auto cond_visitor = FindCondVisitor(&expr);
1092
120k
    if (cond_visitor) {
1093
6.55k
      cond_visitor->PostVisit(&expr);
1094
6.55k
      cond_visitor_stack_.pop();
1095
6.55k
      return;
1096
6.55k
    }
1097
1098
    // Check if the call is intercepted by a custom handler.
1099
114k
    if (auto handler = call_handlers_.find(call_expr.function());
1100
114k
        handler != call_handlers_.end()) {
1101
34.0k
      CallHandlerResult result = handler->second(expr, call_expr);
1102
34.0k
      if (result == CallHandlerResult::kIntercepted) {
1103
13.5k
        return;
1104
13.5k
      }  // otherwise, apply default function handling.
1105
34.0k
    }
1106
1107
100k
    AddResolvedFunctionStep(&call_expr, &expr, call_expr.function());
1108
100k
  }
1109
1110
  void PreVisitComprehension(
1111
      const cel::Expr& expr,
1112
17.7k
      const cel::ComprehensionExpr& comprehension) override {
1113
17.7k
    if (!progress_status_.ok()) {
1114
289
      return;
1115
289
    }
1116
17.4k
    if (!ValidateOrError(options_.enable_comprehension,
1117
17.4k
                         "Comprehension support is disabled")) {
1118
0
      return;
1119
0
    }
1120
17.4k
    const auto& accu_var = comprehension.accu_var();
1121
17.4k
    const auto& iter_var = comprehension.iter_var();
1122
17.4k
    const auto& iter_var2 = comprehension.iter_var2();
1123
17.4k
    ValidateOrError(!accu_var.empty(),
1124
17.4k
                    "Invalid comprehension: 'accu_var' must not be empty");
1125
17.4k
    ValidateOrError(!iter_var.empty(),
1126
17.4k
                    "Invalid comprehension: 'iter_var' must not be empty");
1127
17.4k
    ValidateOrError(
1128
17.4k
        accu_var != iter_var,
1129
17.4k
        "Invalid comprehension: 'accu_var' must not be the same as 'iter_var'");
1130
17.4k
    ValidateOrError(accu_var != iter_var2,
1131
17.4k
                    "Invalid comprehension: 'accu_var' must not be the same as "
1132
17.4k
                    "'iter_var2'");
1133
17.4k
    ValidateOrError(iter_var2 != iter_var,
1134
17.4k
                    "Invalid comprehension: 'iter_var2' must not be the same "
1135
17.4k
                    "as 'iter_var'");
1136
17.4k
    ValidateOrError(comprehension.has_accu_init(),
1137
17.4k
                    "Invalid comprehension: 'accu_init' must be set");
1138
17.4k
    ValidateOrError(comprehension.has_loop_condition(),
1139
17.4k
                    "Invalid comprehension: 'loop_condition' must be set");
1140
17.4k
    ValidateOrError(comprehension.has_loop_step(),
1141
17.4k
                    "Invalid comprehension: 'loop_step' must be set");
1142
17.4k
    ValidateOrError(comprehension.has_result(),
1143
17.4k
                    "Invalid comprehension: 'result' must be set");
1144
1145
17.4k
    size_t iter_slot, iter2_slot, accu_slot, slot_count;
1146
17.4k
    bool is_bind = IsBind(&comprehension);
1147
1148
17.4k
    if (is_bind) {
1149
0
      accu_slot = iter_slot = iter2_slot = index_manager_.ReserveSlots(1);
1150
0
      slot_count = 1;
1151
17.4k
    } else if (comprehension.iter_var2().empty()) {
1152
17.4k
      iter_slot = iter2_slot = index_manager_.ReserveSlots(2);
1153
17.4k
      accu_slot = iter_slot + 1;
1154
17.4k
      slot_count = 2;
1155
17.4k
    } 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
17.4k
    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
17.4k
    bool in_bind_init = false;
1177
125k
    for (ComprehensionStackRecord& record : comprehension_stack_) {
1178
125k
      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
125k
    }
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
17.4k
    const bool is_stack_releasable =
1191
17.4k
        !is_bind && !in_bind_init && (!block_.has_value() || !block_->in);
1192
1193
17.4k
    if (is_stack_releasable) {
1194
17.4k
      index_manager_.ReserveIterStack();
1195
17.4k
    } else if (!is_bind) {
1196
0
      index_manager_.AddLazyIterStack();
1197
0
    }
1198
1199
17.4k
    comprehension_stack_.push_back(
1200
17.4k
        {&expr, &comprehension, iter_slot, iter2_slot, accu_slot, slot_count,
1201
17.4k
         /*subexpression=*/-1,
1202
         /*.is_optimizable_list_append=*/
1203
17.4k
         IsOptimizableListAppend(&comprehension,
1204
17.4k
                                 options_.enable_comprehension_list_append,
1205
17.4k
                                 options_.short_circuiting),
1206
         /*.is_optimizable_map_insert=*/
1207
17.4k
         IsOptimizableMapInsert(&comprehension,
1208
17.4k
                                options_.enable_comprehension_mutable_map,
1209
17.4k
                                options_.short_circuiting),
1210
17.4k
         /*.is_optimizable_bind=*/is_bind,
1211
17.4k
         /*.is_stack_releasable=*/is_stack_releasable,
1212
17.4k
         /*.iter_var_in_scope=*/false,
1213
17.4k
         /*.iter_var2_in_scope=*/false,
1214
17.4k
         /*.accu_var_in_scope=*/false,
1215
17.4k
         /*.in_accu_init=*/false,
1216
17.4k
         std::make_unique<ComprehensionVisitor>(this, is_bind, iter_slot,
1217
17.4k
                                                iter2_slot, accu_slot)});
1218
17.4k
    comprehension_stack_.back().visitor->PreVisit(&expr);
1219
17.4k
  }
1220
1221
  // Invoked after all child nodes are processed.
1222
  void PostVisitComprehension(
1223
      const cel::Expr& expr,
1224
17.7k
      const cel::ComprehensionExpr& comprehension_expr) override {
1225
17.7k
    if (!progress_status_.ok()) {
1226
1.75k
      return;
1227
1.75k
    }
1228
1229
16.0k
    ComprehensionStackRecord& record = comprehension_stack_.back();
1230
16.0k
    if (comprehension_stack_.empty() ||
1231
16.0k
        record.comprehension != &comprehension_expr) {
1232
0
      return;
1233
0
    }
1234
1235
16.0k
    record.visitor->PostVisit(&expr);
1236
1237
16.0k
    index_manager_.ReleaseSlots(record.slot_count);
1238
16.0k
    if (record.is_stack_releasable) {
1239
16.0k
      ABSL_DCHECK(!record.is_optimizable_bind);
1240
16.0k
      index_manager_.ReleaseIterStack();
1241
16.0k
    }
1242
16.0k
    comprehension_stack_.pop_back();
1243
16.0k
  }
1244
1245
  void PreVisitComprehensionSubexpression(
1246
      const cel::Expr& expr, const cel::ComprehensionExpr& compr,
1247
88.8k
      cel::ComprehensionArg comprehension_arg) override {
1248
88.8k
    if (!progress_status_.ok()) {
1249
7.05k
      return;
1250
7.05k
    }
1251
1252
81.7k
    if (comprehension_stack_.empty() ||
1253
81.7k
        comprehension_stack_.back().comprehension != &compr) {
1254
0
      return;
1255
0
    }
1256
1257
81.7k
    ComprehensionStackRecord& record = comprehension_stack_.back();
1258
1259
81.7k
    switch (comprehension_arg) {
1260
17.4k
      case cel::ITER_RANGE: {
1261
17.4k
        record.in_accu_init = false;
1262
17.4k
        record.iter_var_in_scope = false;
1263
17.4k
        record.iter_var2_in_scope = false;
1264
17.4k
        record.accu_var_in_scope = false;
1265
17.4k
        break;
1266
0
      }
1267
16.0k
      case cel::ACCU_INIT: {
1268
16.0k
        record.in_accu_init = true;
1269
16.0k
        record.iter_var_in_scope = false;
1270
16.0k
        record.iter_var2_in_scope = false;
1271
16.0k
        record.accu_var_in_scope = false;
1272
16.0k
        break;
1273
0
      }
1274
16.0k
      case cel::LOOP_CONDITION: {
1275
16.0k
        record.in_accu_init = false;
1276
16.0k
        record.iter_var_in_scope = true;
1277
16.0k
        record.iter_var2_in_scope = true;
1278
16.0k
        record.accu_var_in_scope = true;
1279
16.0k
        break;
1280
0
      }
1281
16.0k
      case cel::LOOP_STEP: {
1282
16.0k
        record.in_accu_init = false;
1283
16.0k
        record.iter_var_in_scope = true;
1284
16.0k
        record.iter_var2_in_scope = true;
1285
16.0k
        record.accu_var_in_scope = true;
1286
16.0k
        break;
1287
0
      }
1288
16.0k
      case cel::RESULT: {
1289
16.0k
        record.in_accu_init = false;
1290
16.0k
        record.iter_var_in_scope = false;
1291
16.0k
        record.iter_var2_in_scope = false;
1292
16.0k
        record.accu_var_in_scope = true;
1293
16.0k
        break;
1294
0
      }
1295
81.7k
    }
1296
81.7k
  }
1297
1298
  void PostVisitComprehensionSubexpression(
1299
      const cel::Expr& expr, const cel::ComprehensionExpr& compr,
1300
88.8k
      cel::ComprehensionArg comprehension_arg) override {
1301
88.8k
    if (!progress_status_.ok()) {
1302
8.51k
      return;
1303
8.51k
    }
1304
1305
80.3k
    if (comprehension_stack_.empty() ||
1306
80.3k
        comprehension_stack_.back().comprehension != &compr) {
1307
0
      return;
1308
0
    }
1309
1310
80.3k
    SetProgressStatusIfError(comprehension_stack_.back().visitor->PostVisitArg(
1311
80.3k
        comprehension_arg, comprehension_stack_.back().expr));
1312
80.3k
  }
1313
1314
  // Invoked after each argument node processed.
1315
239k
  void PostVisitArg(const cel::Expr& expr, int arg_num) override {
1316
239k
    if (!progress_status_.ok()) {
1317
9.63k
      return;
1318
9.63k
    }
1319
230k
    auto cond_visitor = FindCondVisitor(&expr);
1320
230k
    if (cond_visitor) {
1321
16.5k
      cond_visitor->PostVisitArg(arg_num, &expr);
1322
16.5k
    }
1323
230k
  }
1324
1325
816
  void PostVisitTarget(const cel::Expr& expr) override {
1326
816
    if (!progress_status_.ok()) {
1327
512
      return;
1328
512
    }
1329
304
    auto cond_visitor = FindCondVisitor(&expr);
1330
304
    if (cond_visitor) {
1331
0
      cond_visitor->PostVisitTarget(&expr);
1332
0
    }
1333
304
  }
1334
1335
  // CreateList node handler.
1336
  // Invoked after child nodes are processed.
1337
  void PostVisitList(const cel::Expr& expr,
1338
55.6k
                     const cel::ListExpr& list_expr) override {
1339
55.6k
    if (!progress_status_.ok()) {
1340
3.58k
      return;
1341
3.58k
    }
1342
1343
52.0k
    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
52.0k
    if (!comprehension_stack_.empty()) {
1352
48.9k
      const ComprehensionStackRecord& comprehension =
1353
48.9k
          comprehension_stack_.back();
1354
48.9k
      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
48.9k
    }
1366
52.0k
    absl::flat_hash_set<size_t> optional_indices =
1367
52.0k
        MakeOptionalIndicesSet(list_expr);
1368
52.0k
    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
52.0k
    AddStep(CreateCreateListStep(list_expr.elements().size(),
1376
52.0k
                                 std::move(optional_indices), expr.id()));
1377
52.0k
  }
1378
1379
  // CreateStruct node handler.
1380
  // Invoked after child nodes are processed.
1381
  void PostVisitStruct(const cel::Expr& expr,
1382
3.42k
                       const cel::StructExpr& struct_expr) override {
1383
3.42k
    if (!progress_status_.ok()) {
1384
437
      return;
1385
437
    }
1386
1387
2.98k
    auto status_or_resolved_fields =
1388
2.98k
        ResolveCreateStructFields(struct_expr, expr.id());
1389
2.98k
    if (!status_or_resolved_fields.ok()) {
1390
314
      SetProgressStatusIfError(status_or_resolved_fields.status());
1391
314
      return;
1392
314
    }
1393
2.67k
    std::string resolved_name =
1394
2.67k
        std::move(status_or_resolved_fields.value().first);
1395
2.67k
    std::vector<std::string> fields =
1396
2.67k
        std::move(status_or_resolved_fields.value().second);
1397
1398
2.67k
    size_t num_fields = fields.size();
1399
2.67k
    int64_t stack_delta =
1400
2.67k
        num_fields <= static_cast<size_t>(std::numeric_limits<int64_t>::max())
1401
2.67k
            ? 1 - static_cast<int64_t>(num_fields)
1402
2.67k
            : std::numeric_limits<int16_t>::max();
1403
2.67k
    AddStep(CreateCreateStructStep(std::move(resolved_name), std::move(fields),
1404
2.67k
                                   MakeOptionalIndicesSet(struct_expr)),
1405
2.67k
            expr.id(), stack_delta);
1406
2.67k
  }
1407
1408
  void PostVisitMap(const cel::Expr& expr,
1409
4.26k
                    const cel::MapExpr& map_expr) override {
1410
4.98k
    for (const auto& entry : map_expr.entries()) {
1411
4.98k
      ValidateOrError(entry.has_key(), "Map entry missing key");
1412
4.98k
      ValidateOrError(entry.has_value(), "Map entry missing value");
1413
4.98k
    }
1414
1415
4.26k
    if (!comprehension_stack_.empty()) {
1416
2.68k
      const ComprehensionStackRecord& comprehension =
1417
2.68k
          comprehension_stack_.back();
1418
2.68k
      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.68k
    }
1425
1426
4.26k
    size_t num_entries = map_expr.entries().size();
1427
4.26k
    int64_t stack_delta =
1428
4.26k
        num_entries <=
1429
4.26k
                static_cast<size_t>(std::numeric_limits<int64_t>::max() / 2)
1430
4.26k
            ? 1 - 2 * static_cast<int64_t>(num_entries)
1431
4.26k
            : std::numeric_limits<int16_t>::max();
1432
4.26k
    AddStep(CreateCreateStructStepForMap(num_entries,
1433
4.26k
                                         MakeOptionalIndicesSet(map_expr)),
1434
4.26k
            expr.id(), stack_delta);
1435
4.26k
  }
1436
1437
18.3k
  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
302
      auto status = issue_collector_.AddIssue(RuntimeIssue::CreateWarning(
1475
302
          absl::InvalidArgumentError(
1476
302
              "No overloads provided for FunctionStep creation"),
1477
302
          RuntimeIssue::ErrorCode::kNoMatchingOverload));
1478
302
      if (!status.ok()) {
1479
302
        SetProgressStatusIfError(status);
1480
302
        return;
1481
302
      }
1482
302
    }
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
28.3k
      std::unique_ptr<T> step, int64_t expr_id = -1, int64_t stack_delta = 1) {
1498
28.3k
    if (progress_status_.ok() && !PlanningSuppressed()) {
1499
28.1k
      T* ptr = step.get();
1500
28.1k
      program_builder_.AddStep(ExpressionStep::MakeGenericStep(
1501
28.1k
          std::move(step), expr_id, stack_delta));
1502
28.1k
      return ptr;
1503
28.1k
    }
1504
250
    return nullptr;
1505
28.3k
  }
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
28.3k
      std::unique_ptr<T> step, int64_t expr_id = -1, int64_t stack_delta = 1) {
1498
28.3k
    if (progress_status_.ok() && !PlanningSuppressed()) {
1499
28.1k
      T* ptr = step.get();
1500
28.1k
      program_builder_.AddStep(ExpressionStep::MakeGenericStep(
1501
28.1k
          std::move(step), expr_id, stack_delta));
1502
28.1k
      return ptr;
1503
28.1k
    }
1504
250
    return nullptr;
1505
28.3k
  }
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
25.7k
      int64_t stack_delta = 1) {
1511
25.7k
    if (step.ok()) {
1512
25.7k
      return AddStep(*std::move(step), expr_id, stack_delta);
1513
25.7k
    } else {
1514
0
      SetProgressStatusIfError(step.status());
1515
0
    }
1516
0
    return nullptr;
1517
25.7k
  }
1518
1519
510k
  ExpressionStep* AddStep(ExpressionStep step) {
1520
510k
    if (progress_status_.ok() && !PlanningSuppressed()) {
1521
510k
      return program_builder_.AddStep(std::move(step));
1522
510k
    }
1523
0
    return nullptr;
1524
510k
  }
1525
1526
80.9k
  void SetProgressStatusIfError(const absl::Status& status) {
1527
80.9k
    if (progress_status_.ok() && !status.ok()) {
1528
630
      progress_status_ = status;
1529
630
    }
1530
80.9k
  }
1531
1532
  // Index of the next step to be inserted, in terms of the current
1533
  // subexpression
1534
167k
  ProgramStepIndex GetCurrentIndex() const {
1535
    // Nonnull while active -- nullptr indicates logic error in the builder.
1536
167k
    ABSL_DCHECK(program_builder_.current() != nullptr);
1537
167k
    return {static_cast<int>(program_builder_.current()->elements().size()),
1538
167k
            program_builder_.current()};
1539
167k
  }
1540
1541
351k
  CondVisitor* FindCondVisitor(const cel::Expr* expr) const {
1542
351k
    if (cond_visitor_stack_.empty()) {
1543
255k
      return nullptr;
1544
255k
    }
1545
1546
95.6k
    const auto& latest = cond_visitor_stack_.top();
1547
1548
95.6k
    return (latest.first == expr) ? latest.second.get() : nullptr;
1549
351k
  }
1550
1551
0
  IndexManager& index_manager() { return index_manager_; }
1552
1553
17.0k
  size_t slot_count() const { return index_manager_.max_slot_count(); }
1554
1555
17.0k
  size_t iter_stack_count() const {
1556
17.0k
    return index_manager_.IterStackRequirement();
1557
17.0k
  }
1558
1559
17.0k
  IdentifierTable BuildIdentifierTable(size_t& total_slot_count) && {
1560
17.0k
    IdentifierTable table;
1561
17.0k
    table.reserve(identifiers_.size());
1562
22.4k
    for (std::string& name : identifiers_) {
1563
22.4k
      table.push_back(Identifier{std::move(name), total_slot_count++});
1564
22.4k
    }
1565
17.0k
    return table;
1566
17.0k
  }
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
838k
                       MP... message_parts) {
1578
838k
    if (valid_expression) {
1579
838k
      return true;
1580
838k
    }
1581
14
    SetProgressStatusIfError(absl::InvalidArgumentError(
1582
14
        absl::StrCat(error_message, message_parts...)));
1583
14
    return false;
1584
838k
  }
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
838k
                       MP... message_parts) {
1578
838k
    if (valid_expression) {
1579
838k
      return true;
1580
838k
    }
1581
14
    SetProgressStatusIfError(absl::InvalidArgumentError(
1582
14
        absl::StrCat(error_message, message_parts...)));
1583
14
    return false;
1584
838k
  }
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
594k
  bool PlanningSuppressed() const {
1640
594k
    return resume_from_suppressed_branch_ != nullptr;
1641
594k
  }
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
2.98k
                            int64_t expr_id) {
1666
2.98k
    absl::string_view ast_name = create_struct_expr.name();
1667
1668
2.98k
    std::optional<std::pair<std::string, cel::Type>> type;
1669
2.98k
    CEL_ASSIGN_OR_RETURN(type, resolver_.FindType(ast_name, expr_id));
1670
1671
2.98k
    if (!type.has_value()) {
1672
262
      return absl::InvalidArgumentError(absl::StrCat(
1673
262
          "Invalid struct creation: missing type info for '", ast_name, "'"));
1674
262
    }
1675
1676
2.72k
    std::string resolved_name = std::move(type).value().first;
1677
1678
2.72k
    std::vector<std::string> fields;
1679
2.72k
    fields.reserve(create_struct_expr.fields().size());
1680
2.72k
    for (const auto& entry : create_struct_expr.fields()) {
1681
1.37k
      if (entry.name().empty()) {
1682
0
        return absl::InvalidArgumentError("Struct field missing name");
1683
0
      }
1684
1.37k
      if (!entry.has_value()) {
1685
0
        return absl::InvalidArgumentError("Struct field missing value");
1686
0
      }
1687
2.75k
      CEL_ASSIGN_OR_RETURN(auto field, type_provider_.FindStructTypeFieldByName(
1688
2.75k
                                           resolved_name, entry.name()));
1689
2.75k
      if (!field.has_value()) {
1690
52
        return absl::InvalidArgumentError(
1691
52
            absl::StrCat("Invalid message creation: field '", entry.name(),
1692
52
                         "' not found in '", resolved_name, "'"));
1693
52
      }
1694
1.32k
      fields.push_back(entry.name());
1695
1.32k
    }
1696
1697
2.67k
    return std::make_pair(std::move(resolved_name), std::move(fields));
1698
2.72k
  }
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
2.85k
    const cel::Expr& expr, const cel::CallExpr& call_expr) {
1757
2.85k
  ABSL_DCHECK(call_expr.function() == cel::builtin::kIndex);
1758
2.85k
  if (!ValidateOrError(
1759
2.85k
          (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
2.85k
          "unexpected number of args for builtin index operator")) {
1764
0
    return CallHandlerResult::kIntercepted;
1765
0
  }
1766
1767
2.85k
  AddStep(CreateContainerAccessStep(call_expr, enable_optional_types_),
1768
2.85k
          expr.id(), /*stack_delta=*/-1);
1769
2.85k
  return CallHandlerResult::kIntercepted;
1770
2.85k
}
1771
1772
FlatExprVisitor::CallHandlerResult FlatExprVisitor::HandleNot(
1773
668
    const cel::Expr& expr, const cel::CallExpr& call_expr) {
1774
668
  ABSL_DCHECK(call_expr.function() == cel::builtin::kNot);
1775
1776
668
  if (!ValidateOrError(call_expr.args().size() == 1 && !call_expr.has_target(),
1777
668
                       "unexpected number of args for builtin not operator")) {
1778
0
    return CallHandlerResult::kIntercepted;
1779
0
  }
1780
1781
668
  AddStep(ExpressionStep::MakeBooleanNotStep(expr.id()));
1782
668
  return CallHandlerResult::kIntercepted;
1783
668
}
1784
1785
FlatExprVisitor::CallHandlerResult FlatExprVisitor::HandleNotStrictlyFalse(
1786
125
    const cel::Expr& expr, const cel::CallExpr& call_expr) {
1787
125
  if (!ValidateOrError(call_expr.args().size() == 1 && !call_expr.has_target(),
1788
125
                       "unexpected number of args for builtin "
1789
125
                       "not_strictly_false operator")) {
1790
0
    return CallHandlerResult::kIntercepted;
1791
0
  }
1792
1793
125
  AddStep(ExpressionStep::MakeNotStrictlyFalseStep(expr.id()));
1794
125
  return CallHandlerResult::kIntercepted;
1795
125
}
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
20.5k
    const cel::Expr& expr, const cel::CallExpr& call_expr) {
1822
20.5k
  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
20.5k
  if (!comprehension_stack_.empty() &&
1827
18.0k
      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
20.5k
  return CallHandlerResult::kNotIntercepted;
1852
20.5k
}
1853
1854
FlatExprVisitor::CallHandlerResult FlatExprVisitor::HandleHeterogeneousEquality(
1855
8.33k
    const cel::Expr& expr, const cel::CallExpr& call, bool inequality) {
1856
8.33k
  if (!ValidateOrError(
1857
8.33k
          call.args().size() == 2 && !call.has_target(),
1858
8.33k
          "unexpected number of args for builtin equality operator")) {
1859
0
    return CallHandlerResult::kIntercepted;
1860
0
  }
1861
1862
8.33k
  AddStep(inequality ? ExpressionStep::MakeFastNotEqualStep(expr.id())
1863
8.33k
                     : ExpressionStep::MakeFastEqualStep(expr.id()));
1864
8.33k
  return CallHandlerResult::kIntercepted;
1865
8.33k
}
1866
1867
FlatExprVisitor::CallHandlerResult
1868
FlatExprVisitor::HandleHeterogeneousEqualityIn(const cel::Expr& expr,
1869
1.58k
                                               const cel::CallExpr& call) {
1870
1.58k
  if (!ValidateOrError(call.args().size() == 2 && !call.has_target(),
1871
1.58k
                       "unexpected number of args for builtin 'in' operator")) {
1872
14
    return CallHandlerResult::kIntercepted;
1873
14
  }
1874
1875
1.57k
  AddStep(ExpressionStep::MakeFastInStep(expr.id()));
1876
1.57k
  return CallHandlerResult::kIntercepted;
1877
1.58k
}
1878
1879
472k
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
472k
  auto it = type_map_.find(expr.id());
1884
472k
  if (it == type_map_.end()) {
1885
472k
    return;
1886
472k
  }
1887
0
  extension_context_.TryResolveType(expr.id(), it->second);
1888
0
}
1889
1890
56.4k
size_t FlatExprVisitor::AddOrUpdateIdentifier(absl::string_view name) {
1891
56.4k
  auto it = identifier_map_.find(name);
1892
56.4k
  if (it == identifier_map_.end()) {
1893
23.6k
    size_t index = identifiers_.size();
1894
23.6k
    it = identifier_map_.emplace(name, index).first;
1895
23.6k
    identifiers_.push_back(std::string(name));
1896
23.6k
  }
1897
56.4k
  return it->second;
1898
56.4k
}
1899
1900
3.40k
void LogicalCondVisitor::PreVisit(const cel::Expr* expr) {
1901
3.40k
  visitor_->ValidateOrError(
1902
3.40k
      !expr->call_expr().has_target() && expr->call_expr().args().size() >= 2,
1903
3.40k
      "Invalid argument count for a binary function call.");
1904
3.40k
}
1905
1906
6.60k
void LogicalCondVisitor::PostVisitArg(int arg_num, const cel::Expr* expr) {
1907
6.60k
  const int last_arg_index = expr->call_expr().args().size() - 1;
1908
6.60k
  const size_t num_args = expr->call_expr().args().size();
1909
6.60k
  if (arg_num == last_arg_index) {
1910
3.29k
    if (is_or_) {
1911
2.31k
      visitor_->AddStep(
1912
2.31k
          ExpressionStep::MakeBooleanOrStep(num_args, expr->id()));
1913
2.31k
    } else {
1914
980
      visitor_->AddStep(
1915
980
          ExpressionStep::MakeBooleanAndStep(num_args, expr->id()));
1916
980
    }
1917
3.29k
    if (short_circuiting_ && !jump_steps_.empty()) {
1918
3.29k
      ProgramStepIndex target = visitor_->GetCurrentIndex();
1919
3.29k
      for (const ProgramStepIndex& jump_pos : jump_steps_) {
1920
3.29k
        absl::StatusOr<int> offset = Jump::CalculateOffset(jump_pos, target);
1921
3.29k
        if (!offset.ok()) {
1922
0
          visitor_->SetProgressStatusIfError(offset.status());
1923
0
          continue;
1924
0
        }
1925
3.29k
        ExpressionStep* step =
1926
3.29k
            jump_pos.subexpression->GetIfExpressionStep(jump_pos.index);
1927
3.29k
        BoolJumpStepInfo* jump_info = GetIfBoolJumpStep(step);
1928
3.29k
        if (jump_info != nullptr) {
1929
3.29k
          jump_info->set = true;
1930
3.29k
          jump_info->offset = *offset;
1931
3.29k
        }
1932
3.29k
      }
1933
3.29k
    }
1934
3.29k
  }
1935
6.60k
  if (short_circuiting_ && arg_num < last_arg_index) {
1936
3.30k
    ProgramStepIndex index = visitor_->GetCurrentIndex();
1937
3.30k
    visitor_->AddStep(is_or_ ? ExpressionStep::MakeBooleanOrJumpStep(
1938
2.31k
                                   /*arg_count=*/arg_num + 1)
1939
3.30k
                             : ExpressionStep::MakeBooleanAndJumpStep(
1940
988
                                   /*arg_count=*/arg_num + 1));
1941
3.30k
    jump_steps_.push_back(index);
1942
3.30k
  }
1943
6.60k
}
1944
1945
3.29k
void LogicalCondVisitor::PostVisit(const cel::Expr* expr) {
1946
3.29k
}
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
3.33k
void TernaryCondVisitor::PreVisit(const cel::Expr* expr) {
1984
3.33k
  visitor_->ValidateOrError(
1985
3.33k
      !expr->call_expr().has_target() && expr->call_expr().args().size() == 3,
1986
3.33k
      "Invalid argument count for a ternary function call.");
1987
3.33k
}
1988
1989
9.90k
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
9.90k
  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
3.32k
    cond_jump_pos_ = visitor_->GetCurrentIndex();
2006
3.32k
    visitor_->AddStep(ExpressionStep::MakeTernaryJumpStep());
2007
6.57k
  } else if (arg_num == 1) {
2008
    // Jump after the first and over the second branch of execution.
2009
3.31k
    jump_after_first_pos_ = visitor_->GetCurrentIndex();
2010
3.31k
    visitor_->AddStep(ExpressionStep::MakeFixedJumpStep());
2011
2012
3.31k
    ExpressionStep* cond_step =
2013
3.31k
        cond_jump_pos_.has_value()
2014
3.31k
            ? cond_jump_pos_->subexpression->GetIfExpressionStep(
2015
3.31k
                  cond_jump_pos_->index)
2016
3.31k
            : nullptr;
2017
3.31k
    TernaryJumpStepInfo* ternary_info = GetIfTernaryJumpStep(cond_step);
2018
3.31k
    if (!visitor_->ValidateOrError(
2019
3.31k
            ternary_info != nullptr,
2020
3.31k
            "Error configuring ternary operator: jump_to_second_ is null")) {
2021
0
      return;
2022
0
    }
2023
2024
3.31k
    absl::StatusOr<int> offset =
2025
3.31k
        Jump::CalculateOffset(*cond_jump_pos_, visitor_->GetCurrentIndex());
2026
3.31k
    if (!offset.ok()) {
2027
0
      visitor_->SetProgressStatusIfError(offset.status());
2028
0
      return;
2029
0
    }
2030
2031
3.31k
    ternary_info->jump_to_second_offset = *offset;
2032
3.31k
  }
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
9.90k
}
2037
2038
3.25k
void TernaryCondVisitor::PostVisit(const cel::Expr* expr) {
2039
  // Determine and set jump offset in jump instruction.
2040
3.25k
  ExpressionStep* cond_step =
2041
3.25k
      cond_jump_pos_.has_value()
2042
3.25k
          ? cond_jump_pos_->subexpression->GetIfExpressionStep(
2043
3.25k
                cond_jump_pos_->index)
2044
3.25k
          : nullptr;
2045
3.25k
  TernaryJumpStepInfo* ternary_info = GetIfTernaryJumpStep(cond_step);
2046
3.25k
  if (visitor_->ValidateOrError(
2047
3.25k
          ternary_info != nullptr,
2048
3.25k
          "Error configuring ternary operator: error_jump_ is null")) {
2049
3.25k
    absl::StatusOr<int> offset =
2050
3.25k
        Jump::CalculateOffset(*cond_jump_pos_, visitor_->GetCurrentIndex());
2051
3.25k
    if (!offset.ok()) {
2052
0
      visitor_->SetProgressStatusIfError(offset.status());
2053
3.25k
    } else {
2054
3.25k
      ternary_info->set = true;
2055
3.25k
      ternary_info->error_offset = *offset;
2056
3.25k
    }
2057
3.25k
  }
2058
3.25k
  ExpressionStep* jump_after_first_step =
2059
3.25k
      jump_after_first_pos_.has_value()
2060
3.25k
          ? jump_after_first_pos_->subexpression->GetIfExpressionStep(
2061
3.25k
                jump_after_first_pos_->index)
2062
3.25k
          : nullptr;
2063
3.25k
  FixedJumpStepInfo* fixed_info = GetIfFixedJumpStep(jump_after_first_step);
2064
3.25k
  if (visitor_->ValidateOrError(
2065
3.25k
          fixed_info != nullptr,
2066
3.25k
          "Error configuring ternary operator: jump_after_first_ is null")) {
2067
3.25k
    absl::StatusOr<int> offset = Jump::CalculateOffset(
2068
3.25k
        *jump_after_first_pos_, visitor_->GetCurrentIndex());
2069
3.25k
    if (!offset.ok()) {
2070
0
      visitor_->SetProgressStatusIfError(offset.status());
2071
3.25k
    } else {
2072
3.25k
      fixed_info->set = true;
2073
3.25k
      fixed_info->offset = *offset;
2074
3.25k
    }
2075
3.25k
  }
2076
3.25k
}
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
17.4k
void ComprehensionVisitor::PreVisit(const cel::Expr* expr) {
2089
17.4k
  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
17.4k
}
2095
2096
16.0k
ComprehensionInitStepInfo* absl_nullable ComprehensionVisitor::GetInitStep() {
2097
16.0k
  if (!init_step_pos_) {
2098
0
    return nullptr;
2099
0
  }
2100
16.0k
  ExpressionStep* step =
2101
16.0k
      init_step_pos_->subexpression->GetIfExpressionStep(init_step_pos_->index);
2102
16.0k
  if (!step) {
2103
0
    return nullptr;
2104
0
  }
2105
16.0k
  return GetIfComprehensionInitStep(*step);
2106
16.0k
}
2107
2108
32.0k
ComprehensionCondStepInfo* absl_nullable ComprehensionVisitor::GetCondStep() {
2109
32.0k
  if (!cond_step_pos_) {
2110
0
    return nullptr;
2111
0
  }
2112
32.0k
  ExpressionStep* step =
2113
32.0k
      cond_step_pos_->subexpression->GetIfExpressionStep(cond_step_pos_->index);
2114
32.0k
  if (!step) {
2115
0
    return nullptr;
2116
0
  }
2117
32.0k
  return GetIfComprehensionCondStep(*step);
2118
32.0k
}
2119
2120
32.0k
ComprehensionNextStepInfo* absl_nullable ComprehensionVisitor::GetNextStep() {
2121
32.0k
  if (!next_step_pos_) {
2122
0
    return nullptr;
2123
0
  }
2124
32.0k
  ExpressionStep* step =
2125
32.0k
      next_step_pos_->subexpression->GetIfExpressionStep(next_step_pos_->index);
2126
32.0k
  if (!step) {
2127
0
    return nullptr;
2128
0
  }
2129
32.0k
  return GetIfComprehensionNextStep(*step);
2130
32.0k
}
2131
2132
absl::Status ComprehensionVisitor::PostVisitArgDefault(
2133
80.3k
    cel::ComprehensionArg arg_num, const cel::Expr* expr) {
2134
80.3k
  switch (arg_num) {
2135
16.0k
    case cel::ITER_RANGE: {
2136
16.0k
      init_step_pos_ = visitor_->GetCurrentIndex();
2137
16.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
16.0k
      } else {
2143
16.0k
        ABSL_DCHECK_EQ(accu_slot_, iter_slot_ + 1);
2144
16.0k
        visitor_->AddStep(ExpressionStep::MakeComprehensionInitStep(
2145
16.0k
            static_cast<uint32_t>(iter_slot_), ComprehensionVersion::kV1));
2146
16.0k
      }
2147
16.0k
      break;
2148
0
    }
2149
16.0k
    case cel::ACCU_INIT: {
2150
16.0k
      next_step_pos_ = visitor_->GetCurrentIndex();
2151
16.0k
      if (iter_slot_ != iter2_slot_) {
2152
0
        visitor_->AddStep(ExpressionStep::MakeComprehensionNext2Step());
2153
16.0k
      } else {
2154
16.0k
        visitor_->AddStep(ExpressionStep::MakeComprehensionNextStep());
2155
16.0k
      }
2156
16.0k
      break;
2157
0
    }
2158
16.0k
    case cel::LOOP_CONDITION: {
2159
16.0k
      cond_step_pos_ = visitor_->GetCurrentIndex();
2160
16.0k
      if (iter_slot_ != iter2_slot_) {
2161
0
        visitor_->AddStep(ExpressionStep::MakeComprehensionCond2Step());
2162
16.0k
      } else {
2163
16.0k
        visitor_->AddStep(ExpressionStep::MakeComprehensionCondStep());
2164
16.0k
      }
2165
16.0k
      break;
2166
0
    }
2167
16.0k
    case cel::LOOP_STEP: {
2168
16.0k
      ProgramStepIndex index = visitor_->GetCurrentIndex();
2169
16.0k
      ExpressionStep* jump_step =
2170
16.0k
          visitor_->AddStep(ExpressionStep::MakeFixedJumpStep());
2171
16.0k
      FixedJumpStepInfo* fixed_info = GetIfFixedJumpStep(jump_step);
2172
16.0k
      if (fixed_info == nullptr) {
2173
        // either an error occurred earlier or planning is suppressed.
2174
0
        break;
2175
0
      }
2176
32.0k
      CEL_ASSIGN_OR_RETURN(int offset,
2177
32.0k
                           Jump::CalculateOffset(index, *next_step_pos_));
2178
32.0k
      fixed_info->set = true;
2179
32.0k
      fixed_info->offset = offset;
2180
2181
      // Set offsets jumping to the result step.
2182
32.0k
      if (auto* cond_step = GetCondStep(); cond_step != nullptr) {
2183
16.0k
        CEL_ASSIGN_OR_RETURN(int jump_from_cond,
2184
16.0k
                             Jump::CalculateOffset(
2185
16.0k
                                 *cond_step_pos_, visitor_->GetCurrentIndex()));
2186
16.0k
        cond_step->set_jump_offset(jump_from_cond);
2187
16.0k
      } else {
2188
0
        return absl::InvalidArgumentError("Comprehension is malformed");
2189
0
      }
2190
2191
16.0k
      if (auto* next_step = GetNextStep(); next_step != nullptr) {
2192
16.0k
        CEL_ASSIGN_OR_RETURN(int jump_from_next,
2193
16.0k
                             Jump::CalculateOffset(
2194
16.0k
                                 *next_step_pos_, visitor_->GetCurrentIndex()));
2195
2196
16.0k
        next_step->set_jump_offset(jump_from_next);
2197
16.0k
      } else {
2198
0
        return absl::InvalidArgumentError("Comprehension is malformed");
2199
0
      }
2200
16.0k
      break;
2201
16.0k
    }
2202
16.0k
    case cel::RESULT: {
2203
16.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
16.0k
      visitor_->AddStep(
2208
16.0k
          ExpressionStep::MakeComprehensionFinishStep(accu_slot_, expr->id()));
2209
      // Set offsets jumping past the result step in case of errors.
2210
16.0k
      if (auto* init_step = GetInitStep(); init_step != nullptr) {
2211
16.0k
        CEL_ASSIGN_OR_RETURN(int jump_from_init,
2212
16.0k
                             Jump::CalculateOffset(
2213
16.0k
                                 *init_step_pos_, visitor_->GetCurrentIndex()));
2214
16.0k
        init_step->set_error_jump_offset(jump_from_init);
2215
16.0k
      } else {
2216
0
        return absl::InvalidArgumentError("Comprehension is malformed");
2217
0
      }
2218
2219
16.0k
      if (auto* next_step = GetNextStep(); next_step != nullptr) {
2220
16.0k
        CEL_ASSIGN_OR_RETURN(int jump_from_next,
2221
16.0k
                             Jump::CalculateOffset(
2222
16.0k
                                 *next_step_pos_, visitor_->GetCurrentIndex()));
2223
16.0k
        next_step->set_error_jump_offset(jump_from_next);
2224
16.0k
      } else {
2225
0
        return absl::InvalidArgumentError("Comprehension is malformed");
2226
0
      }
2227
2228
16.0k
      if (auto* cond_step = GetCondStep(); cond_step != nullptr) {
2229
16.0k
        CEL_ASSIGN_OR_RETURN(int jump_from_cond,
2230
16.0k
                             Jump::CalculateOffset(
2231
16.0k
                                 *cond_step_pos_, visitor_->GetCurrentIndex()));
2232
16.0k
        cond_step->set_error_jump_offset(jump_from_cond);
2233
16.0k
      } else {
2234
0
        return absl::InvalidArgumentError("Comprehension is malformed");
2235
0
      }
2236
16.0k
      break;
2237
16.0k
    }
2238
80.3k
  }
2239
80.3k
  return absl::OkStatus();
2240
80.3k
}
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
16.0k
void ComprehensionVisitor::PostVisit(const cel::Expr* expr) {
2269
16.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
17.0k
    ProgramBuilder& program_builder, ExecutionPath& main) {
2275
17.0k
  std::vector<std::pair<size_t, size_t>> ranges;
2276
17.0k
  main = program_builder.FlattenMain();
2277
17.0k
  ranges.push_back(std::make_pair(0, main.size()));
2278
2279
17.0k
  std::vector<ExecutionPath> subexpressions =
2280
17.0k
      program_builder.FlattenSubexpressions();
2281
17.0k
  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
17.0k
  std::vector<ExecutionPathView> subexpression_indexes;
2287
17.0k
  subexpression_indexes.reserve(ranges.size());
2288
17.0k
  for (const auto& range : ranges) {
2289
17.0k
    subexpression_indexes.push_back(
2290
17.0k
        absl::MakeSpan(main).subspan(range.first, range.second));
2291
17.0k
  }
2292
17.0k
  return subexpression_indexes;
2293
17.0k
}
2294
2295
std::optional<int64_t> CheckedDeltaAdd(int64_t current,
2296
512k
                                       std::optional<int64_t> delta) {
2297
512k
  if (!delta.has_value()) {
2298
0
    return std::nullopt;
2299
0
  }
2300
512k
  if (*delta > 0 && current > std::numeric_limits<int64_t>::max() - *delta) {
2301
0
    return std::nullopt;
2302
0
  }
2303
512k
  if (*delta < 0 && current < std::numeric_limits<int64_t>::min() - *delta) {
2304
0
    return std::nullopt;
2305
0
  }
2306
512k
  current += *delta;
2307
512k
  if (current < 0) {
2308
0
    return std::nullopt;
2309
0
  }
2310
512k
  return current;
2311
512k
}
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
17.0k
                            size_t fallback_size) {
2320
17.0k
  size_t total_max_stack = 0;
2321
17.0k
  for (ExecutionPathView path : subexpressions) {
2322
17.0k
    int64_t current = 0;
2323
17.0k
    int64_t max_depth = 0;
2324
512k
    for (const ExpressionStep& step : path) {
2325
512k
      std::optional<int64_t> next = CheckedDeltaAdd(current, step.StackDelta());
2326
512k
      if (!next.has_value()) {
2327
0
        return fallback_size;
2328
0
      }
2329
512k
      current = *next;
2330
512k
      max_depth = std::max(max_depth, current);
2331
512k
    }
2332
17.0k
    if (static_cast<uint64_t>(max_depth) >
2333
17.0k
        std::numeric_limits<size_t>::max() - total_max_stack) {
2334
0
      return fallback_size;
2335
0
    }
2336
17.0k
    total_max_stack += static_cast<size_t>(max_depth);
2337
17.0k
  }
2338
17.0k
  return total_max_stack;
2339
17.0k
}
2340
2341
absl::Status CheckAstExtensions(
2342
    const std::vector<cel::ExtensionSpec>& extensions,
2343
17.7k
    bool enable_select_optimization) {
2344
17.7k
  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
17.7k
  return absl::OkStatus();
2360
17.7k
}
2361
2362
}  // namespace
2363
2364
absl::StatusOr<FlatExpression> FlatExprBuilder::CreateExpressionImpl(
2365
17.7k
    std::unique_ptr<Ast> ast, std::vector<RuntimeIssue>* issues) const {
2366
17.7k
  if (absl::StartsWith(container_, ".") || absl::EndsWith(container_, ".")) {
2367
0
    return absl::InvalidArgumentError(
2368
0
        absl::StrCat("Invalid expression container: '", container_, "'"));
2369
0
  }
2370
2371
17.7k
  RuntimeIssue::Severity max_severity = options_.fail_on_warnings
2372
17.7k
                                            ? RuntimeIssue::Severity::kWarning
2373
17.7k
                                            : RuntimeIssue::Severity::kError;
2374
17.7k
  IssueCollector issue_collector(max_severity);
2375
17.7k
  auto record_issues = absl::MakeCleanup([issues, &issue_collector] {
2376
17.7k
    if (issues == nullptr) {
2377
17.7k
      return;
2378
17.7k
    }
2379
0
    *issues = issue_collector.ExtractIssues();
2380
0
  });
2381
2382
17.7k
  absl::StatusOr<std::vector<cel::ExtensionSpec>> runtime_extensions =
2383
17.7k
      ExtractAndValidateRuntimeExtensions(*ast);
2384
2385
17.7k
  if (!runtime_extensions.ok()) {
2386
0
    CEL_RETURN_IF_ERROR(issue_collector.AddIssue(
2387
0
        RuntimeIssue::CreateError(runtime_extensions.status())));
2388
17.7k
  } else {
2389
17.7k
    absl::Status status =
2390
17.7k
        CheckAstExtensions(*runtime_extensions, enable_select_optimization_);
2391
17.7k
    if (!status.ok()) {
2392
0
      CEL_RETURN_IF_ERROR(
2393
0
          issue_collector.AddIssue(RuntimeIssue::CreateError(status)));
2394
0
    }
2395
17.7k
  }
2396
2397
17.7k
  Resolver resolver(container_, function_registry_, type_registry_,
2398
17.7k
                    GetTypeProvider(),
2399
17.7k
                    options_.enable_qualified_type_identifiers);
2400
2401
17.7k
  std::shared_ptr<google::protobuf::Arena> arena;
2402
17.7k
  ProgramBuilder program_builder;
2403
17.7k
  PlannerContext extension_context(env_, resolver, options_, GetTypeProvider(),
2404
17.7k
                                   issue_collector, program_builder, arena);
2405
2406
17.7k
  for (const std::unique_ptr<AstTransform>& transform : ast_transforms_) {
2407
17.7k
    CEL_RETURN_IF_ERROR(transform->UpdateAst(extension_context, *ast));
2408
17.7k
  }
2409
2410
17.7k
  std::vector<std::unique_ptr<ProgramOptimizer>> optimizers;
2411
17.7k
  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
17.7k
  FlatExprVisitor visitor(resolver, options_, std::move(optimizers),
2422
17.7k
                          ast->type_map(), GetTypeProvider(), issue_collector,
2423
17.7k
                          program_builder, extension_context,
2424
17.7k
                          enable_optional_types_);
2425
2426
17.7k
  cel::TraversalOptions opts;
2427
17.7k
  opts.use_comprehension_callbacks = true;
2428
17.7k
  AstTraverse(ast->root_expr(), visitor, opts);
2429
2430
17.7k
  if (!visitor.progress_status().ok()) {
2431
630
    return visitor.progress_status();
2432
630
  }
2433
2434
17.0k
  size_t total_slot_count = visitor.slot_count();
2435
17.0k
  size_t iterator_stack_size = visitor.iter_stack_count();
2436
17.0k
  IdentifierTable identifiers =
2437
17.0k
      std::move(visitor).BuildIdentifierTable(total_slot_count);
2438
2439
17.0k
  if (total_slot_count > std::numeric_limits<uint32_t>::max() ||
2440
17.0k
      program_builder.ExtractedSubexpressionCount() >
2441
17.0k
          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
17.0k
  ExecutionPath execution_path;
2449
17.0k
  std::vector<ExecutionPathView> subexpressions =
2450
17.0k
      FlattenExpressionTable(program_builder, execution_path);
2451
17.0k
  size_t value_stack_size =
2452
17.0k
      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
512k
  for (ExpressionStep& step : execution_path) {
2458
512k
    if (IdentStepInfo* ident_step = GetIfIdentStep(step);
2459
512k
        ident_step != nullptr) {
2460
51.8k
      ident_step->slot_index = static_cast<uint32_t>(
2461
51.8k
          identifiers[ident_step->ident_index].slot_index);
2462
51.8k
    }
2463
512k
  }
2464
2465
17.0k
  return FlatExpression(std::move(execution_path), std::move(subexpressions),
2466
17.0k
                        total_slot_count, iterator_stack_size,
2467
17.0k
                        GetTypeProvider(), options_, std::move(arena),
2468
17.0k
                        std::move(identifiers), value_stack_size);
2469
17.0k
}
2470
70.1k
const cel::TypeProvider& FlatExprBuilder::GetTypeProvider() const {
2471
70.1k
  return use_legacy_type_provider_
2472
70.1k
             ? static_cast<const cel::TypeProvider&>(
2473
70.1k
                   GetLegacyRuntimeTypeProvider(type_registry_))
2474
70.1k
             : GetRuntimeTypeProvider(type_registry_);
2475
70.1k
}
2476
2477
}  // namespace google::api::expr::runtime