【发布时间】:2011-05-24 20:02:47
【问题描述】:
我正在尝试学习 Boost Spirit,作为练习,我尝试使用 Boost Spirit Classic 解析 SQL INSERT statement。
这是我要解析的字符串:
INSERT INTO example_tab (cola, colb, colc, cold) VALUES (vala, valb, valc, vald);
从SELECT example 我创建了这个小语法:
struct microsql_grammar : public grammar<microsql_grammar>
{
template <typename ScannerT>
struct definition
{
definition(microsql_grammar const& self)
{
keywords = "insert", "into", "values";
chlit<> LPAREN('(');
chlit<> RPAREN(')');
chlit<> SEMI(';');
chlit<> COMMA(',');
typedef inhibit_case<strlit<> > token_t;
token_t INSERT = as_lower_d["insert"];
token_t INTO = as_lower_d["into"];
token_t VALUES = as_lower_d["values"];
identifier =
nocase_d
[
lexeme_d
[
(alpha_p >> *(alnum_p | '_'))
]
];
string_literal =
lexeme_d
[
ch_p('\'') >> +( anychar_p - ch_p('\'') )
>> ch_p('\'')
];
program = +(query);
query = insert_into_clause >> SEMI;
insert_into_clause = insert_clause >> into_clause;
insert_clause = INSERT >> INTO >> identifier >> LPAREN >> var_list_clause >> RPAREN;
into_clause = VALUES >> LPAREN >> var_list_clause >> RPAREN;
var_list_clause = list_p( identifier, COMMA );
}
rule<ScannerT> const& start() const { return program; }
symbols<> keywords;
rule<ScannerT> identifier, string_literal, program, query, insert_into_clause, insert_clause,
into_clause, var_list_clause;
};
};
使用最小值来测试它:
void test_it(const string& my_example)
{
microsql_grammar g;
if (!parse(example.c_str(), g, space_p).full)
{
// point a - FAIL
throw new exception();
}
// point b - OK
}
不幸的是它总是进入A点并抛出异常。因为我是新手,所以我不知道我的错误在哪里。我有两个问题:
- 在使用 Boost Spirit 时调试解析错误的正确方法是什么?
- 为什么在这个例子中解析失败?
【问题讨论】:
-
我试过你的语法,它会解析上面的输入。如果您提供的输入有任何尾随空格或换行符,它们将阻止设置 parse_info::full 标志,但是,将设置 parse_info::hit 标志。
标签: c++ parsing boost boost-spirit