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 <memory>
7 #include <string>
8 
9 #include <hilti/base/intrusive-ptr.h>
10 #include <hilti/base/util.h>
11 
12 namespace hilti {
13 
14 class Node;
15 
16 namespace node_ref {
17 namespace detail {
18 
19 // Control block for referring to nodes.
21 public:
22  Control(const Node* n) : _node(n), _rid(++_rid_counter) {}
23  const Node* _node;
24  uint64_t _rid;
25 
26  static uint64_t _rid_counter;
27 };
28 
29 } // namespace detail
30 
32 struct Invalid : std::runtime_error {
33  using std::runtime_error::runtime_error;
34 };
35 
36 } // namespace node_ref
37 
44 class NodeRef {
45 public:
46  explicit NodeRef(const Node& n);
47  explicit NodeRef(const NodeRef& other) = default;
48  NodeRef(NodeRef&& other) = default;
49  NodeRef& operator=(const NodeRef& other) = default;
50  NodeRef& operator=(NodeRef&& other) = default;
51  NodeRef() = default;
52  ~NodeRef() = default;
53 
60  uint64_t rid() const { return _control ? _control->_rid : 0; }
61 
68  std::string renderedRid() const { return _control && _control->_node ? util::fmt("%%%" PRIu64, rid()) : "%???"; };
69 
75  const Node* operator->() const { return _node(); }
76 
83  const Node& operator*() const { return *_node(); }
84 
85  operator const Node&() const { return *_node(); }
86 
88  explicit operator bool() const { return _control && _control->_node; }
89 
90 private:
91  const Node* _node() const;
93 };
94 
95 } // namespace hilti
std::string renderedRid() const
Definition: node-ref.h:68
Definition: node-ref.h:20
Definition: node-ref.h:32
const Node * operator->() const
Definition: node-ref.h:75
Definition: intrusive-ptr.h:28
const Node & operator*() const
Definition: node-ref.h:83
std::string fmt(const char *fmt, const Args &... args)
Definition: util.h:80
Definition: intrusive-ptr.h:69
Definition: node.h:113
Definition: node-ref.h:44
uint64_t rid() const
Definition: node-ref.h:60