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

201 行
7.0 KiB

14 年前
  1. %% -*- 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. {ok, _} = xref:start(xref),
  41. ok = xref:set_library_path(xref, code_path()),
  42. xref:set_default(xref, [{warnings,
  43. rebar_config:get(Config, xref_warnings, false)},
  44. {verbose, rebar_config:is_verbose()}]),
  45. {ok, _} = xref:add_directory(xref, "ebin"),
  46. %% Save the code path prior to doing anything
  47. OrigPath = code:get_path(),
  48. true = code:add_path(filename:join(rebar_utils:get_cwd(), "ebin")),
  49. %% Get list of xref checks we want to run
  50. XrefChecks = rebar_config:get(Config, xref_checks,
  51. [exports_not_used,
  52. undefined_function_calls]),
  53. %% Look for exports that are unused by anything
  54. ExportsNoWarn =
  55. case lists:member(exports_not_used, XrefChecks) of
  56. true ->
  57. check_exports_not_used();
  58. false ->
  59. true
  60. end,
  61. %% Look for calls to undefined functions
  62. UndefNoWarn =
  63. case lists:member(undefined_function_calls, XrefChecks) of
  64. true ->
  65. check_undefined_function_calls();
  66. false ->
  67. true
  68. end,
  69. %% Restore the original code path
  70. true = code:set_path(OrigPath),
  71. %% Stop xref
  72. stopped = xref:stop(xref),
  73. case lists:all(fun(NoWarn) -> NoWarn end, [ExportsNoWarn, UndefNoWarn]) of
  74. true ->
  75. ok;
  76. false ->
  77. ?FAIL
  78. end.
  79. %% ===================================================================
  80. %% Internal functions
  81. %% ===================================================================
  82. check_exports_not_used() ->
  83. {ok, UnusedExports0} = xref:analyze(xref, exports_not_used),
  84. UnusedExports = filter_away_ignored(UnusedExports0),
  85. %% Report all the unused functions
  86. display_mfas(UnusedExports, "is unused export (Xref)"),
  87. UnusedExports =:= [].
  88. check_undefined_function_calls() ->
  89. {ok, UndefinedCalls0} = xref:analyze(xref, undefined_function_calls),
  90. UndefinedCalls =
  91. [{find_mfa_source(Caller), format_fa(Caller), format_mfa(Target)}
  92. || {Caller, Target} <- UndefinedCalls0],
  93. lists:foreach(
  94. fun({{Source, Line}, FunStr, Target}) ->
  95. ?CONSOLE("~s:~w: Warning ~s calls undefined function ~s\n",
  96. [Source, Line, FunStr, Target])
  97. end, UndefinedCalls),
  98. UndefinedCalls =:= [].
  99. code_path() ->
  100. [P || P <- code:get_path(),
  101. filelib:is_dir(P)] ++ [filename:join(rebar_utils:get_cwd(), "ebin")].
  102. %%
  103. %% Ignore behaviour functions, and explicitly marked functions
  104. %%
  105. filter_away_ignored(UnusedExports) ->
  106. %% Functions can be ignored by using
  107. %% -ignore_xref([{F, A}, ...]).
  108. %% Setup a filter function that builds a list of behaviour callbacks and/or
  109. %% any functions marked to ignore. We then use this list to mask any
  110. %% functions marked as unused exports by xref
  111. F = fun(Mod) ->
  112. Attrs = kf(attributes, Mod:module_info()),
  113. Ignore = kf(ignore_xref, Attrs),
  114. Callbacks =
  115. [B:behaviour_info(callbacks) || B <- kf(behaviour, Attrs)],
  116. [{Mod, F, A} || {F, A} <- Ignore ++ lists:flatten(Callbacks)]
  117. end,
  118. AttrIgnore =
  119. lists:flatten(
  120. lists:map(F, lists:usort([M || {M, _, _} <- UnusedExports]))),
  121. [X || X <- UnusedExports, not lists:member(X, AttrIgnore)].
  122. kf(Key, List) ->
  123. case lists:keyfind(Key, 1, List) of
  124. {Key, Value} ->
  125. Value;
  126. false ->
  127. []
  128. end.
  129. display_mfas([], _Message) ->
  130. ok;
  131. display_mfas([{_Mod, Fun, Args} = MFA | Rest], Message) ->
  132. {Source, Line} = find_mfa_source(MFA),
  133. ?CONSOLE("~s:~w: Warning: function ~s/~w ~s\n",
  134. [Source, Line, Fun, Args, Message]),
  135. display_mfas(Rest, Message).
  136. format_mfa({M, F, A}) ->
  137. ?FMT("~s:~s/~w", [M, F, A]).
  138. format_fa({_M, F, A}) ->
  139. ?FMT("~s/~w", [F, A]).
  140. %%
  141. %% Extract an element from a tuple, or undefined if N > tuple size
  142. %%
  143. safe_element(N, Tuple) ->
  144. case catch(element(N, Tuple)) of
  145. {'EXIT', {badarg, _}} ->
  146. undefined;
  147. Value ->
  148. Value
  149. end.
  150. %%
  151. %% Given a MFA, find the file and LOC where it's defined. Note that
  152. %% xref doesn't work if there is no abstract_code, so we can avoid
  153. %% being too paranoid here.
  154. %%
  155. find_mfa_source({M, F, A}) ->
  156. {M, Bin, _} = code:get_object_code(M),
  157. AbstractCode = beam_lib:chunks(Bin, [abstract_code]),
  158. {ok, {M, [{abstract_code, {raw_abstract_v1, Code}}]}} = AbstractCode,
  159. %% Extract the original source filename from the abstract code
  160. [{attribute, 1, file, {Source, _}} | _] = Code,
  161. %% Extract the line number for a given function def
  162. Fn = [E || E <- Code,
  163. safe_element(1, E) == function,
  164. safe_element(3, E) == F,
  165. safe_element(4, E) == A],
  166. case Fn of
  167. [{function, Line, F, _, _}] -> {Source, Line};
  168. %% do not crash if functions are exported, even though they
  169. %% are not in the source.
  170. %% parameterized modules add new/1 and instance/1 for example.
  171. [] -> {Source, function_not_found}
  172. end.