Skip to content

Commit f45f794

Browse files
committed
Move loading tokens to file utils module
1 parent 7b9cc49 commit f45f794

File tree

3 files changed

+21
-18
lines changed

3 files changed

+21
-18
lines changed

lib/gradient/ast_specifier.ex

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -64,16 +64,8 @@ defmodule Gradient.AstSpecifier do
6464
"""
6565
@spec specify(nonempty_list(:erl_parse.abstract_form())) :: [:erl_parse.abstract_form()]
6666
def specify(forms) do
67-
with {:attribute, line, :file, {path, _}} <- hd(forms),
68-
path <- to_string(path),
69-
{:ok, code} <- File.read(path),
70-
{:ok, tokens} <- :elixir.string_to_tokens(String.to_charlist(code), line, line, path, []) do
71-
run_mappers(forms, tokens)
72-
else
73-
error ->
74-
IO.puts("Error occurred when specifying forms : #{inspect(error)}")
75-
forms
76-
end
67+
tokens = Gradient.ElixirFileUtils.load_tokens(forms)
68+
run_mappers(forms, tokens)
7769
end
7870

7971
@doc """

lib/gradient/elixir_file_utils.ex

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ defmodule Gradient.ElixirFileUtils do
33
Module used to load beam files generated from Elixir.
44
"""
55

6+
alias Gradient.Types
7+
68
@type path() :: :file.filename() | String.t()
79

810
@type abstract_forms() :: [:erl_parse.abstract_form() | :erl_parse.form_info()]
@@ -39,4 +41,18 @@ defmodule Gradient.ElixirFileUtils do
3941
{:forms_error, reason}
4042
end
4143
end
44+
45+
@spec load_tokens([:erl_parse.abstract_form()]) :: Types.tokens()
46+
def load_tokens(forms) do
47+
with [{:attribute, _, :file, {path, _}} | _] <- forms,
48+
path <- to_string(path),
49+
{:ok, code} <- File.read(path),
50+
{:ok, tokens} <- :elixir.string_to_tokens(String.to_charlist(code), 1, 1, path, []) do
51+
tokens
52+
else
53+
error ->
54+
IO.puts("Cannot load tokens: #{inspect(error)}")
55+
[]
56+
end
57+
end
4258
end

test/support/helpers.ex

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,18 +8,13 @@ defmodule Gradient.TestHelpers do
88
beam_file = String.to_charlist(@examples_path <> beam_file)
99
ex_file = @examples_path <> ex_file
1010

11-
code =
12-
File.read!(ex_file)
13-
|> String.to_charlist()
14-
15-
{:ok, tokens} =
16-
code
17-
|> :elixir.string_to_tokens(1, 1, ex_file, [])
18-
1911
{:ok, {_, [abstract_code: {:raw_abstract_v1, ast}]}} =
2012
:beam_lib.chunks(beam_file, [:abstract_code])
2113

2214
ast = replace_file_path(ast, ex_file)
15+
16+
[_ | _] = tokens = Gradient.ElixirFileUtils.load_tokens(ast)
17+
2318
{tokens, ast}
2419
end
2520

0 commit comments

Comments
 (0)