D issues are now tracked on GitHub. This Bugzilla instance remains as a read-only archive.
Issue 14107 - compiler shouldn't allow to compare unions without custom opEquals
Summary: compiler shouldn't allow to compare unions without custom opEquals
Status: NEW
Alias: None
Product: D
Classification: Unclassified
Component: dmd (show other issues)
Version: D2
Hardware: All All
: P4 enhancement
Assignee: No Owner
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2015-02-02 01:19 UTC by Martin Nowak
Modified: 2024-12-13 18:39 UTC (History)
2 users (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this issue.
Description Martin Nowak 2015-02-02 01:19:33 UTC
I almost spend 2 days to track down a bug in Higgs that could have been easily catched by the compiler (see bug 13952).

It just shouldn't be possible to compare unions. Right now this compares the memory representation, but this is almost always a bug, because a union might only be partially initialized or the assigned fields might differ.

cat > bug.d << CODE
union Foo
{
    ubyte sm;
    uint bg;
}

void main()
{
    Foo a, b;
    a.bg = 12121212;
    b.bg = 13131313;
    a.sm = 2;
    b.sm = 2;
    assert(a == b); // shouldn't be allowed
}
CODE
dmd -run bug
Comment 1 Marco Leise 2015-03-22 13:30:39 UTC
Assuming that you were expecting someone to come up with a counter case, in your case it is an either-or sort of structure and after assigning to sm, bg is invalid. Disallowing comparisons all-together means that any struct using unions needs to have its own opEquals that checks which part of the union is 'active' in each instance and compares them if needed.

There are other uses of unions such as:

union Color
{
  uint c;
  struct { ubyte r, g, b, a; }
  ubyte[4] arr;
}

where different representations of the same data are offered and a comparison of the memory representation is correct.
Having to write a comparison function for every struct that uses a color can become a chore.
Comment 2 Marco Leise 2016-02-10 04:24:29 UTC
I think when I wrote the above I wasn't aware that unions can have toString(). Can they also offer a custom opEquals() ? That would be more convenient for cases like the color example or float/int "reinterpret cast" named unions which can perform the comparison themselves instead of the one in Higgs that is anonymously embedded in a struct with a tag.
Comment 3 dlangBugzillaToGithub 2024-12-13 18:39:48 UTC
THIS ISSUE HAS BEEN MOVED TO GITHUB

https://github.com/dlang/dmd/issues/17695

DO NOT COMMENT HERE ANYMORE, NOBODY WILL SEE IT, THIS ISSUE HAS BEEN MOVED TO GITHUB