www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - commutative Keyword

This bug inspired me a little bit:
http://d.puremagic.com/issues/show_bug.cgi?id=124

Actually the operator overloading is somewhat lack of important semantic.

Commutative operators work differently from the non-commutative operators.
consider OPER is a non-commutative operator.

operand2 = operand1 OPER operand2

there's a chance of optimizing as in the  
http://www.digitalmars.com/pnews/read.php?server=news.digitalmars.com&group=digitalmars.D&artnum=35949

The main idea is provide OPER_r overloading.

so operand2 = operand2.OPER_r(operand1)

Let's review OPER_r and OPER , actually they are quite close.
consider the plain function calling(the class object get pushed):

typeof(this) OPER(this, operand1)

and OPER_r can actually be

typeof(this) OPER(operand1, this)

so the binary form of OPER_r could actually be deduced from OPER  
impelmenation

We don't need to implement OPER_r explicitly now. And with commutative  
keyword
we have something like:

commutative opAdd(int operand)  {}
opSub(int operand){}

when compiler meet the expression

X = A - ((B*C)+D) * E;

it evaluates it with the first priority in this expression.

X = A - ((B*C)+D) * E; would get A evaluated first, then

T2 = ((B*C)+D)*E  // since - is non commutative, so we need T2 to store the
		  // *EXPRESSION* result
		  // so compiler optimizes it to :
		  // X = T2.opSubAssign_r (A)

to evaluate T2
T3 = ((B*C)+D) evaluated , and then
E

to evaluate T3
(B*C) evaluated , and then
D

then
B
then
C

The optimization as we can see is not complicated.
Compiler could optimize it from top to buttom.

OPTIMIZATION RULE:
Once find an operator is non commutative, the compiler optimizes it to the  
operator_r calling form.








-- 
使用 Opera 革命性的电子邮件客户程序: http://www.opera.com/mail/
Jun 27 2007