Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix remove producing invalid AST for do/else/rescue/catch/after #143

Merged
merged 1 commit into from
May 31, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions lib/sourceror/identifier.ex
Original file line number Diff line number Diff line change
Expand Up @@ -287,6 +287,32 @@ defmodule Sourceror.Identifier do
defguard is_atomic_literal(quoted)
when __is_atomic_literal__(quoted) or __is_atomic_literal_block__(quoted)

@doc """
Checks if the given quoted form is a reserved block name.

## Examples

iex> is_reserved_block_name(:do)
true

iex> is_reserved_block_name(:else)
true

iex> is_reserved_block_name(:catch)
true

iex> is_reserved_block_name(:after)
true

iex> is_reserved_block_name(:rescue)
true

iex> is_reserved_block_name(:foo)
false
"""
@spec is_reserved_block_name(Macro.t()) :: Macro.t()
defguard is_reserved_block_name(name) when name in [:do, :else, :catch, :after, :rescue]

@doc """
Checks if the given atom is a valid module alias.

Expand Down
14 changes: 13 additions & 1 deletion lib/sourceror/zipper.ex
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ defmodule Sourceror.Zipper do
"""

import Kernel, except: [node: 1]
import Sourceror.Identifier, only: [is_reserved_block_name: 1]

alias Sourceror.Zipper, as: Z

Expand Down Expand Up @@ -197,8 +198,19 @@ defmodule Sourceror.Zipper do
def remove(%Z{path: nil}),
do: raise(ArgumentError, message: "Cannot remove the top level node.")

def remove(%Z{path: path}) do
def remove(%Z{path: path} = zipper) do
case path.left do
[{:__block__, meta, [name]} = left | rest] when is_reserved_block_name(name) ->
if meta[:format] == :keyword do
left
|> new(%{path | left: rest})
|> do_prev()
else
zipper
|> replace({:__block__, meta, []})
|> up()
end

[left | rest] ->
left
|> new(%{path | left: rest})
Expand Down
Loading