forked from erlang/otp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdialyzer_dataflow.erl
3893 lines (3634 loc) · 129 KB
/
dialyzer_dataflow.erl
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
%% -*- erlang-indent-level: 2 -*-
%%
%% 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.
%%%-------------------------------------------------------------------
%%% File : dialyzer_dataflow.erl
%%% Author : Tobias Lindahl <[email protected]>
%%% Description :
%%%
%%% Created : 19 Apr 2005 by Tobias Lindahl <[email protected]>
%%%-------------------------------------------------------------------
-module(dialyzer_dataflow).
-export([get_fun_types/5, get_warnings/5, format_args/3]).
%% Data structure interfaces.
-export([state__add_warning/2, state__cleanup/1,
state__duplicate/1, dispose_state/1,
state__get_callgraph/1, state__get_races/1,
state__get_records/1, state__put_callgraph/2,
state__put_races/2, state__records_only/1,
state__find_function/2]).
-export_type([state/0]).
-include("dialyzer.hrl").
-import(erl_types,
[t_inf/2, t_inf/3, t_inf_lists/2, t_inf_lists/3,
t_inf_lists/3, t_is_equal/2, t_is_subtype/2, t_subtract/2,
t_sup/1, t_sup/2]).
-import(erl_types,
[any_none/1, t_any/0, t_atom/0, t_atom/1, t_atom_vals/1, t_atom_vals/2,
t_binary/0, t_boolean/0,
t_bitstr/0, t_bitstr/2, t_bitstr_concat/1, t_bitstr_match/2,
t_cons/0, t_cons/2, t_cons_hd/2, t_cons_tl/2,
t_contains_opaque/2,
t_find_opaque_mismatch/3, t_float/0, t_from_range/2, t_from_term/1,
t_fun/0, t_fun/2, t_fun_args/1, t_fun_args/2, t_fun_range/1,
t_fun_range/2, t_integer/0, t_integers/1,
t_is_any/1, t_is_atom/1, t_is_atom/2, t_is_any_atom/3,
t_is_boolean/2,
t_is_integer/2, t_is_list/1,
t_is_nil/2, t_is_none/1, t_is_none_or_unit/1,
t_is_number/2, t_is_reference/2, t_is_pid/2, t_is_port/2,
t_is_unit/1,
t_limit/2, t_list/0, t_list_elements/2,
t_maybe_improper_list/0, t_module/0,
t_none/0, t_non_neg_integer/0, t_number/0, t_number_vals/2,
t_pid/0, t_port/0, t_product/1, t_reference/0,
t_to_string/2, t_to_tlist/1,
t_tuple/0, t_tuple/1, t_tuple_args/1, t_tuple_args/2,
t_tuple_subtypes/2,
t_unit/0, t_unopaque/2,
t_map/0, t_map/1, t_is_singleton/2
]).
%%-define(DEBUG, true).
%%-define(DEBUG_PP, true).
%%-define(DEBUG_TIME, true).
-ifdef(DEBUG).
-import(erl_types, [t_to_string/1]).
-define(debug(S_, L_), io:format(S_, L_)).
-else.
-define(debug(S_, L_), ok).
-endif.
%%--------------------------------------------------------------------
-type type() :: erl_types:erl_type().
-type types() :: erl_types:type_table().
-type curr_fun() :: 'undefined' | 'top' | mfa_or_funlbl().
-define(no_arg, no_arg).
-define(TYPE_LIMIT, 3).
-define(BITS, 128).
%% Types with comment 'race' are due to dialyzer_races.erl.
-record(state, {callgraph :: dialyzer_callgraph:callgraph()
| 'undefined', % race
codeserver :: dialyzer_codeserver:codeserver()
| 'undefined', % race
envs :: env_tab()
| 'undefined', % race
fun_tab :: fun_tab()
| 'undefined', % race
fun_homes :: dict:dict(label(), mfa())
| 'undefined', % race
reachable_funs :: sets:set(label())
| 'undefined', % race
plt :: dialyzer_plt:plt()
| 'undefined', % race
opaques :: [type()]
| 'undefined', % race
races = dialyzer_races:new() :: dialyzer_races:races(),
records = dict:new() :: types(),
tree_map :: dict:dict(label(), cerl:cerl())
| 'undefined', % race
warning_mode = false :: boolean(),
warnings = [] :: [raw_warning()],
work :: {[_], [_], sets:set()}
| 'undefined', % race
module :: module(),
curr_fun :: curr_fun()
}).
-record(map, {map = maps:new() :: type_tab(),
subst = maps:new() :: subst_tab(),
modified = [] :: [Key :: term()],
modified_stack = [] :: [{[Key :: term()],reference()}],
ref = undefined :: reference() | undefined}).
-type env_tab() :: dict:dict(label(), #map{}).
-type fun_entry() :: {Args :: [type()], RetType :: type()}.
-type fun_tab() :: dict:dict('top' | label(),
{'not_handled', fun_entry()} | fun_entry()).
-type key() :: label() | cerl:cerl().
-type type_tab() :: #{key() => type()}.
-type subst_tab() :: #{key() => cerl:cerl()}.
%% Exported Types
-opaque state() :: #state{}.
%%--------------------------------------------------------------------
-type fun_types() :: orddict:orddict(label(), type()).
-spec get_warnings(cerl:c_module(), dialyzer_plt:plt(),
dialyzer_callgraph:callgraph(),
dialyzer_codeserver:codeserver(),
types()) ->
{[raw_warning()], fun_types()}.
get_warnings(Tree, Plt, Callgraph, Codeserver, Records) ->
State1 = analyze_module(Tree, Plt, Callgraph, Codeserver, Records, true),
State2 = state__renew_warnings(state__get_warnings(State1), State1),
State3 = state__get_race_warnings(State2),
{State3#state.warnings, state__all_fun_types(State3)}.
-spec get_fun_types(cerl:c_module(), dialyzer_plt:plt(),
dialyzer_callgraph:callgraph(),
dialyzer_codeserver:codeserver(),
types()) -> fun_types().
get_fun_types(Tree, Plt, Callgraph, Codeserver, Records) ->
State = analyze_module(Tree, Plt, Callgraph, Codeserver, Records, false),
state__all_fun_types(State).
%%% ===========================================================================
%%%
%%% The analysis.
%%%
%%% ===========================================================================
analyze_module(Tree, Plt, Callgraph, Codeserver, Records, GetWarnings) ->
debug_pp(Tree, false),
Module = cerl:atom_val(cerl:module_name(Tree)),
TopFun = cerl:ann_c_fun([{label, top}], [], Tree),
State = state__new(Callgraph, Codeserver, TopFun, Plt, Module, Records),
State1 = state__race_analysis(not GetWarnings, State),
State2 = analyze_loop(State1),
case GetWarnings of
true ->
State3 = state__set_warning_mode(State2),
State4 = analyze_loop(State3),
dialyzer_races:race(State4);
false ->
State2
end.
analyze_loop(State) ->
case state__get_work(State) of
none -> state__set_curr_fun(undefined, State);
{Fun, NewState0} ->
NewState1 = state__set_curr_fun(get_label(Fun), NewState0),
{ArgTypes, IsCalled} = state__get_args_and_status(Fun, NewState1),
case not IsCalled of
true ->
?debug("Not handling (not called) ~w: ~ts\n",
[NewState1#state.curr_fun,
t_to_string(t_product(ArgTypes))]),
analyze_loop(NewState1);
false ->
case state__fun_env(Fun, NewState1) of
none ->
?debug("Not handling (no env) ~w: ~ts\n",
[NewState1#state.curr_fun,
t_to_string(t_product(ArgTypes))]),
analyze_loop(NewState1);
Map ->
?debug("Handling fun ~p: ~ts\n",
[NewState1#state.curr_fun,
t_to_string(state__fun_type(Fun, NewState1))]),
Vars = cerl:fun_vars(Fun),
Map1 = enter_type_lists(Vars, ArgTypes, Map),
Body = cerl:fun_body(Fun),
FunLabel = get_label(Fun),
IsRaceAnalysisEnabled = is_race_analysis_enabled(State),
NewState3 =
case IsRaceAnalysisEnabled of
true ->
NewState2 = state__renew_curr_fun(
state__lookup_name(FunLabel, NewState1), FunLabel,
NewState1),
state__renew_race_list([], 0, NewState2);
false -> NewState1
end,
{NewState4, _Map2, BodyType} =
traverse(Body, Map1, NewState3),
?debug("Done analyzing: ~w:~ts\n",
[NewState1#state.curr_fun,
t_to_string(t_fun(ArgTypes, BodyType))]),
NewState5 =
case IsRaceAnalysisEnabled of
true -> renew_race_code(NewState4);
false -> NewState4
end,
NewState6 =
state__update_fun_entry(Fun, ArgTypes, BodyType, NewState5),
?debug("done adding stuff for ~tw\n",
[state__lookup_name(get_label(Fun), State)]),
analyze_loop(NewState6)
end
end
end.
traverse(Tree, Map, State) ->
?debug("Handling ~p\n", [cerl:type(Tree)]),
%% debug_pp_map(Map),
case cerl:type(Tree) of
alias ->
%% This only happens when checking for illegal record patterns
%% so the handling is a bit rudimentary.
traverse(cerl:alias_pat(Tree), Map, State);
apply ->
handle_apply(Tree, Map, State);
binary ->
Segs = cerl:binary_segments(Tree),
{State1, Map1, SegTypes} = traverse_list(Segs, Map, State),
{State1, Map1, t_bitstr_concat(SegTypes)};
bitstr ->
handle_bitstr(Tree, Map, State);
call ->
handle_call(Tree, Map, State);
'case' ->
handle_case(Tree, Map, State);
'catch' ->
{State1, _Map1, _} = traverse(cerl:catch_body(Tree), Map, State),
{State1, Map, t_any()};
cons ->
handle_cons(Tree, Map, State);
'fun' ->
Type = state__fun_type(Tree, State),
case state__warning_mode(State) of
true -> {State, Map, Type};
false ->
FunLbl = get_label(Tree),
State2 = state__add_work(FunLbl, State),
State3 = state__update_fun_env(Tree, Map, State2),
State4 = state__add_reachable(FunLbl, State3),
{State4, Map, Type}
end;
'let' ->
handle_let(Tree, Map, State);
letrec ->
Defs = cerl:letrec_defs(Tree),
Body = cerl:letrec_body(Tree),
%% By not including the variables in scope we can assure that we
%% will get the current function type when using the variables.
FoldFun = fun({Var, Fun}, {AccState, AccMap}) ->
{NewAccState, NewAccMap0, FunType} =
traverse(Fun, AccMap, AccState),
NewAccMap = enter_type(Var, FunType, NewAccMap0),
{NewAccState, NewAccMap}
end,
{State1, Map1} = lists:foldl(FoldFun, {State, Map}, Defs),
traverse(Body, Map1, State1);
literal ->
Type = literal_type(Tree),
{State, Map, Type};
module ->
handle_module(Tree, Map, State);
primop ->
Type =
case cerl:atom_val(cerl:primop_name(Tree)) of
match_fail -> t_none();
raise -> t_none();
bs_init_writable -> t_from_term(<<>>);
build_stacktrace -> erl_bif_types:type(erlang, build_stacktrace, 0);
Other -> erlang:error({'Unsupported primop', Other})
end,
{State, Map, Type};
'receive' ->
handle_receive(Tree, Map, State);
seq ->
Arg = cerl:seq_arg(Tree),
Body = cerl:seq_body(Tree),
{State1, Map1, ArgType} = SMA = traverse(Arg, Map, State),
case t_is_none_or_unit(ArgType) of
true ->
SMA;
false ->
State2 =
case
t_is_any(ArgType)
orelse t_is_simple(ArgType, State)
orelse is_call_to_send(Arg)
orelse is_lc_simple_list(Arg, ArgType, State)
of
true -> % do not warn in these cases
State1;
false ->
state__add_warning(State1, ?WARN_UNMATCHED_RETURN, Arg,
{unmatched_return,
[format_type(ArgType, State1)]})
end,
traverse(Body, Map1, State2)
end;
'try' ->
handle_try(Tree, Map, State);
tuple ->
handle_tuple(Tree, Map, State);
map ->
handle_map(Tree, Map, State);
values ->
Elements = cerl:values_es(Tree),
{State1, Map1, EsType} = traverse_list(Elements, Map, State),
Type = t_product(EsType),
{State1, Map1, Type};
var ->
?debug("Looking up unknown variable: ~p\n", [Tree]),
case state__lookup_type_for_letrec(Tree, State) of
error ->
LType = lookup_type(Tree, Map),
{State, Map, LType};
{ok, Type} -> {State, Map, Type}
end;
Other ->
erlang:error({'Unsupported type', Other})
end.
traverse_list(Trees, Map, State) ->
traverse_list(Trees, Map, State, []).
traverse_list([Tree|Tail], Map, State, Acc) ->
{State1, Map1, Type} = traverse(Tree, Map, State),
traverse_list(Tail, Map1, State1, [Type|Acc]);
traverse_list([], Map, State, Acc) ->
{State, Map, lists:reverse(Acc)}.
%%________________________________________
%%
%% Special instructions
%%
handle_apply(Tree, Map, State) ->
Args = cerl:apply_args(Tree),
Op = cerl:apply_op(Tree),
{State0, Map1, ArgTypes} = traverse_list(Args, Map, State),
{State1, Map2, OpType} = traverse(Op, Map1, State0),
case any_none(ArgTypes) of
true ->
{State1, Map2, t_none()};
false ->
FunList =
case state__lookup_call_site(Tree, State) of
error -> [external]; %% so that we go directly in the fallback
{ok, List} -> List
end,
FunInfoList = [{local, state__fun_info(Fun, State)} || Fun <- FunList],
case
handle_apply_or_call(FunInfoList, Args, ArgTypes, Map2, Tree, State1)
of
{had_external, State2} ->
%% Fallback: use whatever info we collected from traversing the op
%% instead of the result that has been generalized to t_any().
Arity = length(Args),
OpType1 = t_inf(OpType, t_fun(Arity, t_any())),
case t_is_none(OpType1) of
true ->
Msg = {fun_app_no_fun,
[format_cerl(Op), format_type(OpType, State2), Arity]},
State3 = state__add_warning(State2, ?WARN_FAILING_CALL,
Tree, Msg),
{State3, Map2, t_none()};
false ->
NewArgs = t_inf_lists(ArgTypes,
t_fun_args(OpType1, 'universe')),
case any_none(NewArgs) of
true ->
EnumNewArgs = lists:zip(lists:seq(1, length(NewArgs)),
NewArgs),
ArgNs = [Arg ||
{Arg, Type} <- EnumNewArgs, t_is_none(Type)],
Msg = {fun_app_args,
[ArgNs,
format_args(Args, ArgTypes, State),
format_type(OpType, State)]},
State3 = state__add_warning(State2, ?WARN_FAILING_CALL,
Tree, Msg),
{State3, enter_type(Op, OpType1, Map2), t_none()};
false ->
Map3 = enter_type_lists(Args, NewArgs, Map2),
Range0 = t_fun_range(OpType1, 'universe'),
Range =
case t_is_unit(Range0) of
true -> t_none();
false -> Range0
end,
{State2, enter_type(Op, OpType1, Map3), Range}
end
end;
Normal -> Normal
end
end.
handle_apply_or_call(FunInfoList, Args, ArgTypes, Map, Tree, State) ->
None = t_none(),
%% Call-site analysis may be inaccurate and consider more funs than those that
%% are actually possible. If all of them are incorrect, then warnings can be
%% emitted. If at least one fun is ok, however, then no warning is emitted,
%% just in case the bad ones are not really possible. The last argument is
%% used for this, with the following encoding:
%% Initial value: {none, []}
%% First fun checked: {one, <List of warns>}
%% More funs checked: {many, <List of warns>}
%% A '{one, []}' can only become '{many, []}'.
%% If at any point an fun does not add warnings, then the list is also
%% replaced with an empty list.
handle_apply_or_call(FunInfoList, Args, ArgTypes, Map, Tree, State,
[None || _ <- ArgTypes], None, false, {none, []}).
handle_apply_or_call([{local, external}|Left], Args, ArgTypes, Map, Tree, State,
_AccArgTypes, _AccRet, _HadExternal, Warns) ->
{HowMany, _} = Warns,
NewHowMany =
case HowMany of
none -> one;
_ -> many
end,
NewWarns = {NewHowMany, []},
handle_apply_or_call(Left, Args, ArgTypes, Map, Tree, State,
ArgTypes, t_any(), true, NewWarns);
handle_apply_or_call([{TypeOfApply, {Fun, Sig, Contr, LocalRet}}|Left],
Args, ArgTypes, Map, Tree,
#state{opaques = Opaques} = State,
AccArgTypes, AccRet, HadExternal, Warns) ->
Any = t_any(),
AnyArgs = [Any || _ <- Args],
GenSig = {AnyArgs, fun(_) -> t_any() end},
{CArgs, CRange} =
case Contr of
{value, #contract{args = As} = C} ->
{As, fun(FunArgs) ->
dialyzer_contracts:get_contract_return(C, FunArgs)
end};
none -> GenSig
end,
{BifArgs, BifRange} =
case TypeOfApply of
remote ->
{M, F, A} = Fun,
case erl_bif_types:is_known(M, F, A) of
true ->
BArgs = erl_bif_types:arg_types(M, F, A),
BRange =
fun(FunArgs) ->
erl_bif_types:type(M, F, A, FunArgs, Opaques)
end,
{BArgs, BRange};
false ->
GenSig
end;
local -> GenSig
end,
{SigArgs, SigRange} =
case Sig of
{value, {SR, SA}} -> {SA, SR};
none -> {AnyArgs, t_any()}
end,
?debug("--------------------------------------------------------\n", []),
?debug("Fun: ~tp\n", [state__lookup_name(Fun, State)]),
?debug("Module ~p\n", [State#state.module]),
?debug("CArgs ~ts\n", [erl_types:t_to_string(t_product(CArgs))]),
?debug("ArgTypes ~ts\n", [erl_types:t_to_string(t_product(ArgTypes))]),
?debug("BifArgs ~tp\n", [erl_types:t_to_string(t_product(BifArgs))]),
NewArgsSig = t_inf_lists(SigArgs, ArgTypes, Opaques),
?debug("SigArgs ~ts\n", [erl_types:t_to_string(t_product(SigArgs))]),
?debug("NewArgsSig: ~ts\n", [erl_types:t_to_string(t_product(NewArgsSig))]),
NewArgsContract = t_inf_lists(CArgs, ArgTypes, Opaques),
?debug("NewArgsContract: ~ts\n",
[erl_types:t_to_string(t_product(NewArgsContract))]),
NewArgsBif = t_inf_lists(BifArgs, ArgTypes, Opaques),
?debug("NewArgsBif: ~ts\n", [erl_types:t_to_string(t_product(NewArgsBif))]),
NewArgTypes0 = t_inf_lists(NewArgsSig, NewArgsContract),
NewArgTypes = t_inf_lists(NewArgTypes0, NewArgsBif, Opaques),
?debug("NewArgTypes ~ts\n", [erl_types:t_to_string(t_product(NewArgTypes))]),
?debug("\n", []),
BifRet = BifRange(NewArgTypes),
ContrRet = CRange(NewArgTypes),
RetWithoutContr = t_inf(SigRange, BifRet),
RetWithoutLocal = t_inf(ContrRet, RetWithoutContr),
?debug("RetWithoutContr: ~ts\n",[erl_types:t_to_string(RetWithoutContr)]),
?debug("RetWithoutLocal: ~ts\n", [erl_types:t_to_string(RetWithoutLocal)]),
?debug("BifRet: ~ts\n", [erl_types:t_to_string(BifRange(NewArgTypes))]),
?debug("SigRange: ~ts\n", [erl_types:t_to_string(SigRange)]),
?debug("ContrRet: ~ts\n", [erl_types:t_to_string(ContrRet)]),
?debug("LocalRet: ~ts\n", [erl_types:t_to_string(LocalRet)]),
State1 =
case is_race_analysis_enabled(State) of
true ->
Ann = cerl:get_ann(Tree),
File = get_file(Ann, State),
Line = abs(get_line(Ann)),
dialyzer_races:store_race_call(Fun, ArgTypes, Args,
{File, Line}, State);
false -> State
end,
FailedConj = any_none([RetWithoutLocal|NewArgTypes]),
IsFailBif = t_is_none(BifRange(BifArgs)),
IsFailSig = t_is_none(SigRange),
?debug("FailedConj: ~p~n", [FailedConj]),
?debug("IsFailBif: ~p~n", [IsFailBif]),
?debug("IsFailSig: ~p~n", [IsFailSig]),
State2 =
case FailedConj andalso not (IsFailBif orelse IsFailSig) of
true ->
case t_is_none(RetWithoutLocal) andalso
not t_is_none(RetWithoutContr) andalso
not any_none(NewArgTypes) of
true ->
{value, C1} = Contr,
Contract = dialyzer_contracts:contract_to_string(C1),
{M1, F1, A1} = state__lookup_name(Fun, State),
ArgStrings = format_args(Args, ArgTypes, State),
CRet = erl_types:t_to_string(RetWithoutContr),
%% This Msg will be post_processed by dialyzer_succ_typings
Msg =
{contract_range, [Contract, M1, F1, A1, ArgStrings, CRet]},
state__add_warning(State1, ?WARN_CONTRACT_RANGE, Tree, Msg);
false ->
FailedSig = any_none(NewArgsSig),
FailedContract =
any_none([CRange(NewArgsContract)|NewArgsContract]),
FailedBif = any_none([BifRange(NewArgsBif)|NewArgsBif]),
InfSig = t_inf(t_fun(SigArgs, SigRange),
t_fun(BifArgs, BifRange(BifArgs))),
FailReason =
apply_fail_reason(FailedSig, FailedBif, FailedContract),
Msg = get_apply_fail_msg(Fun, Args, ArgTypes, NewArgTypes, InfSig,
Contr, CArgs, State1, FailReason, Opaques),
WarnType = case Msg of
{call, _} -> ?WARN_FAILING_CALL;
{apply, _} -> ?WARN_FAILING_CALL;
{call_with_opaque, _} -> ?WARN_OPAQUE;
{call_without_opaque, _} -> ?WARN_OPAQUE;
{opaque_type_test, _} -> ?WARN_OPAQUE
end,
Frc = {erlang, is_record, 3} =:= state__lookup_name(Fun, State),
state__add_warning(State1, WarnType, Tree, Msg, Frc)
end;
false -> State1
end,
State3 =
case TypeOfApply of
local ->
case state__is_escaping(Fun, State2) of
true -> State2;
false ->
ForwardArgs = [t_limit(X, ?TYPE_LIMIT) || X <- ArgTypes],
forward_args(Fun, ForwardArgs, State2)
end;
remote ->
add_bif_warnings(Fun, NewArgTypes, Tree, State2)
end,
NewAccArgTypes =
case FailedConj of
true -> AccArgTypes;
false -> [t_sup(X, Y) || {X, Y} <- lists:zip(NewArgTypes, AccArgTypes)]
end,
TotalRet =
case t_is_none(LocalRet) andalso t_is_unit(RetWithoutLocal) of
true -> RetWithoutLocal;
false -> t_inf(RetWithoutLocal, LocalRet)
end,
NewAccRet = t_sup(AccRet, TotalRet),
?debug("NewAccRet: ~ts\n", [t_to_string(NewAccRet)]),
{NewWarnings, State4} = state__remove_added_warnings(State, State3),
{HowMany, OldWarnings} = Warns,
NewWarns =
case HowMany of
none -> {one, NewWarnings};
_ ->
case OldWarnings =:= [] of
true -> {many, []};
false ->
case NewWarnings =:= [] of
true -> {many, []};
false -> {many, NewWarnings ++ OldWarnings}
end
end
end,
handle_apply_or_call(Left, Args, ArgTypes, Map, Tree,
State4, NewAccArgTypes, NewAccRet, HadExternal, NewWarns);
handle_apply_or_call([], Args, _ArgTypes, Map, _Tree, State,
AccArgTypes, AccRet, HadExternal, {_, Warnings}) ->
State1 = state__add_warnings(Warnings, State),
case HadExternal of
false ->
NewMap = enter_type_lists(Args, AccArgTypes, Map),
{State1, NewMap, AccRet};
true ->
{had_external, State1}
end.
apply_fail_reason(FailedSig, FailedBif, FailedContract) ->
if
(FailedSig orelse FailedBif) andalso (not FailedContract) -> only_sig;
FailedContract andalso (not (FailedSig orelse FailedBif)) -> only_contract;
true -> both
end.
get_apply_fail_msg(Fun, Args, ArgTypes, NewArgTypes,
Sig, Contract, ContrArgs, State, FailReason, Opaques) ->
ArgStrings = format_args(Args, ArgTypes, State),
ContractInfo =
case Contract of
{value, #contract{} = C} ->
{dialyzer_contracts:is_overloaded(C),
dialyzer_contracts:contract_to_string(C)};
none -> {false, none}
end,
EnumArgTypes = lists:zip(lists:seq(1, length(NewArgTypes)), NewArgTypes),
ArgNs = [Arg || {Arg, Type} <- EnumArgTypes, t_is_none(Type)],
case state__lookup_name(Fun, State) of
{M, F, A} ->
case is_opaque_type_test_problem(Fun, Args, NewArgTypes, State) of
{yes, Arg, ArgType} ->
{opaque_type_test, [atom_to_list(F), ArgStrings,
format_arg(Arg), format_type(ArgType, State)]};
no ->
SigArgs = t_fun_args(Sig),
BadOpaque =
opaque_problems([SigArgs, ContrArgs], ArgTypes, Opaques, ArgNs),
%% In fact *both* 'call_with_opaque' and
%% 'call_without_opaque' are possible.
case lists:keyfind(decl, 1, BadOpaque) of
{decl, BadArgs} ->
%% a structured term is used where an opaque is expected
ExpectedTriples =
case FailReason of
only_sig -> expected_arg_triples(BadArgs, SigArgs, State);
_ -> expected_arg_triples(BadArgs, ContrArgs, State)
end,
{call_without_opaque, [M, F, ArgStrings, ExpectedTriples]};
false ->
case lists:keyfind(use, 1, BadOpaque) of
{use, BadArgs} ->
%% an opaque term is used where a structured term is expected
ExpectedArgs =
case FailReason of
only_sig -> SigArgs;
_ -> ContrArgs
end,
{call_with_opaque, [M, F, ArgStrings, BadArgs, ExpectedArgs]};
false ->
case
erl_bif_types:opaque_args(M, F, A, ArgTypes, Opaques)
of
[] -> %% there is a structured term clash in some argument
{call, [M, F, ArgStrings,
ArgNs, FailReason,
format_sig_args(Sig, State),
format_type(t_fun_range(Sig), State),
ContractInfo]};
Ns ->
{call_with_opaque, [M, F, ArgStrings, Ns, ContrArgs]}
end
end
end
end;
Label when is_integer(Label) ->
{apply, [ArgStrings,
ArgNs, FailReason,
format_sig_args(Sig, State),
format_type(t_fun_range(Sig), State),
ContractInfo]}
end.
%% -> [{ElementI, [ArgN]}] where [ArgN] is a non-empty list of
%% arguments containing unknown opaque types and Element is 1 or 2.
opaque_problems(ContractOrSigList, ArgTypes, Opaques, ArgNs) ->
ArgElementList = find_unknown(ContractOrSigList, ArgTypes, Opaques, ArgNs),
F = fun(1) -> decl; (2) -> use end,
[{F(ElementI), lists:usort([ArgN || {ArgN, EI} <- ArgElementList,
EI =:= ElementI])} ||
ElementI <- lists:usort([EI || {_, EI} <- ArgElementList])].
%% -> [{ArgN, ElementI}] where ElementI = 1 means there is an unknown
%% opaque type in argument ArgN of the the contract/signature,
%% and ElementI = 2 means that there is an unknown opaque type in
%% argument ArgN of the the (current) argument types.
find_unknown(ContractOrSigList, ArgTypes, Opaques, NoneArgNs) ->
ArgNs = lists:seq(1, length(ArgTypes)),
[{ArgN, ElementI} ||
ContractOrSig <- ContractOrSigList,
{E1, E2, ArgN} <- lists:zip3(ContractOrSig, ArgTypes, ArgNs),
lists:member(ArgN, NoneArgNs),
ElementI <- erl_types:t_find_unknown_opaque(E1, E2, Opaques)].
is_opaque_type_test_problem(Fun, Args, ArgTypes, State) ->
case Fun of
{erlang, FN, 1} when FN =:= is_atom; FN =:= is_boolean;
FN =:= is_binary; FN =:= is_bitstring;
FN =:= is_float; FN =:= is_function;
FN =:= is_integer; FN =:= is_list;
FN =:= is_number; FN =:= is_pid; FN =:= is_port;
FN =:= is_reference; FN =:= is_tuple;
FN =:= is_map ->
type_test_opaque_arg(Args, ArgTypes, State#state.opaques);
{erlang, FN, 2} when FN =:= is_function ->
type_test_opaque_arg(Args, ArgTypes, State#state.opaques);
_ -> no
end.
type_test_opaque_arg([], [], _Opaques) ->
no;
type_test_opaque_arg([Arg|Args], [ArgType|ArgTypes], Opaques) ->
case erl_types:t_has_opaque_subtype(ArgType, Opaques) of
true -> {yes, Arg, ArgType};
false -> type_test_opaque_arg(Args, ArgTypes, Opaques)
end.
expected_arg_triples(ArgNs, ArgTypes, State) ->
[begin
Arg = lists:nth(N, ArgTypes),
{N, Arg, format_type(Arg, State)}
end || N <- ArgNs].
add_bif_warnings({erlang, Op, 2}, [T1, T2] = Ts, Tree, State)
when Op =:= '=:='; Op =:= '==' ->
Opaques = State#state.opaques,
Inf = t_inf(T1, T2, Opaques),
case
t_is_none(Inf) andalso (not any_none(Ts))
andalso (not is_int_float_eq_comp(T1, Op, T2, Opaques))
of
true ->
%% Give priority to opaque warning (as usual).
case erl_types:t_find_unknown_opaque(T1, T2, Opaques) of
[] ->
Args = comp_format_args([], T1, Op, T2, State),
state__add_warning(State, ?WARN_MATCHING, Tree, {exact_eq, Args});
Ns ->
Args = comp_format_args(Ns, T1, Op, T2, State),
state__add_warning(State, ?WARN_OPAQUE, Tree, {opaque_eq, Args})
end;
false ->
State
end;
add_bif_warnings({erlang, Op, 2}, [T1, T2] = Ts, Tree, State)
when Op =:= '=/='; Op =:= '/=' ->
Opaques = State#state.opaques,
case
(not any_none(Ts))
andalso (not is_int_float_eq_comp(T1, Op, T2, Opaques))
of
true ->
case erl_types:t_find_unknown_opaque(T1, T2, Opaques) of
[] -> State;
Ns ->
Args = comp_format_args(Ns, T1, Op, T2, State),
state__add_warning(State, ?WARN_OPAQUE, Tree, {opaque_neq, Args})
end;
false ->
State
end;
add_bif_warnings(_, _, _, State) ->
State.
is_int_float_eq_comp(T1, Op, T2, Opaques) ->
(Op =:= '==' orelse Op =:= '/=') andalso
((erl_types:t_is_float(T1, Opaques)
andalso t_is_integer(T2, Opaques)) orelse
(t_is_integer(T1, Opaques)
andalso erl_types:t_is_float(T2, Opaques))).
comp_format_args([1|_], T1, Op, T2, State) ->
[format_type(T2, State), Op, format_type(T1, State)];
comp_format_args(_, T1, Op, T2, State) ->
[format_type(T1, State), Op, format_type(T2, State)].
%%----------------------------------------
handle_bitstr(Tree, Map, State) ->
%% Construction of binaries.
Size = cerl:bitstr_size(Tree),
Val = cerl:bitstr_val(Tree),
BitstrType = cerl:concrete(cerl:bitstr_type(Tree)),
{State1, Map1, SizeType0} = traverse(Size, Map, State),
{State2, Map2, ValType0} = traverse(Val, Map1, State1),
case cerl:bitstr_bitsize(Tree) of
BitSz when BitSz =:= all orelse BitSz =:= utf ->
ValType =
case BitSz of
all ->
true = (BitstrType =:= binary),
t_inf(ValType0, t_bitstr());
utf ->
true = lists:member(BitstrType, [utf8, utf16, utf32]),
t_inf(ValType0, t_integer())
end,
Map3 = enter_type(Val, ValType, Map2),
case t_is_none(ValType) of
true ->
Msg = {bin_construction, ["value",
format_cerl(Val), format_cerl(Tree),
format_type(ValType0, State2)]},
State3 = state__add_warning(State2, ?WARN_BIN_CONSTRUCTION, Val, Msg),
{State3, Map3, t_none()};
false ->
{State2, Map3, t_bitstr()}
end;
BitSz when is_integer(BitSz) orelse BitSz =:= any ->
SizeType = t_inf(SizeType0, t_non_neg_integer()),
ValType =
case BitstrType of
binary -> t_inf(ValType0, t_bitstr());
float -> t_inf(ValType0, t_number());
integer -> t_inf(ValType0, t_integer())
end,
case any_none([SizeType, ValType]) of
true ->
{Msg, Offending} =
case t_is_none(SizeType) of
true ->
{{bin_construction,
["size", format_cerl(Size), format_cerl(Tree),
format_type(SizeType0, State2)]},
Size};
false ->
{{bin_construction,
["value", format_cerl(Val), format_cerl(Tree),
format_type(ValType0, State2)]},
Val}
end,
State3 = state__add_warning(State2, ?WARN_BIN_CONSTRUCTION,
Offending, Msg),
{State3, Map2, t_none()};
false ->
UnitVal = cerl:concrete(cerl:bitstr_unit(Tree)),
Opaques = State2#state.opaques,
NumberVals = t_number_vals(SizeType, Opaques),
{State3, Type} =
case t_contains_opaque(SizeType, Opaques) of
true ->
Msg = {opaque_size, [format_type(SizeType, State2),
format_cerl(Size)]},
{state__add_warning(State2, ?WARN_OPAQUE, Size, Msg),
t_none()};
false ->
case NumberVals of
[OneSize] -> {State2, t_bitstr(0, OneSize * UnitVal)};
unknown -> {State2, t_bitstr()};
_ ->
MinSize = erl_types:number_min(SizeType, Opaques),
{State2, t_bitstr(UnitVal, UnitVal * MinSize)}
end
end,
Map3 = enter_type_lists([Val, Size, Tree],
[ValType, SizeType, Type], Map2),
{State3, Map3, Type}
end
end.
%%----------------------------------------
handle_call(Tree, Map, State) ->
M = cerl:call_module(Tree),
F = cerl:call_name(Tree),
Args = cerl:call_args(Tree),
MFAList = [M, F|Args],
{State1, Map1, [MType0, FType0|As]} = traverse_list(MFAList, Map, State),
Opaques = State#state.opaques,
MType = t_inf(t_module(), MType0, Opaques),
FType = t_inf(t_atom(), FType0, Opaques),
Map2 = enter_type_lists([M, F], [MType, FType], Map1),
MOpaque = t_is_none(MType) andalso (not t_is_none(MType0)),
FOpaque = t_is_none(FType) andalso (not t_is_none(FType0)),
case any_none([MType, FType|As]) of
true ->
State2 =
if
MOpaque -> % This is a problem we just detected; not a known one
MS = format_cerl(M),
case t_is_none(t_inf(t_module(), MType0)) of
true ->
Msg = {app_call, [MS, format_cerl(F),
format_args(Args, As, State1),
MS, format_type(t_module(), State1),
format_type(MType0, State1)]},
state__add_warning(State1, ?WARN_FAILING_CALL, Tree, Msg);
false ->
Msg = {opaque_call, [MS, format_cerl(F),
format_args(Args, As, State1),
MS, format_type(MType0, State1)]},
state__add_warning(State1, ?WARN_FAILING_CALL, Tree, Msg)
end;
FOpaque ->
FS = format_cerl(F),
case t_is_none(t_inf(t_atom(), FType0)) of
true ->
Msg = {app_call, [format_cerl(M), FS,
format_args(Args, As, State1),
FS, format_type(t_atom(), State1),
format_type(FType0, State1)]},
state__add_warning(State1, ?WARN_FAILING_CALL, Tree, Msg);
false ->
Msg = {opaque_call, [format_cerl(M), FS,
format_args(Args, As, State1),
FS, format_type(FType0, State1)]},
state__add_warning(State1, ?WARN_FAILING_CALL, Tree, Msg)
end;
true -> State1
end,
{State2, Map2, t_none()};
false ->
case t_is_atom(MType) of
true ->
%% XXX: Consider doing this for all combinations of MF
case {t_atom_vals(MType), t_atom_vals(FType)} of
{[MAtom], [FAtom]} ->
FunInfo = [{remote, state__fun_info({MAtom, FAtom, length(Args)},
State1)}],
handle_apply_or_call(FunInfo, Args, As, Map2, Tree, State1);
{_MAtoms, _FAtoms} ->
{State1, Map2, t_any()}
end;
false ->
{State1, Map2, t_any()}
end
end.
%%----------------------------------------
handle_case(Tree, Map, State) ->
Arg = cerl:case_arg(Tree),
Clauses = filter_match_fail(cerl:case_clauses(Tree)),
{State1, Map1, ArgType} = SMA = traverse(Arg, Map, State),
case t_is_none_or_unit(ArgType) of
true -> SMA;
false ->
State2 =
case is_race_analysis_enabled(State) of
true ->
{RaceList, RaceListSize} = get_race_list_and_size(State1),
state__renew_race_list([beg_case|RaceList],
RaceListSize + 1, State1);
false -> State1
end,
Map2 = join_maps_begin(Map1),
{MapList, State3, Type, Warns} =
handle_clauses(Clauses, Arg, ArgType, ArgType, State2,
[], Map2, [], [], []),
%% Non-Erlang BEAM languages, such as Elixir, expand language constructs
%% into case statements. In that case, we do not want to warn on
%% individual clauses not matching unless none of them can.
SupressForced = is_compiler_generated(cerl:get_ann(Tree))
andalso not (t_is_none(Type)),
State4 = lists:foldl(fun({T,R,M,F}, S) ->
state__add_warning(
S,T,R,M,F andalso (not SupressForced))
end, State3, Warns),
Map3 = join_maps_end(MapList, Map2),
debug_pp_map(Map3),
{State4, Map3, Type}
end.