Bug 5682 – Silently wrong CTFE result possibly related to operator overloading and expression order
Status
RESOLVED
Resolution
FIXED
Severity
critical
Priority
P2
Component
dmd
Product
D
Version
D2
Platform
Other
OS
Mac OS X
Creation time
2011-03-02T12:50:00Z
Last change time
2011-05-18T21:19:56Z
Keywords
wrong-code
Assigned to
nobody
Creator
code
Comments
Comment #0 by code — 2011-03-02T12:50:58Z
The test function below will produce different results depending on whether it is executed normally or via CTFE with latest DMD (git master at a47637b0):
---
import std.stdio;
struct A {
int n;
auto opBinary(string op : "*")(A rhs) {
return A(n * rhs.n);
}
}
A foo(A[] lhs, A[] rhs) {
A current;
for (size_t k = 0; k < rhs.length; ++k) {
current = lhs[k] * rhs[k]; // This is the crucial line.
}
return current;
}
auto test() {
return foo([A(1), A(2)], [A(3), A(4)]);
}
void main() {
enum tc = test();
writefln("compile-time: %s; run-time: %s", tc.n, test().n);
}
---
compile-time: 4; run-time: 8
---
A few observations:
- At compile-time, the first element from the first factor (lhs[0]) seems to be read twice, replacing A(2) with another value doesn't change the CTFE result.
- Swapping lhs[k] and rhs[k] will change the CTFE result to 6 (supporting the above assumption).
- If foo() is modified to work on e.g. int instead of A values, the problem doesn't occur.
- If the assignment in question is replaced with »A a1 = lhs[k]; A a2 = rhs[k]; current = a1 * a2;«, the bug does not longer occur.