草庐IT

c++ - 使用精神以替代方式解析结构时混淆输出

coder 2024-02-23 原文

这是我尝试以尽可能最好的方式做的事情的一个大大减少的案例。 (当然,问题还在于,我试图了解如何最好地使用精神。)

我需要将数据解析为具有多个成员的结构。成员被简单地列为键值对,因此这很简单——但是,如果某些键不同,那么在我正在解析的数据中,不同的值可能会稍后出现,或者某些键可能会被省略。尽管如此,我最终解析的数据结构是有固定形式的。

在示例代码中,my_structstruct像这样:

struct my_struct {
  std::string a;
  std::string b;
  std::string c;
  std::string d;
};

grammar1是一个像这样解析字符串的语法

"a: x b: y c: z d: w"

进入这样的结构

my_struct{ "x", "y", "z", "w" }

我还想像这样解析字符串:

"a: x b: y d-no-c: w"

进入这样的结构

my_struct{ "x", "y", "", "w" }

理想情况下,我希望以尽可能简单的方式完成此操作,而不会在此过程中制作不必要的字符串拷贝。

我的第一个想法是,应该重写主要规则,以便它解析“a”和“b”,然后根据“c”是否存在在两个备选方案之间进行选择。这作为一个语法很容易解决,但是当我们试图为它的属性语法部分获取正确的数据类型时,我似乎无法让它工作。我尝试使用 std::pair<std::string, std::string>还有fusion::vector对于替代类型,但这显然不能使用 qi 流式传输到我的结构中运算符(operator) << . (grammar2 测试被注释掉,因为它无法编译。)

我的下一个想法是,我们可以简单地有两种主要规则的替代形式,它们的属性类型为 my_struct以确保属性解析有效。令人惊讶的是,这个实现实际上被破坏了——似乎当语法回溯时,它复制了 a。和 b结果结构中的字段。我没想到会这样,我也不知道为什么会这样,你知道吗? (这是 grammar3 )。

grammar3有一个问题,即使它像我认为的那样工作(测试通过),当替代部分回溯时,它也必须重新解析 ab这是一些低效率。如果我们愿意将目标结构从 my_struct 更改为到不同的结构,那么我们可以使用 grammar4 ,与grammar2具有相同的计划, 但目标是其中一个元素是 std::pair 的结构.然后我们将所有字符串从这个临时结构中移出,变成我们真正想要的格式。

那么,问题是:

  • grammar4有效,但是有没有办法按照 grammar2 的方式做一些事情?哪个可能更有效?
  • 为什么 grammar3考试不及格?

完整 list :

#define SPIRIT_USE_PHOENIX_V3
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_fusion.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/fusion/adapted/struct/define_struct.hpp>
#include <boost/fusion/include/define_struct.hpp>
#include <boost/fusion/include/std_pair.hpp>

#include <iostream>
#include <string>
#include <utility>

namespace qi = boost::spirit::qi;

BOOST_FUSION_DEFINE_STRUCT(
 /**/
 ,
 my_struct,
 (std::string, a)
 (std::string, b)
 (std::string, c)
 (std::string, d))

template<typename Iterator>
class grammar1 : public qi::grammar<Iterator, my_struct()> {
public:
  qi::rule<Iterator, std::string()> id;
  qi::rule<Iterator, my_struct()> main;

  grammar1() : grammar1::base_type(main) {
    using qi::lit;
    using qi::char_;
    using qi::omit;
    using qi::space;
    id = omit[ *space ] >> *char_("A-Za-z_") >> omit [ *space ];
    main = lit("a:") >> id >> lit("b:") >> id >> lit("c:") >> id >> lit("d:") >> id;
  }
};


//typedef std::pair<std::string, std::string> second_part_type;
typedef boost::fusion::vector<std::string, std::string> second_part_type;

template<typename Iterator>
class grammar2 : public qi::grammar<Iterator, my_struct()> {
public:
  qi::rule<Iterator, std::string()> id;
  qi::rule<Iterator, second_part_type()> with_c;
  qi::rule<Iterator, second_part_type()> without_c;
  qi::rule<Iterator, my_struct()> main;

