Coverage Report

Created: 2026-11-12 06:42

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/proc/self/cwd/eval/compiler/constant_folding.cc
Line
Count
Source
1
// Copyright 2019 Google LLC
2
//
3
// Licensed under the Apache License, Version 2.0 (the "License");
4
// you may not use this file except in compliance with the License.
5
// You may obtain a copy of the License at
6
//
7
//     https://www.apache.org/licenses/LICENSE-2.0
8
//
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
// See the License for the specific language governing permissions and
13
// limitations under the License.
14
15
#include "eval/compiler/constant_folding.h"
16
17
#include <cstddef>
18
#include <memory>
19
#include <utility>
20
#include <vector>
21
22
#include "absl/base/nullability.h"
23
#include "absl/status/status.h"
24
#include "absl/status/statusor.h"
25
#include "base/builtins.h"
26
#include "base/type_provider.h"
27
#include "common/ast.h"
28
#include "common/constant.h"
29
#include "common/expr.h"
30
#include "common/value.h"
31
#include "eval/compiler/flat_expr_builder_extensions.h"
32
#include "eval/compiler/resolver.h"
33
#include "eval/eval/evaluator_core.h"
34
#include "internal/status_macros.h"
35
#include "runtime/activation.h"
36
#include "runtime/internal/convert_constant.h"
37
#include "google/protobuf/arena.h"
38
#include "google/protobuf/descriptor.h"
39
#include "google/protobuf/message.h"
40
41
namespace cel::runtime_internal {
42
43
namespace {
44
45
using ::cel::Expr;
46
using ::cel::builtin::kAnd;
47
using ::cel::builtin::kOr;
48
using ::cel::builtin::kTernary;
49
using ::cel::runtime_internal::ConvertConstant;
50
using ::google::api::expr::runtime::EvaluationListener;
51
using ::google::api::expr::runtime::ExecutionFrame;
52
using ::google::api::expr::runtime::ExecutionPath;
53
using ::google::api::expr::runtime::ExecutionPathView;
54
using ::google::api::expr::runtime::ExpressionStep;
55
using ::google::api::expr::runtime::FlatExpressionEvaluatorState;
56
using ::google::api::expr::runtime::PlannerContext;
57
using ::google::api::expr::runtime::ProgramOptimizer;
58
using ::google::api::expr::runtime::ProgramOptimizerFactory;
59
using ::google::api::expr::runtime::Resolver;
60
61
enum class IsConst {
62
  kConditional,
63
  kNonConst,
64
};
65
66
class ConstantFoldingExtension : public ProgramOptimizer {
67
 public:
68
  ConstantFoldingExtension(
69
      const google::protobuf::DescriptorPool* absl_nonnull descriptor_pool,
70
      absl_nullable std::shared_ptr<google::protobuf::Arena> shared_arena,
71
      google::protobuf::Arena* absl_nonnull arena,
72
      absl_nullable std::shared_ptr<google::protobuf::MessageFactory>
73
          shared_message_factory,
74
      google::protobuf::MessageFactory* absl_nonnull message_factory,
75
      const TypeProvider& type_provider)
76
0
      : shared_arena_(std::move(shared_arena)),
77
0
        shared_message_factory_(std::move(shared_message_factory)),
78
0
        state_(kDefaultStackLimit, kComprehensionSlotCount,
79
0
               /*iterator_stack_size=*/0, type_provider, descriptor_pool,
80
0
               message_factory, arena) {}
81
82
  absl::Status OnPreVisit(google::api::expr::runtime::PlannerContext& context,
83
                          const Expr& node) override;
84
  absl::Status OnPostVisit(google::api::expr::runtime::PlannerContext& context,
85
                           const Expr& node) override;
86
87
 private:
88
  // Most constant folding evaluations are simple
89
  // binary operators.
90
  static constexpr size_t kDefaultStackLimit = 4;
91
92
  // Comprehensions are not evaluated -- the current implementation can't detect
93
  // if the comprehension variables are only used in a const way.
94
  static constexpr size_t kComprehensionSlotCount = 0;
95
96
  absl_nullable std::shared_ptr<google::protobuf::Arena> shared_arena_;
97
  [[maybe_unused]]
98
  absl_nullable std::shared_ptr<google::protobuf::MessageFactory> shared_message_factory_;
99
  Activation empty_;
100
  FlatExpressionEvaluatorState state_;
101
102
  std::vector<IsConst> is_const_;
103
};
104
105
0
IsConst IsConstExpr(const Expr& expr, const Resolver& resolver) {
106
0
  switch (expr.kind_case()) {
107
0
    case ExprKindCase::kConstant:
108
0
      return IsConst::kConditional;
109
0
    case ExprKindCase::kIdentExpr:
110
0
      return IsConst::kNonConst;
111
0
    case ExprKindCase::kComprehensionExpr:
112
      // Not yet supported, need to identify whether range and
113
      // iter vars are compatible with const folding.
114
0
      return IsConst::kNonConst;
115
0
    case ExprKindCase::kStructExpr:
116
0
      return IsConst::kNonConst;
117
0
    case ExprKindCase::kMapExpr:
118
      // Empty maps are rare and not currently supported as they may eventually
119
      // have similar issues to empty list when used within comprehensions or
120
      // macros.
121
0
      if (expr.map_expr().entries().empty()) {
122
0
        return IsConst::kNonConst;
123
0
      }
124
0
      return IsConst::kConditional;
125
0
    case ExprKindCase::kListExpr:
126
0
      if (expr.list_expr().elements().empty()) {
127
        // Don't fold for empty list to allow comprehension
128
        // list append optimization.
129
0
        return IsConst::kNonConst;
130
0
      }
131
0
      return IsConst::kConditional;
132
0
    case ExprKindCase::kSelectExpr:
133
0
      return IsConst::kConditional;
134
0
    case ExprKindCase::kCallExpr: {
135
0
      const auto& call = expr.call_expr();
136
      // Short Circuiting operators not yet supported.
137
0
      if (call.function() == kAnd || call.function() == kOr ||
138
0
          call.function() == kTernary) {
139
0
        return IsConst::kNonConst;
140
0
      }
141
      // For now we skip constant folding for cel.@block. We do not yet setup
142
      // slots. When we enable constant folding for comprehensions (like
143
      // cel.bind), we can address cel.@block.
144
0
      if (call.function() == "cel.@block") {
145
0
        return IsConst::kNonConst;
146
0
      }
147
148
0
      int arg_len = call.args().size() + (call.has_target() ? 1 : 0);
149
      // Check for any lazy overloads (activation dependant)
150
0
      if (!resolver
151
0
               .FindLazyOverloads(call.function(), call.has_target(), arg_len)
152
0
               .empty()) {
153
0
        return IsConst::kNonConst;
154
0
      }
155
156
0
      auto overloads =
157
0
          resolver.FindOverloads(call.function(), call.has_target(), arg_len);
158
      // Check for any contextual overloads. If there are any, we cowardly
159
      // avoid constant folding instead of trying to check if one of the
160
      // overloads would be safe to use.
161
0
      for (const auto& overload : overloads) {
162
0
        if (overload.descriptor.is_contextual()) {
163
0
          return IsConst::kNonConst;
164
0
        }
165
0
      }
166
167
0
      return IsConst::kConditional;
168
0
    }
169
0
    case ExprKindCase::kUnspecifiedExpr:
170
0
    default:
171
0
      return IsConst::kNonConst;
172
0
  }
173
0
}
174
175
absl::Status ConstantFoldingExtension::OnPreVisit(PlannerContext& context,
176
0
                                                  const Expr& node) {
177
0
  IsConst is_const = IsConstExpr(node, context.resolver());
178
0
  is_const_.push_back(is_const);
179
180
0
  return absl::OkStatus();
181
0
}
182
183
absl::Status ConstantFoldingExtension::OnPostVisit(PlannerContext& context,
184
0
                                                   const Expr& node) {
185
0
  if (is_const_.empty()) {
186
0
    return absl::InternalError("ConstantFoldingExtension called out of order.");
187
0
  }
188
189
0
  IsConst is_const = is_const_.back();
190
0
  is_const_.pop_back();
191
192
0
  if (is_const == IsConst::kNonConst) {
193
0
    if (context.options().enable_subexpression_inlining &&
194
0
        node.has_ident_expr()) {
195
0
      ExecutionPathView subplan = context.GetSubplan(node);
196
0
      if (subplan.size() == 1 &&
197
0
          google::api::expr::runtime::IsConstant(subplan[0])) {
198
0
        return absl::OkStatus();
199
0
      }
200
0
    }
201
    // update parent
202
0
    if (!is_const_.empty()) {
203
0
      is_const_.back() = IsConst::kNonConst;
204
0
    }
205
0
    return absl::OkStatus();
206
0
  }
207
0
  ExecutionPathView subplan = context.GetSubplan(node);
208
0
  if (subplan.empty()) {
209
    // This subexpression is already optimized out or suppressed.
210
0
    return absl::OkStatus();
211
0
  }
212
  // Ensure that string constants are copied to the constant folding arena
213
0
  Value value;
214
0
  if (node.has_const_expr()) {
215
0
    CEL_ASSIGN_OR_RETURN(value,
216
0
                         ConvertConstant(node.const_expr(), state_.arena()));
217
0
  } else {
218
0
    state_.Reset();
219
    // Update stack size to accommodate sub expression.
220
    // This only results in a vector resize if the new maxsize is greater than
221
    // the current capacity.
222
0
    state_.value_stack().SetMaxSize(subplan.size());
223
0
    ExecutionFrame frame(subplan, empty_, context.options(), state_);
224
225
0
    auto result = frame.Evaluate();
226
    // If this would be a runtime error, then don't adjust the program plan, but
227
    // rather allow the error to occur at runtime to preserve the evaluation
228
    // contract with non-constant folding use cases.
229
0
    if (!result.ok()) {
230
0
      return absl::OkStatus();
231
0
    }
232
0
    value = *result;
233
0
    if (value->Is<UnknownValue>()) {
234
0
      return absl::OkStatus();
235
0
    }
236
0
  }
237
238
  // Otherwise make a stack machine plan.
239
0
  ExecutionPath new_plan;
240
0
  new_plan.push_back(ExpressionStep::MakeConstant(value, node.id()));
241
242
0
  return context.ReplaceSubplan(node, std::move(new_plan));
243
0
}
244
245
}  // namespace
246
247
ProgramOptimizerFactory CreateConstantFoldingOptimizer(
248
    absl_nullable std::shared_ptr<google::protobuf::Arena> arena,
249
0
    absl_nullable std::shared_ptr<google::protobuf::MessageFactory> message_factory) {
250
0
  return
251
0
      [shared_arena = std::move(arena),
252
0
       shared_message_factory = std::move(message_factory)](
253
0
          PlannerContext& context,
254
0
          const Ast&) -> absl::StatusOr<std::unique_ptr<ProgramOptimizer>> {
255
        // If one was explicitly provided during planning or none was explicitly
256
        // provided during configuration, request one from the planning context.
257
        // Otherwise use the one provided during configuration.
258
0
        google::protobuf::Arena* absl_nonnull arena =
259
0
            context.HasExplicitArena() || shared_arena == nullptr
260
0
                ? context.MutableArena()
261
0
                : shared_arena.get();
262
0
        google::protobuf::MessageFactory* absl_nonnull message_factory =
263
0
            context.HasExplicitMessageFactory() ||
264
0
                    shared_message_factory == nullptr
265
0
                ? context.MutableMessageFactory()
266
0
                : shared_message_factory.get();
267
0
        return std::make_unique<ConstantFoldingExtension>(
268
0
            context.descriptor_pool(), shared_arena, arena,
269
0
            shared_message_factory, message_factory, context.type_reflector());
270
0
      };
271
0
}
272
273
}  // namespace cel::runtime_internal