call_trace/
lib.rs

1#![warn(missing_docs)]
2
3/*!
4# Example
5
6```
7use call_trace::{trace_with, CallContext, Trace};
8
9struct My;
10
11impl My {
12    #[inline]
13    #[trace_with(self)]
14    /// test
15    fn foo(&mut self) {
16        self.bar();
17    }
18
19    #[trace_with(self)]
20    fn bar(&mut self) {
21        let x = self.baz();
22        let y = self.baz();
23        println!("x + y = {}", x + y);
24    }
25
26    #[trace_with(self)]
27    fn baz(&mut self) -> i32 {
28        15
29    }
30}
31
32impl Trace for My {
33    fn on_pre(&mut self, ctx: &CallContext) {
34        println!("> {:?}", ctx);
35    }
36    fn on_post(&mut self, ctx: &CallContext) {
37        println!("< {:?}", ctx);
38    }
39}
40
41fn main() {
42    My.foo();
43}
44```
45
46Output
47
48```text
49> CallContext { file: "main.rs", line: 13, fn_name: "bar" }
50> CallContext { file: "main.rs", line: 20, fn_name: "baz" }
51< CallContext { file: "main.rs", line: 20, fn_name: "baz" }
52> CallContext { file: "main.rs", line: 20, fn_name: "baz" }
53< CallContext { file: "main.rs", line: 20, fn_name: "baz" }
54x + y = 30
55< CallContext { file: "main.rs", line: 13, fn_name: "bar" }
56< CallContext { file: "main.rs", line: 7, fn_name: "foo" }
57```
58*/
59
60pub use call_trace_macro::trace_with;
61
62/// Tracing interface invoked by `#[trace]` and `#[trace_with]`
63pub trait Trace {
64    /// Called immediately after entering the function
65    fn on_pre(&mut self, ctx: &CallContext);
66    /// Called immediately before returning from the function
67    fn on_post(&mut self, ctx: &CallContext);
68}
69
70#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
71/// Contains information about the current call site.
72pub struct CallContext {
73    /// Current file, as returned by `file!()`
74    pub file: &'static str,
75
76    /// Current line, as returned by `line!()`. Will point at the `#[trace_with]` attribute.
77    pub line: u32,
78
79    /// Name of the called function. Does not contain the module path.
80    pub fn_name: &'static str,
81}