wide-log-macros 0.2.0

Macros for a fast wide event logging crate a la loggingsucks.com
Documentation
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
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
use proc_macro2::TokenStream as TokenStream2;
use quote::{format_ident, quote};

use crate::parse::{JsonNode, Marker, Number};

pub fn generate(root: JsonNode, tokio: bool) -> Result<TokenStream2, syn::Error> {
    let mut ctx = GenContext::new();
    ctx.walk(&root, &[])?;

    ctx.auto_add_duration(&root)?;

    ctx.validate()?;

    Ok(ctx.emit(tokio))
}

#[derive(Clone, Debug)]
struct KeyEntry {
    json_name: String,
    variant: String,
}

#[derive(Clone, Debug)]
struct PathEntry {
    dotted: String,
    segments: Vec<String>,
}

#[derive(Clone, Debug)]
struct DefaultEntry {
    segments: Vec<String>,
    value: DefaultValue,
}

#[derive(Clone, Debug)]
enum DefaultValue {
    Str(String),
    Bool(bool),
    Int(i64),
    Uint(u64),
    Float(f64),
}

struct GenContext {
    keys: Vec<KeyEntry>,
    key_index: std::collections::BTreeMap<String, usize>,
    paths: Vec<PathEntry>,
    path_index: std::collections::BTreeMap<String, usize>,
    defaults: Vec<DefaultEntry>,
    duration_segments: Vec<String>,
    has_duration_marker: bool,
}

impl GenContext {
    fn new() -> Self {
        Self {
            keys: Vec::new(),
            key_index: std::collections::BTreeMap::new(),
            paths: Vec::new(),
            path_index: std::collections::BTreeMap::new(),
            defaults: Vec::new(),
            duration_segments: Vec::new(),
            has_duration_marker: false,
        }
    }

    fn add_key(&mut self, name: &str) -> usize {
        if let Some(&idx) = self.key_index.get(name) {
            return idx;
        }
        let idx = self.keys.len();
        let variant = to_pascal_case(name);
        self.keys.push(KeyEntry {
            json_name: name.to_string(),
            variant,
        });
        self.key_index.insert(name.to_string(), idx);
        idx
    }

    fn add_path(&mut self, segments: &[String]) {
        let dotted = segments.join(".");
        if self.path_index.contains_key(&dotted) {
            return;
        }
        let idx = self.paths.len();
        self.paths.push(PathEntry {
            dotted,
            segments: segments.to_vec(),
        });
        self.path_index.insert(self.paths[idx].dotted.clone(), idx);
    }

    fn walk(&mut self, node: &JsonNode, path: &[String]) -> Result<(), syn::Error> {
        match node {
            JsonNode::Object(entries) => {
                if path.is_empty() {
                    for (k, v) in entries {
                        let mut p = path.to_vec();
                        p.push(k.clone());
                        self.walk(v, &p)?;
                    }
                } else {
                    self.add_key(&path[path.len() - 1]);
                    self.add_path(path);
                    for (k, v) in entries {
                        let mut p = path.to_vec();
                        p.push(k.clone());
                        self.walk(v, &p)?;
                    }
                }
            }
            JsonNode::Null => {
                self.add_key(&path[path.len() - 1]);
                self.add_path(path);
            }
            JsonNode::Bool(b) => {
                self.add_key(&path[path.len() - 1]);
                self.add_path(path);
                self.defaults.push(DefaultEntry {
                    segments: path.to_vec(),
                    value: DefaultValue::Bool(*b),
                });
            }
            JsonNode::Number(n) => {
                self.add_key(&path[path.len() - 1]);
                self.add_path(path);
                let dv = match n {
                    Number::Int(x) => DefaultValue::Int(*x),
                    Number::Uint(x) => DefaultValue::Uint(*x),
                    Number::Float(x) => DefaultValue::Float(*x),
                };
                self.defaults.push(DefaultEntry {
                    segments: path.to_vec(),
                    value: dv,
                });
            }
            JsonNode::Str(s) => {
                self.add_key(&path[path.len() - 1]);
                self.add_path(path);
                self.defaults.push(DefaultEntry {
                    segments: path.to_vec(),
                    value: DefaultValue::Str(s.clone()),
                });
            }
            JsonNode::Marker(m) => {
                self.add_key(&path[path.len() - 1]);
                self.add_path(path);
                match m {
                    Marker::Duration => {
                        self.has_duration_marker = true;
                        self.duration_segments = path.to_vec();
                    }
                    Marker::Counter => {}
                }
            }
        }
        Ok(())
    }

