-
Notifications
You must be signed in to change notification settings - Fork 414
/
match_in_condition.ex
121 lines (98 loc) · 3.01 KB
/
match_in_condition.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
defmodule Credo.Check.Refactor.MatchInCondition do
use Credo.Check,
explanations: [
check: """
Pattern matching should only ever be used for simple assignments
inside `if` and `unless` clauses.
While this fine:
# okay, simple wildcard assignment:
if contents = File.read!("foo.txt") do
do_something()
end
the following should be avoided, since it mixes a pattern match with a
condition and do/else blocks.
# considered too "complex":
if {:ok, contents} = File.read("foo.txt") do
do_something()
end
# also considered "complex":
if allowed? && ( contents = File.read!("foo.txt") ) do
do_something()
end
If you want to match for something and execute another block otherwise,
consider using a `case` statement:
case File.read("foo.txt") do
{:ok, contents} ->
do_something()
_ ->
do_something_else()
end
"""
]
@condition_ops [:if, :unless]
@doc false
@impl true
def run(%SourceFile{} = source_file, params) do
issue_meta = IssueMeta.for(source_file, params)
Credo.Code.prewalk(source_file, &traverse(&1, &2, issue_meta))
end
# Skip if arguments is not enumerable
defp traverse({_op, _meta, nil} = ast, issues, _source_file) do
{ast, issues}
end
# TODO: consider for experimental check front-loader (ast)
# NOTE: we have to exclude the cases matching the above
for op <- @condition_ops do
defp traverse({unquote(op), _meta, arguments} = ast, issues, issue_meta) do
# remove do/else blocks
condition_arguments = Enum.reject(arguments, &Keyword.keyword?/1)
new_issues =
Credo.Code.prewalk(
condition_arguments,
&traverse_condition(
&1,
&2,
unquote(op),
condition_arguments,
issue_meta
)
)
{ast, issues ++ new_issues}
end
end
defp traverse(ast, issues, _source_file) do
{ast, issues}
end
defp traverse_condition(
{:=, meta, arguments} = ast,
issues,
op,
op_arguments,
issue_meta
) do
case arguments do
[{atom, _, nil}, _right] when is_atom(atom) ->
# this means that the current ast is part of the `if/unless`
if Enum.member?(op_arguments, ast) do
{ast, issues}
else
new_issue = issue_for(op, meta[:line], "=", issue_meta)
{ast, issues ++ [new_issue]}
end
_ ->
new_issue = issue_for(op, meta[:line], "=", issue_meta)
{ast, issues ++ [new_issue]}
end
end
defp traverse_condition(ast, issues, _op, _op_arguments, _issue_meta) do
{ast, issues}
end
defp issue_for(op, line_no, trigger, issue_meta) do
format_issue(
issue_meta,
message: "There should be no matches in `#{op}` conditions.",
trigger: trigger,
line_no: line_no
)
end
end