No CompileError for unknown struct key in Protocol when called in function

Should this raise a CompileError?

defmodule Foo do
  defstruct [foo: "fooval"]
end

defprotocol Compiler do
  def compile(_)
end

# No CompileError
defimpl Compiler, for: Foo do

  # struct key called in function
  def compile(%Foo{} = foo) do
    foo.bar
  end
end

Referencing key in function head raises compile error

# (CompileError) <path>: unknown key :bar for struct Foo
defimpl Compiler, for: Foo do
  def compile(%Foo{bar: bar} = foo) do
    bar
  end
end

The compiler doesn’t know about foo beeing an instance of %Foo{} anymore. There are no typeinformation available at compile time.

1 Like

It could be made to know, couldn’t it? Just a bit of meta-programming related to how the method is defined.

That has already been discussed on the core Mailinglist. But since I’m on mobile right now I have trouble to search the archives.

Thanks.

It turns out I had a misconception about how the compiler works. I expected the example below to compile, and it did not. So there’s nothing special about the use of a Protocol in the issue I mentioned above.

defmodule Foo do
  defstruct [:bar]
end

defmodule Bar do
  def bar(%Foo{} = foo) do
    foo.banana
  end
end