Skip to content

Fix Code.Fragment.surround_context for keyword keys #13843

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

Merged
merged 2 commits into from
Sep 20, 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
17 changes: 15 additions & 2 deletions lib/elixir/lib/code/fragment.ex
Original file line number Diff line number Diff line change
Expand Up @@ -590,7 +590,8 @@ defmodule Code.Fragment do
| {:sigil, charlist}
| {:struct, inside_struct}
| {:unquoted_atom, charlist}
| {:keyword, charlist},
| {:keyword, charlist}
| {:key, charlist},
inside_dot:
{:alias, charlist}
| {:alias, inside_alias, charlist}
Expand Down Expand Up @@ -640,7 +641,16 @@ defmodule Code.Fragment do
maybe_operator(reversed_pre, post, line, opts)

{:identifier, reversed_post, rest} ->
{rest, _} = strip_spaces(rest, 0)
{keyword_key?, rest} =
case rest do
[?: | tail] when tail == [] or hd(tail) in @space ->
{true, rest}

_ ->
{rest, _} = strip_spaces(rest, 0)
{false, rest}
end

reversed = reversed_post ++ reversed_pre

case codepoint_cursor_context(reversed, opts) do
Expand All @@ -656,6 +666,9 @@ defmodule Code.Fragment do
{{:dot, _, [_ | _]} = dot, offset} ->
build_surround(dot, reversed, line, offset)

{{:local_or_var, acc}, offset} when keyword_key? ->
build_surround({:key, acc}, reversed, line, offset)

{{:local_or_var, acc}, offset} when hd(rest) == ?( ->
build_surround({:local_call, acc}, reversed, line, offset)

Expand Down
38 changes: 38 additions & 0 deletions lib/elixir/test/elixir/code_fragment_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -1110,6 +1110,44 @@ defmodule CodeFragmentTest do

assert CF.surround_context(":", {1, 1}) == :none
end

test "keyword keys" do
for i <- 2..4 do
assert CF.surround_context("[foo:", {1, i}) == %{
context: {:key, ~c"foo"},
begin: {1, 2},
end: {1, 5}
}
end

for i <- 10..12 do
assert CF.surround_context("[foo: 1, bar: 2]", {1, i}) == %{
context: {:key, ~c"bar"},
begin: {1, 10},
end: {1, 13}
}
end

assert CF.surround_context("if foo?, do: bar()", {1, 10}) == %{
context: {:key, ~c"do"},
begin: {1, 10},
end: {1, 12}
}
end

test "keyword false positives" do
assert CF.surround_context("<<foo::", {1, 3}) == %{
context: {:local_or_var, ~c"foo"},
begin: {1, 3},
end: {1, 6}
}

assert CF.surround_context("[foo :atom", {1, 2}) == %{
context: {:local_or_var, ~c"foo"},
begin: {1, 2},
end: {1, 5}
}
end
end

describe "container_cursor_to_quoted/2" do
Expand Down
Loading