Search code examples
cased

Limits in switch cases in case range


I'm trying to include UTF-8 identifiers in a case switch but I get this error:

Error: had 399 cases which is more than 256 cases in case range

D code:

    switch(value)
    {
        case 'a': ..  case 'z':
        case 'A': ..  case 'Z':
        case 0xC0: .. case 0x24F:

Why did the compiler impose such a limitation? for optimazation purposes? can I overcome it?


Solution

  • Doing this as an answer to get more space.

    The limitation you see here is not in the spec http://dlang.org/statement and ONLY applies to CaseRangeStatements in the compiler: src/dmd/statement.c line 3437 in the version I have:

    if (lval - fval > 256)
    {   error("had %llu cases which is more than 256 cases in case range", lval - fval);
        lval = fval + 256;
    }
    

    As a result, a fix would be to break that range up into several pieces and put them right next to each other:

            switch(value)
    {
        case 'a': ..  case 'z':
        case 'A': ..  case 'Z':
        case 0xC0: .. case 0x14F: // this compiles
        case 0x150: .. case 0x24F: // since it is broken up
    

    Then you handle them the same way.

    The compiler source doesn't say why it has that check, but the github history says it was committed in response to this bug: https://issues.dlang.org/show_bug.cgi?id=3139

    [s]So it is an implementation detail in the compiler to avoid an infinite loop.[/s]

    EDIT: actually, the 256 check was before that, I read the patch wrong, Don added a check in addition to it. Looks like the 256 thing precedes github so I don't know why it specifically was added, but I'm still pretty confident it has to do with that loop and memory concerns, just compiler implementation details and bugs.