www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.bugs - [Issue 5682] New: Silently wrong CTFE result possibly related to operator overloading and expression order

reply d-bugmail puremagic.com writes:
http://d.puremagic.com/issues/show_bug.cgi?id=5682

           Summary: Silently wrong CTFE result possibly related to
                    operator overloading and expression order
           Product: D
           Version: D2
          Platform: Other
        OS/Version: Mac OS X
            Status: NEW
          Keywords: wrong-code
          Severity: critical
          Priority: P2
         Component: DMD
        AssignedTo: nobody puremagic.com
        ReportedBy: code klickverbot.at


--- Comment #0 from klickverbot <code klickverbot.at> 2011-03-02 12:50:58 PST
---
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.

-- 
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------
Mar 02 2011
parent d-bugmail puremagic.com writes:
http://d.puremagic.com/issues/show_bug.cgi?id=5682


Don <clugdbug yahoo.com.au> changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
             Status|NEW                         |RESOLVED
                 CC|                            |clugdbug yahoo.com.au
         Resolution|                            |FIXED


--- Comment #1 from Don <clugdbug yahoo.com.au> 2011-05-18 21:19:56 PDT ---
D2 fix:
https://github.com/D-Programming-Language/dmd/commit/0c8750880ad31e0715546daa68be4d69f4af88c0

D1:
https://github.com/D-Programming-Language/dmd/commit/669cafeb9fecc98d5f4689f379f638a9661f0b35

-- 
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------
May 18 2011