【发布时间】:2019-04-19 15:51:10
【问题描述】:
我正在尝试解析头文件中定义的 C++ 结构。我开始定义语法,但我遇到了问题。
这是我的代码:
#include <boost/spirit/home/x3.hpp>
int main() {
namespace x3 = boost::spirit::x3;
// Parse "#if !defined XXX_X_" or "'#ifndef X_X"
auto Ifndef = x3::skip(x3::space)[(x3::lit('#') >> (x3::lit("ifndef") | (x3::lit("if") >> x3::lit("!defined"))))];
auto HeaderGuardFirstRow = Ifndef >> +(x3::alnum | '_');
// Parse "#define XXX_X" or "# define XXX_X"
auto Define = x3::skip(x3::space)[(x3::lit('#') >> x3::lit("define"))];
auto HeaderGuardSecondRow = Define >> +(x3::alnum | '_');
// Parse
// "
// #if !defined XXX_X_
// #define XXX_X
// "
auto HeaderGuardBegin = HeaderGuardFirstRow >> HeaderGuardSecondRow;
// Parse "#endif" or "# endif"
auto HeaderGuardEnd = x3::skip(x3::space)[x3::lit('#') >> (x3::lit("endif"))];
// Parse variable name like "xxx" or "my_var"
auto VariableName = x3::lexeme[x3::char_("a-zA-Z_") >> *(x3::alnum | x3::lit("_"))];
// Skipper for C++ comments (nested /* */ are not handled for now)
auto SingleLineComment = "//" >> *(x3::char_ - x3::eol) >> (x3::eol | x3::eoi);
auto BlockComment = "/*" >> *(x3::char_ - "*/") >> "*/";
auto Skipper = SingleLineComment | BlockComment | x3::ascii::space;
// Parse
// "
// typedef struct {
// } MyStruct;
// "
// ERROR: This parse does not work
auto StructType = -x3::lit("typedef") >> x3::skip(Skipper)[x3::lit("struct") >> x3::lit('{')] >>
x3::skip(Skipper)[x3::lit('}') >> VariableName >> x3::lit(";")];
// Header grammar. Should parse
// "
// #if !defined XXX_H
// #define XXX_H
// typedef struct {
// } MyStruct;
// #endif
// "
auto grammar = HeaderGuardBegin >> *(StructType) >> HeaderGuardEnd;
std::string data01(R"xx(
#if !defined XXX_H
#define XXX_H
#endif
)xx");
bool r = phrase_parse(
data01.begin(),
data01.end(),
grammar,
Skipper
);
std::string data02(R"xx(
#if !defined XXX_H
// Single line comment
#define XXX_H
#endif // !XXX_H
)xx");
r = phrase_parse(
data02.begin(),
data02.end(),
grammar,
Skipper
);
std::string data03(R"xx(
#if !defined XXX_H
#define XXX_H
typedef struct {
} MyStruct;
#endif
)xx");
// r = false: This parsing does not work.
r = phrase_parse(
data03.begin(),
data03.end(),
grammar,
Skipper
);
return 0;
}
在代码中要解析三个字符串:一个只有标头保护,第二个与第一个类似,但带有一些 C++ cmets,第三个带有空结构。
这是最后一个解析失败,我不明白为什么。在我用于结构StructType 的语法中,我首先检查一个可选的typedef,然后检查关键字struct 和可以附加或不附加的{ 字符,然后搜索} 字符后跟一个变量名,后跟;。
我不明白错误在哪里。我在解析空结构时做错了什么?
【问题讨论】:
标签: c++ boost boost-spirit boost-spirit-x3