使用boost :: spirit以任何顺序解析命名参数 [英] Using boost::spirit to parse named parameters in any order

查看:59
本文介绍了使用boost :: spirit以任何顺序解析命名参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为一种类型的输入文件编写解析器.输入文件如下所示:

I am writing a parser for a type of input file. The input file looks something like:

[CalculationBlock]
CalculationTitle="Test Parser Input System" , MatchingRadius=25.0, StepSize=0.01,ProblemType=RelSchroedingerEqn
MaxPartialWaveJ=800, SMatConv=10E-8
PartialWaveConv= 10E-8, SmallValueLimit = 10E-8
PotentialRadType=HeavyIon
[end]

从本质上讲,它分为以[BlockName]开头的块,然后在其中包含一组命名参数.命名的参数可以用',''\n'字符分隔.

Essentially it is divided into blocks that start with [BlockName] and then have a set of named parameters within. The named parameters can be separated by ',' or '\n' characters.

使用我在上面给出的不完整的输入文件,我想为其编写一个解析器,以作为更完整的输入文件的起点.我这样做了,但是解析器有一个我不确定如何解决的缺点.它与参数顺序无关.例如,如果用户将参数PartialWaveConv= 10E-8放在SMatConv=10E-8之前,它将失败.

Using the incomplete input file I gave above, I wanted to write a parser for it that would serve as a jumping off point for a more complete input file. I did so but the parser has a weakness that I am not sure how to address. It is not parameter order independent. For example, if a user were to put the parameter PartialWaveConv= 10E-8 before SMatConv=10E-8 it would fail.

我简要地考虑了枚举块中参数的每个可能顺序,但是由于存在n个参数值对的n!置换,因此我将其丢弃. 所以我的问题是:有没有办法使解析器与参数顺序无关?

I briefly contemplated enumerating each possible order of parameters in a block but I discarded it since there are n! permutations of n parameter value pairs. So my question is: Is there any way to make the parser independent of parameter ordering?

下面我写的玩具解析器很抱歉,这是业余的,这是我第一次尝试,更不用说boost.spirit了.

The toy parser I wrote is below, I apologize if it is amateurish, this is my first foray into boost, let alone boost.spirit.

#include<string>
#include<iostream>
#include<cstdlib>
#include<fstream>
#include<boost/config/warning_disable.hpp>
#include<boost/spirit/include/qi.hpp>
#include<boost/spirit/include/phoenix_core.hpp>
#include<boost/spirit/include/phoenix_operator.hpp>
#include<boost/spirit/include/phoenix_object.hpp>
#include<boost/fusion/include/adapt_struct.hpp>
#include<boost/fusion/include/io.hpp>
#include<boost/spirit/include/support_istream_iterator.hpp>

namespace blocks
{
namespace qi = boost::spirit::qi;
namespace ascii = boost::spirit::ascii;
namespace phoenix = boost::phoenix;

struct CalcBlock
{
    std::string calculationTitle;
    float matchingRad;
    float stepSize;
    std::string problemType;
    int maxPartialWaveJ;
    float sMatrixConvergenceValue;
    float partialWaveConvergenceValue;
    float smallValueLimit;
    std::string potentialRadType;
};

}

//tell fusion about the block structure
BOOST_FUSION_ADAPT_STRUCT(blocks::CalcBlock,
                        (std::string, calculationTitle)
                        (float, matchingRad)
                        (float, stepSize)
                        (std::string, problemType)
                        (int, maxPartialWaveJ)
                        (float, sMatrixConvergenceValue)
                        (float, partialWaveConvergenceValue)
                        (float, smallValueLimit)
                        (std::string, potentialRadType)
)

