1 /*============================================================================== 2 Copyright (c) 2001-2011 Joel de Guzman 3 Copyright (c) 2010-2011 Bryce Lelbach 4 5 Distributed under the Boost Software License, Version 1.0. (See accompanying 6 file BOOST_LICENSE_1_0.rst or copy at http://www.boost.org/LICENSE_1_0.txt) 7 ==============================================================================*/ 8 9 #if !defined(BOOST_SPIRIT_UTREE_EXAMPLE_ERROR_HANDLER_HPP) 10 #define BOOST_SPIRIT_UTREE_EXAMPLE_ERROR_HANDLER_HPP 11 12 #include <string> 13 #include <sstream> 14 15 #include <boost/config.hpp> 16 #include <boost/spirit/home/support/info.hpp> 17 #include <boost/spirit/include/support_line_pos_iterator.hpp> 18 19 namespace sexpr 20 { 21 22 using boost::spirit::info; 23 24 template <typename Out> 25 struct print_info 26 { 27 typedef boost::spirit::utf8_string string; 28 print_infosexpr::print_info29 print_info(Out& out) : out(out), first(true) {} 30 elementsexpr::print_info31 void element(string const& tag, string const& value, int) const 32 { 33 if (!first) { 34 out << ' '; 35 first = false; 36 } 37 38 if (value == "") 39 out << tag; 40 else 41 out << "\"" << value << '"'; 42 } 43 44 Out& out; 45 mutable bool first; 46 }; 47 48 struct expected_component : std::exception 49 { 50 std::string msg; 51 expected_componentsexpr::expected_component52 expected_component(std::string const& source, std::size_t line 53 , info const& w) 54 { 55 using boost::spirit::basic_info_walker; 56 57 std::ostringstream oss; 58 oss << "(exception \"" << source << "\" "; 59 60 if (line == -1) 61 oss << -1; 62 else 63 oss << line; 64 65 oss << " '(expected_component ("; 66 67 print_info<std::ostringstream> pr(oss); 68 basic_info_walker<print_info<std::ostringstream> > 69 walker(pr, w.tag, 0); 70 71 boost::apply_visitor(walker, w.value); 72 73 oss << ")))"; 74 75 msg = oss.str(); 76 } 77 ~expected_componentsexpr::expected_component78 virtual ~expected_component() BOOST_NOEXCEPT_OR_NOTHROW {} 79 whatsexpr::expected_component80 virtual char const* what() const BOOST_NOEXCEPT_OR_NOTHROW 81 { 82 return msg.c_str(); 83 } 84 }; 85 86 template <typename Iterator> 87 struct error_handler 88 { 89 template <typename, typename, typename, typename> 90 struct result 91 { 92 typedef void type; 93 }; 94 95 std::string source; 96 error_handlersexpr::error_handler97 error_handler(std::string const& source_ = "<string>") : source(source_) {} 98 operator ()sexpr::error_handler99 void operator()(Iterator first, Iterator last, Iterator err_pos 100 , info const& what) const 101 { 102 using boost::spirit::get_line; 103 Iterator eol = err_pos; 104 std::size_t line = get_line(err_pos); 105 throw expected_component(source, line, what); 106 } 107 }; 108 109 } // sexpr 110 111 #endif // BOOST_SPIRIT_UTREE_EXAMPLE_ERROR_HANDLER_HPP 112 113