Skip to content

Commit

Permalink
Catch error case when prewalk fails to replace ast
Browse files Browse the repository at this point in the history
  • Loading branch information
NJichev committed Feb 22, 2024
1 parent 3f764b3 commit 5392a7d
Showing 1 changed file with 10 additions and 7 deletions.
17 changes: 10 additions & 7 deletions lib/next_ls/commands/to_pipe.ex
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,8 @@ defmodule NextLS.Commands.ToPipe do
defp to_pipe_edit(text, position) do
with {:ok, ast} <- code_to_ast(text),
{:ok, first_argument_ast} <- get_function_or_argument_to_pipe(ast, position),
{edit, range} = get_edit(ast, first_argument_ast),
{:ok, new_ast} <- extract_to_pipe(ast, first_argument_ast),
{edit, range} = get_edit(new_ast),
{:ok, indent} = EditHelpers.get_indent(text, range.start.line),
edit <- EditHelpers.add_indent_to_edit(edit, indent) do
{:ok, %TextEdit{new_text: edit, range: range}}
Expand All @@ -56,11 +57,9 @@ defmodule NextLS.Commands.ToPipe do
|> Spitfire.parse()
end

defp get_edit(ast, first_argument) do
new_ast = extract_to_pipe(ast, first_argument)
defp get_edit(new_ast) do
{pipe, open, args = [_arg1, {_, context, _}]} = new_ast
ast = {pipe, [], args}
edit = Macro.to_string(ast)
edit = Macro.to_string({pipe, [], args})

open = if open[:line], do: open, else: context
closing = context[:closing] || context[:end_of_expression] || context[:end]
Expand All @@ -75,7 +74,7 @@ defmodule NextLS.Commands.ToPipe do

@conditionals [:if, :case, :unless]
defp extract_to_pipe(ast, {call, context, _args} = arg_ast) do
{_changed_ast, {new_ast, true}} =
{_changed_ast, {new_ast, changed}} =
Macro.prewalk(ast, {_new_ast = nil, _changed = false}, fn
{^call, ^context, [first | rest]}, {_, false} ->
new_ast = {:|>, context, [first, {call, context, rest}]}
Expand All @@ -102,7 +101,11 @@ defmodule NextLS.Commands.ToPipe do
{ast, acc}
end)

new_ast
if changed do
{:ok, new_ast}
else
{:error, "could not change the ast"}
end
end

@elixir_macros [:def, :defmodule, :__aliases__]
Expand Down

0 comments on commit 5392a7d

Please sign in to comment.