7

I am creating a parse tree that will contain expressions similar to

3 - 4 * 8

or

8 * -5

or

-(10 * 1)

I need a way to distinguish between the unary and binary minus. The way my grammar is going now the binary minus is reached first, but I am thinking of changing that and adding a flag variable that holds the last variable.

Ex: if it is 5 - 6

The flag is holding 5 and if it sees minus and the flag is a number the skip unary and go to binary.

However I am not sure exactly how to implement this in C++

Any help would be greatly appreciated.

Thanks

2
  • 1
    Do you mean a way to distinguish them as you're doing the parsing, or a way to distinguish them in the parse tree? In the parse tree, it's trivial -- just have separate UNARY_MINUS and BINARY_MINUS operators. If you mean as you're parsing, a unary minus occurs when you're expecting an operand, not an operator. May 11, 2012 at 18:09
  • In my parser I would like it to distinguish between a -5 and 4 -5. My next part converts the leafs of this Tree to as AST tree (which is working) but my parser sees everything as a binary minus (4 - 5).
    – Dfranc3373
    May 11, 2012 at 18:16

1 Answer 1

8

The easiest way to implement a parser is by the method of Recursive Descent. Make sure to give binary minus a higher priority than unary minus, like in the referenced site:

 E -->  | E "+" E
        | E "-" E
        | "-" E
        | E "*" E
        | E "/" E
        | E "^" E
        | "(" E ")"
        | v
3
  • After looking at the site I may re write my grammar rules to follow those of the site, but one problem with that is that this parser must also be able to handle = , < , <=, >, >=, and, or, not
    – Dfranc3373
    May 11, 2012 at 18:33
  • @Dfranc3373 see en.cppreference.com/w/cpp/language/operator_precedence for the complete operator precedence for C++ May 11, 2012 at 18:39
  • 1
    @Dfranc3373 Great! BTW, did you already read the FAQ stackoverflow.com/faq#howtoask on how to score answers? You have accepted an answer to every question that you asked, which is great, but you can also score any answer that you find useful. May 11, 2012 at 18:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.