Skip to content

Commit

Permalink
Fix remove producing invalid AST for do/else/rescue/catch/after (#143)
Browse files Browse the repository at this point in the history
  • Loading branch information
doorgan authored May 31, 2024
1 parent ce5c368 commit 6c34a57
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
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

0 comments on commit 6c34a57

Please sign in to comment.