Debian Codegraph @

src/lib.rs

raw symbols SCIP
1 //! This crate removes some boilerplate for structs that simply delegate
2 //! some of their methods to one or more of their fields.
3 //!
4 //! It gives you the `delegate!` macro, which delegates method calls to selected expressions (usually inner fields).
5 //!
6 //! ## Features:
7 //! - Delegate to a method with a different name
8 //! ```rust
9 //! use delegate::delegate;
10 //!
11 //! struct Stack { inner: Vec<u32> }
12 //! impl Stack {
13 //! delegate! {
14 //! to self.inner {
15 //! #[call(push)]
16 //! pub fn add(&mut self, value: u32);
17 //! }
18 //! }
19 //! }
20 //! ```
21 //! - Use an arbitrary inner field expression
22 //! ```rust
23 //! use delegate::delegate;
24 //!
25 //! use std::rc::Rc;
26 //! use std::cell::RefCell;
27 //! use std::ops::Deref;
28 //!
29 //! struct Wrapper { inner: Rc<RefCell<Vec<u32>>> }
30 //! impl Wrapper {
31 //! delegate! {
32 //! to self.inner.deref().borrow_mut() {
33 //! pub fn push(&mut self, val: u32);
34 //! }
35 //! }
36 //! }
37 //! ```
38 //!
39 //! - Delegate to enum variants
40 //!
41 //! ```rust
42 //! use delegate::delegate;
43 //!
44 //! enum Enum {
45 //! A(A),
46 //! B(B),
47 //! C { v: C },
48 //! }
49 //!
50 //! struct A {
51 //! val: usize,
52 //! }
53 //!
54 //! impl A {
55 //! fn dbg_inner(&self) -> usize {
56 //! dbg!(self.val);
57 //! 1
58 //! }
59 //! }
60 //! struct B {
61 //! val_a: String,
62 //! }
63 //!
64 //! impl B {
65 //! fn dbg_inner(&self) -> usize {
66 //! dbg!(self.val_a.clone());
67 //! 2
68 //! }
69 //! }
70 //!
71 //! struct C {
72 //! val_c: f64,
73 //! }
74 //!
75 //! impl C {
76 //! fn dbg_inner(&self) -> usize {
77 //! dbg!(self.val_c);
78 //! 3
79 //! }
80 //! }
81 //!
82 //! impl Enum {
83 //! delegate! {
84 //! // transformed to
85 //! //
86 //! // ```rust
87 //! // match self {
88 //! // Enum::A(a) => a.dbg_inner(),
89 //! // Enum::B(b) => { println!("i am b"); b }.dbg_inner(),
90 //! // Enum::C { v: c } => { c }.dbg_inner(),
91 //! // }
92 //! // ```
93 //! to match self {
94 //! Enum::A(a) => a,
95 //! Enum::B(b) => { println!("i am b"); b },
96 //! Enum::C { v: c } => { c },
97 //! } {
98 //! fn dbg_inner(&self) -> usize;
99 //! }
100 //! }
101 //! }
102 //! ```
103 //!
104 //! - Use modifiers that alter the generated method body
105 //! ```rust
106 //! use delegate::delegate;
107 //! struct Inner;
108 //! impl Inner {
109 //! pub fn method(&self, num: u32) -> u32 { num }
110 //! pub fn method_res(&self, num: u32) -> Result<u32, ()> { Ok(num) }
111 //! }
112 //! struct Wrapper { inner: Inner }
113 //! impl Wrapper {
114 //! delegate! {
115 //! to self.inner {
116 //! // calls method, converts result to u64 using `From`
117 //! #[into]
118 //! pub fn method(&self, num: u32) -> u64;
119 //!
120 //! // calls method, returns ()
121 //! #[call(method)]
122 //! pub fn method_noreturn(&self, num: u32);
123 //!
124 //! // calls method, converts result to i6 using `TryFrom`
125 //! #[try_into]
126 //! #[call(method)]
127 //! pub fn method2(&self, num: u32) -> Result<u16, std::num::TryFromIntError>;
128 //!
129 //! // calls method_res, unwraps the result
130 //! #[unwrap]
131 //! pub fn method_res(&self, num: u32) -> u32;
132 //!
133 //! // calls method_res, unwraps the result, then calls into
134 //! #[unwrap]
135 //! #[into]
136 //! #[call(method_res)]
137 //! pub fn method_res_into(&self, num: u32) -> u64;
138 //!
139 //! // specify explicit type for into
140 //! #[into(u64)]
141 //! #[call(method)]
142 //! pub fn method_into_explicit(&self, num: u32) -> u64;
143 //! }
144 //! }
145 //! }
146 //! ```
147 //!
148 //! - Custom called expression
149 //!
150 //! The `#[expr()]` attribute can be used to modify the delegated call. You can use the `$` sigil as a placeholder for what delegate would normally expand to, and wrap that expression with custom code.
151 //!
152 //! _Note:_ the `$` placeholder isn't required and can be present multiple times if you want.
153 //!
154 //! ```rs
155 //! struct A(Vec<u8>);
156 //!
157 //! impl A {
158 //! delegate! {
159 //! to self.0 {
160 //! #[expr(*$.unwrap())]
161 //! /// Here `$` == `self.0.get(idx)`
162 //! /// Will expand to `*self.0.get(idx).unwrap()`
163 //! fn get(&self, idx: usize) -> u8;
164 //!
165 //! #[call(get)]
166 //! #[expr($?.checked_pow(2))]
167 //! /// Here `$` == `self.0.get(idx)`
168 //! /// Will expand to `self.0.get(idx)?.checked_pow(2)`
169 //! fn get_checked_pow_2(&self, idx: usize) -> Option<u8>;
170 //! }
171 //! }
172 //! }
173 //! ```
174 //!
175 //! - Call `await` on async functions
176 //! ```rust
177 //! use delegate::delegate;
178 //!
179 //! struct Inner;
180 //! impl Inner {
181 //! pub async fn method(&self, num: u32) -> u32 { num }
182 //! }
183 //! struct Wrapper { inner: Inner }
184 //! impl Wrapper {
185 //! delegate! {
186 //! to self.inner {
187 //! // calls method(num).await, returns impl Future<Output = u32>
188 //! pub async fn method(&self, num: u32) -> u32;
189 //!
190 //! // calls method(num).await.into(), returns impl Future<Output = u64>
191 //! #[into]
192 //! #[call(method)]
193 //! pub async fn method_into(&self, num: u32) -> u64;
194 //! }
195 //! }
196 //! }
197 //! ```
198 //! You can use the `#[await(true/false)]` attribute on delegated methods to specify if `.await` should
199 //! be generated after the delegated expression. It will be generated by default if the delegated
200 //! method is `async`.
201 //! - Delegate to multiple fields
202 //! ```rust
203 //! use delegate::delegate;
204 //!
205 //! struct MultiStack {
206 //! left: Vec<u32>,
207 //! right: Vec<u32>,
208 //! }
209 //! impl MultiStack {
210 //! delegate! {
211 //! to self.left {
212 //! // Push an item to the top of the left stack
213 //! #[call(push)]
214 //! pub fn push_left(&mut self, value: u32);
215 //! }
216 //! to self.right {
217 //! // Push an item to the top of the right stack
218 //! #[call(push)]
219 //! pub fn push_right(&mut self, value: u32);
220 //! }
221 //! }
222 //! }
223 //! ```
224 //! - Inserts `#[inline(always)]` automatically (unless you specify `#[inline]` manually on the method)
225 //! - You can use an attribute on a whole segment to automatically apply it to all methods in that
226 //! segment:
227 //! ```rust
228 //! use delegate::delegate;
229 //!
230 //! struct Inner;
231 //!
232 //! impl Inner {
233 //! fn foo(&self) -> Result<u32, ()> { Ok(0) }
234 //! fn bar(&self) -> Result<u32, ()> { Ok(1) }
235 //! }
236 //!
237 //! struct Wrapper { inner: Inner }
238 //!
239 //! impl Wrapper {
240 //! delegate! {
241 //! #[unwrap]
242 //! to self.inner {
243 //! fn foo(&self) -> u32; // calls self.inner.foo().unwrap()
244 //! fn bar(&self) -> u32; // calls self.inner.bar().unwrap()
245 //! }
246 //! }
247 //! }
248 //! ```
249 //! - Specify expressions in the signature that will be used as delegated arguments
250 //! ```rust
251 //! use delegate::delegate;
252 //! struct Inner;
253 //! impl Inner {
254 //! pub fn polynomial(&self, a: i32, x: i32, b: i32, y: i32, c: i32) -> i32 {
255 //! a + x * x + b * y + c
256 //! }
257 //! }
258 //! struct Wrapper { inner: Inner, a: i32, b: i32, c: i32 }
259 //! impl Wrapper {
260 //! delegate! {
261 //! to self.inner {
262 //! // Calls `polynomial` on `inner` with `self.a`, `self.b` and
263 //! // `self.c` passed as arguments `a`, `b`, and `c`, effectively
264 //! // calling `polynomial(self.a, x, self.b, y, self.c)`.
265 //! pub fn polynomial(&self, [ self.a ], x: i32, [ self.b ], y: i32, [ self.c ]) -> i32 ;
266 //! // Calls `polynomial` on `inner` with `0`s passed for arguments
267 //! // `a` and `x`, and `self.b` and `self.c` for `b` and `c`,
268 //! // effectively calling `polynomial(0, 0, self.b, y, self.c)`.
269 //! #[call(polynomial)]
270 //! pub fn linear(&self, [ 0 ], [ 0 ], [ self.b ], y: i32, [ self.c ]) -> i32 ;
271 //! }
272 //! }
273 //! }
274 //! ```
275 //! - Modify how will an input parameter be passed to the delegated method with parameter attribute modifiers.
276 //! Currently, the following modifiers are supported:
277 //! - `#[into]`: Calls `.into()` on the parameter passed to the delegated method.
278 //! - `#[as_ref]`: Calls `.as_ref()` on the parameter passed to the delegated method.
279 //! - `#[newtype]`: Calls `.0` on the parameter passed to the delegated method.
280 //! ```rust
281 //! use delegate::delegate;
282 //!
283 //! struct InnerType {}
284 //! impl InnerType {
285 //! fn foo(&self, other: Self) {}
286 //! }
287 //!
288 //! impl From<Wrapper> for InnerType {
289 //! fn from(wrapper: Wrapper) -> Self {
290 //! wrapper.0
291 //! }
292 //! }
293 //!
294 //! struct Wrapper(InnerType);
295 //! impl Wrapper {
296 //! delegate! {
297 //! to self.0 {
298 //! // Calls `self.0.foo(other.into());`
299 //! pub fn foo(&self, #[into] other: Self);
300 //! }
301 //! }
302 //! }
303 //! ```
304 //! - Specify a trait through which will the delegated method be called
305 //! (using [UFCS](https://doc.rust-lang.org/reference/expressions/call-expr.html#disambiguating-function-calls).
306 //! ```rust
307 //! use delegate::delegate;
308 //!
309 //! struct InnerType {}
310 //! impl InnerType {
311 //!
312 //! }
313 //!
314 //! trait MyTrait {
315 //! fn foo(&self);
316 //! }
317 //! impl MyTrait for InnerType {
318 //! fn foo(&self) {}
319 //! }
320 //!
321 //! struct Wrapper(InnerType);
322 //! impl Wrapper {
323 //! delegate! {
324 //! to &self.0 {
325 //! // Calls `MyTrait::foo(&self.0)`
326 //! #[through(MyTrait)]
327 //! pub fn foo(&self);
328 //! }
329 //! }
330 //! }
331 //! ```
332 //!
333 //! - Add additional arguments to method
334 //!
335 //! ```rust
336 //! use delegate::delegate;
337 //! use std::cell::OnceCell;
338 //! struct Inner(u32);
339 //! impl Inner {
340 //! pub fn new(m: u32) -> Self {
341 //! // some "very complex" constructing work
342 //! Self(m)
343 //! }
344 //! pub fn method(&self, n: u32) -> u32 {
345 //! self.0 + n
346 //! }
347 //! }
348 //!
349 //! struct Wrapper {
350 //! inner: OnceCell<Inner>,
351 //! }
352 //!
353 //! impl Wrapper {
354 //! pub fn new() -> Self {
355 //! Self {
356 //! inner: OnceCell::new(),
357 //! }
358 //! }
359 //! fn content(&self, val: u32) -> &Inner {
360 //! self.inner.get_or_init(|| Inner(val))
361 //! }
362 //! delegate! {
363 //! to |k: u32| self.content(k) {
364 //! // `wrapper.method(k, num)` will call `self.content(k).method(num)`
365 //! pub fn method(&self, num: u32) -> u32;
366 //! }
367 //! }
368 //! }
369 //! ```
370 //! - Delegate associated functions
371 //! ```rust
372 //! use delegate::delegate;
373 //!
374 //! struct A {}
375 //! impl A {
376 //! fn foo(a: u32) -> u32 {
377 //! a + 1
378 //! }
379 //! }
380 //!
381 //! struct B;
382 //!
383 //! impl B {
384 //! delegate! {
385 //! to A {
386 //! fn foo(a: u32) -> u32;
387 //! }
388 //! }
389 //! }
390 //!
391 //! assert_eq!(B::foo(1), 2);
392 //! ```
393 //! - Delegate associated constants
394 //!
395 //! ```rust
396 //! use delegate::delegate;
397 //!
398 //! trait WithConst {
399 //! const TOTO: u8;
400 //! }
401 //!
402 //! struct A;
403 //! impl WithConst for A {
404 //! const TOTO: u8 = 1;
405 //! }
406 //!
407 //! struct B;
408 //! impl WithConst for B {
409 //! const TOTO: u8 = 2;
410 //! }
411 //! struct C;
412 //! impl WithConst for C {
413 //! const TOTO: u8 = 2;
414 //! }
415 //!
416 //! enum Enum {
417 //! A(A),
418 //! B(B),
419 //! C(C),
420 //! }
421 //!
422 //! impl Enum {
423 //! delegate! {
424 //! to match self {
425 //! Self::A(a) => a,
426 //! Self::B(b) => b,
427 //! Self::C(c) => { println!("hello from c"); c },
428 //! } {
429 //! #[const(WithConst::TOTO)]
430 //! fn get_toto(&self) -> u8;
431 //! }
432 //! }
433 //! }
434 //!
435 //! assert_eq!(Enum::A(A).get_toto(), <A as WithConst>::TOTO);
436 //! ```
437 //!
438 //! - Delegate to fields
439 //! ```rust
440 //! use delegate::delegate;
441 //!
442 //! struct Datum {
443 //! value: u32,
444 //! error: u32,
445 //! }
446 //!
447 //! struct DatumWrapper(Datum);
448 //!
449 //! impl DatumWrapper {
450 //! delegate! {
451 //! to self.0 {
452 //! /// Get the value of a nested field with the same name
453 //! #[field]
454 //! fn value(&self) -> u32;
455 //!
456 //! /// Get the value of a nested field with a different name
457 //! #[field(value)]
458 //! fn renamed_value(&self) -> u32;
459 //!
460 //! /// Get shared reference to a nested field
461 //! #[field(&value)]
462 //! fn value_ref(&self) -> &u32;
463 //!
464 //! /// Get mutable reference to a nested field
465 //! #[field(&mut value)]
466 //! fn value_ref_mut(&mut self) -> &mut u32;
467 //!
468 //! /// Get mutable reference to a nested field with the same name
469 //! #[field(&)]
470 //! fn error(&self) -> &u32;
471 //! }
472 //! }
473 //! }
474 //! ```
475
476 extern crate proc_macro;
477 use std::mem;
478
479 use attributes::AssociatedConstant;
480 use proc_macro::TokenStream;
481
482 use proc_macro2::Ident;
483 use quote::{quote, ToTokens};
484 use syn::parse::{Parse, ParseStream};
485 use syn::spanned::Spanned;
486 use syn::visit_mut::VisitMut;
487 use syn::{parse_quote, Error, Expr, ExprField, ExprMethodCall, FnArg, GenericParam, Meta};
488
489 use crate::attributes::{
490 combine_attributes, parse_method_attributes, parse_segment_attributes, ReturnExpression,
491 SegmentAttributes, TargetSpecifier,
492 };
493
494 mod attributes;
495
496 mod kw {
497 syn::custom_keyword!(to);
498 syn::custom_keyword!(target);
499 }
500
501 #[derive(Clone)]
502 enum ArgumentModifier {
503 Into,
504 AsRef,
505 Newtype,
506 }
507
508 #[derive(Clone)]
509 enum DelegatedInput {
510 Input {
511 parameter: syn::FnArg,
512 modifier: Option<ArgumentModifier>,
513 },
514 Argument(syn::Expr),
515 }
516
517 fn get_argument_modifier(attribute: syn::Attribute) -> Result<ArgumentModifier, Error> {
518 if let Meta::Path(mut path) = attribute.meta {
519 if path.segments.len() == 1 {
520 let segment = path.segments.pop().unwrap();
521 if segment.value().arguments.is_empty() {
522 let ident = segment.value().ident.to_string();
523 let ident = ident.as_str();
524
525 match ident {
526 "into" => return Ok(ArgumentModifier::Into),
527 "as_ref" => return Ok(ArgumentModifier::AsRef),
528 "newtype" => return Ok(ArgumentModifier::Newtype),
529 _ => (),
530 }
531 }
532 }
533 };
534
535 panic!("The attribute argument has to be `into` or `as_ref`, like this: `#[into] a: u32`.")
536 }
537
538 impl syn::parse::Parse for DelegatedInput {
539 fn parse(input: ParseStream) -> Result<Self, Error> {
540 let lookahead = input.lookahead1();
541 if lookahead.peek(syn::token::Bracket) {
542 let content;
543 let _bracket_token = syn::bracketed!(content in input);
544 let expression: syn::Expr = content.parse()?;
545 Ok(Self::Argument(expression))
546 } else {
547 let (input, modifier) = if lookahead.peek(syn::token::Pound) {
548 let mut attributes = input.call(tolerant_outer_attributes)?;
549 if attributes.len() > 1 {
550 panic!("You can specify at most a single attribute for each parameter in a delegated method");
551 }
552 let modifier = get_argument_modifier(attributes.pop().unwrap())
553 .expect("Could not parse argument modifier attribute");
554
555 let input: syn::FnArg = input.parse()?;
556 (input, Some(modifier))
557 } else {
558 (input.parse()?, None)
559 };
560
561 Ok(Self::Input {
562 parameter: input,
563 modifier,
564 })
565 }
566 }
567 }
568
569 struct DelegatedMethod {
570 method: syn::TraitItemFn,
571 attributes: Vec<syn::Attribute>,
572 visibility: syn::Visibility,
573 arguments: syn::punctuated::Punctuated<syn::Expr, syn::Token![,]>,
574 }
575
576 // Given an input parameter from a function signature, create a function
577 // argument used to call the delegate function: omit receiver, extract an
578 // identifier from a typed input parameter (and wrap it in an `Expr`).
579 fn parse_input_into_argument_expression(
580 function_name: &Ident,
581 input: &syn::FnArg,
582 ) -> Option<syn::Expr> {
583 match input {
584 // Parse inputs of the form `x: T` to retrieve their identifiers.
585 syn::FnArg::Typed(typed) => {
586 match &*typed.pat {
587 // This should not happen, I think. If it does,
588 // it will be ignored as if it were the
589 // receiver.
590 syn::Pat::Ident(ident) if ident.ident == "self" => None,
591 // Expression in the form `x: T`. Extract the
592 // identifier, wrap it in Expr for type compatibility with bracketed expressions,
593 // and append it
594 // to the argument list.
595 syn::Pat::Ident(ident) => {
596 let path_segment = syn::PathSegment {
597 ident: ident.ident.clone(),
598 arguments: syn::PathArguments::None,
599 };
600 let mut segments = syn::punctuated::Punctuated::new();
601 segments.push(path_segment);
602 let path = syn::Path {
603 leading_colon: None,
604 segments,
605 };
606 let ident_as_expr = syn::Expr::from(syn::ExprPath {
607 attrs: Vec::new(),
608 qself: None,
609 path,
610 });
611 Some(ident_as_expr)
612 }
613 // Other more complex argument expressions are not covered.
614 _ => panic!(
615 "You have to use simple identifiers for delegated method parameters ({})",
616 function_name // The signature is not constructed yet. We make due.
617 ),
618 }
619 }
620 // Skip any `self`/`&self`/`&mut self` argument, since
621 // it does not appear in the argument list and it's
622 // already added to the parameter list.
623 syn::FnArg::Receiver(_receiver) => None,
624 }
625 }
626
627 impl syn::parse::Parse for DelegatedMethod {
628 fn parse(input: ParseStream) -> Result<Self, Error> {
629 let attributes = input.call(tolerant_outer_attributes)?;
630 let visibility = input.call(syn::Visibility::parse)?;
631
632 // Unchanged from Parse from TraitItemMethod
633 let constness: Option<syn::Token![const]> = input.parse()?;
634 let asyncness: Option<syn::Token![async]> = input.parse()?;
635 let unsafety: Option<syn::Token![unsafe]> = input.parse()?;
636 let abi: Option<syn::Abi> = input.parse()?;
637 let fn_token: syn::Token![fn] = input.parse()?;
638 let ident: Ident = input.parse()?;
639 let generics: syn::Generics = input.parse()?;
640
641 let content;
642 let paren_token = syn::parenthesized!(content in input);
643
644 // Parse inputs (method parameters) and arguments. The parameters
645 // constitute the parameter list of the signature of the delegating
646 // method so it must include all inputs, except bracketed expressions.
647 // The argument list constitutes the list of arguments used to call the
648 // delegated function. It must include all inputs, excluding the
649 // receiver (self-type) input. The arguments must all be parsed to
650 // retrieve the expressions inside of the brackets as well as variable
651 // identifiers of ordinary inputs. The arguments must preserve the order
652 // of the inputs.
653 let delegated_inputs = content.parse_terminated(DelegatedInput::parse, syn::Token![,])?;
654 let mut inputs: syn::punctuated::Punctuated<syn::FnArg, syn::Token![,]> =
655 syn::punctuated::Punctuated::new();
656 let mut arguments: syn::punctuated::Punctuated<syn::Expr, syn::Token![,]> =
657 syn::punctuated::Punctuated::new();
658
659 // First, combine the cases for pairs with cases for end, to remove
660 // redundancy below.
661 delegated_inputs
662 .into_pairs()
663 .map(|punctuated_pair| match punctuated_pair {
664 syn::punctuated::Pair::Punctuated(item, comma) => (item, Some(comma)),
665 syn::punctuated::Pair::End(item) => (item, None),
666 })
667 .for_each(|pair| match pair {
668 // This input is a bracketed argument (eg. `[ self.x ]`). It
669 // is omitted in the signature of the delegator, but the
670 // expression inside the brackets is used in the body of the
671 // delegator, as an arugnment to the delegated function (eg.
672 // `self.x`). The argument needs to be generated in the
673 // appropriate position with respect other arguments and non-
674 // argument inputs. As long as inputs are added to the
675 // `arguments` vector in order of occurance, this is trivial.
676 (DelegatedInput::Argument(argument), maybe_comma) => {
677 arguments.push_value(argument);
678 if let Some(comma) = maybe_comma {
679 arguments.push_punct(comma)
680 }
681 }
682 // The input is a standard function parameter with a name and
683 // a type (eg. `x: T`). This input needs to be reflected in
684 // the delegator signature as is (eg. `x: T`). The identifier
685 // also needs to be included in the argument list in part
686 // (eg. `x`). The argument list needs to preserve the order of
687 // the inputs with relation to arguments (see above), so the
688 // parsing is best done here (previously it was done at
689 // generation).
690 (
691 DelegatedInput::Input {
692 parameter,
693 modifier,
694 },
695 maybe_comma,
696 ) => {
697 inputs.push_value(parameter.clone());
698 if let Some(comma) = maybe_comma {
699 inputs.push_punct(comma);
700 }
701 let maybe_argument = parse_input_into_argument_expression(&ident, &parameter);
702 if let Some(mut argument) = maybe_argument {
703 let span = argument.span();
704
705 if let Some(modifier) = modifier {
706 let method_call = |name: &str| {
707 syn::Expr::from(ExprMethodCall {
708 attrs: vec![],
709 receiver: Box::new(argument.clone()),
710 dot_token: Default::default(),
711 method: Ident::new(name, span),
712 turbofish: None,
713 paren_token,
714 args: Default::default(),
715 })
716 };
717
718 let field_call = || {
719 syn::Expr::from(ExprField {
720 attrs: vec![],
721 base: Box::new(argument.clone()),
722 dot_token: Default::default(),
723 member: syn::Member::Unnamed(0.into()),
724 })
725 };
726
727 match modifier {
728 ArgumentModifier::Into => {
729 argument = method_call("into");
730 }
731 ArgumentModifier::AsRef => {
732 argument = method_call("as_ref");
733 }
734 ArgumentModifier::Newtype => argument = field_call(),
735 }
736 }
737
738 arguments.push(argument);
739 if let Some(comma) = maybe_comma {
740 arguments.push_punct(comma);
741 }
742 }
743 }
744 });
745
746 // Unchanged from Parse from TraitItemMethod
747 let output: syn::ReturnType = input.parse()?;
748 let where_clause: Option<syn::WhereClause> = input.parse()?;
749
750 // This needs to be generated manually, because inputs need to be
751 // separated into actual inputs that go in the signature (the
752 // parameters) and the additional expressions in square brackets which
753 // go into the arguments vector (artguments of the call on the method
754 // on the inner object).
755 let signature = syn::Signature {
756 constness,
757 asyncness,
758 unsafety,
759 abi,
760 fn_token,
761 ident,
762 paren_token,
763 inputs,
764 output,
765 variadic: None,
766 generics: syn::Generics {
767 where_clause,
768 ..generics
769 },
770 };
771
772 // Check if the input contains a semicolon or a brace. If it contains
773 // a semicolon, we parse it (to retain token location information) and
774 // continue. However, if it contains a brace, this indicates that
775 // there is a default definition of the method. This is not supported,
776 // so in that case we error out.
777 let lookahead = input.lookahead1();
778 let semi_token: Option<syn::Token![;]> = if lookahead.peek(syn::Token![;]) {
779 Some(input.parse()?)
780 } else {
781 panic!(
782 "Do not include implementation of delegated functions ({})",
783 signature.ident
784 );
785 };
786
787 // This needs to be populated from scratch because of the signature above.
788 let method = syn::TraitItemFn {
789 // All attributes are attached to `DelegatedMethod`, since they
790 // presumably pertain to the process of delegation, not the
791 // signature of the delegator.
792 attrs: Vec::new(),
793 sig: signature,
794 default: None,
795 semi_token,
796 };
797
798 Ok(DelegatedMethod {
799 method,
800 attributes,
801 visibility,
802 arguments,
803 })
804 }
805 }
806
807 struct DelegatedSegment {
808 delegator: syn::Expr,
809 methods: Vec<DelegatedMethod>,
810 segment_attrs: SegmentAttributes,
811 }
812
813 impl syn::parse::Parse for DelegatedSegment {
814 fn parse(input: ParseStream) -> Result<Self, Error> {
815 let attributes = input.call(tolerant_outer_attributes)?;
816 let segment_attrs = parse_segment_attributes(&attributes);
817
818 if let Ok(keyword) = input.parse::<kw::target>() {
819 return Err(Error::new(keyword.span(), "You are using the old `target` expression, which is deprecated. Please replace `target` with `to`."));
820 } else {
821 input.parse::<kw::to>()?;
822 }
823
824 syn::Expr::parse_without_eager_brace(input).and_then(|delegator| {
825 let content;
826 syn::braced!(content in input);
827
828 let mut methods = vec![];
829 while !content.is_empty() {
830 methods.push(
831 content
832 .parse::<DelegatedMethod>()
833 .expect("Cannot parse delegated method"),
834 );
835 }
836
837 Ok(DelegatedSegment {
838 delegator,
839 methods,
840 segment_attrs,
841 })
842 })
843 }
844 }
845
846 struct DelegationBlock {
847 segments: Vec<DelegatedSegment>,
848 }
849
850 impl syn::parse::Parse for DelegationBlock {
851 fn parse(input: ParseStream) -> Result<Self, Error> {
852 let mut segments = vec![];
853 while !input.is_empty() {
854 segments.push(input.parse()?);
855 }
856
857 Ok(DelegationBlock { segments })
858 }
859 }
860
861 /// Returns true if there are any `inline` attributes in the input.
862 fn has_inline_attribute(attrs: &[&syn::Attribute]) -> bool {
863 attrs.iter().any(|attr| {
864 if let syn::AttrStyle::Outer = attr.style {
865 attr.path().is_ident("inline")
866 } else {
867 false
868 }
869 })
870 }
871
872 struct MatchVisitor<F>(F);
873
874 impl<F: Fn(&Expr) -> proc_macro2::TokenStream> VisitMut for MatchVisitor<F> {
875 fn visit_arm_mut(&mut self, arm: &mut syn::Arm) {
876 let transformed = self.0(&arm.body);
877 arm.body = parse_quote!(#transformed);
878 }
879 }
880
881 #[proc_macro]
882 pub fn delegate(tokens: TokenStream) -> TokenStream {
883 let block: DelegationBlock = syn::parse_macro_input!(tokens);
884 let sections = block.segments.iter().map(|delegator| {
885 let delegated_expr = &delegator.delegator;
886 let functions = delegator.methods.iter().map(|method| {
887 let input = &method.method;
888 let mut signature = input.sig.clone();
889 if let Expr::Closure(closure) = delegated_expr {
890 let additional_inputs: Vec<FnArg> = closure
891 .inputs
892 .iter()
893 .map(|input| {
894 if let syn::Pat::Type(pat_type) = input {
895 syn::parse_quote!(#pat_type)
896 } else {
897 panic!(
898 "Use a type pattern (`a: u32`) for delegation closure arguments"
899 );
900 }
901 })
902 .collect();
903 let mut origin_inputs = mem::take(&mut signature.inputs).into_iter();
904 // When delegating methods, `first_input` should be self or similar receivers
905 // Then we need to move it to first
906 // When delegating associated methods, it may be a trivial argument or does not even exist
907 // We just keep the origin order.
908 let first_input = origin_inputs.next();
909 match first_input {
910 Some(FnArg::Receiver(receiver)) => {
911 signature.inputs.push(FnArg::Receiver(receiver));
912 signature.inputs.extend(additional_inputs);
913 }
914 Some(first_input) => {
915 signature.inputs.extend(additional_inputs);
916 signature.inputs.push(first_input);
917 }
918 _ => {
919 signature.inputs.extend(additional_inputs);
920 }
921 }
922 signature.inputs.extend(origin_inputs);
923 }
924 let attributes = parse_method_attributes(&method.attributes, input);
925 let attributes = combine_attributes(attributes, &delegator.segment_attrs);
926 if input.default.is_some() {
927 panic!(
928 "Do not include implementation of delegated functions ({})",
929 signature.ident
930 );
931 }
932
933 // Generate an argument vector from Punctuated list.
934 let args: Vec<Expr> = method.arguments.clone().into_iter().collect();
935
936 // Get name (or index) of the target method or field
937 let name = match &attributes.target_specifier {
938 Some(target) => target.get_member(&input.sig.ident),
939 None => input.sig.ident.clone().into(),
940 };
941
942 let inline = if has_inline_attribute(&attributes.attributes) {
943 quote!()
944 } else {
945 quote! { #[inline] }
946 };
947 let visibility = &method.visibility;
948
949 let is_method = method.method.sig.receiver().is_some();
950 let associated_const = &attributes.associated_constant;
951 let expr_attr = &attributes.expr_attr;
952
953 // Use the body of a closure (like `|k: u32| <body>`) as the delegation expression
954 let delegated_body = if let Expr::Closure(closure) = delegated_expr {
955 &closure.body
956 } else {
957 delegated_expr
958 };
959
960 let span = input.span();
961 let generate_await = attributes
962 .generate_await
963 .unwrap_or_else(|| method.method.sig.asyncness.is_some());
964
965 // fn method<'a, A, B> -> method::<A, B>
966 let generic_params = &method.method.sig.generics.params;
967 let generics = if generic_params.is_empty() {
968 quote::quote! {}
969 } else {
970 let span = generic_params.span();
971 let mut params: syn::punctuated::Punctuated<
972 proc_macro2::TokenStream,
973 syn::Token![,],
974 > = syn::punctuated::Punctuated::new();
975 for param in generic_params.iter() {
976 let token = match param {
977 GenericParam::Lifetime(_) => {
978 // Do not pass lifetimes to generic arguments explicitly to avoid
979 // things like https://doc.rust-lang.org/error_codes/E0794.html
980 // See https://github.com/Kobzol/rust-delegate/issues/85.
981 continue;
982 }
983 GenericParam::Type(t) => {
984 let token = &t.ident;
985 let span = t.span();
986 quote::quote_spanned! {span=> #token }
987 }
988 GenericParam::Const(c) => {
989 let token = &c.ident;
990 let span = c.span();
991 quote::quote_spanned! {span=> #token }
992 }
993 };
994 params.push(token);
995 }
996 quote::quote_spanned! {span=> ::<#params> }
997 };
998
999 let modify_expr = |expr: &Expr| {
1000 let body = if let Some(target_trait) = &attributes.target_trait {
1001 quote::quote! { #target_trait::#name#generics(#expr, #(#args),*) }
1002 } else if let Some(AssociatedConstant {
1003 const_name,
1004 trait_path,
1005 }) = associated_const
1006 {
1007 let return_type = &signature.output;
1008 quote::quote! {{
1009 const fn get_const<T: #trait_path>(t: &T) #return_type {
1010 <T as #trait_path>::#const_name
1011 }
1012 get_const(#expr)
1013 }}
1014 } else if is_method {
1015 match &attributes.target_specifier {
1016 None | Some(TargetSpecifier::Method(_)) => {
1017 quote::quote! { #expr.#name#generics(#(#args),*) }
1018 }
1019 Some(TargetSpecifier::Field(target)) => {
1020 let reference = target.reference_tokens();
1021 quote::quote! { #reference#expr.#name }
1022 }
1023 }
1024 } else {
1025 quote::quote! { #expr::#name#generics(#(#args),*) }
1026 };
1027
1028 let mut body = if generate_await {
1029 quote::quote! { #body.await }
1030 } else {
1031 body
1032 };
1033
1034 for expression in &attributes.expressions {
1035 match expression {
1036 ReturnExpression::Into(type_name) => {
1037 body = match type_name {
1038 Some(name) => {
1039 quote::quote! { ::core::convert::Into::<#name>::into(#body) }
1040 }
1041 None => quote::quote! { ::core::convert::Into::into(#body) },
1042 };
1043 }
1044 ReturnExpression::TryInto => {
1045 body = quote::quote! { ::core::convert::TryInto::try_into(#body) };
1046 }
1047 ReturnExpression::Unwrap => {
1048 body = quote::quote! { #body.unwrap() };
1049 }
1050 }
1051 }
1052 body
1053 };
1054 let mut body = if let Expr::Match(expr_match) = delegated_body {
1055 let mut expr_match = expr_match.clone();
1056 MatchVisitor(modify_expr).visit_expr_match_mut(&mut expr_match);
1057 expr_match.into_token_stream()
1058 } else {
1059 modify_expr(delegated_body)
1060 };
1061
1062 if let syn::ReturnType::Default = &signature.output {
1063 body = quote::quote! { #body; };
1064 };
1065
1066 if let Some(expr_template) = expr_attr {
1067 body = expr_template.expand_template(&body);
1068 }
1069
1070 let attrs = &attributes.attributes;
1071 quote::quote_spanned! {span=>
1072 #(#attrs)*
1073 #inline
1074 #visibility #signature {
1075 #body
1076 }
1077 }
1078 });
1079
1080 quote! { #(#functions)* }
1081 });
1082
1083 let result = quote! {
1084 #(#sections)*
1085 };
1086 result.into()
1087 }
1088
1089 // we cannot use `Attributes::parse_outer` directly, because it does not allow keywords to appear
1090 // in meta path positions, i.e., it does not accept `#[await(true)]`.
1091 // related issue: https://github.com/dtolnay/syn/issues/1458
1092 fn tolerant_outer_attributes(input: ParseStream) -> syn::Result<Vec<syn::Attribute>> {
1093 use proc_macro2::{Delimiter, TokenTree};
1094 use syn::{
1095 bracketed,
1096 ext::IdentExt,
1097 parse::discouraged::Speculative,
1098 token::{Brace, Bracket, Paren},
1099 AttrStyle, Attribute, ExprLit, Lit, MacroDelimiter, MetaList, MetaNameValue, Path, Result,
1100 Token,
1101 };
1102
1103 fn tolerant_attr(input: ParseStream) -> Result<Attribute> {
1104 let content;
1105 Ok(Attribute {
1106 pound_token: input.parse()?,
1107 style: AttrStyle::Outer,
1108 bracket_token: bracketed!(content in input),
1109 meta: content.call(tolerant_meta)?,
1110 })
1111 }
1112
1113 // adapted from `impl Parse for Meta`
1114 fn tolerant_meta(input: ParseStream) -> Result<Meta> {
1115 // Try to parse as Meta
1116 if let Ok(meta) = input.call(Meta::parse) {
1117 Ok(meta)
1118 } else {
1119 // If it's not possible, try to parse it as any identifier, to support #[await]
1120 let path = Path::from(input.call(Ident::parse_any)?);
1121 if input.peek(Paren) || input.peek(Bracket) || input.peek(Brace) {
1122 // adapted from the private `syn::attr::parse_meta_after_path`
1123 input.step(|cursor| {
1124 if let Some((TokenTree::Group(g), rest)) = cursor.token_tree() {
1125 let span = g.delim_span();
1126 let delimiter = match g.delimiter() {
1127 Delimiter::Parenthesis => MacroDelimiter::Paren(Paren(span)),
1128 Delimiter::Brace => MacroDelimiter::Brace(Brace(span)),
1129 Delimiter::Bracket => MacroDelimiter::Bracket(Bracket(span)),
1130 Delimiter::None => {
1131 return Err(cursor.error("expected delimiter"));
1132 }
1133 };
1134 Ok((
1135 Meta::List(MetaList {
1136 path,
1137 delimiter,
1138 tokens: g.stream(),
1139 }),
1140 rest,
1141 ))
1142 } else {
1143 Err(cursor.error("expected delimiter"))
1144 }
1145 })
1146 } else if input.peek(Token![=]) {
1147 // adapted from the private `syn::attr::parse_meta_name_value_after_path`
1148 let eq_token = input.parse()?;
1149 let ahead = input.fork();
1150 let value = match ahead.parse::<Option<Lit>>()? {
1151 // this branch is probably for speeding up the parsing for doc comments etc.
1152 Some(lit) if ahead.is_empty() => {
1153 input.advance_to(&ahead);
1154 Expr::Lit(ExprLit {
1155 attrs: Vec::new(),
1156 lit,
1157 })
1158 }
1159 _ => input.parse()?,
1160 };
1161 Ok(Meta::NameValue(MetaNameValue {
1162 path,
1163 eq_token,
1164 value,
1165 }))
1166 } else {
1167 Ok(Meta::Path(path))
1168 }
1169 }
1170 }
1171
1172 let mut attrs = Vec::new();
1173 while input.peek(Token![#]) {
1174 attrs.push(input.call(tolerant_attr)?);
1175 }
1176 Ok(attrs)
1177 }