【问题标题】:How can I keep certain semantic actions out of the AST in boost::spirit::qi如何在 boost::spirit::qi 中将某些语义动作排除在 AST 之外
【发布时间】:2018-08-24 13:04:31
【问题描述】:

我尝试使用 boost::spirit::qi 解析大量文件。解析不是问题,但有些文件包含我想跳过的噪音。构建一个简单的解析器(不使用 boost::spirit::qi)验证我可以通过在行首跳过任何与规则不匹配的内容来避免噪音。所以,我正在寻找一种方法来编写一个基于行的解析器,它在不匹配任何规则时会跳过行。

下面的示例允许语法在它们根本不匹配时跳过行,但“垃圾”规则仍会插入 V() 的空实例,这是不受欢迎的行为。 在示例中使用 \r 而不是 \n 是有意的,因为我在文件中遇到了 \n、\r 和 \r\n。

#include <iostream>
#include <string>
#include <vector>
#include <boost/foreach.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix.hpp>
#include <boost/fusion/include/std_tuple.hpp>

namespace qi = boost::spirit::qi;
namespace ascii = boost::spirit::ascii;
namespace phx = boost::phoenix;

using V = std::tuple<std::string, double, double, double>;

namespace client {
    template <typename Iterator>
    struct VGrammar : qi::grammar<Iterator, std::vector<V>(), ascii::space_type> {
        VGrammar() : VGrammar::base_type(start) {
            using namespace qi;

            v %= string("v") > double_ > double_ > double_;
            junk = +(char_ - eol);
            start %= +(v | junk);

            v.name("v");
            junk.name("junk");
            start.name("start");

            using phx::val;
            using phx::construct;

            on_error<fail>(
                start,
                std::cout
                    << val("Error! Expecting \n\n'")
                    << qi::_4
                    << val("'\n\n here: \n\n'")
                    << construct<std::string>(qi::_3, qi::_2)
                    << val("'")
                    << std::endl
            );

            //debug(v);
            //debug(junk);
            //debug(start);
        }

        qi::rule<Iterator> junk;
        //qi::rule<Iterator, qi::unused_type()> junk; // Doesn't work either
        //qi::rule<Iterator, qi::unused_type(), qi::unused_type()> junk; // Doesn't work either
        qi::rule<Iterator, V(), ascii::space_type> v;
        qi::rule<Iterator, std::vector<V>(), ascii::space_type> start;
    };
} // namespace client

int main(int argc, char* argv[]) {
    using iterator_type = std::string::const_iterator;

    std::string input = "";
    input += "v 1 2 3\r";         // keep v 1 2 3
    input += "o a b c\r";         // parse as junk
    input += "v 4 5 6 v 7 8 9\r"; // keep v 4 5 6, but parse v 7 8 9 as junk
    input += "   v 10 11 12\r\r"; // parse as junk

    iterator_type iter = input.begin();
    const iterator_type end = input.end();
    std::vector<V> parsed_output;
    client::VGrammar<iterator_type> v_grammar;

    std::cout << "run" << std::endl;
    bool r = phrase_parse(iter, end, v_grammar, ascii::space, parsed_output);
    std::cout << "done ... r: " << (r ? "true" : "false") << ", iter==end: " << ((iter == end) ? "true" : "false") << std::endl;

    if (r && (iter == end)) {
        BOOST_FOREACH(V const& v_row, parsed_output) {
            std::cout << std::get<0>(v_row) << ", " << std::get<1>(v_row) << ", " << std::get<2>(v_row) << ", " << std::get<3>(v_row) << std::endl;
        }
    }

    return EXIT_SUCCESS;
}

这是示例的输出:

run
done ... r: true, iter==end: true
v, 1, 2, 3
, 0, 0, 0
v, 4, 5, 6
v, 7, 8, 9
v, 10, 11, 12

这就是我真正希望解析器返回的内容。

run
done ... r: true, iter==end: true
v, 1, 2, 3
v, 4, 5, 6

