使用提升精神的递归BNF规则

时间:2017-07-20 16:25:32

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

我正在尝试使用 boost spirit 为以下BNF规则编写解析器 (提升v1.64)
规则是:

<numeric-literal>::= integer  
<type-name> ::= "in" | "out" | "in_out"  
<array-type-spec> ::= <type-spec> "[" [<numeric-literal>] "]"  
<tuple-type-spec> ::= "(" <type-spec> ("," <type-spec>)+ ")"
<type-spec> ::= <type-name> | <array-type-spec> | <tuple-type-spec>  

以下是我的尝试,使用boost::make_recursive_variant
它似乎在字符串in上工作正常 但它在in[2]上失败了 我的错在哪里?
什么是优雅的解决方案?

namespace Ast {
enum class TypeName { IN, OUT, INOUT};
using NumericLiteral = int;
    using TypeSpec = boost::make_recursive_variant
    <
    TypeName,
    std::pair<boost::recursive_variant_, NumericLiteral>,
    std::vector < boost::recursive_variant_ >
    >::type;
}
//grammar:
namespace myGrammar {
namespace qi = boost::spirit::qi;

template <typename Iterator = char const*,typename Signature = Ast::TypeSpec()>
struct myRules : qi::grammar < Iterator, Signature> {

    myRules() : myRules::base_type(start) {
        fillSymbols();
        rNumericLiteral = qi::int_;
        rTypeName = sTypeName;
        rTypeSpec = rTypeName | (rTypeSpec >> '[' >> rNumericLiteral >> ']') | ('(' >> qi::repeat(2, qi::inf)[(rTypeSpec % ',')] >> ')');

        start = qi::skip(qi::space)[rTypeSpec];
    }

private:
    using Skipper = qi::space_type;
    qi::rule<Iterator,  Ast::TypeSpec()> start;
    qi::rule<Iterator, Ast::NumericLiteral(), Skipper> rNumericLiteral;

    qi::rule<Iterator, Ast::TypeName(), Skipper> rTypeName;
    qi::rule<Iterator, Ast::TypeSpec(), Skipper> rTypeSpec;


    //symbols
    qi::symbols<char, Ast::TypeName>sTypeName;
    void fillSymbols()
    {
        using namespace Ast;
        sTypeName.add
            ("in", TypeName::IN)
            ("out", TypeName::OUT)
            ("in_out", TypeName::INOUT)
    }

};
}

1 个答案:

答案 0 :(得分:2)

将语法1:1转换为PEG语法存在问题,因为左递归会导致无限递归。

您仍然可以轻松地重新排列规则,因此不会发生左递归,但是您在合成所需的AST时会遇到更多麻烦。

这是一个中途站,有一半不错的测试结果:

<强> Live On Coliru

//#define BOOST_SPIRIT_DEBUG
#include <boost/spirit/include/qi.hpp>
#include <boost/fusion/adapted/std_pair.hpp>

/*
    <numeric-literal> ::= integer
    <type-name>       ::= "in" | "out" | "in_out"
    <array-type-spec> ::= <type-spec> "[" [<numeric-literal>] "]"
    <tuple-type-spec> ::= "(" <type-spec> ("," <type-spec>)+ ")"
    <type-spec>       ::= <type-name> | <array-type-spec> | <tuple-type-spec>
*/

namespace Ast {
    enum class TypeName { IN, OUT, INOUT };

    static inline std::ostream& operator<<(std::ostream& os, TypeName tn) {
        switch(tn) {
            case TypeName::IN:    return os << "IN";
            case TypeName::OUT:   return os << "OUT";
            case TypeName::INOUT: return os << "INOUT";
        }
        return os << "?";
    }

    using NumericLiteral = int;

    using TypeSpec = boost::make_recursive_variant<
        TypeName,
        std::pair<boost::recursive_variant_, NumericLiteral>,
        std::vector<boost::recursive_variant_>
    >::type;

    using ArraySpec = std::pair<TypeSpec, NumericLiteral>;
    using TupleSpec = std::vector<TypeSpec>;
}

