culpa-1.0.2/.cargo_vcs_info.json0000644000000001360000000000100121400ustar { "git": { "sha1": "033a8706be7a9c1ea09cc1ed6c6d4c0b8b4136b9" }, "path_in_vcs": "" }culpa-1.0.2/.git-blame-ignore-revs000064400000000000000000000000511046102023000150240ustar 00000000000000c2384d659b4c3e221e683e088f44e1d8ffb957f0 culpa-1.0.2/.github/workflows/nightly.yml000064400000000000000000000002241046102023000165240ustar 00000000000000jobs: nightly: uses: Nullus157/.github/.github/workflows/nightly.yml@main on: schedule: - cron: '0 2 * * *' push: branches: [main] culpa-1.0.2/.github/workflows/pull_request.yml000064400000000000000000000007011046102023000175720ustar 00000000000000jobs: pull_request: uses: Nullus157/.github/.github/workflows/pull_request.yml@main success: runs-on: ubuntu-latest needs: [pull_request] if: ${{ always() }} steps: - if: ${{ contains(needs.*.result, 'failure') }} run: exit 1 - if: ${{ contains(needs.*.result, 'cancelled') }} run: exit 1 - if: ${{ contains(needs.*.result, 'skipped') }} run: exit 1 on: pull_request: branches: [main] culpa-1.0.2/.github/workflows/staging.yml000064400000000000000000000010331046102023000165010ustar 00000000000000jobs: pull_request: uses: Nullus157/.github/.github/workflows/pull_request.yml@main staging: uses: Nullus157/.github/.github/workflows/staging.yml@main success: runs-on: ubuntu-latest needs: [pull_request, staging] if: ${{ always() }} steps: - if: ${{ contains(needs.*.result, 'failure') }} run: exit 1 - if: ${{ contains(needs.*.result, 'cancelled') }} run: exit 1 - if: ${{ contains(needs.*.result, 'skipped') }} run: exit 1 on: merge_group: type: [checks_requested] culpa-1.0.2/.gitignore000064400000000000000000000000231046102023000127130ustar 00000000000000/target **/*.rs.bk culpa-1.0.2/Cargo.lock0000644000000024740000000000100101220ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[package]] name = "culpa" version = "1.0.2" dependencies = [ "culpa-macros", ] [[package]] name = "culpa-macros" version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1234e1717066d3c71dcf89b75e7b586299e41204d361db56ec51e6ded5014279" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "proc-macro2" version = "1.0.63" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7b368fba921b0dce7e60f5e04ec15e565b3303972b42bcfde1d0713b881959eb" dependencies = [ "unicode-ident", ] [[package]] name = "quote" version = "1.0.29" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "573015e8ab27661678357f27dc26460738fd2b6c86e46f386fde94cb5d913105" dependencies = [ "proc-macro2", ] [[package]] name = "syn" version = "2.0.22" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2efbeae7acf4eabd6bcdcbd11c92f45231ddda7539edc7806bd1a04a03b24616" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] [[package]] name = "unicode-ident" version = "1.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b15811caf2415fb889178633e7724bad2509101cde276048e013b9def5e51fa0" culpa-1.0.2/Cargo.toml0000644000000014270000000000100101420ustar # 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 = "culpa" version = "1.0.2" description = "A library for error-handling syntax in Rust" readme = "README.md" keywords = [ "error-handling", "exceptions", ] license = "MIT OR Apache-2.0" repository = "https://github.com/Nullus157/culpa" [dependencies.culpa-macros] version = "=1.0.2" culpa-1.0.2/Cargo.toml.orig000064400000000000000000000005021046102023000136140ustar 00000000000000[package] name = "culpa" version = "1.0.2" edition = "2018" license = "MIT OR Apache-2.0" description = "A library for error-handling syntax in Rust" repository = "https://github.com/Nullus157/culpa" keywords = ["error-handling", "exceptions"] [dependencies.culpa-macros] path = "macros" version = "=1.0.2" [workspace] culpa-1.0.2/LICENSE-APACHE000064400000000000000000000250061046102023000126570ustar 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 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. culpa-1.0.2/LICENSE-MIT000064400000000000000000000020701046102023000123630ustar 00000000000000The 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. culpa-1.0.2/README.md000064400000000000000000000055411046102023000122140ustar 00000000000000[![version-badge][]][version] [![license-badge][]][license] [![rust-version-badge][]][rust-version] Adding 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. > A fork of [Der Fehler](https://github.com/withoutboats/fehler) updating dependencies and fixing issues while (by my understanding) boats is unable to contribute to open source. # 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 { 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. # Rust Version Policy This crate only supports the current stable version of Rust, patch releases may use new features at any time. # 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. [version-badge]: https://img.shields.io/crates/v/culpa.svg?style=flat-square [version]: https://crates.io/crates/culpa [license-badge]: https://img.shields.io/crates/l/culpa.svg?style=flat-square [license]: #license [rust-version-badge]: https://img.shields.io/badge/rust-latest%20stable-blueviolet.svg?style=flat-square [rust-version]: #rust-version-policy culpa-1.0.2/deny.toml000064400000000000000000000001061046102023000125610ustar 00000000000000[licenses] allow = [ "MIT", "Apache-2.0", "Unicode-DFS-2016", ] culpa-1.0.2/examples/throwing-main.rs000064400000000000000000000002741046102023000157020ustar 00000000000000use culpa::{throw, throws}; #[derive(Debug)] struct Error; #[throws(_)] fn do_it() -> i32 { if true { throw!(Error); } 0 } #[throws(_)] fn main() { do_it()?; } culpa-1.0.2/src/lib.rs000064400000000000000000000165051046102023000126420ustar 00000000000000#![no_std] //! Annotates a function that "throws" a Result. //! //! Inside functions tagged with either `throws` or `try_fn`, 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 infallible. 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. //! //! The difference between `throws` and `try_fn` is in the function signature, with `throws` you //! write the signature as if it were infallible too, it will be transformed into a `Result` for //! you. With `try_fn` you write the signature as normal and only the body of the function will be //! transformed. //! //! ## Example //! //! ``` //! use std::io::{self, Read}; //! //! use culpa::{throw, throws, try_fn}; //! //! #[throws(io::Error)] //! fn check() { //! 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!"); //! } //! //! #[try_fn] //! fn check_as_try_fn() -> std::io::Result<()> { //! 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!"); //! } //! ``` //! //! # `throws` Default Error Type //! //! The `throws` macro supports a "default error type" - if you do not pass a type to the macro, it //! will use the type named `Error` in the current scope. So if you have defined an error type in //! the 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 //! //! ``` //! use culpa::throws; //! //! // Set the default error type for this module: //! use std::io::Error; //! //! #[throws] //! fn print() { //! 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`. To use //! this with `throws` pass `as Option` as the argument in place of the error type, to use it with //! `try_fn` just put it as the return type like normal //! //! In functions that return `Option`, you can use the `throw!()` macro without any argument to //! return `None`. //! //! ## Example //! //! ``` //! #[culpa::throws(as Option)] //! fn example(slice: &[T], needle: &T) -> usize { //! if !slice.contains(needle) { //! culpa::throw!(); //! } //! slice.binary_search(needle).ok()? //! } //! //! #[culpa::try_fn] //! fn example_as_try_fn(slice: &[T], needle: &T) -> Option { //! if !slice.contains(needle) { //! culpa::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. #[doc(inline)] /// Annotates a function that "throws" a Result. /// /// See the main crate docs for more details. pub use culpa_macros::throws; #[doc(inline)] /// Annotates a function that implicitly wraps a try block. /// /// See the main crate docs for more details. pub use culpa_macros::try_fn; /// 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) } } } } /// Test that function is marked as dead code, because compile_fail is such a blunt instrument /// these tests should be kept in sync in pairs other than the deny, to ensure there's not another /// reason to fail compilation /// /// ``` /// #[culpa::throws(())] /// fn f() {} /// ``` /// ```compile_fail /// #[deny(dead_code)] /// #[culpa::throws(())] /// fn f() {} /// ``` /// /// ``` /// pub struct Foo; /// impl Foo { /// #[culpa::throws(())] /// fn f() {} /// } /// ``` /// ```compile_fail /// pub struct Foo; /// impl Foo { /// #[deny(dead_code)] /// #[culpa::throws(())] /// fn f() {} /// } /// ``` const _DEAD_CODE: () = (); /// ```compile_fail /// #[culpa::try_(())] /// fn f() {} /// ``` const _NO_TRY_ARGS: () = (); culpa-1.0.2/tests/inner-functions.rs000064400000000000000000000006351046102023000155650ustar 00000000000000use culpa::throws; pub type Error = isize; #[throws] pub fn inner_function() { fn foo() {} foo(); } #[throws] pub fn fn_parameters(_: fn()) {} #[throws] pub fn fn_type_alias() { #[allow(dead_code)] type X = fn(); } #[throws] pub fn type_ascription() { let _: fn() = panic!(); } #[throws(std::io::Error)] pub fn dyn_fn_once() { let mut _unused: Box = Box::new(|| ()); } culpa-1.0.2/tests/no_std.rs000064400000000000000000000002401046102023000137220ustar 00000000000000#![no_std] use culpa::{throw, throws}; #[throws(i32)] fn no_std_fn() { throw!(0); } #[test] fn test_expansion() { assert_eq!(Err(0), no_std_fn()); } culpa-1.0.2/tests/option.rs000064400000000000000000000004041046102023000137460ustar 00000000000000use culpa::{throw, throws}; #[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)) } culpa-1.0.2/tests/throw.rs000064400000000000000000000006161046102023000136060ustar 00000000000000use culpa::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(())); } culpa-1.0.2/tests/throws.rs000064400000000000000000000041021046102023000137630ustar 00000000000000use culpa::{throw, throws}; type Error = isize; #[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() {} pub mod foo { use culpa::{throw, throws}; pub type Error = i32; #[throws] pub fn throws_integer() { throw!(0); } } pub mod foo_trait_obj { use culpa::throws; pub trait FooTrait {} struct FooStruct; pub struct FooError; impl FooTrait for FooStruct {} #[throws(FooError)] pub fn foo() -> Box { Box::new(FooStruct) } } #[throws] pub fn let_else(a: Option) -> u8 { let Some(a) = a else { return 0; }; a } #[throws] pub fn impl_trait() -> impl std::fmt::Debug {} #[throws(i32)] #[deny(unreachable_code)] pub fn unreachable() { todo!() } trait Example { #[throws] fn foo() -> i32; } culpa-1.0.2/tests/try.rs000064400000000000000000000051131046102023000132560ustar 00000000000000use culpa::{throw, try_fn}; type Error = isize; #[try_fn] pub fn unit_fn() -> Result<(), Error> {} #[try_fn] pub fn returns_fn() -> Result { return 0; } #[try_fn] pub fn returns_unit_fn() -> Result<(), Error> { if true { return; } } #[try_fn] pub fn tail_returns_value() -> Result { 0 } #[try_fn] pub async fn async_fn() -> Result<(), Error> {} #[try_fn] pub async fn async_fn_with_ret() -> Result { 0 } #[try_fn] pub fn throws_error() -> Result<(), i32> { if true { throw!(0); } } #[try_fn] pub fn throws_and_has_return_type() -> Result<&'static str, i32> { if true { return "success"; } else if false { throw!(0); } "okay" } #[try_fn] pub fn throws_generics() -> Result<(), E> {} pub struct Foo; impl Foo { #[try_fn] pub fn static_method() -> Result<(), Error> {} #[try_fn] pub fn bar(&self) -> Result { if true { return 1; } 0 } } #[try_fn] pub fn has_inner_fn() -> Result<(), Error> { fn inner_fn() -> i32 { 0 } let _: i32 = inner_fn(); } #[try_fn] pub fn has_inner_closure() -> Result<(), Error> { let f = || 0; let _: i32 = f(); } #[try_fn] pub async fn has_inner_async_block() -> Result<(), Error> { let f = async { 0 }; let _: i32 = f.await; } #[try_fn] pub fn throws_as_result() -> Result { 0 } #[try_fn] pub fn throws_as_result_alias() -> std::io::Result { 0 } #[try_fn] pub fn ommitted_error() -> Result<(), Error> {} pub mod foo { use culpa::{throw, try_fn}; pub type Error = i32; #[try_fn] pub fn throws_integer() -> Result<(), i32> { throw!(0); } } pub mod foo_trait_obj { use culpa::try_fn; pub trait FooTrait {} struct FooStruct; pub struct FooError; impl FooTrait for FooStruct {} #[try_fn] pub fn foo() -> Result, FooError> { Box::new(FooStruct) } } #[try_fn] pub fn let_else(a: Option) -> Result { let Some(a) = a else { return 0; }; a } #[try_fn] pub fn impl_trait() -> Result {} #[try_fn] #[deny(unreachable_code)] pub fn unreachable() -> Result<(), i32> { todo!() } trait Example { #[try_fn] fn foo() -> Result; } #[try_fn] fn as_option(x: bool) -> Option { if x { throw!(); } 0 } #[test] fn test_as_option_true() { assert_eq!(None, as_option(true)); } #[test] fn test_as_option_false() { assert_eq!(Some(0), as_option(false)) }