| 1 | use std::fmt::Display; |
| 2 | |
| 3 | use proc_macro2::Span; |
| 4 | use syn::Type; |
| 5 | |
| 6 | // https://stackoverflow.com/questions/55271857/how-can-i-get-the-t-from-an-optiont-when-using-syn |
| 7 | pub(crate) fn extract_type_from_option(ty: &Type) -> Option<Type> { |
| 8 | use syn::{GenericArgument, Path, PathArguments, PathSegment}; |
| 9 | |
| 10 | fn extract_type_path(ty: &Type) -> Option<&Path> { |
| 11 | match *ty { |
| 12 | Type::Path(ref typepath) if typepath.qself.is_none() => Some(&typepath.path), |
| 13 | _ => None, |
| 14 | } |
| 15 | } |
| 16 | |
| 17 | fn extract_option_segment(path: &Path) -> Option<&PathSegment> { |
| 18 | let idents_of_path = path.segments.iter().fold(String::new(), |mut acc, v| { |
| 19 | acc.push_str(&v.ident.to_string()); |
| 20 | acc.push('|'); |
| 21 | acc |
| 22 | }); |
| 23 | vec!["Option|", "std|option|Option|", "core|option|Option|"] |
| 24 | .into_iter() |
| 25 | .find(|s| idents_of_path == *s) |
| 26 | .and_then(|_| path.segments.last()) |
| 27 | } |
| 28 | |
| 29 | extract_type_path(ty) |
| 30 | .and_then(extract_option_segment) |
| 31 | .and_then(|path_seg| { |
| 32 | let type_params = &path_seg.arguments; |
| 33 | // It should have only on angle-bracketed param ("<String>"): |
| 34 | match *type_params { |
| 35 | PathArguments::AngleBracketed(ref params) => params.args.first(), |
| 36 | _ => None, |
| 37 | } |
| 38 | }) |
| 39 | .and_then(|generic_arg| match *generic_arg { |
| 40 | GenericArgument::Type(ref ty) => Some(ty.clone()), |
| 41 | _ => None, |
| 42 | }) |
| 43 | } |
| 44 | |
| 45 | pub(crate) fn err<T: Display>(span: Span, error: T) -> syn::Error { |
| 46 | syn::Error::new(span, error) |
| 47 | } |