www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.bugs - [Issue 12753] New: All enum members trait, and missing function

https://issues.dlang.org/show_bug.cgi?id=12753

          Issue ID: 12753
           Summary: All enum members trait, and missing function return
                    values
           Product: D
           Version: D2
          Hardware: All
                OS: All
            Status: NEW
          Severity: enhancement
          Priority: P1
         Component: DMD
          Assignee: nobody puremagic.com
          Reporter: bearophile_hugs eml.cc

import std.traits: EnumMembers;
enum Foo { A, B, C }
int bar1(immutable Foo x) {
    foreach (immutable pos, immutable y; EnumMembers!Foo)
        if (x == y)
            return pos;
}
int bar2(immutable Foo x) {
    foreach (immutable pos, immutable y; [EnumMembers!Foo])
        if (x == y)
            return pos;
}
void main() {}


With dmd 2.066alpha gives errors:

temp.d(3,5): Error: function temp.bar1 no return exp; or assert(0); at end of
function
temp.d(8,5): Error: function temp.bar2 no return exp; or assert(0); at end of
function


But I think the D compiler should be able to understand that a foreach on the
whole range of an enum (found with EnumMembers) covers its all possible values,
so those two functions always return a value and don't need the assert(0) at
the end.

To do this the D compiler should know that EnumMembers gives all the members of
an enum.

One way to do this is to introduce in D a built-in operation to get all members
of an enum, something like this, re-using allMembers:


int bar3(immutable Foo x) {
    foreach (immutable pos, immutable y; __traits(allMembers, Foo))
        if (x == y)
            return pos;
}


I think the Ada compiler is able to do this, accepting simple code like (the
'Range is an Ada built-in operation):


type Foo is (One, Two, Three, Four, Five);

function Test(X: Foo) return Integer is begin
   for Y in Foo'Range loop
     if X = Y then
        return Foo'Pos(Y);
     end if;
   end loop;
end Test;

--
May 16 2014