Search code examples
c++parsingc++14boost-spiritboost-spirit-x3

Parsing recursive rules with spirit x3


I would like to parse the following recusive rule which parses simple template classe identifier like foo<bar> foo<bar,baz> foo<bar<baz>> here is the simple grammar:

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

I tried to write a parser with x3 like this:

 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)

But this try fails to parse stuff like this foo<bar<baz>> but foo is fine. Is there some logical error in my grammar or am I using boost spirit wrong since this is a recursive rule?


Solution

  • I have found why this fails to parse. I hade to change this (identifier | class_identifier) to this (class_identifier | identifier) because it also the class_identifier rule also starts with an identifier. thats why it tried to parse everytime with the identifier rule and then fails at the <