您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

638 行
25 KiB

  1. %% -*- erlang-indent-level: 4;indent-tabs-mode: nil -*-
  2. %% ex: ts=4 sw=4 et
  3. -module(rebar_prv_dialyzer).
  4. -behaviour(provider).
  5. -export([init/1,
  6. do/1,
  7. format_error/1]).
  8. -include("rebar.hrl").
  9. -include_lib("providers/include/providers.hrl").
  10. -define(PROVIDER, dialyzer).
  11. -define(DEPS, [compile]).
  12. -define(PLT_PREFIX, "rebar3").
  13. %% ===================================================================
  14. %% Public API
  15. %% ===================================================================
  16. -spec init(rebar_state:t()) -> {ok, rebar_state:t()}.
  17. init(State) ->
  18. Opts = [{update_plt, $u, "update-plt", boolean, "Enable updating the PLT. Default: true"},
  19. {succ_typings, $s, "succ-typings", boolean, "Enable success typing analysis. Default: true"},
  20. {base_plt_location, undefined, "base-plt-location", string, "The location of base PLT file, defaults to $HOME/.cache/rebar3"},
  21. {plt_location, undefined, "plt-location", string, "The location of the PLT file, defaults to the profile's base directory"},
  22. {plt_prefix, undefined, "plt-prefix", string, "The prefix to the PLT file, defaults to \"rebar3\"" },
  23. {app, $a, "app", string, "Perform success typing analysis of a single application"},
  24. {base_plt_prefix, undefined, "base-plt-prefix", string, "The prefix to the base PLT file, defaults to \"rebar3\"" },
  25. {statistics, undefined, "statistics", boolean, "Print information about the progress of execution. Default: false" }],
  26. State1 = rebar_state:add_provider(State, providers:create([{name, ?PROVIDER},
  27. {module, ?MODULE},
  28. {bare, true},
  29. {deps, ?DEPS},
  30. {example, "rebar3 dialyzer"},
  31. {short_desc, short_desc()},
  32. {desc, desc()},
  33. {opts, Opts}])),
  34. {ok, State1}.
  35. desc() ->
  36. short_desc() ++ "\n"
  37. "\n"
  38. "This command will build, and keep up-to-date, a suitable PLT and will use "
  39. "it to carry out success typing analysis on the current project.\n"
  40. "\n"
  41. "The following (optional) configurations can be added to a `proplist` of "
  42. "options `dialyzer` in rebar.config:\n"
  43. "`warnings` - a list of dialyzer warnings\n"
  44. "`get_warnings` - display warnings when altering a PLT file (boolean)\n"
  45. "`plt_apps` - the strategy for determining the applications which included "
  46. "in the PLT file, `top_level_deps` to include just the direct dependencies "
  47. "or `all_deps` to include all nested dependencies "
  48. "or `all_apps` to include all project apps and nested dependencies*\n"
  49. "`plt_extra_apps` - a list of extra applications to include in the PLT "
  50. "file\n"
  51. "`plt_extra_mods` - a list of extra modules to includes in the PLT file\n"
  52. "`plt_location` - the location of the PLT file, `local` to store in the "
  53. "profile's base directory (default) or a custom directory.\n"
  54. "`plt_prefix` - the prefix to the PLT file, defaults to \"rebar3\"**\n"
  55. "`base_plt_apps` - a list of applications to include in the base "
  56. "PLT file***\n"
  57. "`base_plt_mods` - a list of modules to include in the base "
  58. "PLT file***\n"
  59. "`base_plt_location` - the location of base PLT file, `global` to store in "
  60. "$HOME/.cache/rebar3 (default) or a custom directory***\n"
  61. "`base_plt_prefix` - the prefix to the base PLT file, defaults to "
  62. "\"rebar3\"** ***\n"
  63. "`exclude_apps` - a list of applications to exclude from PLT files and "
  64. "success typing analysis, `plt_extra_mods` and `base_plt_mods` can add "
  65. "modules from excluded applications\n"
  66. "`exclude_mods` - a list of modules to exclude from PLT files and "
  67. "success typing analysis\n"
  68. "\n"
  69. "For example, to warn on unmatched returns: \n"
  70. "{dialyzer, [{warnings, [unmatched_returns]}]}.\n"
  71. "\n"
  72. "*The direct dependent applications are listed in `applications` and "
  73. "`included_applications` of their .app files.\n"
  74. "**PLT files are named \"<prefix>_<otp_release>_plt\".\n"
  75. "***The base PLT is a PLT containing the core applications often required "
  76. "for a project's PLT. One base PLT is created per OTP version and "
  77. "stored in `base_plt_location`. A base PLT is used to build project PLTs."
  78. "\n".
  79. short_desc() ->
  80. "Run the Dialyzer analyzer on the project.".
  81. -spec do(rebar_state:t()) -> {ok, rebar_state:t()} | {error, string()}.
  82. do(State) ->
  83. maybe_fix_env(),
  84. ?INFO("Dialyzer starting, this may take a while...", []),
  85. rebar_paths:unset_paths([plugins], State), % no plugins in analysis
  86. rebar_paths:set_paths([deps], State),
  87. {Args, _} = rebar_state:command_parsed_args(State),
  88. Plt = get_plt(Args, State),
  89. try
  90. do(Args, State, Plt)
  91. catch
  92. throw:{dialyzer_error, Error} ->
  93. ?PRV_ERROR({error_processing_apps, Error});
  94. throw:{dialyzer_warnings, Warnings} ->
  95. ?PRV_ERROR({dialyzer_warnings, Warnings});
  96. throw:{unknown_application, _} = Error ->
  97. ?PRV_ERROR(Error);
  98. throw:{unknown_module, _} = Error ->
  99. ?PRV_ERROR(Error);
  100. throw:{duplicate_module, _, _, _} = Error ->
  101. ?PRV_ERROR(Error);
  102. throw:{output_file_error, _, _} = Error ->
  103. ?PRV_ERROR(Error)
  104. after
  105. rebar_paths:set_paths([plugins,deps], State)
  106. end.
  107. %% This is used to workaround dialyzer quirk discussed here
  108. %% https://github.com/erlang/rebar3/pull/489#issuecomment-107953541
  109. %% Dialyzer gets default plt location wrong way by peeking HOME environment
  110. %% variable which usually is not defined on Windows.
  111. maybe_fix_env() ->
  112. os:putenv("DIALYZER_PLT", filename:join(rebar_dir:home_dir(), ".dialyzer_plt")).
  113. -spec format_error(any()) -> iolist().
  114. format_error({error_processing_apps, Error}) ->
  115. io_lib:format("Error in dialyzing apps: ~ts", [Error]);
  116. format_error({dialyzer_warnings, Warnings}) ->
  117. io_lib:format("Warnings occurred running dialyzer: ~b", [Warnings]);
  118. format_error({unknown_application, App}) ->
  119. io_lib:format("Could not find application: ~ts", [App]);
  120. format_error({unknown_module, Mod}) ->
  121. io_lib:format("Could not find module: ~ts", [Mod]);
  122. format_error({duplicate_module, Mod, File1, File2}) ->
  123. io_lib:format("Duplicates of module ~ts: ~ts ~ts", [Mod, File1, File2]);
  124. format_error({output_file_error, File, Error}) ->
  125. Error1 = file:format_error(Error),
  126. io_lib:format("Failed to write to ~ts: ~ts", [File, Error1]);
  127. format_error(Reason) ->
  128. io_lib:format("~p", [Reason]).
  129. %% Internal functions
  130. get_plt(Args, State) ->
  131. Prefix = proplists:get_value(plt_prefix, Args, get_config(State, plt_prefix, ?PLT_PREFIX)),
  132. Name = plt_name(Prefix),
  133. case proplists:get_value(plt_location, Args, get_config(State, plt_location, local)) of
  134. local ->
  135. BaseDir = rebar_dir:base_dir(State),
  136. filename:join(BaseDir, Name);
  137. Dir ->
  138. filename:join(Dir, Name)
  139. end.
  140. plt_name(Prefix) ->
  141. Prefix ++ "_" ++ rebar_utils:otp_release() ++ "_plt".
  142. do(Args, State, Plt) ->
  143. Output = get_output_file(State),
  144. case debug_info(State) of
  145. true ->
  146. ok;
  147. false ->
  148. ?WARN("Add debug_info to compiler options (erl_opts) "
  149. "if Dialyzer fails to load Core Erlang.", [])
  150. end,
  151. {PltWarnings, State1} = update_proj_plt(Args, State, Plt, Output),
  152. {Warnings, State2} = succ_typings(Args, State1, Plt, Output),
  153. case PltWarnings + Warnings of
  154. 0 ->
  155. {ok, State2};
  156. TotalWarnings ->
  157. ?INFO("Warnings written to ~ts", [rebar_dir:format_source_file_name(Output)]),
  158. throw({dialyzer_warnings, TotalWarnings})
  159. end.
  160. get_output_file(State) ->
  161. BaseDir = rebar_dir:base_dir(State),
  162. Output = filename:join(BaseDir, default_output_file()),
  163. case file:open(Output, [write]) of
  164. {ok, File} ->
  165. ok = file:close(File),
  166. Output;
  167. {error, Reason} ->
  168. throw({output_file_error, Output, Reason})
  169. end.
  170. default_output_file() ->
  171. rebar_utils:otp_release() ++ ".dialyzer_warnings".
  172. update_proj_plt(Args, State, Plt, Output) ->
  173. case proplists:get_value(update_plt, Args) of
  174. false ->
  175. {0, State};
  176. _ ->
  177. do_update_proj_plt(Args, State, Plt, Output)
  178. end.
  179. do_update_proj_plt(Args, State, Plt, Output) ->
  180. ?INFO("Updating plt...", []),
  181. Files = proj_plt_files(State),
  182. case read_plt(State, Plt) of
  183. {ok, OldFiles} ->
  184. check_plt(State, Plt, Output, OldFiles, Files);
  185. error ->
  186. build_proj_plt(Args, State, Plt, Output, Files)
  187. end.
  188. proj_plt_files(State) ->
  189. BasePltApps = base_plt_apps(State),
  190. PltApps = get_config(State, plt_extra_apps, []) ++ BasePltApps,
  191. BasePltMods = get_config(State, base_plt_mods, []),
  192. PltMods = get_config(State, plt_extra_mods, []) ++ BasePltMods,
  193. DepApps = lists:usort(proj_plt_apps(State) ++ PltApps),
  194. get_files(State, DepApps, [], PltMods, [], []).
  195. proj_apps(State) ->
  196. [ec_cnv:to_atom(rebar_app_info:name(App)) ||
  197. App <- rebar_state:project_apps(State)].
  198. proj_plt_apps(State) ->
  199. Apps = rebar_state:project_apps(State),
  200. DepApps = lists:flatmap(fun rebar_app_info:applications/1, Apps),
  201. ProjApps = proj_apps(State),
  202. case get_config(State, plt_apps, top_level_deps) of
  203. top_level_deps ->
  204. DepApps -- ProjApps;
  205. all_deps ->
  206. collect_nested_dependent_apps(DepApps) -- ProjApps;
  207. all_apps ->
  208. proj_apps(State) ++ collect_nested_dependent_apps(DepApps)
  209. end.
  210. get_files(State, Apps, SkipApps, Mods, SkipMods, ExtraDirs) ->
  211. ?INFO("Resolving files...", []),
  212. ExcludeApps = get_config(State, exclude_apps, []),
  213. Files0 = apps_files(Apps, ExcludeApps ++ SkipApps, ExtraDirs, dict:new()),
  214. BaseDir = filename:join(rebar_dir:base_dir(State), "extras"),
  215. Files1 = extras_files(BaseDir, ExtraDirs, Files0),
  216. ExcludeMods = get_config(State, exclude_mods, []),
  217. Files2 = mods_files(Mods, ExcludeMods ++ SkipMods, Files1),
  218. dict:fold(fun(_, File, Acc) -> [File | Acc] end, [], Files2).
  219. apps_files([], _, _ExtraDirs, Files) ->
  220. Files;
  221. apps_files([AppName | DepApps], SkipApps, ExtraDirs, Files) ->
  222. case lists:member(AppName, SkipApps) of
  223. true ->
  224. apps_files(DepApps, SkipApps, ExtraDirs, Files);
  225. false ->
  226. AppFiles = app_files(AppName, ExtraDirs),
  227. ?DEBUG("~ts modules: ~p", [AppName, dict:fetch_keys(AppFiles)]),
  228. Files2 = merge_files(Files, AppFiles),
  229. apps_files(DepApps, [AppName | SkipApps], ExtraDirs, Files2)
  230. end.
  231. app_files(AppName, ExtraDirs) ->
  232. case app_ebin(AppName) of
  233. {ok, EbinDir} ->
  234. merge_files(ebin_files(EbinDir), extra_files(AppName, ExtraDirs));
  235. {error, bad_name} ->
  236. throw({unknown_application, AppName})
  237. end.
  238. app_ebin(AppName) ->
  239. case code:lib_dir(AppName, ebin) of
  240. {error, bad_name} = Error ->
  241. Error;
  242. EbinDir ->
  243. check_ebin(EbinDir)
  244. end.
  245. check_ebin(EbinDir) ->
  246. case filelib:is_dir(EbinDir) of
  247. true ->
  248. {ok, EbinDir};
  249. false ->
  250. {error, bad_name}
  251. end.
  252. ebin_files(EbinDir) ->
  253. Ext = code:objfile_extension(),
  254. Wildcard = "*" ++ Ext,
  255. Files = filelib:wildcard(Wildcard, EbinDir),
  256. Store = fun(File, Mods) ->
  257. Mod = list_to_atom(filename:basename(File, Ext)),
  258. Absname = filename:join(EbinDir, File),
  259. dict:store(Mod, Absname, Mods)
  260. end,
  261. lists:foldl(Store, dict:new(), Files).
  262. extras_files(_BaseDir, [], Acc) ->
  263. Acc;
  264. extras_files(BaseDir, [ExtraDir | Rest], Acc) ->
  265. Files = ebin_files(filename:join(BaseDir, ExtraDir)),
  266. extras_files(BaseDir, Rest, merge_files(Acc, Files)).
  267. extra_files(AppName, ExtraDirs) ->
  268. lists:foldl(
  269. fun(ExtraDir, Files) ->
  270. merge_files(Files, ebin_files(filename:join(code:lib_dir(AppName), ExtraDir)))
  271. end,
  272. dict:new(),
  273. ExtraDirs
  274. ).
  275. merge_files(Files1, Files2) ->
  276. Duplicate = fun(Mod, File1, File2) ->
  277. throw({duplicate_module, Mod, File1, File2})
  278. end,
  279. dict:merge(Duplicate, Files1, Files2).
  280. mods_files(Mods, SkipMods, Files) ->
  281. Keep = fun(File) -> File end,
  282. Ensure = fun(Mod, Acc) ->
  283. case lists:member(Mod, SkipMods) of
  284. true ->
  285. Acc;
  286. false ->
  287. dict:update(Mod, Keep, mod_file(Mod), Acc)
  288. end
  289. end,
  290. Files2 = lists:foldl(Ensure, Files, Mods),
  291. lists:foldl(fun dict:erase/2, Files2, SkipMods).
  292. mod_file(Mod) ->
  293. File = atom_to_list(Mod) ++ code:objfile_extension(),
  294. case code:where_is_file(File) of
  295. non_existing -> throw({unknown_module, Mod});
  296. Absname -> Absname
  297. end.
  298. read_plt(_State, Plt) ->
  299. Vsn = dialyzer_version(),
  300. case plt_files(Plt) of
  301. {ok, Files} when Vsn < {2, 9, 0} ->
  302. % Before dialyzer-2.9 (OTP 18.3) removing a beam file from the PLT
  303. % that no longer exists would crash. Therefore force a rebuild of
  304. % PLT if any files no longer exist.
  305. read_plt_files(Plt, Files);
  306. {ok, _} = Result when Vsn >= {2, 9, 0} ->
  307. Result;
  308. {error, no_such_file} ->
  309. error;
  310. {error, not_valid} ->
  311. error;
  312. {error, read_error} ->
  313. Error = io_lib:format("Could not read the PLT file ~ts", [rebar_dir:format_source_file_name(Plt)]),
  314. throw({dialyzer_error, Error})
  315. end.
  316. plt_files(Plt) ->
  317. case dialyzer:plt_info(Plt) of
  318. {ok, Info} ->
  319. {ok, proplists:get_value(files, Info, [])};
  320. {error, _} = Error ->
  321. Error
  322. end.
  323. %% If any file no longer exists dialyzer will fail when updating the PLT.
  324. read_plt_files(Plt, Files) ->
  325. case [File || File <- Files, not filelib:is_file(File)] of
  326. [] ->
  327. {ok, Files};
  328. Missing ->
  329. ?INFO("Could not find ~p files in ~ts...", [length(Missing), rebar_dir:format_source_file_name(Plt)]),
  330. ?DEBUG("Could not find files: ~p", [Missing]),
  331. error
  332. end.
  333. check_plt(State, Plt, Output, OldList, FilesList) ->
  334. Old = sets:from_list(OldList),
  335. Files = sets:from_list(FilesList),
  336. Remove = sets:to_list(sets:subtract(Old, Files)),
  337. {RemWarnings, State1} = remove_plt(State, Plt, Output, Remove),
  338. Check = sets:to_list(sets:intersection(Files, Old)),
  339. {CheckWarnings, State2} = check_plt(State1, Plt, Output, Check),
  340. Add = sets:to_list(sets:subtract(Files, Old)),
  341. {AddWarnings, State3} = add_plt(State2, Plt, Output, Add),
  342. {RemWarnings + CheckWarnings + AddWarnings, State3}.
  343. remove_plt(State, _Plt, _Output, []) ->
  344. {0, State};
  345. remove_plt(State, Plt, Output, Files) ->
  346. ?INFO("Removing ~b files from ~ts...", [length(Files), rebar_dir:format_source_file_name(Plt)]),
  347. run_plt(State, Plt, Output, plt_remove, Files).
  348. check_plt(State, _Plt, _Output, []) ->
  349. {0, State};
  350. check_plt(State, Plt, Output, Files) ->
  351. ?INFO("Checking ~b files in ~ts...", [length(Files), rebar_dir:format_source_file_name(Plt)]),
  352. run_plt(State, Plt, Output, plt_check, Files).
  353. add_plt(State, _Plt, _Output, []) ->
  354. {0, State};
  355. add_plt(State, Plt, Output, Files) ->
  356. ?INFO("Adding ~b files to ~ts...", [length(Files), rebar_dir:format_source_file_name(Plt)]),
  357. run_plt(State, Plt, Output, plt_add, Files).
  358. run_plt(State, Plt, Output, Analysis, Files) ->
  359. GetWarnings = get_config(State, get_warnings, false),
  360. Opts = [{analysis_type, Analysis},
  361. {get_warnings, GetWarnings},
  362. {init_plt, Plt},
  363. {output_plt, Plt},
  364. {from, byte_code},
  365. {files, Files}],
  366. run_dialyzer(State, Opts, Output).
  367. build_proj_plt(Args, State, Plt, Output, Files) ->
  368. BasePlt = get_base_plt(Args, State),
  369. ?INFO("Updating base plt...", []),
  370. BaseFiles = base_plt_files(State),
  371. {BaseWarnings, State1} = update_base_plt(State, BasePlt, Output, BaseFiles),
  372. ?INFO("Copying ~ts to ~ts...", [rebar_dir:format_source_file_name(BasePlt),
  373. rebar_dir:format_source_file_name(Plt)]),
  374. _ = filelib:ensure_dir(Plt),
  375. case file:copy(BasePlt, Plt) of
  376. {ok, _} ->
  377. {CheckWarnings, State2} = check_plt(State1, Plt, Output, BaseFiles,
  378. Files),
  379. {BaseWarnings + CheckWarnings, State2};
  380. {error, Reason} ->
  381. Error = io_lib:format("Could not copy PLT from ~ts to ~ts: ~ts",
  382. [BasePlt, Plt, file:format_error(Reason)]),
  383. throw({dialyzer_error, Error})
  384. end.
  385. get_base_plt(Args, State) ->
  386. Prefix = proplists:get_value(base_plt_prefix, Args, get_config(State, base_plt_prefix, ?PLT_PREFIX)),
  387. Name = plt_name(Prefix),
  388. case proplists:get_value(base_plt_location, Args, get_config(State, base_plt_location, global)) of
  389. global ->
  390. GlobalCacheDir = rebar_dir:global_cache_dir(rebar_state:opts(State)),
  391. filename:join(GlobalCacheDir, Name);
  392. Dir ->
  393. filename:join(Dir, Name)
  394. end.
  395. base_plt_files(State) ->
  396. BasePltApps = base_plt_apps(State),
  397. BasePltMods = get_config(State, base_plt_mods, []),
  398. get_files(State, BasePltApps, [], BasePltMods, [], []).
  399. base_plt_apps(State) ->
  400. get_config(State, base_plt_apps, [erts, crypto, kernel, stdlib]).
  401. update_base_plt(State, BasePlt, Output, BaseFiles) ->
  402. case read_plt(State, BasePlt) of
  403. {ok, OldBaseFiles} ->
  404. check_plt(State, BasePlt, Output, OldBaseFiles, BaseFiles);
  405. error ->
  406. _ = filelib:ensure_dir(BasePlt),
  407. build_plt(State, BasePlt, Output, BaseFiles)
  408. end.
  409. build_plt(State, Plt, _, []) ->
  410. ?INFO("Building with no files in ~ts...", [rebar_dir:format_source_file_name(Plt)]),
  411. Opts = [{get_warnings, false},
  412. {output_plt, Plt},
  413. {apps, [erts]}],
  414. % Create a PLT with erts files and then remove erts files to be left with an
  415. % empty PLT. Dialyzer will crash when trying to build a PLT with an empty
  416. % file list.
  417. _ = dialyzer:run([{analysis_type, plt_build} | Opts]),
  418. _ = dialyzer:run([{analysis_type, plt_remove}, {init_plt, Plt} | Opts]),
  419. {0, State};
  420. build_plt(State, Plt, Output, Files) ->
  421. ?INFO("Building with ~b files in ~ts...", [length(Files), rebar_dir:format_source_file_name(Plt)]),
  422. GetWarnings = get_config(State, get_warnings, false),
  423. Opts = [{analysis_type, plt_build},
  424. {get_warnings, GetWarnings},
  425. {output_plt, Plt},
  426. {files, Files}],
  427. run_dialyzer(State, Opts, Output).
  428. succ_typings(Args, State, Plt, Output) ->
  429. case proplists:get_value(succ_typings, Args) of
  430. false ->
  431. {0, State};
  432. _ ->
  433. ?INFO("Doing success typing analysis...", []),
  434. Files = proj_files(proplists:get_value(app, Args), State),
  435. succ_typings_(State, Plt, Output, Files)
  436. end.
  437. succ_typings_(State, Plt, _, []) ->
  438. ?INFO("Analyzing no files with ~ts...", [rebar_dir:format_source_file_name(Plt)]),
  439. {0, State};
  440. succ_typings_(State, Plt, Output, Files) ->
  441. ?INFO("Analyzing ~b files with ~ts...", [length(Files), rebar_dir:format_source_file_name(Plt)]),
  442. Opts = [{analysis_type, succ_typings},
  443. {get_warnings, true},
  444. {from, byte_code},
  445. {files, Files},
  446. {init_plt, Plt}],
  447. run_dialyzer(State, Opts, Output).
  448. succ_typing_apps(undefined, ProjApps) ->
  449. ProjApps;
  450. succ_typing_apps(App, ProjApps) ->
  451. try
  452. true = lists:member(ec_cnv:to_atom(App), ProjApps),
  453. [ec_cnv:to_atom(App)]
  454. catch
  455. error:_ ->
  456. throw({unknown_application, App})
  457. end.
  458. proj_files(SingleApp, State) ->
  459. Apps = succ_typing_apps(SingleApp, proj_apps(State)),
  460. BasePltApps = get_config(State, base_plt_apps, []),
  461. PltApps = get_config(State, plt_extra_apps, []) ++ BasePltApps,
  462. BasePltMods = get_config(State, base_plt_mods, []),
  463. PltMods = get_config(State, plt_extra_mods, []) ++ BasePltMods,
  464. ExtraDirs = rebar_dir:extra_src_dirs(rebar_state:opts(State)),
  465. get_files(State, Apps, PltApps, [], PltMods, ExtraDirs).
  466. run_dialyzer(State, Opts, Output) ->
  467. {Args, _} = rebar_state:command_parsed_args(State),
  468. %% dialyzer uses command-line option `--statistics` for enabling
  469. %% additional info about progress of execution, but internally
  470. %% this option has name `timing`.
  471. %% NOTE: Option `timing` accept boolean() or 'debug', but here we support
  472. %% only boolean().
  473. Timing = proplists:get_bool(statistics, Args),
  474. %% dialyzer may return callgraph warnings when get_warnings is false
  475. case proplists:get_bool(get_warnings, Opts) of
  476. true ->
  477. WarningsList = get_config(State, warnings, []),
  478. Opts2 = [{warnings, legacy_warnings(WarningsList)},
  479. {check_plt, false},
  480. {timing, Timing} |
  481. Opts],
  482. ?DEBUG("Running dialyzer with options: ~p~n", [Opts2]),
  483. Warnings = format_warnings(rebar_state:opts(State),
  484. Output, dialyzer:run(Opts2)),
  485. {Warnings, State};
  486. false ->
  487. Opts2 = [{warnings, no_warnings()},
  488. {check_plt, false} |
  489. Opts],
  490. ?DEBUG("Running dialyzer with options: ~p~n", [Opts2]),
  491. dialyzer:run(Opts2),
  492. {0, State}
  493. end.
  494. legacy_warnings(Warnings) ->
  495. case dialyzer_version() of
  496. TupleVsn when TupleVsn < {2, 8, 0} ->
  497. [Warning || Warning <- Warnings, Warning =/= unknown];
  498. _ ->
  499. Warnings
  500. end.
  501. format_warnings(Opts, Output, Warnings) ->
  502. Warnings1 = rebar_dialyzer_format:format_warnings(Opts, Warnings),
  503. console_warnings(Warnings1),
  504. file_warnings(Output, Warnings),
  505. length(Warnings).
  506. console_warnings(Warnings) ->
  507. _ = [?CONSOLE("~ts", [Warning]) || Warning <- Warnings],
  508. ok.
  509. file_warnings(_, []) ->
  510. ok;
  511. file_warnings(Output, Warnings) ->
  512. Warnings1 = [[dialyzer:format_warning(Warning, fullpath), $\n] || Warning <- Warnings],
  513. case file:write_file(Output, Warnings1, [append]) of
  514. ok ->
  515. ok;
  516. {error, Reason} ->
  517. throw({output_file_error, Output, Reason})
  518. end.
  519. no_warnings() ->
  520. [no_return,
  521. no_unused,
  522. no_improper_lists,
  523. no_fun_app,
  524. no_match,
  525. no_opaque,
  526. no_fail_call,
  527. no_contracts,
  528. no_behaviours,
  529. no_undefined_callbacks].
  530. get_config(State, Key, Default) ->
  531. Config = rebar_state:get(State, dialyzer, []),
  532. proplists:get_value(Key, Config, Default).
  533. debug_info(State) ->
  534. Config = rebar_state:get(State, erl_opts, []),
  535. proplists:get_value(debug_info, Config, false) =/= false orelse
  536. proplists:get_value(debug_info_key, Config, false) =/= false orelse
  537. proplists:get_value(encrypt_debug_info, Config, false) =/= false.
  538. -spec collect_nested_dependent_apps([atom()]) -> [atom()].
  539. collect_nested_dependent_apps(RootApps) ->
  540. Deps = lists:foldl(fun collect_nested_dependent_apps/2, sets:new(), RootApps),
  541. sets:to_list(Deps).
  542. -spec collect_nested_dependent_apps(atom(), rebar_set()) -> rebar_set().
  543. collect_nested_dependent_apps(App, Seen) ->
  544. case sets:is_element(App, Seen) of
  545. true ->
  546. Seen;
  547. false ->
  548. Seen1 = sets:add_element(App, Seen),
  549. case code:lib_dir(App) of
  550. {error, _} ->
  551. throw({unknown_application, App});
  552. AppDir ->
  553. case rebar_app_discover:find_app(AppDir, all) of
  554. false ->
  555. throw({unknown_application, App});
  556. {true, AppInfo} ->
  557. lists:foldl(fun collect_nested_dependent_apps/2,
  558. Seen1,
  559. rebar_app_info:applications(AppInfo))
  560. end
  561. end
  562. end.
  563. dialyzer_version() ->
  564. _ = application:load(dialyzer),
  565. {ok, Vsn} = application:get_key(dialyzer, vsn),
  566. case rebar_string:lexemes(Vsn, ".") of
  567. [Major, Minor] ->
  568. version_tuple(Major, Minor, "0");
  569. [Major, Minor, Patch | _] ->
  570. version_tuple(Major, Minor, Patch)
  571. end.
  572. version_tuple(Major, Minor, Patch) ->
  573. {list_to_integer(Major), list_to_integer(Minor), list_to_integer(Patch)}.