我现在的主要问题是防止“垃圾”规则添加空的 V() 对象。我该如何做到这一点?还是我想多了?

我尝试将 lit(junk) 添加到启动规则中,因为 lit() 不返回任何内容,但这不会编译。它失败了:“静态断言失败:error_invalid_expression”。

我还尝试将垃圾规则的语义操作设置为 qi::unused_type() 但在这种情况下,该规则仍会创建一个空的 V()。

我知道以下问题,但它们没有解决这个特定问题。我之前已经尝试过评论跳过程序,但看起来我必须重新实现跳过程序中的所有解析规则才能识别噪音。我的示例受到最后一个链接中的解决方案的启发:

How to skip line/block/nested-block comments in Boost.Spirit?

How to parse entries followed by semicolon or newline (boost::spirit)?

版本信息:

Linux debian 4.9.0-7-amd64 #1 SMP Debian 4.9.110-3+deb9u2 (2018-08-13) x86_64 GNU/Linux
g++ (Debian 6.3.0-18+deb9u1) 6.3.0 20170516
#define BOOST_VERSION 106200

和:

Linux raspberrypi 4.14.24-v7+ #1097 SMP Mon Mar 5 16:42:05 GMT 2018 armv7l GNU/Linux
g++ (Raspbian 4.9.2-10+deb8u1) 4.9.2
#define BOOST_VERSION 106200 

对于那些想知道的人:是的,我正在尝试解析类似于 Wavefront OBJ 文件的文件,并且我知道已经有很多解析器可用。然而,我正在解析的数据是一个更大的数据结构的一部分,它也需要解析,所以构建一个新的解析器确实有意义。

【问题讨论】:

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


【解决方案1】:

您想要实现的目标称为错误恢复。

不幸的是,Spirit 并没有很好的方法(也有一些内部决策使得外部很难做出)。但是,在您的情况下,通过语法重写很容易实现。

#include <iostream>
#include <string>
#include <vector>
#include <boost/foreach.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix.hpp>
#include <boost/fusion/include/std_tuple.hpp>

namespace qi = boost::spirit::qi;
namespace ascii = boost::spirit::ascii;
namespace phx = boost::phoenix;

using V = std::tuple<std::string, double, double, double>;

namespace client {
    template <typename Iterator>
    struct VGrammar : qi::grammar<Iterator, std::vector<V>()> {
        VGrammar() : VGrammar::base_type(start) {
            using namespace qi;

            v = skip(blank)[no_skip[string("v")] > double_ > double_ > double_];
            junk = +(char_ - eol);
            start = (v || -junk) % eol;

            v.name("v");
            junk.name("junk");
            start.name("start");

            using phx::val;
            using phx::construct;

            on_error<fail>(
                start,
                std::cout
                << val("Error! Expecting \n\n'")
                << qi::_4
                << val("'\n\n here: \n\n'")
                << construct<std::string>(qi::_3, qi::_2)
                << val("'")
                << std::endl
                );

            //debug(v);
            //debug(junk);
            //debug(start);
        }

        qi::rule<Iterator> junk;
        //qi::rule<Iterator, qi::unused_type()> junk; // Doesn't work either
        //qi::rule<Iterator, qi::unused_type(), qi::unused_type()> junk; // Doesn't work either
        qi::rule<Iterator, V()> v;
        qi::rule<Iterator, std::vector<V>()> start;
    };
} // namespace client