namespace blocks
{

template <typename Iterator>
struct CalcBlockParser : qi::grammar<Iterator, CalcBlock(), boost::spirit::ascii::blank_type>
{
    CalcBlockParser() : CalcBlockParser::base_type(start)
    {
        using qi::int_;
        using qi::lit;
        using qi::float_;
        using qi::lexeme;
        using ascii::char_;

        quotedString %= lexeme['"' >> +(char_ - '"' - '\n') >> '"'];
        plainString %= lexeme[ +(char_ - ' ' - ',' - '\n') ];

        start %=
            lit("[CalculationBlock]") >> '\n'
            >> lit("CalculationTitle") >> '=' >> quotedString >> (lit(',') | lit('\n'))
            >> lit("MatchingRadius") >> '=' >> float_ >> (lit(',') | lit('\n'))
            >> lit("StepSize") >> '=' >> float_ >> (lit(',') | lit('\n'))
            >> lit("ProblemType") >> '=' >> plainString >> (lit(',') | lit('\n'))
            >> lit("MaxPartialWaveJ") >> '=' >> int_ >> (lit(',') | lit('\n'))
            >> lit("SMatConv") >> '=' >> float_ >> (lit(',') | lit('\n'))
            >> lit("PartialWaveConv") >> '=' >> float_ >> (lit(',') | lit('\n'))
            >> lit("SmallValueLimit") >> '=' >> float_ >> (lit(',') | lit('\n'))
            >> lit("PotentialRadType") >> '=' >> plainString
            >> lit("\n[end]\n");
    }

    qi::rule<Iterator, std::string(), boost::spirit::ascii::blank_type> quotedString;
    qi::rule<Iterator, std::string(), boost::spirit::ascii::blank_type> plainString;
    qi::rule<Iterator, CalcBlock(), boost::spirit::ascii::blank_type> start;
};

}

using std::cout;
using std::endl;
namespace spirit = boost::spirit;
int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        cout << "\nUsage:\n\t./echos InputFileName\n" << endl;
        return EXIT_FAILURE;
    }

    std::string inputFileName(argv[1]);
    cout << "Reading input from the file: " << inputFileName << endl;
    std::ifstream input(inputFileName);
    input.unsetf(std::ios::skipws);

    spirit::istream_iterator start(input);
    spirit::istream_iterator stop;

    typedef blocks::CalcBlockParser<spirit::istream_iterator> CalcBlockParser;

    CalcBlockParser cbParser;

    blocks::CalcBlock cb;

    bool success = phrase_parse(start, stop, cbParser, boost::spirit::ascii::blank, cb);

    if (success && start == stop)
    {
        std::cout << boost::fusion::tuple_open('[');
        std::cout << boost::fusion::tuple_close(']');
        std::cout << boost::fusion::tuple_delimiter(", ");

        std::cout << "-------------------------\n";
        std::cout << "Parsing succeeded\n";
        std::cout << "got: " << boost::fusion::as_vector(cb) << std::endl;
        std::cout << "\n-------------------------\n";
    }
    else
    {
        std::cout << boost::fusion::tuple_open('[');
        std::cout << boost::fusion::tuple_close(']');
        std::cout << boost::fusion::tuple_delimiter(", ");

        std::cout << "-------------------------\n";
        std::cout << "Parsing failed\n";
        std::cout << "got: " << boost::fusion::as_vector(cb) << std::endl;
        std::cout << "\n-------------------------\n";
    }

    return EXIT_SUCCESS;
}

推荐答案

仅出于乐趣/完整性,我回顾了语法并提出了以下测试.

Just for fun/completeness I reviewed the grammar and came up with the following test.

我向左和向右提出了一些改进建议(如OP在实时流中所见证),结果代码,测试和输出在这里:

I have made a few improvement suggestions left and right (as the OP witnessed on the live stream), and the resulting code, test and output are here:

在Coliru上直播

#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/spirit/include/qi.hpp>
#include <fstream>
#include <iostream>

namespace blocks {
    struct CalcBlock {
        std::string calculationTitle;
        float       matchingRad;
        float       stepSize;
        std::string problemType;
        int         maxPartialWaveJ;
        float       sMatrixConvergenceValue;
        float       partialWaveConvergenceValue;    
        float       smallValueLimit;
        std::string potentialRadType;
    };
}

