D issues are now tracked on GitHub. This Bugzilla instance remains as a read-only archive.
Issue 1517 - (D1 only) .sort for structs behaves badly with ref opCmp
Summary: (D1 only) .sort for structs behaves badly with ref opCmp
Status: RESOLVED WONTFIX
Alias: None
Product: D
Classification: Unclassified
Component: dmd (show other issues)
Version: D1 (retired)
Hardware: All All
: P2 normal
Assignee: No Owner
URL:
Keywords: wrong-code
Depends on:
Blocks:
 
Reported: 2007-09-19 02:44 UTC by Bill Baxter
Modified: 2019-06-26 11:36 UTC (History)
3 users (show)

See Also:


Attachments
Simple test (1.42 KB, text/plain)
2007-09-19 02:45 UTC, Bill Baxter
Details

Note You need to log in before you can comment on or make changes to this issue.
Description Bill Baxter 2007-09-19 02:44:17 UTC
This is incorrect code according to the spec but it doesn't really make sense to me why it doesn't work.  

So the spec says:
"""
For the .sort property to work on arrays of structs or unions, the struct or union definition must define the function: int opCmp(S) or int opCmp(S*). The type S is the type of the struct or union. This function will determine the sort ordering.
"""
But I just happened to use opCmp(ref S) and it seemed to work (everything compiled fine and ran without crashing, anyway). 

But it doesn't actually work.  Sorting sorts improperly.

I think making a ref opCmp in a struct should either be made to work (i see no reason why it should not work), or it should be made a compiler error to try to create one.

Attached is a simple test.
Comment 1 Bill Baxter 2007-09-19 02:45:32 UTC
Created attachment 185 [details]
Simple test
Comment 2 bearophile_hugs 2010-03-17 20:10:47 UTC
Reduced test case, on dmd v2.041:


struct S {
    int i;

    int opCmp(S other) {
        return this.i - other.i;
    }
}

void main() {
    S[S] aa;
    foreach (int i; [1, -1, 7])
        aa[S(i)] = S(-i);

    // wrong order:
    assert(aa.keys.sort == [S(1), S(7), S(-1)]);
}


If this is a real bug (and it seems so) then I think it's serious bug, it's worse than a compiler crash, because the program runs unreliably.
Comment 3 yebblies 2014-08-31 13:52:21 UTC
I get

object.Error@(0): TypeInfo.compare is not implemented

On recent dmd (2.067 HEAD), and given that builtin .sort is going away this is WONTFIX for D2.