thautwarm/MLStyle.jl

Disallow capturing pattern with same name as variant

Opened this issue · 2 comments

Consider:

julia> using MLStyle

julia> @data Foo begin
           C1
           C2(Int)
       end

julia> @match C1 begin
           C2 => 1
           _ => 2
       end
1

I was pretty surprised to see this. Turns out I needed to do:

julia> @match C1 begin
           C2(s) => 1
           _ => 2
       end
2

instead, but it's an easy mistake to make.
Would it be possible to statically throw an error if you define a capturing pattern with the same name as a variant (in this case C2?)

C1 should be recognised as a pattern if C1 is an MLStyle enum from the global scope.

This is because C1 is not an enum, so locally shadowing C2 is allowed.

See MLStyle.is_enum at here.

I'd admit this gives unexpected results in some cases, and MLStyle used to reject such symbols.

It could be possible for us to add a per-module option to check such cases for you, like

using MLStyle
@MLStyle.add_checker global_name_shadowing, ...

However, it might not become default. Tradionally, match is similar to let, and performs name shadowing.

struct C2 end
let C2 = ...
     # do some with C2
end