v2 / vlib / v / debug / trace.v
68 lines · 59 sloc · 1.49 KB · 152a97786568c09917641ef7a631714a059f46ef
Raw
1@[has_globals]
2module debug
3
4@[markused]
5__global g_trace = TraceHook{}
6
7type HookFnCall = fn (string)
8
9@[noinit]
10pub struct TraceHook {
11mut:
12 in_hook bool
13pub mut:
14 trace_after_call []HookFnCall
15 trace_before_call []HookFnCall
16}
17
18// after_call_hook calls the registered hook fns
19@[markused]
20fn after_call_hook(fn_name string) {
21 g_trace.in_hook = true
22 for func in g_trace.trace_after_call {
23 func(fn_name)
24 }
25 g_trace.in_hook = false
26}
27
28// before_call_hook calls the registered hook fns
29@[markused]
30fn before_call_hook(fn_name string) {
31 g_trace.in_hook = true
32 for func in g_trace.trace_before_call {
33 func(fn_name)
34 }
35 g_trace.in_hook = false
36}
37
38// add_after_call adds a fn hook to after hook list and returns its id
39@[inline; markused]
40pub fn add_after_call(func HookFnCall) HookFnCall {
41 g_trace.trace_after_call << func
42 return func
43}
44
45// add_before_call adds a fn hook to before hook list and return its id
46@[inline; markused]
47pub fn add_before_call(func HookFnCall) HookFnCall {
48 g_trace.trace_before_call << func
49 return func
50}
51
52// remove_after_call removes a fn hook from after hook list by its idx
53@[inline; markused]
54pub fn remove_after_call(func HookFnCall) {
55 idx := g_trace.trace_after_call.index(func)
56 if idx != -1 {
57 g_trace.trace_after_call.delete(idx)
58 }
59}
60
61// remove_before_call removes a fn hook from before hook list by its idx
62@[inline; markused]
63pub fn remove_before_call(func HookFnCall) {
64 idx := g_trace.trace_before_call.index(func)
65 if idx != -1 {
66 g_trace.trace_before_call.delete(idx)
67 }
68}
69