  grammar2() : grammar2::base_type(main) {
    using qi::lit;
    using qi::char_;
    using qi::omit;
    using qi::space;
    using qi::attr;
    id = omit[ *space ] >> *char_("A-Za-z_") >> omit [ *space ];
    with_c = lit("c:") >> id >> lit("d:") >> id;
    without_c = attr("") >> lit("d-no-c:") >> id;
    main = lit("a:") >> id >> lit("b:") >> id >> (with_c  | without_c);
  }
};


template<typename Iterator>
class grammar3 : public qi::grammar<Iterator, my_struct()> {
public:
  qi::rule<Iterator, std::string()> id;
  qi::rule<Iterator, my_struct()> with_c;
  qi::rule<Iterator, my_struct()> without_c;
  qi::rule<Iterator, my_struct()> main;

  grammar3() : grammar3::base_type(main) {
    using qi::lit;
    using qi::char_;
    using qi::omit;
    using qi::space;
    using qi::attr;
    id = omit[ *space ] >> *char_("A-Za-z_") >> omit [ *space ];
    with_c = lit("a:") >> id >> lit("b:") >> id >> lit("c:") >> id >> lit("d:") >> id;
    without_c = lit("a:") >> id >> lit("b:") >> id >> attr("") >> lit("d-no-c:") >> id;
    main = with_c | without_c;
  }
};

/***
 * Alternate approach
 */
typedef std::pair<std::string, std::string> spair;

BOOST_FUSION_DEFINE_STRUCT(
 /**/
 ,
 my_struct2,
 (std::string, a)
 (std::string, b)
 (spair, cd))

template<typename Iterator>
class grammar4 : public qi::grammar<Iterator, my_struct2()> {
public:
  qi::rule<Iterator, std::string()> id;
  qi::rule<Iterator, spair()> with_c;
  qi::rule<Iterator, spair()> without_c;
  qi::rule<Iterator, my_struct2()> main;

  grammar4() : grammar4::base_type(main) {
    using qi::lit;
    using qi::char_;
    using qi::omit;
    using qi::space;
    using qi::attr;
    id = omit[ *space ] >> *char_("A-Za-z_") >> omit [ *space ];
    with_c = lit("c:") >> id >> lit("d:") >> id;
    without_c = attr("") >> lit("d-no-c:") >> id;
    main = lit("a:") >> id >> lit("b:") >> id >> (with_c  | without_c);
  }
};

my_struct convert_struct(my_struct2 && s) {
  return { std::move(s.a), std::move(s.b), std::move(s.cd.first), std::move(s.cd.second) };
}

/***
 * Testing
 */
void check_strings_eq(const std::string & a, const std::string & b, const char * label, int line = 0) {
  if (a != b) {
    std::cerr << "Mismatch '" << label << "' ";
    if (line) { std::cerr << "at line " << line << " "; }
    std::cerr << "\"" << a << "\" != \"" << b << "\"\n";
  }
}

void check_eq(const my_struct & s, const my_struct & t, int line = 0) {
  check_strings_eq(s.a, t.a, "a", line);
  check_strings_eq(s.b, t.b, "b", line);
  check_strings_eq(s.c, t.c, "c", line);
  check_strings_eq(s.d, t.d, "d", line);
}

template<template<typename> class Grammar>
void test_grammar(const std::string & input, const my_struct & expected, int line = 0) {
  auto it = input.begin();
  auto end = input.end();
  Grammar<decltype(it)> grammar;
  my_struct result;
  if (!qi::parse(it, end, grammar, result)) {
    std::cerr << "Failed to parse! ";
    if (line) { std::cerr << "line = " << line; }
    std::cerr << "\n";
    std::cerr << "Stopped at:\n" << input << "\n";
    for (auto temp = input.begin(); temp != it; ++temp) { std::cerr << " "; }
    std::cerr << "^\n";
  } else {
    check_eq(result, expected, line);
  }
}

