-
Notifications
You must be signed in to change notification settings - Fork 3.3k
Expand file tree
/
Copy pathv3_core.erl
More file actions
4913 lines (4482 loc) · 184 KB
/
Copy pathv3_core.erl
File metadata and controls
4913 lines (4482 loc) · 184 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
%%
%% %CopyrightBegin%
%%
%% SPDX-License-Identifier: Apache-2.0
%%
%% Copyright Ericsson AB 1999-2026. All Rights Reserved.
%%
%% Licensed under the Apache License, Version 2.0 (the "License");
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% http://www.apache.org/licenses/LICENSE-2.0
%%
%% Unless required by applicable law or agreed to in writing, software
%% distributed under the License is distributed on an "AS IS" BASIS,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%
%% %CopyrightEnd%
%%
%% Purpose : Transform normal Erlang to Core Erlang
%% At this stage all preprocessing has been done. All that is left are
%% "pure" Erlang functions.
%%
%% Core transformation is done in four stages:
%%
%% 1. Flatten expressions into an internal core form without doing
%% matching.
%%
%% 2. Step "forwards" over the icore code annotating each "top-level"
%% thing with variable usage. Detect bound variables in matching
%% and replace with explicit guard test. Annotate "internal-core"
%% expressions with variables they use and create. Convert matches
%% to cases when not pure assignments.
%%
%% 3. Step "backwards" over icore code using variable usage
%% annotations to change implicit exported variables to explicit
%% returns.
%%
%% 4. Lower receives to more primitive operations. Split binary
%% patterns where a value is matched out and then used used as
%% a size in the same pattern. That simplifies the subsequent
%% passes as all variables are within a single pattern are either
%% new or used, but never both at the same time.
%%
%% To ensure the evaluation order we ensure that all arguments are
%% safe. A "safe" is basically a core_lib simple with VERY restricted
%% binaries.
%%
%% We have to be very careful with matches as these create variables.
%% While we try not to flatten things more than necessary we must make
%% sure that all matches are at the top level. For this we use the
%% type "novars" which are non-match expressions. Cases and receives
%% can also create problems due to exports variables so they are not
%% "novars" either. I.e. a novars will not export variables.
%%
%% Annotations in the #iset, #iletrec, and all other internal records
%% is kept in a record, #a, not in a list as in proper core. This is
%% easier and faster and creates no problems as we have complete control
%% over all annotations.
%%
%% On output, the annotation for most Core Erlang terms will contain
%% the source line number. A few terms will be marked with the atom
%% atom 'compiler_generated', to indicate that the compiler has generated
%% them and that no warning should be generated if they are optimized
%% away.
%%
%%
%% In this translation:
%%
%% call ops are safes
%% call arguments are safes
%% match arguments are novars
%% case arguments are novars
%% receive timeouts are novars
%% binaries and maps are novars
%% let/set arguments are expressions
%% fun is not a safe
-module(v3_core).
-moduledoc false.
-export([module/2,format_error/1]).
-import(lists, [all/2,any/2,append/1,droplast/1,duplicate/2,
foldl/3,foldr/3,
keydelete/3,keyfind/3,keymember/3,
last/1,map/2,member/2,mapfoldl/3,
reverse/1,reverse/2,
split/2,splitwith/2,sort/1]).
-import(ordsets, [add_element/2,del_element/2,is_element/2,
union/1,union/2,intersection/2,subtract/2]).
-import(cerl, [ann_c_cons/3,ann_c_tuple/2,c_tuple/1,
ann_c_map/3,ann_c_record/4,cons_hd/1,cons_tl/1]).
-include("core_parse.hrl").
%% Matches expansion max segment in v3_kernel.
-define(COLLAPSE_MAX_SIZE_SEGMENT, 1024).
%% Internal core expressions and help functions.
%% N.B. annotations fields in place as normal Core expressions.
-record(a, {us=[],ns=[],anno=[]}). %Internal annotation
-record(iapply, {anno=#a{},op,args}).
-record(ibinary, {anno=#a{},segments}). %Not used in patterns.
-record(ibitstr, {anno=#a{},val,size,unit,type,flags}).
-record(icall, {anno=#a{},module,name,args}).
-record(icase, {anno=#a{},args,clauses,fc}).
-record(icatch, {anno=#a{},body}).
-record(iclause, {anno=#a{},pats,guard,body}).
-record(ifun, {anno=#a{},id,vars,clauses,fc,name=unnamed}).
-record(iletrec, {anno=#a{},defs,body}).
-record(imatch, {anno=#a{},pat,guard=[],arg,fc}).
-record(iexprs, {anno=#a{},bodies=[]}).
-record(imap, {anno=#a{},arg=#c_literal{val=#{}},es,is_pat=false}).
-record(imappair, {anno=#a{},op,key,val}).
-record(iprimop, {anno=#a{},name,args}).
-record(iprotect, {anno=#a{},body}).
-record(ireceive1, {anno=#a{},clauses}).
-record(ireceive2, {anno=#a{},clauses,timeout,action}).
-record(iset, {anno=#a{},var,arg}).
-record(itry, {anno=#a{},args,vars,body,evars,handler}).
-record(ifilter, {anno=#a{},arg}).
-record(igen, {anno=#a{},acc_pat,acc_guard,
nomatch_pat,nomatch_mode,
tail,tail_pat,arg,
refill={nomatch,ignore}}).
-record(izip, {anno=#a{},acc_pats=[],acc_guard,
nomatch_pats=[],nomatch_total=[],skip_pats=[],
tails=[],tail_pats=[],pres=[],args=[],
refill_pats=[],refill_as=[]}).
-record(isimple, {anno=#a{},term :: cerl:cerl()}).
-type iapply() :: #iapply{}.
-type ibinary() :: #ibinary{}.
-type icall() :: #icall{}.
-type icase() :: #icase{}.
-type icatch() :: #icatch{}.
-type iclause() :: #iclause{}.
-type ifun() :: #ifun{}.
-type iletrec() :: #iletrec{}.
-type imatch() :: #imatch{}.
-type imap() :: #imap{}.
-type iprimop() :: #iprimop{}.
-type iprotect() :: #iprotect{}.
-type ireceive1() :: #ireceive1{}.
-type ireceive2() :: #ireceive2{}.
-type iset() :: #iset{}.
-type itry() :: #itry{}.
-type ifilter() :: #ifilter{}.
-type igen() :: #igen{}.
-type izip() :: #izip{}.
-type isimple() :: #isimple{}.
-type i() :: iapply() | ibinary() | icall() | icase() | icatch()
| iclause() | ifun() | iletrec() | imatch() | imap()
| iprimop() | iprotect() | ireceive1() | ireceive2()
| iset() | itry() | ifilter()
| igen() | izip() | isimple().
-type warning() :: {file:filename(), [{integer(), module(), term()}]}.
-record(core, {vcount=0 :: non_neg_integer(), %Variable counter
fcount=0 :: non_neg_integer(), %Function counter
gcount=0 :: non_neg_integer(), %Goto counter
module :: module(), %Module name.
function={none,0} :: fa(), %Current function.
in_guard=false :: boolean(), %In guard or not.
wanted=true :: boolean(), %Result wanted or not.
opts=[] :: [compile:option()], %Options.
dialyzer=false :: boolean(), %Help dialyzer or not.
ws=[] :: [warning()], %Warnings.
file=[{file,""}], %File.
load_nif=false :: boolean() %true if calls erlang:load_nif/2
}).
-type state() :: #core{}.
%% XXX: The following type declarations do not belong in this module
-type fa() :: {atom(), arity()}.
-type attribute() :: atom().
-type form() :: {function, integer(), atom(), arity(), _}
| {attribute, integer(), attribute(), _}.
-record(imodule, {name = [],
exports = ordsets:new(),
nifs = none ::
'none' | sets:set(), % Is a set if the attribute is
% present in the module.
attrs = [],
defs = [],
file = [],
opts = [],
ws = [],
load_nif=false :: boolean() %true if calls erlang:load_nif/2
}).
-spec module([form()], [compile:option()]) ->
{'ok',cerl:c_module(),[warning()]}.
module(Forms0, Opts) ->
Forms = erl_internal:add_predefined_functions(Forms0),
Module = foldl(fun (F, Acc) ->
form(F, Acc, Opts)
end, #imodule{}, Forms),
#imodule{name=Mod,exports=Exp0,attrs=As0,
defs=Kfs0,ws=Ws,load_nif=LoadNif,nifs=Nifs} = Module,
Exp = case member(export_all, Opts) of
true -> defined_functions(Forms);
false -> Exp0
end,
Cexp = [#c_var{name=FA} || {_,_}=FA <:- Exp],
Kfs1 = reverse(Kfs0),
Kfs = if LoadNif, Nifs =:= none ->
insert_nif_start(Kfs1);
true ->
Kfs1
end,
As = reverse(As0),
{ok,#c_module{name=#c_literal{val=Mod},exports=Cexp,attrs=As,defs=Kfs},Ws}.
form({function,_,_,_,_}=F0,
#imodule{defs=Defs,load_nif=LoadNif0}=Module,
Opts) ->
{F,Ws,LoadNif} = function(F0, Module, Opts),
Module#imodule{defs=[F|Defs],ws=Ws,load_nif=LoadNif orelse LoadNif0};
form({attribute,_,module,Mod}, Module, _Opts) ->
true = is_atom(Mod),
Module#imodule{name=Mod};
form({attribute,_,file,{File,_Line}}=F, #imodule{attrs=As}=Module, _Opts) ->
Module#imodule{file=File, attrs=[attribute(F)|As]};
form({attribute,_,import,_}, Module, _Opts) ->
%% Ignore. We have no further use for imports.
Module;
form({attribute,_,export,Es}, #imodule{exports=Exp0}=Module, _Opts) ->
Exp = ordsets:union(ordsets:from_list(Es), Exp0),
Module#imodule{exports=Exp};
form({attribute,_,nifs,Ns}, #imodule{nifs=Nifs0}=Module, _Opts) ->
Nifs1 = case Nifs0 of
none ->
sets:new();
_ ->
Nifs0
end,
Nifs = sets:union(sets:from_list(Ns, [{version,2}]), Nifs1),
Module#imodule{nifs=Nifs};
form({attribute,_,_,_}=F, #imodule{attrs=As}=Module, _Opts) ->
Module#imodule{attrs=[attribute(F)|As]};
form(_, Module, _Opts) ->
%% Ignore uninteresting forms such as 'eof'.
Module.
attribute({attribute,A,Name,Val0}) ->
Line = [erl_anno:location(A)],
Val = if
is_list(Val0) -> Val0;
true -> [Val0]
end,
{#c_literal{val=Name, anno=Line}, #c_literal{val=Val, anno=Line}}.
defined_functions(Forms) ->
Fs = [{Name,Arity} || {function,_,Name,Arity,_} <- Forms],
ordsets:from_list(Fs).
%% function_dump(module_info,_,_,_) -> ok;
%% function_dump(Name,Arity,Format,Terms) ->
%% io:format("~w/~w " ++ Format,[Name,Arity]++Terms),
%% ok.
function({function,_,Name,Arity,Cs0}, Module, Opts)
when is_integer(Arity), 0 =< Arity, Arity =< 255 ->
#imodule{name=Mod, file=File, ws=Ws0, nifs=Nifs} = Module,
try
St0 = #core{vcount=0,module=Mod,function={Name,Arity},
opts=Opts,
dialyzer=member(dialyzer, Opts),
ws=Ws0,file=[{file,File}]},
{Cs1,Anno} = handle_debug_line(Cs0, St0),
{B0,St1} = body(Cs1, Name, Arity, St0),
%% ok = function_dump(Name, Arity, "body:~n~p~n",[B0]),
{B1,St2} = ubody(B0, St1),
%% ok = function_dump(Name, Arity, "ubody:~n~p~n",[B1]),
{B2,St3} = cbody(B1, Nifs, St2),
%% ok = function_dump(Name, Arity, "cbody:~n~p~n",[B2]),
{B3,#core{ws=Ws,load_nif=LoadNif}} = lbody(B2, St3),
%% ok = function_dump(Name, Arity, "lbody:~n~p~n",[B3]),
{{#c_var{anno=Anno,name={Name,Arity}},B3},Ws,LoadNif}
catch
Class:Error:Stack ->
io:fwrite("Function: ~w/~w\n", [Name,Arity]),
erlang:raise(Class, Error, Stack)
end.
handle_debug_line(Cs0, #core{opts=Opts}=St) ->
maybe
true ?= member(beam_debug_info, Opts),
[{clause,_,_,_,[{debug_line,Line,Index}|_]}|Cs] ?= Cs0,
{Cs,[{debug_line,{lineno_anno(Line, St),Index}}]}
else
_ ->
{Cs0,[]}
end.
body(Cs0, Name, Arity, St0) ->
Anno = lineno_anno(element(2, hd(Cs0)), St0),
FunAnno = [{function,{Name,Arity}} | Anno],
{Args0,St1} = new_vars(Anno, Arity, St0),
Args = reverse(Args0), %Nicer order
{Cs1,St2} = clauses(Cs0, St1),
{Ps,St3} = new_vars(Arity, St2), %Need new variables here
Fc = function_clause(Ps, FunAnno),
{#ifun{anno=#a{anno=FunAnno},id=[],vars=Args,clauses=Cs1,fc=Fc},St3}.
%% clause(Clause, State) -> {Cclause,State}.
%% clauses([Clause], State) -> {[Cclause],State}.
%% Convert clauses. Trap bad pattern aliases.
clauses([C0|Cs0], St0) ->
{C,St1} = clause(C0, St0),
{Cs,St2} = clauses(Cs0, St1),
{[C|Cs],St2};
clauses([], St) -> {[],St}.
clause({clause,Lc,H0,G0,B0}, St0) ->
try head(H0, St0) of
{H1,St1} ->
{G1,St2} = guard(G0, St1),
{B1,St3} = exprs(B0, St2),
Anno = lineno_anno(Lc, St3),
{#iclause{anno=#a{anno=Anno},pats=H1,guard=G1,body=B1},St3}
catch
throw:nomatch ->
%% This pattern can't possibly match. If we simply remove
%% the clause, variables that are used later might not be
%% bound. Therefore, we must keep the clause, but rewrite
%% the pattern to a pattern that will bind the same
%% variables and ensure that the clause can't be executed
%% by letting the guard return false.
St1 = add_warning(Lc, {nomatch,pattern}, St0),
H1 = [sanitize(P) || P <- H0],
false = H0 =:= H1, %Assertion.
G1 = [[{atom,Lc,false}]],
LcNoWarn = no_compiler_warning(Lc),
clause({clause,LcNoWarn,H1,G1,B0}, St1)
end.
clause_arity({clause,_,H0,_,_}) -> length(H0).
%% head([P], State) -> {[P],[Cexpr],State}.
head(Ps, St) ->
pattern_list(Ps, St).
%% guard([Expr], State) -> {[Cexpr],State}.
%% Build an explicit and/or tree of guard alternatives, then traverse
%% top-level and/or tree and "protect" inner tests.
guard([], St) -> {[],St};
guard(Gs0, St0) ->
Gs1 = foldr(fun (Gt0, Rhs) ->
Gt1 = guard_tests(Gt0),
L = element(2, Gt1),
{op,L,'or',Gt1,Rhs}
end, guard_tests(last(Gs0)), droplast(Gs0)),
{Gs,St} = gexpr_top(Gs1, St0#core{in_guard=true}),
{Gs,St#core{in_guard=false}}.
guard_tests(Gs) ->
L = element(2, hd(Gs)),
{protect,L,foldr(fun (G, Rhs) -> {op,L,'and',G,Rhs} end, last(Gs), droplast(Gs))}.
%% gexpr_top(Expr, State) -> {Cexpr,State}.
%% Generate an internal core expression of a guard test. Explicitly
%% handle outer boolean expressions and "protect" inner tests in a
%% reasonably smart way.
gexpr_top(E0, St0) ->
{E1,Eps0,Bools,St1} = gexpr(E0, [], St0),
{E,Eps,St} = force_booleans(Bools, E1, Eps0, St1),
{Eps++[E],St}.
%% gexpr(Expr, Bools, State) -> {Cexpr,[PreExp],Bools,State}.
%% Generate an internal core expression of a guard test.
gexpr({protect,Line,Arg}, Bools0, St0) ->
case gexpr(Arg, [], St0) of
{E0,[],Bools,St1} ->
{E,Eps,St} = force_booleans(Bools, E0, [], St1),
{E,Eps,Bools0,St};
{E0,Eps0,Bools,St1} ->
{E,Eps,St} = force_booleans(Bools, E0, Eps0, St1),
Anno = lineno_anno(Line, St),
{#iprotect{anno=#a{anno=Anno},body=Eps++[E]},[],Bools0,St}
end;
gexpr({op,_,'andalso',_,_}=E0, Bools, St0) ->
{op,L,'andalso',E1,E2} = right_assoc(E0, 'andalso'),
Anno = lineno_anno(L, St0),
{#c_var{name=V0},St} = new_var(Anno, St0),
V = {var,L,V0},
False = {atom,L,false},
E = make_bool_switch(L, E1, V, E2, False),
gexpr(E, Bools, St);
gexpr({op,_,'orelse',_,_}=E0, Bools, St0) ->
{op,L,'orelse',E1,E2} = right_assoc(E0, 'orelse'),
Anno = lineno_anno(L, St0),
{#c_var{name=V0},St} = new_var(Anno, St0),
V = {var,L,V0},
True = {atom,L,true},
E = make_bool_switch(L, E1, V, True, E2),
gexpr(E, Bools, St);
gexpr({op,Line,Op,L,R}=E, Bools, St) ->
case erl_internal:bool_op(Op, 2) of
true ->
gexpr_bool(Op, L, R, Bools, St, Line);
false ->
gexpr_test(E, Bools, St)
end;
gexpr({call,Line,{remote,_,{atom,_,erlang},{atom,_,Op}},[L,R]}=E, Bools, St) ->
case erl_internal:bool_op(Op, 2) of
true ->
gexpr_bool(Op, L, R, Bools, St, Line);
false ->
gexpr_test(E, Bools, St)
end;
gexpr({op,Line,'not',A}, Bools, St) ->
gexpr_not(A, Bools, St, Line);
gexpr({call,Line,{remote,_,{atom,_,erlang},{atom,_,'not'}},[A]}, Bools, St) ->
gexpr_not(A, Bools, St, Line);
gexpr(E0, Bools, St0) ->
gexpr_test(E0, Bools, St0).
%% gexpr_bool(L, R, Bools, State) -> {Cexpr,[PreExp],Bools,State}.
%% Generate a guard for boolean operators
gexpr_bool(Op, L, R, Bools0, St0, Line) ->
{Le,Lps,Bools1,St1} = gexpr(L, Bools0, St0),
{Ll,Llps,St2} = force_safe(Le, St1),
{Re,Rps,Bools,St3} = gexpr(R, Bools1, St2),
{Rl,Rlps,St4} = force_safe(Re, St3),
Anno = lineno_anno(Line, St4),
{#icall{anno=#a{anno=Anno}, %Must have an #a{}
module=#c_literal{anno=Anno,val=erlang},
name=#c_literal{anno=Anno,val=Op},
args=[Ll,Rl]},Lps ++ Llps ++ Rps ++ Rlps,Bools,St4}.
%% gexpr_not(Expr, Bools, State) -> {Cexpr,[PreExp],Bools,State}.
%% Generate an erlang:'not'/1 guard test.
gexpr_not(A, Bools0, St0, Line) ->
{Ae0,Aps,Bools,St1} = gexpr(A, Bools0, St0),
case Ae0 of
#icall{anno=#a{anno=[v3_core,compiler_generated]},
module=#c_literal{val=erlang},
name=#c_literal{val='=:='},
args=[E,#c_literal{val=true}]}=EqCall ->
%%
%% We here have the expression:
%%
%% not(Expr =:= true)
%%
%% The annotations tested in the code above guarantees
%% that the original expression in the Erlang source
%% code was:
%%
%% not Expr
%%
%% That expression can be transformed as follows:
%%
%% not Expr ==> Expr =:= false
%%
%% which will produce the same result, but may eliminate
%% redundant is_boolean/1 tests (see unforce/3).
%%
%% Note that this transformation would not be safe if the
%% original expression had been:
%%
%% not(Expr =:= true)
%%
Ae = EqCall#icall{args=[E,#c_literal{val=false}]},
{Al,Alps,St2} = force_safe(Ae, St1),
{Al,Aps ++ Alps,Bools,St2};
Ae ->
{Al,Alps,St2} = force_safe(Ae, St1),
Anno = lineno_anno(Line, St2),
{#icall{anno=#a{anno=Anno}, %Must have an #a{}
module=#c_literal{anno=Anno,val=erlang},
name=#c_literal{anno=Anno,val='not'},
args=[Al]},Aps ++ Alps,Bools,St2}
end.
%% gexpr_test(Expr, Bools, State) -> {Cexpr,[PreExp],Bools,State}.
%% Generate a guard test. At this stage we must be sure that we have
%% a proper boolean value here so wrap things with an true test if we
%% don't know, i.e. if it is not a comparison or a type test.
gexpr_test({atom,L,true}, Bools, St0) ->
{#c_literal{anno=lineno_anno(L, St0),val=true},[],Bools,St0};
gexpr_test({atom,L,false}, Bools, St0) ->
{#c_literal{anno=lineno_anno(L, St0),val=false},[],Bools,St0};
gexpr_test(E0, Bools0, St0) ->
{E1,Eps0,St1} = expr(E0, St0),
%% Generate "top-level" test and argument calls.
case E1 of
#icall{anno=Anno,module=#c_literal{val=erlang},
name=#c_literal{val=is_function},
args=[_,_]} ->
%% is_function/2 is not a safe type test. We must force
%% it to be protected.
Lanno = Anno#a.anno,
{New,St2} = new_var(Lanno, St1),
{icall_eq_true(New),
Eps0 ++ [#iset{anno=Anno,var=New,arg=E1}],Bools0,St2};
#icall{anno=Anno,module=#c_literal{val=erlang},name=#c_literal{val=N},args=As} ->
%% Note that erl_expand_records has renamed type
%% tests to the new names; thus, float/1 as a type
%% test will now be named is_float/1.
Ar = length(As),
case erl_internal:new_type_test(N, Ar) orelse
erl_internal:comp_op(N, Ar) orelse
erl_internal:bool_op(N, Ar) of
true -> {E1,Eps0,Bools0,St1};
false ->
Lanno = Anno#a.anno,
{New,St2} = new_var(Lanno, St1),
Bools = [New|Bools0],
{icall_eq_true(New),
Eps0 ++ [#iset{anno=Anno,var=New,arg=E1}],Bools,St2}
end;
_ ->
Lanno = get_lineno_anno(E1),
ACompGen = #a{anno=[compiler_generated]},
case is_simple(E1) of
true ->
Bools = [E1|Bools0],
{icall_eq_true(E1),Eps0,Bools,St1};
false ->
{New,St2} = new_var(Lanno, St1),
Bools = [New|Bools0],
{icall_eq_true(New),
Eps0 ++ [#iset{anno=ACompGen,var=New,arg=E1}],Bools,St2}
end
end.
icall_eq_true(Arg) ->
%% We need to recognize a '=:=' added by this pass, so we will add
%% an extra 'v3_core' annotation. (Being paranoid, we don't want
%% to trust 'compiler_generated' alone as it could have been added
%% by a parse transform.)
#icall{anno=#a{anno=[v3_core,compiler_generated]},
module=#c_literal{val=erlang},
name=#c_literal{val='=:='},
args=[Arg,#c_literal{val=true}]}.
%% force_booleans([Var], E, Eps, St) -> Expr.
%% Variables used in the top-level of a guard must be booleans.
%%
%% Add necessary is_boolean/1 guard tests to ensure that the guard
%% will fail if any of the variables is not a boolean.
force_booleans(Vs0, E, Eps, St) ->
Vs1 = [set_anno(V, []) || V <- Vs0],
%% Prune the list of variables that will need is_boolean/1
%% tests. Basically, if the guard consists of simple expressions
%% joined by 'and's no is_boolean/1 tests are needed.
Vs = unforce(E, Eps, Vs1),
%% Add is_boolean/1 tests for the remaining variables.
force_booleans_1(Vs, E, Eps, St).
force_booleans_1([], E, Eps, St) ->
{E,Eps,St};
force_booleans_1([V|Vs], E0, Eps0, St0) ->
{E1,Eps1,St1} = force_safe(E0, St0),
ACompGen = #a{anno=[compiler_generated]},
Call = #icall{anno=ACompGen,module=#c_literal{val=erlang},
name=#c_literal{val=is_boolean},
args=[V]},
{New,St} = new_var([], St1),
Iset = #iset{var=New,arg=Call},
Eps = Eps0 ++ Eps1 ++ [Iset],
E = #icall{anno=ACompGen,
module=#c_literal{val=erlang},name=#c_literal{val='and'},
args=[E1,New]},
force_booleans_1(Vs, E, Eps, St).
%% unforce(Expr, PreExprList, BoolExprList) -> BoolExprList'.
%% Filter BoolExprList. BoolExprList is a list of simple expressions
%% (variables or literals) of which we are not sure whether they are booleans.
%%
%% The basic idea for filtering is the following transformation:
%%
%% (E =:= Bool) and is_boolean(E) ==> E =:= Bool
%%
%% where E is an arbitrary expression and Bool is 'true' or 'false'.
%%
%% The transformation is still valid if there are other expressions joined
%% by 'and' operations:
%%
%% E1 and (E2 =:= true) and E3 and is_boolean(E) ==> E1 and (E2 =:= true) and E3
%%
%% but expressions such as:
%%
%% not (E =:= true) and is_boolean(E)
%%
%% or expression using 'or' or 'xor' cannot be transformed in this
%% way (such expressions are the reason for adding the is_boolean/1
%% test in the first place).
%%
unforce(_, _, []) ->
[];
unforce(E, Eps, Vs) ->
Tree = unforce_tree(Eps++[E], gb_trees:empty()),
unforce(Tree, Vs).
unforce_tree([#iexprs{bodies=Exprs}|Es], D0) ->
unforce_tree(lists:append(Exprs) ++ Es, D0);
unforce_tree([#iset{var=#c_var{name=V},arg=Arg0}|Es], D0) ->
Arg = unforce_tree_subst(Arg0, D0),
D = gb_trees:insert(V, Arg, D0),
unforce_tree(Es, D);
unforce_tree([#icall{}=Call], D) ->
unforce_tree_subst(Call, D);
unforce_tree([#c_var{name=V}], D) ->
gb_trees:get(V, D).
unforce_tree_subst(#icall{module=#c_literal{val=erlang},
name=#c_literal{val='=:='},
args=[_Expr,#c_literal{val=Bool}]}=Call, _)
when is_boolean(Bool) ->
%% We have erlang:'=:='(Expr, Bool). We must not expand this call any more
%% or we will not recognize is_boolean(Expr) later.
Call;
unforce_tree_subst(#icall{args=Args0}=Call, D) ->
Args = map(fun(#c_var{name=V}=Var) ->
case gb_trees:lookup(V, D) of
{value,Val} -> Val;
none -> Var
end;
(Expr) -> Expr
end, Args0),
Call#icall{args=Args};
unforce_tree_subst(Expr, _) -> Expr.
unforce(#icall{module=#c_literal{val=erlang},
name=#c_literal{val=Name},
args=Args}, Vs0) ->
case {Name,Args} of
{'and',[Arg1,Arg2]} ->
Vs = unforce(Arg1, Vs0),
unforce(Arg2, Vs);
{'=:=',[E,#c_literal{val=Bool}]} when is_boolean(Bool) ->
Vs0 -- [set_anno(E, [])];
{_,_} ->
%% Give up.
Vs0
end;
unforce(_, Vs) -> Vs.
%% exprs([Expr], State) -> {[Cexpr],State}.
%% Flatten top-level exprs.
exprs([E0|Es0], St0) ->
{E1,Eps,St1} = expr(E0, St0),
{Es1,St2} = exprs(Es0, St1),
{Eps ++ [E1] ++ Es1,St2};
exprs([], St) -> {[],St}.
%% exprs([Expr], State) -> {[Cexpr],State}.
%% Flatten top-level exprs while handling maybe_match operators.
maybe_match_exprs([{maybe_match,L,P0,E0}|Es0], Fail, St0) ->
{Es1,St1} = maybe_match_exprs(Es0, Fail, St0),
{C,St2} =
case Es1 of
[] ->
{AllName,StInt} = new_var_name(St1),
All = {var,L,AllName},
clause({clause,L,[{match,L,P0,All}],[],[All]}, StInt);
[_|_] ->
{C0,StInt} = clause({clause,L,[P0],[],[{nil,0}]}, St1),
{C0#iclause{body=Es1},StInt}
end,
{E1,Eps,St3} = novars(E0, St2),
{Fpat,St4} = new_var(St3),
Lanno = lineno_anno(L, St4),
Fc = #iclause{anno=#a{anno=[dialyzer_ignore,compiler_generated|Lanno]},pats=[Fpat],guard=[],
body=[#iapply{op=Fail,args=[Fpat]}]},
{Eps ++ [#icase{anno=#a{anno=Lanno},args=[E1],clauses=[C],fc=Fc}],St4};
maybe_match_exprs([E0|Es0], Fail, St0) ->
{E1,Eps,St1} = expr(E0, St0),
{Es1,St2} = maybe_match_exprs(Es0, Fail, St1),
{Eps ++ [E1|Es1],St2};
maybe_match_exprs([], _Fail, St) ->
{[],St}.
%% expr(Expr, State) -> {Cexpr,[PreExp],State}.
%% Generate an internal core expression.
expr({var,L,V}, St) -> {#c_var{anno=lineno_anno(L, St),name=V},[],St};
expr({char,L,C}, St) -> {#c_literal{anno=full_anno(L, St),val=C},[],St};
expr({integer,L,I}, St) -> {#c_literal{anno=full_anno(L, St),val=I},[],St};
expr({float,L,F}, St) -> {#c_literal{anno=full_anno(L, St),val=F},[],St};
expr({atom,L,A}, St) -> {#c_literal{anno=full_anno(L, St),val=A},[],St};
expr({nil,L}, St) -> {#c_literal{anno=full_anno(L, St),val=[]},[],St};
expr({string,L,S}, St) -> {#c_literal{anno=full_anno(L, St),val=S},[],St};
expr({cons,L,H0,T0}, St0) ->
{[H1,T1],Eps,St1} = safe_list([H0,T0], St0),
A = full_anno(L, St1),
{annotate_cons(A, H1, T1, St1),Eps,St1};
expr({lc,L,E,Qs0}, St0) ->
{Qs1,St1} = preprocess_quals(L, Qs0, St0),
{Lc, Pre, _OptInfo, St2} = lc_tq(L, {lc, wrap_list(E)}, Qs1, #c_literal{anno=lineno_anno(L, St1),val=[]}, St1),
{Lc, Pre, St2};
expr({bc,L,E,Qs}, St) ->
bc_tq(L, E, Qs, St);
expr({mc,L,E,Qs0}, St0) ->
{Qs1,St1} = preprocess_quals(L, Qs0, St0),
mc_tq(L, wrap_list(E), Qs1, #c_literal{anno=lineno_anno(L, St1),val=[]}, St1);
expr({tuple,L,Es0}, St0) ->
{Es1,Eps,St1} = safe_list(Es0, St0),
A = record_anno(L, St1),
{annotate_tuple(A, Es1, St1),Eps,St1};
expr({map,L,Es0}, St0) ->
map_build_pairs(#c_literal{val=#{}}, Es0, full_anno(L, St0), St0);
expr({map,L,M,Es}, St) ->
expr_map(M, Es, L, St);
expr({record,L,Id,Es0}, St0) ->
record_build_pairs(#c_literal{val=empty}, #c_literal{val=Id}, Es0,
full_anno(L, St0), St0);
expr({record,L,S,Id,Es}, St) ->
expr_record(S, #c_literal{val=Id}, Es, L, St);
expr({bin,L,Es0}, St0) ->
try expr_bin(Es0, full_anno(L, St0), St0) of
{_,_,_}=Res -> Res
catch
throw:{bad_binary,Eps,St1} ->
St = add_warning(L, {failed,bad_binary}, St1),
LineAnno = lineno_anno(L, St),
As = [#c_literal{anno=LineAnno,val=badarg}],
{#icall{anno=#a{anno=LineAnno}, %Must have an #a{}
module=#c_literal{anno=LineAnno,val=erlang},
name=#c_literal{anno=LineAnno,val=error},
args=As},Eps,St}
end;
expr({block,_,Es0}, St0) ->
%% Inline the block directly.
{Es1,St1} = exprs(droplast(Es0), St0),
{E1,Eps,St2} = expr(last(Es0), St1),
{E1,Es1 ++ Eps,St2};
expr({'maybe',L,Es}, St0) ->
{V,St1} = new_var_name(St0),
Var = {var,L,V},
Cs = [{clause,L,[Var],[],[Var]}],
expr({'maybe',L,Es,{'else',L,Cs}}, St1);
expr({'maybe',L,Es0,{'else',_,Cs0}}, St0) ->
%% Translate the maybe ... else ... end construct.
%%
%% As an example, the following Erlang code:
%%
%% foo(A) ->
%% maybe
%% {ok, V} ?= A,
%% V
%% else
%% Other ->
%% {error, Other}
%% end.
%%
%% is translated into Core Erlang like this:
%%
%% 'foo'/1 =
%% fun (_0) ->
%% case _0 of
%% <A> when 'true' ->
%% ( letrec
%% 'maybe_else_fail'/1 =
%% fun (_3) ->
%% case _3 of
%% <_2> when 'true' ->
%% case _2 of
%% <Other> when 'true' ->
%% {'error',Other}
%% ( <_1> when 'true' ->
%% primop 'match_fail'({'else_clause',_1})
%% -| ['compiler_generated'] )
%% end
%% ( <_1> when 'true' ->
%% primop 'match_fail'('never_fails')
%% -| ['compiler_generated'] )
%% end
%% in
%% case A of
%% <{'ok',V}> when 'true' ->
%% V
%% ( <_4> when 'true' ->
%% apply 'maybe_else_fail'/1(_4)
%% -| ['dialyzer_ignore','compiler_generated'] )
%% end
%% -| ['letrec_goto','no_inline'] )
%% ( <_5> when 'true' ->
%% primop 'match_fail'({'function_clause',_5})
%% -| ['compiler_generated'] )
%% end
{[V1,V2,FailVar],St1} = new_vars(3, St0),
%% Translate the body of the letrec.
Fail = {maybe_else_fail,1},
Lanno = lineno_anno(L, St1),
{Es1,St2} = maybe_match_exprs(Es0, #c_var{name=Fail}, St1),
%% Translate the 'else' clauses. Note that we must not put the clauses
%% as the top-level clauses in the fun, because all shawdowing variables
%% in a fun head will be renamed.
{Cs1,St3} = clauses(Cs0, St2),
Fc1 = fail_clause([FailVar], Lanno, c_tuple([#c_literal{val=else_clause},FailVar])),
FailCase = #icase{args=[V2],clauses=Cs1,fc=Fc1},
FailFunCs = [#iclause{pats=[V2],guard=[#c_literal{val=true}],
body=[FailCase]}],
Anno = #a{anno=[letrec_goto,no_inline|Lanno]},
Fc2 = fail_clause([FailVar], Lanno, #c_literal{val=never_fails}),
FailFun = #ifun{id=[],vars=[V1],
clauses=FailFunCs,
fc=Fc2},
%% Construct the letrec.
Letrec = #iletrec{anno=Anno,defs=[{Fail,FailFun}],body=Es1},
{Letrec,[],St3};
expr({'if',L,Cs0}, St0) ->
{Cs1,St1} = clauses(Cs0, St0),
Lanno = lineno_anno(L, St1),
Fc = fail_clause([], Lanno, #c_literal{val=if_clause}),
{#icase{anno=#a{anno=Lanno},args=[],clauses=Cs1,fc=Fc},[],St1};
expr({'case',L,E0,Cs0}, St0) ->
{E1,Eps,St1} = novars(E0, St0),
{Cs1,St2} = clauses(Cs0, St1),
{Fpat,St3} = new_var(St2),
Lanno = lineno_anno(L, St2),
Fc = fail_clause([Fpat], Lanno, c_tuple([#c_literal{val=case_clause},Fpat])),
{#icase{anno=#a{anno=Lanno},args=[E1],clauses=Cs1,fc=Fc},Eps,St3};
expr({'receive',L,Cs0}, St0) ->
{Cs1,St1} = clauses(Cs0, St0),
{#ireceive1{anno=#a{anno=lineno_anno(L, St1)},clauses=Cs1},[],St1};
expr({'receive',L,Cs0,Te0,Tes0}, St0) ->
{Te1,Teps,St1} = novars(Te0, St0),
{Tes1,St2} = exprs(Tes0, St1),
{Cs1,St3} = clauses(Cs0, St2),
{#ireceive2{anno=#a{anno=lineno_anno(L, St3)},
clauses=Cs1,timeout=Te1,action=Tes1},Teps,St3};
expr({'try',L,Es0,[],Ecs,[]}, St0) ->
%% 'try ... catch ... end'
{Es1,St1} = exprs(Es0, St0),
{V,St2} = new_var(St1), %This name should be arbitrary
{Evs,Hs,St3} = try_exception(Ecs, St2),
Lanno = lineno_anno(L, St3),
{#itry{anno=#a{anno=Lanno},args=Es1,vars=[V],body=[V],
evars=Evs,handler=Hs},
[],St3};
expr({'try',L,Es0,Cs0,Ecs,[]}, St0) ->
%% 'try ... of ... catch ... end'
{Es1,St1} = exprs(Es0, St0),
{V,St2} = new_var(St1), %This name should be arbitrary
{Cs1,St3} = clauses(Cs0, St2),
{Fpat,St4} = new_var(St3),
Lanno = lineno_anno(L, St4),
Fc = fail_clause([Fpat], Lanno,
c_tuple([#c_literal{val=try_clause},Fpat])),
{Evs,Hs,St5} = try_exception(Ecs, St4),
{#itry{anno=#a{anno=lineno_anno(L, St5)},args=Es1,
vars=[V],body=[#icase{anno=#a{anno=Lanno},args=[V],clauses=Cs1,fc=Fc}],
evars=Evs,handler=Hs},
[],St5};
expr({'try',L,Es0,[],[],As0}, St0) ->
%% 'try ... after ... end'
try_after(L, Es0, As0, St0);
expr({'try',L,Es,Cs,Ecs,As}, St0) ->
%% 'try ... [of ...] [catch ...] after ... end'
expr({'try',L,[{'try',L,Es,Cs,Ecs,[]}],[],[],As}, St0);
expr({'catch',L,E0}, St0) ->
{E1,Eps,St1} = expr(E0, St0),
Lanno = lineno_anno(L, St1),
{#icatch{anno=#a{anno=Lanno},body=Eps ++ [E1]},[],St1};
expr({'fun',L,{function,F,A}}, St0) ->
Lanno = full_anno(L, St0),
{#c_var{anno=Lanno,name={F,A}},[],St0};
expr({'fun',L,{function,M,F,A}}, St0) ->
{As,Aps,St1} = safe_list([M,F,A], St0),
Lanno = full_anno(L, St1),
{#icall{anno=#a{anno=Lanno},
module=#c_literal{val=erlang},
name=#c_literal{val=make_fun},
args=As},Aps,St1};
expr({'fun',L,{clauses,Cs}}, St) ->
fun_tq(Cs, L, St, unnamed);
expr({named_fun,L,'_',Cs}, St) ->
fun_tq(Cs, L, St, unnamed);
expr({named_fun,L,Name,Cs}, St) ->
fun_tq(Cs, L, St, {named,Name});
expr({call,L,{remote,_,M0,F0},As0}, St0) ->
{[M1,F1|As1],Aps,St1} = safe_list([M0,F0|As0], St0),
Anno = full_anno(L, St1),
case {M1,F1,As1} of
{#c_literal{val=erlang},
#c_literal{val=error},
[#c_tuple{es=[#c_literal{val=badrecord},_]}=Tuple]} ->
Fail = #iprimop{anno=#a{anno=Anno},
name=#c_literal{val=match_fail},
args=[Tuple]},
{Fail,Aps,St1};
{#c_literal{val=erlang},#c_literal{val=load_nif},[_,_]} ->
{#icall{anno=#a{anno=Anno},module=M1,name=F1,args=As1},
Aps,St1#core{load_nif=true}};
{_,_,_} ->
{#icall{anno=#a{anno=Anno},module=M1,name=F1,args=As1},Aps,St1}
end;
expr({call,Lc,{atom,Lf,F},As0}, St0) ->
{As1,Aps,St1} = safe_list(As0, St0),
Op = #c_var{anno=lineno_anno(Lf, St1),name={F,length(As1)}},
{#iapply{anno=#a{anno=lineno_anno(Lc, St1)},op=Op,args=As1},Aps,St1};
expr({call,L,FunExp,As0}, St0) ->
{Fun,Fps,St1} = safe(FunExp, St0),
{As1,Aps,St2} = safe_list(As0, St1),
Lanno = lineno_anno(L, St2),
{#iapply{anno=#a{anno=Lanno},op=Fun,args=As1},Fps ++ Aps,St2};
expr({match,L,P0,E0}, St0) ->
St1 = set_wanted(P0, St0),
case fold_match(E0, P0) of
{{sequential_match,_,_,_}=P1,E1} ->
%% Matching of an expression to more than one pattern. Example:
%%
%% #{Key := Value} = #{key := Key} = Expr
{E2,Eps1,St2} = safe(E1, St1),
St3 = St2#core{wanted=St0#core.wanted},
%% If necessary, bind the expression to a variable to ensure it is
%% only evaluted once.
{Var,Eps2,St4} =
case E2 of
#c_var{} ->
{E2,[],St3};
_ ->
{Var0,StInt} = new_var(St3),
{Var0,[#iset{var=Var0,arg=E2}],StInt}
end,
%% Rewrite to a begin/end block matching one pattern at the time
%% (using the `single_match` operator). Example:
%%
%% begin
%% V = Expr,
%% #{key := Key} = V,
%% #{Key := Value} = V
%% end
Block = blockify(L, P1, Var),
{E3,Eps3,St5} = expr({block,L,Block}, St4),
{E3,Eps1 ++ Eps2 ++ Eps3,St5};
{P0,E1} ->
%% Matching of an expression to a single pattern. Example:
%% {A,B} = Expr
{E2,Eps1,St2} = novars(E1, St1),
St3 = St2#core{wanted=St0#core.wanted},
{E3,Eps2,St4} = single_match(L, P0, E2, St3),
{E3,Eps1 ++ Eps2,St4}
end;
expr({single_match,L,P,#c_var{}=E}, St0) ->
single_match(L, P, E, St0);
expr({record_field=Op,Loc,Src0,Id,F0}, St0) ->
{Src,Aps0,St1} = safe(Src0, St0),
{F,Aps1,St2} = safe(F0, St1),
PrimOp = #iprimop{anno=#a{anno=lineno_anno(Loc, St0)},
name=#c_literal{val=Op},
args=[Src,#c_literal{val=Id},F]},
Aps = Aps0 ++ Aps1,
{PrimOp,Aps,St2};
expr({op,_,'andalso',_,_}=E0, St0) ->
{op,L,'andalso',E1,E2} = right_assoc(E0, 'andalso'),
Anno = lineno_anno(L, St0),
{#c_var{name=V0},St} = new_var(Anno, St0),
V = {var,L,V0},
False = {atom,L,false},
E = make_bool_switch(L, E1, V, E2, False),
expr(E, St);
expr({op,_,'orelse',_,_}=E0, St0) ->
{op,L,'orelse',E1,E2} = right_assoc(E0, 'orelse'),
Anno = lineno_anno(L, St0),
{#c_var{name=V0},St} = new_var(Anno, St0),
V = {var,L,V0},
True = {atom,L,true},
E = make_bool_switch(L, E1, V, True, E2),
expr(E, St);
expr({op,L,Op,A0}, St0) ->
{A1,Aps,St1} = safe(A0, St0),
LineAnno = full_anno(L, St1),
{#icall{anno=#a{anno=LineAnno}, %Must have an #a{}