fehler-1.0.0/.cargo_vcs_info.json0000644000000001121364263334200123750ustar00{ "git": { "sha1": "67a237309a9e943c9de506ba2748501811f4117a" } } fehler-1.0.0/.gitignore010064400017500001750000000000361364262550100131710ustar0000000000000000/target **/*.rs.bk Cargo.lock fehler-1.0.0/Cargo.lock0000644000000024531364263334200103620ustar00# This file is automatically @generated by Cargo. # It is not intended for manual editing. [[package]] name = "fehler" version = "1.0.0" dependencies = [ "fehler-macros", ] [[package]] name = "fehler-macros" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ccb5acb1045ebbfa222e2c50679e392a71dd77030b78fb0189f2d9c5974400f9" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "proc-macro2" version = "1.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "df246d292ff63439fea9bc8c0a270bed0e390d5ebd4db4ba15aba81111b5abe3" dependencies = [ "unicode-xid", ] [[package]] name = "quote" version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2bdc6c187c65bca4260c9011c9e3132efe4909da44726bad24cf7572ae338d7f" dependencies = [ "proc-macro2", ] [[package]] name = "syn" version = "1.0.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0df0eb663f387145cab623dea85b09c2c5b4b0aef44e945d928e682fce71bb03" dependencies = [ "proc-macro2", "quote", "unicode-xid", ] [[package]] name = "unicode-xid" version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "826e7639553986605ec5979c7dd957c7895e93eabed50ab2ffa7f6128a75097c" fehler-1.0.0/Cargo.toml0000644000000016161364263334200104050ustar00# 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 believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] edition = "2018" name = "fehler" version = "1.0.0" authors = ["Without Boats "] description = "A library for error-handling syntax in Rust" documentation = "https://docs.rs/fehler" keywords = ["error-handling", "exceptions"] license = "MIT OR Apache-2.0" repository = "https://github.com/withoutboats/fehler" [dependencies.fehler-macros] version = "1.0.0" fehler-1.0.0/Cargo.toml.orig010064400017500001750000000006511364263261000140720ustar0000000000000000[package] name = "fehler" version = "1.0.0" edition = "2018" authors = ["Without Boats "] license = "MIT OR Apache-2.0" description = "A library for error-handling syntax in Rust" repository = "https://github.com/withoutboats/fehler" documentation = "https://docs.rs/fehler" keywords = ["error-handling", "exceptions"] [dependencies.fehler-macros] path = "./fehler-macros" version = "1.0.0" [workspace] fehler-1.0.0/LICENSE-APACHE010064400017500001750000000250061364262550100131310ustar0000000000000000 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 Copyright 2019 Without Boats 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. fehler-1.0.0/LICENSE-MIT010064400017500001750000000020701364262550100126350ustar0000000000000000The MIT License (MIT) Copyright (c) 2019 Without Boats 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. fehler-1.0.0/README.md010064400017500001750000000047211364263261000124640ustar0000000000000000# Der Fehler [![Documentation](https://docs.rs/fehler/badge.svg)](https://docs.rs/fehler/*/fehler/) Der Fehler is a library to add support for "throwing functions" to Rust through procedural macros. Functions marked with the `throws` attribute return `Result`, but the "Ok" path is used by default and you don't need to wrap ok return values in `Ok`. To throw errors, use `?` or the `throws` macro. Der Fehler provides these items: ### The `#[throws]` attribute The throws attribute modifies a function or method to make it return a `Result`. It takes an optional typename as an argument to the attribute which will be the error type of this function; if no typename is supplied, it uses the default error type for this crate. Within the function body, `return`s (including the implicit final return) are automatically "Ok-wrapped." To raise errors, use `?` or the `throws!` macro. For example, these two functions are equivalent: ```rust #[throws(i32)] fn foo(x: bool) -> i32 { if x { 0 } else { throw!(1); } } fn bar(x: bool) -> Result { if x { Ok(0) } else { Err(1) } } ``` ## In functions that return `Option` The attribute can be used to make a function that returns an Option using the `as Option` syntax, demonstrated below: ```rust // This function returns `Option` #[throws(as Option)] fn foo(x: bool) -> i32 { if x { return 0; } else { throw!(); } } ``` ### The `throw!` macro `throw!` is a macro which is equivalent to the `Err($e)?` pattern. It takes an error type and "throws" it. One important aspect of the `throw!` macro is that it allows you to return errors inside of functions marked with `throws`. You cannot just `return` errors from these functions, you need to use this macro. # TODO * Make throws work on closures and async blocks (attributes are not allowed on expressions on stable) * Make throws work on Try types other than Result and Option (TRy is not on stable). ## License Licensed under either of * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) at your option. #### Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. fehler-1.0.0/examples/throwing-main.rs010064400017500001750000000002571364262550100161550ustar0000000000000000use fehler::*; #[derive(Debug)] struct Error; #[throws(_)] fn do_it() -> i32 { if true { throw!(Error); } 0 } #[throws(_)] fn main() { do_it()?; } fehler-1.0.0/src/lib.rs010064400017500001750000000125231364263224300131110ustar0000000000000000#![no_std] #[doc(inline)] /// Annotations a function that "throws" a Result. /// /// Inside functions tagged with `throws`, you can use `?` and the `throw!` macro to return errors, /// but you don't need to wrap the successful return values in `Ok`. /// /// Using this syntax, you can write fallible functions almost as if they were nonfallible. Every /// time a function call would return a `Result`, you "re-raise" the error using `?`, and if you /// wish to raise your own error, you can return it with the `throw!` macro. /// /// ## Example /// ```should_panic /// use std::io::{self, Read}; /// /// use fehler::{throw, throws}; /// /// #[throws(io::Error)] /// fn main() { /// let mut file = std::fs::File::open("The_House_of_the_Spirits.txt")?; /// let mut text = String::new(); /// file.read_to_string(&mut text)?; /// /// if !text.starts_with("Barrabas came to us by sea, the child Clara wrote") { /// throw!(io::Error::from_raw_os_error(22)); /// } /// /// println!("Okay!"); /// } /// ``` /// /// # Default Error Type /// /// This macro supports a "default error type" - if you do not pass a type to the macro, it will /// use the type named `Error` in this scope. So if you have defined an error type in this /// module, that will be the error thrown by this function. /// /// You can access this feature by omitting the arguments entirely or by passing `_` as the type. /// /// ## Example /// /// ```should_panic /// use fehler::throws; /// /// // Set the default error type for this module: /// type Error = std::io::Error; /// /// #[throws] /// fn main() { /// let file = std::fs::read_to_string("my_file.txt")?; /// println!("{}", file); /// } /// ``` /// /// # Throwing as an Option /// /// This syntax can also support functions which return an `Option` instead of a `Result`. The /// way to access this is to pass `as Option` as the argument to `throw`. /// /// In functions that return `Option`, you can use the `throw!()` macro without any argument to /// return `None`. /// /// ## Example /// /// ``` /// use fehler::{throw, throws}; /// /// #[throws(as Option)] /// fn example(slice: &[T], needle: &T) -> usize { /// if !slice.contains(needle) { /// throw!(); /// } /// slice.binary_search(needle).ok()? /// } /// ``` /// /// # Other `Try` types /// /// The `?` syntax in Rust is controlled by a trait called `Try`, which is currently unstable. /// Because this feature is unstable and I don't want to maintain compatibility if its interface /// changes, this crate currently only works with two stable `Try` types: Result and Option. /// However, its designed so that it will hopefully support other `Try` types as well in the /// future. /// /// It's worth noting that `Try` also has some other stable implementations: specifically `Poll`. /// Because of the somewhat unusual implementation of `Try` for those types, this crate does not /// support `throws` syntax on functions that return `Poll` (so you can't use this syntax when /// implementing a Future by hand, for example). I hope to come up with a way to support Poll in /// the future. pub use fehler_macros::throws; /// Throw an error. /// /// This macro is equivalent to `Err($err)?`. #[macro_export] macro_rules! throw { ($err:expr) => (return <_ as $crate::__internal::_Throw>::from_error((::core::convert::From::from($err)))); () => (return <_ as ::core::default::Default>::default()); } #[doc(hidden)] pub mod __internal { pub trait _Succeed { type Ok; fn from_ok(ok: Self::Ok) -> Self; } pub trait _Throw { type Error; fn from_error(error: Self::Error) -> Self; } mod stable { use core::task::Poll; impl super::_Succeed for Result { type Ok = T; fn from_ok(ok: T) -> Self { Ok(ok) } } impl super::_Throw for Result { type Error = E; fn from_error(error: Self::Error) -> Self { Err(error) } } impl super::_Succeed for Poll> { type Ok = Poll; fn from_ok(ok: Self::Ok) -> Self { match ok { Poll::Ready(ok) => Poll::Ready(Ok(ok)), Poll::Pending => Poll::Pending, } } } impl super::_Throw for Poll> { type Error = E; fn from_error(error: Self::Error) -> Self { Poll::Ready(Err(error)) } } impl super::_Succeed for Poll>> { type Ok = Poll>; fn from_ok(ok: Self::Ok) -> Self { match ok { Poll::Ready(Some(ok)) => Poll::Ready(Some(Ok(ok))), Poll::Ready(None) => Poll::Ready(None), Poll::Pending => Poll::Pending, } } } impl super::_Throw for Poll>> { type Error = E; fn from_error(error: Self::Error) -> Self { Poll::Ready(Some(Err(error))) } } impl super::_Succeed for Option { type Ok = T; fn from_ok(ok: Self::Ok) -> Self { Some(ok) } } } } fehler-1.0.0/tests/no_std.rs010064400017500001750000000002411364262632000141750ustar0000000000000000#![no_std] use fehler::{throw, throws}; #[throws(i32)] fn no_std_fn() { throw!(0); } #[test] fn test_expansion() { assert_eq!(Err(0), no_std_fn()); } fehler-1.0.0/tests/option.rs010064400017500001750000000003531364263224300142240ustar0000000000000000use fehler::*; #[throws(as Option)] fn foo(x: bool) -> i32 { if x { throw!(); } 0 } #[test] fn test_outcome_true() { assert!(foo(true).is_none()) } #[test] fn test_outcome_false() { assert_eq!(Some(0), foo(false)) } fehler-1.0.0/tests/throw.rs010064400017500001750000000006031364262550100140540ustar0000000000000000use fehler::throw; #[test] fn throw_works() { fn foo() -> Result<(), i32> { throw!(0) } assert_eq!(foo(), Err(0)); } #[test] fn throw_infers_ok_type() { fn foo(b: bool) -> Result { let x = if b { 0 } else { throw!(()); }; Ok(x) } assert_eq!(foo(true), Ok(0)); assert_eq!(foo(false), Err(())); } fehler-1.0.0/tests/throws.rs010064400017500001750000000026441364263224300142470ustar0000000000000000use fehler::*; type Error = (); #[throws(_)] pub fn unit_fn() { } #[throws(_)] pub fn returns_fn() -> i32 { return 0; } #[throws(_)] pub fn returns_unit_fn() { if true { return; } } #[throws(_)] pub fn explicit_unit() -> () { } #[throws(_)] pub fn tail_returns_value() -> i32 { 0 } #[throws(_)] pub async fn async_fn() { } #[throws(_)] pub async fn async_fn_with_ret() -> i32 { 0 } #[throws(i32)] pub fn throws_error() { if true { throw!(0); } } #[throws(i32)] pub fn throws_and_has_return_type() -> &'static str { if true { return "success"; } else if false { throw!(0); } "okay" } #[throws(E)] pub fn throws_generics() { } pub struct Foo; impl Foo { #[throws(_)] pub fn static_method() { } #[throws(_)] pub fn bar(&self) -> i32 { if true { return 1; } 0 } } #[throws(_)] pub fn has_inner_fn() { fn inner_fn() -> i32 { 0 } let _: i32 = inner_fn(); } #[throws(_)] pub fn has_inner_closure() { let f = || 0; let _: i32 = f(); } #[throws(_)] pub async fn has_inner_async_block() { let f = async { 0 }; let _: i32 = f.await; } #[throws(_ as Result)] pub fn throws_as_result() -> i32 { 0 } #[throws(as std::io::Result)] pub fn throws_as_result_alias() -> i32 { 0 } #[throws] pub fn ommitted_error() { } mod foo { use fehler::*; type Error = i32; #[throws] fn throws_integer() { throw!(0); } }