├── .formatter.exs ├── .gitignore ├── CHANGELOG.md ├── LICENSE ├── README.md ├── lib ├── build_dot_zig │ ├── compiler.ex │ ├── http.ex │ └── zig_installer.ex └── mix │ ├── build_dot_zig.ex │ ├── build_dot_zig │ └── c_nif.ex │ └── tasks │ ├── build_dot_zig.gen.c_nif.ex │ └── compile.build_dot_zig.ex ├── mix.exs ├── mix.lock ├── priv ├── .gitkeep └── templates │ └── build_dot_zig.gen.c_nif │ ├── build.zig.eex │ ├── library.c.eex │ └── module.ex.eex └── test └── test_helper.exs /.formatter.exs: -------------------------------------------------------------------------------- 1 | # Used by "mix format" 2 | [ 3 | inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"] 4 | ] 5 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # The directory Mix will write compiled artifacts to. 2 | /_build/ 3 | 4 | # If you run "mix test --cover", coverage assets end up here. 5 | /cover/ 6 | 7 | # The directory Mix downloads your dependencies sources to. 8 | /deps/ 9 | 10 | # Where third-party dependencies like ExDoc output generated docs. 11 | /doc/ 12 | 13 | # Ignore .fetch files in case you like to edit your project deps locally. 14 | /.fetch 15 | 16 | # If the VM crashes, it generates a dump, let's ignore it too. 17 | erl_crash.dump 18 | 19 | # Also ignore archive artifacts (built via "mix archive.build"). 20 | *.ez 21 | 22 | # Ignore package tarball (built via "mix hex.build"). 23 | build_dot_zig-*.tar 24 | 25 | # Temporary files, for example, from tests. 26 | /tmp/ 27 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to this project will be documented in this file. 4 | 5 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), 6 | and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). 7 | 8 | ## [0.6.1] - 2025-03-10 9 | 10 | - Update deps. 11 | - Clarify docs on supported Zig versions. 12 | 13 | ## [0.6.0] - 2025-03-10 14 | 15 | - Bump default Zig version to `0.14.0`. 16 | 17 | ## [0.5.0] - 2024-07-26 18 | 19 | - Bump default Zig version to `0.13.0` and make the generated `build.zig` compatible with it. 20 | 21 | ## [0.4.2] - 2023-12-13 22 | 23 | ### Fixed 24 | 25 | - Add missing include in generated library to make it work on Windows 26 | 27 | ## [0.4.1] - 2023-12-13 28 | 29 | ### Fixed 30 | 31 | - Fix the generated `build.zig` to make it work on Windows. 32 | 33 | ## [0.4.0] - 2023-12-11 34 | 35 | ### Added 36 | 37 | - Add `mix build_dot_zig.gen.c_nif` Mix generator. 38 | - Allow passing project-specific options with `zig_extra_options`. 39 | 40 | ### Changed 41 | 42 | - Use `:release_safe` build mode by default in `:prod` env. Leave `:debug` as default in all other 43 | cases. 44 | 45 | ### Fixed 46 | 47 | - Fix arch detection on Windows. 48 | 49 | ## [0.3.1] - 2023-08-22 50 | 51 | ### Fixed 52 | 53 | - Pass the correct option for optimize modes. 54 | 55 | ### Changed 56 | 57 | - Due to the different options for the optimize modes, `:build_dot_zig` is currently only 58 | compatible with Zig version `0.11.0`. 59 | 60 | ## [0.3.0] - 2023-08-08 61 | 62 | ### Added 63 | 64 | - Add `zig_target` option. 65 | - Add `zig_cpu` option. 66 | 67 | ### Changed 68 | 69 | - Bump latest stable `zig` to `0.11.0`. 70 | 71 | ## [0.2.0] - 2023-07-10 72 | 73 | ### Added 74 | 75 | - Clean Zig cache on `mix.clean`. 76 | - Add functionality to automatically download the `zig` toolchain, also with a specific version. 77 | - Allow defining the build mode from the Mix configuration. 78 | 79 | ### Changed 80 | 81 | - BREAKING: rename `:build_dot_zig_executable` option to `:zig_executable`. 82 | 83 | ## [0.1.1] - 2023-03-03 84 | 85 | ### Fixed 86 | 87 | - Handle `:default` in the `:build_dot_zig_executable` option. 88 | 89 | ### Changed 90 | 91 | - Put `zig-cache` in the `_build` folder with all other build artifacts. 92 | 93 | ## [0.1.0] - 2023-02-26 94 | 95 | ### Added 96 | 97 | - Initial release. 98 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # A `build.zig` compiler for Mix 2 | 3 | This package aims to be similar to [`elixir_make`](https://github.com/elixir-lang/elixir_make) (from 4 | which it takes lots of inspiration) but for projects based on Zig as a build system, instead of 5 | Make. 6 | 7 | ## Usage 8 | 9 | The package can be installed by adding `build_dot_zig` to your list of dependencies in `mix.exs`: 10 | 11 | ```elixir 12 | def deps do 13 | [ 14 | {:build_dot_zig, "~> 0.5.0", runtime: false} 15 | ] 16 | end 17 | ``` 18 | 19 | Still in your `mix.exs` file, you will need to add `:build_dot_zig` to your list of compilers in 20 | `project/0`: 21 | 22 | ``` 23 | compilers: [:build_dot_zig] ++ Mix.compilers(), 24 | ``` 25 | 26 | If you're starting a new C NIF from scratch, you can use the Mix generator to bootstrap it. Run: 27 | 28 | ```console 29 | mix help build_dot_zig.gen.c_nif 30 | ``` 31 | 32 | to read the documentation of the generator. You can also use the output of the generator as 33 | inspiration to replace an existing build system for a NIF with the Zig build system. 34 | 35 | The appropriate `zig` binary will be automatically downloaded and used to run the `build.zig` 36 | builder. 37 | 38 | For more information about what you can do with the Zig build system, read the [Zig build system 39 | guide](https://ziglang.org/learn/build-system). 40 | 41 | ## License 42 | 43 | Copyright (c) 2023 Riccardo Binetti 44 | 45 | Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in 46 | compliance with the License. You may obtain a copy of the License at 47 | https://www.apache.org/licenses/LICENSE-2.0 48 | 49 | Unless required by applicable law or agreed to in writing, software distributed under the License is 50 | distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 51 | implied. See the License for the specific language governing permissions and limitations under the 52 | License. 53 | -------------------------------------------------------------------------------- /lib/build_dot_zig/compiler.ex: -------------------------------------------------------------------------------- 1 | defmodule BuildDotZig.Compiler do 2 | alias BuildDotZig.ZigInstaller 3 | 4 | @latest_stable_zig "0.14.0" 5 | 6 | def compile do 7 | config = Mix.Project.config() 8 | Mix.shell().print_app() 9 | priv? = File.dir?("priv") 10 | Mix.Project.ensure_structure() 11 | build(config) 12 | 13 | # IF there was no priv before and now there is one, we assume 14 | # the user wants to copy it. If priv already existed and was 15 | # written to it, then it won't be copied if build_embedded is 16 | # set to true. 17 | if not priv? and File.dir?("priv") do 18 | Mix.Project.build_structure() 19 | end 20 | 21 | {:ok, []} 22 | end 23 | 24 | def clean do 25 | # Remove the zig cache 26 | Mix.Project.config() 27 | |> Mix.Project.build_path() 28 | |> cache_dir() 29 | |> File.rm_rf!() 30 | end 31 | 32 | def build(config) do 33 | downloaded_zig_install_dir = 34 | Keyword.get(config, :install_zig, true) 35 | |> zig_download_version() 36 | |> ensure_downloaded_zig!() 37 | 38 | downloaded_zig_exec = downloaded_zig_exec(downloaded_zig_install_dir) 39 | 40 | explicit_exec = Keyword.get(config, :zig_executable, :default) 41 | exec = exec(explicit_exec, downloaded_zig_exec) 42 | 43 | app_path = Mix.Project.app_path(config) 44 | mix_target = Mix.target() 45 | install_prefix = "#{app_path}/priv/#{mix_target}" 46 | build_path = Mix.Project.build_path(config) 47 | build_mode = Keyword.get(config, :zig_build_mode, default_build_mode(Mix.env())) 48 | target = Keyword.get(config, :zig_target, :host) 49 | cpu = Keyword.get(config, :zig_cpu, :native) 50 | extra_options = Keyword.get(config, :zig_extra_options, []) 51 | args = build_args(install_prefix, build_path, build_mode, target, cpu, extra_options) 52 | 53 | env = 54 | default_env(config) 55 | |> maybe_add_zig_install_dir(downloaded_zig_install_dir) 56 | 57 | case cmd(exec, args, env) do 58 | 0 -> 59 | :ok 60 | 61 | exit_status -> 62 | raise_build_error(exec, exit_status) 63 | end 64 | end 65 | 66 | defp default_build_mode(:prod), do: :release_safe 67 | defp default_build_mode(_), do: :debug 68 | 69 | # Runs `zig build` and prints the stdout and stderr in real time, 70 | # as soon as `exec` prints them (using `IO.Stream`). 71 | defp cmd(exec, args, env) do 72 | opts = [ 73 | into: IO.stream(:stdio, :line), 74 | stderr_to_stdout: true, 75 | env: env 76 | ] 77 | 78 | {%IO.Stream{}, status} = System.cmd(exec, args, opts) 79 | status 80 | end 81 | 82 | defp raise_build_error(exec, exit_status) do 83 | Mix.raise("Could not compile with #{exec} (exit status: #{exit_status}).\n") 84 | end 85 | 86 | defp zig_install_prefix do 87 | :code.priv_dir(:build_dot_zig) |> to_string() 88 | end 89 | 90 | defp zig_download_version(_install = false), do: nil 91 | defp zig_download_version(_install = true), do: @latest_stable_zig 92 | defp zig_download_version(version) when is_binary(version), do: version 93 | 94 | defp exec(explicit_exec, _downloaded_zig_exec) when is_binary(explicit_exec) do 95 | explicit_exec 96 | |> Path.expand() 97 | |> System.find_executable() || 98 | Mix.raise(""" 99 | "#{explicit_exec}" not found in the path. If you have set the :zig_executable \ 100 | variable, please make sure it is correct. 101 | """) 102 | end 103 | 104 | defp exec(:default, :not_downloaded = _downloaded_zig_exec) do 105 | System.find_executable("zig") || 106 | Mix.raise(""" 107 | "zig not found in the path. If you set :install_zig to false, you have \ 108 | to manully install zig in your system and add it to the PATH. 109 | """) 110 | end 111 | 112 | defp exec(:default, downloaded_zig_exec) when is_binary(downloaded_zig_exec) do 113 | downloaded_zig_exec 114 | end 115 | 116 | defp build_args(install_prefix, build_path, build_mode, target, cpu, extra_options) do 117 | ["build"] ++ 118 | install_prefix_args(install_prefix) ++ 119 | cache_dir_args(build_path) ++ 120 | build_mode_args(build_mode) ++ 121 | target_args(target) ++ cpu_args(cpu) ++ extra_option_args(extra_options) 122 | end 123 | 124 | defp install_prefix_args(install_prefix) do 125 | ["-p", install_prefix] 126 | end 127 | 128 | defp cache_dir_args(build_path) do 129 | ["--cache-dir", cache_dir(build_path)] 130 | end 131 | 132 | defp build_mode_args(build_mode) do 133 | case build_mode do 134 | :debug -> 135 | [] 136 | 137 | :release_safe -> 138 | ["-Doptimize=ReleaseSafe"] 139 | 140 | :release_fast -> 141 | ["-Doptimize=ReleaseFast"] 142 | 143 | :release_small -> 144 | ["-Doptimize=ReleaseSmall"] 145 | 146 | other -> 147 | Mix.raise( 148 | "Invalid build mode #{inspect(other)} in :zig_build_mode. " <> 149 | "Should be one of: :debug, :release_safe, :release_fast, :release_small." 150 | ) 151 | end 152 | end 153 | 154 | defp cache_dir(build_path) do 155 | Path.join(build_path, "zig-cache") 156 | end 157 | 158 | defp target_args(:host) do 159 | [] 160 | end 161 | 162 | defp target_args(target) when is_binary(target) do 163 | ["-Dtarget=#{target}"] 164 | end 165 | 166 | defp cpu_args(:native) do 167 | [] 168 | end 169 | 170 | defp cpu_args(cpu) when is_binary(cpu) do 171 | ["-Dcpu=#{cpu}"] 172 | end 173 | 174 | defp extra_option_args(extra_options) when is_list(extra_options) do 175 | for {k, v} <- extra_options do 176 | "-D#{k}=#{v}" 177 | end 178 | end 179 | 180 | # Returns a map of default environment variables 181 | # Defaults may be overwritten. 182 | defp default_env(config) do 183 | root_dir = :code.root_dir() 184 | erl_interface_dir = Path.join(root_dir, "usr") 185 | erts_dir = Path.join(root_dir, "erts-#{:erlang.system_info(:version)}") 186 | erts_include_dir = Path.join(erts_dir, "include") 187 | erl_ei_lib_dir = Path.join(erl_interface_dir, "lib") 188 | erl_ei_include_dir = Path.join(erl_interface_dir, "include") 189 | 190 | %{ 191 | # Don't use Mix.target/0 here for backwards compatibility 192 | "MIX_TARGET" => env("MIX_TARGET", "host"), 193 | "MIX_ENV" => to_string(Mix.env()), 194 | "MIX_BUILD_PATH" => Mix.Project.build_path(config), 195 | "MIX_APP_PATH" => Mix.Project.app_path(config), 196 | "MIX_COMPILE_PATH" => Mix.Project.compile_path(config), 197 | "MIX_CONSOLIDATION_PATH" => Mix.Project.consolidation_path(config), 198 | "MIX_DEPS_PATH" => Mix.Project.deps_path(config), 199 | "MIX_MANIFEST_PATH" => Mix.Project.manifest_path(config), 200 | 201 | # Rebar naming 202 | "ERL_EI_LIBDIR" => env("ERL_EI_LIBDIR", erl_ei_lib_dir), 203 | "ERL_EI_INCLUDE_DIR" => env("ERL_EI_INCLUDE_DIR", erl_ei_include_dir), 204 | 205 | # erlang.mk naming 206 | "ERTS_INCLUDE_DIR" => env("ERTS_INCLUDE_DIR", erts_include_dir), 207 | "ERL_INTERFACE_LIB_DIR" => env("ERL_INTERFACE_LIB_DIR", erl_ei_lib_dir), 208 | "ERL_INTERFACE_INCLUDE_DIR" => env("ERL_INTERFACE_INCLUDE_DIR", erl_ei_include_dir), 209 | 210 | # Disable default erlang values 211 | "BINDIR" => nil, 212 | "ROOTDIR" => nil, 213 | "PROGNAME" => nil, 214 | "EMU" => nil 215 | } 216 | end 217 | 218 | defp maybe_add_zig_install_dir(env, :not_downloaded), do: env 219 | 220 | defp maybe_add_zig_install_dir(env, install_dir) when is_binary(install_dir) do 221 | # Add an env variable that points to the downloaded Zig install dir 222 | Map.put(env, "ZIG_INSTALL_DIR", install_dir) 223 | end 224 | 225 | defp env(var, default) do 226 | System.get_env(var) || default 227 | end 228 | 229 | defp ensure_downloaded_zig!(nil = _zig_version) do 230 | # If zig_version is nil, we just return :not_downloaded as install dir 231 | :not_downloaded 232 | end 233 | 234 | defp ensure_downloaded_zig!(zig_version) when is_binary(zig_version) do 235 | prefix = zig_install_prefix() 236 | 237 | # Avoid that multiple applications looking to install the same Zig version stomp on each others 238 | # feet by using a version-scoped lock 239 | lock_id = {__MODULE__, zig_version} 240 | 241 | :global.set_lock(lock_id) 242 | 243 | if not ZigInstaller.installed?(prefix, zig_version) do 244 | ZigInstaller.install!(prefix, zig_version) 245 | end 246 | 247 | :global.del_lock(lock_id) 248 | 249 | ZigInstaller.install_dir(prefix, zig_version) 250 | end 251 | 252 | defp downloaded_zig_exec(:not_downloaded), do: :not_downloaded 253 | 254 | defp downloaded_zig_exec(downloaded_zig_install_dir) do 255 | Path.join(downloaded_zig_install_dir, "zig") 256 | |> System.find_executable() || 257 | Mix.raise("zig executable not found in #{downloaded_zig_install_dir}") 258 | end 259 | end 260 | -------------------------------------------------------------------------------- /lib/build_dot_zig/http.ex: -------------------------------------------------------------------------------- 1 | defmodule BuildDotZig.HTTP do 2 | @moduledoc false 3 | 4 | # Extremely minimal HTTP client to download the Zig build index and compiler using :httpc 5 | def get(url) do 6 | request_timeout = 60_000 * 5 7 | request_connect_timeout = 30_000 8 | 9 | http_opts = build_http_opts(request_timeout, request_connect_timeout) 10 | opts = [body_format: :binary] 11 | request = {url, []} 12 | 13 | case :httpc.request(:get, request, http_opts, opts) do 14 | {:ok, {{_version, status, _reason}, headers, body}} -> 15 | {:ok, %{status: status, headers: headers, body: body}} 16 | 17 | {:error, reason} -> 18 | {:error, reason} 19 | end 20 | end 21 | 22 | defp build_http_opts(timeout, connect_timeout) do 23 | [ 24 | timeout: timeout, 25 | connect_timeout: connect_timeout, 26 | relaxed: true, 27 | ssl: build_ssl_opts() 28 | ] 29 | end 30 | 31 | defp build_ssl_opts do 32 | [ 33 | verify: :verify_peer, 34 | depth: 4, 35 | cacertfile: CAStore.file_path(), 36 | secure_renegotiate: true, 37 | reuse_sessions: true, 38 | customize_hostname_check: [ 39 | match_fun: :public_key.pkix_verify_hostname_match_fun(:https) 40 | ] 41 | ] 42 | end 43 | end 44 | -------------------------------------------------------------------------------- /lib/build_dot_zig/zig_installer.ex: -------------------------------------------------------------------------------- 1 | defmodule BuildDotZig.ZigInstaller do 2 | @moduledoc false 3 | 4 | require Logger 5 | 6 | alias BuildDotZig.HTTP 7 | 8 | def installed?(prefix, zig_version) do 9 | install_dir(prefix, zig_version) 10 | |> File.dir?() 11 | end 12 | 13 | def install!(prefix, zig_version) do 14 | zig_target = zig_target() 15 | 16 | case HTTP.get("https://ziglang.org/download/index.json") do 17 | {:ok, %{status: 200, body: body}} -> 18 | info = Jason.decode!(body) 19 | actual_version = actual_version(info, zig_version) 20 | 21 | Logger.info("Downloading zig #{actual_version}...") 22 | %{url: url, checksum: checksum} = archive_url_and_checksum(info, zig_version, zig_target) 23 | 24 | install_dir = install_dir(prefix, zig_version, zig_target) 25 | 26 | download_and_extract!(url, checksum, install_dir) 27 | 28 | other -> 29 | raise_download_error!("Could not retrieve Zig download info", other) 30 | end 31 | end 32 | 33 | def install_dir(prefix, zig_version, zig_target \\ zig_target()) do 34 | Path.join(prefix, "zig-#{zig_target}-#{zig_version}") 35 | |> Path.expand() 36 | end 37 | 38 | defp download_and_extract!(archive_url, checksum, install_dir) do 39 | case HTTP.get(archive_url) do 40 | {:ok, %{status: 200, body: archive}} -> 41 | verify_checksum!(archive, checksum) 42 | 43 | archive_filename = Path.basename(archive_url) 44 | File.write!(archive_filename, archive) 45 | extract_archive!(archive_filename, install_dir) 46 | 47 | other -> 48 | raise_download_error!("Could not download Zig archive", other) 49 | end 50 | end 51 | 52 | defp extract_archive!(archive_filename, install_dir) do 53 | temporary_archive_dir = 54 | cond do 55 | String.ends_with?(archive_filename, ".tar.xz") -> 56 | extract_tar_xz(archive_filename) 57 | 58 | String.ends_with?(archive_filename, ".zip") -> 59 | extract_zip(archive_filename) 60 | 61 | true -> 62 | Mix.raise("Unsupported archive format: #{archive_filename}") 63 | end 64 | 65 | File.rm!(archive_filename) 66 | 67 | File.rename!(temporary_archive_dir, install_dir) 68 | end 69 | 70 | defp extract_tar_xz(archive_filename) do 71 | {_, 0} = System.cmd("tar", ["-xf", archive_filename]) 72 | Path.basename(archive_filename, ".tar.xz") 73 | end 74 | 75 | defp extract_zip(archive_filename) do 76 | # windows needs a charlist path 77 | archive_filename_charlist = 78 | archive_filename 79 | |> to_charlist() 80 | 81 | {:ok, _} = :zip.unzip(archive_filename_charlist) 82 | Path.basename(archive_filename, ".zip") 83 | end 84 | 85 | defp raise_download_error!(msg, {:ok, %{status: status, body: body}}) do 86 | Mix.raise("#{msg} (status #{status}, response #{body})") 87 | end 88 | 89 | defp raise_download_error!(msg, {:error, reason}) do 90 | Mix.raise("#{msg} (reason #{inspect(reason)})") 91 | end 92 | 93 | defp verify_checksum!(archive, expected_checksum) do 94 | actual_checksum = 95 | :crypto.hash(:sha256, archive) 96 | |> Base.encode16(case: :lower) 97 | 98 | if actual_checksum != expected_checksum do 99 | Mix.raise("Zig checksum mismatch: expected #{expected_checksum}, got #{actual_checksum}") 100 | end 101 | 102 | :ok 103 | end 104 | 105 | defp actual_version(info, "master") do 106 | info 107 | |> Map.fetch!("master") 108 | |> Map.fetch!("version") 109 | end 110 | 111 | defp actual_version(_info, zig_version) do 112 | zig_version 113 | end 114 | 115 | defp archive_url_and_checksum(info, zig_version, zig_target) do 116 | version_map = 117 | Map.get(info, zig_version) || 118 | Mix.raise("Version #{zig_version} not found in Zig build index") 119 | 120 | target_map = 121 | Map.get(version_map, zig_target) || 122 | Mix.raise("Target #{zig_target} not found in Zig build index for version #{zig_version}") 123 | 124 | url = Map.fetch!(target_map, "tarball") 125 | checksum = Map.fetch!(target_map, "shasum") 126 | %{url: url, checksum: checksum} 127 | end 128 | 129 | defp zig_target do 130 | "#{arch()}-#{os()}" 131 | end 132 | 133 | defp os do 134 | case :erlang.system_info(:os_type) do 135 | {:unix, :linux} -> "linux" 136 | {:unix, :darwin} -> "macos" 137 | {:win32, _} -> "windows" 138 | other -> Mix.raise("Unsupported os type: #{inspect(other)}") 139 | end 140 | end 141 | 142 | defp arch do 143 | arch = 144 | :erlang.system_info(:system_architecture) 145 | |> to_string() 146 | 147 | cond do 148 | arch =~ "x86_64" -> "x86_64" 149 | arch =~ "aarch64" -> "aarch64" 150 | # Erlang just returns "win32" for Windows, assume it's x86_64 151 | # TODO: what happens for Windows on ARM? 152 | arch == "win32" -> "x86_64" 153 | true -> Mix.raise("Cannot determine architecture: #{arch}") 154 | end 155 | end 156 | end 157 | -------------------------------------------------------------------------------- /lib/mix/build_dot_zig.ex: -------------------------------------------------------------------------------- 1 | defmodule Mix.BuildDotZig do 2 | @moduledoc false 3 | 4 | def otp_app do 5 | Mix.Project.config() |> Keyword.fetch!(:app) 6 | end 7 | 8 | def app_base(app) do 9 | case Application.get_env(app, :namespace, app) do 10 | ^app -> app |> to_string() |> Macro.camelize() 11 | mod -> mod |> inspect() 12 | end 13 | end 14 | 15 | def lib_path(rel_path) do 16 | Path.join(["lib", rel_path]) 17 | end 18 | 19 | def src_path(rel_path) do 20 | Path.join(["src", rel_path]) 21 | end 22 | 23 | def render_parameter_placeholders(0 = _arity) do 24 | nil 25 | end 26 | 27 | def render_parameter_placeholders(arity) do 28 | placeholders = 29 | Stream.repeatedly(fn -> "_" end) 30 | |> Enum.take(arity) 31 | |> Enum.join(", ") 32 | 33 | ["(", placeholders, ")"] 34 | end 35 | end 36 | -------------------------------------------------------------------------------- /lib/mix/build_dot_zig/c_nif.ex: -------------------------------------------------------------------------------- 1 | defmodule Mix.BuildDotZig.CNif do 2 | @moduledoc false 3 | 4 | @enforce_keys [:otp_app, :module, :module_file, :library, :library_file, :functions] 5 | defstruct @enforce_keys 6 | 7 | alias Mix.BuildDotZig.CNif 8 | 9 | def new(module, library, functions) do 10 | otp_app = Mix.BuildDotZig.otp_app() 11 | 12 | base = Mix.BuildDotZig.app_base(otp_app) 13 | module = Module.concat([base, module]) 14 | module_path = Macro.underscore(module) 15 | module_file = Mix.BuildDotZig.lib_path(module_path <> ".ex") 16 | 17 | library_file = Mix.BuildDotZig.src_path(library <> ".c") 18 | 19 | %CNif{ 20 | otp_app: otp_app, 21 | module: module, 22 | module_file: module_file, 23 | library: library, 24 | library_file: library_file, 25 | functions: Enum.map(functions, &parse_function/1) 26 | } 27 | end 28 | 29 | defp parse_function(function) do 30 | [name, arity] = String.split(function, "/", parts: 2) 31 | 32 | int_arity = 33 | case Integer.parse(arity) do 34 | {int_arity, ""} -> 35 | int_arity 36 | 37 | _other -> 38 | Mix.raise("Invalid arity: `#{inspect(arity)}` given to generator. Expected an integer.") 39 | end 40 | 41 | {name, int_arity} 42 | end 43 | end 44 | -------------------------------------------------------------------------------- /lib/mix/tasks/build_dot_zig.gen.c_nif.ex: -------------------------------------------------------------------------------- 1 | defmodule Mix.Tasks.BuildDotZig.Gen.CNif do 2 | @shortdoc "Initializes a C NIF" 3 | 4 | @moduledoc """ 5 | Initializes a C NIF with its build system based on `build.zig`. 6 | 7 | mix build_dot_zig.gen.c_nif Math math sum/2 multiply/2 8 | 9 | The first argument is the Elixir module that will expose the NIF, relative to the base namespace 10 | of your app. In this case the generated module will be in `lib/your_app/math.ex` and will be 11 | called `YourApp.Math`. 12 | 13 | The second argument is the name of the NIF library. In this case the generated C file will be 14 | `src/math.c`. 15 | 16 | The other arguments represent the functions exposed by the NIF with their arity. Empty stubs 17 | for each of the listed functions will be generated both on the Elixir and C side. By default 18 | the function stubs just raise a `:not_implemented` error. 19 | 20 | ## Functions 21 | 22 | The functions are given using `name/arity` syntax. 23 | 24 | It's possible to pass the same function with multiple arities (e.g. `sum/2`, `sum/3`), in 25 | that case on the C side there will still be only a single function and its implementation 26 | will have to distinguish between the different arities at runtime by looking at `argc`. 27 | """ 28 | use Mix.Task 29 | 30 | alias Mix.BuildDotZig.CNif 31 | 32 | @doc false 33 | def run(args) do 34 | c_nif = build(args) 35 | 36 | create_files(c_nif, nif: c_nif) 37 | print_shell_instructions() 38 | end 39 | 40 | @doc false 41 | def build(args) do 42 | {_, parsed, _} = OptionParser.parse(args, switches: []) 43 | [module, library | functions] = validate_args!(parsed) 44 | 45 | CNif.new(module, library, functions) 46 | end 47 | 48 | @doc false 49 | def validate_args!([module, library | functions] = args) do 50 | if not valid_module?(module) do 51 | raise_with_help( 52 | "Expected the module argument, #{inspect(module)}, to be a valid module name" 53 | ) 54 | end 55 | 56 | if not valid_library?(library) do 57 | raise_with_help( 58 | "Expected the NIF library argument, #{inspect(library)}, to be a valid library name (lowercase and underscore)" 59 | ) 60 | end 61 | 62 | for function <- functions do 63 | if not valid_function?(function) do 64 | raise_with_help("Expected #{inspect(function)} to be in the form name/arity") 65 | end 66 | end 67 | 68 | args 69 | end 70 | 71 | def validate_args!(_) do 72 | raise_with_help("Invalid arguments") 73 | end 74 | 75 | defp valid_module?(module) do 76 | module =~ ~r/^[A-Z]\w*(\.[A-Z]\w*)*$/ 77 | end 78 | 79 | defp valid_library?(library) do 80 | # TODO: evaluate if this is ok or too strict/permissive 81 | library =~ ~r/^[a-z](_?[a-z]+)*[a-z]$/ 82 | end 83 | 84 | defp valid_function?(function) do 85 | # TODO: evaluate if this is ok or too strict/permissive 86 | function =~ ~r|^[a-z](_?[a-z]+)*[a-z]/\d+$| 87 | end 88 | 89 | @doc false 90 | @spec raise_with_help(String.t()) :: no_return() 91 | defp raise_with_help(msg) do 92 | Mix.raise(""" 93 | #{msg} 94 | 95 | mix build_dot_zig.gen.c_nif expects a module name followed by 96 | a library name followed by one or more function name with arity 97 | 98 | mix build_dot_zig.gen.c_nif Math math sum/2 multiply/2 99 | """) 100 | end 101 | 102 | defp create_files(%CNif{} = c_nif, binding) do 103 | %CNif{ 104 | module_file: module_file, 105 | library_file: library_file 106 | } = c_nif 107 | 108 | templates_dir = Application.app_dir(:build_dot_zig, "priv/templates/build_dot_zig.gen.c_nif") 109 | 110 | Mix.Generator.create_file( 111 | module_file, 112 | EEx.eval_file(Path.join(templates_dir, "module.ex.eex"), binding) 113 | ) 114 | 115 | Mix.Generator.create_file( 116 | library_file, 117 | EEx.eval_file(Path.join(templates_dir, "library.c.eex"), binding) 118 | ) 119 | 120 | Mix.Generator.create_file( 121 | "build.zig", 122 | EEx.eval_file(Path.join(templates_dir, "build.zig.eex"), binding) 123 | ) 124 | 125 | c_nif 126 | end 127 | 128 | defp print_shell_instructions do 129 | Mix.shell().info(""" 130 | 131 | Make sure you have :build_dot_zig in your list of compilers inside project/0 in mix.exs: 132 | def project do 133 | [ 134 | # ... 135 | compilers: [:build_dot_zig] ++ Mix.compilers(), 136 | # ... 137 | ] 138 | end 139 | """) 140 | end 141 | end 142 | -------------------------------------------------------------------------------- /lib/mix/tasks/compile.build_dot_zig.ex: -------------------------------------------------------------------------------- 1 | defmodule Mix.Tasks.Compile.BuildDotZig do 2 | @moduledoc """ 3 | Runs `zig build` using the `build.zig` file in the current project. 4 | 5 | This task runs `zig build` in the current project; any output coming from `zig build` is printed 6 | in real-time on stdout. 7 | 8 | ## Configuration 9 | 10 | This compiler can be configured through the return value of the `project/0` function in 11 | `mix.exs`; for example: 12 | 13 | def project() do 14 | [ 15 | app: :myapp, 16 | compilers: [:build_dot_zig] ++ Mix.compilers, 17 | deps: deps() 18 | ] 19 | end 20 | 21 | The following options are available: 22 | 23 | * `:install_zig` - (binary or boolean) determines if a Zig installation should be automatically 24 | downloaded and installed locally in the build directory. If `false`, no Zig installation is 25 | downloaded. If `true` (default), the latest Zig stable version is downloaded. Otherwise, it's 26 | possible to pass a specific Zig version, e.g. `install_zig: "0.14.0"`. 27 | 28 | > ### Zig version support {: .warning } 29 | > 30 | > `:build_dot_zig` currently supports only Zig version `>= 0.11.0` due to breaking changes 31 | > to the build options passed in the command line. As long as the command line interface 32 | > remains stable, it will be possible to support multiple Zig versions. 33 | 34 | * `:zig_executable` - (binary or `:default`) it's the executable to use as the `zig` 35 | program. If not provided or if `:default`, it defaults to the downloaded `zig` binary if 36 | the `install_zig` was configured to download Zig, otherwise it defaults to `zig` (it assumes 37 | to find it in the `PATH`). Note that it's possible to both install a downloaded Zig installation 38 | _and_ pass a local `:zig_executable`. This is useful for use cases where the downloaded Zig 39 | installation must be called through some wrapper script. 40 | 41 | * `:zig_build_mode` - (atom) allows choosing the build mode. The supported build modes are 42 | `:debug`, `:release_safe`, `:release_fast` and `:release_small`. By default the build mode 43 | is `:release_safe` when `Mix.env()` is `:prod` and `:debug` in all other cases. 44 | 45 | * `:zig_target` - (binary or `:host`) it's the target that will be passed with the 46 | `-Dtarget` flag to `zig`. This can be used to support cross-compilation. If not provided or if 47 | `:host` (which is the default returned by `Mix.target()`), the `-Dtarget` flag is not passed. 48 | 49 | * `:zig_cpu` - (binary or `:native`) the set of CPU features that will be passed with the 50 | `-Dcpu` flag to `zig`. If not provided or if `:native` the `-Dcpu` flag is not passed, which 51 | makes `zig` use _all_ the CPU features of the host. If you're not running the compiled code on 52 | the same machine where you're compiling, setting this to `"baseline"` is a good starting point. 53 | 54 | * `:zig_extra_options` - (keyword list) if you define additional options in your `build.zig` 55 | using `b.option()`, you can pass the values of those options here (e.g. 56 | `[some_option: "some_value"]`). 57 | 58 | ## Default environment variables 59 | 60 | This compiler also sets deveral default environment variables which are accessible 61 | from `build.zig`: 62 | 63 | * `MIX_TARGET` 64 | * `MIX_ENV` 65 | * `MIX_BUILD_PATH` - same as `Mix.Project.build_path/0` 66 | * `MIX_APP_PATH` - same as `Mix.Project.app_path/0` 67 | * `MIX_COMPILE_PATH` - same as `Mix.Project.compile_path/0` 68 | * `MIX_CONSOLIDATION_PATH` - same as `Mix.Project.consolidation_path/0` 69 | * `MIX_DEPS_PATH` - same as `Mix.Project.deps_path/0` 70 | * `MIX_MANIFEST_PATH` - same as `Mix.Project.manifest_path/0` 71 | * `ERL_EI_LIBDIR` 72 | * `ERL_EI_INCLUDE_DIR` 73 | * `ERTS_INCLUDE_DIR` 74 | * `ERL_INTERFACE_LIB_DIR` 75 | * `ERL_INTERFACE_INCLUDE_DIR` 76 | * `ZIG_INSTALL_DIR` - the directory where the Zig toolchain was downloaded, if it was. 77 | 78 | ## Compilation artifacts and working with priv directories 79 | 80 | Generally speaking, compilation artifacts are written to the `priv` directory, as that the only 81 | directory, besides `ebin`, which are available to Erlang/OTP applications. 82 | 83 | However, note that Mix projects supports the `:build_embedded` configuration, which controls if 84 | assets in the `_build` directory are symlinked (when `false`, the default) or copied (`true`). 85 | In order to support both options for `:build_embedded`, it is important to follow the given 86 | guidelines: 87 | 88 | * The `"priv"` directory must not exist in the source code 89 | * If there are static assets, `build.zig` should copy them over from a directory at the project 90 | root (not named "priv") 91 | 92 | This compiler passes `$MIX_APP_PATH/priv/$MIX_TARGET` as install prefix to `zig build`, so the 93 | resulting artifacts can be found in `$PREFIX/lib` for libraries and `$PREFIX/bin` for binaries. 94 | Note that the default `$MIX_TARGET` is `:host`. 95 | """ 96 | 97 | use Mix.Task.Compiler 98 | 99 | @doc false 100 | def run(_args) do 101 | BuildDotZig.Compiler.compile() 102 | end 103 | 104 | @doc false 105 | def clean do 106 | BuildDotZig.Compiler.clean() 107 | end 108 | end 109 | -------------------------------------------------------------------------------- /mix.exs: -------------------------------------------------------------------------------- 1 | defmodule BuildDotZig.MixProject do 2 | use Mix.Project 3 | 4 | @version "0.6.1" 5 | 6 | def project do 7 | [ 8 | app: :build_dot_zig, 9 | version: @version, 10 | elixir: "~> 1.14", 11 | start_permanent: Mix.env() == :prod, 12 | description: "A build.zig compiler for Mix", 13 | package: package(), 14 | docs: docs(), 15 | deps: deps() 16 | ] 17 | end 18 | 19 | # Run "mix help compile.app" to learn about applications. 20 | def application do 21 | [ 22 | extra_applications: [:ssl, :inets, :logger] 23 | ] 24 | end 25 | 26 | # Run "mix help deps" to learn about dependencies. 27 | defp deps do 28 | [ 29 | {:castore, "~> 1.0"}, 30 | {:jason, "~> 1.4"}, 31 | {:ex_doc, "~> 0.20", only: :docs} 32 | ] 33 | end 34 | 35 | defp package() do 36 | [ 37 | licenses: ["Apache-2.0"], 38 | links: %{"GitHub" => "https://github.com/rbino/build_dot_zig"}, 39 | maintainers: ["Riccardo Binetti"] 40 | ] 41 | end 42 | 43 | defp docs do 44 | [ 45 | main: "Mix.Tasks.Compile.BuildDotZig", 46 | extras: ["CHANGELOG.md"], 47 | source_ref: "v#{@version}", 48 | source_url: "https://github.com/rbino/build_dot_zig" 49 | ] 50 | end 51 | end 52 | -------------------------------------------------------------------------------- /mix.lock: -------------------------------------------------------------------------------- 1 | %{ 2 | "castore": {:hex, :castore, "1.0.12", "053f0e32700cbec356280c0e835df425a3be4bc1e0627b714330ad9d0f05497f", [:mix], [], "hexpm", "3dca286b2186055ba0c9449b4e95b97bf1b57b47c1f2644555879e659960c224"}, 3 | "earmark_parser": {:hex, :earmark_parser, "1.4.43", "34b2f401fe473080e39ff2b90feb8ddfeef7639f8ee0bbf71bb41911831d77c5", [:mix], [], "hexpm", "970a3cd19503f5e8e527a190662be2cee5d98eed1ff72ed9b3d1a3d466692de8"}, 4 | "ex_doc": {:hex, :ex_doc, "0.37.3", "f7816881a443cd77872b7d6118e8a55f547f49903aef8747dbcb345a75b462f9", [:mix], [{:earmark_parser, "~> 1.4.42", [hex: :earmark_parser, repo: "hexpm", optional: false]}, {:makeup_c, ">= 0.1.0", [hex: :makeup_c, repo: "hexpm", optional: true]}, {:makeup_elixir, "~> 0.14 or ~> 1.0", [hex: :makeup_elixir, repo: "hexpm", optional: false]}, {:makeup_erlang, "~> 0.1 or ~> 1.0", [hex: :makeup_erlang, repo: "hexpm", optional: false]}, {:makeup_html, ">= 0.1.0", [hex: :makeup_html, repo: "hexpm", optional: true]}], "hexpm", "e6aebca7156e7c29b5da4daa17f6361205b2ae5f26e5c7d8ca0d3f7e18972233"}, 5 | "jason": {:hex, :jason, "1.4.4", "b9226785a9aa77b6857ca22832cffa5d5011a667207eb2a0ad56adb5db443b8a", [:mix], [{:decimal, "~> 1.0 or ~> 2.0", [hex: :decimal, repo: "hexpm", optional: true]}], "hexpm", "c5eb0cab91f094599f94d55bc63409236a8ec69a21a67814529e8d5f6cc90b3b"}, 6 | "makeup": {:hex, :makeup, "1.2.1", "e90ac1c65589ef354378def3ba19d401e739ee7ee06fb47f94c687016e3713d1", [:mix], [{:nimble_parsec, "~> 1.4", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm", "d36484867b0bae0fea568d10131197a4c2e47056a6fbe84922bf6ba71c8d17ce"}, 7 | "makeup_elixir": {:hex, :makeup_elixir, "1.0.1", "e928a4f984e795e41e3abd27bfc09f51db16ab8ba1aebdba2b3a575437efafc2", [:mix], [{:makeup, "~> 1.0", [hex: :makeup, repo: "hexpm", optional: false]}, {:nimble_parsec, "~> 1.2.3 or ~> 1.3", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm", "7284900d412a3e5cfd97fdaed4f5ed389b8f2b4cb49efc0eb3bd10e2febf9507"}, 8 | "makeup_erlang": {:hex, :makeup_erlang, "1.0.2", "03e1804074b3aa64d5fad7aa64601ed0fb395337b982d9bcf04029d68d51b6a7", [:mix], [{:makeup, "~> 1.0", [hex: :makeup, repo: "hexpm", optional: false]}], "hexpm", "af33ff7ef368d5893e4a267933e7744e46ce3cf1f61e2dccf53a111ed3aa3727"}, 9 | "nimble_parsec": {:hex, :nimble_parsec, "1.4.2", "8efba0122db06df95bfaa78f791344a89352ba04baedd3849593bfce4d0dc1c6", [:mix], [], "hexpm", "4b21398942dda052b403bbe1da991ccd03a053668d147d53fb8c4e0efe09c973"}, 10 | } 11 | -------------------------------------------------------------------------------- /priv/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rbino/build_dot_zig/30680c5875067c25da567311ea5a40790d558675/priv/.gitkeep -------------------------------------------------------------------------------- /priv/templates/build_dot_zig.gen.c_nif/build.zig.eex: -------------------------------------------------------------------------------- 1 | const std = @import("std"); 2 | 3 | // Although this function looks imperative, note that its job is to 4 | // declaratively construct a build graph that will be executed by an external 5 | // runner. 6 | pub fn build(b: *std.Build) void { 7 | // Standard target options allows the person running `zig build` to choose 8 | // what target to build for. Here we do not override the defaults, which 9 | // means any target is allowed, and the default is native. Other options 10 | // for restricting supported target set are available. 11 | const target = b.standardTargetOptions(.{}); 12 | 13 | // Standard optimization options allow the person running `zig build` to select 14 | // between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall. Here we do not 15 | // set a preferred release mode, allowing the user to decide how to optimize. 16 | const optimize = b.standardOptimizeOption(.{}); 17 | 18 | // Get ERTS_INCLUDE_DIR from the env populated by :build_dot_zig 19 | const erts_include_dir = std.process.getEnvVarOwned(b.allocator, "ERTS_INCLUDE_DIR") catch blk: { 20 | // Fallback to extracting it from the erlang shell so it's possible to 21 | // execute zig build manually 22 | const argv = [_][]const u8{ 23 | "erl", 24 | "-eval", 25 | "io:format(\"~s\", [lists:concat([code:root_dir(), \"/erts-\", erlang:system_info(version), \"/include\"])])", 26 | "-s", 27 | "init", 28 | "stop", 29 | "-noshell", 30 | }; 31 | 32 | break :blk b.run(&argv); 33 | }; 34 | 35 | const lib = b.addSharedLibrary(.{ 36 | .name = "<%= nif.library %>", 37 | .target = target, 38 | .optimize = optimize, 39 | .link_libc = true, 40 | }); 41 | lib.addCSourceFile(.{ 42 | .file = .{ .src_path = .{ .owner = b, .sub_path = "<%= nif.library_file %>" } }, 43 | // Here you can pass a comma separated list of C flags, e.g. `&.{"-std=c17", ...}` 44 | .flags = &.{}, 45 | }); 46 | lib.addSystemIncludePath(.{ .cwd_relative = erts_include_dir }); 47 | // This is needed to avoid errors on MacOS when loading the NIF 48 | lib.linker_allow_shlib_undefined = true; 49 | 50 | // Do this so `lib` doesn't get prepended to the lib name, and `.so` is used 51 | // as suffix also on MacOS, since it's required by the NIF loading mechanism. 52 | // See https://github.com/ziglang/zig/issues/2231 53 | // Windows still needs the .dll suffix 54 | const lib_name = if (target.result.os.tag == .windows) "<%= nif.library %>.dll" else "<%= nif.library %>.so"; 55 | const nif_so_install = b.addInstallFileWithDir(lib.getEmittedBin(), .lib, lib_name); 56 | nif_so_install.step.dependOn(&lib.step); 57 | b.getInstallStep().dependOn(&nif_so_install.step); 58 | } 59 | -------------------------------------------------------------------------------- /priv/templates/build_dot_zig.gen.c_nif/library.c.eex: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | <%= for {name, _} <- Enum.dedup_by(nif.functions, fn {name, _arity} -> name end) do %> 4 | static ERL_NIF_TERM <%= name %>(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) 5 | { 6 | // TODO: implement NIF 7 | return enif_raise_exception(env, enif_make_atom(env, "not_implemented")); 8 | } 9 | <% end %> 10 | static ErlNifFunc nif_funcs[] = 11 | {<%= for {name, arity} <- nif.functions do %> 12 | {"<%= name %>", <%= arity %>, <%= name %>},<% end %> 13 | }; 14 | 15 | ERL_NIF_INIT(<%= to_string(nif.module) %>, nif_funcs, NULL, NULL, NULL, NULL) 16 | -------------------------------------------------------------------------------- /priv/templates/build_dot_zig.gen.c_nif/module.ex.eex: -------------------------------------------------------------------------------- 1 | defmodule <%= inspect nif.module %> do 2 | @on_load :load_nif 3 | @nif_path "priv/#{Mix.target()}/lib/<%= nif.library %>" 4 | 5 | defp load_nif do 6 | Application.app_dir(<%= inspect nif.otp_app %>, @nif_path) 7 | |> String.to_charlist() 8 | |> :erlang.load_nif(0) 9 | end 10 | <%= for {name, arity} <- nif.functions do %> 11 | def <%= name %><%= Mix.BuildDotZig.render_parameter_placeholders(arity) %> do 12 | :erlang.nif_error(:nif_not_loaded) 13 | end 14 | <% end %>end 15 | -------------------------------------------------------------------------------- /test/test_helper.exs: -------------------------------------------------------------------------------- 1 | ExUnit.start() 2 | --------------------------------------------------------------------------------