Skip to content

Commit

Permalink
Warn on unused shadowed aliases (#13550)
Browse files Browse the repository at this point in the history
  • Loading branch information
sabiwara committed May 10, 2024
1 parent 203baf3 commit d1b3063
Show file tree
Hide file tree
Showing 4 changed files with 38 additions and 3 deletions.
15 changes: 14 additions & 1 deletion lib/elixir/lib/kernel/lexical_tracker.ex
Expand Up @@ -123,7 +123,14 @@ defmodule Kernel.LexicalTracker do

@doc false
def handle_call(:unused_aliases, _from, state) do
{:reply, Enum.sort(state.aliases), state}
unused_aliases =
Enum.map(state.aliases, fn
{{:shadowed, module}, meta} -> {module, meta}
{module, meta} when is_atom(module) -> {module, meta}
end)
|> Enum.sort()

{:reply, unused_aliases, state}
end

def handle_call(:unused_imports, _from, state) do
Expand Down Expand Up @@ -220,6 +227,12 @@ defmodule Kernel.LexicalTracker do

def handle_cast({:add_alias, module, meta, warn}, state) do
if warn do
state =
case state do
%{aliases: %{^module => meta}} -> put_in(state.aliases[{:shadowed, module}], meta)
_ -> state
end

{:noreply, put_in(state.aliases[module], meta)}
else
{:noreply, state}
Expand Down
4 changes: 2 additions & 2 deletions lib/elixir/lib/macro/env.ex
Expand Up @@ -447,7 +447,7 @@ defmodule Macro.Env do
## Examples
iex> alias List, as: MyList
iex> alias List, as: MyList, warn: false
iex> Macro.Env.expand_alias(__ENV__, [], [:MyList])
{:alias, List}
iex> Macro.Env.expand_alias(__ENV__, [], [:MyList, :Nested])
Expand All @@ -456,7 +456,7 @@ defmodule Macro.Env do
If there is no alias or the alias starts with `Elixir.`
(which disables aliasing), then `:error` is returned:
iex> alias List, as: MyList
iex> alias List, as: MyList, warn: false
iex> Macro.Env.expand_alias(__ENV__, [], [:Elixir, MyList])
:error
iex> Macro.Env.expand_alias(__ENV__, [], [:AnotherList])
Expand Down
6 changes: 6 additions & 0 deletions lib/elixir/test/elixir/kernel/alias_test.exs
Expand Up @@ -34,6 +34,12 @@ defmodule Kernel.AliasTest do
assert Billing == :"Elixir.MyApp.Billing"
end

test "overriding parent alias with child alias" do
alias MyApp.Billing
alias Billing.Billing
assert Billing == :"Elixir.MyApp.Billing.Billing"
end

test "lexical" do
if true_fun() do
alias OMG, as: List, warn: false
Expand Down
16 changes: 16 additions & 0 deletions lib/elixir/test/elixir/kernel/warning_test.exs
Expand Up @@ -894,6 +894,22 @@ defmodule Kernel.WarningTest do
purge(Sample)
end

test "unused alias due to shadowing" do
assert_warn_compile(
["nofile:2:3", "unused alias Baz"],
"""
defmodule Sample do
alias Foo.Baz
alias Bar.Baz
def baz, do: Baz
end
"""
)
after
purge(Sample)
end

test "unused inside dynamic module" do
import List, only: [flatten: 1], warn: false

Expand Down

0 comments on commit d1b3063

Please sign in to comment.