Skip to content

Commit

Permalink
Aliases was confused by nested non-module blocks (#368)
Browse files Browse the repository at this point in the history
Aliases would get confused if a module had another block that didn't
define another module (like in a DSL). This was because it only popped
a single scope at a time, and if several scopes ended on the same
line, only the inner scope would be popped. Calling the pop funcion
recursively solves the issue.
  • Loading branch information
scohen authored Sep 14, 2023
1 parent 395d61c commit 94af9dd
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 2 deletions.
5 changes: 3 additions & 2 deletions apps/common/lib/lexical/ast/aliases.ex
Original file line number Diff line number Diff line change
Expand Up @@ -243,12 +243,13 @@ defmodule Lexical.Ast.Aliases do
%__MODULE__{reducer | scopes: new_scopes}
end

defp maybe_pop_scope(%__MODULE__{} = reducer, {_, metadata, _}) do
defp maybe_pop_scope(%__MODULE__{} = reducer, {_, metadata, _} = elem) do
with {:ok, current_line} <- Keyword.fetch(metadata, :line),
{:ok, current_column} <- Keyword.fetch(metadata, :column),
[current_scope | scopes] <- reducer.scopes,
true <- Scope.ended?(current_scope, {current_line, current_column}) do
current_scope.on_exit.(%__MODULE__{reducer | scopes: scopes})
popped_reducer = current_scope.on_exit.(%__MODULE__{reducer | scopes: scopes})
maybe_pop_scope(popped_reducer, elem)
else
_ ->
reducer
Expand Down
22 changes: 22 additions & 0 deletions apps/common/test/lexical/ast/aliases_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -356,6 +356,28 @@ defmodule Lexical.Ast.AliasesTest do
refute aliases[InDsl]
end

test "sibling modules with nested blocks" do
{:ok, aliases} =
~q[
defmodule First do
defstuff do
field :x
end
end
defmodule Second do
defstuff do
field :y
end
end
|
]
|> aliases_at_cursor()

assert aliases[:First] == First
assert aliases[:Second] == Second
end

# Note: it looks like Code.container_cursor_to_quoted doesn't work with
# anonymous functions
@tag :skip
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -312,6 +312,41 @@ defmodule Lexical.RemoteControl.Search.Indexer.SourceTest do

assert second.ref != first.ref
end

test "aren't nested" do
{:ok, [first, second, third, fourth], _} =
~q[
defmodule A.B.C do
defstruct do
field(:ok, :boolean)
end
end
defmodule D.E.F do
defstruct do
field(:ok, :boolean)
end
end
defmodule G.H.I do
defstruct do
field(:ok, :boolean)
end
end
defmodule J.K.L do
defstruct do
field(:ok, :boolean)
end
end
]
|> index()

assert first.subject == A.B.C
assert second.subject == D.E.F
assert third.subject == G.H.I
assert fourth.subject == J.K.L
end
end

describe "nested modules" do
Expand Down

0 comments on commit 94af9dd

Please sign in to comment.