简体   繁体   中英

Elixir compiler warning on ignored function return values

Is there a way to get a warning—either from the elixirc compiler, Credo, or some other linting tool—when I unintentionally ignore the return value of a function?

That is, I'd like a warning in this sample where it ignores the result of increment_state() :

defmodule CountingServer do
  use GenServer

  def init(_) do
    :timer.send_interval(1000, :tick)
    {:ok, 1}
  end

  def handle_info(:tick, count_state) do
    IO.puts count_state
    increment_state(count_state)
    {:noreply, count_state}
  end

  def increment_state(prev_count) do
    prev_count + 1
  end
end

In the above example, we "intended" to return the incremented state from the handle_info/2 call, rather than the "old" state; that is, we intended for the server to print 1, 2, 3, ... instead of printing 1 repeatedly.

If the sample code had intentionally ignored the result of the increment_state/1 call (assigning it to _ , for instance), no warning would have been necessary.

I've looked through the Credo configuration options and couldn't find anything that seems to fit the bill...

I went ahead and madea Credo check based off Credo's default UnusedOperation and UnusedFunctionReturnHelper .

Those checks almost support what I want to do as-is, but they require essentially a "blacklist" to say exactly which functions' return values must not be ignored; I just had to invert the logic to support warning on any function not present in a whitelist ( Logger.info , Enum.each , etc.).

The check supports adding additional (presumably project-specific) functions to the whitelist via the .credo.exs config.

See the first comment for instructions on using it in your own project. (TL;DR: Drop the file in your project, add it to both the requires and checks lists in your .credo.exs .)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM