err-derive-0.3.1/.cargo_vcs_info.json0000644000000001360000000000100131010ustar { "git": { "sha1": "b15c6a33c7151bc79d67c100d79648f5c09330fa" }, "path_in_vcs": "" }err-derive-0.3.1/.gitignore000064400000000000000000000000540072674642500137100ustar 00000000000000/target **/*.rs.bk Cargo.lock libtest.rmeta err-derive-0.3.1/.gitlab-ci.yml000064400000000000000000000011330072674642500143530ustar 00000000000000image: rust:latest stages: - test - deploy # Use cargo to test the project test cargo stable: stage: test script: - rustc --version && cargo --version # Print version info for debugging - cargo test --all --verbose - cargo test --all --no-default-features test cargo 1.34: image: rust:1.34.0 stage: test script: - rustc --version && cargo --version - cargo run --example enums #deploy:crates.io: # image: registry.gitlab.com/torkleyy/cargo-publish-all:latest # stage: deploy # script: # - cargo-publish-all --token $CRATES_IO_TOKEN --yes # only: # refs: # - main err-derive-0.3.1/Cargo.lock0000644000000217630000000000100110650ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[package]] name = "bitflags" version = "1.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" [[package]] name = "bytecount" version = "0.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72feb31ffc86498dacdbd0fcebb56138e7177a8cc5cea4516031d15ae85a742e" [[package]] name = "camino" version = "1.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6f3132262930b0522068049f5870a856ab8affc80c70d08b6ecb785771a6fc23" dependencies = [ "serde", ] [[package]] name = "cargo-platform" version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cbdb825da8a5df079a43676dbe042702f1707b1109f713a01420fbb4cc71fa27" dependencies = [ "serde", ] [[package]] name = "cargo_metadata" version = "0.14.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ba2ae6de944143141f6155a473a6b02f66c7c3f9f47316f802f80204ebfe6e12" dependencies = [ "camino", "cargo-platform", "semver", "serde", "serde_json", ] [[package]] name = "cfg-if" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "err-derive" version = "0.3.1" dependencies = [ "proc-macro-error", "proc-macro2", "quote", "rustversion", "skeptic", "syn", "synstructure", ] [[package]] name = "error-chain" version = "0.12.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2d2f06b9cac1506ece98fe3231e3cc9c4410ec3d5b1f24ae1c8946f0742cdefc" dependencies = [ "version_check", ] [[package]] name = "fastrand" version = "1.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3fcf0cee53519c866c09b5de1f6c56ff9d647101f81c1964fa632e148896cdf" dependencies = [ "instant", ] [[package]] name = "glob" version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b919933a397b79c37e33b77bb2aa3dc8eb6e165ad809e58ff75bc7db2e34574" [[package]] name = "instant" version = "0.1.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7a5bbe824c507c5da5956355e86a746d82e0e1464f65d862cc5e71da70e94b2c" dependencies = [ "cfg-if", ] [[package]] name = "itoa" version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1aab8fc367588b89dcee83ab0fd66b72b50b72fa1904d7095045ace2b0c81c35" [[package]] name = "libc" version = "0.2.117" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e74d72e0f9b65b5b4ca49a346af3976df0f9c61d550727f349ecd559f251a26c" [[package]] name = "memchr" version = "2.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "308cc39be01b73d0d18f82a0e7b2a3df85245f84af96fdddc5d202d27e47b86a" [[package]] name = "proc-macro-error" version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c" dependencies = [ "proc-macro-error-attr", "proc-macro2", "quote", "syn", "version_check", ] [[package]] name = "proc-macro-error-attr" version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869" dependencies = [ "proc-macro2", "quote", "version_check", ] [[package]] name = "proc-macro2" version = "1.0.36" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c7342d5883fbccae1cc37a2353b09c87c9b0f3afd73f5fb9bba687a1f733b029" dependencies = [ "unicode-xid", ] [[package]] name = "pulldown-cmark" version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "34f197a544b0c9ab3ae46c359a7ec9cbbb5c7bf97054266fecb7ead794a181d6" dependencies = [ "bitflags", "memchr", "unicase", ] [[package]] name = "quote" version = "1.0.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "864d3e96a899863136fc6e99f3d7cae289dafe43bf2c5ac19b70df7210c0a145" dependencies = [ "proc-macro2", ] [[package]] name = "redox_syscall" version = "0.2.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8383f39639269cde97d255a32bdb68c047337295414940c68bdd30c2e13203ff" dependencies = [ "bitflags", ] [[package]] name = "remove_dir_all" version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3acd125665422973a33ac9d3dd2df85edad0f4ae9b00dafb1a05e43a9f5ef8e7" dependencies = [ "winapi", ] [[package]] name = "rustversion" version = "1.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2cc38e8fa666e2de3c4aba7edeb5ffc5246c1c2ed0e3d17e560aeeba736b23f" [[package]] name = "ryu" version = "1.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "73b4b750c782965c211b42f022f59af1fbceabdd026623714f104152f1ec149f" [[package]] name = "same-file" version = "1.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" dependencies = [ "winapi-util", ] [[package]] name = "semver" version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0486718e92ec9a68fbed73bb5ef687d71103b142595b406835649bebd33f72c7" dependencies = [ "serde", ] [[package]] name = "serde" version = "1.0.136" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ce31e24b01e1e524df96f1c2fdd054405f8d7376249a5110886fb4b658484789" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" version = "1.0.136" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "08597e7152fcd306f41838ed3e37be9eaeed2b61c42e2117266a554fab4662f9" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "serde_json" version = "1.0.78" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d23c1ba4cf0efd44be32017709280b32d1cea5c3f1275c3b6d9e8bc54f758085" dependencies = [ "itoa", "ryu", "serde", ] [[package]] name = "skeptic" version = "0.13.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "16d23b015676c90a0f01c197bfdc786c20342c73a0afdda9025adb0bc42940a8" dependencies = [ "bytecount", "cargo_metadata", "error-chain", "glob", "pulldown-cmark", "tempfile", "walkdir", ] [[package]] name = "syn" version = "1.0.86" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8a65b3f4ffa0092e9887669db0eae07941f023991ab58ea44da8fe8e2d511c6b" dependencies = [ "proc-macro2", "quote", "unicode-xid", ] [[package]] name = "synstructure" version = "0.12.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f36bdaa60a83aca3921b5259d5400cbf5e90fc51931376a9bd4a0eb79aa7210f" dependencies = [ "proc-macro2", "quote", "syn", "unicode-xid", ] [[package]] name = "tempfile" version = "3.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5cdb1ef4eaeeaddc8fbd371e5017057064af0911902ef36b39801f67cc6d79e4" dependencies = [ "cfg-if", "fastrand", "libc", "redox_syscall", "remove_dir_all", "winapi", ] [[package]] name = "unicase" version = "2.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "50f37be617794602aabbeee0be4f259dc1778fabe05e2d67ee8f79326d5cb4f6" dependencies = [ "version_check", ] [[package]] name = "unicode-xid" version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8ccb82d61f80a663efe1f787a51b16b5a51e3314d6ac365b08639f52387b33f3" [[package]] name = "version_check" version = "0.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" [[package]] name = "walkdir" version = "2.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "808cf2735cd4b6866113f648b791c6adc5714537bc222d9347bb203386ffda56" dependencies = [ "same-file", "winapi", "winapi-util", ] [[package]] name = "winapi" version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" dependencies = [ "winapi-i686-pc-windows-gnu", "winapi-x86_64-pc-windows-gnu", ] [[package]] name = "winapi-i686-pc-windows-gnu" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" [[package]] name = "winapi-util" version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178" dependencies = [ "winapi", ] [[package]] name = "winapi-x86_64-pc-windows-gnu" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" err-derive-0.3.1/Cargo.toml0000644000000024400000000000100110770ustar # 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 = "2018" name = "err-derive" version = "0.3.1" build = "build.rs" description = "Derive macro for `std::error::Error`" readme = "README.md" keywords = ["derive", "error", "display"] license = "MIT/Apache-2.0" repository = "https://gitlab.com/torkleyy/err-derive" [lib] proc-macro = true [dependencies.proc-macro-error] version = "1.0.0" [dependencies.proc-macro2] version = "1.0.1" [dependencies.quote] version = "1.0.2" [dependencies.skeptic] version = "0.13.5" optional = true [dependencies.syn] version = "1.0.5" [dependencies.synstructure] version = "0.12.2" [build-dependencies.rustversion] version = "1.0" [build-dependencies.skeptic] version = "0.13.5" optional = true [features] default = ["std"] std = [] [badges.gitlab] repository = "torkleyy/err-derive" [badges.maintenance] status = "passively-maintained" err-derive-0.3.1/Cargo.toml.orig000064400000000000000000000013130072674642500146060ustar 00000000000000[package] name = "err-derive" version = "0.3.1" description = "Derive macro for `std::error::Error`" readme = "README.md" keywords = ["derive", "error", "display"] repository = "https://gitlab.com/torkleyy/err-derive" license = "MIT/Apache-2.0" edition = "2018" build = "build.rs" [badges] gitlab = { repository = "torkleyy/err-derive" } maintenance = { status = "passively-maintained" } [lib] proc-macro = true [build-dependencies] rustversion = "1.0" skeptic = { version = "0.13.5", optional = true } [dependencies] quote = "1.0.2" syn = "1.0.5" synstructure = "0.12.2" proc-macro2 = "1.0.1" proc-macro-error = "1.0.0" skeptic = { version = "0.13.5", optional = true } [features] default = ["std"] std = [] err-derive-0.3.1/LICENSE000064400000000000000000000002150072674642500127240ustar 00000000000000The `nitric` repository is licensed under the Apache License, Version 2.0 (LICENSE-APACHE) or the MIT license (LICENSE-MIT), at your option. err-derive-0.3.1/LICENSE-APACHE000064400000000000000000000261210072674642500136470ustar 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 APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2018 Thomas Schaller Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. err-derive-0.3.1/LICENSE-MIT000064400000000000000000000020600072674642500133530ustar 00000000000000MIT License Copyright (c) 2018 Thomas Schaller Permission 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. err-derive-0.3.1/README.md000064400000000000000000000074250072674642500132100ustar 00000000000000# err-derive [![Build status](https://img.shields.io/gitlab/pipeline/torkleyy/err-derive.svg?style=flat-square)](https://gitlab.com/torkleyy/err-derive) [![Crates.io](https://img.shields.io/crates/v/err-derive.svg?style=flat-square)](https://crates.io/crates/err-derive) [![API Docs](https://img.shields.io/badge/API-on%20docs.rs-blue.svg?style=flat-square)](https://docs.rs/err-derive) A failure-like derive macro for the std `Error`. The source code is mostly copied from `failure-derive`. Minimum Rust version: 1.34.0 ## Motivation Why yet another error handling library? There already are dozen others, the most popular being: * [failure](https://docs.rs/failure/0.1.3/failure/) * [error-chain](https://docs.rs/error-chain/0.12.0/error_chain/) The former provides a nice `#[derive(Fail)]` macro, but it uses its own error type (`Fail`) and its usage is rather discouraged since `std::error::Error` is getting fixed to provide the same benefits as `Fail`. `error-chain` does support `std::error::Error`, but it uses a declarative for generating the error implementation which makes the syntax too obscure in my opinion. This crate tries to combine both advantages: * work with `std::error::Error` * provide a custom `#[derive(Error)]` that works just like `failure-derive` `err-derive` is compatible with `std`, including the recent change to deprecate `Error::cause` in favour of `Error::source`, and provides an easy syntax for generating the `Display` and `Error` boilerplate (the latter being 99% copied from `failure-derive`). ## Features `err-derive` can be applied to your error struct / enum and does the following for you: * Derive `Display` implementation * Derive `Error` implementation (implementing `source` to return the cause of the error) * Derive `From` implementations ## Usage Cargo.toml: ```toml [dependencies] err-derive = "0.1" ``` Rust code: ```rust,no_run #[cfg(feature = "std")] use std::error::Error; #[cfg(not(feature = "std"))] use std::fmt::Display; use std::path::PathBuf; use err_derive::Error; #[derive(Debug, Error)] pub enum FormatError { #[error(display = "invalid header (expected: {:?}, got: {:?})", expected, found)] InvalidHeader { expected: String, found: String, }, #[error(display = "missing attribute: {:?}", _0)] MissingAttribute(String), } #[derive(Debug, Error)] pub enum LoadingError { #[error(display = "could not decode file")] FormatError(#[error(source)] FormatError), #[error(display = "could not find file: {:?}", path)] NotFound { path: PathBuf }, } fn main() { let my_error: LoadingError = FormatError::MissingAttribute("some_attr".to_owned()).into(); print_error(&my_error); } #[cfg(feature = "std")] fn print_error(e: &dyn Error) { eprintln!("error: {}", e); let mut cause = e.source(); while let Some(e) = cause { eprintln!("caused by: {}", e); cause = e.source(); } } #[cfg(not(feature = "std"))] fn print_error(e: &dyn Display) { eprintln!("error: {}", e); } ``` ## no_std You can use this library in your `#![no_std]` projects by disabling the default `std` feature. ```toml [dependencies] err-derive = { version = "...", default-features = false } ``` Without the default `std` feature, only the `From` and `Display` implementations are derived, as `Error` requires `std`. ## Credit Credit goes to [@withoutboats](https://github.com/withoutboats) and [other contributors of `failure`](https://github.com/rust-lang-nursery/failure/graphs/contributors). ## License This project is dual-licensed under Apache-2.0 / MIT. You're free to choose one of both licenses. Every contribution made to this project is assumed to be licensed according to these terms. See LICENSE, [LICENSE-MIT](LICENSE-MIT) and [LICENSE-APACHE](LICENSE-APACHE) for more information. err-derive-0.3.1/build.rs000064400000000000000000000003310072674642500133630ustar 00000000000000#[rustversion::before(1.34)] compile_error!("`err-derive` depends on `proc-macro-error`, which requires rustc >= 1.34"); fn main() { #[cfg(feature = "skeptic")] skeptic::generate_doc_tests(&["README.md"]); } err-derive-0.3.1/deny.toml000064400000000000000000000000730072674642500135550ustar 00000000000000[licenses] allow-osi-fsf-free = "either" copyleft = "warn" err-derive-0.3.1/examples/enums.rs000064400000000000000000000021770072674642500152430ustar 00000000000000#[cfg(feature = "std")] use std::error::Error; #[cfg(not(feature = "std"))] use std::fmt::Display; use std::path::PathBuf; use err_derive::Error; #[derive(Debug, Error)] pub enum FormatError { #[error( display = "invalid header (expected: {:?}, got: {:?})", expected, found )] InvalidHeader { expected: String, found: String }, #[error(display = "missing attribute: {:?}", _0)] MissingAttribute(String), } #[derive(Debug, Error)] pub enum LoadingError { #[error(display = "could not decode file")] FormatError(#[error(source)] FormatError), #[error(display = "could not find file: {:?}", path)] NotFound { path: PathBuf }, } fn main() { let my_error: LoadingError = FormatError::MissingAttribute("some_attr".to_owned()).into(); print_error(&my_error); } #[cfg(feature = "std")] fn print_error(e: &dyn Error) { eprintln!("error: {}", e); let mut cause = e.source(); while let Some(e) = cause { eprintln!("caused by: {}", e); cause = e.source(); } } #[cfg(not(feature = "std"))] fn print_error(e: &dyn Display) { eprintln!("error: {}", e); } err-derive-0.3.1/src/lib.rs000064400000000000000000000357600072674642500136370ustar 00000000000000//! # `err-derive` //! //! ## Deriving error causes / sources //! //! Add an `#[error(source)]` attribute to the field: //! //! ``` //! use std::io; //! use err_derive::Error; //! //! /// `MyError::source` will return a reference to the `io_error` field //! #[derive(Debug, Error)] //! #[error(display = "An error occurred.")] //! struct MyError { //! #[error(source)] //! io_error: io::Error, //! } //! # //! # fn main() {} //! ``` //! //! ## Automatic From implementations //! //! From will be automatically implemented when there is a single field //! in the enum variant or struct, and that field has the `#[source]` attribute. //! //! In cases where multiple enum variants have a `#[source]` field of the same type //! all but one of the variants need to be opted-out from the automatic From implementation (see //! below). //! //! ``` //! use std::io; //! use err_derive::Error; //! //! /// `From` will be implemented for `MyError` //! #[derive(Debug, Error)] //! #[error(display = "An error occurred.")] //! struct MyError { //! #[error(from)] //! io_error: io::Error, //! } //! # //! # fn main() {} //! ``` //! //! ### Opt out of From implementation //! //! Use the `#[no_from]` attribute on either the enum or a single variant to opt-out of the //! automatic From implementation. //! //! When `#[no_from]` is set on the enum, you can opt-in individual variants by using `#[from]` //! //! ```rust //! use err_derive::Error; //! use std::{io, fmt}; //! //! #[derive(Debug, Error)] //! enum ClientError { //! #[error(display = "regular bad io error {}", _0)] //! Io(#[source] io::Error), //! #[error(display = "extra bad io error {}", _0)] //! // Without #[no_from], this From impl would conflict with the normal Io error //! ReallyBadIo(#[error(source, no_from)] io::Error) //! } //! //! #[derive(Debug, Error)] //! #[error(no_from)] // Don't impl From for any variants by default //! enum InnerError { //! #[error(display = "an error")] //! Io(#[source] io::Error), //! #[error(display = "an error")] //! // Opt-in impl From for a single variant //! Formatting(#[error(source, from)] fmt::Error) //! } //! ``` //! //! ### Auto-boxing From implementation //! //! If an enum single variant has `Box` as its type, a `From` //! implementation for `T` will be automatically be generated that wraps it in //! `Box::new`. //! //! ```rust //! use err_derive::Error; //! use std::{io, fmt}; //! //! #[derive(Debug, Error)] //! enum ClientError { //! #[error(display = "io error in a box{}", _0)] //! Io(#[error(source)] Box), //! } //! ``` //! //! ## Formatting fields //! //! ```rust //! use std::path::PathBuf; //! use err_derive::Error; //! //! #[derive(Debug, Error)] //! pub enum FormatError { //! #[error(display = "invalid header (expected: {:?}, got: {:?})", expected, found)] //! InvalidHeader { //! expected: String, //! found: String, //! }, //! // Note that tuple fields need to be prefixed with `_` //! #[error(display = "missing attribute: {:?}", _0)] //! MissingAttribute(String), //! //! } //! //! #[derive(Debug, Error)] //! pub enum LoadingError { //! #[error(display = "could not decode file")] //! FormatError(#[error(source)] #[error(from)] FormatError), //! #[error(display = "could not find file: {:?}", path)] //! NotFound { path: PathBuf }, //! } //! # //! # fn main() {} //! ``` //! //! ## Printing the error //! //! ``` //! use std::error::Error; //! //! fn print_error(e: &dyn Error) { //! eprintln!("error: {}", e); //! let mut cause = e.source(); //! while let Some(e) = cause { //! eprintln!("caused by: {}", e); //! cause = e.source(); //! } //! } //! ``` //! extern crate proc_macro; extern crate syn; use quote::quote; use synstructure::decl_derive; use proc_macro::TokenStream; use proc_macro2::TokenStream as TokenStream2; use syn::spanned::Spanned; extern crate proc_macro_error; use proc_macro_error::{abort, proc_macro_error}; use syn::Attribute; decl_derive!([Error, attributes(error, source, cause)] => #[proc_macro_error] error_derive); fn error_derive(s: synstructure::Structure) -> TokenStream { let source_body = s.each_variant(|v| { if let Some(source) = v.bindings().iter().find(|binding| { has_attr(&binding.ast().attrs, "source") || has_attr(&binding.ast().attrs, "cause") }) // TODO https://github.com/rust-lang/rust/issues/54140 deprecate cause with warning { quote!(return Some(#source as & ::std::error::Error)) } else { quote!(return None) } }); let source_method = quote! { #[allow(unreachable_code)] fn source(&self) -> ::std::option::Option<&(::std::error::Error + 'static)> { match *self { #source_body } None } }; let cause_method = quote! { #[allow(unreachable_code)] fn cause(&self) -> ::std::option::Option<& ::std::error::Error> { match *self { #source_body } None } }; let error = if cfg!(feature = "std") { s.unbound_impl( quote!(::std::error::Error), quote! { fn description(&self) -> &str { "description() is deprecated; use Display" } #cause_method #source_method }, ) } else { quote!() }; let display_body = display_body(&s); let display = s.unbound_impl( quote!(::core::fmt::Display), quote! { #[allow(unreachable_code)] fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { match *self { #display_body } write!(f, "An error has occurred.") } }, ); let from = from_body(&s); quote!(#error #display #from).into() } fn display_body(s: &synstructure::Structure) -> TokenStream2 { s.each_variant(|v| { let span = v.ast().ident.span(); let msg = match find_error_msg(&v.ast().attrs) { Some(msg) => msg, None => abort!(span, "Variant is missing display attribute."), }; if msg.nested.is_empty() { abort!(span, "Expected at least one argument to error attribute"); } let format_string = match msg.nested[0] { syn::NestedMeta::Meta(syn::Meta::NameValue(ref nv)) if nv .path .get_ident() .map_or(false, |ident| ident == "display") => { nv.lit.clone() } _ => abort!( msg.nested.span(), "Error attribute must begin `display = \"\"` to control the Display message." ), }; let args = msg.nested.iter().skip(1).map(|arg| match *arg { syn::NestedMeta::Lit(syn::Lit::Int(ref i)) => { let bi = &v.bindings()[i .base10_parse::() .unwrap_or_else(|_| abort!(i.span(), "integer literal overflows usize"))]; quote!(#bi) } syn::NestedMeta::Meta(syn::Meta::Path(ref path)) => { let id = match path.get_ident() { Some(id) => id, // Allows std::u8::MAX (for example) None => return quote!(#arg), }; let id_s = id.to_string(); if id_s.starts_with('_') { if let Ok(idx) = id_s[1..].parse::() { let bi = match v.bindings().get(idx) { Some(bi) => bi, None => { abort!( id.span(), "display attempted to access field `{}` in `{}::{}` which \ does not exist (there {} {} field{})", idx, s.ast().ident, v.ast().ident, if v.bindings().len() != 1 { "are" } else { "is" }, v.bindings().len(), if v.bindings().len() != 1 { "s" } else { "" } ); } }; return quote!(#bi); } } for bi in v.bindings() { if bi.ast().ident.as_ref() == Some(id) { return quote!(#bi); } } // Arg is not a field - might be in global scope return quote!(#id); } // Allows u8::max_value() (for example) syn::NestedMeta::Meta(syn::Meta::List(ref list)) => return quote!(#list), _ => abort!(msg.nested.span(), "Invalid argument to error attribute!"), }); quote! { return write!(f, #format_string #(, #args)*) } }) } fn find_error_msg(attrs: &[syn::Attribute]) -> Option { let mut error_msg = None; for attr in attrs { if let Ok(meta) = attr.parse_meta() { if meta .path() .get_ident() .map_or(false, |ident| ident == "error") { let span = attr.span(); if error_msg.is_some() { abort!(span, "Cannot have two display attributes") } else if let syn::Meta::List(list) = meta { error_msg = Some(list); } else { abort!(span, "error attribute must take a list in parentheses") } } } } error_msg } fn has_attr(attributes: &[Attribute], attr_name: &str) -> bool { let mut found_attr = false; for attr in attributes { if let Ok(meta) = attr.parse_meta() { if meta .path() .get_ident() .map_or(false, |ident| ident == attr_name) { if found_attr { abort!(attr.span(), "Cannot have two `{}` attributes", attr_name); } found_attr = true; } if meta .path() .get_ident() .map_or(false, |ident| ident == "error") { if let syn::Meta::List(ref list) = meta { for pair in list.nested.iter() { if let syn::NestedMeta::Meta(syn::Meta::Path(path)) = pair { let is_attr_name = |ident: &syn::Ident| { ident.to_string().split(", ").any(|part| part == attr_name) }; if path.get_ident().map_or(false, is_attr_name) { if found_attr { abort!( path.span(), "Cannot have two `{}` attributes", attr_name ); } found_attr = true; } } } } } } } found_attr } // If `ty` is a `Box`, return `Some(T)`. Otherwise return `None`. fn box_content_type(ty: &syn::Type) -> Option<&syn::Type> { let path = match ty { syn::Type::Path(p) => p, _ => return None, }; if path.path.segments.len() != 1 { return None; } let seg = &path.path.segments[0]; if seg.ident != "Box" { return None; } let args = match &seg.arguments { syn::PathArguments::AngleBracketed(args) => args, _ => return None, }; if args.args.len() != 1 { return None; } let inner_ty = match &args.args[0] { syn::GenericArgument::Type(ty) => ty, _ => return None, }; Some(inner_ty) } fn from_body(s: &synstructure::Structure) -> TokenStream2 { let default_from = !has_attr(&s.ast().attrs, "no_from"); let mut from_types = Vec::new(); let froms = s.variants().iter().flat_map(|v| { let span = v.ast().ident.span(); if let Some((from, is_explicit)) = v.bindings().iter().find_map(|binding| { let is_explicit = has_attr(&binding.ast().attrs, "from"); let is_source = has_attr(&binding.ast().attrs, "source"); // TODO https://github.com/rust-lang/rust/issues/54140 deprecate cause with warning let is_cause = has_attr(&binding.ast().attrs, "cause"); let exclude = has_attr(&binding.ast().attrs, "no_from"); if is_source && is_cause { abort!( span, "#[error(cause)] is deprecated, use #[error(source)] instead" ) } let is_source = is_source || is_cause; if ((default_from && is_source) || is_explicit) && !exclude { Some((binding, is_explicit)) } else { None } }) { if v.bindings().len() > 1 { if is_explicit { abort!( span, "Variants containing `from` can only contain a single field" ); } else { return vec![]; } } let from_ident = &from.ast().ty; if from_types .iter() .any(|existing_from_type| *existing_from_type == from_ident) { abort!( from_ident.span(), "`from` can only be applied for a type once{}", if is_explicit { "" } else { ", hint: use #[error(no_from)] to disable automatic From derive" } ); } from_types.push(from_ident); let construct = v.construct(|_, _| quote! {from}); let mut from_impls = vec![s.unbound_impl( quote! {::core::convert::From<#from_ident>}, quote! { fn from(from: #from_ident) -> Self { #construct } }, )]; if let Some(box_content_ty) = box_content_type(from_ident) { from_impls.push(s.unbound_impl( quote! {::core::convert::From<#box_content_ty>}, quote! { fn from(from: #box_content_ty) -> Self { Box::new(from).into() } }, )); } from_impls } else { vec![] } }); quote! { #(#froms)* } } err-derive-0.3.1/tests/no-std.rs000064400000000000000000000016040072674642500146360ustar 00000000000000#![cfg(not(feature = "std"))] extern crate alloc; use alloc::format; use alloc::string::{String, ToString}; use err_derive::Error; #[derive(Debug, Error)] pub enum FormatError { #[error( display = "invalid header (expected: {:?}, got: {:?})", expected, found )] InvalidHeader { expected: String, found: String }, #[error(display = "missing attribute: {:?}", _0)] MissingAttribute(String), } #[derive(Debug, Error)] pub enum LoadingError { #[error(display = "could not decode file")] FormatError(#[error(source)] FormatError), #[error(display = "could not find file: {:?}", path)] NotFound { path: String }, } /// Verify that our error types implement `From` and `Display` pub fn test_impl() { let loading_err: LoadingError = FormatError::MissingAttribute("attr".to_string()).into(); let _ = format!("Error: {}", loading_err); } err-derive-0.3.1/tests/skeptic.rs000064400000000000000000000001250072674642500150710ustar 00000000000000#[cfg(feature = "skeptic")] include!(concat!(env!("OUT_DIR"), "/skeptic-tests.rs")); err-derive-0.3.1/tests/tests.rs000064400000000000000000000103000072674642500145650ustar 00000000000000#![cfg(feature = "std")] use std::error::Error; #[macro_use] extern crate err_derive; #[derive(Debug, Error)] #[error(display = "An error has occurred.")] struct UnitError; #[test] fn unit_struct() { let s = format!("{}", UnitError); assert_eq!(&s[..], "An error has occurred."); } #[derive(Debug, Error)] #[error(display = "Error code: {}", code)] struct RecordError { code: u32, } #[test] fn record_struct() { let s = format!("{}", RecordError { code: 0 }); assert_eq!(&s[..], "Error code: 0"); } #[derive(Debug, Error)] #[error(display = "Error code: {}", _0)] struct TupleError(i32); #[test] fn tuple_struct() { let s = format!("{}", TupleError(2)); assert_eq!(&s[..], "Error code: 2"); } #[derive(Debug, Error)] enum EnumError { #[error(display = "Error code: {}", code)] StructVariant { code: i32 }, #[error(display = "Error: {}", _0)] TupleVariant(&'static str), #[error(display = "An error has occurred.")] UnitVariant, } #[test] fn enum_error() { let s = format!("{}", EnumError::StructVariant { code: 2 }); assert_eq!(&s[..], "Error code: 2"); let s = format!("{}", EnumError::TupleVariant("foobar")); assert_eq!(&s[..], "Error: foobar"); let s = format!("{}", EnumError::UnitVariant); assert_eq!(&s[..], "An error has occurred."); } #[derive(Debug, Error)] enum ErrorWithSource { #[error(display = "tuple error")] A(#[error(source)] TupleError), } #[test] fn error_with_source() { let e = ErrorWithSource::A(TupleError(1)); assert!(e.source().is_some()); } #[derive(Debug, Error)] enum EnumFrom { #[error(display = "Tuple error: {}", _0)] TupleVariant(#[error(source)] UnitError), #[error(display = "Struct error: {}", inner)] StructVariant { #[error(from)] inner: EnumError, }, } #[allow(dead_code)] #[derive(Debug, Error)] enum EnumNoFromVariant { #[error(display = "First error: {}", _0)] First(#[error(source)] UnitError), #[error(display = "Second error: {}", _0)] Second(#[error(source, no_from)] UnitError), } #[allow(dead_code)] #[derive(Debug, Error)] #[error(no_from)] enum EnumNoFromStruct { #[error(display = "First error: {}", _0)] First(#[error(source)] UnitError), #[error(display = "Second error: {}", _0)] Second(#[error(source, from)] UnitError), } #[test] fn from_inner() { let inner = EnumError::StructVariant { code: 12 }; let outer = EnumFrom::from(inner); let s = format!("{}", outer); assert_eq!(&s[..], "Struct error: Error code: 12"); let s = format!("{}", EnumNoFromVariant::from(UnitError)); assert_eq!(&s[..], "First error: An error has occurred."); let s = format!("{}", EnumNoFromStruct::from(UnitError)); assert_eq!(&s[..], "Second error: An error has occurred."); } #[allow(dead_code)] #[derive(Debug, Error)] enum EnumAutoBox { #[error(display = "Boxed error: {}", _0)] First(#[error(source)] Box), } #[test] fn from_enum_autobox() { let s = format!("{}", EnumAutoBox::from(UnitError)); assert_eq!(&s[..], "Boxed error: An error has occurred."); let s = format!("{}", EnumAutoBox::from(Box::new(UnitError))); assert_eq!(&s[..], "Boxed error: An error has occurred."); } #[derive(Debug, Error)] pub enum TestsNonFieldDisplayValues { #[error(display = "{}", STATIC_STR)] A, #[error(display = "{}", get_static_str())] B, #[error(display = "{}", Self::some_method(self))] C, #[error(display = "{}", u8::max_value())] D, #[error(display = "{}", std::u8::MAX)] E, } impl TestsNonFieldDisplayValues { fn some_method(&self) -> &'static str { "some_method" } } static STATIC_STR: &str = "STATIC_STR"; fn get_static_str() -> &'static str { STATIC_STR } #[test] fn non_field_display() { let s = format!("{}", TestsNonFieldDisplayValues::A); assert_eq!(&s, "STATIC_STR"); let s = format!("{}", TestsNonFieldDisplayValues::B); assert_eq!(&s, "STATIC_STR"); let s = format!("{}", TestsNonFieldDisplayValues::C); assert_eq!(&s, "some_method"); let s = format!("{}", TestsNonFieldDisplayValues::D); assert_eq!(&s, "255"); let s = format!("{}", TestsNonFieldDisplayValues::E); assert_eq!(&s, "255"); }