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/unknowns.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
#ifndef THIRD_PARTY_CEL_CPP_COMMON_INTERNAL_UNKNOWNS_H_
16
#define THIRD_PARTY_CEL_CPP_COMMON_INTERNAL_UNKNOWNS_H_
17
18
#include <cstddef>
19
#include <cstdint>
20
#include <cstring>
21
#include <limits>
22
#include <string>
23
#include <variant>
24
25
#include "absl/base/attributes.h"
26
#include "absl/base/nullability.h"
27
#include "absl/base/optimization.h"
28
#include "absl/container/flat_hash_set.h"
29
#include "absl/container/inlined_vector.h"
30
#include "absl/functional/overload.h"
31
#include "absl/log/absl_check.h"
32
#include "absl/strings/string_view.h"
33
#include "base/attribute.h"
34
#include "base/attribute_matcher.h"
35
#include "internal/arena_tree.h"
36
#include "google/protobuf/arena.h"
37
38
namespace cel::common_internal {
39
40
class UnknownAttributeNode;
41
class UnknownTree;
42
class UnknownRoot;
43
struct UnknownFunctionSet;
44
struct UnknownAttributeSet;
45
46
// Node in an arena-based red black tree. Leaf nodes are matches to unknown
47
// attributes. The root node is owned by UnknownRoot. Nodes which are direct
48
// children of the root node are variables. All nodes below them are qualifiers.
49
class UnknownAttributeNode
50
    : public internal::ArenaTreeNodeCrtp<UnknownAttributeNode> {
51
 private:
52
  struct Compare {
53
    using is_transparent = void;
54
55
    int operator()(const AttributeQualifierView& lhs,
56
0
                   const AttributeQualifierView& rhs) const {
57
0
      if (lhs < rhs) {
58
0
        return -1;
59
0
      }
60
0
      if (lhs == rhs) {
61
0
        return 0;
62
0
      }
63
0
      return 1;
64
0
    }
65
66
    int operator()(const AttributeQualifierView& lhs,
67
0
                   const UnknownAttributeNode& rhs) const {
68
0
      return (*this)(lhs, rhs.key());
69
0
    }
70
71
    int operator()(const UnknownAttributeNode& lhs,
72
0
                   const AttributeQualifierView& rhs) const {
73
0
      return (*this)(lhs.key(), rhs);
74
0
    }
75
76
    int operator()(const UnknownAttributeNode& lhs,
77
0
                   const UnknownAttributeNode& rhs) const {
78
0
      return (*this)(lhs.key(), rhs.key());
79
0
    }
80
  };
81
82
 public:
83
  explicit UnknownAttributeNode(UnknownAttributeNode* absl_nullable parent,
84
                                const AttributeQualifierView& key)
85
0
      : ArenaTreeNodeCrtp(),
86
0
        parent_(parent),
87
0
        key_(key),
88
0
        depth_(parent != nullptr ? parent->depth() + 1 : 0) {}
89
90
  [[nodiscard]]
91
0
  const AttributeQualifierView& key() const {
92
0
    return key_;
93
0
  }
94
95
  [[nodiscard]]
96
0
  UnknownAttributeNode* parent() const {
97
0
    return parent_;
98
0
  }
99
100
  [[nodiscard]]
101
0
  size_t depth() const {
102
0
    return depth_;
103
0
  }
104
105
  [[nodiscard]]
106
  UnknownAttributeNode* Step(UnknownTree* absl_nonnull tree,
107
                             const AttributeQualifierView& key);
108
109
  [[nodiscard]]
110
0
  UnknownAttributeNode* Find(const AttributeQualifierView& key) const {
111
0
    return internal::ArenaTreeFind(children_, key, Compare{});
112
0
  }
113
114
 private:
115
  // Pointer to our parent node. If this is null, then this node is the root
116
  // node and its key is invalid. If this is a pointer to the root node then
117
  // this node is a variable and the key is guaranteed to be a string.
118
  UnknownAttributeNode* const absl_nullability_unknown parent_ = nullptr;
119
  const AttributeQualifierView key_;
120
  // How many nodes between us and the root node.
121
  const size_t depth_;
122
  // Root of the red black tree for children.
123
  UnknownAttributeNode* absl_nullable children_ = nullptr;
124
};
125
126
// Node in an arena-based red black tree. Leaf nodes are matches to unknown
127
// functions. The root node is owned by UnknownRoot.
128
class UnknownFunctionNode
129
    : public internal::ArenaTreeNodeCrtp<UnknownFunctionNode> {
130
 public:
131
  struct Compare {
132
    using is_transparent = void;
133
134
0
    int operator()(absl::string_view lhs, absl::string_view rhs) const {
135
0
      return lhs.compare(rhs);
136
0
    }
137
138
    int operator()(absl::string_view lhs,
139
0
                   const UnknownFunctionNode& rhs) const {
140
0
      return (*this)(lhs, rhs.key());
141
0
    }
142
143
    int operator()(const UnknownFunctionNode& lhs,
144
0
                   absl::string_view rhs) const {
145
0
      return (*this)(lhs.key(), rhs);
146
0
    }
147
148
    int operator()(const UnknownFunctionNode& lhs,
149
0
                   const UnknownFunctionNode& rhs) const {
150
0
      return (*this)(lhs.key(), rhs.key());
151
0
    }
152
  };
153
154
  explicit UnknownFunctionNode(absl::string_view key)
155
0
      : ArenaTreeNodeCrtp(), key_(key) {}
156
157
  [[nodiscard]]
158
0
  absl::string_view key() const {
159
0
    return key_;
160
0
  }
161
162
 private:
163
  const absl::string_view key_;
164
};
165
166
class UnknownTree;
167
168
[[nodiscard]]
169
absl::string_view ArenaString(google::protobuf::Arena* absl_nonnull arena,
170
                              absl::string_view string);
171
172
// Holds the the red black tree for functions and the root attribute node which
173
// holds a red black tree for variables. The root is lazily created on the arena
174
// by UnknownTree as needed.
175
class UnknownRoot {
176
 public:
177
  explicit UnknownRoot(google::protobuf::Arena* absl_nonnull arena)
178
0
      : arena_(arena), attributes_(nullptr, AttributeQualifierView()) {}
179
180
  [[nodiscard]]
181
0
  google::protobuf::Arena* absl_nonnull GetArena() const {
182
0
    return arena_;
183
0
  }
184
185
  [[nodiscard]]
186
0
  UnknownAttributeNode* absl_nonnull Attributes() {
187
0
    return &attributes_;
188
0
  }
189
190
  [[nodiscard]]
191
0
  const UnknownAttributeNode* absl_nonnull Attributes() const {
192
0
    return &attributes_;
193
0
  }
194
195
  [[nodiscard]]
196
  UnknownFunctionNode* absl_nonnull SetFunction(UnknownTree* absl_nonnull tree,
197
                                                absl::string_view name);
198
199
  [[nodiscard]]
200
  UnknownFunctionNode* absl_nullable FindFunction(absl::string_view name) const;
201
202
 private:
203
  google::protobuf::Arena* const absl_nonnull arena_;
204
  UnknownAttributeNode attributes_;
205
  UnknownFunctionNode* functions_ = nullptr;
206
};
207
208
// Represents a set of unknown function nodes.
209
struct UnknownFunctionSet {
210
  size_t size;
211
  // Nodes are sorted in ascending order by pointer. There are no duplicates.
212
  UnknownFunctionNode* absl_nonnull nodes[];
213
214
  [[nodiscard]]
215
  static UnknownFunctionSet* Allocate(size_t size,
216
                                      google::protobuf::Arena* absl_nonnull arena) {
217
    ABSL_DCHECK_GT(size, 0);
218
    UnknownFunctionSet* ptr = reinterpret_cast<UnknownFunctionSet*>(
219
        arena->AllocateAligned(offsetof(UnknownFunctionSet, nodes) +
220
                               (size * sizeof(UnknownFunctionNode*))));
221
    ptr->size = size;
222
    return ptr;
223
  }
224
};
225
226
// Represents a set of unknown attribute nodes, which themselves represent a
227
// partial or full match to an unknown attribute.
228
struct UnknownAttributeSet {
229
  uint32_t size;
230
  uint32_t max_depth;
231
  // Nodes are sorted in ascending order by pointer. There are no duplicates.
232
  UnknownAttributeNode* absl_nonnull nodes[];
233
234
  [[nodiscard]]
235
  static UnknownAttributeSet* Allocate(size_t size,
236
                                       google::protobuf::Arena* absl_nonnull arena) {
237
    ABSL_DCHECK_GT(size, 0);
238
    ABSL_DCHECK_LE(size, std::numeric_limits<uint32_t>::max());
239
    UnknownAttributeSet* ptr = reinterpret_cast<UnknownAttributeSet*>(
240
        arena->AllocateAligned(offsetof(UnknownAttributeSet, nodes) +
241
                               (size * sizeof(UnknownAttributeNode*))));
242
    ptr->size = static_cast<uint32_t>(size);
243
    return ptr;
244
  }
245
};
246
247
// Underlying representation used by UnknownValue.
248
struct UnknownSet {
249
  const UnknownRoot* root = nullptr;
250
  const UnknownAttributeSet* attributes = nullptr;
251
  const UnknownFunctionSet* functions = nullptr;
252
};
253
254
// Used by the runtime to build unknown attribute and unknown function trees.
255
class UnknownTree {
256
 public:
257
18.9k
  UnknownTree() : arena_(nullptr) {}
258
259
  UnknownTree(const UnknownTree&) = delete;
260
  UnknownTree& operator=(const UnknownTree&) = delete;
261
262
0
  explicit UnknownTree(google::protobuf::Arena* absl_nonnull arena) : arena_(arena) {
263
0
    ABSL_DCHECK(arena != nullptr);
264
0
  }
265
266
18.9k
  void Reset(google::protobuf::Arena* absl_nonnull arena) {
267
18.9k
    ABSL_DCHECK(arena != nullptr);
268
18.9k
    arena_ = arena;
269
18.9k
    root_ = nullptr;
270
18.9k
    strings_.clear();
271
18.9k
    scratch_.clear();
272
18.9k
  }
273
274
  [[nodiscard]]
275
0
  google::protobuf::Arena* absl_nonnull GetArena() const {
276
0
    ABSL_DCHECK(arena_ != nullptr);
277
0
    return arena_;
278
0
  }
279
280
  [[nodiscard]]
281
0
  UnknownRoot* absl_nonnull Root() {
282
0
    UnknownRoot* root = RootIfPresent();
283
0
    if (ABSL_PREDICT_FALSE(root == nullptr)) {
284
0
      root_ = root = google::protobuf::Arena::Create<UnknownRoot>(GetArena(), GetArena());
285
0
    }
286
0
    return root;
287
0
  }
288
289
  [[nodiscard]]
290
0
  UnknownRoot* absl_nullable RootIfPresent() const {
291
0
    return root_;
292
0
  }
293
294
  // Called when an unknown attribute match is encountered to materialize the
295
  // match in the unknown attribute tree.
296
  [[nodiscard]]
297
  UnknownAttributeNode* absl_nonnull Convert(
298
      const AttributeMatcherNode* absl_nonnull matcher,
299
0
      const AttributeQualifierView& key) {
300
0
    const bool is_wildcard = matcher->key().IsWildcard();
301
0
    ABSL_DCHECK(is_wildcard || matcher->key() == key);
302
0
    if (is_wildcard) {
303
0
      return Convert(matcher->parent())->Step(this, key);
304
0
    }
305
0
    return Convert(matcher);
306
0
  }
307
  [[nodiscard]]
308
  UnknownAttributeNode* absl_nonnull Convert(
309
      const AttributeMatcherNode* absl_nonnull matcher);
310
  [[nodiscard]]
311
  UnknownAttributeNode* absl_nonnull Convert(
312
0
      const AttributeMatch& match, const AttributeQualifierView& key) {
313
0
    return Convert(common_internal::GetAttributeMatcherNode(match), key);
314
0
  }
315
  [[nodiscard]]
316
0
  UnknownAttributeNode* absl_nonnull Convert(const AttributeMatch& match) {
317
0
    return Convert(common_internal::GetAttributeMatcherNode(match));
318
0
  }
319
320
  // Converts an unknown attribute node to its corresponding attribute pattern
321
  // string, as if the node was converted to AttributePattern and
322
  // AttributePattern::ToString was called.
323
  [[nodiscard]]
324
  std::string ToString(const AttributeMatcherNode* absl_nonnull matcher,
325
                       const AttributeQualifierView& key);
326
  [[nodiscard]]
327
  std::string ToString(const AttributeMatch& match,
328
0
                       const AttributeQualifierView& key) {
329
0
    return ToString(common_internal::GetAttributeMatcherNode(match), key);
330
0
  }
331
332
  // Converts an unknown attribute node to its corresponding attribute string,
333
  // as if the node was converted to Attribute and Attribute::ToString was
334
  // called.
335
  [[nodiscard]]
336
  std::string ToString(const UnknownAttributeNode* absl_nonnull unknown);
337
338
  // In the rare event that somebody manages to pass an unknown set from one
339
  // expression into another, we need to be able to graft those nodes into our
340
  // tree. The unknown attribute set and unknown function set sort nodes by
341
  // address for efficiency. This function does that grafting when it is
342
  // required.
343
  [[nodiscard]]
344
0
  ABSL_ATTRIBUTE_ALWAYS_INLINE UnknownSet Graft(const UnknownSet& in) {
345
    // Fast path, should be taken almost always.
346
0
    UnknownSet out;
347
0
    if (ABSL_PREDICT_TRUE(in.root == nullptr || in.root == RootIfPresent())) {
348
0
      ABSL_DCHECK(in.root != nullptr || in.attributes == nullptr);
349
0
      ABSL_DCHECK(in.root != nullptr || in.functions == nullptr);
350
0
      out = in;
351
0
    } else {
352
      // Slow path, should be taken extremely rarely.
353
0
      GraftImpl(in, out);
354
0
    }
355
0
    return out;
356
0
  }
357
358
  // In the rare event that somebody manages to pass an unknown set from one
359
  // expression into another, we need to be able to graft those nodes into our
360
  // tree. The unknown attribute set and unknown function set sort nodes by
361
  // address for efficiency. This function does that grafting when it is
362
  // required.
363
0
  ABSL_ATTRIBUTE_ALWAYS_INLINE void GraftAt(UnknownSet& in) {
364
0
    if (ABSL_PREDICT_TRUE(in.root == nullptr || in.root == RootIfPresent())) {
365
      // Fast path, should be taken almost always.
366
0
      ABSL_DCHECK(in.root != nullptr || in.attributes == nullptr);
367
0
      ABSL_DCHECK(in.root != nullptr || in.functions == nullptr);
368
0
    } else {
369
      // Slow path, should be taken extremely rarely.
370
0
      GraftImpl(in, in);
371
0
    }
372
0
  }
373
374
 private:
375
  friend class UnknownAttributeNode;
376
  friend class UnknownRoot;
377
378
  ABSL_ATTRIBUTE_NOINLINE void GraftImpl(const UnknownSet& in, UnknownSet& out);
379
380
  [[nodiscard]]
381
  UnknownAttributeNode* GraftImpl(const UnknownAttributeNode* in);
382
383
  [[nodiscard]]
384
0
  UnknownFunctionNode* GraftImpl(const UnknownFunctionNode* in) {
385
0
    return Root()->SetFunction(this, in->key());
386
0
  }
387
388
  [[nodiscard]]
389
  std::string ToString(const AttributeMatcherNode* absl_nonnull matcher);
390
391
  [[nodiscard]]
392
0
  AttributeQualifierView InternKey(const AttributeQualifierView& key) {
393
0
    return std::visit(
394
0
        absl::Overload(
395
0
            [](std::monostate) -> AttributeQualifierView {
396
0
              return AttributeQualifierView();
397
0
            },
398
0
            [](bool value) -> AttributeQualifierView {
399
0
              return AttributeQualifierView::OfBool(value);
400
0
            },
401
0
            [](int64_t value) -> AttributeQualifierView {
402
0
              return AttributeQualifierView::OfInt(value);
403
0
            },
404
0
            [](uint64_t value) -> AttributeQualifierView {
405
0
              return AttributeQualifierView::OfUint(value);
406
0
            },
407
0
            [this](absl::string_view value) -> AttributeQualifierView {
408
0
              return AttributeQualifierView::OfString(InternStringKey(value));
409
0
            }),
410
0
        common_internal::AsVariant(key));
411
0
  }
412
413
  [[nodiscard]]
414
0
  absl::string_view InternStringKey(absl::string_view key) {
415
0
    if (key.empty()) {
416
0
      return "";
417
0
    }
418
0
    return *strings_.lazy_emplace(key, [this, key](const auto& constructor) {
419
0
      constructor((ArenaString)(GetArena(), key));
420
0
    });
421
0
  }
422
423
  google::protobuf::Arena* absl_nullability_unknown arena_;
424
  // Created as needed.
425
  UnknownRoot* absl_nullable root_ = nullptr;
426
  // These strings are actually null terminated.
427
  absl::flat_hash_set<absl::string_view> strings_;
428
  // Temporary storage for materializing AttributeMatcherNode* trail to
429
  // UnknownAttributeNode* or for converting either type to a string.
430
  absl::InlinedVector<const void* absl_nullability_unknown, 2> scratch_;
431
};
432
433
inline UnknownAttributeNode* UnknownAttributeNode::Step(
434
0
    UnknownTree* absl_nonnull tree, const AttributeQualifierView& key) {
435
0
  auto [node, emplaced] = internal::ArenaTreeLazyEmplace(
436
0
      tree->GetArena(), &children_, key, Compare{},
437
0
      [this, tree, &key](const auto& constructor) -> void {
438
0
        constructor(this, tree->InternKey(key));
439
0
      });
440
0
  return node;
441
0
}
442
443
inline UnknownFunctionNode* absl_nonnull UnknownRoot::SetFunction(
444
0
    UnknownTree* absl_nonnull tree, absl::string_view name) {
445
0
  auto [node, emplaced] = internal::ArenaTreeLazyEmplace(
446
0
      tree->GetArena(), &functions_, name, UnknownFunctionNode::Compare{},
447
0
      [tree, &name](const auto& constructor) -> void {
448
0
        constructor((ArenaString)(tree->GetArena(), name));
449
0
      });
450
0
  return node;
451
0
}
452
453
inline UnknownFunctionNode* absl_nullable UnknownRoot::FindFunction(
454
0
    absl::string_view name) const {
455
0
  return internal::ArenaTreeFind(functions_, name,
456
0
                                 UnknownFunctionNode::Compare{});
457
0
}
458
459
[[nodiscard]]
460
inline const UnknownFunctionSet* absl_nonnull CreateUnknownFunctionSet(
461
0
    UnknownFunctionNode* absl_nonnull node, google::protobuf::Arena* absl_nonnull arena) {
462
0
  UnknownFunctionSet* ufs = UnknownFunctionSet::Allocate(1, arena);
463
0
  ufs->nodes[0] = node;
464
0
  return ufs;
465
0
}
466
467
// Fast two-way unknown function set merger without temporary storage.
468
[[nodiscard]]
469
const UnknownFunctionSet* absl_nonnull MergeUnknownFunctionSets(
470
    const UnknownFunctionSet* absl_nonnull lhs,
471
    const UnknownFunctionSet* absl_nonnull rhs,
472
    google::protobuf::Arena* absl_nonnull arena);
473
474
[[nodiscard]]
475
inline const UnknownAttributeSet* absl_nonnull CreateUnknownAttributeSet(
476
    UnknownAttributeNode* absl_nonnull node,
477
0
    google::protobuf::Arena* absl_nonnull arena) {
478
0
  UnknownAttributeSet* uas = UnknownAttributeSet::Allocate(1, arena);
479
0
  uas->max_depth = static_cast<uint32_t>(node->depth());
480
0
  uas->nodes[0] = node;
481
0
  return uas;
482
0
}
483
484
// Fast two-way unknown attribute set merger without temporary storage.
485
[[nodiscard]]
486
const UnknownAttributeSet* absl_nonnull MergeUnknownAttributeSets(
487
    const UnknownAttributeSet* absl_nonnull lhs,
488
    const UnknownAttributeSet* absl_nonnull rhs,
489
    google::protobuf::Arena* absl_nonnull arena);
490
491
}  // namespace cel::common_internal
492
493
#endif  // THIRD_PARTY_CEL_CPP_COMMON_INTERNAL_UNKNOWNS_H_