annotation.hpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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_ANNOTATION_HPP)
  7. #define BOOST_SPIRIT_CALC8_ANNOTATION_HPP
  8. #include <map>
  9. #include <boost/variant/apply_visitor.hpp>
  10. #include <boost/type_traits/is_base_of.hpp>
  11. #include <boost/mpl/bool.hpp>
  12. #include "ast.hpp"
  13. namespace client
  14. {
  15. ///////////////////////////////////////////////////////////////////////////////
  16. // The annotation handler links the AST to a map of iterator positions
  17. // for the purpose of subsequent semantic error handling when the
  18. // program is being compiled.
  19. ///////////////////////////////////////////////////////////////////////////////
  20. template <typename Iterator>
  21. struct annotation
  22. {
  23. template <typename, typename>
  24. struct result { typedef void type; };
  25. std::vector<Iterator>& iters;
  26. annotation(std::vector<Iterator>& iters)
  27. : iters(iters) {}
  28. struct set_id
  29. {
  30. typedef void result_type;
  31. int id;
  32. set_id(int id) : id(id) {}
  33. template <typename T>
  34. void operator()(T& x) const
  35. {
  36. this->dispatch(x, boost::is_base_of<ast::tagged, T>());
  37. }
  38. // This will catch all nodes except those inheriting from ast::tagged
  39. template <typename T>
  40. void dispatch(T& x, boost::mpl::false_) const
  41. {
  42. // (no-op) no need for tags
  43. }
  44. // This will catch all nodes inheriting from ast::tagged
  45. template <typename T>
  46. void dispatch(T& x, boost::mpl::true_) const
  47. {
  48. x.id = id;
  49. }
  50. };
  51. void operator()(ast::operand& ast, Iterator pos) const
  52. {
  53. int id = iters.size();
  54. iters.push_back(pos);
  55. boost::apply_visitor(set_id(id), ast);
  56. }
  57. void operator()(ast::assignment& ast, Iterator pos) const
  58. {
  59. int id = iters.size();
  60. iters.push_back(pos);
  61. ast.lhs.id = id;
  62. }
  63. };
  64. }
  65. #endif