1-module(elixir_expand).
2-export([expand/2, expand_args/2, expand_arg/2, format_error/1]).
3-import(elixir_errors, [form_error/4]).
4-include("elixir.hrl").
5
6%% =
7
8expand({'=', Meta, [Left, Right]}, E) ->
9  assert_no_guard_scope(Meta, "=", E),
10  {ERight, ER} = expand(Right, E),
11  {ELeft, EL} = elixir_clauses:match(fun expand/2, Left, ER, E),
12  refute_parallel_bitstring_match(ELeft, ERight, E, ?key(E, context) == match),
13  {{'=', Meta, [ELeft, ERight]}, EL};
14
15%% Literal operators
16
17expand({'{}', Meta, Args}, E) ->
18  {EArgs, EA} = expand_args(Args, E),
19  {{'{}', Meta, EArgs}, EA};
20
21expand({'%{}', Meta, Args}, E) ->
22  elixir_map:expand_map(Meta, Args, E);
23
24expand({'%', Meta, [Left, Right]}, E) ->
25  elixir_map:expand_struct(Meta, Left, Right, E);
26
27expand({'<<>>', Meta, Args}, E) ->
28  elixir_bitstring:expand(Meta, Args, E, false);
29
30expand({'->', Meta, _Args}, E) ->
31  form_error(Meta, E, ?MODULE, unhandled_arrow_op);
32
33%% __block__
34
35expand({'__block__', _Meta, []}, E) ->
36  {nil, E};
37expand({'__block__', _Meta, [Arg]}, E) ->
38  expand(Arg, E);
39expand({'__block__', Meta, Args}, E) when is_list(Args) ->
40  {EArgs, EA} = expand_block(Args, [], Meta, E),
41  {{'__block__', Meta, EArgs}, EA};
42
43%% __aliases__
44
45expand({'__aliases__', _, _} = Alias, E) ->
46  expand_aliases(Alias, E, true);
47
48%% alias
49
50expand({Kind, Meta, [{{'.', _, [Base, '{}']}, _, Refs} | Rest]}, E)
51    when Kind == alias; Kind == require; Kind == import ->
52  case Rest of
53    [] ->
54      expand_multi_alias_call(Kind, Meta, Base, Refs, [], E);
55    [Opts] ->
56      case lists:keymember(as, 1, Opts) of
57        true ->
58          form_error(Meta, E, ?MODULE, as_in_multi_alias_call);
59        false ->
60          expand_multi_alias_call(Kind, Meta, Base, Refs, Opts, E)
61      end
62  end;
63expand({alias, Meta, [Ref]}, E) ->
64  expand({alias, Meta, [Ref, []]}, E);
65expand({alias, Meta, [Ref, Opts]}, E) ->
66  assert_no_match_or_guard_scope(Meta, "alias", E),
67  {ERef, ER} = expand_without_aliases_report(Ref, E),
68  {EOpts, ET}  = expand_opts(Meta, alias, [as, warn], no_alias_opts(Opts), ER),
69
70  if
71    is_atom(ERef) ->
72      {ERef, expand_alias(Meta, true, ERef, EOpts, ET)};
73    true ->
74      form_error(Meta, E, ?MODULE, {expected_compile_time_module, alias, Ref})
75  end;
76
77expand({require, Meta, [Ref]}, E) ->
78  expand({require, Meta, [Ref, []]}, E);
79expand({require, Meta, [Ref, Opts]}, E) ->
80  assert_no_match_or_guard_scope(Meta, "require", E),
81
82  {ERef, ER} = expand_without_aliases_report(Ref, E),
83  {EOpts, ET}  = expand_opts(Meta, require, [as, warn], no_alias_opts(Opts), ER),
84
85  if
86    is_atom(ERef) ->
87      elixir_aliases:ensure_loaded(Meta, ERef, ET),
88      {ERef, expand_require(Meta, ERef, EOpts, ET)};
89    true ->
90      form_error(Meta, E, ?MODULE, {expected_compile_time_module, require, Ref})
91  end;
92
93expand({import, Meta, [Left]}, E) ->
94  expand({import, Meta, [Left, []]}, E);
95
96expand({import, Meta, [Ref, Opts]}, E) ->
97  assert_no_match_or_guard_scope(Meta, "import", E),
98  {ERef, ER} = expand_without_aliases_report(Ref, E),
99  {EOpts, ET}  = expand_opts(Meta, import, [only, except, warn], Opts, ER),
100
101  if
102    is_atom(ERef) ->
103      elixir_aliases:ensure_loaded(Meta, ERef, ET),
104      {Functions, Macros} = elixir_import:import(Meta, ERef, EOpts, ET),
105      {ERef, expand_require(Meta, ERef, EOpts, ET#{functions := Functions, macros := Macros})};
106    true ->
107      form_error(Meta, E, ?MODULE, {expected_compile_time_module, import, Ref})
108  end;
109
110%% Compilation environment macros
111
112expand({'__MODULE__', _, Atom}, E) when is_atom(Atom) ->
113  {?key(E, module), E};
114expand({'__DIR__', _, Atom}, E) when is_atom(Atom) ->
115  {filename:dirname(?key(E, file)), E};
116expand({'__CALLER__', Meta, Atom} = Caller, E) when is_atom(Atom) ->
117  assert_contextual_var(Meta, '__CALLER__', E, caller_not_allowed),
118  {Caller, E};
119expand({'__STACKTRACE__', Meta, Atom} = Stacktrace, E) when is_atom(Atom) ->
120  assert_contextual_var(Meta, '__STACKTRACE__', E, stacktrace_not_allowed),
121  {Stacktrace, E};
122expand({'__ENV__', Meta, Atom}, #{context := match} = E) when is_atom(Atom) ->
123  form_error(Meta, E, ?MODULE, env_not_allowed);
124expand({'__ENV__', Meta, Atom}, E) when is_atom(Atom) ->
125  {maybe_escape_map(escape_env_entries(Meta, E)), E};
126expand({{'.', DotMeta, [{'__ENV__', Meta, Atom}, Field]}, CallMeta, []}, E) when is_atom(Atom), is_atom(Field) ->
127  Env = escape_env_entries(Meta, E),
128  case maps:is_key(Field, Env) of
129    true  -> {maps:get(Field, Env), E};
130    false -> {{{'.', DotMeta, [maybe_escape_map(Env), Field]}, CallMeta, []}, E}
131  end;
132
133%% Quote
134
135expand({Unquote, Meta, [_]}, E) when Unquote == unquote; Unquote == unquote_splicing ->
136  form_error(Meta, E, ?MODULE, {unquote_outside_quote, Unquote});
137
138expand({quote, Meta, [Opts]}, E) when is_list(Opts) ->
139  case lists:keyfind(do, 1, Opts) of
140    {do, Do} ->
141      expand({quote, Meta, [lists:keydelete(do, 1, Opts), [{do, Do}]]}, E);
142    false ->
143      form_error(Meta, E, ?MODULE, {missing_option, 'quote', [do]})
144  end;
145
146expand({quote, Meta, [_]}, E) ->
147  form_error(Meta, E, ?MODULE, {invalid_args, 'quote'});
148
149expand({quote, Meta, [Opts, Do]}, E) when is_list(Do) ->
150  Exprs =
151    case lists:keyfind(do, 1, Do) of
152      {do, Expr} -> Expr;
153      false -> form_error(Meta, E, ?MODULE, {missing_option, 'quote', [do]})
154    end,
155
156  ValidOpts = [context, location, line, file, unquote, bind_quoted, generated],
157  {EOpts, ET} = expand_opts(Meta, quote, ValidOpts, Opts, E),
158
159  Context = proplists:get_value(context, EOpts, case ?key(E, module) of
160    nil -> 'Elixir';
161    Mod -> Mod
162  end),
163
164  {File, Line} = case lists:keyfind(location, 1, EOpts) of
165    {location, keep} ->
166      {elixir_utils:relative_to_cwd(?key(E, file)), false};
167    false ->
168      {proplists:get_value(file, EOpts, nil), proplists:get_value(line, EOpts, false)}
169  end,
170
171  {Binding, DefaultUnquote} = case lists:keyfind(bind_quoted, 1, EOpts) of
172    {bind_quoted, BQ} ->
173      case is_list(BQ) andalso
174            lists:all(fun({Key, _}) when is_atom(Key) -> true; (_) -> false end, BQ) of
175        true -> {BQ, false};
176        false -> form_error(Meta, E, ?MODULE, {invalid_bind_quoted_for_quote, BQ})
177      end;
178    false ->
179      {[], true}
180  end,
181
182  Unquote = proplists:get_value(unquote, EOpts, DefaultUnquote),
183  Generated = proplists:get_value(generated, EOpts, false),
184
185  {Q, Prelude} = elixir_quote:build(Meta, Line, File, Context, Unquote, Generated),
186  Quoted = elixir_quote:quote(Meta, Exprs, Binding, Q, Prelude, ET),
187  expand(Quoted, ET);
188
189expand({quote, Meta, [_, _]}, E) ->
190  form_error(Meta, E, ?MODULE, {invalid_args, 'quote'});
191
192%% Functions
193
194expand({'&', Meta, [{super, SuperMeta, Args} = Expr]}, E) when is_list(Args) ->
195  assert_no_match_or_guard_scope(Meta, "&", E),
196
197  case resolve_super(Meta, length(Args), E) of
198    {Kind, Name, _} when Kind == def; Kind == defp ->
199      expand_fn_capture(Meta, {Name, SuperMeta, Args}, E);
200    _ ->
201      expand_fn_capture(Meta, Expr, E)
202  end;
203
204expand({'&', Meta, [{'/', _, [{super, _, Context}, Arity]} = Expr]}, E) when is_atom(Context), is_integer(Arity) ->
205  assert_no_match_or_guard_scope(Meta, "&", E),
206
207  case resolve_super(Meta, Arity, E) of
208    {Kind, Name, _} when Kind == def; Kind == defp ->
209      {{'&', Meta, [{'/', [], [{Name, [], Context}, Arity]}]}, E};
210    _ ->
211      expand_fn_capture(Meta, Expr, E)
212  end;
213
214expand({'&', Meta, [Arg]}, E) ->
215  assert_no_match_or_guard_scope(Meta, "&", E),
216  expand_fn_capture(Meta, Arg, E);
217
218expand({fn, Meta, Pairs}, E) ->
219  assert_no_match_or_guard_scope(Meta, "fn", E),
220  elixir_fn:expand(Meta, Pairs, E);
221
222%% Case/Receive/Try
223
224expand({'cond', Meta, [Opts]}, E) ->
225  assert_no_match_or_guard_scope(Meta, "cond", E),
226  assert_no_underscore_clause_in_cond(Opts, E),
227  {EClauses, EC} = elixir_clauses:'cond'(Meta, Opts, E),
228  {{'cond', Meta, [EClauses]}, EC};
229
230expand({'case', Meta, [Expr, Options]}, E) ->
231  assert_no_match_or_guard_scope(Meta, "case", E),
232  expand_case(Meta, Expr, Options, E);
233
234expand({'receive', Meta, [Opts]}, E) ->
235  assert_no_match_or_guard_scope(Meta, "receive", E),
236  {EClauses, EC} = elixir_clauses:'receive'(Meta, Opts, E),
237  {{'receive', Meta, [EClauses]}, EC};
238
239expand({'try', Meta, [Opts]}, E) ->
240  assert_no_match_or_guard_scope(Meta, "try", E),
241  {EClauses, EC} = elixir_clauses:'try'(Meta, Opts, E),
242  {{'try', Meta, [EClauses]}, EC};
243
244%% Comprehensions
245
246expand({for, Meta, [_ | _] = Args}, E) ->
247  assert_no_match_or_guard_scope(Meta, "for", E),
248  {Cases, Block} =
249    case elixir_utils:split_last(Args) of
250      {OuterCases, OuterOpts} when is_list(OuterOpts) ->
251        case elixir_utils:split_last(OuterCases) of
252          {InnerCases, InnerOpts} when is_list(InnerOpts) ->
253            {InnerCases, InnerOpts ++ OuterOpts};
254          _ ->
255            {OuterCases, OuterOpts}
256        end;
257      _ ->
258        {Args, []}
259    end,
260
261  validate_opts(Meta, for, [do, into, uniq, reduce], Block, E),
262
263  {Expr, Opts} =
264    case lists:keytake(do, 1, Block) of
265      {value, {do, Do}, DoOpts} ->
266        {Do, DoOpts};
267      false ->
268        form_error(Meta, E, ?MODULE, {missing_option, for, [do]})
269    end,
270
271  {EOpts, EO} = expand(Opts, elixir_env:reset_unused_vars(E)),
272  {ECases, EC} = lists:mapfoldl(fun expand_for/2, EO, Cases),
273  assert_generator_start(Meta, ECases, E),
274
275  {EExpr, EE} =
276    case validate_for_options(EOpts, false, false, false) of
277      {ok, MaybeReduce} -> expand_for_do_block(Meta, Expr, EC, MaybeReduce);
278      {error, Error} -> form_error(Meta, E, ?MODULE, Error)
279    end,
280
281  {{for, Meta, ECases ++ [[{do, EExpr} | EOpts]]}, elixir_env:merge_and_check_unused_vars(E, EE)};
282
283%% With
284
285expand({with, Meta, [_ | _] = Args}, E) ->
286  assert_no_match_or_guard_scope(Meta, "with", E),
287  elixir_clauses:with(Meta, Args, E);
288
289%% Super
290
291expand({super, Meta, Args}, E) when is_list(Args) ->
292  assert_no_match_or_guard_scope(Meta, "super", E),
293  {Kind, Name, _} = resolve_super(Meta, length(Args), E),
294  {EArgs, EA} = expand_args(Args, E),
295  {{super, [{super, {Kind, Name}} | Meta], EArgs}, EA};
296
297%% Vars
298
299expand({'^', Meta, [Arg]}, #{context := match} = E) ->
300  #{current_vars := {_ReadCurrent, WriteCurrent}, prematch_vars := {Prematch, _}} = E,
301
302  %% We need to rollback to a no match context.
303  NoMatchE = E#{context := nil, current_vars := {Prematch, WriteCurrent}, prematch_vars := pin},
304
305  case expand(Arg, NoMatchE) of
306    {{Name, _, Kind} = Var, #{unused_vars := Unused}} when is_atom(Name), is_atom(Kind) ->
307      {{'^', Meta, [Var]}, E#{unused_vars := Unused}};
308    _ ->
309      form_error(Meta, E, ?MODULE, {invalid_arg_for_pin, Arg})
310  end;
311expand({'^', Meta, [Arg]}, E) ->
312  form_error(Meta, E, ?MODULE, {pin_outside_of_match, Arg});
313
314expand({'_', _Meta, Kind} = Var, #{context := match} = E) when is_atom(Kind) ->
315  {Var, E};
316expand({'_', Meta, Kind}, E) when is_atom(Kind) ->
317  form_error(Meta, E, ?MODULE, unbound_underscore);
318
319expand({Name, Meta, Kind}, #{context := match} = E) when is_atom(Name), is_atom(Kind) ->
320  #{
321    current_vars := {ReadCurrent, WriteCurrent},
322    unused_vars := {Unused, Version},
323    prematch_vars := {_, PrematchVersion}
324  } = E,
325
326  Pair = {Name, elixir_utils:var_context(Meta, Kind)},
327
328  case ReadCurrent of
329    %% Variable was already overridden
330    #{Pair := VarVersion} when VarVersion >= PrematchVersion ->
331      maybe_warn_underscored_var_repeat(Meta, Name, Kind, E),
332      NewUnused = var_used(Pair, VarVersion, Unused),
333      Var = {Name, [{version, VarVersion} | Meta], Kind},
334      {Var, E#{unused_vars := {NewUnused, Version}}};
335
336    %% Variable is being overridden now
337    #{Pair := _} ->
338      NewUnused = var_unused(Pair, Meta, Version, Unused, true),
339      NewReadCurrent = ReadCurrent#{Pair => Version},
340      NewWriteCurrent = (WriteCurrent /= false) andalso WriteCurrent#{Pair => Version},
341      Var = {Name, [{version, Version} | Meta], Kind},
342      {Var, E#{current_vars := {NewReadCurrent, NewWriteCurrent}, unused_vars := {NewUnused, Version + 1}}};
343
344    %% Variable defined for the first time
345    _ ->
346      NewVars = ordsets:add_element(Pair, ?key(E, vars)),
347      NewUnused = var_unused(Pair, Meta, Version, Unused, false),
348      NewReadCurrent = ReadCurrent#{Pair => Version},
349      NewWriteCurrent = (WriteCurrent /= false) andalso WriteCurrent#{Pair => Version},
350      Var = {Name, [{version, Version} | Meta], Kind},
351      {Var, E#{vars := NewVars, current_vars := {NewReadCurrent, NewWriteCurrent}, unused_vars := {NewUnused, Version + 1}}}
352  end;
353
354expand({Name, Meta, Kind}, E) when is_atom(Name), is_atom(Kind) ->
355  #{current_vars := {ReadCurrent, _WriteCurrent}, unused_vars := {Unused, Version}} = E,
356  Pair = {Name, elixir_utils:var_context(Meta, Kind)},
357
358  case ReadCurrent of
359    #{Pair := PairVersion} ->
360      maybe_warn_underscored_var_access(Meta, Name, Kind, E),
361      Var = {Name, [{version, PairVersion} | Meta], Kind},
362      {Var, E#{unused_vars := {var_used(Pair, PairVersion, Unused), Version}}};
363
364    _ ->
365      %% TODO: Remove this check on v2.0 as we can always raise undefined_var
366      case lists:keyfind(var, 1, Meta) of
367        {var, true} ->
368          form_error(Meta, E, ?MODULE, {undefined_var_bang, Name, Kind});
369
370        _ ->
371          case ?key(E, prematch_vars) of
372            warn ->
373              %% TODO: Remove warn option on v2.0
374              elixir_errors:form_warn(Meta, E, ?MODULE, {unknown_variable, Name}),
375              expand({Name, Meta, []}, E);
376
377            raise ->
378              form_error(Meta, E, ?MODULE, {undefined_var, Name, Kind});
379
380            pin ->
381              form_error(Meta, E, ?MODULE, {undefined_var_pin, Name, Kind});
382
383            apply ->
384              expand({Name, Meta, []}, E)
385          end
386      end
387  end;
388
389%% Local calls
390
391expand({Atom, Meta, Args}, E) when is_atom(Atom), is_list(Meta), is_list(Args) ->
392  assert_no_ambiguous_op(Atom, Meta, Args, E),
393
394  elixir_dispatch:dispatch_import(Meta, Atom, Args, E, fun() ->
395    expand_local(Meta, Atom, Args, E)
396  end);
397
398%% Remote calls
399
400expand({{'.', DotMeta, [Left, Right]}, Meta, Args}, E)
401    when (is_tuple(Left) orelse is_atom(Left)), is_atom(Right), is_list(Meta), is_list(Args) ->
402  {ELeft, EL} = expand(Left, elixir_env:prepare_write(E)),
403
404  elixir_dispatch:dispatch_require(Meta, ELeft, Right, Args, EL, fun(AR, AF, AA) ->
405    expand_remote(AR, DotMeta, AF, Meta, AA, E, EL)
406  end);
407
408%% Anonymous calls
409
410expand({{'.', DotMeta, [Expr]}, Meta, Args}, E) when is_list(Args) ->
411  assert_no_match_or_guard_scope(Meta, "anonymous call", E),
412
413  case expand_args([Expr | Args], E) of
414    {[EExpr | _], _} when is_atom(EExpr) ->
415      form_error(Meta, E, ?MODULE, {invalid_function_call, EExpr});
416
417    {[EExpr | EArgs], EA} ->
418      {{{'.', DotMeta, [EExpr]}, Meta, EArgs}, EA}
419  end;
420
421%% Invalid calls
422
423expand({_, Meta, Args} = Invalid, E) when is_list(Meta) and is_list(Args) ->
424  form_error(Meta, E, ?MODULE, {invalid_call, Invalid});
425
426expand({_, _, _} = Tuple, E) ->
427  form_error([{line, 0}], ?key(E, file), ?MODULE, {invalid_quoted_expr, Tuple});
428
429%% Literals
430
431expand({Left, Right}, E) ->
432  {[ELeft, ERight], EE} = expand_args([Left, Right], E),
433  {{ELeft, ERight}, EE};
434
435expand(List, #{context := match} = E) when is_list(List) ->
436  expand_list(List, fun expand/2, E, []);
437
438expand(List, E) when is_list(List) ->
439  {EArgs, {EE, _}} = expand_list(List, fun expand_arg/2, {elixir_env:prepare_write(E), E}, []),
440  {EArgs, elixir_env:close_write(EE, E)};
441
442expand(Function, E) when is_function(Function) ->
443  case (erlang:fun_info(Function, type) == {type, external}) andalso
444       (erlang:fun_info(Function, env) == {env, []}) of
445    true ->
446      {elixir_quote:fun_to_quoted(Function), E};
447    false ->
448      form_error([{line, 0}], ?key(E, file), ?MODULE, {invalid_quoted_expr, Function})
449  end;
450
451expand(Pid, E) when is_pid(Pid) ->
452  case ?key(E, function) of
453    nil ->
454      {Pid, E};
455    Function ->
456      %% TODO: Make me an error on v2.0
457      elixir_errors:form_warn([], E, ?MODULE, {invalid_pid_in_function, Pid, Function}),
458      {Pid, E}
459  end;
460
461expand(Other, E) when is_number(Other); is_atom(Other); is_binary(Other) ->
462  {Other, E};
463
464expand(Other, E) ->
465  form_error([{line, 0}], ?key(E, file), ?MODULE, {invalid_quoted_expr, Other}).
466
467%% Helpers
468
469escape_env_entries(Meta, #{current_vars := {Read, Write}, unused_vars := {Unused, Version}} = Env0) ->
470  Env1 = case Env0 of
471    #{function := nil} -> Env0;
472    _ -> Env0#{lexical_tracker := nil, tracers := []}
473  end,
474  Current = {maybe_escape_map(Read), maybe_escape_map(Write)},
475  Env2 = Env1#{current_vars := Current, unused_vars := {maybe_escape_map(Unused), Version}},
476  Env3 = elixir_env:linify({?line(Meta), Env2}),
477  Env3.
478
479maybe_escape_map(#{} = Map) -> {'%{}', [], maps:to_list(Map)};
480maybe_escape_map(Other) -> Other.
481
482expand_multi_alias_call(Kind, Meta, Base, Refs, Opts, E) ->
483  {BaseRef, EB} = expand_without_aliases_report(Base, E),
484  Fun = fun
485    ({'__aliases__', _, Ref}, ER) ->
486      expand({Kind, Meta, [elixir_aliases:concat([BaseRef | Ref]), Opts]}, ER);
487    (Ref, ER) when is_atom(Ref) ->
488      expand({Kind, Meta, [elixir_aliases:concat([BaseRef, Ref]), Opts]}, ER);
489    (Other, _ER) ->
490      form_error(Meta, E, ?MODULE, {expected_compile_time_module, Kind, Other})
491  end,
492  lists:mapfoldl(Fun, EB, Refs).
493
494resolve_super(Meta, Arity, E) ->
495  Module = assert_module_scope(Meta, super, E),
496  Function = assert_function_scope(Meta, super, E),
497
498  case Function of
499    {_, Arity} ->
500      {Kind, Name, SuperMeta} = elixir_overridable:super(Meta, Module, Function, E),
501      maybe_warn_deprecated_super_in_gen_server_callback(Meta, Function, SuperMeta, E),
502      {Kind, Name, SuperMeta};
503
504    _ ->
505      form_error(Meta, E, ?MODULE, wrong_number_of_args_for_super)
506  end.
507
508expand_fn_capture(Meta, Arg, E) ->
509  case elixir_fn:capture(Meta, Arg, E) of
510    {{remote, Remote, Fun, Arity}, EE} ->
511      is_atom(Remote) andalso
512        elixir_env:trace({remote_function, Meta, Remote, Fun, Arity}, E),
513      AttachedMeta = attach_context_module(Remote, Meta, E),
514      {{'&', AttachedMeta, [{'/', [], [{{'.', [], [Remote, Fun]}, [], []}, Arity]}]}, EE};
515    {{local, Fun, Arity}, #{function := nil}} ->
516      form_error(Meta, E, ?MODULE, {undefined_local_capture, Fun, Arity});
517    {{local, Fun, Arity}, EE} ->
518      {{'&', Meta, [{'/', [], [{Fun, [], nil}, Arity]}]}, EE};
519    {expand, Expr, EE} ->
520      expand(Expr, EE)
521  end.
522
523expand_list([{'|', Meta, [_, _] = Args}], Fun, Acc, List) ->
524  {EArgs, EAcc} = lists:mapfoldl(Fun, Acc, Args),
525  expand_list([], Fun, EAcc, [{'|', Meta, EArgs} | List]);
526expand_list([H | T], Fun, Acc, List) ->
527  {EArg, EAcc} = Fun(H, Acc),
528  expand_list(T, Fun, EAcc, [EArg | List]);
529expand_list([], _Fun, Acc, List) ->
530  {lists:reverse(List), Acc}.
531
532expand_block([], Acc, _Meta, E) ->
533  {lists:reverse(Acc), E};
534expand_block([H], Acc, Meta, E) ->
535  {EH, EE} = expand(H, E),
536  expand_block([], [EH | Acc], Meta, EE);
537expand_block([H | T], Acc, Meta, E) ->
538  {EH, EE} = expand(H, E),
539
540  %% Note that checks rely on the code BEFORE expansion
541  %% instead of relying on Erlang checks.
542  %%
543  %% That's because expansion may generate useless
544  %% terms on their own (think compile time removed
545  %% logger calls) and we don't want to catch those.
546  %%
547  %% Or, similarly, the work is all in the expansion
548  %% (for example, to register something) and it is
549  %% simply returning something as replacement.
550  case is_useless_building(H, EH, Meta) of
551    {UselessMeta, UselessTerm} ->
552      elixir_errors:form_warn(UselessMeta, E, ?MODULE, UselessTerm);
553    false ->
554      ok
555  end,
556
557  expand_block(T, [EH | Acc], Meta, EE).
558
559%% Note that we don't handle atoms on purpose. They are common
560%% when unquoting AST and it is unlikely that we would catch
561%% bugs as we don't do binary operations on them like in
562%% strings or numbers.
563is_useless_building(H, _, Meta) when is_binary(H); is_number(H) ->
564  {Meta, {useless_literal, H}};
565is_useless_building({'@', Meta, [{Var, _, Ctx}]}, _, _) when is_atom(Ctx); Ctx == [] ->
566  {Meta, {useless_attr, Var}};
567is_useless_building({Var, Meta, Ctx}, {Var, _, Ctx}, _) when is_atom(Ctx) ->
568  {Meta, {useless_var, Var}};
569is_useless_building(_, _, _) ->
570  false.
571
572%% Variables in arguments are not propagated from one
573%% argument to the other. For instance:
574%%
575%%   x = 1
576%%   foo(x = x + 2, x)
577%%   x
578%%
579%% Should be the same as:
580%%
581%%   foo(3, 1)
582%%   3
583%%
584%% However, lexical information is.
585expand_arg(Arg, Acc) when is_number(Arg); is_atom(Arg); is_binary(Arg); is_pid(Arg) ->
586  {Arg, Acc};
587expand_arg(Arg, {Acc, E}) ->
588  {EArg, EAcc} = expand(Arg, elixir_env:reset_read(Acc, E)),
589  {EArg, {EAcc, E}}.
590
591expand_args([Arg], E) ->
592  {EArg, EE} = expand(Arg, E),
593  {[EArg], EE};
594expand_args(Args, #{context := match} = E) ->
595  lists:mapfoldl(fun expand/2, E, Args);
596expand_args(Args, E) ->
597  {EArgs, {EA, _}} = lists:mapfoldl(fun expand_arg/2, {elixir_env:prepare_write(E), E}, Args),
598  {EArgs, elixir_env:close_write(EA, E)}.
599
600%% Match/var helpers
601
602var_unused({Name, Kind}, Meta, Version, Unused, Override) ->
603  case (Kind == nil) andalso should_warn(Meta) of
604    true -> Unused#{{Name, Version} => {?line(Meta), Override}};
605    false -> Unused
606  end.
607
608var_used({Name, Kind}, Version, Unused) ->
609  case Kind of
610    nil -> Unused#{{Name, Version} => false};
611    _ -> Unused
612  end.
613
614maybe_warn_underscored_var_repeat(Meta, Name, Kind, E) ->
615  case should_warn(Meta) andalso atom_to_list(Name) of
616    "_" ++ _ ->
617      elixir_errors:form_warn(Meta, E, ?MODULE, {underscored_var_repeat, Name, Kind});
618    _ ->
619      ok
620  end.
621
622maybe_warn_underscored_var_access(Meta, Name, Kind, E) ->
623  case (Kind == nil) andalso should_warn(Meta) andalso atom_to_list(Name) of
624    "_" ++ _ ->
625      elixir_errors:form_warn(Meta, E, ?MODULE, {underscored_var_access, Name});
626    _ ->
627      ok
628  end.
629
630%% TODO: Remove this on Elixir v2.0 and make all GenServer callbacks optional
631maybe_warn_deprecated_super_in_gen_server_callback(Meta, Function, SuperMeta, E) ->
632  case lists:keyfind(context, 1, SuperMeta) of
633    {context, 'Elixir.GenServer'} ->
634      case Function of
635        {child_spec, 1} ->
636          ok;
637
638        _ ->
639          elixir_errors:form_warn(Meta, E, ?MODULE, {super_in_genserver, Function})
640      end;
641
642    _ ->
643      ok
644  end.
645
646context_info(Kind) when Kind == nil; is_integer(Kind) -> "";
647context_info(Kind) -> io_lib:format(" (context ~ts)", [elixir_aliases:inspect(Kind)]).
648
649should_warn(Meta) ->
650  lists:keyfind(generated, 1, Meta) /= {generated, true}.
651
652%% Case
653
654expand_case(Meta, Expr, Opts, E) ->
655  {EExpr, EE} = expand(Expr, E),
656
657  ROpts =
658    case proplists:get_value(optimize_boolean, Meta, false) of
659      true ->
660        case elixir_utils:returns_boolean(EExpr) of
661          true -> rewrite_case_clauses(Opts);
662          false -> generated_case_clauses(Opts)
663        end;
664
665      false ->
666        Opts
667    end,
668
669  {EOpts, EO} = elixir_clauses:'case'(Meta, ROpts, EE),
670  {{'case', Meta, [EExpr, EOpts]}, EO}.
671
672rewrite_case_clauses([{do, [
673  {'->', FalseMeta, [
674    [{'when', _, [Var, {{'.', _, ['Elixir.Kernel', 'in']}, _, [Var, [false, nil]]}]}],
675    FalseExpr
676  ]},
677  {'->', TrueMeta, [
678    [{'_', _, _}],
679    TrueExpr
680  ]}
681]}]) ->
682  rewrite_case_clauses(FalseMeta, FalseExpr, TrueMeta, TrueExpr);
683
684rewrite_case_clauses([{do, [
685  {'->', FalseMeta, [[false], FalseExpr]},
686  {'->', TrueMeta, [[true], TrueExpr]} | _
687]}]) ->
688  rewrite_case_clauses(FalseMeta, FalseExpr, TrueMeta, TrueExpr);
689
690rewrite_case_clauses(Other) ->
691  generated_case_clauses(Other).
692
693rewrite_case_clauses(FalseMeta, FalseExpr, TrueMeta, TrueExpr) ->
694  [{do, [
695    {'->', ?generated(FalseMeta), [[false], FalseExpr]},
696    {'->', ?generated(TrueMeta), [[true], TrueExpr]}
697  ]}].
698
699generated_case_clauses([{do, Clauses}]) ->
700  RClauses = [{'->', ?generated(Meta), Args} || {'->', Meta, Args} <- Clauses],
701  [{do, RClauses}].
702
703%% Comprehensions
704
705validate_for_options([{into, _} = Pair | Opts], _Into, Uniq, Reduce) ->
706  validate_for_options(Opts, Pair, Uniq, Reduce);
707validate_for_options([{uniq, Boolean} = Pair | Opts], Into, _Uniq, Reduce) when is_boolean(Boolean) ->
708  validate_for_options(Opts, Into, Pair, Reduce);
709validate_for_options([{uniq, Value} | _], _, _, _) ->
710  {error, {for_invalid_uniq, Value}};
711validate_for_options([{reduce, _} = Pair | Opts], Into, Uniq, _Reduce) ->
712  validate_for_options(Opts, Into, Uniq, Pair);
713validate_for_options([], Into, Uniq, {reduce, _}) when Into /= false; Uniq /= false ->
714  {error, for_conflicting_reduce_into_uniq};
715validate_for_options([], _Into, _Uniq, Reduce) ->
716  {ok, Reduce}.
717
718expand_for_do_block(Meta, Expr, E, false) ->
719  case Expr of
720    [{'->', _, _} | _] -> form_error(Meta, E, ?MODULE, for_without_reduce_bad_block);
721    _ -> expand(Expr, E)
722  end;
723expand_for_do_block(Meta, Clauses, E, {reduce, _}) ->
724  Transformer = fun({_, _, [Left, _Right]} = Clause, Acc) ->
725    case Left of
726      [_] ->
727        EReset = elixir_env:reset_unused_vars(Acc),
728        {EClause, EAcc} = elixir_clauses:clause(Meta, fn, fun elixir_clauses:head/2, Clause, EReset),
729        {EClause, elixir_env:merge_and_check_unused_vars(Acc, EAcc)};
730      _ ->
731        form_error(Meta, E, ?MODULE, for_with_reduce_bad_block)
732    end
733  end,
734
735  case Clauses of
736    [{'->', _, _} | _] -> lists:mapfoldl(Transformer, E, Clauses);
737    _ -> form_error(Meta, E, ?MODULE, for_with_reduce_bad_block)
738  end.
739
740%% Locals
741
742assert_no_ambiguous_op(Name, Meta, [Arg], E) ->
743  case lists:keyfind(ambiguous_op, 1, Meta) of
744    {ambiguous_op, Kind} ->
745      Pair = {Name, Kind},
746      case ?key(E, current_vars) of
747        {#{Pair := _}, _} ->
748          form_error(Meta, E, ?MODULE, {op_ambiguity, Name, Arg});
749        _ ->
750          ok
751      end;
752    _ ->
753      ok
754  end;
755assert_no_ambiguous_op(_Atom, _Meta, _Args, _E) ->
756  ok.
757
758assert_no_clauses(_Name, _Meta, [], _E) ->
759  ok;
760assert_no_clauses(Name, Meta, Args, E) ->
761  assert_arg_with_no_clauses(Name, Meta, lists:last(Args), E).
762
763assert_arg_with_no_clauses(Name, Meta, [{Key, Value} | Rest], E) when is_atom(Key) ->
764  case Value of
765    [{'->', _, _} | _] ->
766      form_error(Meta, E, ?MODULE, {invalid_clauses, Name});
767    _ ->
768      assert_arg_with_no_clauses(Name, Meta, Rest, E)
769  end;
770assert_arg_with_no_clauses(_Name, _Meta, _Arg, _E) ->
771  ok.
772
773expand_local(Meta, Name, Args, #{module := Module, function := Function, context := nil} = E)
774    when Function /= nil ->
775  assert_no_clauses(Name, Meta, Args, E),
776  Arity = length(Args),
777  elixir_env:trace({local_function, Meta, Name, Arity}, E),
778  elixir_locals:record_local({Name, Arity}, Module, Function, Meta, false),
779  {EArgs, EA} = expand_args(Args, E),
780  {{Name, Meta, EArgs}, EA};
781expand_local(Meta, Name, Args, E) when Name == '|'; Name == '::' ->
782  form_error(Meta, E, ?MODULE, {undefined_function, Name, Args});
783expand_local(Meta, Name, Args, #{function := nil} = E) ->
784  form_error(Meta, E, ?MODULE, {undefined_function, Name, Args});
785expand_local(Meta, Name, Args, #{context := Context} = E) when Context == match; Context == guard ->
786  form_error(Meta, E, ?MODULE, {invalid_local_invocation, Context, {Name, Meta, Args}}).
787
788%% Remote
789
790expand_remote(Receiver, DotMeta, Right, Meta, Args, #{context := Context} = E, EL) when is_atom(Receiver) or is_tuple(Receiver) ->
791  assert_no_clauses(Right, Meta, Args, E),
792
793  case {Context, lists:keyfind(no_parens, 1, Meta)} of
794    {guard, {no_parens, true}} when is_tuple(Receiver) ->
795      {{{'.', DotMeta, [Receiver, Right]}, Meta, []}, EL};
796
797    {guard, _} when is_tuple(Receiver) ->
798      form_error(Meta, E, ?MODULE, {parens_map_lookup_guard, Receiver, Right});
799
800    _ ->
801      AttachedDotMeta = attach_context_module(Receiver, DotMeta, E),
802
803      is_atom(Receiver) andalso
804        elixir_env:trace({remote_function, DotMeta, Receiver, Right, length(Args)}, E),
805
806      {EArgs, {EA, _}} = lists:mapfoldl(fun expand_arg/2, {EL, E}, Args),
807
808      case rewrite(Context, Receiver, AttachedDotMeta, Right, Meta, EArgs) of
809        {ok, Rewritten} ->
810          maybe_warn_comparison(Rewritten, Args, E),
811          {Rewritten, elixir_env:close_write(EA, E)};
812        {error, Error} ->
813          form_error(Meta, E, elixir_rewrite, Error)
814      end
815  end;
816expand_remote(Receiver, DotMeta, Right, Meta, Args, E, _) ->
817  Call = {{'.', DotMeta, [Receiver, Right]}, Meta, Args},
818  form_error(Meta, E, ?MODULE, {invalid_call, Call}).
819
820attach_context_module(_Receiver, Meta, #{function := nil}) ->
821  Meta;
822attach_context_module(Receiver, Meta, #{context_modules := ContextModules}) ->
823  case lists:member(Receiver, ContextModules) of
824    true -> [{context_module, true} | Meta];
825    false -> Meta
826  end.
827
828rewrite(match, Receiver, DotMeta, Right, Meta, EArgs) ->
829  elixir_rewrite:match_rewrite(Receiver, DotMeta, Right, Meta, EArgs);
830rewrite(guard, Receiver, DotMeta, Right, Meta, EArgs) ->
831  elixir_rewrite:guard_rewrite(Receiver, DotMeta, Right, Meta, EArgs);
832rewrite(_, Receiver, DotMeta, Right, Meta, EArgs) ->
833  {ok, elixir_rewrite:rewrite(Receiver, DotMeta, Right, Meta, EArgs)}.
834
835maybe_warn_comparison({{'.', _, [erlang, Op]}, Meta, [ELeft, ERight]}, [Left, Right], E)
836    when Op =:= '>'; Op =:= '<'; Op =:= '=<'; Op =:= '>='; Op =:= min; Op =:= max ->
837  case is_struct_comparison(ELeft, ERight, Left, Right) of
838    false ->
839      case is_nested_comparison(Op, ELeft, ERight, Left, Right) of
840        false -> ok;
841        CompExpr ->
842          elixir_errors:form_warn(Meta, E, ?MODULE, {nested_comparison, CompExpr})
843      end;
844    StructExpr ->
845      elixir_errors:form_warn(Meta, E, ?MODULE, {struct_comparison, StructExpr})
846  end;
847maybe_warn_comparison(_, _, _) ->
848  ok.
849
850is_struct_comparison(ELeft, ERight, Left, Right) ->
851  case is_struct_expression(ELeft) of
852    true -> Left;
853    false ->
854      case is_struct_expression(ERight) of
855        true -> Right;
856        false -> false
857      end
858  end.
859
860is_struct_expression({'%', _, [Struct, _]}) when is_atom(Struct) ->
861  true;
862is_struct_expression({'%{}', _, KVs}) ->
863  case lists:keyfind('__struct__', 1, KVs) of
864    {'__struct__', Struct} when is_atom(Struct) -> true;
865    false -> false
866  end;
867is_struct_expression(_Other) -> false.
868
869is_nested_comparison(Op, ELeft, ERight, Left, Right) ->
870  NestedExpr = {elixir_utils:erlang_comparison_op_to_elixir(Op), [], [Left, Right]},
871  case is_comparison_expression(ELeft) of
872    true ->
873      NestedExpr;
874    false ->
875      case is_comparison_expression(ERight) of
876        true -> NestedExpr;
877        false -> false
878      end
879  end.
880is_comparison_expression({{'.',_,[erlang,Op]},_,_})
881  when Op =:= '>'; Op =:= '<'; Op =:= '=<'; Op =:= '>=' -> true;
882is_comparison_expression(_Other) -> false.
883
884%% Lexical helpers
885
886expand_opts(Meta, Kind, Allowed, Opts, E) ->
887  {EOpts, EE} = expand(Opts, E),
888  validate_opts(Meta, Kind, Allowed, EOpts, EE),
889  {EOpts, EE}.
890
891validate_opts(Meta, Kind, Allowed, Opts, E) when is_list(Opts) ->
892  [begin
893    form_error(Meta, E, ?MODULE, {unsupported_option, Kind, Key})
894  end || {Key, _} <- Opts, not lists:member(Key, Allowed)];
895
896validate_opts(Meta, Kind, _Allowed, Opts, E) ->
897  form_error(Meta, E, ?MODULE, {options_are_not_keyword, Kind, Opts}).
898
899no_alias_opts(Opts) when is_list(Opts) ->
900  case lists:keyfind(as, 1, Opts) of
901    {as, As} -> lists:keystore(as, 1, Opts, {as, no_alias_expansion(As)});
902    false -> Opts
903  end;
904no_alias_opts(Opts) -> Opts.
905
906no_alias_expansion({'__aliases__', _, [H | T]}) when is_atom(H) ->
907  elixir_aliases:concat([H | T]);
908no_alias_expansion(Other) ->
909  Other.
910
911expand_require(Meta, Ref, Opts, E) ->
912  elixir_env:trace({require, Meta, Ref, Opts}, E),
913  RE = E#{requires := ordsets:add_element(Ref, ?key(E, requires))},
914  expand_alias(Meta, false, Ref, Opts, RE).
915
916expand_alias(Meta, IncludeByDefault, Ref, Opts, #{context_modules := Context} = E) ->
917  New = expand_as(lists:keyfind(as, 1, Opts), Meta, IncludeByDefault, Ref, E),
918
919  %% Add the alias to context_modules if defined is set.
920  %% This is used by defmodule in order to store the defined
921  %% module in context modules.
922  NewContext =
923    case lists:keyfind(defined, 1, Meta) of
924      {defined, Mod} when is_atom(Mod) -> [Mod | Context];
925      false -> Context
926    end,
927
928  {Aliases, MacroAliases} = elixir_aliases:store(Meta, New, Ref, Opts, E),
929  E#{aliases := Aliases, macro_aliases := MacroAliases, context_modules := NewContext}.
930
931expand_as({as, nil}, _Meta, _IncludeByDefault, Ref, _E) ->
932  Ref;
933expand_as({as, Atom}, Meta, _IncludeByDefault, _Ref, E) when is_atom(Atom), not is_boolean(Atom) ->
934  case atom_to_list(Atom) of
935    "Elixir." ++ ([FirstLetter | _] = Rest) when FirstLetter >= $A, FirstLetter =< $Z ->
936      case string:tokens(Rest, ".") of
937        [_] ->
938          Atom;
939        _ ->
940          form_error(Meta, E, ?MODULE, {invalid_alias_for_as, nested_alias, Atom})
941      end;
942    _ ->
943      form_error(Meta, E, ?MODULE, {invalid_alias_for_as, not_alias, Atom})
944  end;
945expand_as(false, _Meta, IncludeByDefault, Ref, _E) ->
946  if IncludeByDefault -> elixir_aliases:last(Ref);
947     true -> Ref
948  end;
949expand_as({as, Other}, Meta, _IncludeByDefault, _Ref, E) ->
950  form_error(Meta, E, ?MODULE, {invalid_alias_for_as, not_alias, Other}).
951
952%% Aliases
953
954expand_without_aliases_report({'__aliases__', _, _} = Alias, E) ->
955  expand_aliases(Alias, E, false);
956expand_without_aliases_report(Other, E) ->
957  expand(Other, E).
958
959expand_aliases({'__aliases__', Meta, _} = Alias, E, Report) ->
960  case elixir_aliases:expand(Alias, E) of
961    Receiver when is_atom(Receiver) ->
962      Report andalso elixir_env:trace({alias_reference, Meta, Receiver}, E),
963      {Receiver, E};
964
965    Aliases ->
966      {EAliases, EA} = expand_args(Aliases, E),
967
968      case lists:all(fun is_atom/1, EAliases) of
969        true ->
970          Receiver = elixir_aliases:concat(EAliases),
971          Report andalso elixir_env:trace({alias_reference, Meta, Receiver}, E),
972          {Receiver, EA};
973        false ->
974          form_error(Meta, E, ?MODULE, {invalid_alias, Alias})
975      end
976  end.
977
978%% Comprehensions
979
980expand_for({'<-', Meta, [Left, Right]}, E) ->
981  {ERight, ER} = expand(Right, E),
982  {[ELeft], EL} = elixir_clauses:head([Left], ER, E),
983  {{'<-', Meta, [ELeft, ERight]}, EL};
984expand_for({'<<>>', Meta, Args} = X, E) when is_list(Args) ->
985  case elixir_utils:split_last(Args) of
986    {LeftStart, {'<-', OpMeta, [LeftEnd, Right]}} ->
987      {ERight, ER} = expand(Right, E),
988      {ELeft, EL} = elixir_clauses:match(fun(BArg, BE) ->
989        elixir_bitstring:expand(Meta, BArg, BE, true)
990      end, LeftStart ++ [LeftEnd], ER, E),
991      {{'<<>>', [], [{'<-', OpMeta, [ELeft, ERight]}]}, EL};
992    _ ->
993      expand(X, E)
994  end;
995expand_for(X, E) ->
996  expand(X, E).
997
998assert_generator_start(_, [{'<-', _, [_, _]} | _], _) ->
999  ok;
1000assert_generator_start(_, [{'<<>>', _, [{'<-', _, [_, _]}]} | _], _) ->
1001  ok;
1002assert_generator_start(Meta, _, E) ->
1003  elixir_errors:form_error(Meta, E, ?MODULE, for_generator_start).
1004
1005%% Assertions
1006
1007refute_parallel_bitstring_match({'<<>>', _, _}, {'<<>>', Meta, _} = Arg, E, true) ->
1008  form_error(Meta, E, ?MODULE, {parallel_bitstring_match, Arg});
1009refute_parallel_bitstring_match(Left, {'=', _Meta, [MatchLeft, MatchRight]}, E, Parallel) ->
1010  refute_parallel_bitstring_match(Left, MatchLeft, E, true),
1011  refute_parallel_bitstring_match(Left, MatchRight, E, Parallel);
1012refute_parallel_bitstring_match([_ | _] = Left, [_ | _] = Right, E, Parallel) ->
1013  refute_parallel_bitstring_match_each(Left, Right, E, Parallel);
1014refute_parallel_bitstring_match({Left1, Left2}, {Right1, Right2}, E, Parallel) ->
1015  refute_parallel_bitstring_match_each([Left1, Left2], [Right1, Right2], E, Parallel);
1016refute_parallel_bitstring_match({'{}', _, Args1}, {'{}', _, Args2}, E, Parallel) ->
1017  refute_parallel_bitstring_match_each(Args1, Args2, E, Parallel);
1018refute_parallel_bitstring_match({'%{}', _, Args1}, {'%{}', _, Args2}, E, Parallel) ->
1019  refute_parallel_bitstring_match_map_field(lists:sort(Args1), lists:sort(Args2), E, Parallel);
1020refute_parallel_bitstring_match({'%', _, [_, Args]}, Right, E, Parallel) ->
1021  refute_parallel_bitstring_match(Args, Right, E, Parallel);
1022refute_parallel_bitstring_match(Left, {'%', _, [_, Args]}, E, Parallel) ->
1023  refute_parallel_bitstring_match(Left, Args, E, Parallel);
1024refute_parallel_bitstring_match(_Left, _Right, _E, _Parallel) ->
1025  ok.
1026
1027refute_parallel_bitstring_match_each([Arg1 | Rest1], [Arg2 | Rest2], E, Parallel) ->
1028  refute_parallel_bitstring_match(Arg1, Arg2, E, Parallel),
1029    refute_parallel_bitstring_match_each(Rest1, Rest2, E, Parallel);
1030refute_parallel_bitstring_match_each(_List1, _List2, _E, _Parallel) ->
1031  ok.
1032
1033refute_parallel_bitstring_match_map_field([{Key, Val1} | Rest1], [{Key, Val2} | Rest2], E, Parallel) ->
1034  refute_parallel_bitstring_match(Val1, Val2, E, Parallel),
1035  refute_parallel_bitstring_match_map_field(Rest1, Rest2, E, Parallel);
1036refute_parallel_bitstring_match_map_field([Field1 | Rest1] = Args1, [Field2 | Rest2] = Args2, E, Parallel) ->
1037  case Field1 > Field2 of
1038    true ->
1039      refute_parallel_bitstring_match_map_field(Args1, Rest2, E, Parallel);
1040    false ->
1041      refute_parallel_bitstring_match_map_field(Rest1, Args2, E, Parallel)
1042  end;
1043refute_parallel_bitstring_match_map_field(_Args1, _Args2, _E, _Parallel) ->
1044  ok.
1045
1046assert_module_scope(Meta, Kind, #{module := nil, file := File}) ->
1047  form_error(Meta, File, ?MODULE, {invalid_expr_in_scope, "module", Kind});
1048assert_module_scope(_Meta, _Kind, #{module:=Module}) -> Module.
1049
1050assert_function_scope(Meta, Kind, #{function := nil, file := File}) ->
1051  form_error(Meta, File, ?MODULE, {invalid_expr_in_scope, "function", Kind});
1052assert_function_scope(_Meta, _Kind, #{function := Function}) -> Function.
1053
1054assert_no_match_or_guard_scope(Meta, Kind, E) ->
1055  assert_no_match_scope(Meta, Kind, E),
1056  assert_no_guard_scope(Meta, Kind, E).
1057assert_no_match_scope(Meta, Kind, #{context := match, file := File}) ->
1058  form_error(Meta, File, ?MODULE, {invalid_pattern_in_match, Kind});
1059assert_no_match_scope(_Meta, _Kind, _E) -> [].
1060assert_no_guard_scope(Meta, Kind, #{context := guard, file := File}) ->
1061  form_error(Meta, File, ?MODULE, {invalid_expr_in_guard, Kind});
1062assert_no_guard_scope(_Meta, _Kind, _E) -> [].
1063
1064assert_contextual_var(Meta, Name, #{contextual_vars := Vars, file := File}, Error) ->
1065  case lists:member(Name, Vars) of
1066    true -> ok;
1067    false -> form_error(Meta, File, ?MODULE, Error)
1068  end.
1069
1070%% Here we look into the Clauses "optimistically", that is, we don't check for
1071%% multiple "do"s and similar stuff. After all, the error we're gonna give here
1072%% is just a friendlier version of the "undefined variable _" error that we
1073%% would raise if we found a "_ -> ..." clause in a "cond". For this reason, if
1074%% Clauses has a bad shape, we just do nothing and let future functions catch
1075%% this.
1076assert_no_underscore_clause_in_cond([{do, Clauses}], E) when is_list(Clauses) ->
1077  case lists:last(Clauses) of
1078    {'->', Meta, [[{'_', _, Atom}], _]} when is_atom(Atom) ->
1079      form_error(Meta, E, ?MODULE, underscore_in_cond);
1080    _Other ->
1081      ok
1082  end;
1083assert_no_underscore_clause_in_cond(_Other, _E) ->
1084  ok.
1085
1086%% Errors
1087
1088format_error({useless_literal, Term}) ->
1089  io_lib:format("code block contains unused literal ~ts "
1090                "(remove the literal or assign it to _ to avoid warnings)",
1091                ['Elixir.Macro':to_string(Term)]);
1092format_error({useless_var, Var}) ->
1093  io_lib:format("variable ~ts in code block has no effect as it is never returned "
1094                "(remove the variable or assign it to _ to avoid warnings)",
1095                [Var]);
1096format_error({useless_attr, Attr}) ->
1097  io_lib:format("module attribute @~ts in code block has no effect as it is never returned "
1098                "(remove the attribute or assign it to _ to avoid warnings)",
1099                [Attr]);
1100format_error({missing_option, Construct, Opts}) when is_list(Opts) ->
1101  StringOpts = lists:map(fun(Opt) -> [$: | atom_to_list(Opt)] end, Opts),
1102  io_lib:format("missing ~ts option in \"~ts\"", [string:join(StringOpts, "/"), Construct]);
1103format_error({invalid_args, Construct}) ->
1104  io_lib:format("invalid arguments for \"~ts\"", [Construct]);
1105format_error({for_invalid_uniq, Value}) ->
1106  io_lib:format(":uniq option for comprehensions only accepts a boolean, got: ~ts", ['Elixir.Macro':to_string(Value)]);
1107format_error(for_conflicting_reduce_into_uniq) ->
1108  "cannot use :reduce alongside :into/:uniq in comprehension";
1109format_error(for_with_reduce_bad_block) ->
1110  "when using :reduce with comprehensions, the do block must be written using acc -> expr clauses, where each clause expects the accumulator as a single argument";
1111format_error(for_without_reduce_bad_block) ->
1112  "the do block was written using acc -> expr clauses but the :reduce option was not given";
1113format_error(for_generator_start) ->
1114  "for comprehensions must start with a generator";
1115format_error(unhandled_arrow_op) ->
1116  "unhandled operator ->";
1117format_error(as_in_multi_alias_call) ->
1118  ":as option is not supported by multi-alias call";
1119format_error({expected_compile_time_module, Kind, GivenTerm}) ->
1120  io_lib:format("invalid argument for ~ts, expected a compile time atom or alias, got: ~ts",
1121                [Kind, 'Elixir.Macro':to_string(GivenTerm)]);
1122format_error({unquote_outside_quote, Unquote}) ->
1123  %% Unquote can be "unquote" or "unquote_splicing".
1124  io_lib:format("~p called outside quote", [Unquote]);
1125format_error({invalid_bind_quoted_for_quote, BQ}) ->
1126  io_lib:format("invalid :bind_quoted for quote, expected a keyword list of variable names, got: ~ts",
1127                ['Elixir.Macro':to_string(BQ)]);
1128format_error(wrong_number_of_args_for_super) ->
1129  "super must be called with the same number of arguments as the current definition";
1130format_error({invalid_arg_for_pin, Arg}) ->
1131  io_lib:format("invalid argument for unary operator ^, expected an existing variable, got: ^~ts",
1132                ['Elixir.Macro':to_string(Arg)]);
1133format_error({pin_outside_of_match, Arg}) ->
1134  io_lib:format("cannot use ^~ts outside of match clauses", ['Elixir.Macro':to_string(Arg)]);
1135format_error(unbound_underscore) ->
1136  "invalid use of _. \"_\" represents a value to be ignored in a pattern and cannot be used in expressions";
1137format_error({undefined_var, Name, Kind}) ->
1138  io_lib:format("undefined variable \"~ts\"~ts", [Name, context_info(Kind)]);
1139format_error({undefined_var_pin, Name, Kind}) ->
1140  Message = "undefined variable ^~ts. No variable \"~ts\"~ts has been defined before the current pattern",
1141  io_lib:format(Message, [Name, Name, context_info(Kind)]);
1142format_error({undefined_var_bang, Name, Kind}) ->
1143  Message = "expected \"~ts\"~ts to expand to an existing variable or be part of a match",
1144  io_lib:format(Message, [Name, context_info(Kind)]);
1145format_error(underscore_in_cond) ->
1146  "invalid use of _ inside \"cond\". If you want the last clause to always match, "
1147    "you probably meant to use: true ->";
1148format_error({invalid_expr_in_guard, Kind}) ->
1149  Message =
1150    "invalid expression in guard, ~ts is not allowed in guards. To learn more about "
1151    "guards, visit: https://hexdocs.pm/elixir/patterns-and-guards.html",
1152  io_lib:format(Message, [Kind]);
1153format_error({invalid_pattern_in_match, Kind}) ->
1154  io_lib:format("invalid pattern in match, ~ts is not allowed in matches", [Kind]);
1155format_error({invalid_expr_in_scope, Scope, Kind}) ->
1156  io_lib:format("cannot invoke ~ts outside ~ts", [Kind, Scope]);
1157format_error({invalid_alias, Expr}) ->
1158  Message =
1159    "invalid alias: \"~ts\". If you wanted to define an alias, an alias must expand "
1160    "to an atom at compile time but it did not, you may use Module.concat/2 to build "
1161    "it at runtime. If instead you wanted to invoke a function or access a field, "
1162    "wrap the function or field name in double quotes",
1163  io_lib:format(Message, ['Elixir.Macro':to_string(Expr)]);
1164format_error({op_ambiguity, Name, Arg}) ->
1165  NameString = atom_to_binary(Name, utf8),
1166  ArgString = 'Elixir.Macro':to_string(Arg),
1167
1168  Message =
1169    "\"~ts ~ts\" looks like a function call but there is a variable named \"~ts\". "
1170    "If you want to perform a function call, use parentheses:\n"
1171    "\n"
1172    "    ~ts(~ts)\n"
1173    "\n"
1174    "If you want to perform an operation on the variable ~ts, use spaces "
1175    "around the unary operator",
1176  io_lib:format(Message, [NameString, ArgString, NameString, NameString, ArgString, NameString]);
1177format_error({invalid_clauses, Name}) ->
1178  Message =
1179    "the function \"~ts\" cannot handle clauses with the -> operator because it is not a macro. "
1180    "Please make sure you are invoking the proper name and that it is a macro",
1181  io_lib:format(Message, [Name]);
1182format_error({invalid_alias_for_as, Reason, Value}) ->
1183  ExpectedGot =
1184    case Reason of
1185      not_alias -> "expected an alias, got";
1186      nested_alias -> "expected a simple alias, got nested alias"
1187    end,
1188  io_lib:format("invalid value for option :as, ~ts: ~ts",
1189                [ExpectedGot, 'Elixir.Macro':to_string(Value)]);
1190format_error({invalid_function_call, Expr}) ->
1191  io_lib:format("invalid function call :~ts.()", [Expr]);
1192format_error({invalid_call, Call}) ->
1193  io_lib:format("invalid call ~ts", ['Elixir.Macro':to_string(Call)]);
1194format_error({invalid_quoted_expr, Expr}) ->
1195  Message =
1196    "invalid quoted expression: ~ts\n\n"
1197    "Please make sure your quoted expressions are made of valid AST nodes. "
1198    "If you would like to introduce a value into the AST, such as a four-element "
1199    "tuple or a map, make sure to call Macro.escape/1 before",
1200  io_lib:format(Message, ['Elixir.Kernel':inspect(Expr, [])]);
1201format_error({invalid_local_invocation, Context, {Name, _, Args} = Call}) ->
1202  Message =
1203    "cannot find or invoke local ~ts/~B inside ~ts. "
1204    "Only macros can be invoked in a ~ts and they must be defined before their invocation. Called as: ~ts",
1205  io_lib:format(Message, [Name, length(Args), Context, Context, 'Elixir.Macro':to_string(Call)]);
1206format_error({invalid_pid_in_function, Pid, {Name, Arity}}) ->
1207  io_lib:format("cannot compile PID ~ts inside quoted expression for function ~ts/~B",
1208                ['Elixir.Kernel':inspect(Pid, []), Name, Arity]);
1209format_error({unsupported_option, Kind, Key}) ->
1210  io_lib:format("unsupported option ~ts given to ~s",
1211                ['Elixir.Macro':to_string(Key), Kind]);
1212format_error({options_are_not_keyword, Kind, Opts}) ->
1213  io_lib:format("invalid options for ~s, expected a keyword list, got: ~ts",
1214                [Kind, 'Elixir.Macro':to_string(Opts)]);
1215format_error({undefined_function, '|', [_, _]}) ->
1216  "misplaced operator |/2\n\n"
1217  "The | operator is typically used between brackets as the cons operator:\n\n"
1218  "    [head | tail]\n\n"
1219  "where head is a single element and the tail is the remaining of a list.\n"
1220  "It is also used to update maps and structs, via the %{map | key: value} notation,\n"
1221  "and in typespecs, such as @type and @spec, to express the union of two types";
1222format_error({undefined_function, '::', [_, _]}) ->
1223  "misplaced operator ::/2\n\n"
1224  "The :: operator is typically used in bitstrings to specify types and sizes of segments:\n\n"
1225  "    <<size::32-integer, letter::utf8, rest::binary>>\n\n"
1226  "It is also used in typespecs, such as @type and @spec, to describe inputs and outputs";
1227format_error({undefined_function, Name, Args}) ->
1228  io_lib:format("undefined function ~ts/~B", [Name, length(Args)]);
1229format_error({underscored_var_repeat, Name, Kind}) ->
1230  io_lib:format("the underscored variable \"~ts\"~ts appears more than once in a "
1231                "match. This means the pattern will only match if all \"~ts\" bind "
1232                "to the same value. If this is the intended behaviour, please "
1233                "remove the leading underscore from the variable name, otherwise "
1234                "give the variables different names", [Name, context_info(Kind), Name]);
1235format_error({underscored_var_access, Name}) ->
1236  io_lib:format("the underscored variable \"~ts\" is used after being set. "
1237                "A leading underscore indicates that the value of the variable "
1238                "should be ignored. If this is intended please rename the "
1239                "variable to remove the underscore", [Name]);
1240format_error({struct_comparison, StructExpr}) ->
1241  String = 'Elixir.Macro':to_string(StructExpr),
1242  io_lib:format("invalid comparison with struct literal ~ts. Comparison operators "
1243                "(>, <, >=, <=, min, and max) perform structural and not semantic comparison. "
1244                "Comparing with a struct literal is unlikely to give a meaningful result. "
1245                "Struct modules typically define a compare/2 function that can be used for "
1246                "semantic comparison", [String]);
1247format_error({nested_comparison, CompExpr}) ->
1248  String = 'Elixir.Macro':to_string(CompExpr),
1249  io_lib:format("Elixir does not support nested comparisons. Something like\n\n"
1250                "     x < y < z\n\n"
1251                "is equivalent to\n\n"
1252                "     (x < y) < z\n\n"
1253                "which ultimately compares z with the boolean result of (x < y). "
1254                "Instead, consider joining together each comparison segment with an \"and\", for example,\n\n"
1255                "     x < y and y < z\n\n"
1256                "You wrote: ~ts", [String]);
1257format_error({undefined_local_capture, Fun, Arity}) ->
1258  io_lib:format("undefined function ~ts/~B", [Fun, Arity]);
1259format_error(env_not_allowed) ->
1260  "__ENV__ is not allowed inside a match";
1261format_error(caller_not_allowed) ->
1262  "__CALLER__ is available only inside defmacro and defmacrop";
1263format_error(stacktrace_not_allowed) ->
1264  "__STACKTRACE__ is available only inside catch and rescue clauses of try expressions";
1265format_error({unknown_variable, Name}) ->
1266  io_lib:format("variable \"~ts\" does not exist and is being expanded to \"~ts()\","
1267                " please use parentheses to remove the ambiguity or change the variable name", [Name, Name]);
1268format_error({parens_map_lookup_guard, Map, Field}) ->
1269  io_lib:format("cannot invoke remote function in guard. "
1270                "If you want to do a map lookup instead, please remove parens from ~ts.~ts()",
1271                ['Elixir.Macro':to_string(Map), Field]);
1272format_error({super_in_genserver, {Name, Arity}}) ->
1273  io_lib:format("calling super for GenServer callback ~ts/~B is deprecated", [Name, Arity]);
1274format_error({parallel_bitstring_match, Expr}) ->
1275  Message =
1276    "binary patterns cannot be matched in parallel using \"=\", excess pattern: ~ts",
1277  io_lib:format(Message, ['Elixir.Macro':to_string(Expr)]).
1278