| 1 | use quote::quote_spanned; |
| 2 | use syn::{parse_quote, punctuated::Punctuated, spanned::Spanned, GenericParam, Token}; |
| 3 | |
| 4 | /// Convert a function signature to a function call with the same arguments. |
| 5 | /// |
| 6 | /// Given `function(a: &str, b: usize)`, get `function(a, b)`. |
| 7 | pub fn signature_to_function_call(sig: &syn::Signature) -> syn::Result<syn::ExprCall> { |
| 8 | // Simply use the function ident as the function expression. |
| 9 | let funcexpr = syn::ExprPath { |
| 10 | attrs: Vec::new(), |
| 11 | qself: None, |
| 12 | path: sig.ident.clone().into(), |
| 13 | }; |
| 14 | |
| 15 | // Extract arguments from the method signature names |
| 16 | let mut funcargs = Punctuated::new(); |
| 17 | for item in &sig.inputs { |
| 18 | match item { |
| 19 | syn::FnArg::Receiver(recv) => { |
| 20 | let span = recv.self_token.span; |
| 21 | funcargs.push(syn::parse2(quote_spanned!(span=> self))?); |
| 22 | } |
| 23 | syn::FnArg::Typed(argty) => { |
| 24 | if let syn::Pat::Ident(ref id) = *argty.pat { |
| 25 | let argpath = syn::ExprPath { |
| 26 | attrs: Vec::new(), |
| 27 | qself: None, |
| 28 | path: id.ident.clone().into(), |
| 29 | }; |
| 30 | funcargs.push(syn::Expr::Path(argpath)); |
| 31 | } else { |
| 32 | return Err(syn::Error::new(argty.span(), "expected identifier")); |
| 33 | } |
| 34 | } |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | // Return the function call as an expression |
| 39 | Ok(syn::ExprCall { |
| 40 | attrs: Vec::new(), |
| 41 | paren_token: syn::token::Paren::default(), |
| 42 | func: Box::new(funcexpr.into()), |
| 43 | args: funcargs, |
| 44 | }) |
| 45 | } |
| 46 | |
| 47 | /// Convert a function signature to a static method call with the same arguments. |
| 48 | /// |
| 49 | /// The call need to be modified to use a fully qualified path to qualify the |
| 50 | /// method, otherwise it may conflict with other methods in the namespace. |
| 51 | pub fn signature_to_associated_function_call( |
| 52 | sig: &syn::Signature, |
| 53 | trait_ident: &syn::Ident, |
| 54 | generic_type: &syn::Ident, |
| 55 | trait_generic_names: &syn::Generics, |
| 56 | ) -> syn::Result<syn::ExprCall> { |
| 57 | let mut call = signature_to_function_call(sig)?; |
| 58 | if let syn::Expr::Path(ref mut exprpath) = call.func.as_mut() { |
| 59 | let span = generic_type.span(); |
| 60 | exprpath.qself = Some(syn::QSelf { |
| 61 | lt_token: Token, |
| 62 | ty: Box::new(parse_quote!(#generic_type)), |
| 63 | position: 1, |
| 64 | as_token: Some(Token), |
| 65 | gt_token: Token, |
| 66 | }); |
| 67 | |
| 68 | let path_arguments = if trait_generic_names.params.is_empty() { |
| 69 | syn::PathArguments::None |
| 70 | } else { |
| 71 | syn::PathArguments::AngleBracketed(parse_quote!(#trait_generic_names)) |
| 72 | }; |
| 73 | |
| 74 | exprpath.path.segments.insert( |
| 75 | 0, |
| 76 | syn::PathSegment { |
| 77 | ident: trait_ident.clone(), |
| 78 | arguments: path_arguments, |
| 79 | }, |
| 80 | ); |
| 81 | } |
| 82 | Ok(call) |
| 83 | } |
| 84 | |
| 85 | /// Convert a function signature to a method call with the same arguments. |
| 86 | /// |
| 87 | /// Given `fn function(&self, a: &str, b: usize)`, get `self.function(a, b)`. |
| 88 | pub fn signature_to_method_call(sig: &syn::Signature) -> syn::Result<syn::ExprMethodCall> { |
| 89 | // Extract receiver |
| 90 | let receiver = sig.receiver().expect("method has no receiver"); |
| 91 | let span = receiver.span(); |
| 92 | |
| 93 | // Extract arguments |
| 94 | let mut funcargs = Punctuated::new(); |
| 95 | for item in &sig.inputs { |
| 96 | match item { |
| 97 | syn::FnArg::Receiver(_) => {} |
| 98 | syn::FnArg::Typed(argty) => { |
| 99 | if let syn::Pat::Ident(ref id) = *argty.pat { |
| 100 | let argpath = syn::ExprPath { |
| 101 | attrs: Vec::new(), |
| 102 | qself: None, |
| 103 | path: id.ident.clone().into(), |
| 104 | }; |
| 105 | funcargs.push(syn::Expr::Path(argpath)); |
| 106 | } else { |
| 107 | return Err(syn::Error::new(argty.span(), "expected identifier")); |
| 108 | } |
| 109 | } |
| 110 | } |
| 111 | } |
| 112 | |
| 113 | // Write the method call |
| 114 | Ok(syn::ExprMethodCall { |
| 115 | attrs: Vec::new(), |
| 116 | receiver: Box::new(syn::parse2(quote_spanned!(span=> self))?), |
| 117 | dot_token: syn::token::Dot { |
| 118 | spans: [sig.span()], |
| 119 | }, |
| 120 | method: sig.ident.clone(), |
| 121 | turbofish: None, |
| 122 | paren_token: syn::token::Paren::default(), |
| 123 | args: funcargs, |
| 124 | }) |
| 125 | } |
| 126 | |
| 127 | /// Prepend a module path to a function call name. |
| 128 | pub fn prepend_function_path(call: &mut syn::ExprCall, module: syn::Path) -> syn::Result<()> { |
| 129 | if let syn::Expr::Path(ref mut path) = *call.func { |
| 130 | for (i, segment) in module.segments.into_iter().enumerate() { |
| 131 | path.path.segments.insert(i, segment); |
| 132 | } |
| 133 | Ok(()) |
| 134 | } else { |
| 135 | Err(syn::Error::new(call.func.span(), "expected path")) |
| 136 | } |
| 137 | } |
| 138 | |
| 139 | /// Deref an expression and wrap it in brackets to preserve operation priority. |
| 140 | pub fn deref_expr(expr: syn::Expr) -> syn::Expr { |
| 141 | syn::Expr::Paren(syn::ExprParen { |
| 142 | attrs: Vec::new(), |
| 143 | paren_token: syn::token::Paren::default(), |
| 144 | expr: Box::new(syn::Expr::Unary(syn::ExprUnary { |
| 145 | attrs: Vec::new(), |
| 146 | op: syn::UnOp::Deref(parse_quote!(*)), |
| 147 | expr: Box::new(expr), |
| 148 | })), |
| 149 | }) |
| 150 | } |
| 151 | |
| 152 | /// Build a generic identifier suitable for the given trait. |
| 153 | /// |
| 154 | /// This function extracts the initials of the trait identifier. If this results |
| 155 | /// in a generic type identifier already present in the generics of that trait, |
| 156 | /// as many underscores are added to the end of the identifier. |
| 157 | /// |
| 158 | /// Given a trait `MyAmazingTrait`, get `MAT`. |
| 159 | pub fn trait_to_generic_ident(trait_: &syn::ItemTrait) -> syn::Ident { |
| 160 | let mut raw = trait_ |
| 161 | .ident |
| 162 | .to_string() |
| 163 | .chars() |
| 164 | .filter(|c| c.is_uppercase()) |
| 165 | .collect::<String>(); |
| 166 | loop { |
| 167 | if !trait_.generics.params.iter().any(|g| match g { |
| 168 | syn::GenericParam::Type(param) if param.ident == raw => true, |
| 169 | syn::GenericParam::Const(param) if param.ident == raw => true, |
| 170 | _ => false, |
| 171 | }) { |
| 172 | break; |
| 173 | } else { |
| 174 | raw.push('_'); |
| 175 | } |
| 176 | } |
| 177 | |
| 178 | syn::Ident::new(&raw, trait_.ident.span()) |
| 179 | } |
| 180 | |
| 181 | /// Convert a generic type declaration to a generic with the same arguments. |
| 182 | /// |
| 183 | /// Given a generic section `<T: 'static + Send>`, get simply `<T>`. |
| 184 | pub fn generics_declaration_to_generics( |
| 185 | generics: &Punctuated<GenericParam, Token![,]>, |
| 186 | ) -> syn::Result<Punctuated<GenericParam, Token![,]>> { |
| 187 | generics |
| 188 | .iter() |
| 189 | .map(|gen| match gen { |
| 190 | syn::GenericParam::Type(t) => Ok(syn::GenericParam::Type(syn::TypeParam { |
| 191 | attrs: t.attrs.clone(), |
| 192 | ident: t.ident.clone(), |
| 193 | colon_token: None, |
| 194 | bounds: Punctuated::new(), |
| 195 | eq_token: None, |
| 196 | default: None, |
| 197 | })), |
| 198 | syn::GenericParam::Lifetime(l) => Ok(syn::GenericParam::Lifetime(syn::LifetimeParam { |
| 199 | attrs: l.attrs.clone(), |
| 200 | lifetime: l.lifetime.clone(), |
| 201 | colon_token: None, |
| 202 | bounds: Punctuated::new(), |
| 203 | })), |
| 204 | syn::GenericParam::Const(c) => { |
| 205 | Err(syn::Error::new(c.span(), "cannot handle const generics")) |
| 206 | } |
| 207 | }) |
| 208 | .collect() |
| 209 | } |
| 210 | |
| 211 | #[cfg(test)] |
| 212 | mod tests { |
| 213 | |
| 214 | use syn::parse_quote; |
| 215 | |
| 216 | #[test] |
| 217 | fn prepend_function_path() { |
| 218 | let path = parse_quote!(crate::qualified::path); |
| 219 | let mut call = parse_quote!(myfunction(arg1, arg2)); |
| 220 | super::prepend_function_path(&mut call, path).unwrap(); |
| 221 | assert_eq!( |
| 222 | call, |
| 223 | parse_quote!(crate::qualified::path::myfunction(arg1, arg2)) |
| 224 | ); |
| 225 | } |
| 226 | |
| 227 | #[test] |
| 228 | fn deref_expr() { |
| 229 | let expr = parse_quote!(self); |
| 230 | let dereffed = super::deref_expr(expr); |
| 231 | assert_eq!(dereffed, parse_quote!((*self))); |
| 232 | } |
| 233 | |
| 234 | #[test] |
| 235 | fn trait_to_generic_ident() { |
| 236 | let trait_ = syn::parse_quote!( |
| 237 | trait Trait {} |
| 238 | ); |
| 239 | let expected: syn::Ident = syn::parse_quote!(T); |
| 240 | assert_eq!(super::trait_to_generic_ident(&trait_), expected); |
| 241 | |
| 242 | let trait_ = syn::parse_quote!( |
| 243 | trait SomeTrait {} |
| 244 | ); |
| 245 | let expected: syn::Ident = syn::parse_quote!(ST); |
| 246 | assert_eq!(super::trait_to_generic_ident(&trait_), expected); |
| 247 | |
| 248 | let trait_ = syn::parse_quote!( |
| 249 | trait Trait<T> {} |
| 250 | ); |
| 251 | let expected: syn::Ident = syn::parse_quote!(T_); |
| 252 | assert_eq!(super::trait_to_generic_ident(&trait_), expected); |
| 253 | } |
| 254 | } |