rrrene / credo

A static code analysis tool for the Elixir language with a focus on code consistency and teaching.
http://credo-ci.org/
MIT License
4.91k stars 415 forks source link

`Credo.Check.Warning.UnsafeToAtom` warning on compile time created atom #1148

Open Wigny opened 2 weeks ago

Wigny commented 2 weeks ago

Environment

What were you trying to do?

Running the Credo.Check.Warning.UnsafeToAtom check (mix credo -c Credo.Check.Warning.UnsafeToAtom) is reporting right now issues for dynamically created atoms passed to unquote().

Expected outcome

AFAIK dynamically created atoms passed to unquote() are generated in compile time and thus should not be reported by this check, given they cannot be exploited in runtime. Thus the following code should not emit the check warning:

defmodule Test do
  for n <- 1..4 do
    def unquote(:"fun_#{n}")(), do: unquote(n)
  end
end

Actual outcome

Running the check on the code above returns

Prefer :erlang.binary_to_existing_atom/2 over :erlang.binary_to_atom/2 to avoid creating atoms at runtime.
Wigny commented 2 weeks ago

Rewriting the code to the following avoids the warning, but I'm unsure if that is the right solution.

defmodule Test do
  for n <- 1..4 do
    def unquote(:erlang.binary_to_atom("fun_#{n}"))(), do: unquote(n)
  end
end