int main() {
  test_grammar<grammar1> ( "a: x    b: y   c: z   d: w",   my_struct{ "x",    "y",   "z",   "w" }, __LINE__);
  test_grammar<grammar1> ( "a: asdf b: jkl c: foo d: bar", my_struct{ "asdf", "jkl", "foo", "bar" }, __LINE__ );
  //test_grammar<grammar2> ( "a: asdf b: jkl c: foo d: bar", my_struct{ "asdf", "jkl", "foo", "bar" }, __LINE__ );
  //test_grammar<grammar2> ( "a: asdf b: jkl d-no-c: bar",   my_struct{ "asdf", "jkl", "", "bar" }, __LINE__ );
  test_grammar<grammar3> ( "a: asdf b: jkl c: foo d: bar", my_struct{ "asdf", "jkl", "foo", "bar" }, __LINE__);
  test_grammar<grammar3> ( "a: asdf b: jkl d-no-c: bar",   my_struct{ "asdf", "jkl", "", "bar" }, __LINE__ );

  // Test 4th grammar
  {
    std::string input = "a: asdf b: jkl c: foo d: bar";
    auto it = input.begin();
    auto end = input.end();
    grammar4<decltype(it)> grammar;
    my_struct2 result;
    if (!qi::parse(it, end, grammar, result)) {
      std::cerr << "Failed to parse! Line = " << __LINE__ << std::endl;
    } else {
      check_eq(convert_struct(std::move(result)),  my_struct{ "asdf", "jkl", "foo", "bar" }, __LINE__);
    }
  }
  {
    std::string input = "a: asdf b: jkl d-no-c: bar";
    auto it = input.begin();
    auto end = input.end();
    grammar4<decltype(it)> grammar;
    my_struct2 result;
    if (!qi::parse(it, end, grammar, result)) {
      std::cerr << "Failed to parse! Line = " << __LINE__ << std::endl;
    } else {
      check_eq(convert_struct(std::move(result)),  my_struct{ "asdf", "jkl", "", "bar" }, __LINE__);
    }
  }
}

最佳答案

我的建议是确实使用置换解析器。

虽然它更加灵活,因此您可能希望在语义操作中添加验证约束:

Live On Coliru

//#define BOOST_SPIRIT_DEBUG
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/tuple/tuple_comparison.hpp>

#include <iostream>
#include <string>

namespace qi = boost::spirit::qi;

struct my_struct {
    std::string a,b,c,d;
};

BOOST_FUSION_ADAPT_STRUCT(my_struct, a, b, c, d)

template<typename Iterator>
class grammar : public qi::grammar<Iterator, my_struct()> {
    public:
        grammar() : grammar::base_type(start) {
            using namespace qi;

            id    = +char_("A-Za-z_");
            part  = lexeme[lit(_r1) >> ':'] >> id;

            main  = part(+"a")
                  ^ part(+"b")
                  ^ part(+"c")
                  ^ (part(+"d") | part(+"d-no-c"));
                  ;

            start = skip(space) [ main ];

            BOOST_SPIRIT_DEBUG_NODES((main)(part))
        }
    private:
        qi::rule<Iterator, std::string()>                            id;
        qi::rule<Iterator, std::string(const char*), qi::space_type> part;
        qi::rule<Iterator, my_struct(), qi::space_type>              main;
        //
        qi::rule<Iterator, my_struct()> start;
};

/***
 * Testing
 */
void check_strings_eq(const std::string & a, const std::string & b, const char * label) {
    if (a != b) {
        std::cerr << "Mismatch '" << label << "' \"" << a << "\" != \"" << b << "\"\n";
    }
}

void check_eq(const my_struct & s, const my_struct & t) {
    check_strings_eq(s.a, t.a, "a");
    check_strings_eq(s.b, t.b, "b");
    check_strings_eq(s.c, t.c, "c");
    check_strings_eq(s.d, t.d, "d");
    if (boost::tie(s.a,s.b,s.c,s.d) == boost::tie(t.a,t.b,t.c,t.d))
        std::cerr << "struct data matches\n";
}

template<template<typename> class Grammar>
void test_grammar(const std::string &input, const my_struct &expected) {
    auto it  = input.begin();
    auto end = input.end();

    Grammar<decltype(it)> grammar;
    my_struct result;

    if (!qi::parse(it, end, grammar, result)) {
        std::cerr << "Failed to parse!\n";
        std::cerr << "Stopped at:\n" << input << "\n";

        for (auto temp = input.begin(); temp != it; ++temp) {
            std::cerr << " ";
        }

        std::cerr << "^\n";
    } else {
        check_eq(result, expected);
    }
}