// grammar:
namespace myGrammar {
    namespace qi = boost::spirit::qi;

    template <typename Iterator = char const *, typename Signature = Ast::TypeSpec()>
        struct myRules : qi::grammar<Iterator, Signature> {

            myRules() : myRules::base_type(start) {
                rNumericLiteral = qi::int_;
                rTypeName       = sTypeName >> !qi::alpha;
                rTupleSpec      = '(' >> rTypeSpec >> +(',' >> rTypeSpec) >> ')'; 
                rScalarSpec     = rTypeName | rTupleSpec;
                rArraySpec      = rScalarSpec >> '[' >> rNumericLiteral >> ']';
                rTypeSpec       = rArraySpec | rScalarSpec;

                start = qi::skip(qi::space)[rTypeSpec >> qi::eoi];

                BOOST_SPIRIT_DEBUG_NODES((start)(rTypeSpec)(rTypeName)(rArraySpec)(rScalarSpec)(rTypeSpec)(rNumericLiteral))
            }

          private:
            using Skipper = qi::space_type;
            qi::rule<Iterator, Ast::TypeSpec()> start;
            qi::rule<Iterator, Ast::NumericLiteral(), Skipper> rNumericLiteral;
            qi::rule<Iterator, Ast::ArraySpec(), Skipper> rArraySpec;
            qi::rule<Iterator, Ast::TypeSpec(), Skipper> rTypeSpec, rScalarSpec;
            qi::rule<Iterator, Ast::TupleSpec(), Skipper> rTupleSpec;
            // implicit lexeme
            qi::rule<Iterator, Ast::TypeName()> rTypeName;

            // symbols
            struct TypeName_r : qi::symbols<char, Ast::TypeName> { 
                TypeName_r() {
                    using Ast::TypeName;
                    add ("in", TypeName::IN)
                        ("out", TypeName::OUT)
                        ("in_out", TypeName::INOUT);
                }
            } sTypeName;
        };
}

static inline std::ostream& operator<<(std::ostream& os, Ast::TypeSpec tn) {
    struct {
        std::ostream& _os;

        void operator()(Ast::TypeSpec const& ts) const {
            apply_visitor(*this, ts);
        }
        void operator()(Ast::TypeName tn) const { std::cout << tn; }
        void operator()(Ast::TupleSpec const& tss) const { 
            std::cout << "(";
            for (auto const& ts: tss) {
                (*this)(ts); 
                std::cout << ", ";
            }
            std::cout << ")";
        }
        void operator()(Ast::ArraySpec const& as) const { 
            (*this)(as.first);
            std::cout << '[' << as.second << ']';
        }
    } const dumper{os};

    dumper(tn);
    return os;
}

int main() {
    using It = std::string::const_iterator;
    myGrammar::myRules<It> const parser;

    std::string const test_ok[] = {
        "in",
        "out",
        "in_out",
        "(in, out)",
        "(out, in)",
        "(in, in, in, out, in_out)",
        "in[13]",
        "in[0]",
        "in[-2]",
        "in[1][2][3]",
        "in[3][3][3]",
        "(in[3][3][3], out, in_out[0])",
        "(in[3][3][3], out, in_out[0])",
        "(in, out)[13]",
        "(in, out)[13][0]",
    };

    std::string const test_fail[] = {
        "",
        "i n",
        "inout",
        "()",
        "(in)",
        "(out)",
        "(in_out)",
        "IN",
    };

    auto expect = [&](std::string const& sample, bool expected) {
        It f = sample.begin(), l = sample.end(); 

        Ast::TypeSpec spec;
        bool ok = parse(f, l, parser, spec);

        std::cout << "Test passed:" << std::boolalpha << (expected == ok) << "\n";

        if (expected || (expected != ok)) {
            if (ok) {
                std::cout << "Parsed: " << spec << "\n";
            } else {
                std::cout << "Parse failed\n";
            }
        }

        if (f!=l) {
            std::cout << "Remaining unparsed: '" << std::string(f,l) << "'\n";
        }
    };

    for (std::string const sample : test_ok)   expect(sample, true); 
    for (std::string const sample : test_fail) expect(sample, false); 
}

