summaryrefslogtreecommitdiff
path: root/lib/elixir/src/elixir_import.erl
blob: 171a7cb87a84a88034dcd8dda366d7f8cbec2bb5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
%% Module responsible for handling imports and conflicts
%% between local functions and imports.
%% For imports dispatch, please check elixir_dispatch.
-module(elixir_import).
-export([import/4, special_form/2, format_error/1]).
-include("elixir.hrl").

import(Meta, Ref, Opts, E) ->
  {Functions, Macros, Added} =
    case keyfind(only, Opts) of
      {only, functions} ->
        {Added1, Funs} = import_functions(Meta, Ref, Opts, E),
        {Funs, keydelete(Ref, ?key(E, macros)), Added1};
      {only, macros} ->
        {Added2, Macs} = import_macros(true, Meta, Ref, Opts, E),
        {keydelete(Ref, ?key(E, functions)), Macs, Added2};
      {only, sigils} ->
        {Added1, Funs} = import_sigil_functions(Meta, Ref, Opts, E),
        {Added2, Macs} = import_sigil_macros(Meta, Ref, Opts, E),
        {Funs, Macs, Added1 or Added2};
      {only, List} when is_list(List) ->
        {Added1, Funs} = import_functions(Meta, Ref, Opts, E),
        {Added2, Macs} = import_macros(false, Meta, Ref, Opts, E),
        {Funs, Macs, Added1 or Added2};
      {only, Other} ->
        elixir_errors:file_error(Meta, E, ?MODULE, {invalid_option, only, Other});
      false ->
        {Added1, Funs} = import_functions(Meta, Ref, Opts, E),
        {Added2, Macs} = import_macros(false, Meta, Ref, Opts, E),
        {Funs, Macs, Added1 or Added2}
    end,

  elixir_env:trace({import, [{imported, Added} | Meta], Ref, Opts}, E),
  {Functions, Macros}.

import_functions(Meta, Ref, Opts, E) ->
  calculate(Meta, Ref, Opts, ?key(E, functions), ?key(E, file), fun() ->
    get_functions(Ref)
  end).

import_macros(Force, Meta, Ref, Opts, E) ->
  calculate(Meta, Ref, Opts, ?key(E, macros), ?key(E, file), fun() ->
    case fetch_macros(Ref) of
      {ok, Macros} ->
        Macros;
      error when Force ->
        elixir_errors:file_error(Meta, E, ?MODULE, {no_macros, Ref});
      error ->
        []
    end
  end).

import_sigil_functions(Meta, Ref, Opts, E) ->
  calculate(Meta, Ref, Opts, ?key(E, functions), ?key(E, file), fun() ->
    filter_sigils(get_functions(Ref))
  end).

import_sigil_macros(Meta, Ref, Opts, E) ->
  calculate(Meta, Ref, Opts, ?key(E, macros), ?key(E, file), fun() ->
    case fetch_macros(Ref) of
      {ok, Macros} ->
        filter_sigils(Macros);
      error ->
        []
    end
  end).

filter_sigils(Key) ->
  lists:filter(fun({Atom, _}) ->
    case atom_to_list(Atom) of
      "sigil_" ++ [L] when L >= $a, L =< $z; L >= $A, L =< $Z -> true;
      _ -> false
    end
  end, Key).

%% Calculates the imports based on only and except

calculate(Meta, Key, Opts, Old, File, Existing) ->
  New = case keyfind(only, Opts) of
    {only, DupOnly} when is_list(DupOnly) ->
      ensure_keyword_list(Meta, File, DupOnly, only),
      Only = ensure_no_duplicates(Meta, File, DupOnly, only),

      case keyfind(except, Opts) of
        false -> ok;
        _ -> elixir_errors:file_error(Meta, File, ?MODULE, only_and_except_given)
      end,

      [elixir_errors:file_warn(Meta, File, ?MODULE, {invalid_import, {Key, Name, Arity}}) ||
       {Name, Arity} <- Only -- get_exports(Key)],

      intersection(Only, Existing());

    _ ->
      case keyfind(except, Opts) of
        false ->
          remove_underscored(Existing());

        {except, DupExcept} when is_list(DupExcept) ->
          ensure_keyword_list(Meta, File, DupExcept, except),
          Except = ensure_no_duplicates(Meta, File, DupExcept, except),
          %% We are not checking existence of exports listed in :except option
          %% on purpose: to support backwards compatible code.
          %% For example, "import String, except: [trim: 1]"
          %% should work across all Elixir versions.
          case keyfind(Key, Old) of
            false -> remove_underscored(Existing()) -- Except;
            {Key, OldImports} -> OldImports -- Except
          end;

        {except, Other} ->
          elixir_errors:file_error(Meta, File, ?MODULE, {invalid_option, except, Other})
      end
  end,

  %% Normalize the data before storing it
  case ordsets:from_list(New) of
    [] ->
      {false, keydelete(Key, Old)};
    Set  ->
      ensure_no_special_form_conflict(Meta, File, Key, Set),
      {true, [{Key, Set} | keydelete(Key, Old)]}
  end.

%% Retrieve functions and macros from modules

get_exports(Module) ->
  get_functions(Module) ++ get_macros(Module).

get_functions(Module) ->
  try
    Module:'__info__'(functions)
  catch
    error:undef -> remove_internals(Module:module_info(exports))
  end.

