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
#![warn(missing_docs)]

/*!
# Example

```
use call_trace::{trace_with, CallContext, Trace};

struct My;

impl My {
    #[inline]
    #[trace_with(self)]
    /// test
    fn foo(&mut self) {
        self.bar();
    }

    #[trace_with(self)]
    fn bar(&mut self) {
        let x = self.baz();
        let y = self.baz();
        println!("x + y = {}", x + y);
    }

    #[trace_with(self)]
    fn baz(&mut self) -> i32 {
        15
    }
}

impl Trace for My {
    fn on_pre(&mut self, ctx: &CallContext) {
        println!("> {:?}", ctx);
    }
    fn on_post(&mut self, ctx: &CallContext) {
        println!("< {:?}", ctx);
    }
}

fn main() {
    My.foo();
}
```

Output

```text
> CallContext { file: "main.rs", line: 13, fn_name: "bar" }
> CallContext { file: "main.rs", line: 20, fn_name: "baz" }
< CallContext { file: "main.rs", line: 20, fn_name: "baz" }
> CallContext { file: "main.rs", line: 20, fn_name: "baz" }
< CallContext { file: "main.rs", line: 20, fn_name: "baz" }
x + y = 30
< CallContext { file: "main.rs", line: 13, fn_name: "bar" }
< CallContext { file: "main.rs", line: 7, fn_name: "foo" }
```
*/

pub use call_trace_macro::trace_with;

/// Tracing interface invoked by `#[trace]` and `#[trace_with]`
pub trait Trace {
    /// Called immediately after entering the function
    fn on_pre(&mut self, ctx: &CallContext);
    /// Called immediately before returning from the function
    fn on_post(&mut self, ctx: &CallContext);
}

#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
/// Contains information about the current call site.
pub struct CallContext {
    /// Current file, as returned by `file!()`
    pub file: &'static str,

    /// Current line, as returned by `line!()`. Will point at the `#[trace_with]` attribute.
    pub line: u32,

    /// Name of the called function. Does not contain the module path.
    pub fn_name: &'static str,
}