Spicy
visitor-util.h
1 // Copyright (c) 2020-2021 by the Zeek Project. See LICENSE for details.
2 
3 #pragma once
4 
5 #include <optional>
6 #include <utility>
7 #include <vector>
8 
9 #include <hilti/ast/node.h>
10 #include <hilti/base/logger.h>
11 #include <hilti/base/util.h>
12 
13 namespace hilti {
14 namespace visitor {
15 
20 template<typename N>
21 using Path = std::vector<std::reference_wrapper<N>>;
22 
24 template<typename N>
25 N& current(const Path<N>& path) {
26  if ( path.empty() )
27  logger().internalError("empty path in visitor");
28 
29  return (*(path.end() - 1)).get();
30 }
31 
39 inline const Node& parent(const Path<const Node>& path, int parent_nr = 1) {
40  if ( path.size() < 1 + parent_nr )
41  throw std::out_of_range("node does not have requested parent");
42 
43  return (*(path.end() - 1 - parent_nr)).get();
44 }
45 
53 inline Node& parent(const Path<Node>& path, int parent_nr = 1) {
54  if ( path.size() < 1 + parent_nr )
55  throw std::out_of_range("node does not have requested parent");
56 
57  return (*(path.end() - 1 - parent_nr)).get();
58 }
59 
64 template<typename T, IF_NOT_SAME(T, Node)>
65 std::optional<const T> findParent(const Path<Node>& path) {
66  for ( auto i = path.rbegin() + 1; i != path.rend(); i++ ) {
67  if ( auto t = (*i).get().tryAs<T>() )
68  return std::move(t);
69  }
70 
71  return {};
72 }
73 
78 template<typename T, IF_NOT_SAME(T, Node)>
79 std::optional<const T> findParent(const Path<const Node>& path) {
80  for ( auto i = path.rbegin() + 1; i != path.rend(); i++ ) {
81  if ( auto t = (*i).get().tryAs<T>() )
82  return std::move(t);
83  }
84 
85  return {};
86 }
87 
88 
89 } // namespace visitor
90 } // namespace hilti
N & current(const Path< N > &path)
Definition: visitor-util.h:25
std::vector< std::reference_wrapper< N > > Path
Definition: visitor-util.h:21
const Node & parent(const Path< const Node > &path, int parent_nr=1)
Definition: visitor-util.h:39
Definition: node.h:97
std::optional< const T > findParent(const Path< Node > &path)
Definition: visitor-util.h:65