BOOST_FUSION_ADAPT_STRUCT(blocks::CalcBlock, // Boost 1.58+ style adapt-struct
        calculationTitle, matchingRad, stepSize, problemType, maxPartialWaveJ,
        sMatrixConvergenceValue, partialWaveConvergenceValue, smallValueLimit,
        potentialRadType)

namespace blocks {

    namespace qi = boost::spirit::qi;

    template <typename Iterator>
    struct CalcBlockParser : qi::grammar<Iterator, CalcBlock()> {

        CalcBlockParser() : CalcBlockParser::base_type(start) {

            using namespace qi;
            auto eol_ = copy((',' >> *eol) | +eol); // http://stackoverflow.com/a/26411266/85371 (!)

            quotedString = '"' >> +~char_("\"\n") >> '"';
            plainString  =  +~char_(" ,\n");

            start        = skip(blank) [cbRule];

            cbRule       = lexeme["[CalculationBlock]"] >> eol 
              >> (
                      (lexeme["CalculationTitle"] >> '=' >> quotedString >> eol_)
                    ^ (lexeme["MatchingRadius"]   >> '=' >> float_       >> eol_)
                    ^ (lexeme["StepSize"]         >> '=' >> float_       >> eol_)
                    ^ (lexeme["ProblemType"]      >> '=' >> plainString  >> eol_)
                    ^ (lexeme["MaxPartialWaveJ"]  >> '=' >> int_         >> eol_)
                    ^ (lexeme["SMatConv"]         >> '=' >> float_       >> eol_)
                    ^ (lexeme["PartialWaveConv"]  >> '=' >> float_       >> eol_)
                    ^ (lexeme["SmallValueLimit"]  >> '=' >> float_       >> eol_)
                    ^ (lexeme["PotentialRadType"] >> '=' >> plainString  >> eol_)
                 )
             >> lexeme["[end]"]
             >> *eol 
             >> eoi;
        }

      private:
        qi::rule<Iterator, CalcBlock()> start;
        qi::rule<Iterator, CalcBlock(), qi::blank_type> cbRule;
        // lexemes:
        qi::rule<Iterator, std::string()> quotedString, plainString;
    };
}

using   boost::fusion::as_vector;
typedef boost::spirit::istream_iterator It;

int main(int argc, char **argv) {
    if (argc != 2) {
        std::cout << "Usage:\n\t" << argv[0] << " InputFileName" << std::endl;
        return 1;
    }

    std::string inputFileName(argv[1]);
    std::cout << "Reading input from the file: " << inputFileName << std::endl;
    std::ifstream input(inputFileName);
    input.unsetf(std::ios::skipws);

    It start(input), stop;

    blocks::CalcBlock cb;
    blocks::CalcBlockParser<It> cbParser;

    bool success = parse(start, stop, cbParser, cb);

    {
        using namespace boost::fusion;
        std::cout << tuple_open('[') << tuple_close(']') << tuple_delimiter(", ");
    }

    std::cout << "-------------------------\n";
    std::cout << "Parsing " << (success?"succeeded":"failed") << "\n";
    std::cout << "got: "    << as_vector(cb)                  << "\n";
    std::cout << "-------------------------\n";
}

输入:

[CalculationBlock]
CalculationTitle="Test Parser Input System"


SMatConv=10E-8,


PartialWaveConv= 10E-8, MaxPartialWaveJ=800, SmallValueLimit = 10E-8

PotentialRadType=HeavyIon , MatchingRadius=25.0, StepSize=0.01,ProblemType=RelSchroedingerEqn

[end]

输出:

Reading input from the file: input.txt
-------------------------
Parsing succeeded
got: [Test Parser Input System, 25, 0.01, RelSchroedingerEqn, 800, 1e-07, 1e-07, 1e-07, HeavyIon]
-------------------------

这篇关于使用boost :: spirit以任何顺序解析命名参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