在流上提升精神词法分析器并不会令人难以理解"早期"足够的(太多的向前看?)

时间:2014-08-02 18:09:26

标签: c++ boost-spirit boost-spirit-lex

我正在使用boost :: spirit :: lex lexer来标记输入流,使用{:: 3}}中描述的spirit :: istream_iterators。

我的问题是lex :: tokenize似乎没有按照我认为的那样“提前”(沿着输入流)输出令牌。在获得前面的令牌之前,它等待一个额外的令牌(或两个?)整体可用。我想这是一个前瞻性的延迟,但我不确定为什么这是必要的,或者如何绕过它。

以下是一个例子:

#include <boost/bind.hpp>
#include <boost/spirit/include/lex_lexertl.hpp>
#include <boost/spirit/include/support_istream_iterator.hpp>
namespace spirit = boost::spirit;
namespace lex = spirit::lex;

#include <iostream>
using std::cin;
using std::cout;
using std::endl;

template <typename Lexer>
struct ALexer : lex::lexer<Lexer> {
  ALexer() {
    this->self.add
      ("hello")
      ("goodbye")
      ("[ \\t\\r\\n]+")
    ;
  }
};

struct Emitter {
  typedef bool result_type;   // for boost::bind
  template <typename Token>
  bool operator() (const Token& t) const {
    cout << "token: " << t.value() << endl;
    return true;
  }
};

int main() {
  cin >> std::noskipws;

  // iterate over stream input
  spirit::istream_iterator in_begin(cin);
  spirit::istream_iterator in_end;

  typedef lex::lexertl::token<spirit::istream_iterator> token_type;
  typedef lex::lexertl::lexer<token_type> lexer_type;
  typedef ALexer<lexer_type> tokenizer_type;
  tokenizer_type tokenizer;

  (void) lex::tokenize(in_begin, in_end, tokenizer, boost::bind(Emitter(), _1));

  return 0;
}

示例会话:(请注意,cin由我的操作系统进行行缓冲,因此第一个“行”立即可供词法分析器使用)

(input)    hello goodbye<NEWLINE>
(output)   token: hello
           token:  
(input)    <EOF>
(output)   token: goodbye
           token: 

我希望词法分析器接收到第一行,并且一旦到达<NEWLINE>,它就应该知道一个完整的“再见”令牌已经被修复并发出它。相反,它似乎等待更多的输入才能得到再见。

0 个答案:

没有答案