[英]Boost spirit x3 tokenizer with annotation does not work
我最近嘗試使用boost spirit x3實現一個最簡單的標記器。 我現在面臨的挑戰是檢索輸入 stream 中每個令牌的 position。
官網有一個很好的注解教程: https://www.boost.org/doc/libs/develop/libs/spirit/doc/x3/html/spirit_x3/tutorials/annotation.html 。 但是,它有一些局限性:它基本上解析了相同(同質)本質的列表,而在現實生活中通常並非如此。
所以我試圖創建具有 2 個本質的標記器:空格(空格序列)和單行注釋(以//
開頭,一直持續到行尾)。
請參閱問題末尾的最小示例代碼。
但是,我在嘗試檢索任何令牌的 position 時遇到錯誤。 經過一些調試,我發現annotate_position::on_success
句柄將T
類型推斷為boost::spirit::x3::unused_type
,但我不知道為什么。
所以,我有幾個問題:
SingleLineComment
和Whitespace
類中的字符串,但沒有成功。 我懷疑這是因為在解析器中省略了注釋和空格字符串,有沒有辦法解決這個問題?grammar
class 或spirit::lex
,但是在x3版本中沒有這樣的東西)這是一個最小的示例代碼片段:
#include <string>
#include <iostream>
#include <functional>
#include <vector>
#include <optional>
#include <variant>
#include <boost/spirit/home/x3.hpp>
#include <boost/spirit/home/x3/support/ast/position_tagged.hpp>
using namespace std;
namespace x3 = boost::spirit::x3;
struct position_cache_tag;
// copy paste from boost documentation example
struct annotate_position
{
template <typename T, typename Iterator, typename Context>
inline void on_success(Iterator const &first, Iterator const &last, T &ast, Context const &context)
{
auto &position_cache = x3::get<position_cache_tag>(context).get();
position_cache.annotate(ast, first, last);
}
};
struct SingleLineComment : public x3::position_tagged
{
// no need to store actual comment string,
// since it is position tagged and
// we can then find the corresponding
// iterators afterwards, is this right?
};
struct Whitespace : public x3::position_tagged
{
// same reasoning
};
// here can be another token types (e.g. MultilineComment, integer, identifier etc.)
struct Token : public x3::position_tagged
{
// unites SingleLineComment and Whitespace
// into a single Token class
enum class Type
{
SingleLineComment,
Whitespace
};
std::optional<Type> type; // type field should be set by semantic action
// std::optional is kind of reinsurance that type will be set
std::optional<std::variant<SingleLineComment, Whitespace>> data;
// same reasoning for std::optional
// this filed might be needed for more complex
// tokens, which hold additional data
};
// unique on success hook classes
struct SingleLineCommentHook : public annotate_position
{
};
struct WhitespaceHook : public annotate_position
{
};
struct TokenHook : public annotate_position
{
};
// rules
const x3::rule<SingleLineCommentHook, SingleLineComment> singleLineComment = "single line comment";
const x3::rule<WhitespaceHook, Whitespace> whitespace = "whitespace";
const x3::rule<TokenHook, Token> token = "token";
// rule definitions
const auto singleLineComment_def = x3::lit("//") >> x3::omit[*(x3::char_ - '\n')];
const auto whitespace_def = x3::omit[+x3::ascii::space];
BOOST_SPIRIT_DEFINE(singleLineComment, whitespace);
auto _setSingleLineComment = [](const auto &context) {
x3::_val(context).type = Token::Type::SingleLineComment;
x3::_val(context).data = x3::_attr(context);
};
auto _setWhitespace = [](const auto &context) {
x3::_val(context).type = Token::Type::Whitespace;
x3::_val(context).data = x3::_attr(context);
};
const auto token_def = (singleLineComment[_setSingleLineComment] | whitespace[_setWhitespace]);
BOOST_SPIRIT_DEFINE(token);
int main()
{
// copy paste from boost documentation example
using iterator_type = std::string::const_iterator;
using position_cache = boost::spirit::x3::position_cache<std::vector<iterator_type>>;
std::string content = R"(// first single line comment
// second single line comment
)";
// expect 4 tokens: comment -> whitespace -> comment -> whitespace
position_cache positions{content.cbegin(), content.cend()};
std::vector<Token> tokens;
const auto parser = x3::with<position_cache_tag>(std::ref(positions))[*token];
auto start = content.cbegin();
auto success = x3::phrase_parse(start, content.cend(), parser, x3::eps(false), tokens);
success &= (start == content.cend());
cout << boolalpha << success << endl;
cout << "Found " << tokens.size() << " tokens" << endl;
for (auto &token : tokens)
cout << (token.type.value() == Token::Type::SingleLineComment ? "comment" : "space") << endl;
// all good till this point
// now I want to get a position
// the following throws
auto pos = positions.position_of(tokens.front());
}
感謝閱讀,期待任何回復!
當涉及語義動作時, on_success
似乎不會發生。
事實上,您對 Ast 節點和變體進行了冗余標記。
您已經可以通過例如獲得第一個令牌的正確結果
auto pos = positions.position_of(
std::get<SingleLineComment>(tokens.front().data)));
由於需要 static 類型的切換,這顯然不是很方便。
這是一個非常簡化的:
#include <iostream>
#include <iomanip>
#include <variant>
#include <boost/spirit/home/x3.hpp>
#include <boost/spirit/home/x3/support/ast/position_tagged.hpp>
namespace x3 = boost::spirit::x3;
struct SingleLineComment{};
struct Whitespace {};
using Variant = std::variant<SingleLineComment, Whitespace>;
struct Token : Variant, x3::position_tagged {
using Variant::Variant;
};
namespace {
struct position_cache_tag;
namespace Parser {
struct annotate_position {
template <typename T, typename Iterator, typename Context>
inline void on_success(Iterator first, Iterator last, T &ast, Context const &context) const {
auto &position_cache = x3::get<position_cache_tag>(context);
position_cache.annotate(ast, first, last);
}
};
// unique on success hook classes
template <typename> struct Hook {}; // no annotate_position mix-in
template <> struct Hook<Token> : annotate_position {};
template <typename T>
static auto constexpr as = [](auto p, char const* name = typeid(decltype(p)).name()) {
return x3::rule<Hook<T>, T> {name} = p;
};
// rule definitions
auto singleLineComment = as<SingleLineComment>("//" >> x3::omit[*(x3::char_ - x3::eol)]);
auto whitespace = as<Whitespace> (x3::omit[+x3::ascii::space]);
auto token = as<Token> (singleLineComment | whitespace, "token");
}
}
int main() {
using It = std::string::const_iterator;
using position_cache = x3::position_cache<std::vector<It>>;
std::string const content = R"(// first single line comment
// second single line comment
)";
position_cache positions{content.begin(), content.end()};
auto parser = x3::with<position_cache_tag>(positions)[*Parser::token];
std::vector<Token> tokens;
if (parse(begin(content), end(content), parser >> x3::eoi, tokens)) {
std::cout << "Found " << tokens.size() << " tokens" << std::endl;
for (auto& token : tokens) {
auto pos = positions.position_of(token);
std::cout
<< (token.index() ? "space" : "comment") << "\t"
<< std::quoted(std::string_view(&*pos.begin(), pos.size()))
<< std::endl;
}
}
}
印刷
Found 4 tokens
comment "// first single line comment"
space "
"
comment "// second single line comment"
space "
"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.