Elixir: The variable usage checker claims that a variable is left unused

Created on 30 Jul 2020  路  7Comments  路  Source: elixir-lang/elixir

Environment

  • Elixir 1.10.3 (compiled with Erlang/OTP 21) through asdf, and the project requires ~> 1.6.
  • Operating system: Fedora 32

Current behavior

With such a code (source):

expected_senderinfo = %SenderInfo{nick: "other_user", host: "host", user: "user"}
assert_receive {:received, "message", expected_senderinfo}, 10              

I get this message:

warning: variable "expected_senderinfo" is unused (if the variable is not meant to be used, prefix it with an underscore)
  test/client_test.exs:80: ExIRC.ClientTest."test receiving private message sends event to handler"/1

Expected behavior

I would have expected that since the variable is used right after its declaration, the compiler would not raise a warning saying it is not used. Is there a coding pattern that I missed?

Most helpful comment

Ah so it stems from that! :) Dzi臋ki!

All 7 comments

the warning is legit, the expected_senderinfo binding on the second line is unused. You probably meant to ensure the received message has the same info in which case you need to pin it:

-assert_receive {:received, "message", expected_senderinfo}, 10
+assert_receive {:received, "message", ^expected_senderinfo}, 10

Ah so it stems from that! :) Dzi臋ki!

While it is in an example in the docs, Should we stress the use of the pin operator?

  You can also match against specific patterns:
      assert_receive {:hello, _}

      x = 5
      assert_receive {:count, ^x} # Note the use of the pin operator (^)

Or maybe not as a comment,

How about detecting the not pinned variable and changing the error message to "Did you forget to use pin operator?"

@lukaszsamson pretty hard to do that since the macro does not have visibility about the code that will come after the macro invocation that may potentially use the variable (or not).

To be clear, this is valid:

assert_receive {:hello, msg}
assert msg == :world

So we cannot simply warn on all unpinned variables.

Sure, I meant suspicious code like

msg == :world
assert_receive {:hello, msg}
Was this page helpful?
0 / 5 - 0 ratings

Related issues

lukaszsamson picture lukaszsamson  路  3Comments

whitepaperclip picture whitepaperclip  路  3Comments

shadowfacts picture shadowfacts  路  3Comments

LucianaMarques picture LucianaMarques  路  3Comments

eproxus picture eproxus  路  3Comments