【发布时间】:2021-10-28 01:32:56
【问题描述】:
我正在使用 Boost Spirit X3 解析一些语法,但遇到了一些我无法解释的错误。下面的代码是我正在尝试做的简化版本。
#ifndef BOOST_SPIRIT_X3_NO_RTTI
#define BOOST_SPIRIT_X3_NO_RTTI
#endif
#include "boost/spirit/home/x3.hpp"
#include <iostream>
#include <string>
namespace spirit3 = boost::spirit::x3;
// Grammar for the language: a^(2n+1)
// S -> aPa
// P -> aPa | a
struct P_id;
constexpr auto P = spirit3::rule<P_id, spirit3::unused_type>{};
constexpr auto P_def = ('a' >> P >> 'a') | 'a';
constexpr auto S = 'a' >> P_def >> 'a';
BOOST_SPIRIT_DEFINE(P);
int
main()
{
int n_chars_list[] = {5, 7, 9};
for (auto n_chars : n_chars_list)
{
std::string content;
for (int i = 0; i < n_chars; ++i)
content += 'a';
auto iter = content.begin();
bool is_matched = spirit3::parse(iter, content.end(), S);
bool is_exhausted = (iter == content.end());
std::cout << "n_chars: " << n_chars << '\t';
std::cout << std::boolalpha << "is_matched: " << is_matched << '\t';
std::cout << std::boolalpha << "is_exhausted: " << is_exhausted << '\n';
}
}
// Output:
// n_chars: 5 is_matched: true is_exhausted: false
// n_chars: 7 is_matched: true is_exhausted: true
// n_chars: 9 is_matched: true is_exhausted: false
谁能解释为什么在 n_chars 为 5 或 9 的情况下解析器无法识别整个字符串,但在 7 的情况下成功?谢谢。
【问题讨论】:
-
你/期望/看到什么?
-
我希望解析器在所有 3 种情况下都能识别整个字符串。
-
为什么?据我所知,这不是语法所表达的。描述(
S?P?“语言:a^(2n+1)”)有点有限。
标签: c++ boost boost-spirit boost-spirit-x3