int main() {
    for (auto&& p : std::vector<std::pair<std::string, my_struct> > {
            {"a: x b: y c: z d: w", my_struct{ "x", "y", "z", "w" }},
            {"a: x      c: z d: w", my_struct{ "x", "" , "z", "w" }},
            {"a: x      c: z"     , my_struct{ "x", "" , "z", ""  }},
            {"     b: y c: z d: w", my_struct{ "" , "y", "z", "w" }},
            {"b: y c: z a: x d: w", my_struct{ "x", "y", "z", "w" }},
            // if you really need:
            {"a: x b: y d-no-c: w", my_struct{ "x", "y", "" , "w" }},
        })
    {
        auto const& input    = p.first;
        auto const& expected = p.second;
        std::cout << "----\nParsing '" << input << "'\n";
        test_grammar<grammar> (input, expected);
    }
}

打印

----
Parsing 'a: x b: y c: z d: w'
struct data matches
----
Parsing 'a: x      c: z d: w'
struct data matches
----
Parsing 'a: x      c: z'
struct data matches
----
Parsing '     b: y c: z d: w'
struct data matches
----
Parsing 'b: y c: z a: x d: w'
struct data matches
----
Parsing 'a: x b: y d-no-c: w'
struct data matches

关于c++ - 使用精神以替代方式解析结构时混淆输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33337623/

有关c++ - 使用精神以替代方式解析结构时混淆输出的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. Ruby 解析字符串 - 2

    我有一个字符串input="maybe(thisis|thatwas)some((nice|ugly)(day|night)|(strange(weather|time)))"Ruby中解析该字符串的最佳方法是什么?我的意思是脚本应该能够像这样构建句子:maybethisissomeuglynightmaybethatwassomenicenightmaybethiswassomestrangetime等等,你明白了......我应该一个字符一个字符地读取字符串并构建一个带有堆栈的状态机来存储括号值以供以后计算,还是有更好的方法?也许为此目的准备了一个开箱即用的库?

  3. ruby - 使用 RubyZip 生成 ZIP 文件时设置压缩级别 - 2

    我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看ruby​​zip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d

  4. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  5. ruby-on-rails - 使用 Ruby on Rails 进行自动化测试 - 最佳实践 - 2

    很好奇,就使用ruby​​onrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提

  6. ruby - 在 Ruby 中使用匿名模块 - 2

    假设我做了一个模块如下:m=Module.newdoclassCendend三个问题:除了对m的引用之外,还有什么方法可以访问C和m中的其他内容?我可以在创建匿名模块后为其命名吗(就像我输入“module...”一样)?如何在使用完匿名模块后将其删除,使其定义的常量不再存在? 最佳答案 三个答案:是的,使用ObjectSpace.此代码使c引用你的类(class)C不引用m:c=nilObjectSpace.each_object{|obj|c=objif(Class===objandobj.name=~/::C$/)}当然这取决于

  7. ruby - 使用 ruby​​ 和 savon 的 SOAP 服务 - 2

    我正在尝试使用ruby​​和Savon来使用网络服务。测试服务为http://www.webservicex.net/WS/WSDetails.aspx?WSID=9&CATID=2require'rubygems'require'savon'client=Savon::Client.new"http://www.webservicex.net/stockquote.asmx?WSDL"client.get_quotedo|soap|soap.body={:symbol=>"AAPL"}end返回SOAP异常。检查soap信封,在我看来soap请求没有正确的命名空间。任何人都可以建议我

  8. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  9. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

  10. ruby - 使用 ruby​​ 将 HTML 转换为纯文本并维护结构/格式 - 2

    我想将html转换为纯文本。不过,我不想只删除标签,我想智能地保留尽可能多的格式。为插入换行符标签,检测段落并格式化它们等。输入非常简单,通常是格式良好的html(不是整个文档,只是一堆内容,通常没有anchor或图像)。我可以将几个正则表达式放在一起,让我达到80%,但我认为可能有一些现有的解决方案更智能。 最佳答案 首先,不要尝试为此使用正则表达式。很有可能你会想出一个脆弱/脆弱的解决方案,它会随着HTML的变化而崩溃,或者很难管理和维护。您可以使用Nokogiri快速解析HTML并提取文本:require'nokogiri'h

随机推荐