Relative precedence of postfix and infix operators

46 views
Skip to first unread message

Eugen Labun

unread,
Oct 21, 2011, 1:59:42 PM10/21/11
to scala-language
Hi All,

The SLS states: "Postfix operators always have lower precedence than infix operators. E.g.
e1 op1 e2 op2 is always equivalent to (e1 op1 e2) op2."

Why this has been choosen? Other programming languages[2], math expressions, EBNF expressions, and
intuition (at least, to me) treat postfix operators as having the highest precedence, even before
prefix operators.


Consider:

math: a + b!
a + b! + c

-x�
-y!

EBNF: x ~ y* (~ instead of comma/space to be Scala-like)
x ~ y? ~ z


--
Thanks,
Eugen


[1] The Scala Language Specification Version 2.9
DRAFT May 24, 2011
http://www.scala-lang.org/docu/files/ScalaReference.pdf
6.12.3 Infix Operations
p. 85

[2] Operators in C and C++ # Operator precedence
http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Operator_precedence
(postfix operators are called "suffix" there)

Eugen Labun

unread,
Oct 25, 2011, 7:39:48 PM10/25/11
to scala-l...@googlegroups.com
OK, after some reading and thinking I see the reasons: it's hard to do other (but imo, more proper) way!

Given that operands, infix operators, and postfix operators can be arbitrary identifiers, it's
impossible for the Scala parser (that tries to be context-free) to distinguish between. Imagine the
chain: ID ID ID ID ID ID ... That is what the parser essentially sees, I guess.

<sidenote:
A similar problem with *prefix* operators is handled in the way that all prefix operators' symbols
are predefined: +, -, ~, !. The parser treats these symbols at the beginning of an expression
*always* as unary prefix operators, independently of the real presence of corresponding methods
"unary_x" (what can lead to errors, see my another post).
/>

If the parser could know somehow, whether the names(IDs) in question are defined as infix or postfix
operators! (I.e. as methods with or without parameters)

This info is definitely here at some phase of compiling ("namer"?). Perhaps the exact treatment of
expression chains could be postponed to that phase? Or rather vice versa, that phase could be
combined with the parser phase?

It would be great to see, what you think about, guys.

--
Best,
Eugen

Reply all
Reply to author
Forward
0 new messages