Spicy
scope.h
1 // Copyright (c) 2020-2021 by the Zeek Project. See LICENSE for details.
2 
3 #pragma once
4 
5 #include <cstddef>
6 #include <map>
7 #include <memory>
8 #include <optional>
9 #include <string>
10 #include <unordered_map>
11 #include <unordered_set>
12 #include <utility>
13 #include <vector>
14 
15 #include <hilti/ast/node-ref.h>
16 #include <hilti/base/intrusive-ptr.h>
17 
18 namespace hilti {
19 
20 class Declaration;
21 class ID;
22 
28 public:
29  Scope() = default;
30  ~Scope() = default;
31 
32  void insert(NodeRef&& n);
33  void insert(const ID& id, NodeRef&& n);
34  void insertNotFound(const ID& id);
35 
37  bool has(const ID& id) const { return ! _findID(id).empty(); }
38 
40  struct Referee {
42  std::string qualified;
43  bool external{};
44  };
45 
47  std::vector<Referee> lookupAll(const ID& id) const { return _findID(id); }
48 
50  std::optional<Referee> lookup(const ID& id) const {
51  if ( auto ids = _findID(id); ! ids.empty() )
52  return ids.front();
53 
54  return {};
55  }
56 
58  void clear() { _items.clear(); }
59 
61  const auto& items() const { return _items; }
62 
69  void render(std::ostream& out, const std::string& prefix = "") const;
70 
71  Scope(const Scope& other) = delete;
72  Scope(Scope&& other) = delete;
73  Scope& operator=(const Scope& other) = delete;
74  Scope& operator=(Scope&& other) = delete;
75 
76 private:
77  // Specialized implementation for `NodeRef` hashing and equality checks for
78  // nodes referencing declarations.
79  struct NodeRefHash {
80  std::size_t operator()(const hilti::NodeRef& n) const;
81  };
82 
83  struct NodeRefEqual {
84  bool operator()(const hilti::NodeRef& a, const hilti::NodeRef& b) const;
85  };
86 
87  using ItemMap = std::map<std::string, std::unordered_set<NodeRef, NodeRefHash, NodeRefEqual>>;
88 
89  std::vector<Referee> _findID(const ID& id, bool external = false) const;
90  std::vector<Referee> _findID(const Scope* scope, const ID& id, bool external = false) const;
91 
92  ItemMap _items;
93 };
94 
95 } // namespace hilti
bool has(const ID &id) const
Definition: scope.h:37
Definition: intrusive-ptr.h:29
NodeRef node
Definition: scope.h:41
const auto & items() const
Definition: scope.h:61
std::optional< Referee > lookup(const ID &id) const
Definition: scope.h:50
Definition: scope.h:27
std::string qualified
Definition: scope.h:42
Definition: scope.h:40
void clear()
Definition: scope.h:58
Definition: node-ref.h:45
void render(std::ostream &out, const std::string &prefix="") const
Definition: scope.cc:107
std::vector< Referee > lookupAll(const ID &id) const
Definition: scope.h:47
Definition: id.h:18
bool external
Definition: scope.h:43