Skip to content

Commit 9b9e308

Browse files
committed
Merge comments into the AST
1 parent f3e8ceb commit 9b9e308

File tree

4 files changed

+1802
-6
lines changed

4 files changed

+1802
-6
lines changed

lib/elixir/lib/code.ex

Lines changed: 41 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1036,12 +1036,13 @@ defmodule Code do
10361036
[
10371037
unescape: false,
10381038
literal_encoder: &{:ok, {:__block__, &2, [&1]}},
1039+
include_comments: true,
10391040
token_metadata: true,
10401041
emit_warnings: false
10411042
] ++ opts
10421043

1043-
{forms, comments} = string_to_quoted_with_comments!(string, to_quoted_opts)
1044-
to_algebra_opts = [comments: comments] ++ opts
1044+
forms = string_to_quoted!(string, to_quoted_opts)
1045+
to_algebra_opts = opts
10451046
doc = Code.Formatter.to_algebra(forms, to_algebra_opts)
10461047
Inspect.Algebra.format(doc, line_length)
10471048
end
@@ -1254,11 +1255,22 @@ defmodule Code do
12541255
file = Keyword.get(opts, :file, "nofile")
12551256
line = Keyword.get(opts, :line, 1)
12561257
column = Keyword.get(opts, :column, 1)
1258+
include_comments = Keyword.get(opts, :include_comments, false)
12571259

1258-
case :elixir.string_to_tokens(to_charlist(string), line, column, file, opts) do
1259-
{:ok, tokens} ->
1260-
:elixir.tokens_to_quoted(tokens, file, opts)
1260+
Process.put(:code_formatter_comments, [])
1261+
opts = [preserve_comments: &preserve_comments/5] ++ opts
12611262

1263+
with {:ok, tokens} <- :elixir.string_to_tokens(to_charlist(string), line, column, file, opts),
1264+
{:ok, quoted} <- :elixir.tokens_to_quoted(tokens, file, opts) do
1265+
if include_comments do
1266+
quoted = Code.Normalizer.normalize(quoted)
1267+
quoted = Code.Comments.merge_comments(quoted, Process.get(:code_formatter_comments))
1268+
1269+
{:ok, quoted}
1270+
else
1271+
{:ok, quoted}
1272+
end
1273+
else
12621274
{:error, _error_msg} = error ->
12631275
error
12641276
end
@@ -1280,7 +1292,30 @@ defmodule Code do
12801292
file = Keyword.get(opts, :file, "nofile")
12811293
line = Keyword.get(opts, :line, 1)
12821294
column = Keyword.get(opts, :column, 1)
1283-
:elixir.string_to_quoted!(to_charlist(string), line, column, file, opts)
1295+
include_comments = Keyword.get(opts, :include_comments, false)
1296+
1297+
Process.put(:code_formatter_comments, [])
1298+
1299+
opts =
1300+
if include_comments do
1301+
[preserve_comments: &preserve_comments/5,
1302+
literal_encoder: &{:ok, {:__block__, &2, [&1]}},
1303+
token_metadata: true,
1304+
unescape: false,
1305+
columns: true,
1306+
] ++ opts
1307+
else
1308+
opts
1309+
end
1310+
1311+
quoted = :elixir.string_to_quoted!(to_charlist(string), line, column, file, opts)
1312+
1313+
if include_comments do
1314+
# quoted = Code.Normalizer.normalize(quoted)
1315+
Code.Comments.merge_comments(quoted, Process.get(:code_formatter_comments))
1316+
else
1317+
quoted
1318+
end
12841319
end
12851320

12861321
@doc """

0 commit comments

Comments
 (0)