Distinguish variable from call of 0-arity function

Summary

How can I distinguish whether given AST is a variable or a call of 0-arity function in AST?

Example

I want to have macro is_variable which will print true when given AST is a variable, otherwise false

defmodule X do
  def private_function(), do: 1

  def f(variable) do
    is_variable(variable) # prints true
    is_variable(private_function) # prints false
  end
end

PS

I took a look into lib/elixir/src/elixir_expand.erl (in elixir’s source code) but I haven’t found the way to distinguish variable from call without raising a warning

defmacro is_var({name, _, Elixir}) do
  Macro.Env.has_var?(__CALLER__, name)
end

Should do what you want. But you need to test it as I have written it late night, on mobile, from memory, so it may require some small polishing.

2 Likes