Coverage Report

Created: 2026-11-12 06:42

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/proc/self/cwd/common/internal/attribute_trail.h
Line
Count
Source
1
// Copyright 2026 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
// This header should ideally be moved to the runtime. Its here temporarily.
16
17
#ifndef THIRD_PARTY_CEL_CPP_COMMON_INTERNAL_ATTRIBUTE_TRAIL_H_
18
#define THIRD_PARTY_CEL_CPP_COMMON_INTERNAL_ATTRIBUTE_TRAIL_H_
19
20
#include <optional>
21
#include <utility>
22
23
#include "absl/base/macros.h"
24
#include "absl/base/optimization.h"
25
#include "absl/container/btree_set.h"
26
#include "absl/log/absl_check.h"
27
#include "absl/strings/string_view.h"
28
#include "absl/types/span.h"
29
#include "base/attribute.h"
30
#include "base/attribute_matcher.h"
31
#include "common/internal/unknowns.h"
32
#include "common/value.h"
33
#include "runtime/internal/errors.h"
34
35
namespace cel::common_internal {
36
37
[[nodiscard]]
38
inline UnknownValue AttributeMatchToUnknownValue(
39
0
    const AttributeMatcherNode* node, UnknownTree* tree) {
40
0
  ABSL_DCHECK(!node->key().IsWildcard());
41
0
  ABSL_DCHECK(tree != nullptr);
42
0
  UnknownAttributeNode* unknown = tree->Convert(node);
43
0
  return common_internal::MakeUnknownValue(UnknownSet{
44
0
      .root = tree->Root(),
45
0
      .attributes =
46
0
          common_internal::CreateUnknownAttributeSet(unknown, tree->GetArena()),
47
0
      .functions = nullptr,
48
0
  });
49
0
}
50
51
[[nodiscard]]
52
inline UnknownValue AttributeMatchToUnknownValue(AttributeMatch match,
53
0
                                                 UnknownTree* tree) {
54
0
  return common_internal::AttributeMatchToUnknownValue(
55
0
      common_internal::GetAttributeMatcherNode(match), tree);
56
0
}
57
58
[[nodiscard]]
59
inline UnknownValue AttributeMatchToUnknownValue(
60
    const AttributeMatcherNode* node, const AttributeQualifierView& key,
61
0
    UnknownTree* tree) {
62
0
  ABSL_DCHECK(node->key().IsWildcard() || node->key() == key);
63
0
  ABSL_DCHECK(tree != nullptr);
64
0
  UnknownAttributeNode* unknown = tree->Convert(node, key);
65
0
  return common_internal::MakeUnknownValue(UnknownSet{
66
0
      .root = tree->Root(),
67
0
      .attributes =
68
0
          common_internal::CreateUnknownAttributeSet(unknown, tree->GetArena()),
69
0
      .functions = nullptr,
70
0
  });
71
0
}
72
73
[[nodiscard]]
74
inline UnknownValue AttributeMatchToUnknownValue(
75
    AttributeMatch match, const AttributeQualifierView& key,
76
0
    UnknownTree* tree) {
77
0
  return common_internal::AttributeMatchToUnknownValue(
78
0
      common_internal::GetAttributeMatcherNode(match), key, tree);
79
0
}
80
81
[[nodiscard]]
82
inline UnknownValue AttributeMatchToUnknownValue(AttributeMatch match,
83
                                                 absl::string_view key,
84
0
                                                 UnknownTree* tree) {
85
0
  return common_internal::AttributeMatchToUnknownValue(
86
0
      common_internal::GetAttributeMatcherNode(match),
87
0
      AttributeQualifierView::OfString(key), tree);
88
0
}
89
90
[[nodiscard]]
91
inline ErrorValue AttributeMatchToMissingValue(
92
    const AttributeMatcherNode* node, const AttributeQualifierView& key,
93
0
    UnknownTree* tree) {
94
0
  ABSL_DCHECK(node->IsFull());
95
0
  ABSL_DCHECK(node->key().IsWildcard() || node->key() == key);
96
0
  ABSL_DCHECK(tree != nullptr);
97
  // We do not need to convert matcher.
98
0
  return ErrorValue::From(
99
0
      runtime_internal::CreateMissingAttributeError(tree->ToString(node, key)),
100
0
      tree->GetArena());
101
0
}
102
103
[[nodiscard]]
104
inline ErrorValue AttributeMatchToMissingValue(
105
    AttributeMatch match, const AttributeQualifierView& key,
106
0
    UnknownTree* tree) {
107
0
  return common_internal::AttributeMatchToMissingValue(
108
0
      common_internal::GetAttributeMatcherNode(match), key, tree);
109
0
}
110
111
[[nodiscard]]
112
inline ErrorValue AttributeMatchToMissingValue(AttributeMatch match,
113
                                               absl::string_view key,
114
0
                                               UnknownTree* tree) {
115
0
  return common_internal::AttributeMatchToMissingValue(
116
0
      common_internal::GetAttributeMatcherNode(match),
117
0
      AttributeQualifierView::OfString(key), tree);
118
0
}
119
120
class AttributeTrail;
121
class UnknownAccumulator;
122
123
// AttributeLeadMatch and AttributeTrail::Match make up the core of the
124
// unknown/known/missing attribute matching algorithm in the runtime. The former
125
// is used by identifier lookup and the later is used by selects and container
126
// accesses.
127
128
// Entry point into attribute matching for unknowns, knowns, and missing. It
129
// should be used when looking up variables from the embedder. All subsequent
130
// "stepping" is done through AttributeTrail::Match. The trail will filled out
131
// with any partial matches and the value will be set with an unknown value or
132
// error value if there are any full matches. The function returns true if a
133
// full match was encountered and the value is set, false otherwise.
134
[[nodiscard]]
135
bool AttributeLeadMatch(const AttributeMatcher& unknown_attributes,
136
                        const AttributeMatcher& known_attributes,
137
                        const AttributeMatcher& missing_attributes,
138
                        absl::string_view variable, Value& value,
139
                        AttributeTrail& trail, UnknownTree* unknown_tree);
140
141
class AttributeTrail {
142
 public:
143
  enum MatchMode {
144
    kFull = 0,
145
    kPartial,
146
  };
147
148
71.9M
  AttributeTrail() = default;
149
  AttributeTrail(const AttributeTrail&) = default;
150
  AttributeTrail& operator=(const AttributeTrail&) = default;
151
152
  // Called to advance attribute matching for unknowns, knowns, and missing. It
153
  // should be called before performing field access, map key accesses, list
154
  // indexing, and related operations. The trail will be filled out with any
155
  // partial matches and the value will be set with an unknown value or error
156
  // value if there are any full matches. The function returns true if a
157
  // full match was encountered and the value is set, false otherwise.
158
  template <MatchMode KnownUnknownMode,
159
            MatchMode MissingMode = MatchMode::kFull>
160
  [[nodiscard]]
161
  bool Match(const AttributeQualifierView& qualifier, Value& value,
162
0
             AttributeTrail& trail, UnknownTree* unknown_tree) const {
163
    // !!!WARNING!!!
164
    // trail can alias *this be careful when updating this code.
165
    // !!!WARNING!!!
166
0
    static_assert(MissingMode == MatchMode::kFull,
167
0
                  "we do not support partial matching for missing attributes");
168
0
    if (known_.IsNone()) {
169
      // Known is not being used or the default outcome for the trail is
170
      // unknown.
171
0
      ABSL_DCHECK(!unknown_.IsFull());
172
0
      trail.unknown_ = unknown_.MatchQualifier(qualifier);
173
0
      if (KnownUnknownMode == MatchMode::kPartial ? !trail.unknown_.IsNone()
174
0
                                                  : trail.unknown_.IsFull()) {
175
0
        trail.missing_ = AttributeMatch();
176
0
        value = AttributeMatchToUnknownValue(
177
0
            std::exchange(trail.unknown_, AttributeMatch()), qualifier,
178
0
            unknown_tree);
179
0
        return true;
180
0
      }
181
0
    } else {
182
      // Known is partial or full.
183
0
      if (unknown_.IsNone()) {
184
        // Unknown is none, it does not matter what known is the outcome is
185
        // known.
186
0
        trail.known_ = trail.unknown_ = AttributeMatch();
187
0
      } else {
188
0
        if (MatchSlow<KnownUnknownMode, MissingMode>(qualifier, value, trail,
189
0
                                                     unknown_tree)) {
190
0
          return true;
191
0
        }
192
0
      }
193
0
    }
194
0
    trail.missing_ = missing_.MatchQualifier(qualifier);
195
0
    if (trail.missing_.IsFull()) {
196
0
      trail.known_ = trail.unknown_ = AttributeMatch();
197
0
      value = AttributeMatchToMissingValue(
198
0
          std::exchange(trail.missing_, AttributeMatch()), qualifier,
199
0
          unknown_tree);
200
0
      return true;
201
0
    }
202
0
    return false;
203
0
  }
204
205
  // Save as above, except this attribute trail is updated.
206
  template <MatchMode KnownUnknownMode,
207
            MatchMode MissingMode = MatchMode::kFull>
208
  [[nodiscard]]
209
  bool Match(const AttributeQualifierView& qualifier, Value& value,
210
0
             UnknownTree* unknown_tree) {
211
0
    return Match<KnownUnknownMode, MissingMode>(qualifier, value, *this,
212
0
                                                unknown_tree);
213
0
  }
214
215
  ABSL_DEPRECATE_AND_INLINE()
216
0
  const AttributeTrail& attribute() const { return *this; }
217
218
  [[nodiscard]]
219
0
  bool IsNone() const {
220
0
    return missing_.IsNone() && unknown_.IsNone();
221
0
  }
222
223
  [[nodiscard]]
224
0
  bool IsFullMatch() const {
225
0
    return missing_.IsFull() || (unknown_.IsFull() && known_.IsNone());
226
0
  }
227
228
  [[nodiscard]]
229
  std::optional<UnknownValue> PartialUnknownMatch(
230
0
      UnknownTree* unknown_tree) const {
231
0
    ABSL_DCHECK(!known_.IsFull());
232
0
    if (!unknown_.IsNone()) {
233
0
      if (known_.IsPartialWildcard()) {
234
0
        return std::nullopt;
235
0
      }
236
0
      if (known_.IsPartial()) {
237
0
        return AttributeMatchToUnknownValue(known_, unknown_tree);
238
0
      }
239
0
      return AttributeMatchToUnknownValue(unknown_, unknown_tree);
240
0
    }
241
0
    return std::nullopt;
242
0
  }
243
244
0
  void Clear() { missing_ = known_ = unknown_ = AttributeMatch(); }
245
246
 private:
247
  friend class UnknownAccumulator;
248
  friend bool AttributeLeadMatch(const AttributeMatcher& unknown_attributes,
249
                                 const AttributeMatcher& known_attributes,
250
                                 const AttributeMatcher& missing_attributes,
251
                                 absl::string_view variable, Value& value,
252
                                 AttributeTrail& trail,
253
                                 UnknownTree* unknown_tree);
254
255
  // Out of line remainder of the logic for Match to allow the compiler to more
256
  // easily inline Match.
257
  template <MatchMode KnownUnknownMode,
258
            MatchMode MissingMode = MatchMode::kFull>
259
  [[nodiscard]]
260
  bool MatchSlow(const AttributeQualifierView& qualifier, Value& value,
261
0
                 AttributeTrail& trail, UnknownTree* unknown_tree) const {
262
0
    static_assert(MissingMode == MatchMode::kFull,
263
0
                  "we do not support partial matching for missing attributes");
264
    // Unknown is partial or full.
265
0
    if (known_.IsFull()) {
266
      // The default from here on out is known.
267
0
      trail.known_ = trail.unknown_ = AttributeMatch();
268
0
      return false;
269
0
    }
270
    // Partial known.
271
0
    ABSL_DCHECK(known_.IsPartial());
272
0
    if (unknown_.IsFull()) {
273
      // The default from here on out is unknown unless we get full known.
274
      // To signal this we leave unknown as full and only match known.
275
0
      trail.unknown_ = unknown_;
276
0
      AttributeMatch prev_known = known_;
277
0
      trail.known_ = known_.MatchQualifier(qualifier);
278
0
      switch (trail.known_.GetType()) {
279
0
        case AttributeMatch::Type::NONE: {
280
          // Result is unknown.
281
0
          trail.missing_ = AttributeMatch();
282
0
          trail.unknown_ = AttributeMatch();
283
0
          UnknownAttributeNode* match =
284
0
              unknown_tree->Convert(prev_known)->Step(unknown_tree, qualifier);
285
0
          value = cel::common_internal::MakeUnknownValue(
286
0
              cel::common_internal::UnknownSet{
287
0
                  .root = unknown_tree->Root(),
288
0
                  .attributes = cel::common_internal::CreateUnknownAttributeSet(
289
0
                      match, unknown_tree->GetArena()),
290
0
                  .functions = nullptr});
291
0
          return true;
292
0
        }
293
0
        case AttributeMatch::Type::PARTIAL:
294
          // If we have a known attribute pattern `a.b.*` and we just
295
          // advanced to `a.b`, we do not consider that partial unknown we
296
          // consider that full known.
297
0
          if (!trail.known_.IsPartialWildcard()) {
298
0
            if (KnownUnknownMode != MatchMode::kPartial) {
299
0
              break;
300
0
            }
301
            // Result is unknown.
302
0
            trail.unknown_ = AttributeMatch();
303
0
            trail.missing_ = AttributeMatch();
304
0
            value = AttributeMatchToUnknownValue(
305
0
                std::exchange(trail.known_, AttributeMatch()), qualifier,
306
0
                unknown_tree);
307
0
            return true;
308
0
          }
309
0
          [[fallthrough]];
310
0
        case AttributeMatch::Type::FULL:
311
          // Result is known.
312
0
          trail.known_ = trail.unknown_ = AttributeMatch();
313
0
          break;
314
0
      }
315
0
      return false;
316
0
    }
317
0
    ABSL_DCHECK(unknown_.IsPartial());
318
    // Partial known and unknown.
319
0
    trail.known_ = known_.MatchQualifier(qualifier);
320
0
    trail.unknown_ = unknown_.MatchQualifier(qualifier);
321
0
    if (trail.known_.IsNone()) {
322
0
      if (KnownUnknownMode == MatchMode::kPartial ? !trail.unknown_.IsNone()
323
0
                                                  : trail.unknown_.IsFull()) {
324
0
        trail.missing_ = AttributeMatch();
325
0
        value = AttributeMatchToUnknownValue(
326
0
            std::exchange(trail.unknown_, AttributeMatch()), qualifier,
327
0
            unknown_tree);
328
0
        return true;
329
0
      }
330
0
    } else {
331
0
      if (trail.unknown_.IsNone()) {
332
0
        trail.known_ = AttributeMatch();
333
0
      } else if (trail.known_.IsFull() || trail.known_.IsPartialWildcard()) {
334
0
        trail.known_ = AttributeMatch();
335
0
        trail.unknown_ = AttributeMatch();
336
0
      }
337
0
    }
338
0
    return false;
339
0
  }
340
341
  // Should only be called from when the unknown accumulator.
342
0
  AttributeMatch GetNotFullUnknownMatch() const {
343
0
    if (known_.IsPartialWildcard()) {
344
      // If we have a known attribute pattern `a.b.*` and we just
345
      // advanced to `a.b`, we do not consider that partial.
346
0
      return AttributeMatch();
347
0
    }
348
0
    ABSL_DCHECK(!unknown_.IsFull());
349
0
    ABSL_DCHECK(!known_.IsFull());
350
0
    if (known_.IsPartial()) {
351
0
      return known_;
352
0
    }
353
0
    return unknown_;
354
0
  }
355
356
  // Due to the complicated logic required to correctly perform attribute
357
  // matching with missing, known, and unknown attributes we keep all this an
358
  // implementation detail and return only what the caller needs to see.
359
360
  // Current match in the attribute matcher used for missing attributes.
361
  AttributeMatch missing_;
362
  // Current match in the attribute matcher used for known attributes.
363
  AttributeMatch known_;
364
  // Current match in the attribute matcher used for unknown attributes.
365
  AttributeMatch unknown_;
366
};
367
368
[[nodiscard]]
369
inline bool AttributeLeadMatch(const AttributeMatcher& unknown_attributes,
370
                               const AttributeMatcher& known_attributes,
371
                               const AttributeMatcher& missing_attributes,
372
                               absl::string_view variable, Value& value,
373
                               AttributeTrail& trail,
374
0
                               UnknownTree* unknown_tree) {
375
0
  trail.known_ = known_attributes.MatchVariable(variable);
376
0
  trail.unknown_ = unknown_attributes.MatchVariable(variable);
377
0
  if (trail.known_.IsNone()) {
378
0
    if (trail.unknown_.IsFull()) {
379
0
      trail.missing_ = AttributeMatch();
380
0
      value = AttributeMatchToUnknownValue(
381
0
          std::exchange(trail.unknown_, AttributeMatch()), variable,
382
0
          unknown_tree);
383
0
      return true;
384
0
    }
385
0
  } else {
386
0
    if (trail.unknown_.IsNone()) {
387
0
      trail.known_ = AttributeMatch();
388
0
    } else if (trail.known_.IsFull() || trail.known_.IsPartialWildcard()) {
389
0
      trail.known_ = trail.unknown_ = AttributeMatch();
390
0
    }
391
0
  }
392
0
  trail.missing_ = missing_attributes.MatchVariable(variable);
393
0
  if (trail.missing_.IsFull()) {
394
0
    trail.known_ = trail.unknown_ = AttributeMatch();
395
0
    value = AttributeMatchToMissingValue(
396
0
        std::exchange(trail.missing_, AttributeMatch()), variable,
397
0
        unknown_tree);
398
0
    return true;
399
0
  }
400
0
  return false;
401
0
}
402
403
class UnknownAccumulator {
404
 public:
405
  UnknownAccumulator(const UnknownAccumulator&) = delete;
406
  UnknownAccumulator(UnknownAccumulator&&) = delete;
407
  UnknownAccumulator& operator=(const UnknownAccumulator&) = delete;
408
  UnknownAccumulator& operator=(UnknownAccumulator&&) = delete;
409
410
0
  explicit UnknownAccumulator(UnknownTree* tree) : tree_(tree) {
411
0
    ABSL_DCHECK(tree != nullptr);
412
0
  }
413
414
0
  void Add(const UnknownValue& value) {
415
0
    Add(common_internal::GetUnknownValueRep(value));
416
0
  }
417
418
  void Add(const UnknownSet& value);
419
420
0
  void Add(AttributeMatch match) {
421
0
    ABSL_DCHECK(!match.IsNone());
422
0
    unknown_attributes_.insert(
423
0
        tree_->Convert(common_internal::GetAttributeMatcherNode(match)));
424
0
    empty_ = false;
425
0
  }
426
427
0
  void MaybeAdd(AttributeMatch match) {
428
0
    if (!match.IsNone()) {
429
0
      Add(match);
430
0
    }
431
0
  }
432
433
0
  void MaybeAdd(const Value& value) {
434
0
    if (auto unknown_value = value.AsUnknown(); unknown_value.has_value()) {
435
0
      Add(*unknown_value);
436
0
    }
437
0
  }
438
439
0
  void MaybeAdd(const AttributeTrail& trail) {
440
0
    MaybeAdd(trail.GetNotFullUnknownMatch());
441
0
  }
442
443
0
  void MaybeAdd(const Value& value, AttributeMatch match) {
444
0
    if (auto unknown_value = value.AsUnknown(); unknown_value.has_value()) {
445
0
      Add(*unknown_value);
446
0
    } else {
447
0
      MaybeAdd(match);
448
0
    }
449
0
  }
450
451
0
  void MaybeAdd(const Value& value, const AttributeTrail& trail) {
452
0
    MaybeAdd(value, trail.GetNotFullUnknownMatch());
453
0
  }
454
455
  [[nodiscard]]
456
0
  bool IsEmpty() const {
457
0
    return empty_;
458
0
  }
459
460
  [[nodiscard]]
461
  std::optional<UnknownValue> Accumulate() &&;
462
463
  [[nodiscard]]
464
0
  UnknownValue Build() && {
465
0
    return std::move(*this).Accumulate().value_or(UnknownValue());
466
0
  }
467
468
 private:
469
  void Add(const UnknownAttributeSet* set);
470
471
  void Add(const UnknownFunctionSet* set);
472
473
  UnknownTree* const tree_;
474
  // BTrees used to perform merges when more than two unknown sets are
475
  // encountered. Merges between two sets are performed without additional
476
  // memory.
477
  absl::btree_set<UnknownAttributeNode*> unknown_attributes_;
478
  absl::btree_set<UnknownFunctionNode*> unknown_functions_;
479
  const UnknownAttributeSet* largest_unknown_attribute_set_ = nullptr;
480
  const UnknownFunctionSet* largest_unknown_function_set_ = nullptr;
481
  const UnknownAttributeSet* unknown_attribute_set_pair_[2] = {nullptr,
482
                                                               nullptr};
483
  const UnknownFunctionSet* unknown_function_set_pair_[2] = {nullptr, nullptr};
484
  bool added_unknown_attribute_set_pair_ = false;
485
  bool added_unknown_function_set_pair_ = false;
486
  bool empty_ = true;
487
};
488
489
[[nodiscard]]
490
inline std::optional<UnknownValue> PartiallyIdentifyAndMergeUnknowns(
491
    absl::Span<const Value> values, absl::Span<const AttributeTrail> attributes,
492
0
    UnknownTree* tree) {
493
0
  ABSL_DCHECK_EQ(values.size(), attributes.size());
494
0
  ABSL_DCHECK(tree != nullptr);
495
0
  UnknownAccumulator accumulator(tree);
496
0
  for (const Value& value : values) {
497
0
    accumulator.MaybeAdd(value);
498
0
  }
499
  // There should not be any full unknown matches in attributes, so only inspect
500
  // it if we want partials.
501
0
  for (const AttributeTrail& attribute : attributes) {
502
0
    accumulator.MaybeAdd(attribute);
503
0
  }
504
0
  return std::move(accumulator).Accumulate();
505
0
}
506
507
[[nodiscard]]
508
inline std::optional<UnknownValue> FullyIdentifyAndMergeUnknowns(
509
0
    absl::Span<const Value> values, UnknownTree* tree) {
510
0
  ABSL_DCHECK(tree != nullptr);
511
0
  UnknownAccumulator accumulator(tree);
512
0
  for (const Value& value : values) {
513
0
    accumulator.MaybeAdd(value);
514
0
  }
515
0
  return std::move(accumulator).Accumulate();
516
0
}
517
518
[[nodiscard]]
519
inline UnknownValue GraftUnknowns(const UnknownValue& value,
520
0
                                  UnknownTree* tree) {
521
0
  ABSL_DCHECK(tree != nullptr);
522
0
  return common_internal::MakeUnknownValue(
523
0
      tree->Graft(common_internal::GetUnknownValueRep(value)));
524
0
}
525
526
[[nodiscard]]
527
0
inline Value GraftUnknowns(const Value& value, UnknownTree* tree) {
528
0
  ABSL_DCHECK(tree != nullptr);
529
0
  if (auto unknown_value = value.AsUnknown();
530
0
      ABSL_PREDICT_FALSE(unknown_value.has_value())) {
531
0
    return common_internal::GraftUnknowns(*unknown_value, tree);
532
0
  }
533
0
  return value;
534
0
}
535
536
0
inline void GraftUnknownsAt(UnknownValue& value, UnknownTree* tree) {
537
0
  ABSL_DCHECK(tree != nullptr);
538
0
  tree->GraftAt(common_internal::GetUnknownValueRep(value));
539
0
}
540
541
0
inline void GraftUnknownsAt(Value& value, UnknownTree* tree) {
542
0
  ABSL_DCHECK(tree != nullptr);
543
0
  if (auto unknown_value = value.AsUnknown();
544
0
      ABSL_PREDICT_FALSE(unknown_value.has_value())) {
545
0
    tree->GraftAt(common_internal::GetUnknownValueRep(*unknown_value));
546
0
  }
547
0
}
548
549
}  // namespace cel::common_internal
550
551
#endif  // THIRD_PARTY_CEL_CPP_COMMON_INTERNAL_ATTRIBUTE_TRAIL_H_