int main(int argc, char* argv[]) {
    using iterator_type = std::string::const_iterator;

    std::string input = "";
    input += "v 1 2 3\r";         // keep v 1 2 3
    input += "o a b c\r";         // parse as junk
    input += "v 4 5 6 v 7 8 9\r"; // keep v 4 5 6, but parse v 7 8 9 as junk
    input += "   v 10 11 12\r\r"; // parse as junk

    iterator_type iter = input.begin();
    const iterator_type end = input.end();
    std::vector<V> parsed_output;
    client::VGrammar<iterator_type> v_grammar;

    std::cout << "run" << std::endl;
    bool r = parse(iter, end, v_grammar, parsed_output);
    std::cout << "done ... r: " << (r ? "true" : "false") << ", iter==end: " << ((iter == end) ? "true" : "false") << std::endl;

    if (r && (iter == end)) {
        BOOST_FOREACH(V const& v_row, parsed_output) {
            std::cout << std::get<0>(v_row) << ", " << std::get<1>(v_row) << ", " << std::get<2>(v_row) << ", " << std::get<3>(v_row) << std::endl;
        }
    }

    return EXIT_SUCCESS;
}

【讨论】:

  • 我认为 OP 想要避免语义动作。另外,您能否澄清一下您认为 OP 试图以何种方式进行“错误恢复”?
  • 我认为您误解了主题名称。此外,由于它说“我有大量文件要解析”,因此最好避免不必要的回溯。错误恢复呢,在解析中跳过“垃圾”称为错误恢复,我不明白你在问什么类型的澄清。
  • 关于回溯的公平点。如果性能是一个问题,那么使用语义动作/自定义属性传播的复杂性可能是有保证的。然后+1 :)
  • 我不认为“跳过垃圾”是错误恢复(就像一个草率的语法)。但我现在明白你的意思了(如果你认为语法“完整”和任何不符合标准的输入是“有缺陷的”,那么确实跳过垃圾可以看作是错误恢复。)其他解析器生成器具有“重新同步点”或类似的任务像这样。
  • 它看起来像是顺序的——或者几乎没有人使用。它一直包含 UB,直到 Boost 1.67 github.com/boostorg/spirit/pull/310
【解决方案2】:

我尝试将 lit(junk) 添加到启动规则中,因为 lit() 不返回任何内容,但这不会编译。它失败了:“静态断言失败:error_invalid_expression”。

您要查找的是omit[junk],但它应该没有区别,因为它仍然会生成合成属性optional&lt;&gt;

解决问题

  1. 首先,您需要有重要的换行符。 意味着不能跳过space。因为它吃换行符。更糟糕的是,您还需要前导空格也很重要(例如,将最后一行垃圾)。你甚至不能使用qi::blank 作为船长。 (见Boost spirit skipper issues)。

    只是为了让v 规则中仍然可以有空格,只需有一个本地船长(不吃换行符):

    v %= &lit("v") >> skip(blank) [ string("v") > double_ > double_ > double_ ];
    

    只有在确定没有意外的前导空格后才会与船长互动。

    请注意,string("v") 这种方式有点多余,但这让我们想到了第二个动机:

  2. 其次,我在avoiding semantic actions 与您同在。但是,这意味着您必须让规则反映您的数据结构。

    在这种特殊情况下,这意味着您可能应该将跳过的行稍微翻转一下。如果您将语法表达为v 的直接重复,穿插/whatever/,而不是/newline/,会怎样?我会这样写:

    junk = *(char_ - eol);
    other = !v >> junk;
    
    start = *(v >> junk >> eol % other);
    

    注意

    • 分隔符表达式现在使用operator%(列表运算符)本身:(eol % other)。这巧妙地完成的是,只要它们仅由“其他”行分隔(此时为 !v 的任何内容),它就会不断吃换行符。
    • otherjunk 更受限制,因为 junk 可能会吃掉 v,而 other 确保永远不会发生
    • 因此v &gt;&gt; junk 允许正确处理样本的第三行(具有v 4 5 6 v 7 8 9\r 的行)

现在一切正常:Live On Coliru

run
done ... r: true, iter==end: true
v, 1, 2, 3
v, 4, 5, 6

完善它

您可能知道,当第一行不是v 行时,它处理这种情况。让我们将该案例添加到示例中并确保它也能正常工作:

Live On Coliru

//#define BOOST_SPIRIT_DEBUG
#include <iostream>
#include <string>
#include <vector>
#include <boost/foreach.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix.hpp>
#include <boost/fusion/include/std_tuple.hpp>

