RelationalAI-oss / Rematch.jl

Pattern matching
Other
52 stars 6 forks source link

Rematch should error if you define two identical match clauses #29

Open ghost opened 4 years ago

ghost commented 4 years ago

This definition should raise an error because there are two identical match clauses and the second one is unreachable:

julia> function foo(x)
       @match x begin
       Rational{Int}(num, den) => begin print("one"); 1 end
       Rational{Int}(num, den) => begin print("two"); 2 end
       end
       end
foo (generic function with 1 method)
julia> foo(3//4)
one1

In fact, maybe we should consider erroring in general if there are unreachable clauses? For example, in this definition, the second clause is unreachable because the first clause matches everything, which should also probably raise an error:

julia> @match 2//3 begin
           _ => 1
           Rational{Int}(x,y) => 2
       end
1
nystrom commented 4 years ago

This is doable, but with the way @match currently works, there will be a big performance penalty because we have to test all the patterns. This penalty could be reduced by changing the implementation to use type dispatch when possible and statically testing for overlapping patterns (which is infeasible if there are where clauses).

I think we should consider introducing different macros for the different semantics: @match_first (currently @match) runs the first matching case and @match_one matches exactly one case, reporting an error if more than one match.

ghost commented 4 years ago

That's a great idea, @nystrom.

I gave up on my effort to rewrite Rematch to use dispatch (in the hopes it would prove more performant, per the problems we saw when upgrading to 1.5), because i realized that it was just way too hard when allowing for full pattern matching.

I imagine it would be easier to implement with @match_one semantics, though still hard.

nystrom commented 4 years ago

I'll give it a try when I have some more time. Can you submit a separate issue? Do you have a branch with your attempt?