Introduce Macro.Env.fetch_aliased_as/2 and improve Macro.Env.fetch_alias/2

35 views
Skip to first unread message

Zach Allaun

unread,
Apr 1, 2023, 11:38:47 AM4/1/23
to elixir-lang-core
Context

Since Elixir 1.13, Macro.Env.fetch_alias/2 has existed as a mechanism to resolve an alias to its fully-qualified name. This has the limitation, however, that you cannot use the actual alias in the lookup.

iex> alias Foo.Bar, as: Baz
iex> Macro.Env.fetch_alias(__ENV__, :Baz)
{:ok, Foo.Bar}
iex> Macro.Env.fetch_alias(__ENV__, Baz)
:error

There is not a mechanism to go the other way without relying on the private aliases field in a Macro.Env struct.

Proposal

Introduce a new function, Macro.Env.fetch_aliased_as/2, that is able to look up the name that a module is aliased as. Additionally, extend the behavior of both Macro.Env.fetch_aliased_as/2 and Macro.Env.fetch_alias/2 to accept qualified atoms.

iex> alias Foo.Bar, as: Baz
Baz

iex> Macro.Env.fetch_alias(__ENV__, :Baz)
{:ok, Foo.Bar}
iex> Macro.Env.fetch_alias(__ENV__, Baz)
{:ok, Foo.Bar}
iex> Macro.Env.fetch_alias(__ENV__, :Unknown)
:error

iex> Macro.Env.fetch_aliased_as(__ENV__, :"Foo.Bar")
{:ok, Baz}
iex> Macro.Env.fetch_aliased_as(__ENV__, Foo.Bar}
{:ok, Baz}
iex> Macro.Env.fetch_aliased_as(__ENV__, Foo.Unknown)
:error

I'll submit a PR shortly for this change, but am happy to wait for any discussion that might happen here before it's acted on.

Zach Allaun

unread,
Apr 1, 2023, 11:48:32 AM4/1/23
to elixir-lang-core
Upon reflection, the change that I'm proposing to Macro.Env.fetch_alias/2 does not make sense. If you have Baz, then it already evaluates to Foo.Bar.

Please ignore that portion of the proposal. :)

José Valim

unread,
Apr 1, 2023, 12:00:36 PM4/1/23
to elixir-l...@googlegroups.com
Hi Zach, thanks for the proposal! A PR for "fetch_alias_as" is welcome, we even use private APIs in Kino.VegaLite and friends which we could stop using if this function existed. :)

--
You received this message because you are subscribed to the Google Groups "elixir-lang-core" group.
To unsubscribe from this group and stop receiving emails from it, send an email to elixir-lang-co...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/elixir-lang-core/d7bce667-b568-4bfa-a0a4-d03ac24b9eben%40googlegroups.com.
Reply all
Reply to author
Forward
Message has been deleted
0 new messages