├── .editorconfig ├── .envrc ├── .github └── workflows │ ├── ci.yml │ ├── flakehub-cache.yml │ └── flakehub-publish-rolling.yaml ├── .gitignore ├── Cargo.lock ├── Cargo.toml ├── LICENSE ├── README.md ├── flake.lock ├── flake.nix └── src └── main.rs /.editorconfig: -------------------------------------------------------------------------------- 1 | # https://editorconfig.org 2 | root = true 3 | 4 | [*] 5 | indent_style = space 6 | indent_size = 2 7 | end_of_line = lf 8 | charset = utf-8 9 | trim_trailing_whitespace = true 10 | insert_final_newline = true 11 | 12 | [*.rs] 13 | indent_size = 4 14 | -------------------------------------------------------------------------------- /.envrc: -------------------------------------------------------------------------------- 1 | use flake 2 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: Nix + Wasm example project 2 | 3 | on: 4 | pull_request: 5 | push: 6 | branches: 7 | - main 8 | 9 | env: 10 | REPO: ${{ github.event.repository.name }} 11 | 12 | jobs: 13 | ci: 14 | runs-on: ubuntu-22.04 15 | steps: 16 | - name: git checkout 17 | uses: actions/checkout@v3 18 | 19 | - name: Install Nix 20 | uses: DeterminateSystems/nix-installer-action@v10 21 | 22 | - name: Set up Magic Nix Cache 23 | uses: DeterminateSystems/magic-nix-cache-action@v4 24 | 25 | - name: nix flake check 26 | run: | 27 | nix flake check --all-systems 28 | 29 | - name: Display package contents 30 | run: | 31 | nix build ".#hello-wasm-pkg" 32 | nix develop --command tree ./result 33 | 34 | - name: Build all packages 35 | run: | 36 | for pkg in hello-wasm-pkg hello-wasmedge-exec hello-wasmtime-exec; do 37 | nix build ".#${pkg}" 38 | done 39 | 40 | - name: Run scripts 41 | run: | 42 | nix run ".#hello-wasmedge-exec" 43 | nix run ".#hello-wasmtime-exec" 44 | -------------------------------------------------------------------------------- /.github/workflows/flakehub-cache.yml: -------------------------------------------------------------------------------- 1 | name: Push dev shell to FlakeHub Cache 2 | 3 | on: 4 | push: 5 | branches: [main] 6 | 7 | jobs: 8 | push-dev-shell-to-flakehub-cache: 9 | env: 10 | ACTIONS_STEP_DEBUG: true 11 | runs-on: ${{ matrix.systems.runner }} 12 | permissions: 13 | id-token: "write" 14 | contents: "read" 15 | strategy: 16 | matrix: 17 | systems: 18 | - nix-system: "aarch64-darwin" 19 | runner: "macos-latest-xlarge" 20 | - nix-system: "x86_64-darwin" 21 | runner: "macos-12" 22 | - nix-system: "x86_64-linux" 23 | runner: "ubuntu-22.04" 24 | steps: 25 | - uses: actions/checkout@v3 26 | - uses: DeterminateSystems/nix-installer-action@main 27 | - uses: DeterminateSystems/magic-nix-cache-action@main 28 | with: 29 | use-flakehub: true 30 | - name: Build dev shell for ${{ matrix.systems.nix-system }} on ${{ matrix.systems.runner }} 31 | run: nix build .#devShells.${{ matrix.systems.nix-system }}.default 32 | -------------------------------------------------------------------------------- /.github/workflows/flakehub-publish-rolling.yaml: -------------------------------------------------------------------------------- 1 | name: "Publish every Git push to main to FlakeHub" 2 | 3 | on: 4 | push: 5 | branches: 6 | - "main" 7 | 8 | jobs: 9 | flakehub-publish: 10 | runs-on: "ubuntu-22.04" 11 | permissions: 12 | id-token: "write" 13 | contents: "read" 14 | steps: 15 | - uses: "actions/checkout@v4" 16 | - uses: "DeterminateSystems/nix-installer-action@v10" 17 | - uses: "DeterminateSystems/flakehub-push@v3" 18 | with: 19 | name: "DeterminateSystems/nix-wasm-example" 20 | rolling: true 21 | visibility: "public" 22 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.wasm 2 | result 3 | /target/ 4 | -------------------------------------------------------------------------------- /Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | version = 3 4 | 5 | [[package]] 6 | name = "hello-wasm" 7 | version = "0.1.0" 8 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "hello-wasm" 3 | version = "0.1.0" 4 | edition = "2021" 5 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Nix + WebAssembly example project 2 | 3 | > [!INFO] 4 | > This repo was created as a complement to the [Nix as a WebAssembly build tool][blog-post] blog post on the [Determinate Systems blog][blog] and fulfilled its purpose. 5 | > It won't be updated further but you're free to use it [as you see fit](./LICENSE)! 6 | 7 | This repo houses an example project that uses [Nix] to build and hack on [WebAssembly][wasm] (Wasm) in [Rust]. 8 | 9 | ## Setup 10 | 11 | First, make sure that [Nix] is installed with [flakes] enabled. We recommend using our [Determinate Nix Installer][dni]: 12 | 13 | ```shell 14 | curl --proto '=https' --tlsv1.2 -sSf -L https://install.determinate.systems/nix \ 15 | | sh -s -- install 16 | ``` 17 | 18 | With Nix installed, you can activate the [development environment][dev]: 19 | 20 | ```shell 21 | nix develop 22 | ``` 23 | 24 | > [!NOTE] 25 | > This should happen automatically if you have [direnv] installed and run `direnv allow`. 26 | 27 | ## Packages 28 | 29 | Below are some packages you can build in this project. 30 | 31 | ### Build Wasm binary 32 | 33 | To build a Wasm binary from the [Rust sources](./src/main.rs): 34 | 35 | ```shell 36 | nix build ".#hello-wasm" 37 | ``` 38 | 39 | This generates a [stripped] Wasm binary at `result/lib/hello-wasm.wasm` (where `result` is a symlink to a [Nix store][store] path). 40 | 41 | ### Build a full Wasm package 42 | 43 | To build a Wasm binary from the Rust sources plus some other goodies: 44 | 45 | ```shell 46 | nix build ".#hello-wasm-pkg" 47 | 48 | # Inspect the package 49 | tree result 50 | ``` 51 | 52 | Inside the package you should see: 53 | 54 | * `lib/hello-wasm.wasm` (the same [stripped] binary from [above](#build-wasm-binary)) 55 | * `share/hello-wasm-dump.txt` (an [object dump][objdump]) 56 | * `share/hello-wasm.dist` (a [stats] file) 57 | * `share/hello-wasm.wat` (a human-readable [WAT] file) 58 | 59 | ### Run the binary 60 | 61 | You can also run the compiled binary using two different Wasm runtimes. 62 | 63 | To run it using [WasmEdge]: 64 | 65 | ```shell 66 | nix run ".#hello-wasmedge-exec" 67 | ``` 68 | 69 | To run it using [Wasmtime]: 70 | 71 | ```shell 72 | nix run ".#hello-wasmtime-exec" 73 | ``` 74 | 75 | ## Advantages of Nix for Wasm development 76 | 77 | * Many languages can build Wasm but creating multi-language development environments (without Nix, of course) is hard. 78 | * Successful Wasm development environments often a wide range of tools, compilers, runtimes, etc. 79 | * Nix can not only provide arbitrarily complex development environments but it can do so across Unix-based platforms. 80 | 81 | [blog]: https://determinate.systems/posts 82 | [blog-post]: https://determinate.systems/posts/nix-wasm 83 | [dev]: https://zero-to-nix.com/concepts/dev-env 84 | [direnv]: https://direnv.net 85 | [dni]: https://github.com/DeterminateSystems/nix-installer 86 | [flakes]: https://zero-to-nix.com/concepts/flakes 87 | [nix]: https://zero-to-nix.com 88 | [objdump]: https://webassembly.github.io/wabt/doc/wasm-objdump.1.html 89 | [rust]: https://rust-lang.org 90 | [stats]: https://webassembly.github.io/wabt/doc/wasm-stats.1.html 91 | [store]: https://zero-to-nix.com/concepts/nix-store 92 | [stripped]: https://webassembly.github.io/wabt/doc/wasm-strip.1.html 93 | [wasm]: https://webassembly.org 94 | [wasmedge]: https://wasmedge.org 95 | [wasmtime]: https://docs.wasmtime.dev 96 | [wat]: https://developer.mozilla.org/docs/WebAssembly/Understanding_the_text_format 97 | 98 | [^1]: `result` isn't a local directory but rather a symlink to the build result directory in the 99 | [Nix store][store]. It should have a path of the form `/nix/store/${HASH}-wasm-all`. 100 | -------------------------------------------------------------------------------- /flake.lock: -------------------------------------------------------------------------------- 1 | { 2 | "nodes": { 3 | "fenix": { 4 | "inputs": { 5 | "nixpkgs": [ 6 | "nixpkgs" 7 | ], 8 | "rust-analyzer-src": "rust-analyzer-src" 9 | }, 10 | "locked": { 11 | "lastModified": 1711952616, 12 | "narHash": "sha256-WJvDdOph001fA1Ap3AyaQtz/afJAe7meSG5uJAdSE+A=", 13 | "rev": "209048d7c545905c470f6f8c05c5061f391031a8", 14 | "revCount": 1822, 15 | "type": "tarball", 16 | "url": "https://api.flakehub.com/f/pinned/nix-community/fenix/0.1.1822%2Brev-209048d7c545905c470f6f8c05c5061f391031a8/018e98ba-d842-7dad-9d6a-0d0ee173b6b1/source.tar.gz" 17 | }, 18 | "original": { 19 | "type": "tarball", 20 | "url": "https://flakehub.com/f/nix-community/fenix/0.1.%2A.tar.gz" 21 | } 22 | }, 23 | "flake-compat": { 24 | "locked": { 25 | "lastModified": 1696426674, 26 | "narHash": "sha256-kvjfFW7WAETZlt09AgDn1MrtKzP7t90Vf7vypd3OL1U=", 27 | "rev": "0f9255e01c2351cc7d116c072cb317785dd33b33", 28 | "revCount": 57, 29 | "type": "tarball", 30 | "url": "https://api.flakehub.com/f/pinned/edolstra/flake-compat/1.0.1/018afb31-abd1-7bff-a5e4-cff7e18efb7a/source.tar.gz" 31 | }, 32 | "original": { 33 | "type": "tarball", 34 | "url": "https://flakehub.com/f/edolstra/flake-compat/%2A.tar.gz" 35 | } 36 | }, 37 | "flake-schemas": { 38 | "locked": { 39 | "lastModified": 1697467827, 40 | "narHash": "sha256-j8SR19V1SRysyJwpOBF4TLuAvAjF5t+gMiboN4gYQDU=", 41 | "rev": "764932025c817d4e500a8d2a4d8c565563923d29", 42 | "revCount": 29, 43 | "type": "tarball", 44 | "url": "https://api.flakehub.com/f/pinned/DeterminateSystems/flake-schemas/0.1.2/018b3da8-4cc3-7fbb-8ff7-1588413c53e2/source.tar.gz" 45 | }, 46 | "original": { 47 | "type": "tarball", 48 | "url": "https://flakehub.com/f/DeterminateSystems/flake-schemas/%2A.tar.gz" 49 | } 50 | }, 51 | "naersk": { 52 | "inputs": { 53 | "nixpkgs": [ 54 | "nixpkgs" 55 | ] 56 | }, 57 | "locked": { 58 | "lastModified": 1713520724, 59 | "narHash": "sha256-CO8MmVDmqZX2FovL75pu5BvwhW+Vugc7Q6ze7Hj8heI=", 60 | "rev": "c5037590290c6c7dae2e42e7da1e247e54ed2d49", 61 | "revCount": 335, 62 | "type": "tarball", 63 | "url": "https://api.flakehub.com/f/pinned/nix-community/naersk/0.1.335%2Brev-c5037590290c6c7dae2e42e7da1e247e54ed2d49/018ef76d-0fd8-71be-8bed-58aa46d5dc3a/source.tar.gz" 64 | }, 65 | "original": { 66 | "type": "tarball", 67 | "url": "https://flakehub.com/f/nix-community/naersk/0.1.%2A.tar.gz" 68 | } 69 | }, 70 | "nixpkgs": { 71 | "locked": { 72 | "lastModified": 1714253743, 73 | "narHash": "sha256-mdTQw2XlariysyScCv2tTE45QSU9v/ezLcHJ22f0Nxc=", 74 | "rev": "58a1abdbae3217ca6b702f03d3b35125d88a2994", 75 | "revCount": 617818, 76 | "type": "tarball", 77 | "url": "https://api.flakehub.com/f/pinned/NixOS/nixpkgs/0.1.617818%2Brev-58a1abdbae3217ca6b702f03d3b35125d88a2994/018f25c6-e917-75c9-967b-ebda3b3dc4ae/source.tar.gz" 78 | }, 79 | "original": { 80 | "type": "tarball", 81 | "url": "https://flakehub.com/f/NixOS/nixpkgs/0.1.%2A.tar.gz" 82 | } 83 | }, 84 | "root": { 85 | "inputs": { 86 | "fenix": "fenix", 87 | "flake-compat": "flake-compat", 88 | "flake-schemas": "flake-schemas", 89 | "naersk": "naersk", 90 | "nixpkgs": "nixpkgs" 91 | } 92 | }, 93 | "rust-analyzer-src": { 94 | "flake": false, 95 | "locked": { 96 | "lastModified": 1711885694, 97 | "narHash": "sha256-dyezzeSbWMpflma+E9USmvSxuLgGcNGcGw3cOnX36ko=", 98 | "owner": "rust-lang", 99 | "repo": "rust-analyzer", 100 | "rev": "e4a405f877efd820bef9c0e77a02494e47c17512", 101 | "type": "github" 102 | }, 103 | "original": { 104 | "owner": "rust-lang", 105 | "ref": "nightly", 106 | "repo": "rust-analyzer", 107 | "type": "github" 108 | } 109 | } 110 | }, 111 | "root": "root", 112 | "version": 7 113 | } 114 | -------------------------------------------------------------------------------- /flake.nix: -------------------------------------------------------------------------------- 1 | { 2 | description = "Nix + WebAssembly example project"; 3 | 4 | inputs = { 5 | nixpkgs.url = "https://flakehub.com/f/NixOS/nixpkgs/0.1.*.tar.gz"; 6 | fenix = { 7 | url = "https://flakehub.com/f/nix-community/fenix/0.1.*.tar.gz"; 8 | inputs.nixpkgs.follows = "nixpkgs"; 9 | }; 10 | naersk = { 11 | url = "https://flakehub.com/f/nix-community/naersk/0.1.*.tar.gz"; 12 | inputs.nixpkgs.follows = "nixpkgs"; 13 | }; 14 | flake-compat.url = "https://flakehub.com/f/edolstra/flake-compat/*.tar.gz"; 15 | flake-schemas.url = "https://flakehub.com/f/DeterminateSystems/flake-schemas/*.tar.gz"; 16 | }; 17 | 18 | outputs = { self, ... }@inputs: 19 | let 20 | pkgName = (self.lib.fromToml ./Cargo.toml).package.name; 21 | supportedSystems = [ "aarch64-darwin" "aarch64-linux" "x86_64-darwin" "x86_64-linux" ]; 22 | forAllSystems = f: inputs.nixpkgs.lib.genAttrs supportedSystems (system: f { 23 | pkgs = import inputs.nixpkgs { inherit system; overlays = [ self.overlays.default ]; }; 24 | inherit system; 25 | }); 26 | rustWasmTarget = "wasm32-wasip1"; 27 | in 28 | { 29 | overlays.default = final: prev: rec { 30 | system = final.stdenv.hostPlatform.system; 31 | 32 | # Builds a Rust toolchain from rust-toolchain.toml 33 | rustToolchain = with inputs.fenix.packages.${system}; 34 | combine [ 35 | latest.rustc 36 | latest.cargo 37 | targets.${rustWasmTarget}.latest.rust-std 38 | ]; 39 | 40 | buildRustWasiWasm = self.lib.buildRustWasiWasm final; 41 | buildWasmPackage = self.lib.buildWasmPackage final; 42 | buildRustWasmScript = self.lib.buildRustWasmScript final; 43 | buildRustWasmEdgeExec = self.lib.buildRustWasmEdgeExec final; 44 | buildRustWasmtimeExec = self.lib.buildRustWasmtimeExec final; 45 | }; 46 | 47 | # Development environments 48 | devShells = forAllSystems ({ pkgs, system }: { 49 | default = 50 | let 51 | helpers = with pkgs; [ direnv jq ]; 52 | in 53 | pkgs.mkShell { 54 | packages = helpers ++ (with pkgs; [ 55 | rustToolchain # cargo, etc. 56 | wabt # WebAssembly Binary Toolkit 57 | wasmedge # Wasm runtime 58 | wasmtime # Wasm runtime 59 | cargo-edit # cargo add, cargo rm, etc. 60 | tree # for visualizing results 61 | ]); 62 | }; 63 | }); 64 | 65 | packages = forAllSystems ({ pkgs, system }: rec { 66 | default = hello-wasm; 67 | hello-wasm = pkgs.buildRustWasiWasm { 68 | name = "hello-wasm"; 69 | src = self; 70 | }; 71 | hello-wasm-pkg = pkgs.buildWasmPackage { }; 72 | hello-wasmtime-exec = pkgs.buildRustWasmtimeExec { }; 73 | hello-wasmedge-exec = pkgs.buildRustWasmEdgeExec { }; 74 | }); 75 | 76 | lib = { 77 | # Helper function for reading TOML files 78 | fromToml = file: builtins.fromTOML (builtins.readFile file); 79 | 80 | handleArgs = 81 | { name ? null 82 | , src ? self 83 | , cargoToml ? ./Cargo.toml 84 | }: 85 | let 86 | meta = (self.lib.fromToml ./Cargo.toml).package; 87 | pkgName = if name == null then meta.name else name; 88 | pkgSrc = builtins.path { path = src; name = "${pkgName}-source"; }; 89 | in 90 | { 91 | inherit (meta) name; 92 | inherit pkgName; 93 | src = pkgSrc; 94 | inherit cargoToml; 95 | }; 96 | 97 | buildRustWasiWasm = pkgs: { name, src }: 98 | let 99 | naerskLib = pkgs.callPackage inputs.naersk { 100 | cargo = pkgs.rustToolchain; 101 | rustc = pkgs.rustToolchain; 102 | }; 103 | in 104 | naerskLib.buildPackage { 105 | inherit name src; 106 | CARGO_BUILD_TARGET = rustWasmTarget; 107 | buildInputs = with pkgs; [ wabt ]; 108 | postInstall = '' 109 | mkdir -p $out/lib 110 | wasm-strip $out/bin/${name}.wasm -o $out/lib/${name}.wasm 111 | rm -rf $out/bin 112 | wasm-validate $out/lib/${name}.wasm 113 | ''; 114 | }; 115 | 116 | buildRustWasmtimeExec = pkgs: args: 117 | let 118 | finalArgs = self.lib.handleArgs args; 119 | wasmPkg = self.lib.buildRustWasiWasm pkgs { 120 | inherit (finalArgs) name src; 121 | }; 122 | in 123 | pkgs.stdenv.mkDerivation rec { 124 | name = finalArgs.name; 125 | src = finalArgs.src; 126 | nativeBuildInputs = with pkgs; [ makeWrapper ]; 127 | installPhase = '' 128 | mkdir -p $out/lib 129 | cp ${wasmPkg}/lib/${finalArgs.name}.wasm $out/lib/${finalArgs.pkgName}.wasm 130 | makeWrapper ${pkgs.wasmtime}/bin/wasmtime $out/bin/${finalArgs.pkgName} \ 131 | --set WASMTIME_NEW_CLI 1 \ 132 | --add-flags "$out/lib/${finalArgs.pkgName}.wasm" 133 | ''; 134 | }; 135 | 136 | buildRustWasmEdgeExec = pkgs: args: 137 | let 138 | finalArgs = self.lib.handleArgs args; 139 | wasmPkg = self.lib.buildRustWasiWasm pkgs { 140 | inherit (finalArgs) name src; 141 | }; 142 | in 143 | pkgs.stdenv.mkDerivation rec { 144 | name = finalArgs.name; 145 | src = finalArgs.src; 146 | nativeBuildInputs = with pkgs; [ makeWrapper ]; 147 | installPhase = '' 148 | mkdir -p $out/lib 149 | cp ${wasmPkg}/lib/${finalArgs.name}.wasm $out/lib/${finalArgs.pkgName}.wasm 150 | makeWrapper ${pkgs.wasmedge}/bin/wasmedge $out/bin/${finalArgs.pkgName} \ 151 | --add-flags "$out/lib/${finalArgs.pkgName}.wasm" 152 | ''; 153 | }; 154 | 155 | # Take a Wasm binary and strip it, provide stats, etc. 156 | buildWasmPackage = pkgs: args: 157 | let 158 | finalArgs = self.lib.handleArgs args; 159 | wasmPkg = self.lib.buildRustWasiWasm pkgs { 160 | inherit (finalArgs) name src; 161 | }; 162 | in 163 | pkgs.stdenv.mkDerivation { 164 | name = finalArgs.name; 165 | src = finalArgs.src; 166 | buildInputs = with pkgs; [ 167 | # includes wasm-strip, wasm2wat, wasm-stats, wasm-objdump, and wasm-validate 168 | wabt 169 | ]; 170 | buildPhase = '' 171 | mkdir -p $out/{lib,share} 172 | cp ${wasmPkg}/lib/${finalArgs.name}.wasm $out/lib/${finalArgs.pkgName}.wasm 173 | wasm2wat $out/lib/${finalArgs.pkgName}.wasm > $out/share/${finalArgs.pkgName}.wat 174 | wasm-stats $out/lib/${finalArgs.pkgName}.wasm -o $out/share/${finalArgs.pkgName}.dist 175 | wasm-objdump \ 176 | --details $out/lib/${finalArgs.pkgName}.wasm > $out/share/${finalArgs.pkgName}-dump.txt 177 | ''; 178 | doCheck = true; 179 | }; 180 | }; 181 | }; 182 | } 183 | -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | println!("Hello there, Nix enthusiast!"); 3 | } 4 | --------------------------------------------------------------------------------