Search code examples
return-typecrystal-lang

Is it possible to get the inferred return type of a method call to be used in a macro?


If the return type of a method is not stated, is it still possible to get the inferred return type to be used in a macro?

class Record
  def explicit : String
     "name"
  end
  def inferred
    ["a", "b"]
  end
end
# The following works:
puts {{Record.methods.find { |m| m.name.id == "explicit".id }.return_type }}

# The following does not (because .return_type
# is useful when the method explicitly states the return type):
puts {{Record.methods.find { |m| m.name.id == "inferred".id }.return_type }}

Solution

  • No, macros run before any type inference is done and it's impossible to access inferred types from macros. This is because macros have to be fully expanded before the type checker can correctly infer return types.