./ct_report/coverage/dynamic_compile.COVER.html

1 %% Copyright (c) 2007
2 %% Mats Cronqvist <mats.cronqvist@ericsson.com>
3 %% Chris Newcombe <chris.newcombe@gmail.com>
4 %% Jacob Vorreuter <jacob.vorreuter@gmail.com>
5 %%
6 %% Permission is hereby granted, free of charge, to any person
7 %% obtaining a copy of this software and associated documentation
8 %% files (the "Software"), to deal in the Software without
9 %% restriction, including without limitation the rights to use,
10 %% copy, modify, merge, publish, distribute, sublicense, and/or sell
11 %% copies of the Software, and to permit persons to whom the
12 %% Software is furnished to do so, subject to the following
13 %% conditions:
14 %%
15 %% The above copyright notice and this permission notice shall be
16 %% included in all copies or substantial portions of the Software.
17 %%
18 %% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
19 %% EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
20 %% OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
21 %% NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
22 %% HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
23 %% WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
24 %% FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
25 %% OTHER DEALINGS IN THE SOFTWARE.
26
27 %%%-------------------------------------------------------------------
28 %%% File : dynamic_compile.erl
29 %%% Description :
30 %%% Authors : Mats Cronqvist <mats.cronqvist@ericsson.com>
31 %%% Chris Newcombe <chris.newcombe@gmail.com>
32 %%% Jacob Vorreuter <jacob.vorreuter@gmail.com>
33 %%% TODO :
34 %%% - add support for limit include-file depth (and prevent circular references)
35 %%% prevent circular macro expansion set FILE correctly when -module() is found
36 %%% -include_lib support $ENVVAR in include filenames
37 %%% substitute-stringize (??MACRO)
38 %%% -undef/-ifdef/-ifndef/-else/-endif
39 %%% -file(File, Line)
40 %%%-------------------------------------------------------------------
41 -module(dynamic_compile).
42
43 %% API
44 -export([from_string/1, from_string/2]).
45
46 -ignore_xref([from_string/2]).
47
48 -import(lists, [reverse/1, keyreplace/4]).
49
50 -type macro_dict() :: dict:dict(term(), term()).
51
52 %%====================================================================
53 %% API
54 %%====================================================================
55
56 %% @doc Returns a binary that can be used with
57 %% code:load_binary(Module, ModuleFilenameForInternalRecords, Binary).
58 -spec from_string('eof' | string()) -> {_, binary()}.
59 from_string(CodeStr) ->
60 6 from_string(CodeStr, []).
61
62 %% @doc takes Options as for compile:forms/2
63 -spec from_string('eof' | string(), [any()]) -> {_, binary()}.
64 from_string(CodeStr, CompileFormsOptions) ->
65 %% Initialise the macro dictionary with the default predefined macros,
66 %% (adapted from epp.erl:predef_macros/1
67 6 Filename = "compiled_from_string",
68 %%Machine = list_to_atom(erlang:system_info(machine)),
69 6 Ms0 = dict:new(),
70 % Ms1 = dict:store('FILE', {[], "compiled_from_string"}, Ms0),
71 % Ms2 = dict:store('LINE', {[], 1}, Ms1), % actually we might add special code for this
72 % Ms3 = dict:store('MODULE', {[], undefined}, Ms2),
73 % Ms4 = dict:store('MODULE_STRING', {[], undefined}, Ms3),
74 % Ms5 = dict:store('MACHINE', {[], Machine}, Ms4),
75 % InitMD = dict:store(Machine, {[], true}, Ms5),
76 6 InitMD = Ms0,
77
78 %% From the docs for compile:forms:
79 %% When encountering an -include or -include_dir directive, the compiler searches for header files in the following directories:
80 %% 1. ".", the current working directory of the file server;
81 %% 2. the base name of the compiled file;
82 %% 3. the directories specified using the i option. The directory specified last is searched first.
83 %% In this case, #2 is meaningless.
84 6 IncludeSearchPath = ["." | reverse([Dir || {i, Dir} <- CompileFormsOptions])],
85 6 {RevForms, _OutMacroDict} = scan_and_parse(CodeStr, Filename, 1, [], InitMD, IncludeSearchPath),
86 6 Forms = reverse(RevForms),
87
88 %% note: 'binary' is forced as an implicit option, whether it is provided or not.
89 6 case compile:forms(Forms, CompileFormsOptions) of
90 {ok, ModuleName, CompiledCodeBinary} when is_binary(CompiledCodeBinary) ->
91 6 {ModuleName, CompiledCodeBinary};
92 {ok, ModuleName, CompiledCodeBinary, []} when is_binary(CompiledCodeBinary) -> % empty warnings list
93
:-(
{ModuleName, CompiledCodeBinary};
94 {ok, _ModuleName, _CompiledCodeBinary, Warnings} ->
95
:-(
throw({?MODULE, warnings, Warnings});
96 Other ->
97
:-(
throw({?MODULE, compile_forms, Other})
98 end.
99
100 %%====================================================================
101 %% Internal functions
102 %%====================================================================
103
104 %% @doc Code from Mats Cronqvist<br/>
105 %% See http://www.erlang.org/pipermail/erlang-questions/2007-March/025507.html
106 %% 'scan_and_parse'
107 %% basically we call the OTP scanner and parser (erl_scan and
108 %% erl_parse) line-by-line, but check each scanned line for (or
109 %% definitions of) macros before parsing. returns {ReverseForms, FinalMacroDict}
110 %% @private
111 -spec scan_and_parse('eof' | string(),
112 _CurrFilename :: file:name(),
113 _CurrLine :: integer() | {integer(), pos_integer()},
114 RevForms :: [any()],
115 MacroDict :: macro_dict(),
116 _IncludeSearchPath :: [file:name()]) -> {[any()], macro_dict()}.
117 scan_and_parse([], _CurrFilename, _CurrLine, RevForms, MacroDict, _IncludeSearchPath) ->
118 6 {RevForms, MacroDict};
119 scan_and_parse(RemainingText, CurrFilename, CurrLine, RevForms, MacroDict, IncludeSearchPath) ->
120 130 case scanner(RemainingText, CurrLine, MacroDict) of
121 {tokens, NLine, NRemainingText, Toks} ->
122 127 {ok, Form} = erl_parse:parse_form(Toks),
123 127 scan_and_parse(NRemainingText, CurrFilename, NLine, [Form | RevForms], MacroDict, IncludeSearchPath);
124 {macro, NLine, NRemainingText, NMacroDict} ->
125
:-(
scan_and_parse(NRemainingText, CurrFilename, NLine, RevForms, NMacroDict, IncludeSearchPath);
126 {include, NLine, NRemainingText, IncludeFilename} ->
127
:-(
IncludeFileRemainingTextents = read_include_file(IncludeFilename, IncludeSearchPath),
128 %%io:format("include file ~p contents: ~n~p~nRemainingText = ~p~n", [IncludeFilename, IncludeFileRemainingTextents, RemainingText]),
129 %% Modify the FILE macro to reflect the filename
130 %%IncludeMacroDict = dict:store('FILE', {[], IncludeFilename}, MacroDict),
131
:-(
IncludeMacroDict = MacroDict,
132
133 %% Process the header file (inc. any nested header files)
134
:-(
{RevIncludeForms, IncludedMacroDict} = scan_and_parse(IncludeFileRemainingTextents, IncludeFilename, 1, [], IncludeMacroDict, IncludeSearchPath),
135 %io:format("include file results = ~p~n", [R]),
136 %% Restore the FILE macro in the NEW MacroDict (so we keep any macros defined in the header file)
137 %%NMacroDict = dict:store('FILE', {[], CurrFilename}, IncludedMacroDict),
138
:-(
NMacroDict = IncludedMacroDict,
139
140 %% Continue with the original file
141
:-(
scan_and_parse(NRemainingText, CurrFilename, NLine, RevIncludeForms ++ RevForms, NMacroDict, IncludeSearchPath);
142 done ->
143 3 scan_and_parse([], CurrFilename, CurrLine, RevForms, MacroDict, IncludeSearchPath)
144 end.
145
146 %% @private
147 -spec scanner(Text :: 'eof' | string(),
148 Line :: integer() | {integer(), pos_integer()},
149 MacroDict :: macro_dict()) ->
150 'done'
151 | {'include', integer() | {integer(), pos_integer()}, 'eof' | string(), _}
152 | {'macro', integer() | {integer(), pos_integer()}, 'eof' | string(), macro_dict()}
153 | {'tokens', integer() | {integer(), pos_integer()}, 'eof' | string(), [any()]}.
154 scanner(Text, Line, MacroDict) ->
155 130 case erl_scan:tokens([], Text, Line) of
156 {done, {ok, Toks, NLine}, LeftOverChars} ->
157 127 case pre_proc(Toks, MacroDict) of
158 127 {tokens, NToks} -> {tokens, NLine, LeftOverChars, NToks};
159
:-(
{macro, NMacroDict} -> {macro, NLine, LeftOverChars, NMacroDict};
160
:-(
{include, Filename} -> {include, NLine, LeftOverChars, Filename}
161 end;
162 {more, _Continuation} ->
163 %% This is supposed to mean "term is not yet complete" (i.e. a '.' has
164 %% not been reached yet).
165 %% However, for some bizarre reason we also get this if there is a comment after the final '.' in a file.
166 %% So we check to see if Text only consists of comments.
167 3 case is_only_comments(Text) of
168 true ->
169 3 done;
170 false ->
171
:-(
throw({incomplete_term, Text, Line})
172 end
173 end.
174
175 %% @private
176 -spec is_only_comments('eof' | string()) -> boolean().
177 3 is_only_comments(Text) -> is_only_comments(Text, not_in_comment).
178
179 %% @private
180 -spec is_only_comments('eof' | string(), 'in_comment' | 'not_in_comment') -> boolean().
181 3 is_only_comments([], _) -> true;
182 15 is_only_comments([$ |T], not_in_comment) -> is_only_comments(T, not_in_comment); % skipping whitspace outside of comment
183
:-(
is_only_comments([$\t |T], not_in_comment) -> is_only_comments(T, not_in_comment); % skipping whitspace outside of comment
184
:-(
is_only_comments([$\n |T], not_in_comment) -> is_only_comments(T, not_in_comment); % skipping whitspace outside of comment
185
:-(
is_only_comments([$% |T], not_in_comment) -> is_only_comments(T, in_comment); % found start of a comment
186
:-(
is_only_comments(_, not_in_comment) -> false;
187 % found any significant char NOT in a comment
188
:-(
is_only_comments([$\n |T], in_comment) -> is_only_comments(T, not_in_comment); % found end of a comment
189
:-(
is_only_comments([_ |T], in_comment) -> is_only_comments(T, in_comment). % skipping over in-comment chars
190
191 %% @doc 'pre-proc'
192 %% have to implement a subset of the pre-processor, since epp insists
193 %% on running on a file. Only handles 2 cases;
194 %% -define(MACRO, something).
195 %% -define(MACRO(VAR1, VARN), {stuff, VAR1, more, stuff, VARN, extra, stuff}).
196 %% @private
197 -spec pre_proc([{_, _} | {_, _, _}], macro_dict()) -> {'include', _} | {'macro', macro_dict()} | {'tokens', [any()]}.
198 pre_proc([{'-', _}, {atom, _, define}, {'(', _}, {_, _, Name}|DefToks], MacroDict) ->
199
:-(
false = dict:is_key(Name, MacroDict),
200
:-(
case DefToks of
201 [{', ', _} | Macro] ->
202
:-(
{macro, dict:store(Name, {[], macro_body_def(Macro, [])}, MacroDict)};
203 [{'(', _} | Macro] ->
204
:-(
{macro, dict:store(Name, macro_params_body_def(Macro, []), MacroDict)}
205 end;
206 pre_proc([{'-', _}, {atom, _, include}, {'(', _}, {string, _, Filename}, {')', _}, {dot, _}], _MacroDict) ->
207
:-(
{include, Filename};
208 pre_proc(Toks, MacroDict) ->
209 127 {tokens, subst_macros(Toks, MacroDict)}.
210
211 %% @private
212 -spec macro_params_body_def(Tokens :: [{_, _} | {_, _, _}, ...],
213 RevParams :: [any()]
214 ) -> {[any()], [{_, _} | {_, _, _}]}.
215 macro_params_body_def([{')', _}, {', ', _} | Toks], RevParams) ->
216
:-(
{reverse(RevParams), macro_body_def(Toks, [])};
217 macro_params_body_def([{var, _, Param} | Toks], RevParams) ->
218
:-(
macro_params_body_def(Toks, [Param | RevParams]);
219 macro_params_body_def([{', ', _}, {var, _, Param} | Toks], RevParams) ->
220
:-(
macro_params_body_def(Toks, [Param | RevParams]).
221
222 %% @private
223 -spec macro_body_def(Tokens :: [{_, _} | {_, _, _}, ...],
224 RevMacroBodyTokens :: [{_, _} | {_, _, _}]
225 ) -> [{_, _} | {_, _, _}].
226 macro_body_def([{')', _}, {dot, _}], RevMacroBodyToks) ->
227
:-(
reverse(RevMacroBodyToks);
228 macro_body_def([Tok|Toks], RevMacroBodyToks) ->
229
:-(
macro_body_def(Toks, [Tok | RevMacroBodyToks]).
230
231 %% @private
232 -spec subst_macros(Toks :: [{_, _} | {_, _, _}], MacroDict :: macro_dict()) -> [any()].
233 subst_macros(Toks, MacroDict) ->
234 127 reverse(subst_macros_rev(Toks, MacroDict, [])).
235
236 %% @doc Returns a reversed list of tokens
237 %% @private
238 -spec subst_macros_rev(Tokens :: maybe_improper_list(),
239 MacroDict :: macro_dict(),
240 RevOutToks :: [any()]) -> [any()].
241 subst_macros_rev([{'?', _}, {_, LineNum, 'LINE'} | Toks], MacroDict, RevOutToks) ->
242 %% special-case for ?LINE, to avoid creating a new MacroDict for every line in the source file
243
:-(
subst_macros_rev(Toks, MacroDict, [{integer, LineNum, LineNum}] ++ RevOutToks);
244 subst_macros_rev([{'?', _}, {_, _, Name}, {'(', _} = Paren | Toks], MacroDict, RevOutToks) ->
245
:-(
case dict:fetch(Name, MacroDict) of
246 {[], MacroValue} ->
247 %% This macro does not have any vars, so ignore the fact that the invocation is followed by "(...stuff"
248 %% Recursively expand any macro calls inside this macro's value
249 %% TODO: avoid infinite expansion due to circular references (even indirect ones)
250
:-(
RevExpandedOtherMacrosToks = subst_macros_rev(MacroValue, MacroDict, []),
251
:-(
subst_macros_rev([Paren|Toks], MacroDict, RevExpandedOtherMacrosToks ++ RevOutToks);
252 ParamsAndBody ->
253 %% This macro does have vars.
254 %% Collect all of the passe arguments, in an ordered list
255
:-(
{NToks, Arguments} = subst_macros_get_args(Toks, []),
256 %% Expand the varibles
257
:-(
ExpandedParamsToks = subst_macros_subst_args_for_vars(ParamsAndBody, Arguments),
258 %% Recursively expand any macro calls inside this macro's value
259 %% TODO: avoid infinite expansion due to circular references (even indirect ones)
260
:-(
RevExpandedOtherMacrosToks = subst_macros_rev(ExpandedParamsToks, MacroDict, []),
261
:-(
subst_macros_rev(NToks, MacroDict, RevExpandedOtherMacrosToks ++ RevOutToks)
262 end;
263 subst_macros_rev([{'?', _}, {_, _, Name} | Toks], MacroDict, RevOutToks) ->
264 %% This macro invocation does not have arguments.
265 %% Therefore the definition should not have parameters
266
:-(
{[], MacroValue} = dict:fetch(Name, MacroDict),
267
268 %% Recursively expand any macro calls inside this macro's value
269 %% TODO: avoid infinite expansion due to circular references (even indirect ones)
270
:-(
RevExpandedOtherMacrosToks = subst_macros_rev(MacroValue, MacroDict, []),
271
:-(
subst_macros_rev(Toks, MacroDict, RevExpandedOtherMacrosToks ++ RevOutToks);
272 subst_macros_rev([Tok|Toks], MacroDict, RevOutToks) ->
273 3364 subst_macros_rev(Toks, MacroDict, [Tok|RevOutToks]);
274 127 subst_macros_rev([], _MacroDict, RevOutToks) -> RevOutToks.
275
276 %% @private
277 -spec subst_macros_get_args(Toks :: nonempty_maybe_improper_list(),
278 RevArgs :: [any()]) -> {_, [any()]}.
279 subst_macros_get_args([{')', _} | Toks], RevArgs) ->
280
:-(
{Toks, reverse(RevArgs)};
281 subst_macros_get_args([{', ', _}, {var, _, ArgName} | Toks], RevArgs) ->
282
:-(
subst_macros_get_args(Toks, [ArgName| RevArgs]);
283 subst_macros_get_args([{var, _, ArgName} | Toks], RevArgs) ->
284
:-(
subst_macros_get_args(Toks, [ArgName | RevArgs]).
285
286 %% @private
287 -spec subst_macros_subst_args_for_vars({[any()], _}, [any()]) -> any().
288 subst_macros_subst_args_for_vars({[], BodyToks}, []) ->
289
:-(
BodyToks;
290 subst_macros_subst_args_for_vars({[Param | Params], BodyToks}, [Arg|Args]) ->
291
:-(
NBodyToks = keyreplace(Param, 3, BodyToks, {var, 1, Arg}),
292
:-(
subst_macros_subst_args_for_vars({Params, NBodyToks}, Args).
293
294 %% @private
295 -spec read_include_file(Filename :: file:name(),
296 IncludeSearchPath :: [file:name(), ...]
297 ) -> [byte()].
298 read_include_file(Filename, IncludeSearchPath) ->
299
:-(
case file:path_open(IncludeSearchPath, Filename, [read, raw, binary]) of
300 {ok, IoDevice, FullName} ->
301
:-(
{ok, Data} = file:read(IoDevice, filelib:file_size(FullName)),
302
:-(
file:close(IoDevice),
303
:-(
binary_to_list(Data);
304 {error, Reason} ->
305
:-(
throw({failed_to_read_include_file, Reason, Filename, IncludeSearchPath})
306 end.
Line Hits Source