no-panic-0.1.32/.cargo_vcs_info.json0000644000000001360000000000100126230ustar { "git": { "sha1": "a2f1c4f80987498a688f74aa88c41891c34b8f25" }, "path_in_vcs": "" }no-panic-0.1.32/.github/FUNDING.yml000064400000000000000000000000201046102023000145600ustar 00000000000000github: dtolnay no-panic-0.1.32/.github/workflows/ci.yml000064400000000000000000000063021046102023000161270ustar 00000000000000name: CI on: push: pull_request: workflow_dispatch: schedule: [cron: "40 1 * * *"] permissions: contents: read env: RUSTFLAGS: -Dwarnings jobs: pre_ci: uses: dtolnay/.github/.github/workflows/pre_ci.yml@master test: name: Rust ${{matrix.rust}} needs: pre_ci if: needs.pre_ci.outputs.continue runs-on: ubuntu-latest strategy: fail-fast: false matrix: rust: [nightly, beta, stable, 1.82.0, 1.70.0] timeout-minutes: 45 steps: - uses: actions/checkout@v4 - uses: dtolnay/rust-toolchain@master with: toolchain: ${{matrix.rust}} - name: Enable deny(non_exhaustive_omitted_patterns) run: echo RUSTFLAGS=$(RUSTFLAGS)\ --cfg=exhaustive >> $GITHUB_ENV if: matrix.rust == 'nightly' - name: Enable type layout randomization run: echo RUSTFLAGS=${RUSTFLAGS}\ -Zrandomize-layout >> $GITHUB_ENV if: matrix.rust == 'nightly' - run: cargo test - uses: actions/upload-artifact@v4 if: matrix.rust == 'nightly' && always() with: name: Cargo.lock path: Cargo.lock continue-on-error: true xplat: name: ${{matrix.name}} needs: pre_ci if: needs.pre_ci.outputs.continue runs-on: ${{matrix.os}}-latest strategy: fail-fast: false matrix: include: - name: macOS os: macos - name: Windows os: windows timeout-minutes: 45 steps: - uses: actions/checkout@v4 - uses: dtolnay/rust-toolchain@nightly - name: Enable type layout randomization run: echo RUSTFLAGS=${RUSTFLAGS}\ -Zrandomize-layout >> $GITHUB_ENV - run: cargo test msrv: name: Rust 1.56.0 needs: pre_ci if: needs.pre_ci.outputs.continue runs-on: ubuntu-latest timeout-minutes: 45 steps: - uses: actions/checkout@v4 - uses: dtolnay/rust-toolchain@1.56.0 - run: cargo build minimal: name: Minimal versions needs: pre_ci if: needs.pre_ci.outputs.continue runs-on: ubuntu-latest timeout-minutes: 45 steps: - uses: actions/checkout@v4 - uses: dtolnay/rust-toolchain@nightly - run: cargo generate-lockfile -Z minimal-versions - run: cargo check --locked doc: name: Documentation needs: pre_ci if: needs.pre_ci.outputs.continue runs-on: ubuntu-latest timeout-minutes: 45 env: RUSTDOCFLAGS: -Dwarnings steps: - uses: actions/checkout@v4 - uses: dtolnay/rust-toolchain@nightly - uses: dtolnay/install@cargo-docs-rs - run: cargo docs-rs - run: cargo docs-rs -p noexcept clippy: name: Clippy runs-on: ubuntu-latest if: github.event_name != 'pull_request' timeout-minutes: 45 steps: - uses: actions/checkout@v4 - uses: dtolnay/rust-toolchain@clippy - run: cargo clippy --tests -- -Dclippy::all -Dclippy::pedantic outdated: name: Outdated runs-on: ubuntu-latest if: github.event_name != 'pull_request' timeout-minutes: 45 steps: - uses: actions/checkout@v4 - uses: dtolnay/rust-toolchain@stable - uses: dtolnay/install@cargo-outdated - run: cargo outdated --exit-code 1 no-panic-0.1.32/.gitignore000064400000000000000000000000361046102023000134020ustar 00000000000000/target **/*.rs.bk Cargo.lock no-panic-0.1.32/Cargo.lock0000644000000202150000000000100105760ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[package]] name = "dissimilar" version = "1.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "59f8e79d1fbf76bdfbde321e902714bf6c49df88a7dda6fc682fc2979226962d" [[package]] name = "equivalent" version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5" [[package]] name = "glob" version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d2fabcfbdc87f4758337ca535fb41a6d701b65693ce38287d856d1674551ec9b" [[package]] name = "hashbrown" version = "0.15.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bf151400ff0baff5465007dd2f3e717f3fe502074ca563069ce3a6629d07b289" [[package]] name = "indexmap" version = "2.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "707907fe3c25f5424cce2cb7e1cbcafee6bdbe735ca90ef77c29e84591e5b9da" dependencies = [ "equivalent", "hashbrown", ] [[package]] name = "itoa" version = "1.0.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d75a2a4b1b190afb6f5425f10f6a8f959d2ea0b9c2b1d79553551850539e4674" [[package]] name = "memchr" version = "2.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" [[package]] name = "no-panic" version = "0.1.32" dependencies = [ "proc-macro2", "quote", "rustversion", "scratch", "syn", "trybuild", ] [[package]] name = "proc-macro2" version = "1.0.92" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "37d3544b3f2748c54e147655edb5025752e2303145b5aefb3c3ea2c78b973bb0" dependencies = [ "unicode-ident", ] [[package]] name = "quote" version = "1.0.37" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b5b9d34b8991d19d98081b46eacdd8eb58c6f2b201139f7c5f643cc155a633af" dependencies = [ "proc-macro2", ] [[package]] name = "rustversion" version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0e819f2bc632f285be6d7cd36e25940d45b2391dd6d9b939e79de557f7014248" [[package]] name = "ryu" version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f3cb5ba0dc43242ce17de99c180e96db90b235b8a9fdc9543c96d2209116bd9f" [[package]] name = "scratch" version = "1.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a3cf7c11c38cb994f3d40e8a8cde3bbd1f72a435e4c49e85d6553d8312306152" [[package]] name = "serde" version = "1.0.215" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6513c1ad0b11a9376da888e3e0baa0077f1aed55c17f50e7b2397136129fb88f" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" version = "1.0.215" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ad1e866f866923f252f05c889987993144fb74e722403468a4ebd70c3cd756c0" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "serde_json" version = "1.0.133" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c7fceb2473b9166b2294ef05efcb65a3db80803f0b03ef86a5fc88a2b85ee377" dependencies = [ "itoa", "memchr", "ryu", "serde", ] [[package]] name = "serde_spanned" version = "0.6.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "87607cb1398ed59d48732e575a4c28a7a8ebf2454b964fe3f224f2afc07909e1" dependencies = [ "serde", ] [[package]] name = "syn" version = "2.0.89" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "44d46482f1c1c87acd84dea20c1bf5ebff4c757009ed6bf19cfd36fb10e92c4e" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] [[package]] name = "target-triple" version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "42a4d50cdb458045afc8131fd91b64904da29548bcb63c7236e0844936c13078" [[package]] name = "termcolor" version = "1.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755" dependencies = [ "winapi-util", ] [[package]] name = "toml" version = "0.8.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a1ed1f98e3fdc28d6d910e6737ae6ab1a93bf1985935a1193e68f93eeb68d24e" dependencies = [ "serde", "serde_spanned", "toml_datetime", "toml_edit", ] [[package]] name = "toml_datetime" version = "0.6.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0dd7358ecb8fc2f8d014bf86f6f638ce72ba252a2c3a2572f2a795f1d23efb41" dependencies = [ "serde", ] [[package]] name = "toml_edit" version = "0.22.22" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4ae48d6208a266e853d946088ed816055e556cc6028c5e8e2b84d9fa5dd7c7f5" dependencies = [ "indexmap", "serde", "serde_spanned", "toml_datetime", "winnow", ] [[package]] name = "trybuild" version = "1.0.101" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8dcd332a5496c026f1e14b7f3d2b7bd98e509660c04239c58b0ba38a12daded4" dependencies = [ "dissimilar", "glob", "serde", "serde_derive", "serde_json", "target-triple", "termcolor", "toml", ] [[package]] name = "unicode-ident" version = "1.0.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "adb9e6ca4f869e1180728b7950e35922a7fc6397f7b641499e8f3ef06e50dc83" [[package]] name = "winapi-util" version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf221c93e13a30d793f7645a0e7762c55d169dbb0a49671918a2319d289b10bb" dependencies = [ "windows-sys", ] [[package]] name = "windows-sys" version = "0.59.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" dependencies = [ "windows-targets", ] [[package]] name = "windows-targets" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" dependencies = [ "windows_aarch64_gnullvm", "windows_aarch64_msvc", "windows_i686_gnu", "windows_i686_gnullvm", "windows_i686_msvc", "windows_x86_64_gnu", "windows_x86_64_gnullvm", "windows_x86_64_msvc", ] [[package]] name = "windows_aarch64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" [[package]] name = "windows_aarch64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" [[package]] name = "windows_i686_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" [[package]] name = "windows_i686_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" [[package]] name = "windows_i686_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" [[package]] name = "windows_x86_64_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" [[package]] name = "windows_x86_64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" [[package]] name = "windows_x86_64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" [[package]] name = "winnow" version = "0.6.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "36c1fec1a2bb5866f07c25f68c26e565c4c200aebb96d7e55710c19d3e8ac49b" dependencies = [ "memchr", ] no-panic-0.1.32/Cargo.toml0000644000000030050000000000100106170ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" rust-version = "1.56" name = "no-panic" version = "0.1.32" authors = ["David Tolnay "] build = "build.rs" autolib = false autobins = false autoexamples = false autotests = false autobenches = false description = "Attribute macro to require that the compiler prove a function can't ever panic." documentation = "https://docs.rs/no-panic" readme = "README.md" categories = [ "no-std", "no-std::no-alloc", ] license = "MIT OR Apache-2.0" repository = "https://github.com/dtolnay/no-panic" [package.metadata.docs.rs] rustdoc-args = ["--generate-link-to-definition"] targets = ["x86_64-unknown-linux-gnu"] [lib] name = "no_panic" path = "src/lib.rs" proc-macro = true [[test]] name = "test" path = "tests/test.rs" [dependencies.proc-macro2] version = "1.0.74" [dependencies.quote] version = "1.0.35" [dependencies.syn] version = "2.0.46" features = ["full"] [dev-dependencies.rustversion] version = "1.0.13" [dev-dependencies.scratch] version = "1" [dev-dependencies.trybuild] version = "1.0.81" features = ["diff"] no-panic-0.1.32/Cargo.toml.orig000064400000000000000000000014511046102023000143030ustar 00000000000000[package] name = "no-panic" version = "0.1.32" authors = ["David Tolnay "] categories = ["no-std", "no-std::no-alloc"] description = "Attribute macro to require that the compiler prove a function can't ever panic." documentation = "https://docs.rs/no-panic" edition = "2021" license = "MIT OR Apache-2.0" repository = "https://github.com/dtolnay/no-panic" rust-version = "1.56" [lib] proc-macro = true [dependencies] proc-macro2 = "1.0.74" quote = "1.0.35" syn = { version = "2.0.46", features = ["full"] } [dev-dependencies] rustversion = "1.0.13" scratch = "1" trybuild = { version = "1.0.81", features = ["diff"] } [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] rustdoc-args = ["--generate-link-to-definition"] [workspace] members = ["noexcept", "noexcept-impl"] no-panic-0.1.32/LICENSE-APACHE000064400000000000000000000227731046102023000133520ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS no-panic-0.1.32/LICENSE-MIT000064400000000000000000000017771046102023000130630ustar 00000000000000Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. no-panic-0.1.32/README.md000064400000000000000000000105031046102023000126710ustar 00000000000000\#\[no\_panic\] =============== [github](https://github.com/dtolnay/no-panic) [crates.io](https://crates.io/crates/no-panic) [docs.rs](https://docs.rs/no-panic) [build status](https://github.com/dtolnay/no-panic/actions?query=branch%3Amaster) A Rust attribute macro to require that the compiler prove a function can't ever panic. ```toml [dependencies] no-panic = "0.1" ``` ```rust use no_panic::no_panic; #[no_panic] fn demo(s: &str) -> &str { &s[1..] } fn main() { println!("{}", demo("input string")); } ``` If the function does panic (or the compiler fails to prove that the function cannot panic), the program fails to compile with a linker error that identifies the function name. Let's trigger that by passing a string that cannot be sliced at the first byte: ```rust fn main() { println!("{}", demo("\u{1f980}input string")); } ``` ```console Compiling no-panic-demo v0.0.1 error: linking with `cc` failed: exit code: 1 | = note: /no-panic-demo/target/release/deps/no_panic_demo-7170785b672ae322.no_p anic_demo1-cba7f4b666ccdbcbbf02b7348e5df1b2.rs.rcgu.o: In function `_$LT$no_pani c_demo..demo..__NoPanic$u20$as$u20$core..ops..drop..Drop$GT$::drop::h72f8f423002 b8d9f': no_panic_demo1-cba7f4b666ccdbcbbf02b7348e5df1b2.rs:(.text._ZN72_$LT$no _panic_demo..demo..__NoPanic$u20$as$u20$core..ops..drop..Drop$GT$4drop17h72f8f42 3002b8d9fE+0x2): undefined reference to ` ERROR[no-panic]: detected panic in function `demo` ' collect2: error: ld returned 1 exit status ``` The error is not stellar but notice the ERROR\[no-panic\] part at the end that provides the name of the offending function.
### Caveats - Functions that require some amount of optimization to prove that they do not panic may no longer compile in debug mode after being marked `#[no_panic]`. - Panic detection happens at link time across the entire dependency graph, so any Cargo commands that do not invoke a linker will not trigger panic detection. This includes `cargo build` of library crates and `cargo check` of binary and library crates. - The attribute is useless in code built with `panic = "abort"`. If you find that code requires optimization to pass `#[no_panic]`, either make no-panic an optional dependency that you only enable in release builds, or add a section like the following to your Cargo.toml or .cargo/config.toml to enable very basic optimization in debug builds. ```toml [profile.dev] opt-level = 1 ``` If the code that you need to prove isn't panicking makes function calls to non-generic non-inline functions from a different crate, you may need thin LTO enabled for the linker to deduce those do not panic. ```toml [profile.release] lto = "thin" ``` If thin LTO isn't cutting it, the next thing to try would be fat LTO with a single codegen unit: ```toml [profile.release] lto = "fat" codegen-units = 1 ``` If you want no\_panic to just assume that some function you call doesn't panic, and get Undefined Behavior if it does at runtime, see [dtolnay/no-panic#16]; try wrapping that call in an `unsafe extern "C"` wrapper. [dtolnay/no-panic#16]: https://github.com/dtolnay/no-panic/issues/16
### Acknowledgments The linker error technique is based on [Kixunil]'s crate [`dont_panic`]. Check out that crate for other convenient ways to require absence of panics. [Kixunil]: https://github.com/Kixunil [`dont_panic`]: https://github.com/Kixunil/dont_panic
#### License Licensed under either of Apache License, Version 2.0 or MIT license at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this crate by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. no-panic-0.1.32/build.rs000064400000000000000000000016421046102023000130630ustar 00000000000000use std::env; use std::process::Command; use std::str; fn main() { println!("cargo:rerun-if-changed=build.rs"); let rustc = match rustc_minor_version() { Some(rustc) => rustc, None => return, }; if rustc >= 80 { println!("cargo:rustc-check-cfg=cfg(exhaustive)"); println!("cargo:rustc-check-cfg=cfg(no_unsafe_extern_blocks)"); } if rustc < 82 { // https://blog.rust-lang.org/2024/10/17/Rust-1.82.0.html#safe-items-with-unsafe-extern println!("cargo:rustc-cfg=no_unsafe_extern_blocks"); } } fn rustc_minor_version() -> Option { let rustc = env::var_os("RUSTC").unwrap(); let output = Command::new(rustc).arg("--version").output().ok()?; let version = str::from_utf8(&output.stdout).ok()?; let mut pieces = version.split('.'); if pieces.next() != Some("rustc 1") { return None; } pieces.next()?.parse().ok() } no-panic-0.1.32/src/lib.rs000064400000000000000000000232261046102023000133230ustar 00000000000000//! [![github]](https://github.com/dtolnay/no-panic) [![crates-io]](https://crates.io/crates/no-panic) [![docs-rs]](https://docs.rs/no-panic) //! //! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github //! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust //! [docs-rs]: https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs //! //!
//! //! A Rust attribute macro to require that the compiler prove a function can't //! ever panic. //! //! ```toml //! [dependencies] //! no-panic = "0.1" //! ``` //! //! ``` //! use no_panic::no_panic; //! //! #[no_panic] //! fn demo(s: &str) -> &str { //! &s[1..] //! } //! //! fn main() { //! # fn demo(s: &str) -> &str { //! # &s[1..] //! # } //! # //! println!("{}", demo("input string")); //! } //! ``` //! //! If the function does panic (or the compiler fails to prove that the function //! cannot panic), the program fails to compile with a linker error that //! identifies the function name. Let's trigger that by passing a string that //! cannot be sliced at the first byte: //! //! ```should_panic //! # fn demo(s: &str) -> &str { //! # &s[1..] //! # } //! # //! fn main() { //! println!("{}", demo("\u{1f980}input string")); //! } //! ``` //! //! ```console //! Compiling no-panic-demo v0.0.1 //! error: linking with `cc` failed: exit code: 1 //! | //! = note: /no-panic-demo/target/release/deps/no_panic_demo-7170785b672ae322.no_p //! anic_demo1-cba7f4b666ccdbcbbf02b7348e5df1b2.rs.rcgu.o: In function `_$LT$no_pani //! c_demo..demo..__NoPanic$u20$as$u20$core..ops..drop..Drop$GT$::drop::h72f8f423002 //! b8d9f': //! no_panic_demo1-cba7f4b666ccdbcbbf02b7348e5df1b2.rs:(.text._ZN72_$LT$no //! _panic_demo..demo..__NoPanic$u20$as$u20$core..ops..drop..Drop$GT$4drop17h72f8f42 //! 3002b8d9fE+0x2): undefined reference to ` //! //! ERROR[no-panic]: detected panic in function `demo` //! ' //! collect2: error: ld returned 1 exit status //! ``` //! //! The error is not stellar but notice the ERROR\[no-panic\] part at the end //! that provides the name of the offending function. //! //!
//! //! ## Caveats //! //! - Functions that require some amount of optimization to prove that they do //! not panic may no longer compile in debug mode after being marked //! `#[no_panic]`. //! //! - Panic detection happens at link time across the entire dependency graph, //! so any Cargo commands that do not invoke a linker will not trigger panic //! detection. This includes `cargo build` of library crates and `cargo check` //! of binary and library crates. //! //! - The attribute is useless in code built with `panic = "abort"`. //! //! If you find that code requires optimization to pass `#[no_panic]`, either //! make no-panic an optional dependency that you only enable in release builds, //! or add a section like the following to your Cargo.toml or .cargo/config.toml //! to enable very basic optimization in debug builds. //! //! ```toml //! [profile.dev] //! opt-level = 1 //! ``` //! //! If the code that you need to prove isn't panicking makes function calls to //! non-generic non-inline functions from a different crate, you may need thin //! LTO enabled for the linker to deduce those do not panic. //! //! ```toml //! [profile.release] //! lto = "thin" //! ``` //! //! If thin LTO isn't cutting it, the next thing to try would be fat LTO with a //! single codegen unit: //! //! ```toml //! [profile.release] //! lto = "fat" //! codegen-units = 1 //! ``` //! //! If you want no_panic to just assume that some function you call doesn't //! panic, and get Undefined Behavior if it does at runtime, see //! [dtolnay/no-panic#16]; try wrapping that call in an `unsafe extern "C"` //! wrapper. //! //! [dtolnay/no-panic#16]: https://github.com/dtolnay/no-panic/issues/16 //! //!
//! //! ## Acknowledgments //! //! The linker error technique is based on [Kixunil]'s crate [`dont_panic`]. //! Check out that crate for other convenient ways to require absence of panics. //! //! [Kixunil]: https://github.com/Kixunil //! [`dont_panic`]: https://github.com/Kixunil/dont_panic #![doc(html_root_url = "https://docs.rs/no-panic/0.1.32")] #![allow( clippy::doc_markdown, clippy::match_same_arms, clippy::missing_panics_doc )] #![cfg_attr(all(test, exhaustive), feature(non_exhaustive_omitted_patterns_lint))] extern crate proc_macro; use proc_macro::TokenStream; use proc_macro2::{Span, TokenStream as TokenStream2}; use quote::quote; use syn::parse::{Error, Nothing, Result}; use syn::{ parse_quote, FnArg, GenericArgument, Ident, ItemFn, Pat, PatType, Path, PathArguments, ReturnType, Token, Type, TypeInfer, TypeParamBound, }; #[proc_macro_attribute] pub fn no_panic(args: TokenStream, input: TokenStream) -> TokenStream { let args = TokenStream2::from(args); let input = TokenStream2::from(input); let expanded = match parse(args, input.clone()) { Ok(function) => expand_no_panic(function), Err(parse_error) => { let compile_error = parse_error.to_compile_error(); quote!(#compile_error #input) } }; TokenStream::from(expanded) } fn parse(args: TokenStream2, input: TokenStream2) -> Result { let function: ItemFn = syn::parse2(input)?; let _: Nothing = syn::parse2::(args)?; if function.sig.asyncness.is_some() { return Err(Error::new( Span::call_site(), "no_panic attribute on async fn is not supported", )); } Ok(function) } // Convert `Path` to `Path<_>` fn make_impl_trait_wild(ret: &mut Type) { match ret { #![cfg_attr(all(test, exhaustive), deny(non_exhaustive_omitted_patterns))] Type::ImplTrait(impl_trait) => { *ret = Type::Infer(TypeInfer { underscore_token: Token![_](impl_trait.impl_token.span), }); } Type::Array(ret) => make_impl_trait_wild(&mut ret.elem), Type::Group(ret) => make_impl_trait_wild(&mut ret.elem), Type::Paren(ret) => make_impl_trait_wild(&mut ret.elem), Type::Path(ret) => make_impl_trait_wild_in_path(&mut ret.path), Type::Ptr(ret) => make_impl_trait_wild(&mut ret.elem), Type::Reference(ret) => make_impl_trait_wild(&mut ret.elem), Type::Slice(ret) => make_impl_trait_wild(&mut ret.elem), Type::TraitObject(ret) => { for bound in &mut ret.bounds { if let TypeParamBound::Trait(bound) = bound { make_impl_trait_wild_in_path(&mut bound.path); } } } Type::Tuple(ret) => ret.elems.iter_mut().for_each(make_impl_trait_wild), Type::BareFn(_) | Type::Infer(_) | Type::Macro(_) | Type::Never(_) | Type::Verbatim(_) => {} _ => {} } } fn make_impl_trait_wild_in_path(path: &mut Path) { for segment in &mut path.segments { if let PathArguments::AngleBracketed(bracketed) = &mut segment.arguments { for arg in &mut bracketed.args { if let GenericArgument::Type(arg) = arg { make_impl_trait_wild(arg); } } } } } fn expand_no_panic(mut function: ItemFn) -> TokenStream2 { let mut move_self = None; let mut arg_pat = Vec::new(); let mut arg_val = Vec::new(); for (i, input) in function.sig.inputs.iter_mut().enumerate() { let numbered = Ident::new(&format!("__arg{}", i), Span::call_site()); match input { FnArg::Typed(PatType { pat, .. }) if match pat.as_ref() { Pat::Ident(pat) => pat.ident != "self", _ => true, } => { arg_pat.push(quote!(#pat)); arg_val.push(quote!(#numbered)); *pat = parse_quote!(mut #numbered); } FnArg::Typed(_) | FnArg::Receiver(_) => { move_self = Some(quote! { if false { loop {} #[allow(unreachable_code)] { let __self = self; } } }); } } } let has_inline = function .attrs .iter() .any(|attr| attr.path().is_ident("inline")); if !has_inline { function.attrs.push(parse_quote!(#[inline])); } let ret = match &function.sig.output { ReturnType::Default => quote!(-> ()), ReturnType::Type(arrow, output) => { let mut output = output.clone(); make_impl_trait_wild(&mut output); quote!(#arrow #output) } }; let stmts = function.block.stmts; let message = format!( "\n\nERROR[no-panic]: detected panic in function `{}`\n", function.sig.ident, ); let unsafe_extern = if cfg!(no_unsafe_extern_blocks) { None } else { Some(Token![unsafe](Span::call_site())) }; function.block = Box::new(parse_quote!({ struct __NoPanic; #unsafe_extern extern "C" { #[link_name = #message] fn trigger() -> !; } impl ::core::ops::Drop for __NoPanic { fn drop(&mut self) { unsafe { trigger(); } } } let __guard = __NoPanic; let __result = (move || #ret { #move_self #( let #arg_pat = #arg_val; )* #(#stmts)* })(); ::core::mem::forget(__guard); __result })); quote!(#function) } no-panic-0.1.32/tests/compiletest/mod.rs000064400000000000000000000047731046102023000162450ustar 00000000000000use std::fs; use std::io; use std::process::Command; use std::sync::Once; pub fn setup() { static BUILD: Once = Once::new(); BUILD.call_once(|| { let status = Command::new("cargo") .arg("build") .status() .expect("failed to build"); assert!(status.success()); }); } pub fn contains_panic(name: &str, code: &str) -> bool { let tempdir = scratch::path("no-panic").join(name); match fs::create_dir(&tempdir) { Ok(()) => {} Err(err) if err.kind() == io::ErrorKind::AlreadyExists => {} err @ Err(_) => err.unwrap(), } let prelude = stringify! { use no_panic::no_panic; }; let rs = tempdir.join(format!("{}.rs", name)); fs::write(&rs, format!("{}{}", prelude, code)).unwrap(); let status = Command::new("rustc") .arg("--crate-name") .arg(name) .arg(rs) .arg("--edition=2018") .arg("-C") .arg("opt-level=3") .arg("--emit=asm") .arg("--out-dir") .arg(&tempdir) .arg("--extern") .arg(format!( "no_panic=target/debug/{prefix}no_panic.{extension}", prefix = std::env::consts::DLL_PREFIX, extension = std::env::consts::DLL_EXTENSION, )) .arg("-D") .arg("warnings") .status() .expect("failed to execute rustc"); assert!(status.success()); let asm = tempdir.join(format!("{}.s", name)); let asm = fs::read_to_string(asm).unwrap(); asm.contains("detected panic in function") } macro_rules! assert_no_panic { ($(mod $name:ident { $($content:tt)* })*) => { mod no_panic { use crate::compiletest; $( #[test] fn $name() { compiletest::setup(); let name = stringify!($name); let content = stringify!($($content)*); assert!(!compiletest::contains_panic(name, content)); } )* } }; } macro_rules! assert_link_error { ($(mod $name:ident { $($content:tt)* })*) => { mod link_error { use crate::compiletest; $( #[test] fn $name() { compiletest::setup(); let name = stringify!($name); let content = stringify!($($content)*); assert!(compiletest::contains_panic(name, content)); } )* } }; } no-panic-0.1.32/tests/test.rs000064400000000000000000000114761046102023000141130ustar 00000000000000#[macro_use] mod compiletest; #[rustversion::attr(not(nightly), ignore = "requires nightly")] #[test] fn ui() { let t = trybuild::TestCases::new(); t.compile_fail("tests/ui/*.rs"); } assert_no_panic![ mod test_readme { #[no_panic] fn demo(s: &str) -> &str { &s[1..] } fn main() { println!("{}", demo("input string")); } } mod test_method_in_impl { struct S; impl S { #[no_panic] fn demo(self) -> &'static str { "test" } } fn main() { println!("{}", S.demo()); } } mod test_lifetime_elision { struct Buffer { bytes: [u8; 24], } #[no_panic] fn demo(buffer: &mut Buffer) -> &[u8] { &buffer.bytes[..] } fn main() { let mut buffer = Buffer { bytes: [0u8; 24] }; println!("{:?}", demo(&mut buffer)); } } mod test_receiver_lifetime_elision { struct Buffer { bytes: [u8; 24], } impl Buffer { #[no_panic] fn demo(&mut self, _s: &str) -> &[u8] { &self.bytes[..] } } fn main() { let mut buffer = Buffer { bytes: [0u8; 24] }; println!("{:?}", buffer.demo("")); } } mod test_ref_argument { #[no_panic] fn demo(ref i: i32) -> i32 { *i } fn main() { println!("{}", demo(0)); } } mod test_mut_argument { #[no_panic] fn demo(mut i: i32) -> i32 { i += 1; i } fn main() { println!("{}", demo(0)); } } mod test_ref_mut_argument { #[no_panic] fn demo(ref mut i: i32) -> i32 { *i += 1; *i } fn main() { println!("{}", demo(0)); } } mod test_borrow_from_mut_self { struct S { data: usize, } impl S { #[no_panic] fn get_mut(&mut self) -> &mut usize { &mut self.data } } fn main() { let mut s = S { data: 0 }; println!("{}", s.get_mut()); } } mod test_self_in_macro { struct S { data: usize, } macro_rules! id { ($expr:expr) => { $expr }; } impl S { #[no_panic] fn get_mut(&mut self) -> usize { id![self.data] } } fn main() { let mut s = S { data: 0 }; println!("{}", s.get_mut()); } } mod test_self_in_macro_containing_fn { pub struct S { data: usize, } macro_rules! emit { ($($tt:tt)*) => { $($tt)* }; } impl S { #[no_panic] fn get_mut(&mut self) -> usize { let _ = emit!({ #[allow(unknown_lints, non_local_definitions)] impl S { pub fn f(self) {} } }); self.data } } fn main() { let mut s = S { data: 0 }; println!("{}", s.get_mut()); } } mod test_self_with_std_pin { use std::pin::Pin; pub struct S; impl S { #[no_panic] fn f(mut self: Pin<&mut Self>) { let _ = self.as_mut(); } } fn main() {} } mod test_deref_coercion { #[no_panic] pub fn f(s: &str) -> &str { &s } fn main() {} } mod test_return_impl_trait { use std::io; #[no_panic] pub fn f() -> io::Result { Ok(Vec::new()) } fn main() {} } mod test_conditional_return { #[no_panic] pub fn f(i: i32) { if i < 0 { return; } } fn main() { println!("{:?}", f(-1)); } } mod test_conditional_return_macro { macro_rules! return_if_negative { ($e:expr) => { if $e < 0 { return; } }; } #[no_panic] pub fn f(i: i32) { return_if_negative!(i); } fn main() { println!("{:?}", f(-1)); } } ]; assert_link_error![ mod test_readme_bad { #[no_panic] fn demo(s: &str) -> &str { &s[1..] } fn main() { println!("{}", demo("\u{1f980}input string")); } } ]; no-panic-0.1.32/tests/ui/async-fn.rs000064400000000000000000000001441046102023000152550ustar 00000000000000use no_panic::no_panic; #[no_panic] async fn f() { g().await; } async fn g() {} fn main() {} no-panic-0.1.32/tests/ui/async-fn.stderr000064400000000000000000000003761046102023000161430ustar 00000000000000error: no_panic attribute on async fn is not supported --> tests/ui/async-fn.rs:3:1 | 3 | #[no_panic] | ^^^^^^^^^^^ | = note: this error originates in the attribute macro `no_panic` (in Nightly builds, run with -Z macro-backtrace for more info) no-panic-0.1.32/tests/ui/trait-fn.rs000064400000000000000000000001711046102023000152630ustar 00000000000000use no_panic::no_panic; trait Trait { #[no_panic] fn f(); } impl Trait for i32 { fn f() {} } fn main() {} no-panic-0.1.32/tests/ui/trait-fn.stderr000064400000000000000000000001401046102023000161360ustar 00000000000000error: expected curly braces --> tests/ui/trait-fn.rs:5:11 | 5 | fn f(); | ^