jGuru Forums

Unary Minus
2 posts in topic
Flat View
TOPIC ACTIONS:

Posted By:   Quirin_Meyer
Posted On:   Tuesday, November 11, 2003 05:09 AM

how do i realize a *real* unary minus i have a problem with unary minus. i use standart grammatics for arithmetic expressions found all over the place, but they all seem to have the same problem (or i guess, i only have) - they are not parsing unary operators correctly here the grammar: primary_expr : constant | (LPAREN! expr RPAREN! ) ; sign_expr : (MINUS)? primary_expr ; mul_expr : sign_expr (( STAR^ | DIV^) sign_expr)* ; expr : mul_expr (( PLUS^ | MINUS^) mul_expr)* ; constant : NUMBER ; -2+3 is a correct expression according to those grammars but   More>>

how do i realize a *real* unary minus

i have a problem with unary minus. i use standart grammatics for arithmetic expressions found all over the place, but they all seem to have the same problem (or i guess, i only have) - they are not parsing unary operators correctly

here the grammar:

```
primary_expr

:  constant

|

(LPAREN! expr RPAREN! )

;

sign_expr

: (MINUS)? primary_expr

;

mul_expr

: sign_expr (( STAR^ | DIV^) sign_expr)*

;

expr

: mul_expr (( PLUS^ | MINUS^) mul_expr)*

;

constant

: NUMBER

;

```

-2+3

is a correct expression according to those grammars but
-2+-3
is one as well but doesn't make much sense, even to a second grader ;-) and even worse: this word (-2+-3) gets accepted and produces
(+ (-2) (-3))
(in lisp notation)

could anyone possible help me to change that grammar so that expressions such as the above do not get accepted by the parser.

thanks a lot.

q    <<Less

Re[2]: Unary Minus

Posted By:   Quirin_Meyer
Posted On:   Sunday, November 16, 2003 08:52 AM

thanks a lot..
that looks almost too good. but i miss the sign_expr production..

q

Re: Unary Minus

Posted By:   Sebastian_Kaliszewski
Posted On:   Thursday, November 13, 2003 12:29 PM

The following
`primary_expr  :  constant     |   (LPAREN! expr RPAREN! )   ;mul_expr  : sign_expr (( STAR^ | DIV^) sign_expr)*  ;expr  : (MINUS^)? mul_expr (( PLUS^ | MINUS^) mul_expr)*  ;constant  : NUMBER  ;`

does the job, but notice that now unary minus is just a special case of binary sumation/difference operators (has the same priority) -- this is the way it's introduced at school.

Is it what you want?

rgds

Sebastian