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

Raise error if impossible default case is reached. #11361

Open
MortimerSnerd opened this issue May 31, 2019 · 1 comment
Open

Raise error if impossible default case is reached. #11361

MortimerSnerd opened this issue May 31, 2019 · 1 comment

Comments

@MortimerSnerd
Copy link

Summary

In the code generated by a compiler for an exhaustive case statement,
it would be helpful for debugging if a default case was emitted that just raises
something like newException(Defect, "Impossible case value").

Description

As an example:

   type
      Kinds = enum
         kThis, kThat
   
   proc doSomething(k: Kinds) = 
      case k
      of kThis:
          echo "this"
      of kThat:
        echo "that"

For the C++ backend, it generates a switch statement with a case
with two branches, one for each enum value. Normally, this is sufficient,
because k can't take on an invalid value - attempts to cast an out of range int
to Kinds will just raise an exception.

This can be a problem if you're working with pointers though. For example,
if the function was:

proc doSomething(k: ptr Kinds) = 
   case k[]
   of ...

Since the memory pointed to by k[] can be initialized outside of the safety constraints of the language, k[] can be out of range of the enum, and no branch of the switch
will be taken. What I'd like for this case is for the switch to have a default branch that
just raises a Defect exception saying something like "Invalid value for case".

Of course this came up because I had a pointer to an incorrectly initialized block of
memory. It took me quite a few rounds of echo debugging to figure out that none of
the branches of my case statement were being executed, and why.

@cooldome
Copy link
Member

cooldome commented May 31, 2019

This would be a noticeable overhead in the release mode, but could be useful in debug mode.
Likely it is not the case that needs extra default clause, but enum value checks instead.

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

3 participants