| 1 | use proc_macro2::{Delimiter, TokenStream, TokenTree}; |
| 2 | use quote::ToTokens; |
| 3 | use std::collections::VecDeque; |
| 4 | use std::ops::Not; |
| 5 | use syn::parse::ParseStream; |
| 6 | use syn::{Attribute, Error, Meta, Path, PathSegment, Token, TypePath}; |
| 7 | |
| 8 | pub struct CallMethodAttribute { |
| 9 | name: syn::Ident, |
| 10 | } |
| 11 | |
| 12 | impl syn::parse::Parse for CallMethodAttribute { |
| 13 | fn parse(input: ParseStream) -> Result<Self, Error> { |
| 14 | Ok(CallMethodAttribute { |
| 15 | name: input.parse()?, |
| 16 | }) |
| 17 | } |
| 18 | } |
| 19 | |
| 20 | #[derive(Default, Clone)] |
| 21 | pub struct GetFieldAttribute { |
| 22 | reference: Option<(Token![&], Option<Token![mut]>)>, |
| 23 | member: Option<syn::Member>, |
| 24 | } |
| 25 | |
| 26 | impl GetFieldAttribute { |
| 27 | pub fn reference_tokens(&self) -> Option<TokenStream> { |
| 28 | let (ref_, mut_) = self.reference.as_ref()?; |
| 29 | let mut tokens = ref_.to_token_stream(); |
| 30 | mut_.to_tokens(&mut tokens); |
| 31 | Some(tokens) |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | impl syn::parse::Parse for GetFieldAttribute { |
| 36 | fn parse(input: ParseStream) -> Result<Self, Error> { |
| 37 | let mut reference = None; |
| 38 | if let Ok(ref_) = input.parse::<syn::Token![&]>() { |
| 39 | reference = Some((ref_, None)); |
| 40 | } |
| 41 | if let Some((_, mut_)) = &mut reference { |
| 42 | *mut_ = input.parse::<syn::Token![mut]>().ok(); |
| 43 | } |
| 44 | let member = input.is_empty().not().then(|| input.parse()).transpose()?; |
| 45 | Ok(GetFieldAttribute { reference, member }) |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | struct GenerateAwaitAttribute { |
| 50 | literal: syn::LitBool, |
| 51 | } |
| 52 | |
| 53 | impl syn::parse::Parse for GenerateAwaitAttribute { |
| 54 | fn parse(input: ParseStream) -> Result<Self, Error> { |
| 55 | Ok(GenerateAwaitAttribute { |
| 56 | literal: input.parse()?, |
| 57 | }) |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | struct IntoAttribute { |
| 62 | type_path: Option<TypePath>, |
| 63 | } |
| 64 | |
| 65 | impl syn::parse::Parse for IntoAttribute { |
| 66 | fn parse(input: ParseStream) -> Result<Self, Error> { |
| 67 | let type_path: TypePath = input.parse().map_err(|error| { |
| 68 | Error::new( |
| 69 | input.span(), |
| 70 | format!("{error}\nExpected type name, e.g. #[into(u32)]"), |
| 71 | ) |
| 72 | })?; |
| 73 | |
| 74 | Ok(IntoAttribute { |
| 75 | type_path: Some(type_path), |
| 76 | }) |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | pub struct AssociatedConstant { |
| 81 | pub const_name: PathSegment, |
| 82 | pub trait_path: Path, |
| 83 | } |
| 84 | |
| 85 | impl syn::parse::Parse for AssociatedConstant { |
| 86 | fn parse(input: ParseStream) -> Result<Self, Error> { |
| 87 | let mut path = input.parse::<syn::Path>().map_err(|error| { |
| 88 | Error::new( |
| 89 | input.span(), |
| 90 | format!( |
| 91 | "{error}\nExpected const path, e.g. #[const(path::to::MyTrait::CONST_NAME)]" |
| 92 | ), |
| 93 | ) |
| 94 | })?; |
| 95 | |
| 96 | let const_name = path.segments.pop().ok_or_else(|| { |
| 97 | Error::new_spanned( |
| 98 | &path, |
| 99 | "Expected a path. e.g. #[const(path::to::MyTrait::CONST_NAME)]", |
| 100 | ) |
| 101 | })?; |
| 102 | // poping a segment leads to trailing `::` |
| 103 | path.segments.pop_punct().ok_or_else(|| { |
| 104 | Error::new_spanned( |
| 105 | &path, |
| 106 | "Expected a multipart path. e.g. #[const(path::to::MyTrait::CONST_NAME)]", |
| 107 | ) |
| 108 | })?; |
| 109 | |
| 110 | Ok(Self { |
| 111 | const_name: const_name.into_value(), |
| 112 | trait_path: path, |
| 113 | }) |
| 114 | } |
| 115 | } |
| 116 | |
| 117 | #[derive(Clone)] |
| 118 | /// Represent the placeholder `$` found inside an expr attribute's template |
| 119 | pub struct ExprPlaceHolder; |
| 120 | |
| 121 | impl syn::parse::Parse for ExprPlaceHolder { |
| 122 | fn parse(input: ParseStream) -> syn::Result<Self> { |
| 123 | input.parse::<syn::Token![$]>()?; |
| 124 | Ok(Self) |
| 125 | } |
| 126 | } |
| 127 | |
| 128 | /// Kind of allowed placeholders in an `expr` attribute template |
| 129 | #[derive(Clone)] |
| 130 | enum Placeholder { |
| 131 | ExprPlaceholder(ExprPlaceHolder), |
| 132 | } |
| 133 | |
| 134 | #[derive(Clone)] |
| 135 | /// Tokens found in the expr attribute's template |
| 136 | /// Token are either |
| 137 | /// - a replacable pattern (placeholder) |
| 138 | /// - a normal token |
| 139 | /// - a group containing a recursive representation of template tokens |
| 140 | enum TemplateToken { |
| 141 | Normal(TokenTree), |
| 142 | Placeholder(Placeholder), |
| 143 | Group(Delimiter, TemplateExpr), |
| 144 | } |
| 145 | |
| 146 | impl TemplateToken { |
| 147 | /// Replace relevant placeholder tokens with the provided tokens |
| 148 | fn replace(&self, replacement: &TokenStream) -> TokenStream { |
| 149 | match self { |
| 150 | Self::Group(del, template) => { |
| 151 | let replaced_tokens = template |
| 152 | .tokens |
| 153 | .iter() |
| 154 | .map(|token| token.replace(replacement)); |
| 155 | proc_macro2::Group::new(*del, quote::quote! { #(#replaced_tokens)* }) |
| 156 | .to_token_stream() |
| 157 | } |
| 158 | Self::Normal(token_tree) => token_tree.to_token_stream(), |
| 159 | Self::Placeholder(_) => replacement.clone(), |
| 160 | } |
| 161 | } |
| 162 | } |
| 163 | |
| 164 | #[derive(Clone)] |
| 165 | /// An expr attribute's template |
| 166 | pub struct TemplateExpr { |
| 167 | tokens: Vec<TemplateToken>, |
| 168 | } |
| 169 | |
| 170 | impl syn::parse::Parse for TemplateExpr { |
| 171 | /// Parsing a template means storing the raw template while differenciating |
| 172 | /// placeholders and "normal" tokens |
| 173 | fn parse(input: ParseStream) -> syn::Result<Self> { |
| 174 | let mut tokens = Vec::new(); |
| 175 | while !input.is_empty() { |
| 176 | if input.fork().parse::<ExprPlaceHolder>().is_ok() { |
| 177 | let placeholder = input.parse()?; |
| 178 | tokens.push(TemplateToken::Placeholder(Placeholder::ExprPlaceholder( |
| 179 | placeholder, |
| 180 | ))); |
| 181 | continue; |
| 182 | } |
| 183 | |
| 184 | match input.parse()? { |
| 185 | TokenTree::Group(group) => { |
| 186 | let inner_stream = group.stream(); |
| 187 | let inner_expr = syn::parse2(inner_stream)?; |
| 188 | tokens.push(TemplateToken::Group(group.delimiter(), inner_expr)); |
| 189 | } |
| 190 | other => { |
| 191 | tokens.push(TemplateToken::Normal(other)); |
| 192 | } |
| 193 | } |
| 194 | } |
| 195 | |
| 196 | Ok(TemplateExpr { tokens }) |
| 197 | } |
| 198 | } |
| 199 | |
| 200 | impl TemplateExpr { |
| 201 | /// returns the template after expanding the relevant placeholders |
| 202 | pub fn expand_template(&self, replacement: &TokenStream) -> TokenStream { |
| 203 | self.tokens.iter().fold(TokenStream::new(), |mut ts, tok| { |
| 204 | ts.extend(tok.replace(replacement)); |
| 205 | ts |
| 206 | }) |
| 207 | } |
| 208 | } |
| 209 | |
| 210 | pub struct TraitTarget { |
| 211 | type_path: TypePath, |
| 212 | } |
| 213 | |
| 214 | impl syn::parse::Parse for TraitTarget { |
| 215 | fn parse(input: ParseStream) -> Result<Self, Error> { |
| 216 | let type_path: TypePath = input.parse().map_err(|error| { |
| 217 | Error::new( |
| 218 | input.span(), |
| 219 | format!("{error}\nExpected trait path, e.g. #[through(foo::MyTrait)]"), |
| 220 | ) |
| 221 | })?; |
| 222 | |
| 223 | Ok(TraitTarget { type_path }) |
| 224 | } |
| 225 | } |
| 226 | |
| 227 | #[derive(Clone)] |
| 228 | pub enum ReturnExpression { |
| 229 | Into(Option<TypePath>), |
| 230 | TryInto, |
| 231 | Unwrap, |
| 232 | } |
| 233 | |
| 234 | pub enum TargetSpecifier { |
| 235 | Field(GetFieldAttribute), |
| 236 | Method(CallMethodAttribute), |
| 237 | } |
| 238 | |
| 239 | impl TargetSpecifier { |
| 240 | pub fn get_member(&self, default: &syn::Ident) -> syn::Member { |
| 241 | match self { |
| 242 | Self::Field(GetFieldAttribute { |
| 243 | member: Some(member), |
| 244 | .. |
| 245 | }) => member.clone(), |
| 246 | Self::Field(_) => default.clone().into(), |
| 247 | Self::Method(method) => method.name.clone().into(), |
| 248 | } |
| 249 | } |
| 250 | } |
| 251 | |
| 252 | enum ParsedAttribute { |
| 253 | ReturnExpression(ReturnExpression), |
| 254 | Await(bool), |
| 255 | TargetSpecifier(TargetSpecifier), |
| 256 | ThroughTrait(TraitTarget), |
| 257 | ConstantAccess(AssociatedConstant), |
| 258 | Expr(TemplateExpr), |
| 259 | } |
| 260 | |
| 261 | fn parse_attributes( |
| 262 | attrs: &[Attribute], |
| 263 | ) -> ( |
| 264 | impl Iterator<Item = ParsedAttribute> + '_, |
| 265 | impl Iterator<Item = &Attribute>, |
| 266 | ) { |
| 267 | let (parsed, other): (Vec<_>, Vec<_>) = attrs |
| 268 | .iter() |
| 269 | .map(|attribute| { |
| 270 | let parsed = if let syn::AttrStyle::Outer = attribute.style { |
| 271 | let name = attribute |
| 272 | .path() |
| 273 | .get_ident() |
| 274 | .map(|i| i.to_string()) |
| 275 | .unwrap_or_default(); |
| 276 | match name.as_str() { |
| 277 | "call" => { |
| 278 | let target = attribute |
| 279 | .parse_args::<CallMethodAttribute>() |
| 280 | .expect("Cannot parse `call` attribute"); |
| 281 | let spec = TargetSpecifier::Method(target); |
| 282 | Some(ParsedAttribute::TargetSpecifier(spec)) |
| 283 | } |
| 284 | "field" => { |
| 285 | let target = if let syn::Meta::Path(_) = &attribute.meta { |
| 286 | GetFieldAttribute::default() |
| 287 | } else { |
| 288 | attribute |
| 289 | .parse_args::<GetFieldAttribute>() |
| 290 | .expect("Cannot parse `field` attribute") |
| 291 | }; |
| 292 | let spec = TargetSpecifier::Field(target); |
| 293 | Some(ParsedAttribute::TargetSpecifier(spec)) |
| 294 | } |
| 295 | "into" => { |
| 296 | let into = match &attribute.meta { |
| 297 | Meta::NameValue(_) => { |
| 298 | panic!("Cannot parse `into` attribute: expected parentheses") |
| 299 | } |
| 300 | Meta::Path(_) => IntoAttribute { type_path: None }, |
| 301 | Meta::List(meta) => meta |
| 302 | .parse_args::<IntoAttribute>() |
| 303 | .expect("Cannot parse `into` attribute"), |
| 304 | }; |
| 305 | Some(ParsedAttribute::ReturnExpression(ReturnExpression::Into( |
| 306 | into.type_path, |
| 307 | ))) |
| 308 | } |
| 309 | "try_into" => { |
| 310 | if let Meta::List(meta) = &attribute.meta { |
| 311 | meta.parse_nested_meta(|meta| { |
| 312 | if meta.path.is_ident("unwrap") { |
| 313 | panic!( |
| 314 | "Replace #[try_into(unwrap)] with\n#[try_into]\n#[unwrap]", |
| 315 | ); |
| 316 | } |
| 317 | Ok(()) |
| 318 | }) |
| 319 | .expect("Invalid `try_into` arguments"); |
| 320 | } |
| 321 | Some(ParsedAttribute::ReturnExpression(ReturnExpression::TryInto)) |
| 322 | } |
| 323 | "unwrap" => Some(ParsedAttribute::ReturnExpression(ReturnExpression::Unwrap)), |
| 324 | "await" => { |
| 325 | let generate = attribute |
| 326 | .parse_args::<GenerateAwaitAttribute>() |
| 327 | .expect("Cannot parse `await` attribute"); |
| 328 | Some(ParsedAttribute::Await(generate.literal.value)) |
| 329 | } |
| 330 | "through" => Some(ParsedAttribute::ThroughTrait( |
| 331 | attribute |
| 332 | .parse_args::<TraitTarget>() |
| 333 | .expect("Cannot parse `through` attribute"), |
| 334 | )), |
| 335 | "const" => Some(ParsedAttribute::ConstantAccess( |
| 336 | attribute |
| 337 | .parse_args::<AssociatedConstant>() |
| 338 | .expect("Cannot parse `const` attribute"), |
| 339 | )), |
| 340 | "expr" => Some(ParsedAttribute::Expr( |
| 341 | attribute |
| 342 | .parse_args::<TemplateExpr>() |
| 343 | .expect("Cannot parse `expr` attribute"), |
| 344 | )), |
| 345 | _ => None, |
| 346 | } |
| 347 | } else { |
| 348 | None |
| 349 | }; |
| 350 | |
| 351 | (parsed, attribute) |
| 352 | }) |
| 353 | .partition(|(parsed, _)| parsed.is_some()); |
| 354 | ( |
| 355 | parsed.into_iter().map(|(parsed, _)| parsed.unwrap()), |
| 356 | other.into_iter().map(|(_, attr)| attr), |
| 357 | ) |
| 358 | } |
| 359 | |
| 360 | pub struct MethodAttributes<'a> { |
| 361 | pub attributes: Vec<&'a Attribute>, |
| 362 | pub target_specifier: Option<TargetSpecifier>, |
| 363 | pub expressions: VecDeque<ReturnExpression>, |
| 364 | pub generate_await: Option<bool>, |
| 365 | pub target_trait: Option<TypePath>, |
| 366 | pub associated_constant: Option<AssociatedConstant>, |
| 367 | pub expr_attr: Option<TemplateExpr>, |
| 368 | } |
| 369 | |
| 370 | /// Iterates through the attributes of a method and filters special attributes. |
| 371 | /// - call => sets the name of the target method to call |
| 372 | /// - into => generates a `into()` call after the delegated expression |
| 373 | /// - try_into => generates a `try_into()` call after the delegated expression |
| 374 | /// - await => generates an `.await` expression after the delegated expression |
| 375 | /// - unwrap => generates a `unwrap()` call after the delegated expression |
| 376 | /// - through => generates a UFCS call (`Target::method(&<expr>, ...)`) around the delegated expression |
| 377 | /// - const => generates a getter to a trait associated constant |
| 378 | pub fn parse_method_attributes<'a>( |
| 379 | attrs: &'a [Attribute], |
| 380 | method: &syn::TraitItemFn, |
| 381 | ) -> MethodAttributes<'a> { |
| 382 | let mut target_spec: Option<TargetSpecifier> = None; |
| 383 | let mut expressions: Vec<ReturnExpression> = vec![]; |
| 384 | let mut generate_await: Option<bool> = None; |
| 385 | let mut target_trait: Option<TraitTarget> = None; |
| 386 | let mut associated_constant: Option<AssociatedConstant> = None; |
| 387 | let mut expr_attr: Option<TemplateExpr> = None; |
| 388 | |
| 389 | let (parsed, other) = parse_attributes(attrs); |
| 390 | for attr in parsed { |
| 391 | match attr { |
| 392 | ParsedAttribute::ReturnExpression(expr) => expressions.push(expr), |
| 393 | ParsedAttribute::Await(value) => { |
| 394 | if generate_await.is_some() { |
| 395 | panic!( |
| 396 | "Multiple `await` attributes specified for {}", |
| 397 | method.sig.ident |
| 398 | ) |
| 399 | } |
| 400 | generate_await = Some(value); |
| 401 | } |
| 402 | ParsedAttribute::TargetSpecifier(spec) => { |
| 403 | if target_spec.is_some() { |
| 404 | panic!( |
| 405 | "Multiple field/call attributes specified for {}", |
| 406 | method.sig.ident |
| 407 | ) |
| 408 | } |
| 409 | target_spec = Some(spec); |
| 410 | } |
| 411 | ParsedAttribute::ThroughTrait(target) => { |
| 412 | if target_trait.is_some() { |
| 413 | panic!( |
| 414 | "Multiple through attributes specified for {}", |
| 415 | method.sig.ident |
| 416 | ) |
| 417 | } |
| 418 | target_trait = Some(target); |
| 419 | } |
| 420 | ParsedAttribute::ConstantAccess(const_attr) => { |
| 421 | if associated_constant.is_some() { |
| 422 | panic!( |
| 423 | "Multiple const attributes specified for {}", |
| 424 | method.sig.ident |
| 425 | ) |
| 426 | } |
| 427 | associated_constant = Some(const_attr); |
| 428 | } |
| 429 | ParsedAttribute::Expr(token_tree) => { |
| 430 | if expr_attr.is_some() { |
| 431 | panic!( |
| 432 | "Multiple expr attributes specified for {}", |
| 433 | method.sig.ident |
| 434 | ) |
| 435 | } |
| 436 | expr_attr = Some(token_tree); |
| 437 | } |
| 438 | } |
| 439 | } |
| 440 | |
| 441 | if associated_constant.is_some() && target_spec.is_some() { |
| 442 | panic!("Cannot use both `call`/`field` and `const` attributes."); |
| 443 | } |
| 444 | |
| 445 | MethodAttributes { |
| 446 | attributes: other.into_iter().collect(), |
| 447 | target_specifier: target_spec, |
| 448 | generate_await, |
| 449 | expressions: expressions.into(), |
| 450 | target_trait: target_trait.map(|t| t.type_path), |
| 451 | associated_constant, |
| 452 | expr_attr, |
| 453 | } |
| 454 | } |
| 455 | |
| 456 | pub struct SegmentAttributes { |
| 457 | pub expressions: Vec<ReturnExpression>, |
| 458 | pub generate_await: Option<bool>, |
| 459 | pub target_trait: Option<TypePath>, |
| 460 | pub other_attrs: Vec<Attribute>, |
| 461 | pub expr_attr: Option<TemplateExpr>, |
| 462 | } |
| 463 | |
| 464 | pub fn parse_segment_attributes(attrs: &[Attribute]) -> SegmentAttributes { |
| 465 | let mut expressions: Vec<ReturnExpression> = vec![]; |
| 466 | let mut generate_await: Option<bool> = None; |
| 467 | let mut target_trait: Option<TraitTarget> = None; |
| 468 | let mut expr_attr: Option<TemplateExpr> = None; |
| 469 | |
| 470 | let (parsed, other) = parse_attributes(attrs); |
| 471 | |
| 472 | for attribute in parsed { |
| 473 | match attribute { |
| 474 | ParsedAttribute::ReturnExpression(expr) => expressions.push(expr), |
| 475 | ParsedAttribute::Await(value) => { |
| 476 | if generate_await.is_some() { |
| 477 | panic!("Multiple `await` attributes specified for segment"); |
| 478 | } |
| 479 | generate_await = Some(value); |
| 480 | } |
| 481 | ParsedAttribute::ThroughTrait(target) => { |
| 482 | if target_trait.is_some() { |
| 483 | panic!("Multiple `through` attributes specified for segment"); |
| 484 | } |
| 485 | target_trait = Some(target); |
| 486 | } |
| 487 | ParsedAttribute::TargetSpecifier(_) => { |
| 488 | panic!("Field/call attribute cannot be specified on a `to <expr>` segment."); |
| 489 | } |
| 490 | ParsedAttribute::ConstantAccess(_) => { |
| 491 | panic!("Const attribute cannot be specified on a `to <expr>` segment."); |
| 492 | } |
| 493 | ParsedAttribute::Expr(token_tree) => { |
| 494 | if expr_attr.is_some() { |
| 495 | panic!("Multiple `expr` attributes specified for segment"); |
| 496 | } |
| 497 | expr_attr = Some(token_tree); |
| 498 | } |
| 499 | } |
| 500 | } |
| 501 | SegmentAttributes { |
| 502 | expressions, |
| 503 | generate_await, |
| 504 | target_trait: target_trait.map(|t| t.type_path), |
| 505 | other_attrs: other.cloned().collect::<Vec<_>>(), |
| 506 | expr_attr, |
| 507 | } |
| 508 | } |
| 509 | |
| 510 | /// Applies default values from the segment and adds them to the method attributes. |
| 511 | pub fn combine_attributes<'a>( |
| 512 | mut method_attrs: MethodAttributes<'a>, |
| 513 | segment_attrs: &'a SegmentAttributes, |
| 514 | ) -> MethodAttributes<'a> { |
| 515 | let SegmentAttributes { |
| 516 | expressions, |
| 517 | generate_await, |
| 518 | target_trait, |
| 519 | other_attrs, |
| 520 | expr_attr, |
| 521 | } = segment_attrs; |
| 522 | |
| 523 | if method_attrs.generate_await.is_none() { |
| 524 | method_attrs.generate_await = *generate_await; |
| 525 | } |
| 526 | |
| 527 | if method_attrs.target_trait.is_none() { |
| 528 | method_attrs.target_trait.clone_from(target_trait); |
| 529 | } |
| 530 | |
| 531 | if method_attrs.expr_attr.is_none() { |
| 532 | method_attrs.expr_attr.clone_from(expr_attr); |
| 533 | } |
| 534 | |
| 535 | for expr in expressions { |
| 536 | match expr { |
| 537 | ReturnExpression::Into(path) => { |
| 538 | if !method_attrs |
| 539 | .expressions |
| 540 | .iter() |
| 541 | .any(|expr| matches!(expr, ReturnExpression::Into(_))) |
| 542 | { |
| 543 | method_attrs |
| 544 | .expressions |
| 545 | .push_front(ReturnExpression::Into(path.clone())); |
| 546 | } |
| 547 | } |
| 548 | _ => method_attrs.expressions.push_front(expr.clone()), |
| 549 | } |
| 550 | } |
| 551 | |
| 552 | for other_attr in other_attrs { |
| 553 | if !method_attrs |
| 554 | .attributes |
| 555 | .iter() |
| 556 | .any(|attr| attr.path().get_ident() == other_attr.path().get_ident()) |
| 557 | { |
| 558 | method_attrs.attributes.push(other_attr); |
| 559 | } |
| 560 | } |
| 561 | |
| 562 | method_attrs |
| 563 | } |