打印

Test passed:true
Parsed: IN
Test passed:true
Parsed: OUT
Test passed:true
Parsed: INOUT
Test passed:true
Parsed: (IN, OUT, )
Test passed:true
Parsed: (OUT, IN, )
Test passed:true
Parsed: (IN, IN, IN, OUT, INOUT, )
Test passed:true
Parsed: IN[13]
Test passed:true
Parsed: IN[0]
Test passed:true
Parsed: IN[-2]
Test passed:false
Parse failed
Remaining unparsed: 'in[1][2][3]'
Test passed:false
Parse failed
Remaining unparsed: 'in[3][3][3]'
Test passed:false
Parse failed
Remaining unparsed: '(in[3][3][3], out, in_out[0])'
Test passed:false
Parse failed
Remaining unparsed: '(in[3][3][3], out, in_out[0])'
Test passed:true
Parsed: (IN, OUT, )[13]
Test passed:false
Parse failed
Remaining unparsed: '(in, out)[13][0]'
Test passed:true
Test passed:true
Remaining unparsed: 'i n'
Test passed:true
Remaining unparsed: 'inout'
Test passed:true
Remaining unparsed: '()'
Test passed:true
Remaining unparsed: '(in)'
Test passed:true
Remaining unparsed: '(out)'
Test passed:true
Remaining unparsed: '(in_out)'
Test passed:true
Remaining unparsed: 'IN'

正如您所看到的,除了像in[1][2]这样的链式数组维度之外,大多数事情都得到了正确的解析。麻烦的是我们通过在规则中引入“优先级”来解决歧义:

rScalarSpec     = rTypeName | rTupleSpec;
rArraySpec      = rScalarSpec >> '[' >> rNumericLiteral >> ']';
rTypeSpec       = rArraySpec | rScalarSpec;

这意味着我们始终首先尝试预期数组维度,如果我们找不到,则只回退到标量类型规范。这是因为任何array-spec总是首先匹配为scalarspec,因此无法解析数组维度部分。

