MLStyle.jl
MLStyle.jl copied to clipboard
Error for unused cases
In this example, one of the cases is a typo and always matches. I would like to get a an error for this.
using MLStyle
using MLStyle.AbstractPatterns: literal
MLStyle.is_enum(::T) where {T<:Enum} = true
MLStyle.pattern_uncall(e::T, _, _, _, _) where {T<:Enum} = literal(e)
@enum COLOR Red Green Blue Yellow
julia> @match Green begin
red => 1
Green => 2
Blue => 3
Yellow => 4
end
1
OCaml gives a warning.
type colour = Red | Green | Blue | Yellow;;
match Green with
| red -> 1
| Green -> 2 (* Warning : this match case is unused. *)
| Blue -> 3 (* Warning : this match case is unused. *)
| Yellow -> 4;; (* Warning : this match case is unused. *)
(* 1 *)
Our compiler does know this information, however, for a more complex case, the checker can do nothing(I mean, we cannot complete this feature in MLStyle, so I decided not to support an incomplete one):
@data S begin
S1(Int)
S2(String)
end
@match xxx begin
S1(a) => ...
S2(b) => ...
end
In a statically typed language, this will be do-able, but never for dynamic ones: open types and unknown incoming code make the analysis impossible. In MLStyle, it is hard for the compiler to know the behaviour of pattern deconstruction(we can at most understand the scope of generated code), so checking nested cases is impossible.
I found this paper "Lower your guards" which seems interesting. It describes a number of fancy matching rules and says
coverage checking for guards is undecidable in general. However, while we cannot accurately check all uses of guards, we can at least give decent warnings for some common cases.
I wonder what can be done in type-stable Julia, or even JET.jl's analysis framework.