assignment: left-to-right or right-to-left evaluation?

Michiel Helvensteijn nomail at please.com
Sat May 9 11:03:24 PDT 2009


Andrei Alexandrescu wrote:

> Consider:
> 
> uint fun();
> int gun();
> ...
> int[] a = new int[5];
> a[fun] = gun;
> 
> Which should be evaluated first, fun() or gun()? It's a rather arbitrary
> decision. C/C++ don't even define an order. Python chooses
> left-to-right, EXCEPT for assignment, which is right-hand side first.
> Lisp and C# choose consistent left-to-right. I don't like exceptions and
> I'd like everything to be left-to-right. However, this leads to some odd
> cases.

I find this a very interesting issue. I've just coauthored a paper
describing three expression evaluation strategies. Their main advantage is
that they preserve operator commutativity. In other words, the evaluation
order of side-effects is independent from their textual order. No
left-to-right or right-to-left.

One of the strategies (parallel evaluation) evaluates all subexpressions in
the old program state. It maintains operator idempotence. An expression is
only legal if no two if its subexpressions make incompatible changes to the
state. This strategy requires some extra memory and runtime, at least in
its most naive implementation. It does scale extremely well to
multi-processor systems, however.

Another strategy (ordering by dependency) recognizes read/write and
write/write hazards and orders evaluation accordingly. An expression would
only be legal if its dependency graph has no cycles. This may be difficult
to verify for more complex languages, which have aliasing and such.

The third strategy (order agnostic evaluation) basically evaluates all
smallest side-effect subexpressions before all pure subexpressions (unless
the pure one is a subexpression of a side-effect one). Ordering between
side-effects is required to be semantically irrelevant. An expression that
depends on any particular ordering of side-effects is illegal. This is
non-trivial to prove at compile-time but always possible to test at
run-time. And it leaves the compiler free to choose the most efficient
evaluation order.

Our new programming language Mist will use order agnostic expression
evaluation.

-- 
Michiel Helvensteijn




More information about the Digitalmars-d mailing list