Vcsn  2.3
Be Rational
raise.hh
Go to the documentation of this file.
1 #pragma once
2 
3 #include <sstream>
4 #include <stdexcept>
5 #include <utility>
6 
8 #include <vcsn/misc/escape.hh>
9 #include <vcsn/misc/to-string.hh> // to_string
10 
11 namespace vcsn
12 {
13  namespace detail
14  {
18  struct pass
19  {
20  template <typename ...T> pass(T...) {}
21  };
22 
23 
25  template <typename T>
26  void print_(std::ostream& o, const T& arg, long)
27  {
28  o << arg;
29  }
30 
34  inline void print_(std::ostream& o, std::istream& is, long)
35  {
36  is.clear();
37  std::string buf;
38  std::getline(is, buf, '\n');
39  if (!is.good())
40  // This shouldn't really happen; however it's best to fail cleanly.
41  is.clear();
42  o << str_escape(buf);
43  }
44 
46  inline void print_(std::ostream& o, std::istringstream& is, long)
47  {
48  print_(o, static_cast<std::istream&>(is), 0);
49  }
50 
52  template <typename T>
53  auto print_(std::ostream& o, const T& arg, int)
54  -> decltype(arg.print_set(o), void())
55  {
56  arg.print_set(o);
57  }
58 
60  //FIXME: I'm sure there's an easier way to do this.
61  //Basic parameter overload did not compile,
62  //empty template + parameter overload did not either.
63  //`long` instead of `int` also doesn't work.
64  template <typename T>
65  auto print_(std::ostream& o, const T& e, int)
66  -> decltype(e.what(), void())
67  {
68  o << e.what() << "\n";
69  }
70  }
71 
73  template <typename... Args>
74  ATTRIBUTE_NORETURN
75  void raise(Args&&... args)
76  {
77  std::ostringstream o;
78  using swallow = int[];
79  (void) swallow
80  {
81  (detail::print_(o, args, 0), 0)...
82  };
83  throw std::runtime_error{o.str()};
84  }
85 
90  template <typename Bool, typename... Args>
91  void require(Bool b, Args&&... args)
92  {
93  if (!b)
94  raise(std::forward<Args>(args)...);
95  }
96 
98  template <typename WeightSet>
99  ATTRIBUTE_NORETURN
101  const typename WeightSet::value_t& w)
102  {
103  raise(ws, ": value is not starrable: ", to_string(ws, w));
104  }
105 }
106 
111 #define VCSN_REQUIRE(Cond, ...) \
112  do { \
113  if (!(Cond)) \
114  ::vcsn::raise(__VA_ARGS__); \
115  } while (false)
std::ostream & str_escape(std::ostream &os, const std::string &str, const char *special=nullptr)
Output a string, escaping special characters.
Definition: escape.cc:51
ATTRIBUTE_NORETURN void raise_not_starrable(const WeightSet &ws, const typename WeightSet::value_t &w)
This value is not starrable.
Definition: raise.hh:100
void require(Bool b, Args &&...args)
If b is not verified, raise an error with args as message.
Definition: raise.hh:91
Definition: a-star.hh:8
std::string to_string(direction d)
Conversion to string.
Definition: direction.cc:7
Ignore its arguments.
Definition: raise.hh:18
Provide a variadic mul on top of a binary mul(), and one().
Definition: fwd.hh:46
void print_(std::ostream &o, const T &arg, long)
Serialize arg into o.
Definition: raise.hh:26