Skip to content

Avoid compile warnings when implementing an empty protocol #11588

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion lib/elixir/lib/protocol.ex
Original file line number Diff line number Diff line change
Expand Up @@ -764,7 +764,7 @@ defmodule Protocol do
end

# TODO: Convert the following warnings into errors in future Elixir versions
def __before_compile__(env) do
defmacro __before_compile__(env) do
# Callbacks
callback_metas = callback_metas(env.module, :callback)
callbacks = :maps.keys(callback_metas)
Expand Down Expand Up @@ -806,6 +806,16 @@ defmodule Protocol do
nil
)
end

quote do
# Register the __impl__/1 callback to ensure the protocol is a behaviour.
# Without this, a protocol that defines no functions won't be detected
# as a behaviour by the Erlang compiler, and any implementations of that
# protocol will log a warning.
@callback __impl__(:for) :: module()
@callback __impl__(:target) :: module()
@callback __impl__(:protocol) :: module()
end
end

defp after_defprotocol do
Expand Down
8 changes: 8 additions & 0 deletions lib/elixir/test/elixir/protocol_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,14 @@ defmodule ProtocolTest do
assert args == [{:type, 23, :product, [{:user_type, 23, :t, []}]}, {:type, 23, :term, []}]
end

test "protocol with no functions is a behaviour" do
defprotocol ProtoNoFunctions do
end

defimpl ProtoNoFunctions, for: Integer do
end
end

test "protocol defines functions and attributes" do
assert Sample.__protocol__(:module) == Sample
assert Sample.__protocol__(:functions) == [ok: 1]
Expand Down