TokenStreamSelector.cpp
上传用户:afrynkmhm
上传日期:2007-01-06
资源大小:1262k
文件大小:2k
源码类别:

编译器/解释器

开发平台:

Others

  1. #include "antlr/TokenStreamSelector.hpp"
  2. #include "antlr/TokenStreamRetryException.hpp"
  3. ANTLR_BEGIN_NAMESPACE(antlr)
  4. /** A token stream MUX (multiplexor) knows about n token streams
  5.  *  and can multiplex them onto the same channel for use by token
  6.  *  stream consumer like a parser.  This is a way to have multiple
  7.  *  lexers break up the same input stream for a single parser.
  8.  * Or, you can have multiple instances of the same lexer handle
  9.  *  multiple input streams; this works great for includes.
  10.  */
  11. TokenStreamSelector::TokenStreamSelector()
  12. : input(0)
  13. {
  14. }
  15. TokenStreamSelector::~TokenStreamSelector()
  16. {
  17. }
  18. void TokenStreamSelector::addInputStream(TokenStream* stream, const ANTLR_USE_NAMESPACE(std)string& key)
  19. {
  20. inputStreamNames[key] = stream;
  21. }
  22. TokenStream* TokenStreamSelector::getCurrentStream() const
  23. {
  24. return input;
  25. }
  26. TokenStream* TokenStreamSelector::getStream(const ANTLR_USE_NAMESPACE(std)string& sname) const
  27. {
  28. inputStreamNames_coll::const_iterator i = inputStreamNames.find(sname);
  29. if (i == inputStreamNames.end()) {
  30. throw ANTLR_USE_NAMESPACE(std)string("TokenStream ")+sname+" not found";
  31. }
  32. return (*i).second;
  33. }
  34. RefToken TokenStreamSelector::nextToken()
  35. {
  36. // keep looking for a token until you don't
  37. // get a retry exception
  38. for (;;) {
  39. try {
  40. return input->nextToken();
  41. }
  42. catch (TokenStreamRetryException& r) {
  43. // just retry "forever"
  44. }
  45. }
  46. }
  47. TokenStream* TokenStreamSelector::pop()
  48. {
  49. TokenStream* stream = streamStack.top();
  50. streamStack.pop();
  51. select(stream);
  52. return stream;
  53. }
  54. void TokenStreamSelector::push(TokenStream* stream)
  55. {
  56. streamStack.push(input);
  57. select(stream);
  58. }
  59. void TokenStreamSelector::push(const ANTLR_USE_NAMESPACE(std)string& sname)
  60. {
  61. streamStack.push(input);
  62. select(sname);
  63. }
  64. void TokenStreamSelector::retry()
  65. {
  66. throw TokenStreamRetryException();
  67. }
  68. /** Set the stream without pushing old stream */
  69. void TokenStreamSelector::select(TokenStream* stream)
  70. {
  71. input = stream;
  72. }
  73. void TokenStreamSelector::select(const ANTLR_USE_NAMESPACE(std)string& sname)
  74. {
  75. inputStreamNames_coll::const_iterator i = inputStreamNames.find(sname);
  76. if (i == inputStreamNames.end()) {
  77. throw ANTLR_USE_NAMESPACE(std)string("TokenStream ")+sname+" not found";
  78. }
  79. input = (*i).second;
  80. }
  81. ANTLR_END_NAMESPACE