A curious metaprogramming-peculiarity: `:{}`

I stumbled across the following curious tidbit of how Elixir’s parser/compiler works:

defmodule Example do
  def {} do
    "Yes, this is allowed!"
  end
end
iex> Example.{}
"Yes, this is allowed!"

I cannot imagine any serious use-case for this, but it is curious.
I believe the cause is that :{} is a special atom that Elixir uses in its AST-definition to describe tuples with more than two elements.

2 Likes

:rofl: My God, I want to use this for so many bad things that I promise to never make public ever.

2 Likes

Not the same, but here’s another fun one: https://thepugautomatic.com/2015/10/how-to-expect-to-in-elixir/

2 Likes

It is impossible to import the Example module in this case, however, because that will make Elixir complain that you are attempting to override one of its special forms.

That said, it is possible to wrap any piece of Elixir AST in a macro that alters how the code that is passed to it is expanded. In this way you are able to alter even the behaviour of Elixir’s special forms.
One place where I’ve used this in the past is the Solution library, where the clauses of with and case-statements are overridden to have slightly extended support for tuples.
Another is e.g. the experiment I wrote late yesterday evening which allows bare captures to exist in pipes.


@henrik Thanks for sharing that piece of code! Tuple calls are indeed a strange historic artifact.