I've figured out how to implement binary operators with precedence, like this (pseudocode):
method plus
times()
while(consume(plus_t)) do
times()
end
end
method times
number()
while(consume(times_t))
number()
end
end
// plus() is the root operation
// omitted: number() consumes a number token
So when I parse 4 + 5 * 6
it would:
- plus
- multiply
- number (4 consumed)
- plus_t consumed
- multiply
- number (5 consumed)
- times_t consumed
- number (6 consumed)
- multiply
However, when I try adding a minus
method (prefix minusing like -4
, not infix minusing like 4 - 5
):
method minus
consume(minus_t)
plus()
end
It takes a very low precedence, so -4 + 5
becomes -(4 + 5)
rather than (-4) + 5
and this is undesirable.
What can I do to make a high precedence unary operator?