1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
//! # BorrowScope Procedural Macros
//!
//! This crate provides the `#[trace_borrow]` attribute macro that instruments
//! Rust code to track ownership and borrowing operations at runtime.
//!
//! ## Quick Start
//!
//! ```ignore
//! use borrowscope_macro::trace_borrow;
//! use borrowscope_runtime::*;
//!
//! #[trace_borrow]
//! fn example() {
//! let x = String::from("hello"); // New event
//! let y = &x; // Borrow event
//! let z = x; // Move event
//! } // Drop events
//!
//! fn main() {
//! reset();
//! example();
//! println!("{:?}", get_events());
//! }
//! ```
//!
//! ## Attribute Options
//!
//! ### Presets
//!
//! | Attribute | Description |
//! |-----------|-------------|
//! | `#[trace_borrow]` | Standard tracking (recommended) |
//! | `#[trace_borrow(quiet)]` | Ownership only (new, move, drop, borrow) |
//! | `#[trace_borrow(verbose)]` | All tracking including noisy features |
//!
//! ### Feature Selection
//!
//! | Attribute | Description |
//! |-----------|-------------|
//! | `#[trace_borrow(skip = "loops,branches")]` | Skip specific feature groups |
//! | `#[trace_borrow(only = "ownership")]` | Enable only specified feature groups |
//!
//! ### Filtering & Sampling (Performance)
//!
//! | Attribute | Description |
//! |-----------|-------------|
//! | `#[trace_borrow(filter = "data*")]` | Only track variables matching glob pattern |
//! | `#[trace_borrow(sample = 0.1)]` | Track ~10% of operations (probabilistic) |
//!
//! ### Conditional Compilation
//!
//! | Attribute | Description |
//! |-----------|-------------|
//! | `#[trace_borrow(debug_only)]` | Only track in debug builds |
//! | `#[trace_borrow(release_only)]` | Only track in release builds |
//! | `#[trace_borrow(feature = "tracing")]` | Only track when cargo feature enabled |
//!
//! ## Feature Groups
//!
//! Use these group names with `skip` or `only` options:
//!
//! | Group | Aliases | Description |
//! |-------|---------|-------------|
//! | `ownership` | - | Variable creation, moves, drops, borrows |
//! | `smart_pointers` | `pointers` | Rc, Arc, RefCell, Cell operations |
//! | `loops` | - | for, while, loop tracking |
//! | `branches` | - | if/else, match tracking |
//! | `control_flow` | `control` | break, continue, return |
//! | `try` | - | ? operator |
//! | `methods` | - | clone, lock, unwrap |
//! | `async` | - | async blocks, await |
//! | `unsafe` | - | unsafe blocks, raw pointers, transmute |
//! | `expressions` | `exprs` | struct, tuple, array, range, cast |
//! | `functions` | `fn` | Function entry/exit (disabled by default) |
//!
//! ## Filtering
//!
//! Filter which variables are tracked using glob patterns:
//!
//! ```ignore
//! #[trace_borrow(filter = "data*")] // Track vars starting with "data"
//! #[trace_borrow(filter = "*_count")] // Track vars ending with "_count"
//! #[trace_borrow(filter = "user_?")] // Track user_1, user_2, etc.
//! ```
//!
//! **Pattern syntax:**
//! - `*` matches zero or more characters
//! - `?` matches exactly one character
//!
//! **Note:** Filtering is applied at compile-time. No tracking code is generated
//! for variables that don't match the pattern, resulting in zero overhead.
//!
//! ## Sampling
//!
//! Reduce tracking overhead by only recording a percentage of operations:
//!
//! ```ignore
//! #[trace_borrow(sample = 0.1)] // Track ~10% of operations
//! #[trace_borrow(sample = 0.5)] // Track ~50% of operations
//! #[trace_borrow(sample = 1.0)] // Track 100% (same as no sampling)
//! ```
//!
//! **Use cases:**
//! - High-frequency loops where full tracking is too expensive
//! - Production monitoring with minimal overhead
//! - Statistical analysis where sampling is acceptable
//!
//! **Note:** Sampling uses a fast PRNG (xorshift64) for minimal overhead.
//! The decision is made at runtime for each tracking call.
//!
//! ## Conditional Compilation
//!
//! Control when tracking code is included:
//!
//! ```ignore
//! // Only in debug builds (recommended for development)
//! #[trace_borrow(debug_only)]
//! fn dev_function() { }
//!
//! // Only in release builds (for production monitoring)
//! #[trace_borrow(release_only)]
//! fn prod_function() { }
//!
//! // Only when cargo feature is enabled
//! #[trace_borrow(feature = "tracing")]
//! fn optional_tracing() { }
//! ```
//!
//! **Generated code:**
//! - `debug_only` → `#[cfg(debug_assertions)]`
//! - `release_only` → `#[cfg(not(debug_assertions))]`
//! - `feature = "x"` → `#[cfg(feature = "x")]`
//!
//! ## Combining Options
//!
//! Multiple options can be combined:
//!
//! ```ignore
//! // Debug-only, quiet mode
//! #[trace_borrow(debug_only, quiet)]
//!
//! // Filter + sampling for high-performance tracking
//! #[trace_borrow(filter = "user*", sample = 0.1)]
//!
//! // Feature-gated with specific groups
//! #[trace_borrow(feature = "trace", only = "ownership,smart_pointers")]
//!
//! // Skip noisy features, debug only
//! #[trace_borrow(debug_only, skip = "loops,branches,expressions")]
//! ```
//!
//! ## Tracked Operations
//!
//! ### Basic Ownership (`ownership` group)
//!
//! | Code Pattern | Event |
//! |--------------|-------|
//! | `let x = value;` | `New` |
//! | `let y = &x;` | `Borrow` |
//! | `let y = &mut x;` | `Borrow` (mutable) |
//! | `let y = x;` (move) | `Move` |
//! | Scope exit | `Drop` |
//!
//! ### Smart Pointers (`smart_pointers` group)
//!
//! | Code Pattern | Event |
//! |--------------|-------|
//! | `Rc::new(v)` | `RcNew` |
//! | `Rc::clone(&rc)` | `RcClone` |
//! | `Arc::new(v)` | `ArcNew` |
//! | `Arc::clone(&arc)` | `ArcClone` |
//! | `Box::new(v)` | `BoxNew` |
//! | `Box::pin(v)` | `PinNew` |
//! | `RefCell::new(v)` | `RefCellNew` |
//! | `refcell.borrow()` | `RefCellBorrow` |
//! | `refcell.borrow_mut()` | `RefCellBorrowMut` |
//! | `Cell::new(v)` | `CellNew` |
//! | `cell.get()` | `CellGet` |
//! | `cell.set(v)` | `CellSet` |
//!
//! ### Loops (`loops` group)
//!
//! | Code Pattern | Event |
//! |--------------|-------|
//! | `for`/`while`/`loop` entry | `LoopEnter` |
//! | Each iteration | `LoopIteration` |
//! | Loop end | `LoopExit` |
//!
//! ### Branches (`branches` group)
//!
//! | Code Pattern | Event |
//! |--------------|-------|
//! | `if`/`else` | `Branch` |
//! | `match` entry | `MatchEnter` |
//! | Match arm taken | `MatchArm` |
//! | Match end | `MatchExit` |
//!
//! ### Control Flow (`control_flow` group)
//!
//! | Code Pattern | Event |
//! |--------------|-------|
//! | `break` | `Break` |
//! | `continue` | `Continue` |
//! | `return` | `Return` |
//!
//! ### Other Groups
//!
//! | Group | Code Patterns | Events |
//! |-------|---------------|--------|
//! | `try` | `expr?` | `Try` |
//! | `methods` | `.clone()`, `.lock()`, `.unwrap()` | `Clone`, `Lock`, `Unwrap` |
//! | `async` | `async { }`, `.await` | `AsyncBlockEnter/Exit`, `AwaitStart/End` |
//! | `unsafe` | `unsafe { }`, `*ptr`, `transmute` | `UnsafeBlockEnter/Exit`, `RawPtrDeref`, `Transmute` |
//! | `expressions` | structs, tuples, arrays, ranges, casts | `StructCreate`, `TupleCreate`, etc. |
//! | `functions` | fn entry/exit | `FnEnter`, `FnExit` |
//!
//! ## Advanced Smart Pointer Tracking
//!
//! Beyond basic `Rc`, `Arc`, `RefCell`, and `Cell`, the macro tracks:
//!
//! ### Weak References
//!
//! | Code Pattern | Event |
//! |--------------|-------|
//! | `Rc::downgrade(&rc)` | `WeakNew` |
//! | `Arc::downgrade(&arc)` | `WeakNewSync` |
//! | `weak.upgrade()` | `WeakUpgrade` / `WeakUpgradeSync` |
//! | `weak.clone()` | `WeakClone` / `WeakCloneSync` |
//!
//! ### Pin, Cow, OnceCell, MaybeUninit
//!
//! | Type | Operations |
//! |------|------------|
//! | `Box` | `Box::pin`, `Box::into_raw`, `Box::from_raw` |
//! | `Pin<T>` | `Pin::new`, `Pin::into_inner` |
//! | `Cow<T>` | `Cow::Borrowed`, `Cow::Owned`, `to_mut()` |
//! | `OnceCell<T>` | `new()`, `set()`, `get()`, `get_or_init()` |
//! | `OnceLock<T>` | `new()`, `set()`, `get()`, `get_or_init()` |
//! | `MaybeUninit<T>` | `uninit()`, `new()`, `write()`, `assume_init()` |
//!
//! ## Concurrency Tracking
//!
//! | Code Pattern | Event |
//! |--------------|-------|
//! | `thread::spawn(...)` | `ThreadSpawn` |
//! | `handle.join()` | `ThreadJoin` |
//! | `mpsc::channel()` | `ChannelNew` |
//! | `tx.send(v)` | `ChannelSend` |
//! | `rx.recv()` | `ChannelRecv` |
//! | `rx.try_recv()` | `ChannelTryRecv` |
//!
//! ## Expression Tracking (`expressions` group)
//!
//! | Code Pattern | Event |
//! |--------------|-------|
//! | `Point { x, y }` | `StructCreate` (with type name) |
//! | `(a, b, c)` | `TupleCreate` (with arity) |
//! | `[1, 2, 3]` | `ArrayCreate` (with length) |
//! | `0..10` | `Range` (half_open) |
//! | `0..=10` | `Range` (closed) |
//! | `x as i64` | `TypeCast` (with target type) |
//!
//! ## Closure Tracking
//!
//! | Code Pattern | Event |
//! |--------------|-------|
//! | `\|x\| x + 1` | `ClosureCreate` (capture mode: ref) |
//! | `move \|x\| x + 1` | `ClosureCreate` (capture mode: move) |
//! | Captured variable | `ClosureCapture` (per variable) |
//!
//! ## Diagnostic Options
//!
//! For patterns that cannot be auto-detected, use diagnostic attributes:
//!
//! | Attribute | Description |
//! |-----------|-------------|
//! | `#[trace_borrow(warn)]` | Emit warnings for ambiguous patterns |
//! | `#[trace_borrow(ffi = ["malloc"])]` | Declare known FFI functions |
//! | `#[trace_borrow(unions = ["MyUnion"])]` | Declare known union types |
//! | `#[trace_borrow(statics = ["GLOBAL"])]` | Declare known static variables |
//!
//! ## How It Works
//!
//! The macro transforms functions by:
//!
//! 1. **Parsing** the function into an AST using `syn`
//! 2. **Walking** the AST with `OwnershipVisitor` that maintains:
//! - Unique IDs for each variable (for event correlation)
//! - Scope stack for LIFO drop ordering
//! - Type context (tracks which vars are Weak, Cow, OnceCell, etc.)
//! 3. **Injecting** `borrowscope_runtime::track_*` calls
//! 4. **Generating** drop calls at scope exits in reverse order
//!
//! ### ID-Based Correlation
//!
//! Each variable gets a unique ID, enabling correlation:
//! - Borrows link to their owner's ID
//! - Clones link to their source's ID
//! - Moves link source and destination IDs
//!
//! ## Performance Tips
//!
//! 1. **Use `quiet` mode** for minimal overhead when you only need ownership tracking
//! 2. **Use `filter`** to track only relevant variables (zero overhead for non-matching)
//! 3. **Use `sample`** for high-frequency code paths
//! 4. **Use `debug_only`** to eliminate all overhead in release builds
//! 5. **Use `skip`** to disable noisy features like loops and branches
//!
//! ```ignore
//! // Minimal overhead configuration
//! #[trace_borrow(debug_only, quiet, filter = "important_*")]
//! fn performance_critical() { }
//! ```
//!
//! ## Common Patterns
//!
//! ```ignore
//! // Development: full tracking, debug only
//! #[trace_borrow(debug_only)]
//! fn dev_function() { }
//!
//! // Learning: ownership only, cleaner output
//! #[trace_borrow(quiet)]
//! fn learning_example() { }
//!
//! // Production monitoring: sampled, feature-gated
//! #[trace_borrow(feature = "monitoring", sample = 0.01)]
//! fn production_function() { }
//!
//! // Debugging specific variables
//! #[trace_borrow(filter = "suspect_*", verbose)]
//! fn debug_specific() { }
//! ```
//!
//! ## Limitations
//!
//! - **const fn**: Cannot be used (tracking requires runtime)
//! - **extern fn**: Cannot be used (only Rust ABI supported)
//! - **async fn**: Works but may not capture all ownership across await points
//! - **unsafe fn**: Works but tracking cannot verify safety invariants
//! - **Macros**: Variables created inside macro expansions may not be tracked
//!
//! ## Troubleshooting
//!
//! **No events recorded:**
//! - Ensure `borrowscope_runtime` has `features = ["track"]` enabled
//! - Call `reset()` before the traced function
//! - Check if `debug_only` is set but running in release mode
//!
//! **Too many events:**
//! - Use `quiet` mode or `only = "ownership"`
//! - Use `skip = "loops,branches"` to reduce noise
//! - Use `filter` to track specific variables
//!
//! **Performance issues:**
//! - Use `sample = 0.1` or lower for high-frequency code
//! - Use `debug_only` to disable in release builds
//! - Use `filter` to reduce tracked variables
use TokenStream;
use ;
use quote;
use ;
use OwnershipVisitor;
/// Validate function before transformation
/// Attribute macro to trace ownership and borrowing in a function.
///
/// This macro transforms a function to inject runtime tracking calls that record
/// ownership transfers, borrows, drops, and other operations. The events can be
/// retrieved using `borrowscope_runtime::get_events()`.
///
/// # Basic Usage
///
/// ```ignore
/// use borrowscope_macro::trace_borrow;
/// use borrowscope_runtime::*;
///
/// #[trace_borrow]
/// fn example() {
/// let x = String::from("hello"); // New event
/// let y = &x; // Borrow event
/// let z = x; // Move event
/// } // Drop events
/// ```
///
/// # Attribute Options
///
/// ## `quiet` - Minimal tracking
///
/// Only tracks basic ownership: new, move, drop, borrow.
///
/// ```ignore
/// #[trace_borrow(quiet)]
/// fn minimal() {
/// let x = vec![1, 2, 3];
/// for i in &x { } // Loop NOT tracked
/// }
/// ```
///
/// ## `verbose` - All tracking
///
/// Enables all tracking features (same as default currently).
///
/// ```ignore
/// #[trace_borrow(verbose)]
/// fn everything() { }
/// ```
///
/// ## `skip` - Disable specific features
///
/// Comma-separated list of feature groups to disable.
///
/// ```ignore
/// #[trace_borrow(skip = "loops,branches")]
/// fn skip_noisy() {
/// for i in 0..10 { } // NOT tracked
/// if true { } // NOT tracked
/// }
/// ```
///
/// ## `only` - Enable only specific features
///
/// Comma-separated list of feature groups to enable (all others disabled).
///
/// ```ignore
/// #[trace_borrow(only = "ownership,functions")]
/// fn focused() {
/// let x = 1; // Tracked (ownership)
/// // FnEnter/FnExit tracked (functions)
/// }
/// ```
///
/// # Feature Groups
///
/// | Group | Aliases | What it tracks |
/// |-------|---------|----------------|
/// | `ownership` | - | `let`, moves, drops, borrows |
/// | `smart_pointers` | `pointers` | Rc, Arc, RefCell, Cell |
/// | `loops` | - | for, while, loop |
/// | `branches` | - | if/else, match |
/// | `control_flow` | `control` | break, continue, return |
/// | `try` | - | `?` operator |
/// | `methods` | - | clone, lock, unwrap |
/// | `async` | - | async blocks, await |
/// | `unsafe` | - | unsafe blocks, raw pointers |
/// | `expressions` | `exprs` | struct, tuple, array, range, cast |
/// | `functions` | `fn` | Function entry/exit (off by default) |
///
/// # Conditional Compilation
///
/// | Option | Description |
/// |--------|-------------|
/// | `debug_only` | Only instrument in debug builds |
/// | `release_only` | Only instrument in release builds |
/// | `feature = "name"` | Only instrument when cargo feature is enabled |
///
/// # Limitations
///
/// - Cannot be used on `const fn` (tracking requires runtime)
/// - Cannot be used on `extern` functions
/// - Async functions work but may miss some ownership across await points