Spicy
scope.h
1 // Copyright (c) 2020-2021 by the Zeek Project. See LICENSE for details.
2 
3 #pragma once
4 
5 #include <map>
6 #include <memory>
7 #include <optional>
8 #include <string>
9 #include <unordered_map>
10 #include <vector>
11 
12 #include <hilti/ast/node_ref.h>
13 #include <hilti/base/intrusive-ptr.h>
14 
15 namespace hilti {
16 
17 class ID;
18 
25 public:
26  Scope() = default;
27  ~Scope() = default;
28 
36  void insert(const ID& id, NodeRef n);
37 
45  void insert(const ID& id, Node&& n);
46 
48  bool has(const ID& id) const { return ! _findID(id).empty(); }
49 
51  struct Referee {
53  std::string qualified;
54  bool external{};
55  };
56 
58  std::vector<Referee> lookupAll(const ID& id) const { return _findID(id); }
59 
61  std::optional<Referee> lookup(const ID& id) const {
62  if ( auto ids = _findID(id); ! ids.empty() )
63  return ids.front();
64 
65  return {};
66  }
67 
69  void clear() { _items.clear(); }
70 
72  const auto& items() const { return _items; }
73 
77  void copyInto(Scope* dst) const {
78  for ( const auto& i : _items )
79  dst->_items.insert(i);
80  }
81 
86  void moveInto(Scope* dst) {
87  // dst->_items.merge(std::move(_items)); // C++17, not supported by libc++ yet it seems
88  for ( const auto& i : _items )
89  dst->_items.insert(i);
90 
91  _items.clear();
92  }
93 
100  void render(std::ostream& out, const std::string& prefix = "") const;
101 
102  Scope(const Scope& other) = delete;
103  Scope(Scope&& other) = delete;
104  Scope& operator=(const Scope& other) = delete;
105  Scope& operator=(Scope&& other) = delete;
106 
107 private:
108  using ItemMap = std::map<std::string, std::vector<NodeRef>>;
109 
110  std::vector<Referee> _findID(const ID& id, bool external = false) const;
111  std::vector<Referee> _findID(const Scope* scope, const ID& id, bool external = false) const;
112 
113  ItemMap _items;
114  std::vector<std::shared_ptr<Node>> _nodes; // Nodes without other owners.
115 };
116 
117 } // namespace hilti
void insert(const ID &id, NodeRef n)
Definition: scope.cc:13
void moveInto(Scope *dst)
Definition: scope.h:86
bool has(const ID &id) const
Definition: scope.h:48
Definition: intrusive-ptr.h:28
NodeRef node
Definition: scope.h:52
const auto & items() const
Definition: scope.h:72
std::optional< Referee > lookup(const ID &id) const
Definition: scope.h:61
Definition: scope.h:24
std::string qualified
Definition: scope.h:53
Definition: scope.h:51
void clear()
Definition: scope.h:69
Definition: node.h:97
Definition: node_ref.h:44
void copyInto(Scope *dst) const
Definition: scope.h:77
void render(std::ostream &out, const std::string &prefix="") const
Definition: scope.cc:89
std::vector< Referee > lookupAll(const ID &id) const
Definition: scope.h:58
Definition: id.h:18
bool external
Definition: scope.h:54