/proc/self/cwd/extensions/select_optimization.cc
Line | Count | Source |
1 | | // Copyright 2023 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 "extensions/select_optimization.h" |
16 | | |
17 | | #include <cstddef> |
18 | | #include <cstdint> |
19 | | #include <iterator> |
20 | | #include <limits> |
21 | | #include <memory> |
22 | | #include <optional> |
23 | | #include <string> |
24 | | #include <utility> |
25 | | #include <variant> |
26 | | #include <vector> |
27 | | |
28 | | #include "absl/algorithm/container.h" |
29 | | #include "absl/base/nullability.h" |
30 | | #include "absl/base/optimization.h" |
31 | | #include "absl/container/flat_hash_map.h" |
32 | | #include "absl/functional/overload.h" |
33 | | #include "absl/log/absl_check.h" |
34 | | #include "absl/status/status.h" |
35 | | #include "absl/status/statusor.h" |
36 | | #include "absl/strings/match.h" |
37 | | #include "absl/strings/str_cat.h" |
38 | | #include "absl/strings/string_view.h" |
39 | | #include "absl/types/span.h" |
40 | | #include "absl/types/variant.h" |
41 | | #include "base/attribute.h" |
42 | | #include "base/builtins.h" |
43 | | #include "common/ast.h" |
44 | | #include "common/ast_rewrite.h" |
45 | | #include "common/constant.h" |
46 | | #include "common/expr.h" |
47 | | #include "common/function_descriptor.h" |
48 | | #include "common/internal/attribute_trail.h" |
49 | | #include "common/kind.h" |
50 | | #include "common/legacy_value.h" |
51 | | #include "common/native_type.h" |
52 | | #include "common/type.h" |
53 | | #include "common/value.h" |
54 | | #include "eval/compiler/flat_expr_builder.h" |
55 | | #include "eval/compiler/flat_expr_builder_extensions.h" |
56 | | #include "eval/eval/evaluator_core.h" |
57 | | #include "eval/eval/expression_step_base.h" |
58 | | #include "extensions/protobuf/internal/map_reflection.h" |
59 | | #include "internal/casts.h" |
60 | | #include "internal/number.h" |
61 | | #include "internal/status_macros.h" |
62 | | #include "runtime/internal/errors.h" |
63 | | #include "runtime/internal/runtime_friend_access.h" |
64 | | #include "runtime/internal/runtime_impl.h" |
65 | | #include "runtime/runtime_builder.h" |
66 | | #include "runtime/runtime_options.h" |
67 | | #include "google/protobuf/arena.h" |
68 | | #include "google/protobuf/descriptor.h" |
69 | | #include "google/protobuf/map_field.h" |
70 | | #include "google/protobuf/message.h" |
71 | | #include "google/protobuf/reflection.h" |
72 | | |
73 | | // undef for Windows |
74 | | #undef GetMessage |
75 | | |
76 | | namespace cel::extensions { |
77 | | namespace { |
78 | | |
79 | | using ::cel::Ast; |
80 | | using ::cel::AstRewriterBase; |
81 | | using ::cel::CallExpr; |
82 | | using ::cel::ConstantKind; |
83 | | using ::cel::Expr; |
84 | | using ::cel::ExprKind; |
85 | | using ::cel::SelectExpr; |
86 | | using ::cel::common_internal::AttributeTrail; |
87 | | using ::google::api::expr::runtime::ExecutionFrame; |
88 | | using ::google::api::expr::runtime::ExecutionFrameBase; |
89 | | using ::google::api::expr::runtime::ExpressionStep; |
90 | | using ::google::api::expr::runtime::ExpressionStepBase; |
91 | | using ::google::api::expr::runtime::PlannerContext; |
92 | | using ::google::api::expr::runtime::ProgramOptimizer; |
93 | | |
94 | | // Represents a single select operation (field access or indexing). |
95 | | // For struct-typed field accesses, includes the field name and the field |
96 | | // number. |
97 | | struct SelectInstruction { |
98 | | int64_t number; |
99 | | std::string name; |
100 | | }; |
101 | | |
102 | | // Represents a single qualifier in a traversal path. |
103 | | // TODO(uncreated-issue/51): support variable indexes. |
104 | | using QualifierInstruction = |
105 | | std::variant<SelectInstruction, std::string, int64_t, uint64_t, bool>; |
106 | | |
107 | | struct SelectPath { |
108 | | Expr* operand; |
109 | | std::vector<QualifierInstruction> select_instructions; |
110 | | bool test_only; |
111 | | // TODO(uncreated-issue/54): support for optionals. |
112 | | }; |
113 | | |
114 | | // Generates the AST representation of the qualification path for the optimized |
115 | | // select branch. I.e., the list-typed second argument of the cel.@attribute |
116 | | // call. |
117 | | Expr MakeSelectPathExpr( |
118 | 0 | const std::vector<QualifierInstruction>& select_instructions) { |
119 | 0 | Expr result; |
120 | 0 | auto& ast_list = result.mutable_list_expr().mutable_elements(); |
121 | 0 | ast_list.reserve(select_instructions.size()); |
122 | 0 | auto visitor = absl::Overload( |
123 | 0 | [&](const SelectInstruction& instruction) { |
124 | 0 | Expr ast_instruction; |
125 | 0 | Expr field_number; |
126 | 0 | field_number.mutable_const_expr().set_int64_value(instruction.number); |
127 | 0 | Expr field_name; |
128 | 0 | field_name.mutable_const_expr().set_string_value(instruction.name); |
129 | 0 | auto& field_specifier = |
130 | 0 | ast_instruction.mutable_list_expr().mutable_elements(); |
131 | 0 | field_specifier.emplace_back().set_expr(std::move(field_number)); |
132 | 0 | field_specifier.emplace_back().set_expr(std::move(field_name)); |
133 | |
|
134 | 0 | ast_list.emplace_back().set_expr(std::move(ast_instruction)); |
135 | 0 | }, |
136 | 0 | [&](absl::string_view instruction) { |
137 | 0 | Expr const_expr; |
138 | 0 | const_expr.mutable_const_expr().set_string_value(instruction); |
139 | 0 | ast_list.emplace_back().set_expr(std::move(const_expr)); |
140 | 0 | }, |
141 | 0 | [&](int64_t instruction) { |
142 | 0 | Expr const_expr; |
143 | 0 | const_expr.mutable_const_expr().set_int64_value(instruction); |
144 | 0 | ast_list.emplace_back().set_expr(std::move(const_expr)); |
145 | 0 | }, |
146 | 0 | [&](uint64_t instruction) { |
147 | 0 | Expr const_expr; |
148 | 0 | const_expr.mutable_const_expr().set_uint64_value(instruction); |
149 | 0 | ast_list.emplace_back().set_expr(std::move(const_expr)); |
150 | 0 | }, |
151 | 0 | [&](bool instruction) { |
152 | 0 | Expr const_expr; |
153 | 0 | const_expr.mutable_const_expr().set_bool_value(instruction); |
154 | 0 | ast_list.emplace_back().set_expr(std::move(const_expr)); |
155 | 0 | }); |
156 | |
|
157 | 0 | for (const auto& instruction : select_instructions) { |
158 | 0 | absl::visit(visitor, instruction); |
159 | 0 | } |
160 | 0 | return result; |
161 | 0 | } |
162 | | |
163 | | // Returns a single select operation based on the inferred type of the operand |
164 | | // and the field name. If the operand type doesn't define the field, returns |
165 | | // nullopt. |
166 | | std::optional<SelectInstruction> MakeFieldStepAst( |
167 | | const StructType& runtime_type, PlannerContext& planner_context, |
168 | 0 | absl::string_view field_name) { |
169 | 0 | auto field_or = planner_context.type_reflector() |
170 | 0 | .FindStructTypeFieldByName(runtime_type, field_name) |
171 | 0 | .value_or(std::nullopt); |
172 | 0 | if (field_or.has_value()) { |
173 | 0 | return SelectInstruction{field_or->number(), std::string(field_or->name())}; |
174 | 0 | } |
175 | 0 | return std::nullopt; |
176 | 0 | } |
177 | | |
178 | | // Returns a qualifier instruction derived from a unoptimized ast. |
179 | | absl::StatusOr<QualifierInstruction> MakeIndexStepAst( |
180 | 0 | const Constant& constant) { |
181 | 0 | if (constant.has_int_value()) { |
182 | 0 | return QualifierInstruction(constant.int_value()); |
183 | 0 | } else if (constant.has_uint_value()) { |
184 | 0 | return QualifierInstruction(constant.uint_value()); |
185 | 0 | } else if (constant.has_bool_value()) { |
186 | 0 | return QualifierInstruction(constant.bool_value()); |
187 | 0 | } else if (constant.has_string_value()) { |
188 | 0 | return QualifierInstruction(constant.string_value()); |
189 | 0 | } else if (constant.has_double_value()) { |
190 | 0 | cel::internal::Number number(constant.double_value()); |
191 | 0 | if (number.LosslessConvertibleToInt()) { |
192 | 0 | return QualifierInstruction(number.AsInt()); |
193 | 0 | } else if (number.LosslessConvertibleToUint()) { |
194 | 0 | return QualifierInstruction(number.AsUint()); |
195 | 0 | } |
196 | 0 | } |
197 | | |
198 | 0 | return absl::InvalidArgumentError("invalid index constant for cel.attribute"); |
199 | 0 | } |
200 | | |
201 | | // Derives select step info from the optimized AST. |
202 | 0 | absl::StatusOr<SelectQualifier> SelectQualifierFromList(const ListExpr& list) { |
203 | | // Type codes may follow [number, name]; they're unused here. |
204 | 0 | if (list.elements().size() < 2 || list.elements().size() > 4) { |
205 | 0 | return absl::InvalidArgumentError("Invalid cel.attribute select list"); |
206 | 0 | } |
207 | | |
208 | 0 | const Expr& field_number = list.elements()[0].expr(); |
209 | 0 | const Expr& field_name = list.elements()[1].expr(); |
210 | |
|
211 | 0 | if (!field_number.has_const_expr() || |
212 | 0 | !field_number.const_expr().has_int64_value()) { |
213 | 0 | return absl::InvalidArgumentError( |
214 | 0 | "Invalid cel.attribute field select number"); |
215 | 0 | } |
216 | | |
217 | 0 | if (!field_name.has_const_expr() || |
218 | 0 | !field_name.const_expr().has_string_value()) { |
219 | 0 | return absl::InvalidArgumentError( |
220 | 0 | "Invalid cel.attribute field select name"); |
221 | 0 | } |
222 | | |
223 | 0 | return FieldSpecifier{field_number.const_expr().int64_value(), |
224 | 0 | field_name.const_expr().string_value()}; |
225 | 0 | } |
226 | | |
227 | | // Derives index step info from the optimized AST. |
228 | | absl::StatusOr<SelectQualifier> SelectQualifierFromConstant( |
229 | 0 | const Constant& constant) { |
230 | 0 | if (constant.has_int_value()) { |
231 | 0 | return AttributeQualifier::OfInt(constant.int_value()); |
232 | 0 | } else if (constant.has_uint_value()) { |
233 | 0 | return AttributeQualifier::OfUint(constant.uint_value()); |
234 | 0 | } else if (constant.has_bool_value()) { |
235 | 0 | return AttributeQualifier::OfBool(constant.bool_value()); |
236 | 0 | } else if (constant.has_string_value()) { |
237 | 0 | return AttributeQualifier::OfString(constant.string_value()); |
238 | 0 | } |
239 | | // TODO(uncreated-issue/51): double keys could possibly be valid selectors, but |
240 | | // the other stacks don't implement the optimization yet and we normalize the |
241 | | // key to a uint or int if we do the late AST rewrite during planning. |
242 | | |
243 | 0 | return absl::InvalidArgumentError("invalid cel.attribute constant"); |
244 | 0 | } |
245 | | |
246 | 0 | absl::StatusOr<size_t> ListIndexFromQualifier(const AttributeQualifier& qual) { |
247 | 0 | int64_t value = -1; |
248 | 0 | switch (qual.kind()) { |
249 | 0 | case Kind::kInt: |
250 | 0 | value = *qual.AsInt(); |
251 | 0 | break; |
252 | 0 | default: |
253 | | // TODO(uncreated-issue/51): type-checker will reject an unsigned literal, but |
254 | | // should be supported as a dyn / variable. |
255 | 0 | return runtime_internal::CreateNoMatchingOverloadError( |
256 | 0 | cel::builtin::kIndex); |
257 | 0 | } |
258 | | |
259 | 0 | if (value < 0) { |
260 | 0 | return absl::InvalidArgumentError("list index less than 0"); |
261 | 0 | } |
262 | | |
263 | 0 | return static_cast<size_t>(value); |
264 | 0 | } |
265 | | |
266 | | absl::StatusOr<Value> MapKeyFromQualifier(const AttributeQualifier& qual, |
267 | 0 | google::protobuf::Arena* absl_nonnull arena) { |
268 | 0 | switch (qual.kind()) { |
269 | 0 | case Kind::kInt: |
270 | 0 | return cel::IntValue(*qual.AsInt()); |
271 | 0 | case Kind::kUint: |
272 | 0 | return cel::UintValue(*qual.AsUint()); |
273 | 0 | case Kind::kBool: |
274 | 0 | return cel::BoolValue(*qual.AsBool()); |
275 | 0 | case Kind::kString: |
276 | | // Safe as `qual` is valid for the lifetime of the expression/program. |
277 | 0 | return StringValue::WrapUnsafe(*qual.GetStringKey()); |
278 | 0 | default: |
279 | 0 | return runtime_internal::CreateNoMatchingOverloadError( |
280 | 0 | cel::builtin::kIndex); |
281 | 0 | } |
282 | 0 | } |
283 | | |
284 | | absl::StatusOr<Value> ApplyQualifier( |
285 | | const Value& operand, const SelectQualifier& qualifier, |
286 | | const google::protobuf::DescriptorPool* absl_nonnull descriptor_pool, |
287 | | google::protobuf::MessageFactory* absl_nonnull message_factory, |
288 | 0 | google::protobuf::Arena* absl_nonnull arena) { |
289 | 0 | return absl::visit( |
290 | 0 | absl::Overload( |
291 | 0 | [&](const FieldSpecifier& field_specifier) -> absl::StatusOr<Value> { |
292 | 0 | if (!operand.Is<StructValue>()) { |
293 | 0 | return cel::ErrorValue::From( |
294 | 0 | cel::runtime_internal::CreateNoMatchingOverloadError( |
295 | 0 | "<select>"), |
296 | 0 | arena); |
297 | 0 | } |
298 | 0 | return operand.GetStruct().GetFieldByName( |
299 | 0 | field_specifier.name, descriptor_pool, message_factory, arena); |
300 | 0 | }, |
301 | 0 | [&](const AttributeQualifier& qualifier) -> absl::StatusOr<Value> { |
302 | 0 | if (operand.Is<ListValue>()) { |
303 | 0 | auto index_or = ListIndexFromQualifier(qualifier); |
304 | 0 | if (!index_or.ok()) { |
305 | 0 | return cel::ErrorValue::From(index_or.status(), arena); |
306 | 0 | } |
307 | 0 | return operand.GetList().Get(*index_or, descriptor_pool, |
308 | 0 | message_factory, arena); |
309 | 0 | } else if (operand.Is<MapValue>()) { |
310 | 0 | auto key_or = MapKeyFromQualifier(qualifier, arena); |
311 | 0 | if (!key_or.ok()) { |
312 | 0 | return cel::ErrorValue::From(key_or.status(), arena); |
313 | 0 | } |
314 | 0 | return operand.GetMap().Get(*key_or, descriptor_pool, |
315 | 0 | message_factory, arena); |
316 | 0 | } |
317 | 0 | return cel::ErrorValue::From( |
318 | 0 | cel::runtime_internal::CreateNoMatchingOverloadError( |
319 | 0 | cel::builtin::kIndex), |
320 | 0 | arena); |
321 | 0 | }), |
322 | 0 | qualifier); |
323 | 0 | } |
324 | | |
325 | | absl::StatusOr<Value> FallbackSelect( |
326 | | const Value& root, absl::Span<const SelectQualifier> select_path, |
327 | | bool presence_test, |
328 | | const google::protobuf::DescriptorPool* absl_nonnull descriptor_pool, |
329 | | google::protobuf::MessageFactory* absl_nonnull message_factory, |
330 | 0 | google::protobuf::Arena* absl_nonnull arena) { |
331 | 0 | const Value* elem = &root; |
332 | 0 | Value result; |
333 | |
|
334 | 0 | for (const auto& instruction : |
335 | 0 | select_path.subspan(0, select_path.size() - 1)) { |
336 | 0 | CEL_ASSIGN_OR_RETURN(result, |
337 | 0 | ApplyQualifier(*elem, instruction, descriptor_pool, |
338 | 0 | message_factory, arena)); |
339 | 0 | if (result->Is<ErrorValue>()) { |
340 | 0 | return result; |
341 | 0 | } |
342 | 0 | elem = &result; |
343 | 0 | } |
344 | | |
345 | 0 | const auto& last_instruction = select_path.back(); |
346 | 0 | if (presence_test) { |
347 | 0 | return absl::visit( |
348 | 0 | absl::Overload( |
349 | 0 | [&](const FieldSpecifier& field_specifier) |
350 | 0 | -> absl::StatusOr<Value> { |
351 | 0 | if (!elem->Is<StructValue>()) { |
352 | 0 | return cel::ErrorValue::From( |
353 | 0 | cel::runtime_internal::CreateNoMatchingOverloadError( |
354 | 0 | "<select>"), |
355 | 0 | arena); |
356 | 0 | } |
357 | 0 | CEL_ASSIGN_OR_RETURN( |
358 | 0 | bool present, |
359 | 0 | elem->GetStruct().HasFieldByName(field_specifier.name)); |
360 | 0 | return cel::BoolValue(present); |
361 | 0 | }, |
362 | 0 | [&](const AttributeQualifier& qualifier) -> absl::StatusOr<Value> { |
363 | 0 | if (!elem->Is<MapValue>() || qualifier.kind() != Kind::kString) { |
364 | 0 | return cel::ErrorValue::From( |
365 | 0 | cel::runtime_internal::CreateNoMatchingOverloadError("has"), |
366 | 0 | arena); |
367 | 0 | } |
368 | | |
369 | 0 | return elem->GetMap().Has( |
370 | 0 | StringValue::WrapUnsafe(*qualifier.GetStringKey()), |
371 | 0 | descriptor_pool, message_factory, arena); |
372 | 0 | }), |
373 | 0 | last_instruction); |
374 | 0 | } |
375 | | |
376 | 0 | return ApplyQualifier(*elem, last_instruction, descriptor_pool, |
377 | 0 | message_factory, arena); |
378 | 0 | } |
379 | | |
380 | | absl::StatusOr<std::vector<SelectQualifier>> SelectInstructionsFromCall( |
381 | 0 | const CallExpr& call) { |
382 | 0 | if (call.args().size() < 2 || !call.args()[1].has_list_expr()) { |
383 | 0 | return absl::InvalidArgumentError("Invalid cel.attribute call"); |
384 | 0 | } |
385 | 0 | std::vector<SelectQualifier> instructions; |
386 | 0 | const auto& ast_path = call.args()[1].list_expr().elements(); |
387 | 0 | instructions.reserve(ast_path.size()); |
388 | |
|
389 | 0 | for (const ListExprElement& element : ast_path) { |
390 | 0 | if (element.optional()) { |
391 | 0 | return absl::InvalidArgumentError("Invalid cel.attribute call"); |
392 | 0 | } |
393 | | // Optimized field select. |
394 | 0 | if (element.has_expr()) { |
395 | 0 | const auto& element_expr = element.expr(); |
396 | 0 | if (element_expr.has_list_expr()) { |
397 | 0 | CEL_ASSIGN_OR_RETURN(instructions.emplace_back(), |
398 | 0 | SelectQualifierFromList(element_expr.list_expr())); |
399 | 0 | } else if (element_expr.has_const_expr()) { |
400 | 0 | CEL_ASSIGN_OR_RETURN( |
401 | 0 | instructions.emplace_back(), |
402 | 0 | SelectQualifierFromConstant(element_expr.const_expr())); |
403 | 0 | } else { |
404 | 0 | return absl::InvalidArgumentError("Invalid cel.attribute call"); |
405 | 0 | } |
406 | 0 | } else { |
407 | 0 | return absl::InvalidArgumentError("Invalid cel.attribute call"); |
408 | 0 | } |
409 | 0 | } |
410 | | |
411 | | // TODO(uncreated-issue/54): support for optionals. |
412 | | |
413 | 0 | return instructions; |
414 | 0 | } |
415 | | |
416 | | class RewriterImpl : public AstRewriterBase { |
417 | | public: |
418 | | RewriterImpl(const Ast& ast, PlannerContext& planner_context, |
419 | | const SelectOptimizationOptions& options) |
420 | 0 | : ast_(ast), planner_context_(planner_context), options_(options) {} |
421 | | |
422 | 0 | void PreVisitExpr(const Expr& expr) override { path_.push_back(&expr); } |
423 | | |
424 | 0 | void PreVisitSelect(const Expr& expr, const SelectExpr& select) override { |
425 | 0 | const Expr& operand = select.operand(); |
426 | 0 | const std::string& field_name = select.field(); |
427 | | // Select optimization can generalize to lists and maps, but for now only |
428 | | // support message traversal. |
429 | 0 | const TypeSpec ast_type = ast_.GetTypeOrDyn(operand.id()); |
430 | 0 | std::optional<Type> rt_type = |
431 | 0 | planner_context_.TryResolveType(operand.id(), ast_type); |
432 | 0 | if (!rt_type.has_value()) { |
433 | 0 | return; |
434 | 0 | } |
435 | 0 | if (rt_type->IsStruct()) { |
436 | 0 | const StructType& runtime_type = rt_type->GetStruct(); |
437 | 0 | std::optional<SelectInstruction> field_or = |
438 | 0 | MakeFieldStepAst(runtime_type, planner_context_, field_name); |
439 | 0 | if (field_or.has_value()) { |
440 | 0 | candidates_[&expr] = std::move(field_or).value(); |
441 | 0 | } |
442 | 0 | } else if (rt_type->IsMap()) { |
443 | 0 | candidates_[&expr] = QualifierInstruction(field_name); |
444 | 0 | } |
445 | | // else |
446 | | // TODO(uncreated-issue/54): add support for either dyn or any. Excluded to |
447 | | // simplify program plan. |
448 | 0 | } |
449 | | |
450 | 0 | void PreVisitCall(const Expr& expr, const CallExpr& call) override { |
451 | 0 | if (call.args().size() != 2 || call.function() != ::cel::builtin::kIndex) { |
452 | 0 | return; |
453 | 0 | } |
454 | | |
455 | 0 | const auto& qualifier_expr = call.args()[1]; |
456 | 0 | if (qualifier_expr.has_const_expr()) { |
457 | 0 | auto qualifier_or = MakeIndexStepAst(qualifier_expr.const_expr()); |
458 | 0 | if (!qualifier_or.ok()) { |
459 | | // TODO(uncreated-issue/54): should warn, but by default warnings fail overall |
460 | | // program planning. |
461 | 0 | return; |
462 | 0 | } |
463 | 0 | candidates_[&expr] = std::move(qualifier_or).value(); |
464 | 0 | } |
465 | | // TODO(uncreated-issue/54): support variable indexes |
466 | 0 | } |
467 | | |
468 | 0 | bool PostVisitRewrite(Expr& expr) override { |
469 | 0 | if (!progress_status_.ok()) { |
470 | 0 | return false; |
471 | 0 | } |
472 | 0 | path_.pop_back(); |
473 | 0 | auto candidate_iter = candidates_.find(&expr); |
474 | 0 | if (candidate_iter == candidates_.end()) { |
475 | 0 | return false; |
476 | 0 | } |
477 | | |
478 | | // On post visit, filter candidates that aren't rooted on a message or a |
479 | | // select chain. |
480 | 0 | const QualifierInstruction& candidate = candidate_iter->second; |
481 | 0 | if (!HasOptimizeableRoot(&expr, candidate)) { |
482 | 0 | candidates_.erase(candidate_iter); |
483 | 0 | return false; |
484 | 0 | } |
485 | | |
486 | 0 | if (!path_.empty() && candidates_.find(path_.back()) != candidates_.end()) { |
487 | | // parent is optimizeable, defer rewriting until we consider the parent. |
488 | 0 | return false; |
489 | 0 | } |
490 | | |
491 | 0 | SelectPath path = GetSelectPath(&expr); |
492 | 0 | if (path.select_instructions.size() < |
493 | 0 | options_.min_field_depth_for_optimization) { |
494 | 0 | return false; |
495 | 0 | } |
496 | | |
497 | | // generate the new cel.attribute call. |
498 | 0 | absl::string_view fn = path.test_only ? kCelHasField : kCelAttribute; |
499 | |
|
500 | 0 | Expr operand(std::move(*path.operand)); |
501 | 0 | Expr call; |
502 | 0 | call.set_id(expr.id()); |
503 | 0 | call.mutable_call_expr().set_function(std::string(fn)); |
504 | 0 | call.mutable_call_expr().mutable_args().reserve(2); |
505 | |
|
506 | 0 | call.mutable_call_expr().mutable_args().push_back(std::move(operand)); |
507 | 0 | call.mutable_call_expr().mutable_args().push_back( |
508 | 0 | MakeSelectPathExpr(path.select_instructions)); |
509 | | |
510 | | // TODO(uncreated-issue/54): support for optionals. |
511 | 0 | expr = std::move(call); |
512 | |
|
513 | 0 | return true; |
514 | 0 | } |
515 | | |
516 | 0 | absl::Status GetProgressStatus() const { return progress_status_; } |
517 | | |
518 | | private: |
519 | 0 | SelectPath GetSelectPath(Expr* expr) { |
520 | 0 | SelectPath result; |
521 | 0 | result.test_only = false; |
522 | 0 | Expr* operand = expr; |
523 | 0 | auto candidate_iter = candidates_.find(operand); |
524 | 0 | while (candidate_iter != candidates_.end()) { |
525 | 0 | result.select_instructions.push_back(candidate_iter->second); |
526 | 0 | if (operand->has_select_expr()) { |
527 | 0 | if (operand->select_expr().test_only()) { |
528 | 0 | result.test_only = true; |
529 | 0 | } |
530 | 0 | operand = &(operand->mutable_select_expr().mutable_operand()); |
531 | 0 | } else { |
532 | 0 | ABSL_DCHECK(operand->has_call_expr()); |
533 | 0 | operand = &(operand->mutable_call_expr().mutable_args()[0]); |
534 | 0 | } |
535 | 0 | candidate_iter = candidates_.find(operand); |
536 | 0 | } |
537 | 0 | absl::c_reverse(result.select_instructions); |
538 | 0 | result.operand = operand; |
539 | 0 | return result; |
540 | 0 | } |
541 | | |
542 | | // Check whether the candidate has a message type as a root (the operand for |
543 | | // the batched select operation). |
544 | | // Called on post visit. |
545 | | bool HasOptimizeableRoot(const Expr* expr, |
546 | 0 | const QualifierInstruction& candidate) { |
547 | 0 | if (absl::holds_alternative<SelectInstruction>(candidate)) { |
548 | 0 | return true; |
549 | 0 | } |
550 | 0 | const Expr* operand = nullptr; |
551 | 0 | if (expr->has_call_expr() && expr->call_expr().args().size() == 2 && |
552 | 0 | expr->call_expr().function() == ::cel::builtin::kIndex) { |
553 | 0 | operand = &expr->call_expr().args()[0]; |
554 | 0 | } else if (expr->has_select_expr()) { |
555 | 0 | operand = &expr->select_expr().operand(); |
556 | 0 | } |
557 | |
|
558 | 0 | if (operand == nullptr) { |
559 | 0 | return false; |
560 | 0 | } |
561 | | |
562 | 0 | return candidates_.find(operand) != candidates_.end(); |
563 | 0 | } |
564 | | |
565 | 0 | void SetProgressStatus(const absl::Status& status) { |
566 | 0 | if (progress_status_.ok() && !status.ok()) { |
567 | 0 | progress_status_ = status; |
568 | 0 | } |
569 | 0 | } |
570 | | |
571 | | const Ast& ast_; |
572 | | PlannerContext& planner_context_; |
573 | | SelectOptimizationOptions options_; |
574 | | // ids of potentially optimizeable expr nodes. |
575 | | absl::flat_hash_map<const Expr*, QualifierInstruction> candidates_; |
576 | | std::vector<const Expr*> path_; |
577 | | absl::Status progress_status_; |
578 | | }; |
579 | | |
580 | | struct FieldSelectStep { |
581 | | const google::protobuf::Descriptor* absl_nonnull containing_type; |
582 | | const google::protobuf::FieldDescriptor* absl_nonnull field; |
583 | | }; |
584 | | |
585 | | struct MapSelectStep { |
586 | | const google::protobuf::FieldDescriptor* absl_nonnull map_field; |
587 | | const google::protobuf::FieldDescriptor* absl_nonnull key_field; |
588 | | const google::protobuf::FieldDescriptor* absl_nonnull value_field; |
589 | | // Store the error to propagate on access at runtime. |
590 | | // The map key might alias string data owned by the SelectOptimizationImpl |
591 | | // object. |
592 | | absl::StatusOr<google::protobuf::MapKey> key; |
593 | | }; |
594 | | |
595 | | struct ListSelectStep { |
596 | | const google::protobuf::FieldDescriptor* absl_nonnull repeated_field; |
597 | | }; |
598 | | |
599 | | using TypedSelectStep = |
600 | | std::variant<FieldSelectStep, MapSelectStep, ListSelectStep>; |
601 | | |
602 | | absl::StatusOr<google::protobuf::MapKey> CreateProtoMapKey( |
603 | | const google::protobuf::FieldDescriptor* absl_nonnull key_desc, |
604 | 0 | const cel::AttributeQualifier& key) { |
605 | 0 | google::protobuf::MapKey proto_key; |
606 | 0 | switch (key_desc->cpp_type()) { |
607 | 0 | case google::protobuf::FieldDescriptor::CPPTYPE_BOOL: |
608 | 0 | if (key.kind() != cel::Kind::kBool) { |
609 | 0 | return runtime_internal::CreateInvalidMapKeyTypeError( |
610 | 0 | key_desc->cpp_type_name()); |
611 | 0 | } |
612 | 0 | proto_key.SetBoolValue(*key.AsBool()); |
613 | 0 | return proto_key; |
614 | 0 | case google::protobuf::FieldDescriptor::CPPTYPE_INT32: { |
615 | 0 | if (key.kind() != cel::Kind::kInt64) { |
616 | 0 | return runtime_internal::CreateInvalidMapKeyTypeError( |
617 | 0 | key_desc->cpp_type_name()); |
618 | 0 | } |
619 | 0 | int64_t key_value = *key.AsInt(); |
620 | 0 | if (key_value > std::numeric_limits<int32_t>::max() || |
621 | 0 | key_value < std::numeric_limits<int32_t>::lowest()) { |
622 | 0 | return absl::OutOfRangeError("integer overflow"); |
623 | 0 | } |
624 | 0 | proto_key.SetInt32Value(static_cast<int32_t>(key_value)); |
625 | 0 | return proto_key; |
626 | 0 | } |
627 | 0 | case google::protobuf::FieldDescriptor::CPPTYPE_INT64: |
628 | 0 | if (key.kind() != cel::Kind::kInt64) { |
629 | 0 | return runtime_internal::CreateInvalidMapKeyTypeError( |
630 | 0 | key_desc->cpp_type_name()); |
631 | 0 | } |
632 | 0 | proto_key.SetInt64Value(*key.AsInt()); |
633 | 0 | return proto_key; |
634 | 0 | case google::protobuf::FieldDescriptor::CPPTYPE_STRING: |
635 | 0 | if (key.kind() != cel::Kind::kString) { |
636 | 0 | return runtime_internal::CreateInvalidMapKeyTypeError( |
637 | 0 | key_desc->cpp_type_name()); |
638 | 0 | } |
639 | | // This is an alias. The underlying string should be stable. |
640 | 0 | proto_key.SetStringValue(*key.AsString()); |
641 | 0 | return proto_key; |
642 | 0 | case google::protobuf::FieldDescriptor::CPPTYPE_UINT32: { |
643 | 0 | if (key.kind() != cel::Kind::kUint64) { |
644 | 0 | return runtime_internal::CreateInvalidMapKeyTypeError( |
645 | 0 | key_desc->cpp_type_name()); |
646 | 0 | } |
647 | 0 | uint64_t key_value = *key.AsUint(); |
648 | 0 | if (key_value > std::numeric_limits<uint32_t>::max()) { |
649 | 0 | return absl::OutOfRangeError("unsigned integer overflow"); |
650 | 0 | } |
651 | 0 | proto_key.SetUInt32Value(static_cast<uint32_t>(key_value)); |
652 | 0 | return proto_key; |
653 | 0 | } |
654 | 0 | case google::protobuf::FieldDescriptor::CPPTYPE_UINT64: |
655 | 0 | if (key.kind() != cel::Kind::kUint64) { |
656 | 0 | return runtime_internal::CreateInvalidMapKeyTypeError( |
657 | 0 | key_desc->cpp_type_name()); |
658 | 0 | } |
659 | 0 | proto_key.SetUInt64Value(*key.AsUint()); |
660 | 0 | return proto_key; |
661 | 0 | default: |
662 | 0 | return runtime_internal::CreateInvalidMapKeyTypeError( |
663 | 0 | key_desc->cpp_type_name()); |
664 | 0 | } |
665 | 0 | } |
666 | | |
667 | | class OptimizedSelectImpl { |
668 | | public: |
669 | | OptimizedSelectImpl(std::vector<SelectQualifier> select_path, |
670 | | std::vector<TypedSelectStep> typed_select_path, |
671 | | std::vector<AttributeQualifier> qualifiers, |
672 | | bool presence_test, SelectOptimizationOptions options) |
673 | 0 | : select_path_(std::move(select_path)), |
674 | 0 | typed_select_path_(std::move(typed_select_path)), |
675 | 0 | qualifiers_(std::move(qualifiers)), |
676 | 0 | presence_test_(presence_test), |
677 | 0 | options_(options) |
678 | | |
679 | 0 | { |
680 | 0 | ABSL_DCHECK(!select_path_.empty()); |
681 | 0 | } |
682 | | |
683 | | // Move constructible. |
684 | | OptimizedSelectImpl(const OptimizedSelectImpl&) = delete; |
685 | | OptimizedSelectImpl& operator=(const OptimizedSelectImpl&) = delete; |
686 | 0 | OptimizedSelectImpl(OptimizedSelectImpl&&) = default; |
687 | | OptimizedSelectImpl& operator=(OptimizedSelectImpl&&) = delete; |
688 | | |
689 | | absl::Status ApplySelect(ExecutionFrameBase& frame, |
690 | | Value& result_in_out) const; |
691 | | |
692 | 0 | std::optional<Attribute> attribute() const { return attribute_; } |
693 | | |
694 | 0 | const std::vector<AttributeQualifier>& qualifiers() const { |
695 | 0 | return qualifiers_; |
696 | 0 | } |
697 | | |
698 | | private: |
699 | | absl::Status ContinueFromValue(ExecutionFrameBase& frame, Value step_result, |
700 | | size_t next_index, Value& result_in_out) const; |
701 | | |
702 | | std::optional<Attribute> attribute_; |
703 | | std::vector<SelectQualifier> select_path_; |
704 | | std::vector<TypedSelectStep> typed_select_path_; |
705 | | std::vector<AttributeQualifier> qualifiers_; |
706 | | bool presence_test_; |
707 | | SelectOptimizationOptions options_; |
708 | | }; |
709 | | |
710 | | bool SupportsCachedFieldDescriptor(const google::protobuf::Message* absl_nonnull message, |
711 | 0 | const TypedSelectStep& step) { |
712 | 0 | if (const FieldSelectStep* field_step = absl::get_if<FieldSelectStep>(&step); |
713 | 0 | field_step != nullptr) { |
714 | 0 | ABSL_DCHECK_EQ(field_step->field->containing_type(), |
715 | 0 | field_step->containing_type); |
716 | 0 | ABSL_DCHECK_EQ(field_step->containing_type->file()->pool(), |
717 | 0 | field_step->field->file()->pool()); |
718 | 0 | return message->GetDescriptor() == field_step->containing_type; |
719 | 0 | } |
720 | 0 | return false; |
721 | 0 | } |
722 | | |
723 | | Value WrapMessageField( |
724 | | const google::protobuf::Message* absl_nonnull message, |
725 | | const google::protobuf::FieldDescriptor* absl_nonnull field_descriptor, |
726 | | bool is_unsafe, const google::protobuf::DescriptorPool* absl_nonnull descriptor_pool, |
727 | | google::protobuf::MessageFactory* absl_nonnull message_factory, |
728 | 0 | google::protobuf::Arena* absl_nonnull arena) { |
729 | 0 | if (is_unsafe) { |
730 | 0 | return Value::WrapFieldUnsafe(ProtoWrapperTypeOptions::kUnsetNull, message, |
731 | 0 | field_descriptor, descriptor_pool, |
732 | 0 | message_factory, arena); |
733 | 0 | } |
734 | 0 | return Value::WrapField(ProtoWrapperTypeOptions::kUnsetNull, message, |
735 | 0 | field_descriptor, descriptor_pool, message_factory, |
736 | 0 | arena); |
737 | 0 | } |
738 | | |
739 | | Value WrapMapElement( |
740 | | const google::protobuf::MapValueConstRef& value_ref, |
741 | | const google::protobuf::Message* absl_nonnull message, |
742 | | const google::protobuf::FieldDescriptor* absl_nonnull value_descriptor, |
743 | | bool is_unsafe, const google::protobuf::DescriptorPool* absl_nonnull descriptor_pool, |
744 | | google::protobuf::MessageFactory* absl_nonnull message_factory, |
745 | 0 | google::protobuf::Arena* absl_nonnull arena) { |
746 | 0 | if (is_unsafe) { |
747 | 0 | return Value::WrapMapFieldValueUnsafe(value_ref, message, value_descriptor, |
748 | 0 | descriptor_pool, message_factory, |
749 | 0 | arena); |
750 | 0 | } |
751 | 0 | return Value::WrapMapFieldValue(value_ref, message, value_descriptor, |
752 | 0 | descriptor_pool, message_factory, arena); |
753 | 0 | } |
754 | | |
755 | | Value WrapRepeatedElement( |
756 | | int index, const google::protobuf::Message* absl_nonnull message, |
757 | | const google::protobuf::FieldDescriptor* absl_nonnull repeated_descriptor, |
758 | | bool is_unsafe, const google::protobuf::DescriptorPool* absl_nonnull descriptor_pool, |
759 | | google::protobuf::MessageFactory* absl_nonnull message_factory, |
760 | 0 | google::protobuf::Arena* absl_nonnull arena) { |
761 | 0 | if (is_unsafe) { |
762 | 0 | return Value::WrapRepeatedFieldUnsafe(index, message, repeated_descriptor, |
763 | 0 | descriptor_pool, message_factory, |
764 | 0 | arena); |
765 | 0 | } |
766 | 0 | return Value::WrapRepeatedField(index, message, repeated_descriptor, |
767 | 0 | descriptor_pool, message_factory, arena); |
768 | 0 | } |
769 | | |
770 | | absl::StatusOr<Value> QualifyOrFallback( |
771 | | ExecutionFrameBase& frame, const StructValue& struct_value, |
772 | | absl::Span<const SelectQualifier> select_path, bool presence_test, |
773 | 0 | bool force_fallback_implementation) { |
774 | 0 | absl::StatusOr<std::pair<Value, int>> value_and_count = |
775 | 0 | (force_fallback_implementation) |
776 | 0 | ? absl::UnimplementedError("Forced fallback impl") |
777 | 0 | : struct_value.Qualify(select_path, presence_test, |
778 | 0 | frame.descriptor_pool(), |
779 | 0 | frame.message_factory(), frame.arena()); |
780 | |
|
781 | 0 | if (!value_and_count.ok()) { |
782 | 0 | if (value_and_count.status().code() == absl::StatusCode::kUnimplemented) { |
783 | 0 | return FallbackSelect(struct_value, select_path, presence_test, |
784 | 0 | frame.descriptor_pool(), frame.message_factory(), |
785 | 0 | frame.arena()); |
786 | 0 | } |
787 | | |
788 | 0 | return value_and_count.status(); |
789 | 0 | } |
790 | | |
791 | 0 | if (value_and_count->second < 0 || |
792 | 0 | value_and_count->second >= select_path.size()) { |
793 | 0 | return std::move(value_and_count->first); |
794 | 0 | } |
795 | | |
796 | 0 | return FallbackSelect(value_and_count->first, |
797 | 0 | select_path.subspan(value_and_count->second), |
798 | 0 | presence_test, frame.descriptor_pool(), |
799 | 0 | frame.message_factory(), frame.arena()); |
800 | 0 | } |
801 | | |
802 | | absl::Status OptimizedSelectImpl::ContinueFromValue( |
803 | | ExecutionFrameBase& frame, Value step_result, size_t next_index, |
804 | 0 | Value& result_in_out) const { |
805 | 0 | if (step_result.IsError() || next_index >= select_path_.size()) { |
806 | 0 | result_in_out = std::move(step_result); |
807 | 0 | return absl::OkStatus(); |
808 | 0 | } |
809 | 0 | absl::Span<const SelectQualifier> remaining = |
810 | 0 | absl::MakeConstSpan(select_path_).subspan(next_index); |
811 | 0 | if (step_result.IsStruct()) { |
812 | 0 | CEL_ASSIGN_OR_RETURN( |
813 | 0 | result_in_out, |
814 | 0 | QualifyOrFallback(frame, step_result.GetStruct(), remaining, |
815 | 0 | presence_test_, |
816 | 0 | options_.force_fallback_implementation)); |
817 | 0 | return absl::OkStatus(); |
818 | 0 | } |
819 | 0 | CEL_ASSIGN_OR_RETURN(result_in_out, |
820 | 0 | FallbackSelect(step_result, remaining, presence_test_, |
821 | 0 | frame.descriptor_pool(), |
822 | 0 | frame.message_factory(), frame.arena())); |
823 | 0 | return absl::OkStatus(); |
824 | 0 | } |
825 | | |
826 | | absl::Status OptimizedSelectImpl::ApplySelect(ExecutionFrameBase& frame, |
827 | 0 | Value& result_in_out) const { |
828 | 0 | if (options_.force_fallback_implementation || typed_select_path_.empty()) { |
829 | 0 | CEL_ASSIGN_OR_RETURN( |
830 | 0 | result_in_out, |
831 | 0 | QualifyOrFallback(frame, result_in_out.GetStruct(), select_path_, |
832 | 0 | presence_test_, |
833 | 0 | options_.force_fallback_implementation)); |
834 | 0 | return absl::OkStatus(); |
835 | 0 | } |
836 | 0 | const google::protobuf::Message* current_message = nullptr; |
837 | 0 | bool is_unsafe = false; |
838 | 0 | if (result_in_out.IsParsedMessage()) { |
839 | 0 | ParsedMessageValue parsed_message = result_in_out.GetParsedMessage(); |
840 | 0 | current_message = &(*parsed_message); |
841 | 0 | is_unsafe = |
842 | 0 | cel::interop_internal::IsUnsafeParsedMessageValue(parsed_message); |
843 | 0 | } else if (const google::protobuf::Message* legacy_message = |
844 | 0 | cel::interop_internal::GetLegacyMessage(result_in_out); |
845 | 0 | legacy_message != nullptr) { |
846 | 0 | current_message = legacy_message; |
847 | 0 | is_unsafe = true; |
848 | 0 | } else { |
849 | 0 | CEL_ASSIGN_OR_RETURN( |
850 | 0 | result_in_out, |
851 | 0 | QualifyOrFallback(frame, result_in_out.GetStruct(), select_path_, |
852 | 0 | presence_test_, |
853 | 0 | options_.force_fallback_implementation)); |
854 | 0 | return absl::OkStatus(); |
855 | 0 | } |
856 | | |
857 | 0 | if (!SupportsCachedFieldDescriptor(current_message, typed_select_path_[0])) { |
858 | 0 | CEL_ASSIGN_OR_RETURN( |
859 | 0 | result_in_out, |
860 | 0 | QualifyOrFallback(frame, result_in_out.GetStruct(), select_path_, |
861 | 0 | presence_test_, |
862 | 0 | options_.force_fallback_implementation)); |
863 | 0 | return absl::OkStatus(); |
864 | 0 | } |
865 | | |
866 | 0 | for (size_t i = 0; i < typed_select_path_.size(); ++i) { |
867 | 0 | const TypedSelectStep& step = typed_select_path_[i]; |
868 | | |
869 | | // handle singular |
870 | 0 | if (const FieldSelectStep* field_step = |
871 | 0 | absl::get_if<FieldSelectStep>(&step); |
872 | 0 | field_step != nullptr) { |
873 | 0 | const google::protobuf::FieldDescriptor* field_descriptor = field_step->field; |
874 | | // We consumed the whole select path. Materialize the leaf. |
875 | 0 | if (i + 1 == select_path_.size()) { |
876 | 0 | if (presence_test_) { |
877 | 0 | result_in_out = |
878 | 0 | BoolValue{cel::UnsafeParsedMessageValue(current_message) |
879 | 0 | .HasField(field_descriptor)}; |
880 | 0 | return absl::OkStatus(); |
881 | 0 | } |
882 | 0 | result_in_out = WrapMessageField( |
883 | 0 | current_message, field_descriptor, is_unsafe, |
884 | 0 | frame.descriptor_pool(), frame.message_factory(), frame.arena()); |
885 | 0 | return absl::OkStatus(); |
886 | 0 | } |
887 | | |
888 | 0 | if (i + 1 >= typed_select_path_.size()) { |
889 | 0 | Value step_result = WrapMessageField( |
890 | 0 | current_message, field_descriptor, is_unsafe, |
891 | 0 | frame.descriptor_pool(), frame.message_factory(), frame.arena()); |
892 | 0 | return ContinueFromValue(frame, std::move(step_result), i + 1, |
893 | 0 | result_in_out); |
894 | 0 | } |
895 | | |
896 | 0 | if (field_descriptor->is_repeated()) { |
897 | | // The next step in `typed_select_path_` is a `MapSelectStep` or |
898 | | // `ListSelectStep` that operates on `current_message`. |
899 | 0 | continue; |
900 | 0 | } |
901 | | |
902 | 0 | const google::protobuf::Message* next_message = |
903 | 0 | ¤t_message->GetReflection()->GetMessage(*current_message, |
904 | 0 | field_descriptor); |
905 | | // Check for messages extended by overlays. This is redundant if all |
906 | | // messages are from hermetic pools, which we cannot guarantee. |
907 | 0 | if (!SupportsCachedFieldDescriptor(next_message, |
908 | 0 | typed_select_path_[i + 1])) { |
909 | 0 | Value step_result = WrapMessageField( |
910 | 0 | current_message, field_descriptor, is_unsafe, |
911 | 0 | frame.descriptor_pool(), frame.message_factory(), frame.arena()); |
912 | 0 | return ContinueFromValue(frame, std::move(step_result), i + 1, |
913 | 0 | result_in_out); |
914 | 0 | } |
915 | 0 | current_message = next_message; |
916 | 0 | continue; |
917 | 0 | } |
918 | | |
919 | | // Handle map |
920 | 0 | if (const MapSelectStep* map_step = absl::get_if<MapSelectStep>(&step); |
921 | 0 | map_step != nullptr) { |
922 | 0 | if (i + 1 == select_path_.size() && presence_test_) { |
923 | 0 | const AttributeQualifier& qualifier = |
924 | 0 | absl::get<AttributeQualifier>(select_path_[i]); |
925 | 0 | if (qualifier.kind() != cel::Kind::kString) { |
926 | 0 | result_in_out = ErrorValue::From( |
927 | 0 | runtime_internal::CreateNoMatchingOverloadError("has"), |
928 | 0 | frame.arena()); |
929 | 0 | return absl::OkStatus(); |
930 | 0 | } |
931 | 0 | if (!map_step->key.ok()) { |
932 | 0 | result_in_out = |
933 | 0 | ErrorValue::From(map_step->key.status(), frame.arena()); |
934 | 0 | return absl::OkStatus(); |
935 | 0 | } |
936 | 0 | bool found = protobuf_internal::ContainsMapKey( |
937 | 0 | *current_message->GetReflection(), *current_message, |
938 | 0 | *map_step->map_field, *map_step->key); |
939 | 0 | result_in_out = BoolValue{found}; |
940 | 0 | return absl::OkStatus(); |
941 | 0 | } |
942 | | |
943 | 0 | if (!map_step->key.ok()) { |
944 | 0 | result_in_out = ErrorValue::From(map_step->key.status(), frame.arena()); |
945 | 0 | return absl::OkStatus(); |
946 | 0 | } |
947 | 0 | google::protobuf::MapValueConstRef value_ref; |
948 | 0 | bool found = protobuf_internal::LookupMapValue( |
949 | 0 | *current_message->GetReflection(), *current_message, |
950 | 0 | *map_step->map_field, *map_step->key, &value_ref); |
951 | 0 | if (!found) { |
952 | 0 | const AttributeQualifier& qualifier = |
953 | 0 | absl::get<AttributeQualifier>(select_path_[i]); |
954 | 0 | result_in_out = ErrorValue::From( |
955 | 0 | runtime_internal::CreateNoSuchKeyError(qualifier.ToString()), |
956 | 0 | frame.arena()); |
957 | 0 | return absl::OkStatus(); |
958 | 0 | } |
959 | | |
960 | 0 | if (i + 1 == select_path_.size()) { |
961 | 0 | result_in_out = WrapMapElement( |
962 | 0 | value_ref, current_message, map_step->value_field, is_unsafe, |
963 | 0 | frame.descriptor_pool(), frame.message_factory(), frame.arena()); |
964 | 0 | return absl::OkStatus(); |
965 | 0 | } |
966 | | |
967 | | // We don't have a typed select step for the next step, so we fall back. |
968 | 0 | if (i + 1 >= typed_select_path_.size()) { |
969 | 0 | Value step_result = WrapMapElement( |
970 | 0 | value_ref, current_message, map_step->value_field, is_unsafe, |
971 | 0 | frame.descriptor_pool(), frame.message_factory(), frame.arena()); |
972 | 0 | return ContinueFromValue(frame, std::move(step_result), i + 1, |
973 | 0 | result_in_out); |
974 | 0 | } |
975 | | |
976 | 0 | const google::protobuf::Message* next_message = &value_ref.GetMessageValue(); |
977 | 0 | if (!SupportsCachedFieldDescriptor(next_message, |
978 | 0 | typed_select_path_[i + 1])) { |
979 | 0 | Value step_result = WrapMapElement( |
980 | 0 | value_ref, current_message, map_step->value_field, is_unsafe, |
981 | 0 | frame.descriptor_pool(), frame.message_factory(), frame.arena()); |
982 | 0 | return ContinueFromValue(frame, std::move(step_result), i + 1, |
983 | 0 | result_in_out); |
984 | 0 | } |
985 | 0 | current_message = next_message; |
986 | 0 | continue; |
987 | 0 | } |
988 | | |
989 | | // handle list |
990 | 0 | if (const ListSelectStep* list_step = absl::get_if<ListSelectStep>(&step); |
991 | 0 | list_step != nullptr) { |
992 | 0 | if (i + 1 == select_path_.size() && presence_test_) { |
993 | 0 | result_in_out = ErrorValue::From( |
994 | 0 | runtime_internal::CreateNoMatchingOverloadError("has"), |
995 | 0 | frame.arena()); |
996 | 0 | return absl::OkStatus(); |
997 | 0 | } |
998 | | |
999 | 0 | const AttributeQualifier& qualifier = |
1000 | 0 | absl::get<AttributeQualifier>(select_path_[i]); |
1001 | 0 | if (qualifier.kind() != cel::Kind::kInt64) { |
1002 | 0 | result_in_out = |
1003 | 0 | ErrorValue::From(runtime_internal::CreateNoMatchingOverloadError( |
1004 | 0 | cel::builtin::kIndex), |
1005 | 0 | frame.arena()); |
1006 | 0 | return absl::OkStatus(); |
1007 | 0 | } |
1008 | 0 | int64_t index = *qualifier.AsInt(); |
1009 | 0 | const google::protobuf::Reflection* reflection = current_message->GetReflection(); |
1010 | 0 | int size = |
1011 | 0 | reflection->FieldSize(*current_message, list_step->repeated_field); |
1012 | 0 | if (index < 0 || index >= size) { |
1013 | 0 | result_in_out = ErrorValue::From( |
1014 | 0 | absl::InvalidArgumentError(absl::StrCat( |
1015 | 0 | "index out of bounds: index=", index, " size=", size)), |
1016 | 0 | frame.arena()); |
1017 | 0 | return absl::OkStatus(); |
1018 | 0 | } |
1019 | 0 | int int_index = static_cast<int>(index); |
1020 | |
|
1021 | 0 | if (i + 1 == select_path_.size()) { |
1022 | 0 | result_in_out = WrapRepeatedElement( |
1023 | 0 | int_index, current_message, list_step->repeated_field, is_unsafe, |
1024 | 0 | frame.descriptor_pool(), frame.message_factory(), frame.arena()); |
1025 | 0 | return absl::OkStatus(); |
1026 | 0 | } |
1027 | | |
1028 | | // We don't have a typed select step for the next step, so we fall back. |
1029 | 0 | if (i + 1 >= typed_select_path_.size()) { |
1030 | 0 | Value step_result = WrapRepeatedElement( |
1031 | 0 | int_index, current_message, list_step->repeated_field, is_unsafe, |
1032 | 0 | frame.descriptor_pool(), frame.message_factory(), frame.arena()); |
1033 | 0 | return ContinueFromValue(frame, std::move(step_result), i + 1, |
1034 | 0 | result_in_out); |
1035 | 0 | } |
1036 | | |
1037 | 0 | const google::protobuf::Message* next_message = &reflection->GetRepeatedMessage( |
1038 | 0 | *current_message, list_step->repeated_field, int_index); |
1039 | 0 | if (!SupportsCachedFieldDescriptor(next_message, |
1040 | 0 | typed_select_path_[i + 1])) { |
1041 | 0 | Value step_result = WrapRepeatedElement( |
1042 | 0 | int_index, current_message, list_step->repeated_field, is_unsafe, |
1043 | 0 | frame.descriptor_pool(), frame.message_factory(), frame.arena()); |
1044 | 0 | return ContinueFromValue(frame, std::move(step_result), i + 1, |
1045 | 0 | result_in_out); |
1046 | 0 | } |
1047 | 0 | current_message = next_message; |
1048 | 0 | continue; |
1049 | 0 | } |
1050 | | |
1051 | 0 | ABSL_UNREACHABLE(); |
1052 | 0 | return absl::InternalError("Unknown select step type"); |
1053 | 0 | } |
1054 | | |
1055 | 0 | return absl::OkStatus(); |
1056 | 0 | } |
1057 | | |
1058 | | class StackMachineImpl : public ExpressionStepBase { |
1059 | | public: |
1060 | | StackMachineImpl(int expr_id, OptimizedSelectImpl impl) |
1061 | 0 | : ExpressionStepBase(expr_id), impl_(std::move(impl)) {} |
1062 | | |
1063 | | void Evaluate(ExecutionFrame* frame) const override; |
1064 | | |
1065 | | private: |
1066 | | OptimizedSelectImpl impl_; |
1067 | | }; |
1068 | | |
1069 | 0 | void StackMachineImpl::Evaluate(ExecutionFrame* frame) const { |
1070 | | // TODO(uncreated-issue/51): add support for variable qualifiers and string literal |
1071 | | // variable names. |
1072 | | // For now, we expect the operand to be top of stack. |
1073 | 0 | Value& operand = frame->value_stack().Peek(); |
1074 | 0 | AttributeTrail& trail = frame->value_stack().PeekAttribute(); |
1075 | |
|
1076 | 0 | if (operand.Is<ErrorValue>() || operand.Is<UnknownValue>()) { |
1077 | | // Just forward the error which is already top of stack. |
1078 | 0 | return; |
1079 | 0 | } |
1080 | | |
1081 | 0 | if (frame->enable_attribute_tracking()) { |
1082 | | // Compute the attribute trail then check for any marked values. |
1083 | | // When possible, this is computed at plan time based on the optimized |
1084 | | // select arguments. |
1085 | | // TODO(uncreated-issue/51): add support variable qualifiers |
1086 | 0 | for (const auto& qualifier : impl_.qualifiers()) { |
1087 | 0 | if (trail.Match<AttributeTrail::kFull>(qualifier, operand, |
1088 | 0 | frame->unknown_tree())) { |
1089 | 0 | return; |
1090 | 0 | } |
1091 | 0 | } |
1092 | 0 | } |
1093 | | |
1094 | 0 | if (!operand.Is<StructValue>()) { |
1095 | 0 | frame->Abort(absl::InvalidArgumentError( |
1096 | 0 | "Expected struct type for select optimization.")); |
1097 | 0 | return; |
1098 | 0 | } |
1099 | | |
1100 | 0 | absl::Status status = impl_.ApplySelect(*frame, operand); |
1101 | 0 | if (!status.ok()) { |
1102 | 0 | frame->Abort(std::move(status)); |
1103 | 0 | } |
1104 | 0 | } |
1105 | | |
1106 | | class SelectOptimizer : public ProgramOptimizer { |
1107 | | public: |
1108 | | explicit SelectOptimizer(const SelectOptimizationOptions& options) |
1109 | 0 | : options_(options) {} |
1110 | | |
1111 | 0 | absl::Status OnPreVisit(PlannerContext& context, const Expr& node) override { |
1112 | 0 | return absl::OkStatus(); |
1113 | 0 | } |
1114 | | |
1115 | | absl::Status OnPostVisit(PlannerContext& context, const Expr& node) override; |
1116 | | |
1117 | | private: |
1118 | | SelectOptimizationOptions options_; |
1119 | | }; |
1120 | | |
1121 | | std::vector<TypedSelectStep> BuildTypedSelectPath( |
1122 | | PlannerContext& context, const Expr& operand, |
1123 | 0 | absl::Span<const SelectQualifier> instructions) { |
1124 | 0 | std::vector<TypedSelectStep> typed_select_path; |
1125 | 0 | std::optional<cel::Type> current_type = context.GetResolvedType(operand.id()); |
1126 | 0 | for (const SelectQualifier& instruction : instructions) { |
1127 | 0 | if (!current_type.has_value()) { |
1128 | 0 | break; |
1129 | 0 | } |
1130 | 0 | if (const FieldSpecifier* field_specifier = |
1131 | 0 | absl::get_if<FieldSpecifier>(&instruction); |
1132 | 0 | field_specifier != nullptr) { |
1133 | 0 | if (!current_type->IsMessage()) { |
1134 | 0 | break; |
1135 | 0 | } |
1136 | 0 | cel::MessageType message_type = current_type->GetMessage(); |
1137 | 0 | absl::StatusOr<std::optional<cel::StructTypeField>> field = |
1138 | 0 | context.type_reflector().FindStructTypeFieldByName( |
1139 | 0 | message_type, field_specifier->name); |
1140 | 0 | if (!field.ok() || !field->has_value() || !(*field)->IsMessage()) { |
1141 | 0 | break; |
1142 | 0 | } |
1143 | 0 | const google::protobuf::Descriptor* containing_descriptor = |
1144 | 0 | message_type.descriptor(); |
1145 | 0 | const google::protobuf::FieldDescriptor* field_descriptor = |
1146 | 0 | (*field)->GetMessage().descriptor(); |
1147 | 0 | if (containing_descriptor->file()->pool() != |
1148 | 0 | field_descriptor->file()->pool()) { |
1149 | 0 | break; |
1150 | 0 | } |
1151 | 0 | typed_select_path.push_back( |
1152 | 0 | FieldSelectStep{containing_descriptor, field_descriptor}); |
1153 | 0 | current_type = (*field)->GetType(); |
1154 | 0 | } else if (const AttributeQualifier* attr_qualifier = |
1155 | 0 | absl::get_if<AttributeQualifier>(&instruction); |
1156 | 0 | attr_qualifier != nullptr) { |
1157 | 0 | if (typed_select_path.empty() || |
1158 | 0 | !absl::holds_alternative<FieldSelectStep>(typed_select_path.back())) { |
1159 | 0 | break; |
1160 | 0 | } |
1161 | 0 | const google::protobuf::FieldDescriptor* prev_field = |
1162 | 0 | absl::get<FieldSelectStep>(typed_select_path.back()).field; |
1163 | 0 | if (prev_field->is_map() && current_type->IsMap()) { |
1164 | 0 | const google::protobuf::Descriptor* entry_descriptor = prev_field->message_type(); |
1165 | 0 | const google::protobuf::FieldDescriptor* key_field = entry_descriptor->map_key(); |
1166 | 0 | const google::protobuf::FieldDescriptor* value_field = |
1167 | 0 | entry_descriptor->map_value(); |
1168 | 0 | if (key_field == nullptr || value_field == nullptr) { |
1169 | 0 | break; |
1170 | 0 | } |
1171 | 0 | typed_select_path.push_back( |
1172 | 0 | MapSelectStep{prev_field, key_field, value_field, |
1173 | 0 | CreateProtoMapKey(key_field, *attr_qualifier)}); |
1174 | 0 | current_type = current_type->GetMap().GetValue(); |
1175 | 0 | } else if (prev_field->is_repeated() && !prev_field->is_map() && |
1176 | 0 | current_type->IsList()) { |
1177 | 0 | typed_select_path.push_back(ListSelectStep{prev_field}); |
1178 | 0 | current_type = current_type->GetList().GetElement(); |
1179 | 0 | } else { |
1180 | 0 | break; |
1181 | 0 | } |
1182 | 0 | } else { |
1183 | 0 | break; |
1184 | 0 | } |
1185 | 0 | } |
1186 | 0 | return typed_select_path; |
1187 | 0 | } |
1188 | | |
1189 | | absl::Status SelectOptimizer::OnPostVisit(PlannerContext& context, |
1190 | 0 | const Expr& node) { |
1191 | 0 | if (!node.has_call_expr()) { |
1192 | 0 | return absl::OkStatus(); |
1193 | 0 | } |
1194 | | |
1195 | 0 | absl::string_view fn = node.call_expr().function(); |
1196 | 0 | if (fn != kCelHasField && fn != kCelAttribute) { |
1197 | 0 | return absl::OkStatus(); |
1198 | 0 | } |
1199 | 0 | const bool presence_test = fn == kCelHasField; |
1200 | | |
1201 | | // cel.@attribute may take a 3rd arg that only types the result; it's unused. |
1202 | 0 | const size_t max_args = presence_test ? 2 : 3; |
1203 | 0 | const size_t num_args = node.call_expr().args().size(); |
1204 | 0 | if (num_args < 2 || num_args > max_args) { |
1205 | 0 | return absl::InvalidArgumentError("Invalid cel.attribute call"); |
1206 | 0 | } |
1207 | | |
1208 | 0 | CEL_ASSIGN_OR_RETURN(std::vector<SelectQualifier> instructions, |
1209 | 0 | SelectInstructionsFromCall(node.call_expr())); |
1210 | |
|
1211 | 0 | if (instructions.empty()) { |
1212 | 0 | return absl::InvalidArgumentError("Invalid cel.attribute no select steps."); |
1213 | 0 | } |
1214 | | |
1215 | 0 | const Expr& operand = node.call_expr().args()[0]; |
1216 | 0 | absl::string_view identifier; |
1217 | 0 | if (operand.has_ident_expr()) { |
1218 | 0 | identifier = operand.ident_expr().name(); |
1219 | 0 | } |
1220 | |
|
1221 | 0 | if (absl::StrContains(identifier, ".")) { |
1222 | 0 | return absl::UnimplementedError("qualified identifiers not supported."); |
1223 | 0 | } |
1224 | | |
1225 | 0 | std::vector<AttributeQualifier> qualifiers; |
1226 | 0 | qualifiers.reserve(instructions.size()); |
1227 | 0 | for (const auto& instruction : instructions) { |
1228 | 0 | qualifiers.push_back( |
1229 | 0 | absl::visit(absl::Overload( |
1230 | 0 | [](const FieldSpecifier& field) { |
1231 | 0 | return AttributeQualifier::OfString(field.name); |
1232 | 0 | }, |
1233 | 0 | [](const AttributeQualifier& q) { return q; }), |
1234 | 0 | instruction)); |
1235 | 0 | } |
1236 | | |
1237 | | // TODO(uncreated-issue/51): If the first argument is a string literal, the custom |
1238 | | // step needs to handle variable lookup. |
1239 | 0 | auto* subexpression = context.program_builder().GetSubexpression(&node); |
1240 | 0 | if (subexpression == nullptr || subexpression->IsFlattened()) { |
1241 | | // No information on the subprogram, can't optimize. |
1242 | 0 | return absl::OkStatus(); |
1243 | 0 | } |
1244 | | |
1245 | 0 | std::vector<TypedSelectStep> typed_select_path; |
1246 | 0 | if (options_.enable_field_descriptor_caching && |
1247 | 0 | context.options().enable_typed_field_access) { |
1248 | 0 | typed_select_path = BuildTypedSelectPath(context, operand, instructions); |
1249 | 0 | } |
1250 | |
|
1251 | 0 | OptimizedSelectImpl impl(std::move(instructions), |
1252 | 0 | std::move(typed_select_path), std::move(qualifiers), |
1253 | 0 | presence_test, options_); |
1254 | |
|
1255 | 0 | google::api::expr::runtime::ExecutionPath path; |
1256 | | |
1257 | | // else, we need to preserve the original plan for the first argument. |
1258 | 0 | if (context.GetSubplan(operand).empty()) { |
1259 | | // Indicates another extension modified the step. Nothing to do here. |
1260 | 0 | return absl::OkStatus(); |
1261 | 0 | } |
1262 | 0 | CEL_ASSIGN_OR_RETURN(auto operand_subplan, context.ExtractSubplan(operand)); |
1263 | 0 | absl::c_move(operand_subplan, std::back_inserter(path)); |
1264 | |
|
1265 | 0 | path.push_back(ExpressionStep::MakeGenericStep( |
1266 | 0 | std::make_unique<StackMachineImpl>(node.id(), std::move(impl)), node.id(), |
1267 | 0 | /*stack_delta=*/0)); |
1268 | |
|
1269 | 0 | return context.ReplaceSubplan(node, std::move(path)); |
1270 | 0 | } |
1271 | | |
1272 | | google::api::expr::runtime::FlatExprBuilder* GetFlatExprBuilder( |
1273 | 0 | RuntimeBuilder& builder) { |
1274 | 0 | auto& runtime = |
1275 | 0 | runtime_internal::RuntimeFriendAccess::GetMutableRuntime(builder); |
1276 | 0 | if (runtime_internal::RuntimeFriendAccess::RuntimeTypeId(runtime) == |
1277 | 0 | NativeTypeId::For<runtime_internal::RuntimeImpl>()) { |
1278 | 0 | auto& runtime_impl = |
1279 | 0 | cel::internal::down_cast<runtime_internal::RuntimeImpl&>(runtime); |
1280 | 0 | return &runtime_impl.expr_builder(); |
1281 | 0 | } |
1282 | 0 | return nullptr; |
1283 | 0 | } |
1284 | | |
1285 | | } // namespace |
1286 | | |
1287 | | absl::Status SelectOptimizationAstUpdater::UpdateAst(PlannerContext& context, |
1288 | 0 | Ast& ast) const { |
1289 | 0 | RewriterImpl rewriter(ast, context, options_); |
1290 | 0 | AstRewrite(ast.mutable_root_expr(), rewriter); |
1291 | 0 | return rewriter.GetProgressStatus(); |
1292 | 0 | } |
1293 | | |
1294 | | google::api::expr::runtime::ProgramOptimizerFactory |
1295 | | CreateSelectOptimizationProgramOptimizer( |
1296 | 0 | const SelectOptimizationOptions& options) { |
1297 | 0 | return [=](PlannerContext& context, const Ast& ast) { |
1298 | 0 | if (options.enable_field_descriptor_caching) { |
1299 | 0 | context.set_resolve_types(); |
1300 | 0 | } |
1301 | 0 | return std::make_unique<SelectOptimizer>(options); |
1302 | 0 | }; |
1303 | 0 | } |
1304 | | |
1305 | | absl::Status EnableSelectOptimization( |
1306 | 0 | cel::RuntimeBuilder& builder, const SelectOptimizationOptions& options) { |
1307 | 0 | auto* flat_expr_builder = GetFlatExprBuilder(builder); |
1308 | 0 | if (flat_expr_builder == nullptr) { |
1309 | 0 | return absl::InvalidArgumentError( |
1310 | 0 | "SelectOptimization requires default runtime implementation"); |
1311 | 0 | } |
1312 | | |
1313 | 0 | flat_expr_builder->AddAstTransform( |
1314 | 0 | std::make_unique<SelectOptimizationAstUpdater>(options)); |
1315 | | // Add overloads for select optimization signature. |
1316 | | // These are never bound, only used to prevent the builder from failing on |
1317 | | // the overloads check. |
1318 | 0 | CEL_RETURN_IF_ERROR(builder.function_registry().RegisterLazyFunction( |
1319 | 0 | FunctionDescriptor(kCelAttribute, false, {Kind::kAny, Kind::kList}))); |
1320 | 0 | CEL_RETURN_IF_ERROR( |
1321 | 0 | builder.function_registry().RegisterLazyFunction(FunctionDescriptor( |
1322 | 0 | kCelAttribute, false, {Kind::kAny, Kind::kList, Kind::kAny}))); |
1323 | | |
1324 | 0 | CEL_RETURN_IF_ERROR(builder.function_registry().RegisterLazyFunction( |
1325 | 0 | FunctionDescriptor(kCelHasField, false, {Kind::kAny, Kind::kList}))); |
1326 | 0 | flat_expr_builder->enable_select_optimization(); |
1327 | | // Add runtime implementation. |
1328 | 0 | flat_expr_builder->AddProgramOptimizer( |
1329 | 0 | CreateSelectOptimizationProgramOptimizer(options)); |
1330 | 0 | return absl::OkStatus(); |
1331 | 0 | } |
1332 | | |
1333 | | } // namespace cel::extensions |