├── .gitignore
├── LICENSE
├── README.md
├── rebar.config
├── relx.config
└── src
├── niffy.app.src
├── niffy.erl
└── niffy_transform.erl
/.gitignore:
--------------------------------------------------------------------------------
1 | .rebar3
2 | _*
3 | .eunit
4 | deps
5 | *.o
6 | *.beam
7 | *.plt
8 | *.swp
9 | *.swo
10 | .erlang.cookie
11 | ebin
12 | log
13 | erl_crash.dump
14 | rel/example_project
15 | .concrete/DEV_MODE
16 | .rebar
17 | logs
18 | _build
19 | _checkouts
20 | .DS_Store
21 | .idea
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright 2016 Erlang Solutions Ltd.
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # niffy
2 | Erlang parse transform to generate NIF files from inlined C code.
3 |
4 | ### Why?
5 | Writing NIFs is time consuming and their code can't help but being riddled with macros. And not only that; our C code has to be in a separate file, adding a layer of complexity when debugging and trying to figure out exactly what's going on.
6 |
7 | ### What can niffy do to help?
8 | Simple, instead of writing your nifs, just inline some C code in your erlang files:
9 |
10 | ```erlang
11 | -module(example).
12 | -niffy([square/1]).
13 | -export([square/1]).
14 |
15 | square(_A) ->
16 | "int square(int a)
17 | {
18 | return a * a;
19 | }".
20 | ```
21 |
22 | That code compiles and does exactly what you would expect:
23 |
24 | ```erlang
25 | > example:square(2).
26 | 4
27 | ```
28 |
29 | ### How?
30 |
31 |
32 |
33 | ### But seriously, how?
34 |
35 | Niffy takes care of many things. First, it generates the NIF from the inlined C code, making all the changes so that erlang can include it. For example, given the previous erlang file, niffy will generate (and compile) the following C code:
36 |
37 | ```c
38 | #include "erl_nif.h"
39 |
40 | static ERL_NIF_TERM square_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
41 | {
42 | int a;
43 | if (!enif_get_int(env, argv[0], &a))
44 | return enif_make_badarg(env);
45 | return enif_make_int(env, a * a);
46 | }
47 |
48 | static ErlNifFunc niffuncs[] = {{"square", 1, square_nif, 0}};
49 |
50 | ERL_NIF_INIT(example, niffuncs, NULL, NULL, NULL, NULL)
51 | ```
52 |
53 | (Yes, it also handles the indentation)
54 |
55 | Once that's done, it will modify the original erlang file so that the function ``square/1`` throws ``nif_not_loaded`` if you attempt to call it.
56 |
57 | And finally, it will add a function to load the nif on the module's ``on_load`` function (don't worry, if no ``on_load`` function is present on the module, niffy just adds one).
58 |
59 | ### What else?
60 | Well, that was just a basic example, niffy also handles includes, whatever compiler flags you need and you can even flag some functions as dirty.
61 |
62 | A more complex example would be this one, where instead of a list of functions we define a map with some properties (they are actually all optional):
63 |
64 | ```erlang
65 | -module(another_example).
66 |
67 | -niffy(#{functions => [sum_c/2, square/1, {nat_log/1, cpu_bound}],
68 | options => [{flags, ["-pedantic"]}]}).
69 |
70 | -export([sum/2, square/1, nat_log/1]).
71 |
72 | square(_A) ->
73 | "int square(int a)
74 | {
75 | return a * a;
76 | }".
77 |
78 | nat_log(_A) ->
79 | "#include
80 | double nat_log(double a)
81 | {
82 | // this will return the natural log
83 | double logA = log(a);
84 | // return logB;
85 | return logA;
86 | }".
87 | ```
88 |
89 | As you can see, it's pretty clear when one of our functions is either ``cpu_bound`` or ``io_bound``. Also, including headers and setting compiler flags is pretty simple (also, notice that you can add the headers as many times as you wish, including on the function bodies, just use whatever you feel makes for a more readable file).
90 |
91 | Again, that works just fine and generates pretty easy to follow code:
92 |
93 | ```c
94 | #include "erl_nif.h"
95 | #include
96 |
97 | static ERL_NIF_TERM nat_log_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
98 | {
99 | double a;
100 | if (!enif_get_double(env, argv[0], &a))
101 | return enif_make_badarg(env);
102 | // this will return the natural log
103 | double logA = log(a);
104 | // return enif_make_double(env, logB);
105 | return logA;
106 | }
107 |
108 | static ERL_NIF_TERM square_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
109 | {
110 | int a;
111 | if (!enif_get_int(env, argv[0], &a))
112 | return enif_make_badarg(env);
113 | return enif_make_int(env, a * a);
114 | }
115 |
116 | static ErlNifFunc niffuncs[] = {{"nat_log", 1, nat_log_nif, ERL_NIF_DIRTY_JOB_CPU_BOUND},
117 | {"square", 1, square_nif, 0}};
118 |
119 | ERL_NIF_INIT(another_example, niffuncs, NULL, NULL, NULL, NULL)
120 | ```
121 |
122 | Just remember that niffy is not parsing your code. And it's just making some reasonable assumptions regarding how it is written. You can see that in the way it handled the C comments, any ``return .*;`` that's not followed by ``enif_make_*`` will be modified.
123 |
124 | ### How to use niffy?
125 | Couldn't be simpler: Set it as a dependency of your project and add ``{parse_transform, niffy_transform}`` to ``erl_opts`` in your ``rebar.config`` file. Any other options go into ``niffy_options`` on ``erl_opts``: The compiler flags that apply to all the files, and the directory where you want to output the generated C code:
126 |
127 | ```erlang
128 | %{application, your_app_name_here},
129 | {niffy_options, [{compiler, "gcc"}, % Default
130 | {flags, ["-Werror",
131 | "-I/usr/lib/erlang/erts-5.8.1/include"]},
132 | {c_dir, "_generated/c_src"}, % Default
133 | {strict_types, false}]}
134 | ```
135 |
136 | Also, you can tell **niffy** the name of your application. This is only useful if you are writing a dependency.
137 |
138 | Just keep in mind that if you want to upgrade niffy, you **should delete your _build folder** (otherwise rebar3 doesn't realise it needs to rebuild all the files) and that it would be a good idea to add ``*.so`` and ``_generated`` to your ``.gitignore``.
139 |
140 | ### Contact Us
141 | For **questions** or **general comments** regarding the use of this library, please use our public
142 | [hipchat room](https://www.hipchat.com/gpBpW3SsT).
143 |
144 | If you find any **bugs**, **problems** or got any **suggestions**, please [open an issue](https://github.com/inaka/niffy/issues/new) in this repo (or even a pull request :)).
145 |
146 | And you can check all of our open-source projects at [inaka.github.io](http://inaka.github.io)
147 |
--------------------------------------------------------------------------------
/rebar.config:
--------------------------------------------------------------------------------
1 | {erl_opts, [debug_info]}.
2 | {deps, []}.
3 | {ct_compile_opts, [ warn_unused_vars
4 | , warn_export_all
5 | , warn_shadow_vars
6 | , warn_unused_import
7 | , warn_unused_function
8 | , warn_bif_clash
9 | , warn_unused_record
10 | , warn_deprecated_function
11 | , warn_obsolete_guard
12 | , strict_validation
13 | , warn_export_vars
14 | , warn_exported_vars
15 | , warn_missing_spec
16 | , warn_untyped_record
17 | , debug_info
18 | ]}.
19 |
--------------------------------------------------------------------------------
/relx.config:
--------------------------------------------------------------------------------
1 | {release, {niffy, "0.1.0"}, [kernel, stdlib]}.
2 | %{sys_config, "config/sys.config"}.
3 | {extended_start_script, true}.
--------------------------------------------------------------------------------
/src/niffy.app.src:
--------------------------------------------------------------------------------
1 | {application,
2 | niffy,
3 | [{description, "NIF code generation tool"},
4 | {vsn, "0.1.0"},
5 | {id, "niffy"},
6 | {registered, []},
7 | {modules, []},
8 | {applications, []},
9 | {env, []},
10 | {maintainers, ["Inaka", "HernanRivasAcosta"]},
11 | {licenses, ["Apache2"]}]}.
12 |
--------------------------------------------------------------------------------
/src/niffy.erl:
--------------------------------------------------------------------------------
1 | -module(niffy).
2 | -export([nif_filename/2]).
3 |
4 | %%==============================================================================
5 | %% API
6 | %%==============================================================================
7 | nif_filename(AppName, NIF) ->
8 | Dir = case code:priv_dir(AppName) of
9 | {error, bad_name} ->
10 | case filelib:is_dir(filename:join("..", "priv")) of
11 | true ->
12 | filename:join("..", "priv");
13 | _ ->
14 | "priv"
15 | end;
16 | PrivDir ->
17 | PrivDir
18 | end,
19 | filename:join(Dir, NIF).
--------------------------------------------------------------------------------
/src/niffy_transform.erl:
--------------------------------------------------------------------------------
1 | -module(niffy_transform).
2 | -export([parse_transform/2]).
3 |
4 | %%==============================================================================
5 | %% API
6 | %%==============================================================================
7 | parse_transform(Forms, Options) ->
8 | case config(Forms) of
9 | undefined ->
10 | Forms;
11 | Config ->
12 | % Get the functions to niffify
13 | Functions = maps:get(functions, Config, []),
14 | % Get the configuration
15 | NiffyOptions = options(maps:get(options, Config, []),
16 | proplists:get_value(niffy_options, Options, [])),
17 | Module = module(Forms),
18 | NIFId = nif_id(Module),
19 | {ok, AppDir} = file:get_cwd(),
20 |
21 | % Parse the Forms and get the C code
22 | {CFunctions, Forms2} = functions_from_forms(Functions, Forms),
23 |
24 | % Build the C file
25 | CDir = proplists:get_value(c_dir, NiffyOptions),
26 | CFileName = filename:join([AppDir, CDir, NIFId ++ ".c"]),
27 | CCode = build_c_code(Module, lists:reverse(CFunctions), NiffyOptions),
28 | ok = filelib:ensure_dir(CFileName),
29 | ok = file:write_file(CFileName, CCode),
30 |
31 | % Make sure we have an init function where we can add the nif loading code
32 | {InitFunc, Forms3} = ensure_init_function(Module, Forms2),
33 |
34 | % Compile the C file to the priv folder
35 | SOName = filename:join([AppDir, "priv", NIFId ++ ".so"]),
36 | ok = filelib:ensure_dir(SOName),
37 | Flags = flags(NiffyOptions),
38 | Compiler = proplists:get_value(compiler, NiffyOptions),
39 | ExtraFiles = proplists:get_value(extra_files, NiffyOptions),
40 | FilesToCompile = string:join([CFileName | ExtraFiles], " "),
41 | Command = [Compiler, " -o ", SOName, " ", Flags, " ", FilesToCompile],
42 | _ = case os:cmd(Command) of
43 | [] ->
44 | ignore;
45 | Error ->
46 | io:format("Compiler Error:~n$ ~s~n> ~s", [Command, Error])
47 | end,
48 | % Add the call to load the nif
49 | add_nif_loader(Forms3, InitFunc, {app_name(Options, AppDir), NIFId})
50 | end.
51 |
52 | %%==============================================================================
53 | %% Utils
54 | %%==============================================================================
55 | config([]) ->
56 | undefined;
57 | % There is the full map configuration for niffy
58 | config([{attribute, _, niffy, Config} | _]) when is_map(Config) ->
59 | Config#{functions := normalize_functions(maps:get(functions, Config))};
60 | % And also a simple function list, in this case, we need to build the map
61 | config([{attribute, _, niffy, Functions} | _]) when is_list(Functions) ->
62 | #{functions => normalize_functions(Functions)};
63 | config([_ | T]) ->
64 | config(T).
65 |
66 | % Make sure all the function specifications have the optional DirtyMode value
67 | normalize_functions(Functions) ->
68 | normalize_functions(Functions, []).
69 |
70 | normalize_functions([], Acc) ->
71 | Acc;
72 | normalize_functions([{{F, A}, DirtyMode} | T], Acc) ->
73 | normalize_functions(T, [{F, A, DirtyMode} | Acc]);
74 | normalize_functions([{F, A} | T], Acc) ->
75 | normalize_functions(T, [{F, A, none} | Acc]).
76 |
77 | options(ModuleOpts, GlobalOpts) ->
78 | [get_option(Type, Name, ModuleOpts, GlobalOpts, Default) ||
79 | {Name, Type, Default} <- options_spec()].
80 |
81 | % This is easy to read, the options are simply tuples where the first element is
82 | % the name, the second is the mode, and the third is the default value.
83 | % Available modes are:
84 | % - merge: Appends the module configuration to the erl_opts AND the default
85 | % - module_first: It will use the module value if available, if not, it will use
86 | % the one in erl_opts (and the default as a last resort)
87 | % - global_only: Used when it makes no sense to have the option on a module
88 | % - module_only: And this is the counterpart, sometimes it doesn't make sense to
89 | % have a global setting
90 | options_spec() ->
91 | [{flags, merge, ["-fpic", "-shared"]},
92 | {compiler, module_first, "gcc"},
93 | {includes, module_only, []},
94 | {strict_types, module_first, true},
95 | {c_dir, global_only, "_generated/c_src"},
96 | {on_load, module_only, "NULL"},
97 | {on_upgrade, module_only, "NULL"},
98 | {on_unload, module_only, "NULL"},
99 | {extra_files, merge, []},
100 | {default_string_type, module_first, string},
101 | {max_string_size, module_first, 1023},
102 | {string_encoding, module_first, "ERL_NIF_LATIN1"}].
103 |
104 | get_option(merge, K, ModuleOpts, GlobalOpts, Def) ->
105 | {K, proplists:get_value(K, ModuleOpts, []) ++
106 | proplists:get_value(K, GlobalOpts, []) ++
107 | Def};
108 | get_option(module_only, K, ModuleOpts, _GlobalOpts, Def) ->
109 | {K, proplists:get_value(K, ModuleOpts, Def)};
110 | get_option(global_only, K, _ModuleOpts, GlobalOpts, Def) ->
111 | {K, proplists:get_value(K, GlobalOpts, Def)};
112 | get_option(module_first, K, ModuleOpts, GlobalOpts, Def) ->
113 | {K,
114 | proplists:get_value(K, ModuleOpts, proplists:get_value(K, GlobalOpts, Def))}.
115 |
116 | % Retrieve the module name
117 | module([{attribute, _, module, Module} | _]) ->
118 | Module;
119 | module([_ | T]) ->
120 | module(T).
121 |
122 | % Get the C code of each of the functions on the niffy config
123 | functions_from_forms(Functions, Forms) ->
124 | functions_from_forms(Functions, Forms, [], []).
125 |
126 | functions_from_forms([], Forms, Functions, Acc) ->
127 | {Functions, lists:reverse(Acc, Forms)};
128 | functions_from_forms(_, [], Functions, Acc) ->
129 | {Functions, lists:reverse(Acc)};
130 | functions_from_forms(FunctionNames,
131 | [{function, L1, F, A,
132 | [{clause, _, Args, [], [{string, L2, CCode}]}]} = H | T],
133 | Functions, Acc) ->
134 | case take_function(F, A, FunctionNames) of
135 | false ->
136 | functions_from_forms(FunctionNames, T, Functions, [H | Acc]);
137 | {{F, A, DirtyMode}, NewFunctionNames} ->
138 | Stub = get_function_stub(L1, L2, F, A, Args),
139 | NewFunctions = [{F, A, DirtyMode, CCode} | Functions],
140 | functions_from_forms(NewFunctionNames, T, NewFunctions, [Stub | Acc])
141 | end;
142 | functions_from_forms(FunctionNames, [H | T], Functions, Acc) ->
143 | functions_from_forms(FunctionNames, T, Functions, [H | Acc]).
144 |
145 | % Get the function specification from the function list
146 | take_function(F, A, Functions) ->
147 | take_function(F, A, Functions, []).
148 |
149 | take_function(_F, _A, [], _Acc) ->
150 | false;
151 | take_function(F, A, [{F, A, _} = H | T], Acc) ->
152 | {H, lists:reverse(Acc, T)};
153 | take_function(F, A, [H | T], Acc) ->
154 | take_function(F, A, T, [H | Acc]).
155 |
156 | nif_id(Module) ->
157 | atom_to_list(Module) ++ "_nif".
158 |
159 | % Get the app name, this is needed at runtime to retrieve the priv_dir
160 | app_name(Options, AppDir) ->
161 | case proplists:get_value(application, Options) of
162 | undefined ->
163 | % If the user didn't specify an application name, we have to get one
164 | AppSrc = filename:join([AppDir, "src", "*.app.src"]),
165 | {ok, [{_, AppName, _}]} = file:consult(hd(filelib:wildcard(AppSrc))),
166 | AppName;
167 | Value ->
168 | Value
169 | end.
170 |
171 | % The list of compiler flags used when calling gcc
172 | flags(NiffyOptions) ->
173 | string:join(lists:usort(proplists:get_value(flags, NiffyOptions)), " ").
174 |
175 | % Make sure we have an init function
176 | ensure_init_function(Module, Forms) ->
177 | ensure_init_function(Module, Forms, []).
178 |
179 | % Yes, this is assuming the last statement on the forms is an EOF
180 | ensure_init_function(Module, [], [Eof | Acc]) ->
181 | FName = list_to_atom(atom_to_list(Module) ++ "_nif_init"),
182 | L = lists:reverse([Eof, {function, 0, FName, 0, [{clause, 0, [], [], []}]} |
183 | Acc]),
184 | {P, S} = lists:split(3, L),
185 | {{FName, 0}, P ++ [{attribute, 0, on_load, {FName, 0}}] ++ S};
186 | ensure_init_function(_Module, [{attribute, _, on_load, F} | _] = L, Acc) ->
187 | {F, lists:reverse(Acc, L)};
188 | ensure_init_function(Module, [H | T], Acc) ->
189 | ensure_init_function(Module, T, [H | Acc]).
190 |
191 | % Assuming we have an init function, add the code to load the nif
192 | add_nif_loader(Forms, Func, NIF) ->
193 | add_nif_loader(Forms, Func, NIF, []).
194 |
195 | add_nif_loader([{function, L, F, A, [Clause]} | T], {F, A}, NIF, Acc) ->
196 | {clause, L2, Args, [], Body} = Clause,
197 | NewClause = {clause, L2, Args, [], [make_nif_loader(L, NIF) | Body]},
198 | NewF = {function, L, F, A, [NewClause]},
199 | lists:reverse([NewF | Acc], T);
200 | add_nif_loader([H | T], Func, NIF, Acc) ->
201 | add_nif_loader(T, Func, NIF, [H | Acc]).
202 |
203 | %%==============================================================================
204 | %% Code generators
205 | %%==============================================================================
206 | get_function_stub(Line1, Line2, Name, Arity, Args) ->
207 | Body = {call, Line2, {atom, Line2, throw}, [{atom, Line2, nif_not_loaded}]},
208 | {function, Line1, Name, Arity, [{clause, Line1, Args, [], [Body]}]}.
209 |
210 | make_nif_loader(L, {AppName, NIF}) ->
211 | % The code this is generating is just:
212 | % erlang:load_nif(niffy:nif_filename(AppName, NIF), 0)
213 | Args = [{call, L,
214 | {remote, L, {atom, L, niffy}, {atom, L, nif_filename}},
215 | [{atom, L, AppName}, {string, L, NIF}]},
216 | {integer, L, 0}],
217 | {match, L, {atom, L, ok},
218 | {call, L, {remote, L, {atom, L, erlang},
219 | {atom, L, load_nif}}, Args}}.
220 |
221 | build_c_code(Mod, Functions, Options) ->
222 | Includes = proplists:get_value(includes, Options),
223 | {NewIncludes, NewFunctions} = includes(Functions, ["erl_nif.h" | Includes]),
224 | NIFIds = [["{\"", atom_to_list(F), "\", ",
225 | integer_to_list(A), ", ",
226 | atom_to_list(F), "_nif, ",
227 | func_flags(DirtyMode),
228 | "}"] || {F, A, DirtyMode, _} <- NewFunctions],
229 | [string:join(NewIncludes, "\n"), "\n\n",
230 | string:join([build_c_function(F, Options) || F <- NewFunctions], "\n"), "\n",
231 | "static ErlNifFunc niffuncs[] = {",
232 | string:join(NIFIds, [",\n", lists:duplicate(32, 32)]), "};\n\n",
233 | "ERL_NIF_INIT(", atom_to_list(Mod), ", niffuncs, ",
234 | proplists:get_value(on_load, Options),
235 | ", NULL, ",
236 | proplists:get_value(on_upgrade, Options), ", ",
237 | proplists:get_value(on_unload, Options), ")\n"].
238 |
239 | build_c_function({F, _, _, Function}, Options) ->
240 | Name = atom_to_list(F),
241 | Body = body(Function),
242 | % Get the function that transforms the return value to an erlang term
243 | ReturnReplacement = build_make_type(return_type(Function, Name)),
244 | % And apply it (via regex) to all returns on the function body
245 | FixedBody = re:replace(Body,
246 | "return\s+(?!enif_make)([^;\n]*);",
247 | ReturnReplacement,
248 | [global]),
249 | ["static ERL_NIF_TERM ", atom_to_list(F),
250 | "_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])\n", "{\n",
251 | build_argument_getters(Function, Options),
252 | FixedBody, "}\n"].
253 |
254 | func_flags(cpu_bound) ->
255 | "ERL_NIF_DIRTY_JOB_CPU_BOUND";
256 | func_flags(io_bound) ->
257 | "ERL_NIF_DIRTY_JOB_IO_BOUND";
258 | func_flags(_None) ->
259 | $0.
260 |
261 | %%==============================================================================
262 | %% C code utils
263 | %%==============================================================================
264 | build_make_type("ERL_NIF_TERM") ->
265 | "return \\1;";
266 | build_make_type("bool") ->
267 | "return enif_make_atom(env, \\1 ? \"true\" : \"false\");";
268 | build_make_type("_Bool") ->
269 | build_make_type("bool");
270 | build_make_type(Type) ->
271 | "return enif_make_" ++
272 | proplists:get_value(Type, numeric_type_mapping()) ++
273 | "(env, \\1);".
274 |
275 | numeric_type_mapping() ->
276 | [{"int", "int"},
277 | {"ErlNifSInt64", "int64"},
278 | {"double", "double"},
279 | {"long int", "long"},
280 | {"unsigned int", "uint"},
281 | {"ErlNifUInt64", "uint64"},
282 | {"unsigned long", "ulong"}].
283 |
284 | % The body of the function is assumed to be anything within the outmost brackets
285 | body(Function) ->
286 | % Get the position of the outmost brackets
287 | OpeningBracket = string:chr(Function, ${),
288 | ClosingBracket = string:rchr(Function, $}),
289 | % Get the spaces we have in front of the first bracket
290 | BeforeOpeningBracket = string:sub_string(Function, 1, OpeningBracket - 1),
291 | Tab = string:sub_string(Function,
292 | string:rchr(BeforeOpeningBracket, $\n) + 1,
293 | OpeningBracket - 1),
294 | % Get the body
295 | Body = string:sub_string(Function, OpeningBracket + 1, ClosingBracket - 1),
296 | % Divide the body in lines and remove all extra spaces on each line
297 | Lines = [Line -- Tab || Line <- string:tokens(Body, "\n")],
298 | % Put the newline characters back
299 | string:join(Lines, "\n").
300 |
301 | return_type(Body, FName) ->
302 | string:strip(string:substr(Body, 1, string:str(Body, FName) - 1), both).
303 |
304 | build_argument_getters(Function, Options) ->
305 | case args(Function) of
306 | % Do nothing for functions with no parameters
307 | [] ->
308 | "";
309 | % Special case to handle when the user doesn't want any parameter magic
310 | [{"ErlNifEnv*", "env"},
311 | {"int", "argc"},
312 | {"const ERL_NIF_TERM", "argv[]"}] ->
313 | "";
314 | % Try to convert the standard C types to the getter functions from erl_nif.h
315 | Args ->
316 | [" // Actual variable declarations from the parameters\n",
317 | string:join([[" ", handle_const_char(T), " ", N, $;] ||
318 | {T, N} <- Args], "\n"),
319 | "\n // Assigning the contents of 'env' to the variables",
320 | case lists:any(fun({"const char*", _}) ->
321 | true;
322 | (_) ->
323 | false
324 | end, Args) of
325 | true ->
326 | "\n unsigned int internal_str_length;";
327 | false ->
328 | ""
329 | end, "\n", build_argument_getters(Args, Options, 0, []),
330 | "\n // Your actual (mostly untached) code\n"]
331 | end.
332 |
333 | handle_const_char("const char*") ->
334 | "char*";
335 | handle_const_char(Other) ->
336 | Other.
337 |
338 | build_argument_getters([], _Options, _, Acc) ->
339 | string:join(lists:reverse(Acc), ["\n"]);
340 | build_argument_getters([{"const char*", Name} | T], Options, I, Acc) ->
341 | IStr = integer_to_list(I),
342 | Get = case get_type_from_name(Name, Options) of
343 | string ->
344 | [" if (!enif_get_list_length(env, argv[", IStr, "], "
345 | "&internal_str_length))\n",
346 | " return enif_make_badarg(env);\n",
347 | " ", Name, " = malloc(internal_str_length + 1);\n"
348 | " if (!", Name, ")\n return enif_raise_exception(env, ",
349 | "enif_make_atom(env, \"malloc_error\"));\n",
350 | " if (!enif_get_string(env, argv[", IStr, "], ",
351 | Name, ", ",
352 | integer_to_list(proplists:get_value(max_string_size, Options)),
353 | ", ", proplists:get_value(string_encoding, Options), "))\n",
354 | " return enif_make_badarg(env);"]
355 | end,
356 | build_argument_getters(T, Options, I + 1, [Get | Acc]);
357 | build_argument_getters([{Type, Name} | T], Options, I, Acc) ->
358 | NewEnifGet = build_numeric_enif_get(I, Type, Name, Options),
359 | build_argument_getters(T, Options, I + 1, [NewEnifGet | Acc]).
360 |
361 | get_type_from_name(Name, Options) ->
362 | LName = string:to_lower(Name),
363 | case lists:suffix("string", LName) orelse
364 | lists:suffix("str", LName) of
365 | true ->
366 | string;
367 | false ->
368 | case lists:suffix("atom", LName) of
369 | true ->
370 | atom;
371 | false ->
372 | case lists:suffix("binary", LName) orelse
373 | lists:suffix("bin", LName) of
374 | true ->
375 | string;
376 | false ->
377 | string
378 | %proplists:get_value(default_string_type, Options)
379 | end
380 | end
381 | end.
382 |
383 | build_numeric_enif_get(I, Type, Name, _Options) ->
384 | [" if (!", ["enif_get_", proplists:get_value(Type, numeric_type_mapping())],
385 | "(env, argv[", integer_to_list(I), "], &", Name, "))\n",
386 | " return enif_make_badarg(env);"].
387 |
388 | args(Function) ->
389 | ArgsStr = string:sub_string(Function, string:chr(Function, $() + 1,
390 | string:chr(Function, $)) - 1),
391 | [case string:tokens(A, " ") of
392 | [T, N] -> {T, N};
393 | [T1, T2, N] -> {T1 ++ " " ++ T2, N}
394 | end || A <- string:tokens(ArgsStr, ",")].
395 |
396 | includes(Functions, Included) ->
397 | lists:foldr(fun(Function, {NewIncludes, NewFunctions}) ->
398 | {Includes, NewFunction} = includes(Function),
399 | {lists:usort(Includes ++ NewIncludes),
400 | [NewFunction | NewFunctions]}
401 | end, {[format_include(I) || I <- Included], []}, Functions).
402 |
403 | includes({F, A, DirtyMode, Body}) ->
404 | {Includes, Rest} = lists:partition(fun([$# | _]) -> true;
405 | (_) -> false
406 | end, string:tokens(Body, "\n")),
407 | {Includes, {F, A, DirtyMode, string:join(Rest, "\n")}}.
408 |
409 | format_include([$< | _] = File) -> "#include " ++ File;
410 | format_include(File) -> "#include \"" ++ File ++ "\"".
--------------------------------------------------------------------------------