Skip to content

Conversation

@josevalim
Copy link
Member

@josevalim josevalim commented Dec 26, 2024

We now type check arguments given to a protocol. The following code:

defmodule HelloWorld do
  def example() do
    to_string(1..3)
  end
end

emits this warning:

Screenshot 2024-12-26 at 13 07 41

We specially handle string interpolations to provide a better experience. So if we replace to_string(1..3) by "#{1..3}", we will this warning instead:

Screenshot 2024-12-26 at 13 07 49

TODO

  • Unit tests of protocol consolidation with and without fallback
  • Unit tests of protocol consolidation without implementations
  • Integration tests of interpolation
  • Integration tests of protocol dispatch
  • Improve warnings for mismatched implementations

#{hint()} string interpolation in Elixir uses the String.Chars protocol to \
convert a data structure into a string. Either convert the data type into a \
string upfront or implement the protocol accordingly
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we suggest for which type to implement this?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unfortunately no, because there may be an infinite amount of them. If someone has a type of not Range.t, it can be any other struct, which wouldn't be valid in String.Chars (and some structs definitely do not implemnt String.Chars , but we also cannot list them).

{{:., _, [mod, fun]}, meta, args} -> erl_to_ex(mod, fun, args, meta)
other -> other
{:%, _, [Range, {:%{}, _, fields}]} = node ->
case :lists.usort(fields) do
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would maps:from_list/1 here make this code easier to read, so that we don't need to do the mental math to check that the fields below are ordered? 😬

@josevalim josevalim merged commit c1c2cf8 into main Dec 27, 2024
18 checks passed
@josevalim josevalim deleted the jv-type-check-protocols branch December 27, 2024 18:40
@josevalim josevalim changed the title Type check protocol dispatch Type checking of protocol dispatch Dec 27, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

5 participants