Alexandria  2.27.0
SDC-CH common library for the Euclid project
AttributeSet.h
Go to the documentation of this file.
1 
19 #ifndef PYSTON_ATTRIBUTESET_H
20 #define PYSTON_ATTRIBUTESET_H
21 
24 #include <boost/python/object.hpp>
25 #include <set>
26 #include <string>
27 
28 namespace Pyston {
29 
33 template <typename T>
34 class AttrGetter : public Node<T> {
35 public:
43  AttrGetter(const unsigned pos, const std::string& name) : m_pos{pos}, m_name{name} {}
44 
48  std::string repr() const override {
49  return "_" + std::to_string(m_pos) + "." + m_name;
50  }
51 
55  void visit(Visitor& visitor) const override {
56  visitor.enter(this);
57  visitor.exit(this);
58  }
59 
65  T eval(const Context&, const Arguments& arguments) const override {
66  auto& attr_set = boost::get<AttributeSet>(arguments[m_pos]);
67  auto value_iter = attr_set.find(m_name);
68  if (value_iter == attr_set.end()) {
69  throw std::out_of_range("AttributeSet object has no attribute '" + m_name + "'");
70  }
71  return boost::get<T>(value_iter->second);
72  }
73 
74 private:
75  unsigned m_pos;
77 };
78 
84 template <>
86 public:
94  Placeholder(const unsigned pos, const AttributeSet& attrs) : m_pos{pos}, m_attrs{attrs} {}
95 
107  boost::python::object get(const std::string& name) const {
108  if (m_attrs.count(name) == 0)
109  throw UnrecoverableError("AttributeSet object has no attribute '" + name + "'");
110  return boost::apply_visitor(AttrGetterFactory(m_pos, name), m_attrs.at(name));
111  }
112 
113 private:
114  unsigned m_pos;
116 
117  struct AttrGetterFactory : public boost::static_visitor<boost::python::object> {
118  unsigned m_pos;
120 
121  AttrGetterFactory(unsigned pos, const std::string& name) : m_pos{pos}, m_name{name} {}
122 
123  template <typename Content>
124  boost::python::object operator()(Content) const {
125  std::shared_ptr<Node<Content>> node = std::make_shared<AttrGetter<Content>>(m_pos, m_name);
126  return boost::python::object(node);
127  }
128  };
129 };
130 } // namespace Pyston
131 
132 #endif // PYSTON_ATTRIBUTESET_H
std::string m_name
Definition: AttributeSet.h:76
std::string repr() const override
Definition: AttributeSet.h:48
T eval(const Context &, const Arguments &arguments) const override
Definition: AttributeSet.h:65
AttrGetter(const unsigned pos, const std::string &name)
Definition: AttributeSet.h:43
void visit(Visitor &visitor) const override
Definition: AttributeSet.h:55
Placeholder(const unsigned pos, const AttributeSet &attrs)
Definition: AttributeSet.h:94
boost::python::object get(const std::string &name) const
Definition: AttributeSet.h:107
virtual void enter(const NodeBase *)=0
virtual void exit(const NodeBase *)=0
AttrGetterFactory(unsigned pos, const std::string &name)
Definition: AttributeSet.h:121
boost::python::object operator()(Content) const
Definition: AttributeSet.h:124
T to_string(T... args)