namespace qi = boost::spirit::qi;
namespace phx = boost::phoenix;

using V = std::tuple<std::string, double, double, double>;

namespace client {
    template <typename Iterator>
    struct VGrammar : qi::grammar<Iterator, std::vector<V>()> {
        VGrammar() : VGrammar::base_type(start) {
            using namespace qi;

            v %= &lit("v") >> skip(blank) [ string("v") > double_ > double_ > double_ ];
            junk = *(char_ - eol);
            other = !v >> junk;

            start = 
                other >> eol % other >>
                *(v >> junk >> eol % other);

            BOOST_SPIRIT_DEBUG_NODES((v)(junk)(start))

            on_error<fail>(
                start,
                std::cout
                    << phx::val("Error! Expecting \n\n'") << qi::_4
                    << "'\n\n here: \n\n'" << phx::construct<std::string>(qi::_3, qi::_2)
                    << "'\n"
            );
        }

      private:
        qi::rule<Iterator> other, junk;
        qi::rule<Iterator, V()> v;
        qi::rule<Iterator, std::vector<V>()> start;
    };
} // namespace client

int main() {
    using iterator_type = std::string::const_iterator;

    std::string input = "";
    input += "o a b c\r";         // parse as junk
    input += "v 1 2 3\r";         // keep v 1 2 3
    input += "o a b c\r";         // parse as junk
    input += "v 4 5 6 v 7 8 9\r"; // keep v 4 5 6, but parse v 7 8 9 as junk
    input += "   v 10 11 12\r\r"; // parse as junk

    iterator_type iter = input.begin();
    const iterator_type end = input.end();
    std::vector<V> parsed_output;
    client::VGrammar<iterator_type> v_grammar;

    std::cout << "run" << std::endl;
    bool r = parse(iter, end, v_grammar, parsed_output);
    std::cout << "done ... r: " << (r ? "true" : "false") << ", iter==end: " << ((iter == end) ? "true" : "false") << std::endl;

    if (iter != end)
        std::cout << "Remaining unparsed: '" << std::string(iter, end) << "'\n";

    if (r) {
        BOOST_FOREACH(V const& v_row, parsed_output) {
            std::cout << std::get<0>(v_row) << ", " << std::get<1>(v_row) << ", " << std::get<2>(v_row) << ", " << std::get<3>(v_row) << std::endl;
        }
    }

    return EXIT_SUCCESS;
}

【讨论】:

  • junkomit[junk]没有区别,junk生成unused_type的属性。该主题中提出的实际问题是“为什么当底层解析器属性为 unused_type 时,Spirit 会将默认构造属性附加到容器而不是什么都不做”。
  • @NikitaKniazev 感谢您让我知道 :) 显然,我只是在最直接和最直接的意义上回应lit(junk) 没有编译的(引用的)观察。正如您在我的其余答案中看到的那样,我什至不再提及它,因为确实unused_type 属性声明的所有不同拼写都是等效的,而这确实不是问题所在。顺便说一句,我的回答是关于你提到的:如何制定解析器,使其确实匹配所需的绑定输出属性。
  • 你已经通过这条奇怪的规则赢得了我的 +1,由于某种原因 Spirit 接受了这条规则。但是我不建议任何人在他们的代码库中实际使用这样的东西:)
  • 它被接受的原因很明显(就像我解释的那样,它只是匹配数据结构)。是的,“奇怪”的部分是分隔符进行负前瞻的地方,但这很常见(尽管我猜在词法分析/扫描中更常见)
  • 感谢您的解释和附加链接。我可以看到,要掌握精神::qi 的细微差别,我还有很长的路要走。但是,您的示例有效,但不适用于原始数据。您在示例中的输入开头添加了“o a b c”。如果我删除该行,解析器将失败。当然,大多数 OBJ 文件在顶点信息之前都有 mtllib 或类似的东西。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多