25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

188 lines
6.7 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. true = 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. true = 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. lists:foreach(fun({{Source, Line}, FunStr, Target}) ->
  82. ?CONSOLE("~s:~w: Warning ~s calls undefined function ~s\n",
  83. [Source, Line, FunStr, Target])
  84. end, UndefinedCalls),
  85. ok.
  86. code_path() ->
  87. [P || P <- code:get_path(),
  88. filelib:is_dir(P)] ++ [filename:join(rebar_utils:get_cwd(), "ebin")].
  89. %%
  90. %% Ignore behaviour functions, and explicitly marked functions
  91. %%
  92. filter_away_ignored(UnusedExports) ->
  93. %% Functions can be ignored by using
  94. %% -ignore_xref([{F, A}, ...]).
  95. %% Setup a filter function that build a list of behaviour callbacks and/or
  96. %% any functions marked to ignore. We then use this list to mask any functions
  97. %% marked as unused exports by xref
  98. F = fun(Mod) ->
  99. Attrs = kf(attributes, Mod:module_info()),
  100. Ignore = kf(ignore_xref, Attrs),
  101. Callbacks = [B:behaviour_info(callbacks) || B <- kf(behaviour, Attrs)],
  102. [{Mod, F, A} || {F, A} <- Ignore ++ lists:flatten(Callbacks)]
  103. end,
  104. AttrIgnore = lists:flatten(lists:map(F, lists:usort([M || {M, _, _} <- UnusedExports]))),
  105. [X || X <- UnusedExports, not(lists:member(X, AttrIgnore))].
  106. kf(Key, List) ->
  107. case lists:keyfind(Key, 1, List) of
  108. {Key, Value} ->
  109. Value;
  110. false ->
  111. []
  112. end.
  113. display_mfas([], _Message) ->
  114. ok;
  115. display_mfas([{_Mod, Fun, Args} = MFA | Rest], Message) ->
  116. {Source, Line} = find_mfa_source(MFA),
  117. ?CONSOLE("~s:~w: Warning: function ~s/~w ~s\n", [Source, Line, Fun, Args, Message]),
  118. display_mfas(Rest, Message).
  119. format_mfa({M, F, A}) ->
  120. ?FMT("~s:~s/~w", [M, F, A]).
  121. format_fa({_M, F, A}) ->
  122. ?FMT("~s/~w", [F, A]).
  123. %%
  124. %% Extract an element from a tuple, or undefined if N > tuple size
  125. safe_element(N, Tuple) ->
  126. case catch(element(N, Tuple)) of
  127. {'EXIT', {badarg, _}} ->
  128. undefined;
  129. Value ->
  130. Value
  131. end.
  132. %%
  133. %% Extract the line number for a given function def
  134. %%
  135. abstract_code_function_line(Code, Name, Args) ->
  136. [{function, Line, Name, _, _}] = [E || E <- Code,
  137. safe_element(1, E) == function,
  138. safe_element(3, E) == Name,
  139. safe_element(4, E) == Args],
  140. Line.
  141. %%
  142. %% Extract the original source filename from the abstract code
  143. %%
  144. abstract_code_source_file(Code) ->
  145. [{attribute, 1, file, {Name, _}} | _] = Code,
  146. Name.
  147. %%
  148. %% Given a MFA, find the file and LOC where it's defined. Note that
  149. %% xref doesn't work if there is no abstract_code, so we can avoid
  150. %% being too paranoid here.
  151. %%
  152. find_mfa_source({M, F, A}) ->
  153. {M, Bin, _} = code:get_object_code(M),
  154. {ok, {M, [{abstract_code, AbstractCode}]}} = beam_lib:chunks(Bin, [abstract_code]),
  155. {raw_abstract_v1, Code} = AbstractCode,
  156. Source = abstract_code_source_file(Code),
  157. Line = abstract_code_function_line(Code, F, A),
  158. {Source, Line}.