1

I'm using boost spirit for parsing some complicated expression such as "0b111 << (0x111 + 1) * ....", the problem is parsing hex and bin values, syntax analyzer found 0 before 'b' or 'x' first and takes it as num, but i want to take "0b1111". Tried to do that, but there is no effect.

            ............
            factor =
            num                                  [ qi::_val =    qi::_1  ]
            |   '('  >> expr                     [ qi::_val =    qi::_1  ] >>')'
            |   '-'  >> num                      [ qi::_val =   -qi::_1  ]
            |   '+'  >> num                      [ qi::_val =    qi::_1  ]
            |   '~'  >> num                      [ qi::_val =   ~qi::_1  ]
            ;


            num =
            qi::uint_                           [ qi::_val =    qi::_1  ]
            |   hexOrBinNum                     [  qi::_val =   qi::_1  ]
            ;


            hexOrBinNum =
            "0x"    >>    qi::int_parser<int, 16>{}        [ qi::_val =    qi::_1  ]
            |   "0b" >>    qi::int_parser<int, 2>{}         [ qi::_val =    qi::_1  ]
            ;
JeJo
  • 30,635
  • 6
  • 49
  • 88
Yaroslav
  • 57
  • 1
  • 8
  • [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) – babu646 May 21 '18 at 09:33
  • Also see https://stackoverflow.com/questions/29132809/using-boostspiritqi-to-parse-numbers-with-separators (both answers) – sehe May 21 '18 at 20:18

1 Answers1

1

Found an answer, just replaced this lines

        num =
        qi::uint_                           [ qi::_val =    qi::_1  ]
        |   hexOrBinNum                     [  qi::_val =   qi::_1  ]
        ;

to

        num =
        hexOrBinNum                       [  qi::_val =   qi::_1  ]
        |   qi::uint_                     [  qi::_val =   qi::_1  ]
        ;
Yaroslav
  • 57
  • 1
  • 8
  • Can you explain that? – sehe May 21 '18 at 20:16
  • Sure, the main things are precedence and ambiguity. So, if parser will find num token, it should descent to a hexOrBinNum token (which has the higher precedence) and then to a final term. For more info look flex and bison book (Ambiguity grammar, p.14) – Yaroslav May 22 '18 at 23:01
  • 2
    I meant to improve your answer. As you'll note if you followed the links, I do know how this works. However, if you want to make thie Q&A useful to anyone (other than you), you should probably explain it in your answer. We're not talking about Flex/Bison. In Spirit's parser expressions, the reason is not precedence nor ambiguity. The reason is [PEG parsers](https://www.boost.org/doc/libs/1_67_0/libs/spirit/doc/html/spirit/abstracts/parsing_expression_grammar.html). – sehe May 22 '18 at 23:13