Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unary And Binary Minus in Parse Tree

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

like image 796
Dfranc3373 Avatar asked May 11 '12 18:05

Dfranc3373


1 Answers

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
like image 172
TemplateRex Avatar answered Nov 05 '22 14:11

TemplateRex