【问题标题】:Parsing recursive rules with spirit x3用精神 x3 解析递归规则
【发布时间】:2016-05-26 16:35:52
【问题描述】:

我想解析以下递归规则,它解析简单的模板类标识符,如foo<bar> foo<bar,baz> foo<bar<baz>> 这是简单的语法:

identifier := A-Z | a-z | _
class_identifier = identifier ?("<" identifier|class_identifier 
                                    ( "," identifier|class_identifier)* 
                                ">") 

我尝试用 x3 编写一个解析器,如下所示:

 auto const identifier = x3::rule<class identifier_id, std::string>{"identifier"}
                          = +x3::char_("A-Za-z");

 x3::rule<class class_identifier, std::string> class_identifier = "class_identifier";

 auto const class_identifier_def  = identifier //classname
                                            >> -(x3::string("<")
                                                 >> (identifier | class_identifier)                                           
                                                 >> *(x3::string(",")                                                     
                                                      >> (identifier | class_identifier))
                                                 >> x3::string(">"));
 BOOST_SPIRIT_DEFINE(class_identifier)

但是这个尝试无法解析像 foo&lt;bar&lt;baz&gt;&gt; 这样的东西,但是 foo 很好。 我的语法是否存在一些逻辑错误,或者我是否使用了错误的提升精神,因为这是一个递归规则?

【问题讨论】:

  • 为了让你的生活更轻松,我相信(identifier | class_identifier) &gt;&gt; *(x3::string(",") &gt;&gt; (identifier | class_identifier))可以换成(identifier | class_identifier) % x3::string(",")。如果可以将其简化为 % ',' 以及文字不会干扰运算符重载的其他地方,我不会感到惊讶。
  • 确实如此。 % ',' 很好
  • 即使我解析成一个字符串并希望',' 在字符串中?
  • @Exagon 确实不是。列表运算符中的分隔符解析器周围有一个隐含的x3::omit[]

标签: c++ parsing c++14 boost-spirit boost-spirit-x3


【解决方案1】:

我找到了无法解析的原因。我不得不将此(identifier | class_identifier) 更改为(class_identifier | identifier),因为它也是class_identifier 规则也以identifier 开头。这就是为什么它每次都尝试使用 identifier 规则解析然后在 &lt; 处失败

【讨论】:

  • 我认为目前替代解析器的第二个分支从未被采用。我还没有测试它,所以我可能是错的,但我很确定你甚至不需要替代运算符,只要你在class_identifier 中有可选的。如果将来您更改属性(从纯字符串到某种 AST),您当前的定义会更好(删除该可选属性)。
猜你喜欢
  • 2017-02-18
  • 2017-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-14
  • 1970-01-01
相关资源
最近更新 更多