Qqwy

Qqwy

TypeCheck Core Team

The following problem came up while developing TypeCheck.
For who does not know about it, it is a library which adds runtime type-checking functionality to your existing Elixir code by using macros that take your @type and @spec annotations and turn them into snippets that run before/after your functions.

A problem however occurs when people are using it in combination with Dialyzer. (c.f. issue #85)
Here is a minimal example:

defmodule Example do
  defstruct [:age]
  @type t() :: %__MODULE__{age: integer()}

  @spec new(integer()) :: Example.t()
  def new(age) do
    %__MODULE__{age: age}
  end

  # The following code is generated by a macro:
  defoverridable new: 1

  def new(param) do
    super_result = super(param)
    maybe_error =
      if is_map(super_result) do
        {:ok, super_result}
      else
        {:error, :not_a_map}
      end
    case maybe_error do
      {:ok, _} -> super_result
      {:error, problem} -> raise "Result did not pass type check: #{problem}."
    end
  end
  # (macro-generated code ends here)
end

The “macro-generated code” here is a simplified version of the actual code that would be inserted. (In the actual code we would first check whether the result is a map (as we do right now), then check whether the result contains the proper struct key and other expected keys, and then check whether :age is an integer. But nevermind that, since the problem already occurs with this simplified snippet.)

However, in this particular case the user-written implementation of new is simple enough to be ‘trivially correct’.
But this makes Dialyzer complain about the checks which have been inserted. Specifically:

lib/dialyzer_tests.ex:0:pattern_match
The pattern can never match the type.

Pattern:
{:error, _problem}

Type:
{:ok, %Example{:age => _}}

________________________________________________________________________________
lib/dialyzer_tests.ex:0:pattern_match
The pattern can never match the type.

Pattern:
false

Type:
true

So there are one small and one big problem:

  • Small: The line numbers seem to be messed up. I have no clue why. Maybe Dialyzer/Dialyxir is partially confused by defoverridable?
  • Big: Dialyzer complains about the error parts of this code not being reachable. But this is somewhat of a ‘false positive’. It would be a proper warning if this code were to be written by hand. But since this is machine-generated code, warnings for branches that can never happen are very unhelpful. (As an aside: the BEAM compiler is clever enough to optimize them away as well in many cases.)

So this brings me to my question:

  • Is it possible to make Dialyzer happy with this kind of machine-generated code?
  • If not, is there a way to fully disable warnings for machine-generated code?

Showing Posts 1 to 3

sasajuric

sasajuric

Author of Elixir In Action

if apply(Kernel, :is_map, [super_result]) might do the job, though it would also introduce some perf overhead.

If not, is there a way to fully disable warnings for machine-generated code?

Something like @dialyzer {:nowarn_function, generated_fun: arity}.

al2o3cr

al2o3cr

You can pass generated: true to quote to get AST tagged with that option. Here’s an example from Kernel.is_struct:
https://github.com/elixir-lang/elixir/blob/33a91237f68edf91afb45700ed149e0c7d1dd379/lib/elixir/lib/kernel.ex#L2431-L2442

If you’re producing AST nodes directly, generated: true goes in the metadata (second position in the tuple):
https://github.com/elixir-lang/elixir/blob/79cd891eb86ecb7654a7acdb63769cfdd950a5c0/lib/ex_unit/lib/ex_unit/assertions.ex#L679-L681

Qqwy

Qqwy OP

TypeCheck Core Team

All code which TypeCheck generates is annotated with generated: true but this does not seem to silence Dialyzer in the slightest. Maybe I am doing something wrong of course (I’m eager to learn how to improve the code further!)

:+1: This technique seems to work. I have altered the wrapper-generating code to (a more complicated variant of):

defmodule Example do
  defstruct [:age]
  @type t() :: %__MODULE__{age: integer()}

  @spec new(integer()) :: Example.t()
  def new(age) do
    %__MODULE__{age: age}
  end

  # The following code is generated by a macro:
  defoverridable new: 1

  def new(param) do
    super_result = super(param)
    __new__type_check_return_type_wrapper__(super_result)
  end

  @compile {:inline {__new__type_check_return_type_wrapper__: 1}
  @dialyzer {:nowarn_function, {__new__type_check_return_type_wrapper__: 1}
  defp __new__type_check_return_type_wrapper__(super_result)
    maybe_error =
      if is_map(super_result) do
        {:ok, super_result}
      else
        {:error, :not_a_map}
      end
    case maybe_error do
      {:ok, _} -> super_result
      {:error, problem} -> raise "Result did not pass type check: #{problem}."
    end
  end
  # (macro-generated code ends here)
end

This way:

  • Dialyzer no longer complains about unused code inside the return type check
  • The code is still inlined into the original function by the compiler
  • If someone is messing up the return result of the original function to the point where the result is vastly different from the written @spec, Dialyzer is still able to produce a warning as it should.

Thank you very much for your help, @al2o3cr and @sasajuric !

— All posts loaded —

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
RemyXRenard
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
samoloth
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New
FlyingNoodle
If a change or preparation module uses Ash.Changeset.get_argument/2 or Ash.Query.get_argument/2 (or any of the other get_argument functio...
New

Other Trending Topics Top

JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Dmk
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews