Skip to content
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

Map start position #137

Merged
merged 2 commits into from
May 24, 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
45 changes: 43 additions & 2 deletions lib/sourceror.ex
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,16 @@ 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 +63,44 @@ 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} ->
{:%{}, Keyword.replace(meta, :column, meta[:column] - 1), 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
3 changes: 3 additions & 0 deletions test/sourceror_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -532,6 +532,9 @@ defmodule SourcerorTest do

quoted = Sourceror.parse_string!("foo(:bar)")
assert Sourceror.get_start_position(quoted) == [line: 1, column: 1]

quoted = Sourceror.parse_string!("%{a: 1}")
assert Sourceror.get_start_position(quoted) == [line: 1, column: 1]
end
end

Expand Down
Loading