Spicy
visitor-types.h
1 // Copyright (c) 2020-2021 by the Zeek Project. See LICENSE for details.
2 
3 #pragma once
4 
5 #include <optional>
6 #include <vector>
7 
8 namespace hilti::visitor {
9 
11 template<typename E>
12 class Location {
13 public:
14  E operator*() const { return node; }
15  typename std::remove_reference<E>::type* operator->() const { return &node; }
16 
17  // private: // TODO: friend doesn't work?
18  // friend class Iterator<Erased, order, isConst>;
19  Location(E node = nullptr, int child = 0) : node(node), child(child) {}
20  E node;
21  int child;
22 };
23 
25 template<typename E>
26 struct Position {
27 public:
28  using Erased = typename std::decay<E>::type;
29 
31  E node;
32 
37  const std::vector<Location<E>>& path;
38 
44  auto pathLength() const { return path.size(); }
45 
52  E parent(unsigned int parent_nr = 1) const { // 1st parent == 1
53  if ( path.size() < 1 + parent_nr )
54  throw std::out_of_range("node does not have requested parent");
55 
56  return (**(path.end() - 1 - parent_nr));
57  }
58 
60  template<typename T>
61  std::optional<std::reference_wrapper<const T>> findParent() const {
62  for ( auto i = path.rbegin() + 1; i != path.rend(); i++ ) {
63  if ( (**i).template isA<T>() )
64  return {(**i).template as<T>()};
65  }
66 
67  return std::nullopt;
68  }
69 };
70 
71 } // namespace hilti::visitor
Definition: operator.h:22
auto pathLength() const
Definition: visitor-types.h:44
Definition: visitor-types.h:26
E node
Definition: visitor-types.h:31
const std::vector< Location< E > > & path
Definition: visitor-types.h:37
std::optional< std::reference_wrapper< const T > > findParent() const
Definition: visitor-types.h:61
Definition: visitor-types.h:12
E parent(unsigned int parent_nr=1) const
Definition: visitor-types.h:52