    fn auto_add_duration(&mut self, root: &JsonNode) -> Result<(), syn::Error> {
        match root {
            JsonNode::Object(entries) => {
                let has_duration = entries.iter().any(|(k, _)| k == "duration");
                if !has_duration {
                    self.add_duration_subtree("total_ms");
                } else {
                    let duration_node = entries
                        .iter()
                        .find(|(k, _)| k == "duration")
                        .map(|(_, v)| v)
                        .unwrap();
                    self.resolve_duration_subtree(duration_node)?;
                }
            }
            _ => unreachable!(),
        }
        Ok(())
    }

    fn add_duration_subtree(&mut self, leaf: &str) {
        let duration_seg = "duration".to_string();
        let leaf_seg = leaf.to_string();
        self.add_key(&duration_seg);
        self.add_key(&leaf_seg);
        let duration_path = vec![duration_seg, leaf_seg];
        self.add_path(&[duration_path[0].clone()]);
        self.add_path(&duration_path);
        self.has_duration_marker = true;
        self.duration_segments = duration_path;
    }

    fn resolve_duration_subtree(&mut self, node: &JsonNode) -> Result<(), syn::Error> {
        match node {
            JsonNode::Object(entries) => {
                let duration_seg = "duration".to_string();
                self.add_key(&duration_seg);
                self.add_path(&[duration_seg.clone()]);

                if entries.is_empty() {
                    self.add_duration_subtree("total_ms");
                    return Ok(());
                }

                if self.has_duration_marker {
                    for (k, v) in entries {
                        let p = vec![duration_seg.clone(), k.clone()];
                        self.walk(v, &p)?;
                    }
                    return Ok(());
                }

                let duration_marker_leaf = entries
                    .iter()
                    .find(|(_, v)| matches!(v, JsonNode::Marker(Marker::Duration)))
                    .map(|(k, _)| k.clone());

                if let Some(_leaf) = duration_marker_leaf {
                    for (k, v) in entries {
                        let p = vec![duration_seg.clone(), k.clone()];
                        self.walk(v, &p)?;
                    }
                    return Ok(());
                }

                let total_ms_entry = entries.iter().find(|(k, _)| k == "total_ms");

                if total_ms_entry.is_some() {
                    for (k, v) in entries {
                        if k == "total_ms" {
                            self.add_key("total_ms");
                            self.add_path(&[duration_seg.clone(), "total_ms".to_string()]);
                            self.has_duration_marker = true;
                            self.duration_segments =
                                vec![duration_seg.clone(), "total_ms".to_string()];
                        } else {
                            let p = vec![duration_seg.clone(), k.clone()];
                            self.walk(v, &p)?;
                        }
                    }
                    return Ok(());
                }

                let non_duration_leaves: Vec<&String> = entries
                    .iter()
                    .filter(|(_, v)| !matches!(v, JsonNode::Marker(Marker::Duration)))
                    .map(|(k, _)| k)
                    .collect();

                if non_duration_leaves.len() == 1 {
                    let leaf = non_duration_leaves[0].clone();
                    self.add_duration_subtree(&leaf);
                    let other_entries: Vec<&(String, JsonNode)> =
                        entries.iter().filter(|(k, _)| *k != leaf).collect();
                    for (k, v) in other_entries {
                        let p = vec![duration_seg.clone(), k.clone()];
                        self.walk(v, &p)?;
                    }
                    return Ok(());
                }

                Err(syn::Error::new(
                    proc_macro2::Span::call_site(),
                    "duration object has multiple non-duration leaves and no duration! marker; \
                     specify exactly one duration! leaf, or use \"total_ms\": duration!",
                ))
            }
            _ => {
                self.add_duration_subtree("total_ms");
                Ok(())
            }
        }
    }

