Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

compiler shouldn't allow to compare unions without custom opEquals #17695

Open
dlangBugzillaToGithub opened this issue Feb 2, 2015 · 2 comments

Comments

@dlangBugzillaToGithub
Copy link

Martin Nowak (@MartinNowak) reported this on 2015-02-02T01:19:33Z

Transferred from https://issues.dlang.org/show_bug.cgi?id=14107

CC List

  • Marco Leise
  • Denis Shelomovskii

Description

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
@dlangBugzillaToGithub
Copy link
Author

Marco.Leise commented on 2015-03-22T13:30:39Z

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.

@dlangBugzillaToGithub
Copy link
Author

Marco.Leise commented on 2016-02-10T04:24:29Z

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant