error_handler.hpp 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /*=============================================================================
  2. Copyright (c) 2001-2011 Joel de Guzman
  3. Distributed under the Boost Software License, Version 1.0. (See accompanying
  4. file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  5. =============================================================================*/
  6. #if !defined(BOOST_SPIRIT_CALC8_ERROR_HANDLER_HPP)
  7. #define BOOST_SPIRIT_CALC8_ERROR_HANDLER_HPP
  8. #include <iostream>
  9. #include <string>
  10. #include <vector>
  11. namespace client
  12. {
  13. ///////////////////////////////////////////////////////////////////////////////
  14. // The error handler
  15. ///////////////////////////////////////////////////////////////////////////////
  16. template <typename Iterator>
  17. struct error_handler
  18. {
  19. template <typename, typename, typename>
  20. struct result { typedef void type; };
  21. error_handler(Iterator first, Iterator last)
  22. : first(first), last(last) {}
  23. template <typename Message, typename What>
  24. void operator()(
  25. Message const& message,
  26. What const& what,
  27. Iterator err_pos) const
  28. {
  29. int line;
  30. Iterator line_start = get_pos(err_pos, line);
  31. if (err_pos != last)
  32. {
  33. std::cout << message << what << " line " << line << ':' << std::endl;
  34. std::cout << get_line(line_start) << std::endl;
  35. for (; line_start != err_pos; ++line_start)
  36. std::cout << ' ';
  37. std::cout << '^' << std::endl;
  38. }
  39. else
  40. {
  41. std::cout << "Unexpected end of file. ";
  42. std::cout << message << what << " line " << line << std::endl;
  43. }
  44. }
  45. Iterator get_pos(Iterator err_pos, int& line) const
  46. {
  47. line = 1;
  48. Iterator i = first;
  49. Iterator line_start = first;
  50. while (i != err_pos)
  51. {
  52. bool eol = false;
  53. if (i != err_pos && *i == '\r') // CR
  54. {
  55. eol = true;
  56. line_start = ++i;
  57. }
  58. if (i != err_pos && *i == '\n') // LF
  59. {
  60. eol = true;
  61. line_start = ++i;
  62. }
  63. if (eol)
  64. ++line;
  65. else
  66. ++i;
  67. }
  68. return line_start;
  69. }
  70. std::string get_line(Iterator err_pos) const
  71. {
  72. Iterator i = err_pos;
  73. // position i to the next EOL
  74. while (i != last && (*i != '\r' && *i != '\n'))
  75. ++i;
  76. return std::string(err_pos, i);
  77. }
  78. Iterator first;
  79. Iterator last;
  80. std::vector<Iterator> iters;
  81. };
  82. }
  83. #endif