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

285 行
9.9 KiB

  1. %% -*- erlang-indent-level: 4;indent-tabs-mode: nil -*-
  2. %% ex: ts=4 sw=4 et
  3. -module(rebar_prv_xref).
  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, xref).
  11. -define(DEPS, [compile]).
  12. -define(SUPPORTED_XREFS, [undefined_function_calls, undefined_functions,
  13. locals_not_used, exports_not_used,
  14. deprecated_function_calls, deprecated_functions]).
  15. %% ===================================================================
  16. %% Public API
  17. %% ===================================================================
  18. -spec init(rebar_state:t()) -> {ok, rebar_state:t()}.
  19. init(State) ->
  20. Provider = providers:create([{name, ?PROVIDER},
  21. {module, ?MODULE},
  22. {deps, ?DEPS},
  23. {bare, false},
  24. {example, "rebar3 xref"},
  25. {short_desc, short_desc()},
  26. {desc, desc()}]),
  27. State1 = rebar_state:add_provider(State, Provider),
  28. {ok, State1}.
  29. -spec do(rebar_state:t()) -> {ok, rebar_state:t()} | {error, string()}.
  30. do(State) ->
  31. code:add_pathsa(rebar_state:code_paths(State, all_deps)),
  32. XrefChecks = prepare(State),
  33. %% Run xref checks
  34. ?INFO("Running cross reference analysis...", []),
  35. XrefResults = xref_checks(XrefChecks),
  36. %% Run custom queries
  37. QueryChecks = rebar_state:get(State, xref_queries, []),
  38. QueryResults = lists:foldl(fun check_query/2, [], QueryChecks),
  39. stopped = xref:stop(xref),
  40. rebar_utils:cleanup_code_path(rebar_state:code_paths(State, default)),
  41. case XrefResults =:= [] andalso QueryResults =:= [] of
  42. true ->
  43. {ok, State};
  44. false ->
  45. ?PRV_ERROR({xref_issues, XrefResults, QueryResults})
  46. end.
  47. -spec format_error(any()) -> iolist().
  48. format_error({xref_issues, XrefResults, QueryResults}) ->
  49. lists:flatten(display_results(XrefResults, QueryResults));
  50. format_error(Reason) ->
  51. io_lib:format("~p", [Reason]).
  52. %% ===================================================================
  53. %% Internal functions
  54. %% ===================================================================
  55. short_desc() ->
  56. "Run cross reference analysis.".
  57. desc() ->
  58. io_lib:format(
  59. "~s~n"
  60. "~n"
  61. "Valid rebar.config options:~n"
  62. " ~p~n"
  63. " ~p~n"
  64. " ~p~n"
  65. " ~p~n",
  66. [short_desc(),
  67. {xref_warnings, false},
  68. {xref_extra_paths,[]},
  69. {xref_checks, [undefined_function_calls, undefined_functions,
  70. locals_not_used, exports_not_used,
  71. deprecated_function_calls, deprecated_functions]},
  72. {xref_queries,
  73. [{"(xc - uc) || (xu - x - b"
  74. " - (\"mod\":\".*foo\"/\"4\"))",[]}]}
  75. ]).
  76. -spec prepare(rebar_state:t()) -> {[file:filename()], [atom()]}.
  77. prepare(State) ->
  78. {ok, _} = xref:start(xref),
  79. ok = xref:set_library_path(xref, code_path(State)),
  80. xref:set_default(xref, [{warnings,
  81. rebar_state:get(State, xref_warnings, false)},
  82. {verbose, rebar_log:is_verbose(State)}]),
  83. [{ok, _} = xref:add_directory(xref, rebar_app_info:ebin_dir(App))
  84. || App <- rebar_state:project_apps(State)],
  85. %% Get list of xref checks we want to run
  86. ConfXrefChecks = rebar_state:get(State, xref_checks,
  87. [exports_not_used,
  88. undefined_function_calls]),
  89. XrefChecks = sets:to_list(sets:intersection(
  90. sets:from_list(?SUPPORTED_XREFS),
  91. sets:from_list(ConfXrefChecks))),
  92. XrefChecks.
  93. xref_checks(XrefChecks) ->
  94. lists:foldl(fun run_xref_check/2, [], XrefChecks).
  95. run_xref_check(XrefCheck, Acc) ->
  96. {ok, Results} = xref:analyze(xref, XrefCheck),
  97. case filter_xref_results(XrefCheck, Results) of
  98. [] ->
  99. Acc;
  100. FilterResult ->
  101. [{XrefCheck, FilterResult} | Acc]
  102. end.
  103. check_query({Query, Value}, Acc) ->
  104. {ok, Answer} = xref:q(xref, Query),
  105. case Answer =:= Value of
  106. false ->
  107. [{Query, Value, Answer} | Acc];
  108. _ ->
  109. Acc
  110. end.
  111. code_path(State) ->
  112. [P || P <- code:get_path() ++
  113. rebar_state:get(State, xref_extra_paths, []),
  114. filelib:is_dir(P)].
  115. %% Ignore behaviour functions, and explicitly marked functions
  116. %%
  117. %% Functions can be ignored by using
  118. %% -ignore_xref([{F, A}, {M, F, A}...]).
  119. get_xref_ignorelist(Mod, XrefCheck) ->
  120. %% Get ignore_xref attribute and combine them in one list
  121. Attributes =
  122. try
  123. Mod:module_info(attributes)
  124. catch
  125. _Class:_Error -> []
  126. end,
  127. IgnoreXref = keyall(ignore_xref, Attributes),
  128. BehaviourCallbacks = get_behaviour_callbacks(XrefCheck, Attributes),
  129. %% And create a flat {M,F,A} list
  130. lists:foldl(
  131. fun({F, A}, Acc) -> [{Mod,F,A} | Acc];
  132. ({M, F, A}, Acc) -> [{M,F,A} | Acc]
  133. end, [], lists:flatten([IgnoreXref, BehaviourCallbacks])).
  134. keyall(Key, List) ->
  135. lists:flatmap(fun({K, L}) when Key =:= K -> L; (_) -> [] end, List).
  136. get_behaviour_callbacks(exports_not_used, Attributes) ->
  137. [B:behaviour_info(callbacks) || B <- keyall(behaviour, Attributes)];
  138. get_behaviour_callbacks(_XrefCheck, _Attributes) ->
  139. [].
  140. parse_xref_result({_, MFAt}) -> MFAt;
  141. parse_xref_result(MFAt) -> MFAt.
  142. filter_xref_results(XrefCheck, XrefResults) ->
  143. SearchModules = lists:usort(
  144. lists:map(
  145. fun({Mt,_Ft,_At}) -> Mt;
  146. ({{Ms,_Fs,_As},{_Mt,_Ft,_At}}) -> Ms;
  147. (_) -> undefined
  148. end, XrefResults)),
  149. Ignores = lists:flatmap(fun(Module) ->
  150. get_xref_ignorelist(Module, XrefCheck)
  151. end, SearchModules),
  152. [Result || Result <- XrefResults,
  153. not lists:member(parse_xref_result(Result), Ignores)].
  154. display_results(XrefResults, QueryResults) ->
  155. [lists:map(fun display_xref_results_for_type/1, XrefResults),
  156. lists:map(fun display_query_result/1, QueryResults)].
  157. display_query_result({Query, Answer, Value}) ->
  158. io_lib:format("Query ~s~n answer ~p~n did not match ~p~n",
  159. [Query, Answer, Value]).
  160. display_xref_results_for_type({Type, XrefResults}) ->
  161. lists:map(display_xref_result_fun(Type), XrefResults).
  162. display_xref_result_fun(Type) ->
  163. fun(XrefResult) ->
  164. {Source, SMFA, TMFA} =
  165. case XrefResult of
  166. {MFASource, MFATarget} ->
  167. {format_mfa_source(MFASource),
  168. format_mfa(MFASource),
  169. format_mfa(MFATarget)};
  170. MFATarget ->
  171. {format_mfa_source(MFATarget),
  172. format_mfa(MFATarget),
  173. undefined}
  174. end,
  175. case Type of
  176. undefined_function_calls ->
  177. io_lib:format("~sWarning: ~s calls undefined function ~s (Xref)\n",
  178. [Source, SMFA, TMFA]);
  179. undefined_functions ->
  180. io_lib:format("~sWarning: ~s is undefined function (Xref)\n",
  181. [Source, SMFA]);
  182. locals_not_used ->
  183. io_lib:format("~sWarning: ~s is unused local function (Xref)\n",
  184. [Source, SMFA]);
  185. exports_not_used ->
  186. io_lib:format("~sWarning: ~s is unused export (Xref)\n",
  187. [Source, SMFA]);
  188. deprecated_function_calls ->
  189. io_lib:format("~sWarning: ~s calls deprecated function ~s (Xref)\n",
  190. [Source, SMFA, TMFA]);
  191. deprecated_functions ->
  192. io_lib:format("~sWarning: ~s is deprecated function (Xref)\n",
  193. [Source, SMFA]);
  194. Other ->
  195. io_lib:format("~sWarning: ~s - ~s xref check: ~s (Xref)\n",
  196. [Source, SMFA, TMFA, Other])
  197. end
  198. end.
  199. format_mfa({M, F, A}) ->
  200. ?FMT("~s:~s/~w", [M, F, A]).
  201. format_mfa_source(MFA) ->
  202. case find_mfa_source(MFA) of
  203. {module_not_found, function_not_found} -> "";
  204. {Source, function_not_found} -> ?FMT("~s: ", [Source]);
  205. {Source, Line} -> ?FMT("~s:~w: ", [Source, Line])
  206. end.
  207. %%
  208. %% Extract an element from a tuple, or undefined if N > tuple size
  209. %%
  210. safe_element(N, Tuple) ->
  211. case catch(element(N, Tuple)) of
  212. {'EXIT', {badarg, _}} ->
  213. undefined;
  214. Value ->
  215. Value
  216. end.
  217. %%
  218. %% Given a MFA, find the file and LOC where it's defined. Note that
  219. %% xref doesn't work if there is no abstract_code, so we can avoid
  220. %% being too paranoid here.
  221. %%
  222. find_mfa_source({M, F, A}) ->
  223. case code:get_object_code(M) of
  224. error -> {module_not_found, function_not_found};
  225. {M, Bin, _} -> find_function_source(M,F,A,Bin)
  226. end.
  227. find_function_source(M, F, A, Bin) ->
  228. AbstractCode = beam_lib:chunks(Bin, [abstract_code]),
  229. {ok, {M, [{abstract_code, {raw_abstract_v1, Code}}]}} = AbstractCode,
  230. %% Extract the original source filename from the abstract code
  231. [{attribute, 1, file, {Source, _}} | _] = Code,
  232. %% Extract the line number for a given function def
  233. Fn = [E || E <- Code,
  234. safe_element(1, E) == function,
  235. safe_element(3, E) == F,
  236. safe_element(4, E) == A],
  237. case Fn of
  238. [{function, Line, F, _, _}] -> {Source, Line};
  239. %% do not crash if functions are exported, even though they
  240. %% are not in the source.
  241. %% parameterized modules add new/1 and instance/1 for example.
  242. [] -> {Source, function_not_found}
  243. end.