Spicy
node-ref.h
1 // Copyright (c) 2020-2021 by the Zeek Project. See LICENSE for details.
2 
3 #pragma once
4 
5 #include <cinttypes>
6 #include <functional>
7 #include <memory>
8 #include <string>
9 
10 #include <hilti/base/intrusive-ptr.h>
11 #include <hilti/base/util.h>
12 
13 namespace hilti {
14 
15 class Node;
16 
17 namespace node_ref {
18 namespace detail {
19 
20 // Control block for referring to nodes.
22 public:
23  Control(const Node* n) : _node(n), _rid(++_rid_counter) {}
24  const Node* _node;
25  uint64_t _rid;
26 
27  static uint64_t _rid_counter;
28 };
29 
30 } // namespace detail
31 
33 struct Invalid : std::runtime_error {
34  using std::runtime_error::runtime_error;
35 };
36 
37 } // namespace node_ref
38 
45 class NodeRef {
46 public:
47  explicit NodeRef(const Node& n);
48  explicit NodeRef(const NodeRef& other) = default;
49  NodeRef(NodeRef&& other) = default;
50  NodeRef& operator=(const NodeRef& other) = default;
51  NodeRef& operator=(NodeRef&& other) = default;
52  NodeRef() = default;
53  ~NodeRef() = default;
54 
61  uint64_t rid() const { return _control ? _control->_rid : 0; }
62 
69  std::string renderedRid() const { return _control && _control->_node ? util::fmt("%%%" PRIu64, rid()) : "%???"; };
70 
76  const Node* operator->() const { return _node(); }
77 
84  const Node& operator*() const { return *_node(); }
85 
86  operator const Node&() const { return *_node(); }
87 
89  explicit operator bool() const { return _control && _control->_node; }
90 
91 private:
92  const Node* _node() const;
94 };
95 
96 } // namespace hilti
std::string renderedRid() const
Definition: node-ref.h:69
Definition: node-ref.h:21
Definition: node-ref.h:33
const Node * operator->() const
Definition: node-ref.h:76
Definition: intrusive-ptr.h:29
const Node & operator*() const
Definition: node-ref.h:84
Definition: intrusive-ptr.h:70
Definition: node.h:111
Definition: node-ref.h:45
uint64_t rid() const
Definition: node-ref.h:61