snafu-derive-0.6.10/.cargo_vcs_info.json0000644000000001121376223232200135420ustar { "git": { "sha1": "69b701656fc1b10f78271f077efcc2584d992cce" } } snafu-derive-0.6.10/.gitignore010064400007660000024000000000361342335237500143440ustar 00000000000000/target **/*.rs.bk Cargo.lock snafu-derive-0.6.10/Cargo.toml0000644000000020041376223232200115420ustar # 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 = "snafu-derive" version = "0.6.10" authors = ["Jake Goulding "] description = "An ergonomic error handling library" documentation = "https://docs.rs/snafu" license = "MIT OR Apache-2.0" repository = "https://github.com/shepmaster/snafu" [lib] proc-macro = true [dependencies.proc-macro2] version = "1.0" [dependencies.quote] version = "1.0" [dependencies.syn] version = "1.0" features = ["full"] [features] unstable-backtraces-impl-std = [] snafu-derive-0.6.10/Cargo.toml.orig010064400007660000024000000007211376223211200152340ustar 00000000000000[package] name = "snafu-derive" version = "0.6.10" authors = ["Jake Goulding "] edition = "2018" description = "An ergonomic error handling library" documentation = "https://docs.rs/snafu" repository = "https://github.com/shepmaster/snafu" license = "MIT OR Apache-2.0" [features] unstable-backtraces-impl-std = [] [lib] proc-macro = true [dependencies] syn = { version = "1.0", features = ["full"] } quote = "1.0" proc-macro2 = "1.0" snafu-derive-0.6.10/LICENSE-APACHE010064400007660000024000000251221346466457000143130ustar 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 2019- Jake Goulding 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. snafu-derive-0.6.10/LICENSE-MIT010064400007660000024000000020421346466457000140170ustar 00000000000000Copyright (c) 2019- Jake Goulding 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. snafu-derive-0.6.10/src/lib.rs010064400007660000024000001674261376205172600143020ustar 00000000000000#![recursion_limit = "128"] // https://github.com/rust-lang/rust/issues/62059 extern crate proc_macro; use proc_macro::TokenStream; use quote::{format_ident, quote}; use std::collections::VecDeque; use std::fmt; use syn::parenthesized; use syn::parse::Result as SynResult; mod shared; /// See the crate-level documentation for SNAFU which contains tested /// examples of this macro. #[proc_macro_derive(Snafu, attributes(snafu))] pub fn snafu_derive(input: TokenStream) -> TokenStream { let ast = syn::parse(input).expect("Could not parse type to derive Error for"); impl_snafu_macro(ast) } type MultiSynResult = std::result::Result>; /// Some arbitrary tokens we treat as a black box type UserInput = Box; enum SnafuInfo { Enum(EnumInfo), NamedStruct(NamedStructInfo), TupleStruct(TupleStructInfo), } struct EnumInfo { crate_root: UserInput, name: syn::Ident, generics: syn::Generics, variants: Vec, default_visibility: UserInput, } struct FieldContainer { name: syn::Ident, backtrace_field: Option, selector_kind: ContextSelectorKind, display_format: Option, doc_comment: String, visibility: Option, } enum ContextSelectorKind { Context { source_field: Option, user_fields: Vec, }, NoContext { source_field: SourceField, }, } impl ContextSelectorKind { fn user_fields(&self) -> &[Field] { match self { ContextSelectorKind::Context { user_fields, .. } => user_fields, ContextSelectorKind::NoContext { .. } => &[], } } fn source_field(&self) -> Option<&SourceField> { match self { ContextSelectorKind::Context { source_field, .. } => source_field.as_ref(), ContextSelectorKind::NoContext { source_field } => Some(source_field), } } } struct NamedStructInfo { crate_root: UserInput, field_container: FieldContainer, generics: syn::Generics, } struct TupleStructInfo { crate_root: UserInput, name: syn::Ident, generics: syn::Generics, transformation: Transformation, } #[derive(Clone)] pub(crate) struct Field { name: syn::Ident, ty: syn::Type, original: syn::Field, } impl Field { fn name(&self) -> &syn::Ident { &self.name } } struct SourceField { name: syn::Ident, transformation: Transformation, backtrace_delegate: bool, } impl SourceField { fn name(&self) -> &syn::Ident { &self.name } } enum Transformation { None { ty: syn::Type }, Transform { ty: syn::Type, expr: syn::Expr }, } impl Transformation { fn ty(&self) -> &syn::Type { match self { Transformation::None { ty } => ty, Transformation::Transform { ty, .. } => ty, } } fn transformation(&self) -> proc_macro2::TokenStream { match self { Transformation::None { .. } => quote! { |v| v }, Transformation::Transform { expr, .. } => quote! { #expr }, } } } /// SyntaxErrors is a convenience wrapper for a list of syntax errors discovered while parsing /// something that derives Snafu. It makes it easier for developers to add and return syntax /// errors while walking through the parse tree. #[derive(Debug, Default)] struct SyntaxErrors { inner: Vec, } impl SyntaxErrors { /// Start a set of errors that all share the same location fn scoped(&mut self, scope: ErrorLocation) -> SyntaxErrorsScoped<'_> { SyntaxErrorsScoped { errors: self, scope, } } /// Adds a new syntax error. The description will be used in the /// compile error pointing to the tokens. fn add(&mut self, tokens: impl quote::ToTokens, description: impl fmt::Display) { self.inner .push(syn::Error::new_spanned(tokens, description)); } /// Adds the given list of errors. fn extend(&mut self, errors: impl IntoIterator) { self.inner.extend(errors); } #[allow(dead_code)] /// Returns the number of errors that have been added. fn len(&self) -> usize { self.inner.len() } /// Consume the SyntaxErrors, returning Ok if there were no syntax errors added, or Err(list) /// if there were syntax errors. fn finish(self) -> MultiSynResult<()> { if self.inner.is_empty() { Ok(()) } else { Err(self.inner) } } /// Consume the SyntaxErrors and a Result, returning the success /// value if neither have errors, otherwise combining the errors. fn absorb(mut self, res: MultiSynResult) -> MultiSynResult { match res { Ok(v) => self.finish().map(|()| v), Err(e) => { self.inner.extend(e); Err(self.inner) } } } } #[derive(Debug, Copy, Clone)] enum ErrorLocation { OnEnum, OnVariant, InVariant, OnField, OnNamedStruct, InNamedStruct, OnTupleStruct, } impl fmt::Display for ErrorLocation { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use crate::ErrorLocation::*; match self { OnEnum => "on an enum".fmt(f), OnVariant => "on an enum variant".fmt(f), InVariant => "within an enum variant".fmt(f), OnField => "on a field".fmt(f), OnNamedStruct => "on a named struct".fmt(f), InNamedStruct => "within a named struct".fmt(f), OnTupleStruct => "on a tuple struct".fmt(f), } } } trait ErrorForLocation { fn for_location(&self, location: ErrorLocation) -> String; } struct SyntaxErrorsScoped<'a> { errors: &'a mut SyntaxErrors, scope: ErrorLocation, } impl SyntaxErrorsScoped<'_> { /// Adds a new syntax error. The description will be used in the /// compile error pointing to the tokens. fn add(&mut self, tokens: impl quote::ToTokens, description: impl ErrorForLocation) { let description = description.for_location(self.scope); self.errors.add(tokens, description) } } /// Helper structure to handle cases where an attribute was used on an /// element where it's not valid. #[derive(Debug)] struct OnlyValidOn { /// The name of the attribute that was misused. attribute: &'static str, /// A description of where that attribute is valid. valid_on: &'static str, } impl ErrorForLocation for OnlyValidOn { fn for_location(&self, location: ErrorLocation) -> String { format!( "`{}` attribute is only valid on {}, not {}", self.attribute, self.valid_on, location, ) } } /// Helper structure to handle cases where a specific attribute value /// was used on an field where it's not valid. #[derive(Debug)] struct WrongField { /// The name of the attribute that was misused. attribute: &'static str, /// The name of the field where that attribute is valid. valid_field: &'static str, } impl ErrorForLocation for WrongField { fn for_location(&self, _location: ErrorLocation) -> String { format!( r#"`{}` attribute is only valid on a field named "{}", not on other fields"#, self.attribute, self.valid_field, ) } } /// Helper structure to handle cases where two incompatible attributes /// were specified on the same element. #[derive(Debug)] struct IncompatibleAttributes(&'static [&'static str]); impl ErrorForLocation for IncompatibleAttributes { fn for_location(&self, location: ErrorLocation) -> String { let attrs_string = self .0 .iter() .map(|attr| format!("`{}`", attr)) .collect::>() .join(", "); format!( "Incompatible attributes [{}] specified {}", attrs_string, location, ) } } /// Helper structure to handle cases where an attribute was /// incorrectly used multiple times on the same element. #[derive(Debug)] struct DuplicateAttribute { attribute: &'static str, location: ErrorLocation, } impl fmt::Display for DuplicateAttribute { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "Multiple `{}` attributes are not supported {}", self.attribute, self.location, ) } } /// AtMostOne is a helper to track attributes seen during parsing. If more than one item is added, /// it's added to a list of DuplicateAttribute errors, using the given `name` and `location` as /// descriptors. /// /// When done parsing a structure, call `finish` to get first attribute found, if any, and the list /// of errors, or call `finish_with_location` to get the attribute and the token tree where it was /// found, which can be useful for error reporting. #[derive(Debug)] struct AtMostOne where U: quote::ToTokens, { name: &'static str, location: ErrorLocation, // We store all the values we've seen to allow for `iter`, which helps the `AtMostOne` be // useful for additional manual error checking. values: VecDeque<(T, U)>, errors: SyntaxErrors, } impl AtMostOne where U: quote::ToTokens + Clone, { /// Creates an AtMostOne to track an attribute with the given /// `name` on the given `location` (often referencing a parent /// element). fn new(name: &'static str, location: ErrorLocation) -> Self { Self { name, location, values: VecDeque::new(), errors: SyntaxErrors::default(), } } /// Add an occurence of the attribute found at the given token tree `tokens`. fn add(&mut self, item: T, tokens: U) { if !self.values.is_empty() { self.errors.add( tokens.clone(), DuplicateAttribute { attribute: self.name, location: self.location, }, ); } self.values.push_back((item, tokens)); } #[allow(dead_code)] /// Returns the number of elements that have been added. fn len(&self) -> usize { self.values.len() } /// Returns true if no elements have been added, otherwise false. #[allow(dead_code)] fn is_empty(&self) -> bool { self.values.is_empty() } /// Returns an iterator over all values that have been added. /// /// This can help with additional manual error checks beyond the duplication checks that /// `AtMostOne` handles for you. fn iter(&self) -> std::collections::vec_deque::Iter<(T, U)> { self.values.iter() } /// Consumes the AtMostOne, returning the first item added, if any, and the list of errors /// representing any items added beyond the first. fn finish(self) -> (Option, Vec) { let (value, errors) = self.finish_with_location(); (value.map(|(val, _location)| val), errors) } /// Like `finish` but also returns the location of the first item added. Useful when you have /// to do additional, manual error checking on the first item added, and you'd like to report /// an accurate location for it in case of errors. fn finish_with_location(mut self) -> (Option<(T, U)>, Vec) { let errors = match self.errors.finish() { Ok(()) => Vec::new(), Err(vec) => vec, }; (self.values.pop_front(), errors) } } fn impl_snafu_macro(ty: syn::DeriveInput) -> TokenStream { match parse_snafu_information(ty) { Ok(info) => info.into(), Err(e) => to_compile_errors(e).into(), } } fn to_compile_errors(errors: Vec) -> proc_macro2::TokenStream { let compile_errors = errors.iter().map(syn::Error::to_compile_error); quote! { #(#compile_errors)* } } fn parse_snafu_information(ty: syn::DeriveInput) -> MultiSynResult { use syn::spanned::Spanned; use syn::Data; let span = ty.span(); let syn::DeriveInput { ident, generics, data, attrs, .. } = ty; match data { Data::Enum(enum_) => parse_snafu_enum(enum_, ident, generics, attrs).map(SnafuInfo::Enum), Data::Struct(struct_) => parse_snafu_struct(struct_, ident, generics, attrs, span), _ => Err(vec![syn::Error::new( span, "Can only derive `Snafu` for an enum or a newtype", )]), } } const ATTR_DISPLAY: OnlyValidOn = OnlyValidOn { attribute: "display", valid_on: "enum variants or structs with named fields", }; const ATTR_SOURCE: OnlyValidOn = OnlyValidOn { attribute: "source", valid_on: "enum variant or struct fields with a name", }; const ATTR_SOURCE_BOOL: OnlyValidOn = OnlyValidOn { attribute: "source(bool)", valid_on: "enum variant or struct fields with a name", }; const ATTR_SOURCE_FALSE: WrongField = WrongField { attribute: "source(false)", valid_field: "source", }; const ATTR_SOURCE_FROM: OnlyValidOn = OnlyValidOn { attribute: "source(from)", valid_on: "enum variant or struct fields with a name", }; const ATTR_BACKTRACE: OnlyValidOn = OnlyValidOn { attribute: "backtrace", valid_on: "enum variant or struct fields with a name", }; const ATTR_BACKTRACE_FALSE: WrongField = WrongField { attribute: "backtrace(false)", valid_field: "backtrace", }; const ATTR_VISIBILITY: OnlyValidOn = OnlyValidOn { attribute: "visibility", valid_on: "an enum, enum variants, or a struct with named fields", }; const ATTR_CONTEXT: OnlyValidOn = OnlyValidOn { attribute: "context", valid_on: "enum variants or structs with named fields", }; const ATTR_CRATE_ROOT: OnlyValidOn = OnlyValidOn { attribute: "crate_root", valid_on: "an enum or a struct", }; const SOURCE_BOOL_FROM_INCOMPATIBLE: IncompatibleAttributes = IncompatibleAttributes(&["source(false)", "source(from)"]); fn parse_snafu_enum( enum_: syn::DataEnum, name: syn::Ident, generics: syn::Generics, attrs: Vec, ) -> MultiSynResult { use syn::spanned::Spanned; use syn::Fields; let mut errors = SyntaxErrors::default(); let mut default_visibilities = AtMostOne::new("visibility", ErrorLocation::OnEnum); let mut crate_roots = AtMostOne::new("crate_root", ErrorLocation::OnEnum); let mut enum_errors = errors.scoped(ErrorLocation::OnEnum); for attr in attributes_from_syn(attrs)? { match attr { SnafuAttribute::Visibility(tokens, v) => { default_visibilities.add(v, tokens); } SnafuAttribute::Display(tokens, ..) => enum_errors.add(tokens, ATTR_DISPLAY), SnafuAttribute::Source(tokens, ss) => { for s in ss { match s { Source::Flag(..) => enum_errors.add(tokens.clone(), ATTR_SOURCE_BOOL), Source::From(..) => enum_errors.add(tokens.clone(), ATTR_SOURCE_FROM), } } } SnafuAttribute::CrateRoot(tokens, root) => { crate_roots.add(root, tokens); } SnafuAttribute::Backtrace(tokens, ..) => enum_errors.add(tokens, ATTR_BACKTRACE), SnafuAttribute::Context(tokens, ..) => enum_errors.add(tokens, ATTR_CONTEXT), SnafuAttribute::DocComment(..) => { /* Just a regular doc comment. */ } } } let (maybe_default_visibility, errs) = default_visibilities.finish(); let default_visibility = maybe_default_visibility.unwrap_or_else(private_visibility); errors.extend(errs); let (maybe_crate_root, errs) = crate_roots.finish(); let crate_root = maybe_crate_root.unwrap_or_else(default_crate_root); errors.extend(errs); let variants: sponge::AllErrors<_, _> = enum_ .variants .into_iter() .map(|variant| { let fields = match variant.fields { Fields::Named(f) => f.named.into_iter().collect(), Fields::Unnamed(_) => { return Err(vec![syn::Error::new( variant.fields.span(), "Only struct-like and unit enum variants are supported", )]); } Fields::Unit => vec![], }; let name = variant.ident; let span = name.span(); let attrs = attributes_from_syn(variant.attrs)?; field_container( name, span, attrs, fields, &mut errors, ErrorLocation::OnVariant, ErrorLocation::InVariant, ) }) .collect(); let variants = errors.absorb(variants.into_result())?; Ok(EnumInfo { crate_root, name, generics, variants, default_visibility, }) } fn field_container( name: syn::Ident, variant_span: proc_macro2::Span, attrs: Vec, fields: Vec, errors: &mut SyntaxErrors, outer_error_location: ErrorLocation, inner_error_location: ErrorLocation, ) -> MultiSynResult { use quote::ToTokens; use syn::spanned::Spanned; let mut outer_errors = errors.scoped(outer_error_location); let mut display_formats = AtMostOne::new("display", outer_error_location); let mut visibilities = AtMostOne::new("visibility", outer_error_location); let mut contexts = AtMostOne::new("context", outer_error_location); let mut doc_comment = String::new(); let mut reached_end_of_doc_comment = false; for attr in attrs { match attr { SnafuAttribute::Display(tokens, d) => display_formats.add(d, tokens), SnafuAttribute::Visibility(tokens, v) => visibilities.add(v, tokens), SnafuAttribute::Context(tokens, c) => contexts.add(c, tokens), SnafuAttribute::Source(tokens, ..) => outer_errors.add(tokens, ATTR_SOURCE), SnafuAttribute::Backtrace(tokens, ..) => outer_errors.add(tokens, ATTR_BACKTRACE), SnafuAttribute::CrateRoot(tokens, ..) => outer_errors.add(tokens, ATTR_CRATE_ROOT), SnafuAttribute::DocComment(_tts, doc_comment_line) => { // We join all the doc comment attributes with a space, // but end once the summary of the doc comment is // complete, which is indicated by an empty line. if !reached_end_of_doc_comment { let trimmed = doc_comment_line.trim(); if trimmed.is_empty() { reached_end_of_doc_comment = true; } else { if !doc_comment.is_empty() { doc_comment.push_str(" "); } doc_comment.push_str(trimmed); } } } } } let mut user_fields = Vec::new(); let mut source_fields = AtMostOne::new("source", inner_error_location); let mut backtrace_fields = AtMostOne::new("backtrace", inner_error_location); for syn_field in fields { let original = syn_field.clone(); let span = syn_field.span(); let name = syn_field .ident .as_ref() .ok_or_else(|| vec![syn::Error::new(span, "Must have a named field")])?; let field = Field { name: name.clone(), ty: syn_field.ty.clone(), original, }; // Check whether we have multiple source/backtrace attributes on this field. // We can't just add to source_fields/backtrace_fields from inside the attribute // loop because source and backtrace are connected and require a bit of special // logic after the attribute loop. For example, we need to know whether there's a // source transformation before we record a source field, but it might be on a // later attribute. We use the data field of `source_attrs` to track any // transformations in case it was a `source(from(...))`, but for backtraces we // don't need any more data. let mut source_attrs = AtMostOne::new("source", ErrorLocation::OnField); let mut backtrace_attrs = AtMostOne::new("backtrace", ErrorLocation::OnField); // Keep track of the negative markers so we can check for inconsistencies and // exclude fields even if they have the "source" or "backtrace" name. let mut source_opt_out = false; let mut backtrace_opt_out = false; let mut field_errors = errors.scoped(ErrorLocation::OnField); for attr in attributes_from_syn(syn_field.attrs.clone())? { match attr { SnafuAttribute::Source(tokens, ss) => { for s in ss { match s { Source::Flag(v) => { // If we've seen a `source(from)` then there will be a // `Some` value in `source_attrs`. let seen_source_from = source_attrs .iter() .map(|(val, _location)| val) .any(Option::is_some); if !v && seen_source_from { field_errors.add(tokens.clone(), SOURCE_BOOL_FROM_INCOMPATIBLE); } if v { source_attrs.add(None, tokens.clone()); } else if name == "source" { source_opt_out = true; } else { field_errors.add(tokens.clone(), ATTR_SOURCE_FALSE); } } Source::From(t, e) => { if source_opt_out { field_errors.add(tokens.clone(), SOURCE_BOOL_FROM_INCOMPATIBLE); } source_attrs.add(Some((t, e)), tokens.clone()); } } } } SnafuAttribute::Backtrace(tokens, v) => { if v { backtrace_attrs.add((), tokens); } else if name == "backtrace" { backtrace_opt_out = true; } else { field_errors.add(tokens, ATTR_BACKTRACE_FALSE); } } SnafuAttribute::Visibility(tokens, ..) => field_errors.add(tokens, ATTR_VISIBILITY), SnafuAttribute::Display(tokens, ..) => field_errors.add(tokens, ATTR_DISPLAY), SnafuAttribute::Context(tokens, ..) => field_errors.add(tokens, ATTR_CONTEXT), SnafuAttribute::CrateRoot(tokens, ..) => field_errors.add(tokens, ATTR_CRATE_ROOT), SnafuAttribute::DocComment(..) => { /* Just a regular doc comment. */ } } } // Add errors for any duplicated attributes on this field. let (source_attr, errs) = source_attrs.finish_with_location(); errors.extend(errs); let (backtrace_attr, errs) = backtrace_attrs.finish_with_location(); errors.extend(errs); let source_attr = source_attr.or_else(|| { if field.name == "source" && !source_opt_out { Some((None, syn_field.clone().into_token_stream())) } else { None } }); let backtrace_attr = backtrace_attr.or_else(|| { if field.name == "backtrace" && !backtrace_opt_out { Some(((), syn_field.clone().into_token_stream())) } else { None } }); if let Some((maybe_transformation, location)) = source_attr { let Field { name, ty, .. } = field; let transformation = maybe_transformation .map(|(ty, expr)| Transformation::Transform { ty, expr }) .unwrap_or_else(|| Transformation::None { ty }); source_fields.add( SourceField { name, transformation, // Specifying `backtrace` on a source field is how you request // delegation of the backtrace to the source error type. backtrace_delegate: backtrace_attr.is_some(), }, location, ); } else if let Some((_, location)) = backtrace_attr { backtrace_fields.add(field, location); } else { user_fields.push(field); } } let (source, errs) = source_fields.finish_with_location(); errors.extend(errs); let (backtrace, errs) = backtrace_fields.finish_with_location(); errors.extend(errs); match (&source, &backtrace) { (Some(source), Some(backtrace)) if source.0.backtrace_delegate => { let source_location = source.1.clone(); let backtrace_location = backtrace.1.clone(); errors.add( source_location, "Cannot have `backtrace` field and `backtrace` attribute on a source field in the same variant", ); errors.add( backtrace_location, "Cannot have `backtrace` field and `backtrace` attribute on a source field in the same variant", ); } _ => {} // no conflict } let (display_format, errs) = display_formats.finish(); errors.extend(errs); let (visibility, errs) = visibilities.finish(); errors.extend(errs); let (is_context, errs) = contexts.finish(); errors.extend(errs); let source_field = source.map(|(val, _tts)| val); let selector_kind = if is_context.unwrap_or(true) { ContextSelectorKind::Context { source_field, user_fields, } } else { errors.extend(user_fields.into_iter().map(|Field { original, .. }| { syn::Error::new_spanned( original, "Context selectors without context must not have context fields", ) })); let source_field = source_field.ok_or_else(|| { vec![syn::Error::new( variant_span, "Context selectors without context must have a source field", )] })?; ContextSelectorKind::NoContext { source_field } }; Ok(FieldContainer { name, backtrace_field: backtrace.map(|(val, _tts)| val), selector_kind, display_format, doc_comment, visibility, }) } fn parse_snafu_struct( struct_: syn::DataStruct, name: syn::Ident, generics: syn::Generics, attrs: Vec, span: proc_macro2::Span, ) -> MultiSynResult { use syn::Fields; match struct_.fields { Fields::Named(f) => { let f = f.named.into_iter().collect(); parse_snafu_named_struct(f, name, generics, attrs, span).map(SnafuInfo::NamedStruct) } Fields::Unnamed(f) => { parse_snafu_tuple_struct(f, name, generics, attrs, span).map(SnafuInfo::TupleStruct) } Fields::Unit => parse_snafu_named_struct(vec![], name, generics, attrs, span) .map(SnafuInfo::NamedStruct), } } fn parse_snafu_named_struct( fields: Vec, name: syn::Ident, generics: syn::Generics, attrs: Vec, span: proc_macro2::Span, ) -> MultiSynResult { let mut errors = SyntaxErrors::default(); let attrs = attributes_from_syn(attrs)?; let mut crate_roots = AtMostOne::new("crate_root", ErrorLocation::OnNamedStruct); let attrs = attrs .into_iter() .flat_map(|attr| match attr { SnafuAttribute::CrateRoot(tokens, root) => { crate_roots.add(root, tokens); None } other => Some(other), }) .collect(); let field_container = field_container( name, span, attrs, fields, &mut errors, ErrorLocation::OnNamedStruct, ErrorLocation::InNamedStruct, )?; let (maybe_crate_root, errs) = crate_roots.finish(); let crate_root = maybe_crate_root.unwrap_or_else(default_crate_root); errors.extend(errs); errors.finish()?; Ok(NamedStructInfo { crate_root, field_container, generics, }) } fn parse_snafu_tuple_struct( mut fields: syn::FieldsUnnamed, name: syn::Ident, generics: syn::Generics, attrs: Vec, span: proc_macro2::Span, ) -> MultiSynResult { let mut transformations = AtMostOne::new("source(from)", ErrorLocation::OnTupleStruct); let mut crate_roots = AtMostOne::new("crate_root", ErrorLocation::OnTupleStruct); let mut errors = SyntaxErrors::default(); let mut struct_errors = errors.scoped(ErrorLocation::OnTupleStruct); for attr in attributes_from_syn(attrs)? { match attr { SnafuAttribute::Display(tokens, ..) => struct_errors.add(tokens, ATTR_DISPLAY), SnafuAttribute::Visibility(tokens, ..) => struct_errors.add(tokens, ATTR_VISIBILITY), SnafuAttribute::Source(tokens, ss) => { for s in ss { match s { Source::Flag(..) => struct_errors.add(tokens.clone(), ATTR_SOURCE_BOOL), Source::From(t, e) => transformations.add((t, e), tokens.clone()), } } } SnafuAttribute::Backtrace(tokens, ..) => struct_errors.add(tokens, ATTR_BACKTRACE), SnafuAttribute::Context(tokens, ..) => struct_errors.add(tokens, ATTR_CONTEXT), SnafuAttribute::CrateRoot(tokens, root) => crate_roots.add(root, tokens), SnafuAttribute::DocComment(..) => { /* Just a regular doc comment. */ } } } fn one_field_error(span: proc_macro2::Span) -> syn::Error { syn::Error::new( span, "Can only derive `Snafu` for tuple structs with exactly one field", ) } let inner = fields .unnamed .pop() .ok_or_else(|| vec![one_field_error(span)])?; if !fields.unnamed.is_empty() { return Err(vec![one_field_error(span)]); } let (maybe_transformation, errs) = transformations.finish(); let transformation = maybe_transformation .map(|(ty, expr)| Transformation::Transform { ty, expr }) .unwrap_or_else(|| Transformation::None { ty: inner.into_value().ty, }); errors.extend(errs); let (maybe_crate_root, errs) = crate_roots.finish(); let crate_root = maybe_crate_root.unwrap_or_else(default_crate_root); errors.extend(errs); errors.finish()?; Ok(TupleStructInfo { crate_root, name, generics, transformation, }) } enum MyMeta { CompatParen(T), CompatDirect(T), Pretty(T), None, } impl MyMeta { fn into_option(self) -> Option { match self { MyMeta::CompatParen(v) => Some(v), MyMeta::CompatDirect(v) => Some(v), MyMeta::Pretty(v) => Some(v), MyMeta::None => None, } } } impl syn::parse::Parse for MyMeta where T: syn::parse::Parse, { fn parse(input: syn::parse::ParseStream) -> SynResult { use syn::token::{Eq, Paren}; use syn::LitStr; let lookahead = input.lookahead1(); if lookahead.peek(Paren) { let inside; parenthesized!(inside in input); let t: T = inside.parse()?; Ok(MyMeta::Pretty(t)) } else if lookahead.peek(Eq) { let _: Eq = input.parse()?; let s: LitStr = input.parse()?; match s.parse::>() { Ok(t) => Ok(MyMeta::CompatParen(t.0)), Err(_) => match s.parse::() { Ok(t) => Ok(MyMeta::CompatDirect(t)), Err(e) => Err(e), }, } } else if input.is_empty() { Ok(MyMeta::None) } else { Err(lookahead.error()) } } } struct MyParens(T); impl syn::parse::Parse for MyParens where T: syn::parse::Parse, { fn parse(input: syn::parse::ParseStream) -> SynResult { let inside; parenthesized!(inside in input); inside.parse().map(MyParens) } } struct List(syn::punctuated::Punctuated); impl syn::parse::Parse for List where T: syn::parse::Parse, { fn parse(input: syn::parse::ParseStream) -> SynResult { use syn::punctuated::Punctuated; let exprs = Punctuated::parse_terminated(input)?; Ok(List(exprs)) } } impl List { fn into_vec(self) -> Vec { self.0.into_iter().collect() } } enum Source { Flag(bool), From(syn::Type, syn::Expr), } impl syn::parse::Parse for Source { fn parse(input: syn::parse::ParseStream) -> SynResult { use syn::token::Comma; use syn::{Expr, Ident, LitBool, Type}; let lookahead = input.lookahead1(); if lookahead.peek(LitBool) { let val: LitBool = input.parse()?; Ok(Source::Flag(val.value)) } else if lookahead.peek(Ident) { let name: Ident = input.parse()?; if name == "from" { let inside; parenthesized!(inside in input); let ty: Type = inside.parse()?; let _: Comma = inside.parse()?; let expr: Expr = inside.parse()?; Ok(Source::From(ty, expr)) } else { Err(syn::Error::new( name.span(), "expected `true`, `false`, or `from`", )) } } else { Err(lookahead.error()) } } } // Having a Backtrace newtype and implementing Parse gives us a way to handle careful parsing // errors outside of `impl Parse for SnafuAttribute` struct Backtrace(bool); impl syn::parse::Parse for Backtrace { fn parse(input: syn::parse::ParseStream) -> SynResult { use syn::{Ident, LitBool}; let lookahead = input.lookahead1(); if lookahead.peek(LitBool) { let val: LitBool = input.parse()?; Ok(Backtrace(val.value)) } else if lookahead.peek(Ident) { let name: Ident = input.parse()?; if name == "delegate" { Err(syn::Error::new( name.span(), "`backtrace(delegate)` has been removed; use `backtrace` on a source field", )) } else { Err(syn::Error::new(name.span(), "expected `true` or `false`")) } } else { Err(lookahead.error()) } } } /// A SnafuAttribute represents one SNAFU-specific attribute inside of `#[snafu(...)]`. For /// example, in `#[snafu(visibility(pub), display("hi"))]`, `visibility(pub)` and `display("hi")` /// are each a SnafuAttribute. /// /// We store the location in the source where we found the attribute (as a `TokenStream`) along /// with the data. The location can be used to give accurate error messages in case there was a /// problem with the use of the attribute. enum SnafuAttribute { Display(proc_macro2::TokenStream, UserInput), Visibility(proc_macro2::TokenStream, UserInput), Source(proc_macro2::TokenStream, Vec), Backtrace(proc_macro2::TokenStream, bool), Context(proc_macro2::TokenStream, bool), CrateRoot(proc_macro2::TokenStream, UserInput), DocComment(proc_macro2::TokenStream, String), } impl syn::parse::Parse for SnafuAttribute { fn parse(input: syn::parse::ParseStream) -> SynResult { use syn::token::{Comma, Paren}; use syn::{Expr, Ident, LitBool, Path, Visibility}; let input_tts = input.cursor().token_stream(); let name: Ident = input.parse()?; if name == "display" { let m: MyMeta> = input.parse()?; let v = m.into_option().ok_or_else(|| { syn::Error::new(name.span(), "`snafu(display)` requires an argument") })?; let v = Box::new(v.0); Ok(SnafuAttribute::Display(input_tts, v)) } else if name == "visibility" { let m: MyMeta = input.parse()?; let v = m .into_option() .map_or_else(private_visibility, |v| Box::new(v) as UserInput); Ok(SnafuAttribute::Visibility(input_tts, v)) } else if name == "source" { let lookahead = input.lookahead1(); if input.is_empty() || lookahead.peek(Comma) { Ok(SnafuAttribute::Source(input_tts, vec![Source::Flag(true)])) } else if lookahead.peek(Paren) { let v: MyParens> = input.parse()?; Ok(SnafuAttribute::Source(input_tts, v.0.into_vec())) } else { Err(lookahead.error()) } } else if name == "backtrace" { let lookahead = input.lookahead1(); if input.is_empty() || lookahead.peek(Comma) { Ok(SnafuAttribute::Backtrace(input_tts, true)) } else if lookahead.peek(Paren) { let v: MyParens = input.parse()?; let backtrace = v.0; Ok(SnafuAttribute::Backtrace(input_tts, backtrace.0)) } else { Err(lookahead.error()) } } else if name == "context" { if input.is_empty() { Ok(SnafuAttribute::Context(input_tts, true)) } else { let v: MyParens = input.parse()?; Ok(SnafuAttribute::Context(input_tts, v.0.value)) } } else if name == "crate_root" { let m: MyMeta = input.parse()?; let v = m.into_option().ok_or_else(|| { syn::Error::new(name.span(), "`snafu(crate_root)` requires an argument") })?; let v = Box::new(v); Ok(SnafuAttribute::CrateRoot(input_tts, v)) } else { Err(syn::Error::new( name.span(), "expected `display`, `visibility`, `source`, `backtrace`, `context`, or `crate_root`", )) } } } struct SnafuAttributeBody(Vec); impl syn::parse::Parse for SnafuAttributeBody { fn parse(input: syn::parse::ParseStream) -> SynResult { use syn::punctuated::Punctuated; use syn::token::Comma; // Remove the parentheses from `#[snafu(...)]` so SnafuAttribute only has to deal with the // tokens inside. let inside; parenthesized!(inside in input); let parse_comma_list = Punctuated::::parse_terminated; let list = parse_comma_list(&inside)?; Ok(SnafuAttributeBody( list.into_pairs().map(|p| p.into_value()).collect(), )) } } struct DocComment(SnafuAttribute); impl syn::parse::Parse for DocComment { fn parse(input: syn::parse::ParseStream) -> SynResult { use syn::token::Eq; use syn::LitStr; let _: Eq = input.parse()?; let tokens = input.cursor().token_stream(); let doc: LitStr = input.parse()?; Ok(DocComment(SnafuAttribute::DocComment(tokens, doc.value()))) } } fn attributes_from_syn(attrs: Vec) -> MultiSynResult> { use syn::parse2; let mut ours = Vec::new(); let mut errs = Vec::new(); let parsed_attrs = attrs.into_iter().flat_map(|attr| { if attr.path.is_ident("snafu") { Some(parse2::(attr.tokens).map(|body| body.0)) } else if attr.path.is_ident("doc") { // Ignore any errors that occur while parsing the doc // comment. This isn't our attribute so we shouldn't // assume that we know what values are acceptable. parse2::(attr.tokens) .ok() .map(|comment| Ok(vec![comment.0])) } else { None } }); for attr in parsed_attrs { match attr { Ok(v) => ours.extend(v), Err(e) => errs.push(e), } } if errs.is_empty() { Ok(ours) } else { Err(errs) } } fn default_crate_root() -> UserInput { Box::new(quote! { ::snafu }) } fn private_visibility() -> UserInput { Box::new(quote! {}) } impl From for proc_macro::TokenStream { fn from(other: SnafuInfo) -> proc_macro::TokenStream { match other { SnafuInfo::Enum(e) => e.into(), SnafuInfo::NamedStruct(s) => s.into(), SnafuInfo::TupleStruct(s) => s.into(), } } } impl From for proc_macro::TokenStream { fn from(other: EnumInfo) -> proc_macro::TokenStream { other.generate_snafu().into() } } impl From for proc_macro::TokenStream { fn from(other: NamedStructInfo) -> proc_macro::TokenStream { other.generate_snafu().into() } } impl From for proc_macro::TokenStream { fn from(other: TupleStructInfo) -> proc_macro::TokenStream { other.generate_snafu().into() } } trait GenericAwareNames { fn name(&self) -> &syn::Ident; fn generics(&self) -> &syn::Generics; fn parameterized_name(&self) -> UserInput { let enum_name = self.name(); let original_generics = self.provided_generic_names(); Box::new(quote! { #enum_name<#(#original_generics,)*> }) } fn provided_generic_types_without_defaults(&self) -> Vec { use syn::TypeParam; self.generics() .type_params() .map(|t: &TypeParam| { let TypeParam { attrs, ident, colon_token, bounds, .. } = t; quote! { #(#attrs)* #ident #colon_token #bounds } }) .collect() } fn provided_generics_without_defaults(&self) -> Vec { self.provided_generic_lifetimes() .into_iter() .chain(self.provided_generic_types_without_defaults().into_iter()) .collect() } fn provided_generic_lifetimes(&self) -> Vec { use syn::{GenericParam, LifetimeDef}; self.generics() .params .iter() .flat_map(|p| match p { GenericParam::Lifetime(LifetimeDef { lifetime, .. }) => Some(quote! { #lifetime }), _ => None, }) .collect() } fn provided_generic_names(&self) -> Vec { use syn::{ConstParam, GenericParam, LifetimeDef, TypeParam}; self.generics() .params .iter() .map(|p| match p { GenericParam::Type(TypeParam { ident, .. }) => quote! { #ident }, GenericParam::Lifetime(LifetimeDef { lifetime, .. }) => quote! { #lifetime }, GenericParam::Const(ConstParam { ident, .. }) => quote! { #ident }, }) .collect() } fn provided_where_clauses(&self) -> Vec { self.generics() .where_clause .iter() .flat_map(|c| c.predicates.iter().map(|p| quote! { #p })) .collect() } } impl EnumInfo { fn generate_snafu(self) -> proc_macro2::TokenStream { let context_selectors = ContextSelectors(&self); let display_impl = DisplayImpl(&self); let error_impl = ErrorImpl(&self); let error_compat_impl = ErrorCompatImpl(&self); quote! { #context_selectors #display_impl #error_impl #error_compat_impl } } } impl GenericAwareNames for EnumInfo { fn name(&self) -> &syn::Ident { &self.name } fn generics(&self) -> &syn::Generics { &self.generics } } struct ContextSelectors<'a>(&'a EnumInfo); impl<'a> quote::ToTokens for ContextSelectors<'a> { fn to_tokens(&self, stream: &mut proc_macro2::TokenStream) { let context_selectors = self .0 .variants .iter() .map(|variant| ContextSelector(self.0, variant)); stream.extend({ quote! { #(#context_selectors)* } }) } } struct ContextSelector<'a>(&'a EnumInfo, &'a FieldContainer); impl<'a> quote::ToTokens for ContextSelector<'a> { fn to_tokens(&self, stream: &mut proc_macro2::TokenStream) { use crate::shared::ContextSelector; let enum_name = &self.0.name; let FieldContainer { name: variant_name, selector_kind, .. } = self.1; let visibility = self .1 .visibility .as_ref() .unwrap_or(&self.0.default_visibility); let selector_doc_string = format!( "SNAFU context selector for the `{}::{}` variant", enum_name, variant_name, ); let context_selector = ContextSelector { backtrace_field: self.1.backtrace_field.as_ref(), crate_root: &self.0.crate_root, error_constructor_name: "e! { #enum_name::#variant_name }, original_generics_without_defaults: &self.0.provided_generics_without_defaults(), parameterized_error_name: &self.0.parameterized_name(), selector_doc_string: &selector_doc_string, selector_kind: &selector_kind, selector_name: variant_name, user_fields: &selector_kind.user_fields(), visibility: Some(&visibility), where_clauses: &self.0.provided_where_clauses(), }; stream.extend(quote! { #context_selector }); } } struct DisplayImpl<'a>(&'a EnumInfo); impl<'a> quote::ToTokens for DisplayImpl<'a> { fn to_tokens(&self, stream: &mut proc_macro2::TokenStream) { use self::shared::{Display, DisplayMatchArm}; let enum_name = &self.0.name; let arms: Vec<_> = self .0 .variants .iter() .map(|variant| { let FieldContainer { backtrace_field, display_format, doc_comment, name: variant_name, selector_kind, .. } = variant; let arm = DisplayMatchArm { backtrace_field: backtrace_field.as_ref(), default_name: &variant_name, display_format: display_format.as_ref().map(|f| &**f), doc_comment, pattern_ident: "e! { #enum_name::#variant_name }, selector_kind, }; quote! { #arm } }) .collect(); let display = Display { arms: &arms, original_generics: &self.0.provided_generics_without_defaults(), parameterized_error_name: &self.0.parameterized_name(), where_clauses: &self.0.provided_where_clauses(), }; let display_impl = quote! { #display }; stream.extend(display_impl) } } struct ErrorImpl<'a>(&'a EnumInfo); impl<'a> quote::ToTokens for ErrorImpl<'a> { fn to_tokens(&self, stream: &mut proc_macro2::TokenStream) { use self::shared::{Error, ErrorSourceMatchArm}; let (variants_to_description, variants_to_source): (Vec<_>, Vec<_>) = self .0 .variants .iter() .map(|field_container| { let enum_name = &self.0.name; let variant_name = &field_container.name; let pattern_ident = "e! { #enum_name::#variant_name }; let error_description_match_arm = quote! { #pattern_ident { .. } => stringify!(#pattern_ident), }; let error_source_match_arm = ErrorSourceMatchArm { field_container, pattern_ident, }; let error_source_match_arm = quote! { #error_source_match_arm }; (error_description_match_arm, error_source_match_arm) }) .unzip(); let error_impl = Error { crate_root: &self.0.crate_root, parameterized_error_name: &self.0.parameterized_name(), description_arms: &variants_to_description, source_arms: &variants_to_source, original_generics: &self.0.provided_generics_without_defaults(), where_clauses: &self.0.provided_where_clauses(), }; let error_impl = quote! { #error_impl }; stream.extend(error_impl); } } struct ErrorCompatImpl<'a>(&'a EnumInfo); impl<'a> quote::ToTokens for ErrorCompatImpl<'a> { fn to_tokens(&self, stream: &mut proc_macro2::TokenStream) { use self::shared::{ErrorCompat, ErrorCompatBacktraceMatchArm}; let variants_to_backtrace: Vec<_> = self .0 .variants .iter() .map(|field_container| { let crate_root = &self.0.crate_root; let enum_name = &self.0.name; let variant_name = &field_container.name; let match_arm = ErrorCompatBacktraceMatchArm { field_container, crate_root, pattern_ident: "e! { #enum_name::#variant_name }, }; quote! { #match_arm } }) .collect(); let error_compat_impl = ErrorCompat { crate_root: &self.0.crate_root, parameterized_error_name: &self.0.parameterized_name(), backtrace_arms: &variants_to_backtrace, original_generics: &self.0.provided_generics_without_defaults(), where_clauses: &self.0.provided_where_clauses(), }; let error_compat_impl = quote! { #error_compat_impl }; stream.extend(error_compat_impl); } } impl NamedStructInfo { fn selector_name(&self) -> syn::Ident { let selector_name = self.field_container.name.to_string(); let selector_name = selector_name.trim_end_matches("Error"); format_ident!( "{}Context", selector_name, span = self.field_container.name.span() ) } fn generate_snafu(self) -> proc_macro2::TokenStream { let parameterized_struct_name = self.parameterized_name(); let original_generics = self.provided_generics_without_defaults(); let where_clauses = self.provided_where_clauses(); let selector_name = self.selector_name(); let Self { crate_root, field_container: FieldContainer { name, selector_kind, backtrace_field, display_format, doc_comment, visibility, }, .. } = &self; let field_container = &self.field_container; let user_fields = selector_kind.user_fields(); use crate::shared::{Error, ErrorSourceMatchArm}; let pattern_ident = "e! { Self }; let error_description_match_arm = quote! { #pattern_ident { .. } => stringify!(#name), }; let error_source_match_arm = ErrorSourceMatchArm { field_container: &field_container, pattern_ident, }; let error_source_match_arm = quote! { #error_source_match_arm }; let error_impl = Error { crate_root: &crate_root, parameterized_error_name: ¶meterized_struct_name, description_arms: &[error_description_match_arm], source_arms: &[error_source_match_arm], original_generics: &original_generics, where_clauses: &where_clauses, }; let error_impl = quote! { #error_impl }; use self::shared::{ErrorCompat, ErrorCompatBacktraceMatchArm}; let match_arm = ErrorCompatBacktraceMatchArm { field_container, crate_root: &crate_root, pattern_ident: "e! { Self }, }; let match_arm = quote! { #match_arm }; let error_compat_impl = ErrorCompat { crate_root: &crate_root, parameterized_error_name: ¶meterized_struct_name, backtrace_arms: &[match_arm], original_generics: &original_generics, where_clauses: &where_clauses, }; use crate::shared::{Display, DisplayMatchArm}; let arm = DisplayMatchArm { backtrace_field: backtrace_field.as_ref(), default_name: &name, display_format: display_format.as_ref().map(|f| &**f), doc_comment: &doc_comment, pattern_ident: "e! { Self }, selector_kind: &selector_kind, }; let arm = quote! { #arm }; let display_impl = Display { arms: &[arm], original_generics: &original_generics, parameterized_error_name: ¶meterized_struct_name, where_clauses: &where_clauses, }; use crate::shared::ContextSelector; let selector_doc_string = format!("SNAFU context selector for the `{}` error", name); let context_selector = ContextSelector { backtrace_field: backtrace_field.as_ref(), crate_root: &crate_root, error_constructor_name: &name, original_generics_without_defaults: &original_generics, parameterized_error_name: ¶meterized_struct_name, selector_doc_string: &selector_doc_string, selector_kind: &selector_kind, selector_name: &selector_name, user_fields: &user_fields, visibility: visibility.as_ref().map(|x| &**x), where_clauses: &where_clauses, }; quote! { #error_impl #error_compat_impl #display_impl #context_selector } } } impl GenericAwareNames for NamedStructInfo { fn name(&self) -> &syn::Ident { &self.field_container.name } fn generics(&self) -> &syn::Generics { &self.generics } } impl TupleStructInfo { fn generate_snafu(self) -> proc_macro2::TokenStream { let parameterized_struct_name = self.parameterized_name(); let TupleStructInfo { crate_root, generics, name, transformation, } = self; let inner_type = transformation.ty(); let transformation = transformation.transformation(); let where_clauses: Vec<_> = generics .where_clause .iter() .flat_map(|c| c.predicates.iter().map(|p| quote! { #p })) .collect(); let description_fn = quote! { fn description(&self) -> &str { #crate_root::Error::description(&self.0) } }; let cause_fn = quote! { fn cause(&self) -> ::core::option::Option<&dyn #crate_root::Error> { #crate_root::Error::cause(&self.0) } }; let source_fn = quote! { fn source(&self) -> ::core::option::Option<&(dyn #crate_root::Error + 'static)> { #crate_root::Error::source(&self.0) } }; let backtrace_fn = quote! { fn backtrace(&self) -> ::core::option::Option<&#crate_root::Backtrace> { #crate_root::ErrorCompat::backtrace(&self.0) } }; let std_backtrace_fn = if cfg!(feature = "unstable-backtraces-impl-std") { quote! { fn backtrace(&self) -> ::core::option::Option<&std::backtrace::Backtrace> { #crate_root::ErrorCompat::backtrace(self) } } } else { quote! {} }; let error_impl = quote! { #[allow(single_use_lifetimes)] impl#generics #crate_root::Error for #parameterized_struct_name where #(#where_clauses),* { #description_fn #cause_fn #source_fn #std_backtrace_fn } }; let error_compat_impl = quote! { #[allow(single_use_lifetimes)] impl#generics #crate_root::ErrorCompat for #parameterized_struct_name where #(#where_clauses),* { #backtrace_fn } }; let display_impl = quote! { #[allow(single_use_lifetimes)] impl#generics ::core::fmt::Display for #parameterized_struct_name where #(#where_clauses),* { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { ::core::fmt::Display::fmt(&self.0, f) } } }; let from_impl = quote! { impl#generics ::core::convert::From<#inner_type> for #parameterized_struct_name where #(#where_clauses),* { fn from(other: #inner_type) -> Self { #name((#transformation)(other)) } } }; quote! { #error_impl #error_compat_impl #display_impl #from_impl } } } impl GenericAwareNames for TupleStructInfo { fn name(&self) -> &syn::Ident { &self.name } fn generics(&self) -> &syn::Generics { &self.generics } } trait Transpose { fn my_transpose(self) -> Result, E>; } impl Transpose for Option> { fn my_transpose(self) -> Result, E> { match self { Some(Ok(v)) => Ok(Some(v)), Some(Err(e)) => Err(e), None => Ok(None), } } } mod sponge { use std::iter::FromIterator; pub struct AllErrors(Result>); impl AllErrors { pub fn into_result(self) -> Result> { self.0 } } impl FromIterator> for AllErrors where T: FromIterator, { fn from_iter(i: I) -> Self where I: IntoIterator>, { let mut errors = Vec::new(); let inner = i .into_iter() .flat_map(|v| match v { Ok(v) => Ok(v), Err(e) => { errors.push(e); Err(()) } }) .collect(); if errors.is_empty() { AllErrors(Ok(inner)) } else { AllErrors(Err(errors)) } } } impl FromIterator>> for AllErrors where T: FromIterator, { fn from_iter(i: I) -> Self where I: IntoIterator>>, { let mut errors = Vec::new(); let inner = i .into_iter() .flat_map(|v| match v { Ok(v) => Ok(v), Err(e) => { errors.extend(e); Err(()) } }) .collect(); if errors.is_empty() { AllErrors(Ok(inner)) } else { AllErrors(Err(errors)) } } } } snafu-derive-0.6.10/src/shared.rs010064400007660000024000000504131376205172600147650ustar 00000000000000pub(crate) use self::context_selector::ContextSelector; pub(crate) use self::display::{Display, DisplayMatchArm}; pub(crate) use self::error::{Error, ErrorSourceMatchArm}; pub(crate) use self::error_compat::{ErrorCompat, ErrorCompatBacktraceMatchArm}; pub mod context_selector { use crate::{ContextSelectorKind, Field}; use proc_macro2::TokenStream; use quote::{format_ident, quote, ToTokens}; #[derive(Copy, Clone)] pub(crate) struct ContextSelector<'a> { pub backtrace_field: Option<&'a Field>, pub crate_root: &'a dyn ToTokens, pub error_constructor_name: &'a dyn ToTokens, pub original_generics_without_defaults: &'a [TokenStream], pub parameterized_error_name: &'a dyn ToTokens, pub selector_doc_string: &'a str, pub selector_kind: &'a ContextSelectorKind, pub selector_name: &'a proc_macro2::Ident, pub user_fields: &'a [Field], pub visibility: Option<&'a dyn ToTokens>, pub where_clauses: &'a [TokenStream], } impl ToTokens for ContextSelector<'_> { fn to_tokens(&self, stream: &mut TokenStream) { use self::ContextSelectorKind::*; let context_selector = match self.selector_kind { Context { source_field, .. } => { let context_selector_type = self.generate_type(); let context_selector_impl = match source_field { Some(_) => None, None => Some(self.generate_leaf()), }; let context_selector_into_error_impl = self.generate_into_error(source_field.as_ref()); quote! { #context_selector_type #context_selector_impl #context_selector_into_error_impl } } NoContext { source_field } => self.generate_from_source(source_field), }; stream.extend(context_selector) } } impl ContextSelector<'_> { fn user_field_generics(&self) -> Vec { (0..self.user_fields.len()) .map(|i| format_ident!("__T{}", i)) .collect() } fn user_field_names(&self) -> Vec<&syn::Ident> { self.user_fields .iter() .map(|Field { name, .. }| name) .collect() } fn parameterized_selector_name(&self) -> TokenStream { let selector_name = self.selector_name; let user_generics = self.user_field_generics(); quote! { #selector_name<#(#user_generics,)*> } } fn extended_where_clauses(&self) -> Vec { let user_fields = self.user_fields; let user_field_generics = self.user_field_generics(); let where_clauses = self.where_clauses; let target_types = user_fields .iter() .map(|Field { ty, .. }| quote! { ::core::convert::Into<#ty>}); user_field_generics .into_iter() .zip(target_types) .map(|(gen, bound)| quote! { #gen: #bound }) .chain(where_clauses.iter().cloned()) .collect() } fn transfer_user_fields(&self) -> Vec { self.user_field_names() .into_iter() .map(|name| { quote! { #name: ::core::convert::Into::into(self.#name) } }) .collect() } fn construct_backtrace_field(&self) -> Option { self.backtrace_field.map(|field| { let crate_root = self.crate_root; let name = &field.name; quote! { #name: #crate_root::GenerateBacktrace::generate(), } }) } fn generate_type(self) -> TokenStream { let visibility = self.visibility; let parameterized_selector_name = self.parameterized_selector_name(); let user_field_generics = self.user_field_generics(); let user_field_names = self.user_field_names(); let selector_doc_string = self.selector_doc_string; let body = if user_field_names.is_empty() { quote! { ; } } else { quote! { { #( #[allow(missing_docs)] #visibility #user_field_names: #user_field_generics ),* } } }; quote! { #[derive(Debug, Copy, Clone)] #[doc = #selector_doc_string] #visibility struct #parameterized_selector_name #body } } fn generate_leaf(self) -> TokenStream { let error_constructor_name = self.error_constructor_name; let original_generics_without_defaults = self.original_generics_without_defaults; let parameterized_error_name = self.parameterized_error_name; let parameterized_selector_name = self.parameterized_selector_name(); let user_field_generics = self.user_field_generics(); let visibility = self.visibility; let extended_where_clauses = self.extended_where_clauses(); let transfer_user_fields = self.transfer_user_fields(); let construct_backtrace_field = self.construct_backtrace_field(); quote! { impl<#(#user_field_generics,)*> #parameterized_selector_name { #[doc = "Consume the selector and return the associated error"] #[must_use] #visibility fn build<#(#original_generics_without_defaults,)*>(self) -> #parameterized_error_name where #(#extended_where_clauses),* { #error_constructor_name { #construct_backtrace_field #(#transfer_user_fields,)* } } #[doc = "Consume the selector and return a `Result` with the associated error"] #visibility fn fail<#(#original_generics_without_defaults,)* __T>(self) -> ::core::result::Result<__T, #parameterized_error_name> where #(#extended_where_clauses),* { ::core::result::Result::Err(self.build()) } } } } fn generate_into_error(self, source_field: Option<&crate::SourceField>) -> TokenStream { let crate_root = self.crate_root; let error_constructor_name = self.error_constructor_name; let original_generics_without_defaults = self.original_generics_without_defaults; let parameterized_error_name = self.parameterized_error_name; let parameterized_selector_name = self.parameterized_selector_name(); let user_field_generics = self.user_field_generics(); let extended_where_clauses = self.extended_where_clauses(); let transfer_user_fields = self.transfer_user_fields(); let construct_backtrace_field = self.construct_backtrace_field(); let (source_ty, transfer_source_field) = match source_field { Some(source_field) => { let (ty, transfer) = build_source_info(source_field); (quote! { #ty }, transfer) } None => (quote! { #crate_root::NoneError }, quote! {}), }; quote! { impl<#(#original_generics_without_defaults,)* #(#user_field_generics,)*> #crate_root::IntoError<#parameterized_error_name> for #parameterized_selector_name where #parameterized_error_name: #crate_root::Error + #crate_root::ErrorCompat, #(#extended_where_clauses),* { type Source = #source_ty; fn into_error(self, error: Self::Source) -> #parameterized_error_name { #error_constructor_name { #transfer_source_field #construct_backtrace_field #(#transfer_user_fields),* } } } } } fn generate_from_source(self, source_field: &crate::SourceField) -> TokenStream { let parameterized_error_name = self.parameterized_error_name; let error_constructor_name = self.error_constructor_name; let construct_backtrace_field = self.construct_backtrace_field(); let original_generics_without_defaults = self.original_generics_without_defaults; let user_field_generics = self.user_field_generics(); let where_clauses = self.where_clauses; let (source_field_type, transfer_source_field) = build_source_info(source_field); quote! { impl<#(#original_generics_without_defaults,)* #(#user_field_generics,)*> ::core::convert::From<#source_field_type> for #parameterized_error_name where #(#where_clauses),* { fn from(error: #source_field_type) -> Self { #error_constructor_name { #transfer_source_field #construct_backtrace_field } } } } } } // Assumes that the error is in a variable called "error" fn build_source_info(source_field: &crate::SourceField) -> (&syn::Type, TokenStream) { let source_field_name = source_field.name(); let source_field_type = source_field.transformation.ty(); let source_transformation = source_field.transformation.transformation(); ( source_field_type, quote! { #source_field_name: (#source_transformation)(error), }, ) } } pub mod display { use crate::{Field, SourceField}; use proc_macro2::TokenStream; use quote::{quote, ToTokens}; struct StaticIdent(&'static str); impl quote::ToTokens for StaticIdent { fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) { proc_macro2::Ident::new(self.0, proc_macro2::Span::call_site()).to_tokens(tokens) } } const FORMATTER_ARG: StaticIdent = StaticIdent("__snafu_display_formatter"); pub(crate) struct Display<'a> { pub(crate) arms: &'a [TokenStream], pub(crate) original_generics: &'a [TokenStream], pub(crate) parameterized_error_name: &'a dyn ToTokens, pub(crate) where_clauses: &'a [TokenStream], } impl ToTokens for Display<'_> { fn to_tokens(&self, stream: &mut TokenStream) { let Self { arms, original_generics, parameterized_error_name, where_clauses, } = *self; let display_impl = quote! { #[allow(single_use_lifetimes)] impl<#(#original_generics),*> ::core::fmt::Display for #parameterized_error_name where #(#where_clauses),* { fn fmt(&self, #FORMATTER_ARG: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { #[allow(unused_variables)] match *self { #(#arms),* } } } }; stream.extend(display_impl); } } pub(crate) struct DisplayMatchArm<'a> { pub(crate) backtrace_field: Option<&'a crate::Field>, pub(crate) default_name: &'a dyn ToTokens, pub(crate) display_format: Option<&'a dyn ToTokens>, pub(crate) doc_comment: &'a str, pub(crate) pattern_ident: &'a dyn ToTokens, pub(crate) selector_kind: &'a crate::ContextSelectorKind, } impl ToTokens for DisplayMatchArm<'_> { fn to_tokens(&self, stream: &mut TokenStream) { let Self { backtrace_field, default_name, display_format, doc_comment, pattern_ident, selector_kind, } = *self; let user_fields = selector_kind.user_fields(); let source_field = selector_kind.source_field(); let format = match (display_format, source_field) { (Some(v), _) => quote! { #v }, (None, _) if !doc_comment.is_empty() => { quote! { #doc_comment } } (None, Some(f)) => { let field_name = &f.name; quote! { concat!(stringify!(#default_name), ": {}"), #field_name } } (None, None) => quote! { stringify!(#default_name)}, }; let field_names = user_fields .iter() .chain(backtrace_field) .map(Field::name) .chain(source_field.map(SourceField::name)); let field_names = quote! { #(ref #field_names),* }; let match_arm = quote! { #pattern_ident { #field_names } => { write!(#FORMATTER_ARG, #format) } }; stream.extend(match_arm); } } } pub mod error { use crate::{FieldContainer, SourceField}; use proc_macro2::TokenStream; use quote::{quote, ToTokens}; pub(crate) struct Error<'a> { pub(crate) crate_root: &'a dyn ToTokens, pub(crate) parameterized_error_name: &'a dyn ToTokens, pub(crate) description_arms: &'a [TokenStream], pub(crate) source_arms: &'a [TokenStream], pub(crate) original_generics: &'a [TokenStream], pub(crate) where_clauses: &'a [TokenStream], } impl ToTokens for Error<'_> { fn to_tokens(&self, stream: &mut TokenStream) { let Self { crate_root, parameterized_error_name, description_arms, source_arms, original_generics, where_clauses, } = *self; let description_fn = quote! { fn description(&self) -> &str { match *self { #(#description_arms)* } } }; let source_body = quote! { use #crate_root::AsErrorSource; match *self { #(#source_arms)* } }; let cause_fn = quote! { fn cause(&self) -> ::core::option::Option<&dyn #crate_root::Error> { #source_body } }; let source_fn = quote! { fn source(&self) -> ::core::option::Option<&(dyn #crate_root::Error + 'static)> { #source_body } }; let std_backtrace_fn = if cfg!(feature = "unstable-backtraces-impl-std") { Some(quote! { fn backtrace(&self) -> ::core::option::Option<&::std::backtrace::Backtrace> { #crate_root::ErrorCompat::backtrace(self) } }) } else { None }; let error = quote! { #[allow(single_use_lifetimes)] impl<#(#original_generics),*> #crate_root::Error for #parameterized_error_name where Self: ::core::fmt::Debug + ::core::fmt::Display, #(#where_clauses),* { #description_fn #cause_fn #source_fn #std_backtrace_fn } }; stream.extend(error); } } pub(crate) struct ErrorSourceMatchArm<'a> { pub(crate) field_container: &'a FieldContainer, pub(crate) pattern_ident: &'a dyn ToTokens, } impl ToTokens for ErrorSourceMatchArm<'_> { fn to_tokens(&self, stream: &mut TokenStream) { let Self { field_container: FieldContainer { selector_kind, .. }, pattern_ident, } = *self; let source_field = selector_kind.source_field(); let arm = match source_field { Some(source_field) => { let SourceField { name: field_name, .. } = source_field; quote! { #pattern_ident { ref #field_name, .. } => { ::core::option::Option::Some(#field_name.as_error_source()) } } } None => { quote! { #pattern_ident { .. } => { ::core::option::Option::None } } } }; stream.extend(arm); } } } pub mod error_compat { use crate::{Field, FieldContainer, SourceField}; use proc_macro2::TokenStream; use quote::{quote, ToTokens}; pub(crate) struct ErrorCompat<'a> { pub(crate) crate_root: &'a dyn ToTokens, pub(crate) parameterized_error_name: &'a dyn ToTokens, pub(crate) backtrace_arms: &'a [TokenStream], pub(crate) original_generics: &'a [TokenStream], pub(crate) where_clauses: &'a [TokenStream], } impl ToTokens for ErrorCompat<'_> { fn to_tokens(&self, stream: &mut TokenStream) { let Self { crate_root, parameterized_error_name, backtrace_arms, original_generics, where_clauses, } = *self; let backtrace_fn = quote! { fn backtrace(&self) -> ::core::option::Option<&#crate_root::Backtrace> { match *self { #(#backtrace_arms),* } } }; let error_compat_impl = quote! { #[allow(single_use_lifetimes)] impl<#(#original_generics),*> #crate_root::ErrorCompat for #parameterized_error_name where #(#where_clauses),* { #backtrace_fn } }; stream.extend(error_compat_impl); } } pub(crate) struct ErrorCompatBacktraceMatchArm<'a> { pub(crate) crate_root: &'a dyn ToTokens, pub(crate) field_container: &'a FieldContainer, pub(crate) pattern_ident: &'a dyn ToTokens, } impl ToTokens for ErrorCompatBacktraceMatchArm<'_> { fn to_tokens(&self, stream: &mut TokenStream) { let Self { crate_root, field_container: FieldContainer { backtrace_field, selector_kind, .. }, pattern_ident, } = *self; let match_arm = match (selector_kind.source_field(), backtrace_field) { (Some(source_field), _) if source_field.backtrace_delegate => { let SourceField { name: field_name, .. } = source_field; quote! { #pattern_ident { ref #field_name, .. } => { #crate_root::ErrorCompat::backtrace(#field_name) } } } (_, Some(backtrace_field)) => { let Field { name: field_name, .. } = backtrace_field; quote! { #pattern_ident { ref #field_name, .. } => { #crate_root::GenerateBacktrace::as_backtrace(#field_name) } } } _ => { quote! { #pattern_ident { .. } => { ::core::option::Option::None } } } }; stream.extend(match_arm); } } }