#![recursion_limit = "128"] 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;
#[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<T> = std::result::Result<T, Vec<syn::Error>>;
type UserInput = Box<dyn quote::ToTokens>;
enum SnafuInfo {
Enum(EnumInfo),
NamedStruct(NamedStructInfo),
TupleStruct(TupleStructInfo),
}
struct EnumInfo {
crate_root: UserInput,
name: syn::Ident,
generics: syn::Generics,
variants: Vec<FieldContainer>,
default_visibility: UserInput,
}
struct FieldContainer {
name: syn::Ident,
backtrace_field: Option<Field>,
selector_kind: ContextSelectorKind,
display_format: Option<UserInput>,
doc_comment: String,
visibility: Option<UserInput>,
}
enum ContextSelectorKind {
Context {
source_field: Option<SourceField>,
user_fields: Vec<Field>,
},
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 },
}
}
}
#[derive(Debug, Default)]
struct SyntaxErrors {
inner: Vec<syn::Error>,
}
impl SyntaxErrors {
fn scoped(&mut self, scope: ErrorLocation) -> SyntaxErrorsScoped<'_> {
SyntaxErrorsScoped {
errors: self,
scope,
}
}
fn add(&mut self, tokens: impl quote::ToTokens, description: impl fmt::Display) {
self.inner
.push(syn::Error::new_spanned(tokens, description));
}
fn extend(&mut self, errors: impl IntoIterator<Item = syn::Error>) {
self.inner.extend(errors);
}
#[allow(dead_code)]
fn len(&self) -> usize {
self.inner.len()
}
fn finish(self) -> MultiSynResult<()> {
if self.inner.is_empty() {
Ok(())
} else {
Err(self.inner)
}
}
fn absorb<T>(mut self, res: MultiSynResult<T>) -> MultiSynResult<T> {
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<'_> {
fn add(&mut self, tokens: impl quote::ToTokens, description: impl ErrorForLocation) {
let description = description.for_location(self.scope);
self.errors.add(tokens, description)
}
}
#[derive(Debug)]
struct OnlyValidOn {
attribute: &'static str,
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,
)
}
}
#[derive(Debug)]
struct WrongField {
attribute: &'static str,
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,
)
}
}
#[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::<Vec<_>>()
.join(", ");
format!(
"Incompatible attributes [{}] specified {}",
attrs_string, location,
)
}
}
#[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,
)
}
}
#[derive(Debug)]
struct AtMostOne<T, U>
where
U: quote::ToTokens,
{
name: &'static str,
location: ErrorLocation,
values: VecDeque<(T, U)>,
errors: SyntaxErrors,
}
impl<T, U> AtMostOne<T, U>
where
U: quote::ToTokens + Clone,
{
fn new(name: &'static str, location: ErrorLocation) -> Self {
Self {
name,
location,
values: VecDeque::new(),
errors: SyntaxErrors::default(),
}
}
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)]
fn len(&self) -> usize {
self.values.len()
}
#[allow(dead_code)]
fn is_empty(&self) -> bool {
self.values.is_empty()
}
fn iter(&self) -> std::collections::vec_deque::Iter<(T, U)> {
self.values.iter()
}
fn finish(self) -> (Option<T>, Vec<syn::Error>) {
let (value, errors) = self.finish_with_location();
(value.map(|(val, _location)| val), errors)
}
fn finish_with_location(mut self) -> (Option<(T, U)>, Vec<syn::Error>) {
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<syn::Error>) -> 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<SnafuInfo> {
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<syn::Attribute>,
) -> MultiSynResult<EnumInfo> {
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(..) => { }
}
}
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<SnafuAttribute>,
fields: Vec<syn::Field>,
errors: &mut SyntaxErrors,
outer_error_location: ErrorLocation,
inner_error_location: ErrorLocation,
) -> MultiSynResult<FieldContainer> {
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) => {
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,
};
let mut source_attrs = AtMostOne::new("source", ErrorLocation::OnField);
let mut backtrace_attrs = AtMostOne::new("backtrace", ErrorLocation::OnField);
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) => {
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(..) => { }
}
}
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,
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",
);
}
_ => {} }
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<syn::Attribute>,
span: proc_macro2::Span,
) -> MultiSynResult<SnafuInfo> {
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<syn::Field>,
name: syn::Ident,
generics: syn::Generics,
attrs: Vec<syn::Attribute>,
span: proc_macro2::Span,
) -> MultiSynResult<NamedStructInfo> {
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<syn::Attribute>,
span: proc_macro2::Span,
) -> MultiSynResult<TupleStructInfo> {
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(..) => { }
}
}
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<T> {
CompatParen(T),
CompatDirect(T),
Pretty(T),
None,
}
impl<T> MyMeta<T> {
fn into_option(self) -> Option<T> {
match self {
MyMeta::CompatParen(v) => Some(v),
MyMeta::CompatDirect(v) => Some(v),
MyMeta::Pretty(v) => Some(v),
MyMeta::None => None,
}
}
}
impl<T> syn::parse::Parse for MyMeta<T>
where
T: syn::parse::Parse,
{
fn parse(input: syn::parse::ParseStream) -> SynResult<Self> {
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::<MyParens<T>>() {
Ok(t) => Ok(MyMeta::CompatParen(t.0)),
Err(_) => match s.parse::<T>() {
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>(T);
impl<T> syn::parse::Parse for MyParens<T>
where
T: syn::parse::Parse,
{
fn parse(input: syn::parse::ParseStream) -> SynResult<Self> {
let inside;
parenthesized!(inside in input);
inside.parse().map(MyParens)
}
}
struct List<T>(syn::punctuated::Punctuated<T, syn::token::Comma>);
impl<T> syn::parse::Parse for List<T>
where
T: syn::parse::Parse,
{
fn parse(input: syn::parse::ParseStream) -> SynResult<Self> {
use syn::punctuated::Punctuated;
let exprs = Punctuated::parse_terminated(input)?;
Ok(List(exprs))
}
}
impl<T> List<T> {
fn into_vec(self) -> Vec<T> {
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<Self> {
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())
}
}
}
struct Backtrace(bool);
impl syn::parse::Parse for Backtrace {
fn parse(input: syn::parse::ParseStream) -> SynResult<Self> {
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())
}
}
}
enum SnafuAttribute {
Display(proc_macro2::TokenStream, UserInput),
Visibility(proc_macro2::TokenStream, UserInput),
Source(proc_macro2::TokenStream, Vec<Source>),
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<Self> {
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<List<Expr>> = 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<Visibility> = 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<List<Source>> = 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<Backtrace> = 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<LitBool> = input.parse()?;
Ok(SnafuAttribute::Context(input_tts, v.0.value))
}
} else if name == "crate_root" {
let m: MyMeta<Path> = 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<SnafuAttribute>);
impl syn::parse::Parse for SnafuAttributeBody {
fn parse(input: syn::parse::ParseStream) -> SynResult<Self> {
use syn::punctuated::Punctuated;
use syn::token::Comma;
let inside;
parenthesized!(inside in input);
let parse_comma_list = Punctuated::<SnafuAttribute, Comma>::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<Self> {
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<syn::Attribute>) -> MultiSynResult<Vec<SnafuAttribute>> {
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::<SnafuAttributeBody>(attr.tokens).map(|body| body.0))
} else if attr.path.is_ident("doc") {
parse2::<DocComment>(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<SnafuInfo> 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<EnumInfo> for proc_macro::TokenStream {
fn from(other: EnumInfo) -> proc_macro::TokenStream {
other.generate_snafu().into()
}
}
impl From<NamedStructInfo> for proc_macro::TokenStream {
fn from(other: NamedStructInfo) -> proc_macro::TokenStream {
other.generate_snafu().into()
}
}
impl From<TupleStructInfo> 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<proc_macro2::TokenStream> {
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<proc_macro2::TokenStream> {
self.provided_generic_lifetimes()
.into_iter()
.chain(self.provided_generic_types_without_defaults().into_iter())
.collect()
}
fn provided_generic_lifetimes(&self) -> Vec<proc_macro2::TokenStream> {
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<proc_macro2::TokenStream> {
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<proc_macro2::TokenStream> {
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<T, E> {
fn my_transpose(self) -> Result<Option<T>, E>;
}
impl<T, E> Transpose<T, E> for Option<Result<T, E>> {
fn my_transpose(self) -> Result<Option<T>, 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<T, E>(Result<T, Vec<E>>);
impl<T, E> AllErrors<T, E> {
pub fn into_result(self) -> Result<T, Vec<E>> {
self.0
}
}
impl<C, T, E> FromIterator<Result<C, E>> for AllErrors<T, E>
where
T: FromIterator<C>,
{
fn from_iter<I>(i: I) -> Self
where
I: IntoIterator<Item = Result<C, E>>,
{
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<C, T, E> FromIterator<Result<C, Vec<E>>> for AllErrors<T, E>
where
T: FromIterator<C>,
{
fn from_iter<I>(i: I) -> Self
where
I: IntoIterator<Item = Result<C, Vec<E>>>,
{
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))
}
}
}
}