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

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