如何解析升压精神正常的保留字 [英] How to parse reserved words correctly in boost spirit
问题描述
我试图解析语法的序列:;方向><键入><名>。例如:
I'm trying to parse a sequence of the syntax: < direction > < type > < name >. For example:
in float foo
的方向在哪里可以为在 退出或 IN_OUT 。我已经成功地用气::符号类的方向关键字转换为枚举解析正确的文本。
where the direction can be either in, out, or in_out. I've succeeded in parsing correct text by using a qi::symbols class to convert the direction keywords to an enum.
然而,问题显示了当我没有正确的文本。就拿例如:
However, the problem shows when I don't have correct text. Take the example:
int foo
符号表解析器将除了'中'的'廉政'类型的一部分,所以结果将是:
The symbol table parser will except the 'in' part of the 'int' type and so the results will be:
direction: in
type: t
name: foo
和未检测到错误。什么是最好的方式,能够解析IN,OUT和IN_OUT保留字,并确保它们后跟一个非标识符字符,这样的previous文本的'廉政'的一部分失败了呢?
And the error is not detected. What's the best way to be able to parse the in, out and in_out reserved words and ensure that they are followed by a non-identifier character so that the 'int' part of the previous text fails?
感谢
推荐答案
在除了麦克建议手册的方法,你可以
In addition to the "manual" approach suggested by Mike you can
- 使用的便捷包装器规则
- 使用
不同的
解析器direetive从圣灵库
- use a convenience wrapper rule
- use the
distinct
parser direetive from the Spirit Repository
我只记得,有一次我想出了这个快速和肮脏的帮助:
1. Use a convenience wrapper
I just remembered, I once came up with this quick and dirty helper:
static const qi::rule<It, qi::unused_type(const char*)> kw
= qi::lit(qi::_r1) >> !qi::alnum;
您可以使用像(使用 +上火
来衰减阵列-REF到为const char *
):
Which you could use like (using +"lit"
to decay the array-ref into const char*
):
stmt =
kw(+"if") >> '(' >> expr >> ')' >> block
>> -(kw(+"else") >> block)
;
您可以把它大大方便
template <std::size_t N>
static auto kw(char const (&keyword)[N]) -> qi::rule<Iterator> {
// qi::lit has problems with char arrays, use pointer instead.
return qi::lit(+keyword) >> !qi::alnum;
}
所以你可以
kw_if = kw("if");
kw_then = kw("then");
kw_else = kw("else");
kw_and = kw("and");
kw_or = kw("or");
kw_not = kw("not");
2。从精神库使用不同的
指令
在除了麦克建议手册的方法,你可以使用来自圣灵库的不同的
解析器指令:
int main()
{
using namespace spirit_test;
using namespace boost::spirit;
{
using namespace boost::spirit::ascii;
qi::rule<char const*, space_type> r;
r = distinct::keyword["description"] >> -lit(':') >> distinct::keyword["ident"];
BOOST_TEST(test("description ident", r, space));
BOOST_TEST(test("description:ident", r, space));
BOOST_TEST(test("description: ident", r, space));
BOOST_TEST(!test("descriptionident", r, space));
}
return boost::report_errors();
}
这篇关于如何解析升压精神正常的保留字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!