Skip to content

Commit

Permalink
Improve illegal pattern error for accidental map associations
Browse files Browse the repository at this point in the history
Given a module such as this:

    -module(test).
    -export([pattern/1]).

    pattern(#{foo => bar}) -> ok.

We presently report an error as:

    test.erl:4:15: illegal pattern
    %    4| pattern(#{foo => bar}) -> ok.
    %     |               ^

Since we have information in `erl_lint` on the bad pattern being a map
field update, we can be a bit more helpful by extending the error with a
hint instructing the user that `:=` is most likely wanted instead:

    test.erl:4:15: illegal pattern, did you mean to use `:=`?
    %    4| pattern(#{foo => bar}) -> ok.
    %     |               ^
  • Loading branch information
jchristgit committed May 25, 2024
1 parent 79bc823 commit 22e7e15
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 3 deletions.
3 changes: 2 additions & 1 deletion lib/stdlib/src/erl_lint.erl
Original file line number Diff line number Diff line change
Expand Up @@ -394,6 +394,7 @@ format_error_1({too_many_arguments,Arity}) ->
format_error_1(update_literal) ->
~"expression updates a literal";
%% --- patterns and guards ---
format_error_1(illegal_map_assoc_in_pattern) -> ~"illegal pattern, did you mean to use `:=`?";
format_error_1(illegal_pattern) -> ~"illegal pattern";
format_error_1(illegal_map_key) -> ~"illegal map key in pattern";
format_error_1(illegal_expr) -> ~"illegal expression";
Expand Down Expand Up @@ -2047,7 +2048,7 @@ is_pattern_expr_1(_Other) -> false.

pattern_map(Ps, Vt0, Old, St0) ->
foldl(fun({map_field_assoc,A,_,_}, {Psvt,Psnew,St1}) ->
{Psvt,Psnew,add_error(A, illegal_pattern, St1)};
{Psvt,Psnew,add_error(A, illegal_map_assoc_in_pattern, St1)};
({map_field_exact,_A,K,V}, {Psvt,Psnew,St1}) ->
St2 = St1#lint{gexpr_context=map_key},
{Kvt, St3} = gexpr(K, Vt0, St2),
Expand Down
4 changes: 2 additions & 2 deletions lib/stdlib/test/erl_lint_SUITE.erl
Original file line number Diff line number Diff line change
Expand Up @@ -4070,7 +4070,7 @@ maps(Config) ->
{{4,24},erl_lint,illegal_map_construction},
{{8,36},erl_lint,illegal_map_construction}],
[{{5,20},erl_lint,update_literal}]}},
{illegal_pattern,
{illegal_map_assoc_in_pattern,
<<"t(#{ a := A,
c => d,
e := F,
Expand All @@ -4082,7 +4082,7 @@ maps(Config) ->
{A,F}.
">>,
[],
{errors,[{{2,22},erl_lint,illegal_pattern},
{errors,[{{2,22},erl_lint,illegal_map_assoc_in_pattern},
{{7,28},erl_lint,illegal_pattern}],
[]}},
{error_in_illegal_map_construction,
Expand Down

0 comments on commit 22e7e15

Please sign in to comment.