get_macros(Module) ->
  case fetch_macros(Module) of
    {ok, Macros} ->
      Macros;
    error ->
      []
  end.

fetch_macros(Module) ->
  try
    {ok, Module:'__info__'(macros)}
  catch
    error:undef -> error
  end.

%% VALIDATION HELPERS

ensure_no_special_form_conflict(Meta, File, Key, [{Name, Arity} | T]) ->
  case special_form(Name, Arity) of
    true  ->
      elixir_errors:file_error(Meta, File, ?MODULE, {special_form_conflict, {Key, Name, Arity}});
    false ->
      ensure_no_special_form_conflict(Meta, File, Key, T)
  end;

ensure_no_special_form_conflict(_Meta, _File, _Key, []) -> ok.

ensure_keyword_list(_Meta, _File, [], _Kind) -> ok;

ensure_keyword_list(Meta, File, [{Key, Value} | Rest], Kind) when is_atom(Key), is_integer(Value) ->
  ensure_keyword_list(Meta, File, Rest, Kind);

ensure_keyword_list(Meta, File, _Other, Kind) ->
  elixir_errors:file_error(Meta, File, ?MODULE, {invalid_option, Kind}).

ensure_no_duplicates(Meta, File, Option, Kind) ->
  lists:foldl(fun({Name, Arity}, Acc) ->
    case lists:member({Name, Arity}, Acc) of
      true ->
        elixir_errors:file_warn(Meta, File, ?MODULE, {duplicated_import, {Kind, Name, Arity}}),
        Acc;
      false ->
        [{Name, Arity} | Acc]
    end
  end, [], Option).

%% ERROR HANDLING

format_error(only_and_except_given) ->
  ":only and :except can only be given together to import "
  "when :only is :functions, :macros, or :sigils";

format_error({duplicated_import, {Option, Name, Arity}}) ->
  io_lib:format("invalid :~s option for import, ~ts/~B is duplicated", [Option, Name, Arity]);

format_error({invalid_import, {Receiver, Name, Arity}}) ->
  io_lib:format("cannot import ~ts.~ts/~B because it is undefined or private",
    [elixir_aliases:inspect(Receiver), Name, Arity]);

format_error({invalid_option, Option}) ->
  Message = "invalid :~s option for import, expected a keyword list with integer values",
  io_lib:format(Message, [Option]);

format_error({invalid_option, only, Value}) ->
  Message = "invalid :only option for import, expected value to be an atom :functions, :macros"
  ", or a list literal, got: ~s",
  io_lib:format(Message, ['Elixir.Macro':to_string(Value)]);

format_error({invalid_option, except, Value}) ->
  Message = "invalid :except option for import, expected value to be a list literal, got: ~s",
  io_lib:format(Message, ['Elixir.Macro':to_string(Value)]);

format_error({special_form_conflict, {Receiver, Name, Arity}}) ->
  io_lib:format("cannot import ~ts.~ts/~B because it conflicts with Elixir special forms",
    [elixir_aliases:inspect(Receiver), Name, Arity]);

format_error({no_macros, Module}) ->
  io_lib:format("could not load macros from module ~ts", [elixir_aliases:inspect(Module)]).

%% LIST HELPERS

keyfind(Key, List) ->
  lists:keyfind(Key, 1, List).

keydelete(Key, List) ->
  lists:keydelete(Key, 1, List).

intersection([H | T], All) ->
  case lists:member(H, All) of
    true  -> [H | intersection(T, All)];
    false -> intersection(T, All)
  end;

intersection([], _All) -> [].

%% Internal funs that are never imported, and the like

remove_underscored(List) ->
  lists:filter(fun({Name, _}) ->
    case atom_to_list(Name) of
      "_" ++ _ -> false;
      _ -> true
    end
  end, List).

remove_internals(Set) ->
  Set -- [{behaviour_info, 1}, {module_info, 1}, {module_info, 0}].

%% Special forms

special_form('&', 1) -> true;
special_form('^', 1) -> true;
special_form('=', 2) -> true;
special_form('%', 2) -> true;
special_form('|', 2) -> true;
special_form('.', 2) -> true;
special_form('::', 2) -> true;
special_form('__block__', _) -> true;
special_form('->', _) -> true;
special_form('<<>>', _) -> true;
special_form('{}', _) -> true;
special_form('%{}', _) -> true;
special_form('alias', 1) -> true;
special_form('alias', 2) -> true;
special_form('require', 1) -> true;
special_form('require', 2) -> true;
special_form('import', 1) -> true;
special_form('import', 2) -> true;
special_form('__ENV__', 0) -> true;
special_form('__CALLER__', 0) -> true;
special_form('__STACKTRACE__', 0) -> true;
special_form('__MODULE__', 0) -> true;
special_form('__DIR__', 0) -> true;
special_form('__aliases__', _) -> true;
special_form('quote', 1) -> true;
special_form('quote', 2) -> true;
special_form('unquote', 1) -> true;
special_form('unquote_splicing', 1) -> true;
special_form('fn', _) -> true;
special_form('super', _) -> true;
special_form('for', _) -> true;
special_form('with', _) -> true;
special_form('cond', 1) -> true;
special_form('case', 2) -> true;
special_form('try', 1) -> true;
special_form('receive', 1) -> true;
special_form(_, _) -> false.