Skip to content

Inline protocol implementations #802

Closed
@josevalim

Description

@josevalim

Today, a protocol definition and implementation happens as follow:

defprotocol Binary.Chars do
  def to_binary(thing)
end

defimpl Binary.Chars, for: BitString do
  def to_binary(thing) when is_binary(thing) do
    thing
  end
end

When one calls:

Binary.Chars.to_binary "hello"

It is then dispatched to:

Binary.Chars.BitString.to_binary "hello"

I want to allow the following construct as well:

defprotocol Binary.Chars do
  def to_binary(thing)

  defimpl for: BitString do
    def to_binary(thing) when is_binary(thing) do
      thing
    end
  end
end

The example above will inline the to_binary implementation with the protocol one, giving the following advantages:

  1. We skip a remote call for the inlined implementations
  2. We avoid generating .beam for a module

However:

  1. It means a Binary.Chars.BitString is no longer available, so we lose the property that every protocol implementation contains a module representing it (since in this case the implementation is inlined)

If we are proceeding with this task, we should:

  • Provide the inlining implementation
  • Set @moduledoc false for all defimpl for default types
  • Update exdoc to include @only and @except values on protocol pages
  • Deprecate __impl_for__ reflection from protocols (which I don't believe is used)

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions