David Tolnay | 56be665 | 2018-01-06 15:55:29 -0800 | [diff] [blame] | 1 | An example of an attribute procedural macro. The `#[trace_var(...)]` attribute |
| 2 | prints the value of the given variables each time they are reassigned. |
| 3 | |
| 4 | - [`trace-var/src/lib.rs`](trace-var/src/lib.rs) |
| 5 | - [`example/src/main.rs`](example/src/main.rs) |
| 6 | |
| 7 | Consider the following factorial implementation. |
| 8 | |
| 9 | ```rust |
| 10 | #[trace_var(p, n)] |
| 11 | fn factorial(mut n: u64) -> u64 { |
| 12 | let mut p = 1; |
| 13 | while n > 1 { |
| 14 | p *= n; |
| 15 | n -= 1; |
| 16 | } |
| 17 | p |
| 18 | } |
| 19 | ``` |
| 20 | |
| 21 | Invoking this with `factorial(8)` prints all the values of `p` and `n` during |
| 22 | the execution of the function. |
| 23 | |
| 24 | ``` |
| 25 | p = 1 |
| 26 | p = 8 |
| 27 | n = 7 |
| 28 | p = 56 |
| 29 | n = 6 |
| 30 | p = 336 |
| 31 | n = 5 |
| 32 | p = 1680 |
| 33 | n = 4 |
| 34 | p = 6720 |
| 35 | n = 3 |
| 36 | p = 20160 |
| 37 | n = 2 |
| 38 | p = 40320 |
| 39 | n = 1 |
| 40 | ``` |
| 41 | |
| 42 | The procedural macro uses a syntax tree [`Fold`] to rewrite every `let` |
| 43 | statement and assignment expression in the following way: |
| 44 | |
| 45 | [`Fold`]: https://docs.rs/syn/0.12/syn/fold/trait.Fold.html |
| 46 | |
| 47 | ```rust |
| 48 | // Before |
| 49 | let VAR = INIT; |
| 50 | |
| 51 | // After |
| 52 | let VAR = { let VAR = INIT; println!("VAR = {:?}", VAR); VAR }; |
| 53 | ``` |
| 54 | |
| 55 | ```rust |
| 56 | // Before |
| 57 | VAR = INIT |
| 58 | |
| 59 | // After |
| 60 | { VAR = INIT; println!("VAR = {:?}", VAR); } |
| 61 | ``` |