使用 Spirit x3,如何控制在每个不同的输入上调用哪个解析器?

Using Spirit x3, how to control which parser is called on each different input?

本文关键字:输入 调用 x3 Spirit 何控制 控制 使用      更新时间:2023-10-16

我正在使用提升精神x3,但不清楚一点。我有一个文件,其中有非常不同和重复的行。前几行可能是注释。接下来的 1000 行可能是坐标,接下来的 1000 行可能是 int 的列表,等等......

我的问题是如何识别该行并知道该行使用哪个解析器。 例如,这里有两个解析器函数....

template <typename Iterator>
bool parse_ints(Iterator first, Iterator last, std::vector<int>& v)
{
using x3::int_;
using x3::phrase_parse;
using x3::_attr;   
using ascii::space;
auto push_back = [&](auto& ctx){ v.push_back(_attr(ctx)); };
bool r = phrase_parse(first, last,
(
int_[push_back]
>> *(',' >> int_[push_back])
)
,
space);
if (first != last) 
return false;
return r;
}
template <typename Iterator>
bool parse_doubles(Iterator first, Iterator last, std::vector<double>& v)
{
using x3::double_;
using x3::phrase_parse;
using x3::_attr;
using ascii::space;
auto push_back = [&](auto& ctx){ v.push_back(_attr(ctx)); };
bool r = phrase_parse(first, last,
(
double_[push_back]
>> *(',' >> double_[push_back])
)
,
space);
if (first != last) // fail if we did not get a full match
return false;
return r;
}

这是输入的方式(istringstream的大小为数百MB)。在 while 循环中,我想知道要调用哪个解析器。

int main()
{
istringstream str(my.data());
while (getline(str, line)) {
// based on the format of 'line', how does one know which 
// parser to call?
}
}

你的语法可以描述整个输入。所以你可以说

auto input = *headerComment 
>> points 
>> edges;

您可以简单地定义的地方

auto headerComment = '#' >> *(char_ - eol) >> eol;

例如

auto points = skip(blank) [ 
*(point >> eol)
];
auto edges = skip(blank) [ 
*(edge >> eol)
];
point = int_ >> int_ >> int_; // assuming x y z
edge  = int_ >> int_;         // assuming from to

这假定输入格式是明确的。 也就是说,如果点被x y,它就不起作用,因为它当时无法与边缘区分开来。