要修复多维案例,您可以尝试断言[不遵循数组规范:

    rArraySpec      = rScalarSpec >> '[' >> rNumericLiteral >> ']' >> !qi::lit('[')
                    | rArraySpec  >> '[' >> rNumericLiteral >> ']';

但是 - BOOM - 我们再次回到左递归(如果我们进入第二个分支,例如in[1][)。

回到绘图板。

我想到了两个想法。

  1. 我想说删除AST中标量/数组规范之间的区别是非常有益的。如果标量被视为零秩数组,那只意味着我们总是可以将可选维度解析为相同的结果AST类型。

  2. 另一个想法或多或少继续沿着上面所示的道路前进,并且如果推测的标量规格后跟一个'['字符,则需要一直向下回溯。在(very long spec)[1][1][1][1][1][1][1][1][1][1]等情况下,这会导致最糟糕的最坏情况。

  3. 让我实现喝咖啡休息后概述的第一个想法:)

    重写AST

    此处TypeSpec始终带有(可能为空)维度集合:

    namespace Ast {
        enum class TypeName { IN, OUT, INOUT };
    
        static inline std::ostream& operator<<(std::ostream& os, TypeName tn) {
            switch(tn) {
                case TypeName::IN:    return os << "IN";
                case TypeName::OUT:   return os << "OUT";
                case TypeName::INOUT: return os << "INOUT";
            }
            return os << "?";
        }
    
        struct TypeSpec;
    
        using ScalarSpec = boost::make_recursive_variant<
            TypeName,
            std::vector<TypeSpec>
        >::type;
    
        struct TypeSpec {
            ScalarSpec            spec;
            std::vector<unsigned> dim;
        };
    
        using TupleSpec = std::vector<TypeSpec>;
    }
    

    请注意,我们还通过使尺寸无符号来改进。语法将检查完整性不是0。由于这个原因,一些“积极”的测试案例已经转移到“预期到失败”的案例中。

    现在语法很简单:

    rRank      %= qi::uint_ [qi::_pass = (qi::_1 > 0)];
    rTypeName   = sTypeName;
    rTupleSpec  = '(' >> rTypeSpec >> +(',' >> rTypeSpec) >> ')'; 
    rScalarSpec = rTypeName | rTupleSpec;
    rTypeSpec   = rScalarSpec >> *('[' >> rRank >> ']');
    
      

    注意使用Phoenix声明数组维度不能为0的语义操作

    这是现场演示,显示所有测试通过:

    完全演示

    <强> Live On Coliru

    //#define BOOST_SPIRIT_DEBUG
    #include <boost/spirit/include/qi.hpp>
    #include <boost/spirit/include/phoenix.hpp>
    #include <boost/fusion/adapted.hpp>
    
    /*
        <numeric-literal> ::= integer
        <type-name>       ::= "in" | "out" | "in_out"
        <array-type-spec> ::= <type-spec> "[" [<numeric-literal>] "]"
        <tuple-type-spec> ::= "(" <type-spec> ("," <type-spec>)+ ")"
        <type-spec>       ::= <type-name> | <array-type-spec> | <tuple-type-spec>
    */
    
    namespace Ast {
        enum class TypeName { IN, OUT, INOUT };
    
        static inline std::ostream& operator<<(std::ostream& os, TypeName tn) {
            switch(tn) {
                case TypeName::IN:    return os << "IN";
                case TypeName::OUT:   return os << "OUT";
                case TypeName::INOUT: return os << "INOUT";
            }
            return os << "?";
        }
    
        struct TypeSpec;
    
        using ScalarSpec = boost::make_recursive_variant<
            TypeName,
            std::vector<TypeSpec>
        >::type;
    
        struct TypeSpec {
            ScalarSpec            spec;
            std::vector<unsigned> dim;
        };
    
        using TupleSpec = std::vector<TypeSpec>;
    }
    
    BOOST_FUSION_ADAPT_STRUCT(Ast::TypeSpec, spec, dim)
    
    // grammar:
    namespace myGrammar {
        namespace qi = boost::spirit::qi;
    
        template <typename Iterator = char const *, typename Signature = Ast::TypeSpec()>
            struct myRules : qi::grammar<Iterator, Signature> {
    
                myRules() : myRules::base_type(start) {
                    rRank      %= qi::uint_ [qi::_pass = (qi::_1 > 0)];
                    rTypeName   = sTypeName;
                    rTupleSpec  = '(' >> rTypeSpec >> +(',' >> rTypeSpec) >> ')'; 
                    rScalarSpec = rTypeName | rTupleSpec;
                    rTypeSpec   = rScalarSpec >> *('[' >> rRank >> ']');
    
                    start = qi::skip(qi::space)[rTypeSpec >> qi::eoi];
    
                    BOOST_SPIRIT_DEBUG_NODES((start)(rTypeSpec)(rTypeName)(rScalarSpec)(rTypeSpec)(rRank))
                }
    
              private:
                using Skipper = qi::space_type;
                qi::rule<Iterator, Ast::TypeSpec()> start;
                qi::rule<Iterator, Ast::ScalarSpec(), Skipper> rScalarSpec;
                qi::rule<Iterator, Ast::TypeSpec(),   Skipper> rTypeSpec;
                qi::rule<Iterator, Ast::TupleSpec(),  Skipper> rTupleSpec;
                // implicit lexeme
                qi::rule<Iterator, Ast::TypeName()> rTypeName;
                qi::rule<Iterator, unsigned()>      rRank;
    
                // symbols
                struct TypeName_r : qi::symbols<char, Ast::TypeName> { 
                    TypeName_r() {
                        using Ast::TypeName;
                        add ("in", TypeName::IN)
                            ("out", TypeName::OUT)
                            ("in_out", TypeName::INOUT);
                    }
                } sTypeName;
            };
    }
    
    static inline std::ostream& operator<<(std::ostream& os, Ast::TypeSpec tn) {
        struct {
            std::ostream& _os;
    
            void operator()(Ast::ScalarSpec const& ts) const {
                apply_visitor(*this, ts);
            }
            void operator()(Ast::TypeName tn) const { std::cout << tn; }
            void operator()(Ast::TupleSpec const& tss) const { 
                std::cout << "(";
                for (auto const& ts: tss) {
                    (*this)(ts); 
                    std::cout << ", ";
                }
                std::cout << ")";
            }
            void operator()(Ast::TypeSpec const& as) const { 
                (*this)(as.spec);
                for (auto rank : as.dim)
                    std::cout << '[' << rank << ']';
            }
        } const dumper{os};
    
        dumper(tn);
        return os;
    }
    
    int main() {
        using It = std::string::const_iterator;
        myGrammar::myRules<It> const parser;
    
        std::string const test_ok[] = {
            "in",
            "out",
            "in_out",
            "(in, out)",
            "(out, in)",
            "(in, in, in, out, in_out)",
            "in[13]",
            "in[1][2][3]",
            "in[3][3][3]",
            "(in[3][3][3], out, in_out[1])",
            "(in[3][3][3], out, in_out[1])",
            "(in, out)[13]",
            "(in, out)[13][14]",
        };
    
        std::string const test_fail[] = {
            "",
            "i n",
            "inout",
            "()",
            "(in)",
            "(out)",
            "(in_out)",
            "IN",
            "in[0]",
            "in[-2]",
            "(in[3][3][3], out, in_out[0])",
            "(in[3][3][3], out, in_out[0])",
        };
    
        auto expect = [&](std::string const& sample, bool expected) {
            It f = sample.begin(), l = sample.end(); 
    
            Ast::TypeSpec spec;
            bool ok = parse(f, l, parser, spec);
    
            std::cout << "Test passed:" << std::boolalpha << (expected == ok) << "\n";
    
            if (expected || (expected != ok)) {
                if (ok) {
                    std::cout << "Parsed: " << spec << "\n";
                } else {
                    std::cout << "Parse failed\n";
                }
            }
    
            if (f!=l) {
                std::cout << "Remaining unparsed: '" << std::string(f,l) << "'\n";
            }
        };
    
        for (std::string const sample : test_ok)   expect(sample, true); 
        for (std::string const sample : test_fail) expect(sample, false); 
    }
    

    打印

    Test passed:true
    Parsed: IN
    Test passed:true
    Parsed: OUT
    Test passed:true
    Parsed: INOUT
    Test passed:true
    Parsed: (IN, OUT, )
    Test passed:true
    Parsed: (OUT, IN, )
    Test passed:true
    Parsed: (IN, IN, IN, OUT, INOUT, )
    Test passed:true
    Parsed: IN[13]
    Test passed:true
    Parsed: IN[1][2][3]
    Test passed:true
    Parsed: IN[3][3][3]
    Test passed:true
    Parsed: (IN[3][3][3], OUT, INOUT[1], )
    Test passed:true
    Parsed: (IN[3][3][3], OUT, INOUT[1], )
    Test passed:true
    Parsed: (IN, OUT, )[13]
    Test passed:true
    Parsed: (IN, OUT, )[13][14]
    Test passed:true
    Test passed:true
    Remaining unparsed: 'i n'
    Test passed:true
    Remaining unparsed: 'inout'
    Test passed:true
    Remaining unparsed: '()'
    Test passed:true
    Remaining unparsed: '(in)'
    Test passed:true
    Remaining unparsed: '(out)'
    Test passed:true
    Remaining unparsed: '(in_out)'
    Test passed:true
    Remaining unparsed: 'IN'
    Test passed:true
    Remaining unparsed: 'in[0]'
    Test passed:true
    Remaining unparsed: 'in[-2]'
    Test passed:true
    Remaining unparsed: '(in[3][3][3], out, in_out[0])'
    Test passed:true
    Remaining unparsed: '(in[3][3][3], out, in_out[0])'