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