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.

286 lines
12 KiB

пре 10 година
пре 14 година
пре 14 година
пре 14 година
пре 10 година
пре 10 година
пре 10 година
пре 10 година
пре 10 година
пре 10 година
пре 10 година
пре 10 година
пре 10 година
  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. -module(rebar_base_compiler).
  28. -include("rebar.hrl").
  29. -export([run/4,
  30. run/7,
  31. run/8,
  32. ok_tuple/2,
  33. error_tuple/4,
  34. report/1,
  35. maybe_report/1,
  36. format_error_source/2]).
  37. -type desc() :: term().
  38. -type loc() :: {line(), col()} | line().
  39. -type line() :: integer().
  40. -type col() :: integer().
  41. -type err_or_warn() :: {module(), desc()} | {loc(), module(), desc()}.
  42. -type compile_fn_ret() :: ok | {ok, [string()]} | skipped | term().
  43. -type compile_fn() :: fun((file:filename(), [{_,_}] | rebar_dict()) -> compile_fn_ret()).
  44. -type compile_fn3() :: fun((file:filename(), file:filename(), [{_,_}] | rebar_dict())
  45. -> compile_fn_ret()).
  46. -type error_tuple() :: {error, [string()], [string()]}.
  47. -export_type([compile_fn/0, compile_fn_ret/0, error_tuple/0]).
  48. %% ===================================================================
  49. %% Public API
  50. %% ===================================================================
  51. %% @doc Runs a compile job, applying `compile_fn()' to all files,
  52. %% starting with `First' files, and then `RestFiles'.
  53. -spec run(rebar_dict() | [{_,_}] , [First], [Next], compile_fn()) ->
  54. compile_fn_ret() when
  55. First :: file:filename(),
  56. Next :: file:filename().
  57. run(Config, FirstFiles, RestFiles, CompileFn) ->
  58. %% Compile the first files in sequence
  59. compile_each(FirstFiles++RestFiles, Config, CompileFn).
  60. %% @doc Runs a compile job, applying `compile_fn3()' to all files,
  61. %% starting with `First' files, and then the other content of `SourceDir'.
  62. %% Files looked for are those ending in `SourceExt'. Results of the
  63. %% compilation are put in `TargetDir' with the base file names
  64. %% postfixed with `SourceExt'.
  65. -spec run(rebar_dict() | [{_,_}] , [First], SourceDir, SourceExt,
  66. TargetDir, TargetExt, compile_fn3()) -> compile_fn_ret() when
  67. First :: file:filename(),
  68. SourceDir :: file:filename(),
  69. TargetDir :: file:filename(),
  70. SourceExt :: string(),
  71. TargetExt :: string().
  72. run(Config, FirstFiles, SourceDir, SourceExt, TargetDir, TargetExt,
  73. Compile3Fn) ->
  74. run(Config, FirstFiles, SourceDir, SourceExt, TargetDir, TargetExt,
  75. Compile3Fn, [check_last_mod]).
  76. %% @doc Runs a compile job, applying `compile_fn3()' to all files,
  77. %% starting with `First' files, and then the other content of `SourceDir'.
  78. %% Files looked for are those ending in `SourceExt'. Results of the
  79. %% compilation are put in `TargetDir' with the base file names
  80. %% postfixed with `SourceExt'.
  81. %% Additional compile options can be passed in the last argument as
  82. %% a proplist.
  83. -spec run(rebar_dict() | [{_,_}] , [First], SourceDir, SourceExt,
  84. TargetDir, TargetExt, compile_fn3(), [term()]) -> compile_fn_ret() when
  85. First :: file:filename(),
  86. SourceDir :: file:filename(),
  87. TargetDir :: file:filename(),
  88. SourceExt :: string(),
  89. TargetExt :: string().
  90. run(Config, FirstFiles, SourceDir, SourceExt0, TargetDir, TargetExt,
  91. Compile3Fn, Opts) ->
  92. %% Convert simple extension to proper regex.
  93. %% If the extension has a leading dot (e.g.: `.peg')
  94. %% we escape it.
  95. %% Otherwise, if the extension doesn't have a leading dot
  96. %% we add it ourselves (e.g.: `peg' -> `.peg')
  97. SourceExt = case SourceExt0 of
  98. [$.|_Ext] -> SourceExt0;
  99. _ -> [$.] ++ SourceExt0
  100. end,
  101. SourceExtRe = "^(?!\\._).*\\" ++ SourceExt ++ [$$],
  102. Recursive = proplists:get_value(recursive, Opts, true),
  103. %% Find all possible source files
  104. FoundFiles = rebar_utils:find_files(SourceDir, SourceExtRe, Recursive),
  105. %% Remove first files from found files
  106. RestFiles = [Source || Source <- FoundFiles,
  107. not lists:member(Source, FirstFiles)],
  108. %% Check opts for flag indicating that compile should check lastmod
  109. CheckLastMod = proplists:get_bool(check_last_mod, Opts),
  110. run(Config, FirstFiles, RestFiles,
  111. fun(S, C) ->
  112. Target = target_file(S, SourceExt,
  113. TargetDir, TargetExt),
  114. simple_compile_wrapper(S, Target, Compile3Fn, C, CheckLastMod)
  115. end).
  116. %% @doc Format good compiler results with warnings to work with
  117. %% module internals. Assumes that warnings are not treated as errors.
  118. -spec ok_tuple(file:filename(), [string()]) -> {ok, [string()]}.
  119. ok_tuple(Source, Ws) ->
  120. {ok, format_warnings(Source, Ws)}.
  121. %% @doc format error and warning strings for a given source file
  122. %% according to user preferences.
  123. -spec error_tuple(file:filename(), [Err], [Warn], rebar_dict() | [{_,_}]) ->
  124. error_tuple() when
  125. Err :: string(),
  126. Warn :: string().
  127. error_tuple(Source, Es, Ws, Opts) ->
  128. {error, format_errors(Source, Es),
  129. format_warnings(Source, Ws, Opts)}.
  130. %% @doc from a given path, and based on the user-provided options,
  131. %% format the file path according to the preferences.
  132. -spec format_error_source(file:filename(), rebar_dict() | [{_,_}]) ->
  133. file:filename().
  134. format_error_source(Path, Opts) ->
  135. rebar_dir:format_source_file_name(Path, Opts).
  136. %% ===================================================================
  137. %% Internal functions
  138. %% ===================================================================
  139. %% @private if a check for last modifications is required, do the verification
  140. %% and possibly skip the compile job.
  141. -spec simple_compile_wrapper(Source, Target, compile_fn3(), [{_,_}] | rebar_dict(), boolean()) -> compile_fn_ret() when
  142. Source :: file:filename(),
  143. Target :: file:filename().
  144. simple_compile_wrapper(Source, Target, Compile3Fn, Config, false) ->
  145. Compile3Fn(Source, Target, Config);
  146. simple_compile_wrapper(Source, Target, Compile3Fn, Config, true) ->
  147. case filelib:last_modified(Target) < filelib:last_modified(Source) of
  148. true ->
  149. Compile3Fn(Source, Target, Config);
  150. false ->
  151. skipped
  152. end.
  153. %% @private take a basic source set of file fragments and a target location,
  154. %% create a file path and name for a compile artifact.
  155. -spec target_file(SourceFile, SourceExt, TargetDir, TargetExt) -> File when
  156. SourceFile :: file:filename(),
  157. TargetDir :: file:filename(),
  158. SourceExt :: string(),
  159. TargetExt :: string(),
  160. File :: file:filename().
  161. target_file(SourceFile, SourceExt, TargetDir, TargetExt) ->
  162. %% BaseFile = remove_common_path(SourceFile, SourceDir),
  163. filename:join([TargetDir, filename:basename(SourceFile, SourceExt) ++ TargetExt]).
  164. %% @private runs the compile function `CompileFn' on every file
  165. %% passed internally, along with the related project configuration.
  166. %% If any errors are encountered, they're reported to stdout.
  167. -spec compile_each([file:filename()], Config, CompileFn) -> Ret | no_return() when
  168. Config :: [{_,_}] | rebar_dict(),
  169. CompileFn :: compile_fn(),
  170. Ret :: compile_fn_ret().
  171. compile_each([], _Config, _CompileFn) ->
  172. ok;
  173. compile_each([Source | Rest], Config, CompileFn) ->
  174. case CompileFn(Source, Config) of
  175. ok ->
  176. ?DEBUG("~tsCompiled ~ts", [rebar_utils:indent(1), filename:basename(Source)]);
  177. {ok, Warnings} ->
  178. report(Warnings),
  179. ?DEBUG("~tsCompiled ~ts", [rebar_utils:indent(1), filename:basename(Source)]);
  180. skipped ->
  181. ?DEBUG("~tsSkipped ~ts", [rebar_utils:indent(1), filename:basename(Source)]);
  182. Error ->
  183. NewSource = format_error_source(Source, Config),
  184. ?ERROR("Compiling ~ts failed", [NewSource]),
  185. maybe_report(Error),
  186. ?DEBUG("Compilation failed: ~p", [Error]),
  187. ?ABORT
  188. end,
  189. compile_each(Rest, Config, CompileFn).
  190. %% @private Formats and returns errors ready to be output.
  191. -spec format_errors(string(), [err_or_warn()]) -> [string()].
  192. format_errors(Source, Errors) ->
  193. format_errors(Source, "", Errors).
  194. %% @private Formats and returns warning strings ready to be output.
  195. -spec format_warnings(string(), [err_or_warn()]) -> [string()].
  196. format_warnings(Source, Warnings) ->
  197. format_warnings(Source, Warnings, []).
  198. %% @private Formats and returns warnings; chooses the distinct format they
  199. %% may have based on whether `warnings_as_errors' option is on.
  200. -spec format_warnings(string(), [err_or_warn()], rebar_dict() | [{_,_}]) -> [string()].
  201. format_warnings(Source, Warnings, Opts) ->
  202. %% `Opts' can be passed in both as a list or a dictionary depending
  203. %% on whether the first call to rebar_erlc_compiler was done with
  204. %% the type `rebar_dict()' or `rebar_state:t()'.
  205. LookupFn = if is_list(Opts) -> fun lists:member/2
  206. ; true -> fun dict:is_key/2
  207. end,
  208. Prefix = case LookupFn(warnings_as_errors, Opts) of
  209. true -> "";
  210. false -> "Warning: "
  211. end,
  212. format_errors(Source, Prefix, Warnings).
  213. %% @private output compiler errors if they're judged to be reportable.
  214. -spec maybe_report(Reportable | term()) -> ok when
  215. Reportable :: {{error, error_tuple()}, Source} | error_tuple() | ErrProps,
  216. ErrProps :: [{error, string()} | Source, ...],
  217. Source :: {source, string()}.
  218. maybe_report({{error, {error, _Es, _Ws}=ErrorsAndWarnings}, {source, _}}) ->
  219. maybe_report(ErrorsAndWarnings);
  220. maybe_report([{error, E}, {source, S}]) ->
  221. report(["unexpected error compiling " ++ S, io_lib:fwrite("~n~p", [E])]);
  222. maybe_report({error, Es, Ws}) ->
  223. report(Es),
  224. report(Ws);
  225. maybe_report(_) ->
  226. ok.
  227. %% @private Outputs a bunch of strings, including a newline
  228. -spec report([string()]) -> ok.
  229. report(Messages) ->
  230. lists:foreach(fun(Msg) -> io:format("~ts~n", [Msg]) end, Messages).
  231. %% private format compiler errors into proper outputtable strings
  232. -spec format_errors(_, Extra, [err_or_warn()]) -> [string()] when
  233. Extra :: string().
  234. format_errors(_MainSource, Extra, Errors) ->
  235. [[format_error(Source, Extra, Desc) || Desc <- Descs]
  236. || {Source, Descs} <- Errors].
  237. %% @private format compiler errors into proper outputtable strings
  238. -spec format_error(file:filename(), Extra, err_or_warn()) -> string() when
  239. Extra :: string().
  240. format_error(Source, Extra, {Line, Mod=epp, Desc={include,lib,File}}) ->
  241. %% Special case for include file errors, overtaking the default one
  242. BaseDesc = Mod:format_error(Desc),
  243. Friendly = case filename:split(File) of
  244. [Lib, "include", _] ->
  245. io_lib:format("; Make sure ~s is in your app "
  246. "file's 'applications' list", [Lib]);
  247. _ ->
  248. ""
  249. end,
  250. FriendlyDesc = BaseDesc ++ Friendly,
  251. ?FMT("~ts:~w: ~ts~ts~n", [Source, Line, Extra, FriendlyDesc]);
  252. format_error(Source, Extra, {{Line, Column}, Mod, Desc}) ->
  253. ErrorDesc = Mod:format_error(Desc),
  254. ?FMT("~ts:~w:~w: ~ts~ts~n", [Source, Line, Column, Extra, ErrorDesc]);
  255. format_error(Source, Extra, {Line, Mod, Desc}) ->
  256. ErrorDesc = Mod:format_error(Desc),
  257. ?FMT("~ts:~w: ~ts~ts~n", [Source, Line, Extra, ErrorDesc]);
  258. format_error(Source, Extra, {Mod, Desc}) ->
  259. ErrorDesc = Mod:format_error(Desc),
  260. ?FMT("~ts: ~ts~ts~n", [Source, Extra, ErrorDesc]).