Exhaustive Pattern-Matching

Alastair Reid alastair@reid-consulting-uk.ltd.uk
Fri, 29 Aug 2003 13:53:48 +0100


Back when I hacked on Hugs routinely, I thought of detecting uncaught cases 
including things like the following:

> f :: Color -> String
> f x = case x of
>        Red -> "r"
>        _   -> " " ++ case x of
> 	            Green -> "g"
> 	            Blue  -> "b"
>
>      Warning: Pattern match(es) are non-exhaustive
> 	     In a case alternative: Patterns not matched: Red
>
>
> "Red" in the second case is unreachable (and this should also be worth a
> warning.)

My plan for how to do it was as follows:

1) In an early phase, insert an easily identified default error case:

> f :: Color -> String
> f x = case x of
>        Red -> "r"
>        _   -> " " ++ case x of
> 	            Green -> "g"
> 	            Blue  -> "b"
>                  _ -> hugs_PMF <location info>
>        _ -> hugs_PMF <location info>

2) In later phases, delete any obviously redundant case alternatives.  
    In this example, this would restore the code to what Christian wrote.

    We could warn when deleting a human-provided case alt
    but this might be a bad idea since it would penalize
    defensive programming.

   If Hugs performed inlining, we would want to be careful not to 
   report the same missing case alt more than once but we would also
   want to allow inlining and other optimizations to have a shot at 
   detecting that a case alt is unreachable.  One of the simplest ways of
   doing this would be to keep a list of which problems have already been
   reported and not report the same problem twice.  Other ways exist.

3) Warn if any occurences of hugs_PMF remain and report any
    runtime failures that miss hugs_PMF as compiler bugs.

I never implemented this but I think it would work well.

--
Alastair Reid