Boost属性树解析自定义配置格式

问题描述

按照@sehe在这文章Boost_option to parse a configuration file中提供的这个链接,我需要解析可能有评论配置文件

https://www.boost.org/doc/libs/1_76_0/doc/html/property_tree/parsers.html#property_tree.parsers.info_parser

但是既然有注释(前导#),那么除了read_info()之外,还应该使用grammer_spirit来取出注释吗?我指的是 /property_tree/examples 文件夹中的 info_grammar_spirit.cpp

解决方法

你最好避免依赖于实现细节,所以我建议你预处理你的配置文件只是为了去掉注释。

"//" 简单替换 "; " 可能就足够了。

基于上一个答案:

std::string tmp;
{
    std::ifstream ifs(file_name.c_str());
    tmp.assign(std::istreambuf_iterator<char>(ifs),{});
} // closes file

boost::algorithm::replace_all(tmp,"//",";");
std::istringstream preprocessed(tmp);
read_info(preprocessed,pt);

现在,如果您将输入更改为包含评论:

Resnet50 {
    Layer CONV1 {
        Type: CONV // this is a comment
        Stride { X: 2,Y: 2 }       ; this too
        Dimensions { K: 64,C: 3,R: 7,S: 7,Y:224,X:224 }
    }

    // don't forget the CONV2_1_1 layer
    Layer CONV2_1_1 {
        Type: CONV
        Stride { X: 1,Y: 1 }       
        Dimensions { K: 64,C: 64,R: 1,S: 1,Y: 56,X: 56 }
    }
}

它仍然按预期解析,如果我们还扩展调试输出来验证:

ptree const& resnet50 = pt.get_child("Resnet50");
for (auto& entry : resnet50) {
    std::cout << entry.first << " " << entry.second.get_value("") << "\n";

    std::cout << " --- Echoing the complete subtree:\n";
    write_info(std::cout,entry.second);
}

印刷品

Layer CONV1
 --- Echoing the complete subtree:
Type: CONV
Stride
{
    X: 2,Y: 2
}
Dimensions
{
    K: 64,X:224
}
Layer CONV2_1_1
 --- Echoing the complete subtree:
Type: CONV
Stride
{
    X: 1,Y: 1
}
Dimensions
{
    K: 64,X: 56
}

看到它Live On Coliru

是的,但是……?

如果 '//' 出现在字符串文字中怎么办?不会也换了吧。是的。

这不是图书馆质量的解决方案。您不应该期待它,因为您不必费力解析您定制的配置文件格式。

您是唯一可以判断这种方法的缺点是否对您造成问题的一方。

然而,除了复制和修改 Boost 的解析器或从头开始实现您自己的解析器之外,没有太多可以做的。

对于受虐狂

如果您不想重新实现整个解析器,但仍希望“智能”跳过字符串文字,这里有一个 pre_process 函数可以完成所有这些。这一次,它真正使用了Boost Spirit

#include <boost/spirit/home/x3.hpp>
std::string pre_process(std::string const& input) {
    std::string result;
    using namespace boost::spirit::x3;
    auto static string_literal
        = raw[ '"' >> *('\\'>> char_ | ~char_('"')) >> '"' ];

    auto static comment
        = char_(';') >> *~char_("\r\n")
        | "//" >> attr(';') >> *~char_("\r\n")
        | omit["/*" >> *(char_ - "*/") >> "*/"];

    auto static other
        = +(~char_(";\"") - "//" - "/*");

    auto static content
        = *(string_literal | comment | other) >> eoi;

    if (!parse(begin(input),end(input),content,result)) {
        throw std::invalid_argument("pre_process");
    }
    return result;
}

如您所见,它识别字符串文字(带转义符),处理“//”和“;”将逐行注释设置为等效样式。为了“炫耀”,我加入了 /block 注释/,这些注释无法用正确的 INFO 语法表示,所以我们只 omit[] 它们。

现在让我们用一个时髦的例子进行测试(扩展自文档中的 "Complicated example demonstrating all INFO features"):

#include <boost/property_tree/info_parser.hpp>
#include <iostream>
using boost::property_tree::ptree;

int main() {
    boost::property_tree::ptree pt;
    std::istringstream iss(
            pre_process(R"~~( ; A comment
key1 value1   // Another comment
key2 "value with /* no problem */ special // characters in it {};#\n\t\"\0"
{
   subkey "value split "\
          "over three"\
          "lines"
   {
      a_key_without_value ""
      "a key with special characters in it {};#\n\t\"\0" ""
      "" value    /* Empty key with a value */
      "" /*also empty value: */ ""       ; Empty key with empty value!
   }
})~~"));

    read_info(iss,pt);

    std::cout << " --- Echoing the parsed tree:\n";
    write_info(std::cout,pt);
}

印刷品 (Live On Coliru)

 --- Echoing the parsed tree:
key1 value1
key2 "value with /* no problem */ special // characters in it {};#\n    \"\0"
{
    subkey "value split over threelines"
    {
        a_key_without_value ""
        "a key with special characters in it {};#\n     \"\0" ""
        "" value
        "" ""
    }
}