    fn validate(&self) -> Result<(), syn::Error> {
        if !self.has_duration_marker {
            return Err(syn::Error::new(
                proc_macro2::Span::call_site(),
                "internal error: no duration path was set",
            ));
        }
        if self.duration_segments.is_empty() {
            return Err(syn::Error::new(
                proc_macro2::Span::call_site(),
                "internal error: duration path is empty",
            ));
        }
        Ok(())
    }

    fn emit(&self, tokio: bool) -> TokenStream2 {
        let enum_variants: Vec<syn::Ident> = self
            .keys
            .iter()
            .map(|k| format_ident!("{}", k.variant))
            .collect();
        let enum_strs: Vec<String> = self.keys.iter().map(|k| k.json_name.clone()).collect();
        let max_keys = self.keys.len();

        let as_str_arms: Vec<TokenStream2> = enum_variants
            .iter()
            .zip(enum_strs.iter())
            .map(|(v, s)| quote! { EventKey::#v => #s })
            .collect();

        let duration_path_idents: Vec<TokenStream2> = self
            .duration_segments
            .iter()
            .map(|s| {
                let ident = format_ident!("{}", to_pascal_case(s));
                quote! { EventKey::#ident }
            })
            .collect();

        let resolve_arms: Vec<TokenStream2> = self
            .paths
            .iter()
            .map(|p| {
                let dotted = &p.dotted;
                let segs: Vec<TokenStream2> = p
                    .segments
                    .iter()
                    .map(|s| {
                        let ident = format_ident!("{}", to_pascal_case(s));
                        quote! { EventKey::#ident }
                    })
                    .collect();
                quote! { #dotted => &[#(#segs),*] }
            })
            .collect();

        let default_stmts: Vec<TokenStream2> = self
            .defaults
            .iter()
            .map(|d| {
                let segs: Vec<TokenStream2> = d
                    .segments
                    .iter()
                    .map(|s| {
                        let ident = format_ident!("{}", to_pascal_case(s));
                        quote! { EventKey::#ident }
                    })
                    .collect();
                let val = match &d.value {
                    DefaultValue::Str(s) => quote! { ::wide_log::Value::from(#s) },
                    DefaultValue::Bool(b) => quote! { ::wide_log::Value::from(#b) },
                    DefaultValue::Int(n) => quote! { ::wide_log::Value::from(#n) },
                    DefaultValue::Uint(n) => quote! { ::wide_log::Value::from(#n) },
                    DefaultValue::Float(n) => {
                        let nf = *n;
                        quote! { ::wide_log::Value::from(#nf) }
                    }
                };
                quote! {
                    inner.add_path(&[#(#segs),*], #val);
                }
            })
            .collect();

        let enum_def = quote! {
            #[derive(Copy, Clone, PartialEq, Eq, Debug)]
            #[repr(u8)]
            pub enum EventKey {
                #(#enum_variants),*
            }
        };

        let key_impl = quote! {
            impl ::wide_log::Key for EventKey {
                fn as_str(self) -> &'static str {
                    match self {
                        #(#as_str_arms,)*
                    }
                }
                const MAX_KEYS: usize = #max_keys;
                fn as_index(self) -> usize { self as usize }
                const DURATION_PATH: &'static [Self] = &[#(#duration_path_idents),*];
            }
        };

        let resolve_fn = quote! {
            #[inline(always)]
            pub fn __wl_resolve_path(path: &str) -> &'static [EventKey] {
                match path {
                    #(#resolve_arms,)*
                    _ => panic!("unknown wide-log key path: {path}"),
                }
            }
        };

        let thread_local = quote! {
            thread_local! {
                static CURRENT_EVENT: ::wide_log::ContextCell<::wide_log::WideEvent<EventKey>> =
                    const { ::wide_log::ContextCell::new() };
            }
        };

        let default_emit = quote! {
            fn default_emit(ev: &::wide_log::WideEvent<EventKey>) {
                if let Ok(json) = ev.to_json() {
                    ::tracing::info!(target: "wide_log", event = %json);
                }
            }
        };

        let guard_struct = quote! {
            pub struct WideLogGuard<F: FnOnce(&::wide_log::WideEvent<EventKey>) + Send + 'static> {
                inner: ::std::boxed::Box<::wide_log::ScopedGuard<EventKey, F>>,
                prev_ptr: *mut ::wide_log::WideEvent<EventKey>,
            }

            // SAFETY: The raw pointer `prev_ptr` is only accessed via the
            // thread-local `CURRENT_EVENT` cell, which is per-thread. When the
            // guard is moved across threads (in async), the task-local
            // `TASK_EVENT` moves with the task. The pointer is never
            // dereferenced from a different thread than the one that set it.
            unsafe impl<F: FnOnce(&::wide_log::WideEvent<EventKey>) + Send + 'static> Send
                for WideLogGuard<F> {}
        };

        let guard_new = quote! {
            impl WideLogGuard<fn(&::wide_log::WideEvent<EventKey>)> {
                pub fn new() -> Self {
                    Self::new_with_emit(default_emit)
                }
            }
        };

        let guard_new_with_emit = if default_stmts.is_empty() {
            quote! {
                impl<F: FnOnce(&::wide_log::WideEvent<EventKey>) + Send + 'static> WideLogGuard<F> {
                    pub fn new_with_emit(emit_fn: F) -> Self {
                        let inner = ::std::boxed::Box::new(::wide_log::ScopedGuard::new(emit_fn));
                        let ptr: *mut ::wide_log::WideEvent<EventKey> = {
                            use ::std::ops::Deref;
                            let guard_ref: &::wide_log::ScopedGuard<EventKey, F> = inner.deref();
                            guard_ref.deref() as *const _ as *mut _
                        };
                        let prev_ptr = CURRENT_EVENT.with(|c| c.replace(ptr));
                        Self { inner, prev_ptr }
                    }
                }
            }
        } else {
            quote! {
                impl<F: FnOnce(&::wide_log::WideEvent<EventKey>) + Send + 'static> WideLogGuard<F> {
                    pub fn new_with_emit(emit_fn: F) -> Self {
                        let mut inner = ::std::boxed::Box::new(::wide_log::ScopedGuard::new(emit_fn));
                        {
                            use ::std::ops::DerefMut;
                            let event: &mut ::wide_log::WideEvent<EventKey> = inner.deref_mut();
                            #(#default_stmts)*
                        }
                        let ptr: *mut ::wide_log::WideEvent<EventKey> = {
                            use ::std::ops::Deref;
                            let guard_ref: &::wide_log::ScopedGuard<EventKey, F> = inner.deref();
                            guard_ref.deref() as *const _ as *mut _
                        };
                        let prev_ptr = CURRENT_EVENT.with(|c| c.replace(ptr));
                        Self { inner, prev_ptr }
                    }
                }
            }
        };

        let guard_drop = quote! {
            impl<F: FnOnce(&::wide_log::WideEvent<EventKey>) + Send + 'static> Drop for WideLogGuard<F> {
                fn drop(&mut self) {
                    CURRENT_EVENT.with(|c| c.restore(self.prev_ptr));
                }
            }
        };

        let current_fn = if tokio {
            quote! {
                pub fn current() -> Option<&'static mut ::wide_log::WideEvent<EventKey>> {
                    if let Ok(Some(ptr)) = TASK_EVENT.try_with(|c| c.get()) {
                        return Some(unsafe { &mut *ptr });
                    }
                    CURRENT_EVENT.with(|c| unsafe { c.deref_mut() })
                }
            }
        } else {
            quote! {
                pub fn current() -> Option<&'static mut ::wide_log::WideEvent<EventKey>> {
                    CURRENT_EVENT.with(|c| unsafe { c.deref_mut() })
                }
            }
        };

        let tokio_code = if tokio {
            let task_local = quote! {
                ::wide_log::__re_exports::tokio::task_local! {
                    static TASK_EVENT: ::wide_log::ContextCell<::wide_log::WideEvent<EventKey>>;
                }
            };

            let scope_fns = quote! {
                pub async fn scope<F, E>(emit_fn: E, f: F) -> F::Output
                where
                    F: ::std::future::Future,
                    E: FnOnce(&::wide_log::WideEvent<EventKey>) + Send + 'static,
                {
                    let mut inner = ::std::boxed::Box::new(::wide_log::ScopedGuard::new(emit_fn));
                    {
                        use ::std::ops::DerefMut;
                        let event: &mut ::wide_log::WideEvent<EventKey> = inner.deref_mut();
                        #(#default_stmts)*
                    }
                    let ptr: *mut ::wide_log::WideEvent<EventKey> = {
                        use ::std::ops::Deref;
                        let guard_ref: &::wide_log::ScopedGuard<EventKey, E> = inner.deref();
                        guard_ref.deref() as *const _ as *mut _
                    };
                    let cell = ::wide_log::ContextCell::new();
                    cell.replace(ptr);
                    let _inner = inner;
                    TASK_EVENT.scope(cell, f).await
                }

                pub async fn scope_default<F: ::std::future::Future>(f: F) -> F::Output {
                    scope(default_emit, f).await
                }
            };

            let middleware = quote! {
                use std::task::{Context, Poll};
                use std::pin::Pin;

                #[derive(Clone)]
                pub struct WideLogLayer;

                impl<S> ::wide_log::__re_exports::tower::Layer<S> for WideLogLayer {
                    type Service = WideLogMiddleware<S>;
                    fn layer(&self, inner: S) -> Self::Service {
                        WideLogMiddleware { inner }
                    }
                }

                #[derive(Clone)]
                pub struct WideLogMiddleware<S> {
                    inner: S,
                }

                impl<S, ReqBody, ResBody, Err> ::wide_log::__re_exports::tower::Service<ReqBody> for WideLogMiddleware<S>
                where
                    S: ::wide_log::__re_exports::tower::Service<ReqBody, Response = ResBody, Error = Err>,
                    S::Future: Send + 'static,
                    ResBody: Send + 'static,
                    Err: Send + 'static,
                {
                    type Response = ResBody;
                    type Error = Err;
                    type Future = WideLogFuture<ResBody, Err>;

                    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
                        self.inner.poll_ready(cx)
                    }

                    fn call(&mut self, req: ReqBody) -> Self::Future {
                        let inner_fut = self.inner.call(req);
                        WideLogFuture::new(inner_fut)
                    }
                }

                pub struct WideLogFuture<ResBody, Err> {
                    inner: ::std::pin::Pin<::std::boxed::Box<dyn ::std::future::Future<Output = Result<ResBody, Err>> + Send>>,
                }

                impl<ResBody, Err> WideLogFuture<ResBody, Err>
                where
                    ResBody: Send + 'static,
                    Err: Send + 'static,
                {
                    fn new<F>(inner: F) -> Self
                    where
                        F: ::std::future::Future<Output = Result<ResBody, Err>> + Send + 'static,
                    {
                        Self {
                            inner: ::std::boxed::Box::pin(scope_default(async move { inner.await })),
                        }
                    }
                }

                impl<ResBody, Err> Future for WideLogFuture<ResBody, Err> {
                    type Output = Result<ResBody, Err>;

                    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
                        self.inner.as_mut().poll(cx)
                    }
                }
            };

            quote! {
                #task_local
                #scope_fns
                #middleware
            }
        } else {
            TokenStream2::new()
        };

        let macros = quote! {
            #[macro_export]
            macro_rules! wl_set {
                ($path:literal, $value:expr) => {
                    if let Some(ev) = current() {
                        ev.add_path(__wl_resolve_path($path), $value);
                    }
                };
            }

            #[macro_export]
            macro_rules! wl_inc {
                ($path:literal) => {
                    if let Some(ev) = current() {
                        ev.inc_path(__wl_resolve_path($path));
                    }
                };
            }

            #[macro_export]
            macro_rules! wl_dec {
                ($path:literal) => {
                    if let Some(ev) = current() {
                        ev.dec_path(__wl_resolve_path($path));
                    }
                };
            }

            #[macro_export]
            macro_rules! wl_add {
                ($path:literal, $n:expr) => {
                    if let Some(ev) = current() {
                        ev.add_n_path(__wl_resolve_path($path), $n);
                    }
                };
            }

            #[macro_export]
            macro_rules! wl_null {
                ($path:literal) => {
                    if let Some(ev) = current() {
                        ev.add_path(__wl_resolve_path($path), ());
                    }
                };
            }

            #[macro_export]
            macro_rules! info {
                ($msg:literal) => {
                    if let Some(ev) = current() {
                        ev.append_log_entry("info", $msg);
                    }
                };
                ($fmt:literal, $($arg:tt)*) => {
                    if let Some(ev) = current() {
                        ev.append_log_entry("info", &format!($fmt, $($arg)*));
                    }
                };
            }

            #[macro_export]
            macro_rules! warn {
                ($msg:literal) => {
                    if let Some(ev) = current() {
                        ev.append_log_entry("warn", $msg);
                    }
                };
                ($fmt:literal, $($arg:tt)*) => {
                    if let Some(ev) = current() {
                        ev.append_log_entry("warn", &format!($fmt, $($arg)*));
                    }
                };
            }

            #[macro_export]
            macro_rules! error {
                ($msg:literal) => {
                    if let Some(ev) = current() {
                        ev.append_log_entry("error", $msg);
                    }
                };
                ($fmt:literal, $($arg:tt)*) => {
                    if let Some(ev) = current() {
                        ev.append_log_entry("error", &format!($fmt, $($arg)*));
                    }
                };
            }

            #[macro_export]
            macro_rules! debug {
                ($msg:literal) => {
                    if let Some(ev) = current() {
                        ev.append_log_entry("debug", $msg);
                    }
                };
                ($fmt:literal, $($arg:tt)*) => {
                    if let Some(ev) = current() {
                        ev.append_log_entry("debug", &format!($fmt, $($arg)*));
                    }
                };
            }

            #[macro_export]
            macro_rules! trace {
                ($msg:literal) => {
                    if let Some(ev) = current() {
                        ev.append_log_entry("trace", $msg);
                    }
                };
                ($fmt:literal, $($arg:tt)*) => {
                    if let Some(ev) = current() {
                        ev.append_log_entry("trace", &format!($fmt, $($arg)*));
                    }
                };
            }
        };

        quote! {
            #enum_def
            #key_impl
            #resolve_fn
            #thread_local
            #default_emit
            #guard_struct
            #guard_new
            #guard_new_with_emit
            #guard_drop
            #current_fn
            #tokio_code
            #macros
        }
    }
}

fn to_pascal_case(name: &str) -> String {
    let mut result = String::new();
    for word in name.split(|c| c == '_' || c == '.') {
        if word.is_empty() {
            continue;
        }
        let mut chars = word.chars();
        if let Some(first) = chars.next() {
            result.extend(first.to_uppercase());
            result.extend(chars);
        }
    }
    if is_rust_keyword(&result) {
        result.push('_');
    }
    result
}

fn is_rust_keyword(s: &str) -> bool {
    matches!(
        s,
        "as" | "break"
            | "const"
            | "continue"
            | "crate"
            | "else"
            | "enum"
            | "extern"
            | "false"
            | "fn"
            | "for"
            | "if"
            | "impl"
            | "in"
            | "let"
            | "loop"
            | "match"
            | "mod"
            | "move"
            | "mut"
            | "pub"
            | "ref"
            | "return"
            | "self"
            | "Self"
            | "static"
            | "struct"
            | "super"
            | "trait"
            | "true"
            | "type"
            | "unsafe"
            | "use"
            | "where"
            | "while"
            | "async"
            | "await"
            | "dyn"
            | "abstract"
            | "become"
            | "box"
            | "do"
            | "final"
            | "macro"
            | "override"
            | "priv"
            | "typeof"
            | "unsized"
            | "virtual"
            | "yield"
            | "try"
            | "union"
    )
}