D issues are now tracked on GitHub. This Bugzilla instance remains as a read-only archive.
Issue 4958 - Floating point enums should check for total loss of precision
Summary: Floating point enums should check for total loss of precision
Status: RESOLVED FIXED
Alias: None
Product: D
Classification: Unclassified
Component: dmd (show other issues)
Version: D2
Hardware: All All
: P2 minor
Assignee: yebblies
URL:
Keywords: accepts-invalid, pull
Depends on:
Blocks:
 
Reported: 2010-09-30 00:22 UTC by Don
Modified: 2012-04-20 10:15 UTC (History)
3 users (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this issue.
Description Don 2010-09-30 00:22:51 UTC
This is a minor issue, but it has worried me ever since floating-point enums were introduced. This code compiles on 2.049:

enum FloatEnum : float { A = float.max/2, B, C }

// but this assert fails!
static assert(FloatEnum.A != FloatEnum.B);

It's an obscure trap, but it's easy to fix.
-----------------

PATCH: enum.c, EnumDeclaration::semantic(), line 234.

            // Now set e to (elast + 1)
            e = new AddExp(em->loc, elast, new IntegerExp(em->loc, 1, Type::tint32));
            e = e->semantic(sce);
            e = e->castTo(sce, elast->type);
            e = e->optimize(WANTvalue | WANTinterpret);

+            // Check that e != elast (not always true for floats)
+            Expression *etest = new EqualExp(TOKequal, em->loc, e, elast);
+            etest = etest->semantic(sce);
+            etest = etest->optimize(WANTvalue | WANTinterpret);
+            if (etest->toInteger())
+                error("enum member %s has inexact value, due to loss of precision", em->toChars());

        }
        elast = e;
        em->value = e;
Comment 2 github-bugzilla 2012-02-24 19:09:23 UTC
Commit pushed to master at https://github.com/D-Programming-Language/dmd

https://github.com/D-Programming-Language/dmd/commit/f9c2d24e198c03194af4cc837f7bbb4488972b8e
Merge pull request #671 from yebblies/issue4958

Issue 4958 - Floating point enums should check for total loss of precision
Comment 3 SomeDude 2012-04-20 09:50:01 UTC
2.059 Win32

PS E:\DigitalMars\dmd2\samples> rdmd -w --main bug.d
bug.d(3): Error: enum bug.FloatEnum enum member B has inexact value, due to loss of precision
bug.d(3): Error: enum bug.FloatEnum enum member C has inexact value, due to loss of precision
PS E:\DigitalMars\dmd2\samples>