Skip to content

Commit

Permalink
Fix for map literal
Browse files Browse the repository at this point in the history
  • Loading branch information
bcardarella committed May 23, 2024
1 parent cb6aab0 commit 65086fa
Showing 1 changed file with 33 additions and 2 deletions.
35 changes: 33 additions & 2 deletions lib/sourceror.ex
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,11 @@ defmodule Sourceror do
with pre 1.13 Elixir versions.
"""
defmacro string_to_quoted!(string, opts) do
quote bind_quoted: [code_module: @code_module, string: string, opts: opts] do
map_literal_fix? = Version.match?(System.version(), "< 1.17.0")

quote bind_quoted: [code_module: @code_module, string: string, opts: opts, map_literal_fix?: map_literal_fix?] do
code_module.string_to_quoted_with_comments!(string, opts)
|> Sourceror.map_literal_fix(map_literal_fix?)
end
end

Expand All @@ -55,11 +58,39 @@ defmodule Sourceror do
with pre 1.13 Elixir versions.
"""
defmacro string_to_quoted(string, opts) do
quote bind_quoted: [code_module: @code_module, string: string, opts: opts] do
map_literal_fix? = Version.match?(System.version(), "< 1.17.0")

quote bind_quoted: [code_module: @code_module, string: string, opts: opts, map_literal_fix?: map_literal_fix?] do
code_module.string_to_quoted_with_comments(string, opts)
|> Sourceror.map_literal_fix(map_literal_fix?)
end
end

@doc false
def map_literal_fix(result, false),
do: result

def map_literal_fix({:error, reason}, _),
do: {:error, reason}

def map_literal_fix({:ok, quoted, comments}, true) do
{quoted, comments} = map_literal_fix({quoted, comments}, true)
{:ok, quoted, comments}
end

def map_literal_fix({quoted, comments}, true) do
quoted = Macro.postwalk(quoted, fn
{:%{}, meta, args} ->
column = meta[:column]
meta = Keyword.replace(meta, :column, column - 1)

{:%{}, meta, args}
quoted -> quoted
end)

{quoted, comments}
end

@doc """
A wrapper around `Code.quoted_to_algebra/2` for compatibility with pre 1.13
Elixir versions.
Expand Down

0 comments on commit 65086fa

Please sign in to comment.