[Mono-bugs] [Bug 676727] New: New Rule - Check Enums for overlapping values

bugzilla_noreply at novell.com bugzilla_noreply at novell.com
Thu Mar 3 11:29:16 EST 2011



           Summary: New Rule - Check Enums for overlapping values
    Classification: Mono
           Product: Mono: Tools
           Version: 2.10.x
          Platform: All
        OS/Version: All
            Status: NEW
          Severity: Enhancement
          Priority: P5 - None
         Component: Gendarme
        AssignedTo: mono-bugs at lists.ximian.com
        ReportedBy: ethan_j_brown at hotmail.com
         QAContact: mono-bugs at lists.ximian.com
          Found By: ---
           Blocker: ---

User-Agent:       Mozilla/5.0 (Windows; Windows NT 6.1) AppleWebKit/534.23
(KHTML, like Gecko) Chrome/11.0.686.1 Safari/534.23

Consider an enum where the intent is to capture a set of non-overlapping
values, where there are more than 32 different values in the enum.  The enum
would be need to be made into a long like so:

public enum BigEnum : long

The most concise way of setting up unique values would be to use the standard
bit-shifting approach

public enum BigEnum : long
One = 1
Two = 1 << 1,
Three = 1 << 2,

However, in this scenario, as soon as you reached 1 << 33, there would be a
subtle bug.

1 << 33 wraps past the boundary of a 32-bit integer, and now the values in the
enum start to overlap.

The subtle bug above is that the values should be setup like:

1L << 33,
1L << 34


Of course, if the number of enum values exceeds 65, you run into the same
scenario when you hit 1L << 65

This was an actual bug in production code that I caught.  Because the
bit-shifting was being performed on a 32-bit int and rolling over, the enum was
full of duplicate values and all sorts of weird things were happening.

While it is perfectly legal to overlap the values of enums, I can't think of
any real cases where thats useful (perhaps only when an enum has been renamed
and the old one obsoleted with
http://msdn.microsoft.com/en-us/library/system.obsoleteattribute.aspx ?)

In any event... maybe there are two rule suggestions here?

- Don't allow enum values to overlap unless [Obsolete] is used on all but one
of the overlapping values.  
- Don't allow values to be bit-shifted beyond their allowable size

For your consideration... one of these rules would have definitely caught a bug
in my case.  (Unit tests were able to flush out the bug by the way.)

Reproducible: Always

Steps to Reproduce:

You are the QA contact for the bug.
You are the assignee for the bug.

More information about the mono-bugs mailing list