You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

188 lines
6.6 KiB

  1. %% -*- tab-width: 4;erlang-indent-level: 4;indent-tabs-mode: nil -*-
  2. %% ex: ts=4 sw=4 et
  3. %% -------------------------------------------------------------------
  4. %%
  5. %% rebar: Erlang Build Tools
  6. %%
  7. %% Copyright (c) 2009 Dave Smith (dizzyd@dizzyd.com)
  8. %%
  9. %% Permission is hereby granted, free of charge, to any person obtaining a copy
  10. %% of this software and associated documentation files (the "Software"), to deal
  11. %% in the Software without restriction, including without limitation the rights
  12. %% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. %% copies of the Software, and to permit persons to whom the Software is
  14. %% furnished to do so, subject to the following conditions:
  15. %%
  16. %% The above copyright notice and this permission notice shall be included in
  17. %% all copies or substantial portions of the Software.
  18. %%
  19. %% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. %% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. %% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. %% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. %% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. %% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. %% THE SOFTWARE.
  26. %%
  27. %% -------------------------------------------------------------------
  28. %% -------------------------------------------------------------------
  29. %% This module borrows heavily from http://github.com/etnt/exrefcheck project as
  30. %% written by Torbjorn Tornkvist <tobbe@kreditor.se>, Daniel Luna and others.
  31. %% -------------------------------------------------------------------
  32. -module(rebar_xref).
  33. -include("rebar.hrl").
  34. -export([xref/2]).
  35. %% ===================================================================
  36. %% Public API
  37. %% ===================================================================
  38. xref(Config, _) ->
  39. %% Spin up xref
  40. xref:start(xref),
  41. ok = xref:set_library_path(xref, code_path()),
  42. xref:set_default(xref, [{warnings, rebar_config:get(Config, xref_warnings, false)},
  43. {verbose, rebar_config:is_verbose()}]),
  44. {ok, _} = xref:add_directory(xref, "ebin"),
  45. %% Save the code path prior to doing anything
  46. OrigPath = code:get_path(),
  47. code:add_path(filename:join(rebar_utils:get_cwd(), "ebin")),
  48. %% Get list of xref checks we want to run
  49. XrefChecks = rebar_config:get(Config, xref_checks, [exports_not_used,
  50. undefined_function_calls]),
  51. %% Look for exports that are unused by anything
  52. case lists:member(exports_not_used, XrefChecks) of
  53. true ->
  54. check_exports_not_used(Config);
  55. false ->
  56. ok
  57. end,
  58. %% Look for calls to undefined functions
  59. case lists:member(undefined_function_calls, XrefChecks) of
  60. true ->
  61. check_undefined_function_calls(Config);
  62. false ->
  63. ok
  64. end,
  65. %% Restore the original code path
  66. code:set_path(OrigPath),
  67. ok.
  68. %% ===================================================================
  69. %% Internal functions
  70. %% ===================================================================
  71. check_exports_not_used(_Config) ->
  72. {ok, UnusedExports0} = xref:analyze(xref, exports_not_used),
  73. UnusedExports = filter_away_ignored(UnusedExports0),
  74. %% Report all the unused functions
  75. display_mfas(UnusedExports, "is unused export (Xref)"),
  76. ok.
  77. check_undefined_function_calls(_Config) ->
  78. {ok, UndefinedCalls0} = xref:analyze(xref, undefined_function_calls),
  79. UndefinedCalls = [{find_mfa_source(Caller), format_fa(Caller), format_mfa(Target)} ||
  80. {Caller, Target} <- UndefinedCalls0],
  81. [?CONSOLE("~s:~w: Warning ~s calls undefined function ~s\n",
  82. [Source, Line, FunStr, Target]) ||
  83. {{Source, Line}, FunStr, Target} <- UndefinedCalls],
  84. ok.
  85. code_path() ->
  86. [P || P <- code:get_path(),
  87. filelib:is_dir(P)] ++ [filename:join(rebar_utils:get_cwd(), "ebin")].
  88. %%
  89. %% Ignore behaviour functions, and explicitly marked functions
  90. %%
  91. filter_away_ignored(UnusedExports) ->
  92. %% Functions can be ignored by using
  93. %% -ignore_xref([{F, A}, ...]).
  94. %% Setup a filter function that build a list of behaviour callbacks and/or
  95. %% any functions marked to ignore. We then use this list to mask any functions
  96. %% marked as unused exports by xref
  97. F = fun(Mod) ->
  98. Attrs = ks(attributes, Mod:module_info()),
  99. Ignore = ks(ignore_xref, Attrs),
  100. Callbacks = [B:behaviour_info(callbacks) || B <- ks(behaviour, Attrs)],
  101. [{Mod, F, A} || {F, A} <- Ignore ++ lists:flatten(Callbacks)]
  102. end,
  103. AttrIgnore = lists:flatten(lists:map(F, lists:usort([M || {M, _, _} <- UnusedExports]))),
  104. [X || X <- UnusedExports, not(lists:member(X, AttrIgnore))].
  105. ks(Key, List) ->
  106. case lists:keysearch(Key, 1, List) of
  107. {value, {Key, Value}} ->
  108. Value;
  109. false ->
  110. []
  111. end.
  112. display_mfas([], _Message) ->
  113. ok;
  114. display_mfas([{_Mod, Fun, Args} = MFA | Rest], Message) ->
  115. {Source, Line} = find_mfa_source(MFA),
  116. ?CONSOLE("~s:~w: Warning: function ~s/~w ~s\n", [Source, Line, Fun, Args, Message]),
  117. display_mfas(Rest, Message).
  118. format_mfa({M, F, A}) ->
  119. ?FMT("~s:~s/~w", [M, F, A]).
  120. format_fa({_M, F, A}) ->
  121. ?FMT("~s/~w", [F, A]).
  122. %%
  123. %% Extract an element from a tuple, or undefined if N > tuple size
  124. safe_element(N, Tuple) ->
  125. case catch(element(N, Tuple)) of
  126. {'EXIT', {badarg, _}} ->
  127. undefined;
  128. Value ->
  129. Value
  130. end.
  131. %%
  132. %% Extract the line number for a given function def
  133. %%
  134. abstract_code_function_line(Code, Name, Args) ->
  135. [{function, Line, Name, _, _}] = [E || E <- Code,
  136. safe_element(1, E) == function,
  137. safe_element(3, E) == Name,
  138. safe_element(4, E) == Args],
  139. Line.
  140. %%
  141. %% Extract the original source filename from the abstract code
  142. %%
  143. abstract_code_source_file(Code) ->
  144. [{attribute, 1, file, {Name, _}} | _] = Code,
  145. Name.
  146. %%
  147. %% Given a MFA, find the file and LOC where it's defined. Note that
  148. %% xref doesn't work if there is no abstract_code, so we can avoid
  149. %% being too paranoid here.
  150. %%
  151. find_mfa_source({M, F, A}) ->
  152. {M, Bin, _} = code:get_object_code(M),
  153. {ok, {M, [{abstract_code, AbstractCode}]}} = beam_lib:chunks(Bin, [abstract_code]),
  154. {raw_abstract_v1, Code} = AbstractCode,
  155. Source = abstract_code_source_file(Code),
  156. Line = abstract_code_function_line(Code, F, A),
  157. {Source, Line}.