From 5392a7d26a25d62bdfca6d4fe3aeb5c6f310cbee Mon Sep 17 00:00:00 2001 From: Nikola Jichev Date: Thu, 22 Feb 2024 20:35:38 +0200 Subject: [PATCH] Catch error case when prewalk fails to replace ast --- lib/next_ls/commands/to_pipe.ex | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/lib/next_ls/commands/to_pipe.ex b/lib/next_ls/commands/to_pipe.ex index 63160825..e21f0ac1 100644 --- a/lib/next_ls/commands/to_pipe.ex +++ b/lib/next_ls/commands/to_pipe.ex @@ -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}} @@ -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] @@ -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}]} @@ -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__]