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 #include <hilti/ast/node-ref.h>
9 
10 namespace hilti::visitor {
11 
13 template<typename E>
14 class Location {
15 public:
16  E operator*() const { return node; }
17  typename std::remove_reference<E>::type* operator->() const { return &node; }
18 
19  // private: // TODO: friend doesn't work?
20  // friend class Iterator<Erased, order, isConst>;
21  Location(E node = nullptr, int child = 0) : node(node), child(child) {}
22  E node;
23  int child;
24 };
25 
27 template<typename E>
28 struct Position {
29 public:
30  using Erased = typename std::decay<E>::type;
31 
33  E node;
34 
39  const std::vector<Location<E>>& path;
40 
46  auto pathLength() const { return path.size(); }
47 
54  E parent(unsigned int parent_nr = 1) const { // 1st parent == 1
55  if ( path.size() < 1 + parent_nr )
56  throw std::out_of_range("node does not have requested parent");
57 
58  return (**(path.end() - 1 - parent_nr));
59  }
60 
62  template<typename T>
63  std::optional<std::reference_wrapper<const T>> findParent() const {
64  for ( auto i = path.rbegin() + 1; i != path.rend(); i++ ) {
65  if ( (**i).template isA<T>() )
66  return {(**i).template as<T>()};
67  }
68 
69  return std::nullopt;
70  }
71 
73  template<typename T>
75  for ( auto i = path.rbegin() + 1; i != path.rend(); i++ ) {
76  if ( (**i).template isA<T>() )
77  return NodeRef(**i);
78  }
79 
80  return {};
81  }
82 };
83 
84 } // namespace hilti::visitor
Definition: operator.h:22
auto pathLength() const
Definition: visitor-types.h:46
Definition: visitor-types.h:28
E node
Definition: visitor-types.h:33
NodeRef findParentRef() const
Definition: visitor-types.h:74
const std::vector< Location< E > > & path
Definition: visitor-types.h:39
Definition: node-ref.h:44
std::optional< std::reference_wrapper< const T > > findParent() const
Definition: visitor-types.h:63
Definition: visitor-types.h:14
E parent(unsigned int parent_nr=1) const
Definition: visitor-types.h:54