redactable-derive 0.7.1

Derive macros for the redactable crate
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
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
//! Derive macros for `redactable`.
//!
//! This crate generates traversal code behind `#[derive(Sensitive)]`,
//! `#[derive(SensitiveDisplay)]`, `#[derive(NotSensitive)]`, and
//! `#[derive(NotSensitiveDisplay)]`. It:
//! - reads `#[sensitive(...)]` and `#[not_sensitive]` attributes
//! - emits trait implementations for redaction and logging integration
//!
//! It does **not** define policy markers or text policies. Those live in the main
//! `redactable` crate and are applied at runtime.

// <https://doc.rust-lang.org/rustc/lints/listing/allowed-by-default.html>
#![warn(
    anonymous_parameters,
    bare_trait_objects,
    elided_lifetimes_in_paths,
    missing_copy_implementations,
    rust_2018_idioms,
    trivial_casts,
    trivial_numeric_casts,
    unreachable_pub,
    unsafe_code,
    unused_extern_crates,
    unused_import_braces
)]
// <https://rust-lang.github.io/rust-clippy/stable>
#![warn(
    clippy::all,
    clippy::cargo,
    clippy::dbg_macro,
    clippy::float_cmp_const,
    clippy::get_unwrap,
    clippy::mem_forget,
    clippy::nursery,
    clippy::pedantic,
    clippy::todo,
    clippy::unwrap_used,
    clippy::uninlined_format_args
)]
// Allow some clippy lints
#![allow(
    clippy::default_trait_access,
    clippy::doc_markdown,
    clippy::if_not_else,
    clippy::module_name_repetitions,
    clippy::multiple_crate_versions,
    clippy::must_use_candidate,
    clippy::needless_pass_by_value,
    clippy::needless_ifs,
    clippy::use_self,
    clippy::cargo_common_metadata,
    clippy::missing_errors_doc,
    clippy::enum_glob_use,
    clippy::struct_excessive_bools,
    clippy::missing_const_for_fn,
    clippy::redundant_pub_crate,
    clippy::result_large_err,
    clippy::future_not_send,
    clippy::option_if_let_else,
    clippy::from_over_into,
    clippy::manual_inspect
)]
// Allow some lints while testing
#![cfg_attr(test, allow(clippy::non_ascii_literal, clippy::unwrap_used))]

#[allow(unused_extern_crates)]
extern crate proc_macro;

use proc_macro_crate::{FoundCrate, crate_name};
#[cfg(feature = "slog")]
use proc_macro2::Span;
use proc_macro2::{Ident, TokenStream};
use quote::{format_ident, quote};
#[cfg(feature = "slog")]
use syn::parse_quote;
use syn::{
    Data, DataEnum, DataStruct, DeriveInput, Fields, Result, parse_macro_input, spanned::Spanned,
};

mod container;
mod derive_enum;
mod derive_struct;
mod generics;
mod redacted_display;
mod strategy;
mod transform;
mod types;
use container::{ContainerOptions, parse_container_options};
use derive_enum::derive_enum;
use derive_struct::derive_struct;
use generics::{
    add_container_bounds, add_debug_bounds, add_display_bounds, add_policy_applicable_bounds,
    add_policy_applicable_ref_bounds, add_redacted_display_bounds, collect_generics_from_type,
};
use redacted_display::derive_redacted_display;

/// Derives `redactable::RedactableWithMapper` (and related impls) for structs and enums.
///
/// # Container Attributes
///
/// These attributes are placed on the struct/enum itself:
///
/// - `#[sensitive(dual)]` - Use when deriving both `Sensitive` and `SensitiveDisplay` on the same
///   type. `Sensitive` skips its `Debug` impl (letting `SensitiveDisplay` provide it), and
///   `SensitiveDisplay` skips its `slog`/`tracing` impls (letting `Sensitive` provide them).
///
/// # Field Attributes
///
/// - **No annotation**: The field is traversed by default. Scalars pass through unchanged; nested
///   structs/enums are walked using `RedactableWithMapper` (so external types must implement it).
///
/// - `#[sensitive(Secret)]`: For scalar types (i32, bool, char, etc.), redacts to default values
///   (0, false, '*'). For string-like types, applies full redaction to `"[REDACTED]"`.
///
/// - `#[sensitive(Policy)]`: Applies the policy's redaction rules to string-like
///   values. Works for `String`, `Option<String>`, `Vec<String>`, `Box<String>`. Scalars can only
///   use `#[sensitive(Secret)]`.
///
/// - `#[not_sensitive]`: Explicit passthrough - the field is not transformed at all. Use this
///   for foreign types that don't implement `RedactableWithMapper`. This is equivalent to wrapping
///   the field type in `NotSensitiveValue<T>`, but without changing the type signature.
///
/// Unions are rejected at compile time.
///
/// # Generated Impls
///
/// - `RedactableWithMapper`: always generated.
/// - `Debug`: redacted in production, actual values in test/testing builds. Skipped when
///   `#[sensitive(dual)]` is set.
/// - `slog::Value` + `SlogRedacted` (requires `slog` feature): implemented by cloning the value
///   and routing it through `redactable::slog::SlogRedactedExt`. Requires `Clone` and
///   `serde::Serialize` because it emits structured JSON. The derive first looks for a top-level
///   `slog` crate; if not found, it checks the `REDACTABLE_SLOG_CRATE` env var for an alternate
///   path (e.g., `my_log::slog`). If neither is available, compilation fails with a clear error.
/// - `TracingRedacted` (requires `tracing` feature): marker trait.
#[proc_macro_derive(Sensitive, attributes(sensitive, not_sensitive))]
pub fn derive_sensitive_container(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    match expand(input, DeriveKind::Sensitive) {
        Ok(tokens) => tokens.into(),
        Err(err) => err.into_compile_error().into(),
    }
}

/// Derives a no-op `redactable::RedactableWithMapper` implementation, along with
/// `slog::Value` / `SlogRedacted` and `TracingRedacted`.
///
/// This is useful for types that are known to be non-sensitive but still need to
/// satisfy `RedactableWithMapper` / `Redactable` bounds. Because the type has no
/// sensitive data, logging integration works without wrappers.
///
/// # Generated Impls
///
/// - `RedactableWithMapper`: no-op passthrough (the type has no sensitive data)
/// - `slog::Value` and `SlogRedacted` (behind `cfg(feature = "slog")`): serializes the value
///   directly as structured JSON without redaction (same format as `Sensitive`, but skips
///   the redaction step). Requires `Serialize` on the type.
/// - `TracingRedacted` (behind `cfg(feature = "tracing")`): marker trait
///
/// `NotSensitive` does **not** generate a `Debug` impl - there's nothing to redact.
/// Use `#[derive(Debug)]` when needed.
///
/// # Rejected Attributes
///
/// `#[sensitive]` and `#[not_sensitive]` attributes are rejected on both the container
/// and its fields - the former is wrong (the type is explicitly non-sensitive), the
/// latter is redundant (the entire type is already non-sensitive).
///
/// Unions are rejected at compile time.
#[proc_macro_derive(NotSensitive, attributes(not_sensitive))]
pub fn derive_not_sensitive(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    match expand_not_sensitive(input) {
        Ok(tokens) => tokens.into(),
        Err(err) => err.into_compile_error().into(),
    }
}

/// Rejects `#[sensitive]` and `#[not_sensitive]` attributes on a non-sensitive type.
///
/// Checks both container-level and field-level attributes. `#[sensitive]` is wrong
/// because the type is explicitly non-sensitive; `#[not_sensitive]` is redundant
/// because the entire type is already non-sensitive.
fn reject_sensitivity_attrs(attrs: &[syn::Attribute], data: &Data, macro_name: &str) -> Result<()> {
    let check_attr = |attr: &syn::Attribute| -> Result<()> {
        if attr.path().is_ident("sensitive") {
            return Err(syn::Error::new(
                attr.span(),
                format!("`#[sensitive]` attributes are not allowed on `{macro_name}` types"),
            ));
        }
        if attr.path().is_ident("not_sensitive") {
            return Err(syn::Error::new(
                attr.span(),
                format!(
                    "`#[not_sensitive]` attributes are not needed on `{macro_name}` types (the entire type is already non-sensitive)"
                ),
            ));
        }
        Ok(())
    };

    for attr in attrs {
        check_attr(attr)?;
    }

    match data {
        Data::Struct(data) => {
            for field in &data.fields {
                for attr in &field.attrs {
                    check_attr(attr)?;
                }
            }
        }
        Data::Enum(data) => {
            for variant in &data.variants {
                for field in &variant.fields {
                    for attr in &field.attrs {
                        check_attr(attr)?;
                    }
                }
            }
        }
        Data::Union(_) => {}
    }

    Ok(())
}

fn expand_not_sensitive(input: DeriveInput) -> Result<TokenStream> {
    let DeriveInput {
        ident,
        generics,
        data,
        attrs,
        ..
    } = input;

    // Reject unions
    if let Data::Union(u) = &data {
        return Err(syn::Error::new(
            u.union_token.span(),
            "`NotSensitive` cannot be derived for unions",
        ));
    }

    reject_sensitivity_attrs(&attrs, &data, "NotSensitive")?;

    let crate_root = crate_root();

    // RedactableWithMapper impl (no-op passthrough)
    let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
    let container_impl = quote! {
        impl #impl_generics #crate_root::RedactableWithMapper for #ident #ty_generics #where_clause {
            fn redact_with<M: #crate_root::RedactableMapper>(self, _mapper: &M) -> Self {
                self
            }
        }
    };

    // slog impl - serialize directly as structured JSON (no redaction needed)
    #[cfg(feature = "slog")]
    let slog_impl = {
        let slog_crate = slog_crate()?;
        let mut slog_generics = generics.clone();
        let (_, ty_generics, _) = slog_generics.split_for_impl();
        let self_ty: syn::Type = parse_quote!(#ident #ty_generics);
        slog_generics
            .make_where_clause()
            .predicates
            .push(parse_quote!(#self_ty: ::serde::Serialize));
        let (slog_impl_generics, slog_ty_generics, slog_where_clause) =
            slog_generics.split_for_impl();
        quote! {
            impl #slog_impl_generics #slog_crate::Value for #ident #slog_ty_generics #slog_where_clause {
                fn serialize(
                    &self,
                    _record: &#slog_crate::Record<'_>,
                    key: #slog_crate::Key,
                    serializer: &mut dyn #slog_crate::Serializer,
                ) -> #slog_crate::Result {
                    #crate_root::slog::__slog_serialize_not_sensitive(self, _record, key, serializer)
                }
            }

            impl #slog_impl_generics #crate_root::slog::SlogRedacted for #ident #slog_ty_generics #slog_where_clause {}
        }
    };

    #[cfg(not(feature = "slog"))]
    let slog_impl = quote! {};

    // tracing impl
    #[cfg(feature = "tracing")]
    let tracing_impl = {
        let (tracing_impl_generics, tracing_ty_generics, tracing_where_clause) =
            generics.split_for_impl();
        quote! {
            impl #tracing_impl_generics #crate_root::tracing::TracingRedacted for #ident #tracing_ty_generics #tracing_where_clause {}
        }
    };

    #[cfg(not(feature = "tracing"))]
    let tracing_impl = quote! {};

    Ok(quote! {
        #container_impl
        #slog_impl
        #tracing_impl
    })
}

/// Derives `redactable::RedactableWithFormatter` for types with no sensitive data.
///
/// This is the display counterpart to `NotSensitive`. Use it when you have a type
/// with no sensitive data that needs logging integration (e.g., for use with slog).
///
/// Unlike `SensitiveDisplay`, this derive does **not** require a display template.
/// Instead, it delegates directly to the type's existing `Display` implementation.
///
/// # Required Bounds
///
/// The type must implement `Display`. This is required because `RedactableWithFormatter` delegates
/// to `Display::fmt`.
///
/// # Generated Impls
///
/// - `RedactableWithMapper`: no-op passthrough (allows use inside `Sensitive` containers)
/// - `RedactableWithFormatter`: delegates to `Display::fmt`
/// - `slog::Value` and `SlogRedacted` (behind `cfg(feature = "slog")`): uses `RedactableWithFormatter` output
/// - `TracingRedacted` (behind `cfg(feature = "tracing")`): marker trait
///
/// # Debug
///
/// `NotSensitiveDisplay` does **not** generate a `Debug` impl - there's nothing to redact.
/// Use `#[derive(Debug)]` alongside `NotSensitiveDisplay` when needed.
///
/// # Rejected Attributes
///
/// `#[sensitive]` and `#[not_sensitive]` attributes are rejected on both the container
/// and its fields - the former is wrong (the type is explicitly non-sensitive), the
/// latter is redundant (the entire type is already non-sensitive).
///
/// # Example
///
/// ```ignore
/// use redactable::NotSensitiveDisplay;
///
/// #[derive(Clone, NotSensitiveDisplay)]
/// #[display(fmt = "RetryDecision")]  // Or use displaydoc/thiserror for Display impl
/// enum RetryDecision {
///     Retry,
///     Abort,
/// }
/// ```
#[proc_macro_derive(NotSensitiveDisplay)]
pub fn derive_not_sensitive_display(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    match expand_not_sensitive_display(input) {
        Ok(tokens) => tokens.into(),
        Err(err) => err.into_compile_error().into(),
    }
}

fn expand_not_sensitive_display(input: DeriveInput) -> Result<TokenStream> {
    let DeriveInput {
        ident,
        generics,
        data,
        attrs,
        ..
    } = input;

    // Reject unions
    if let Data::Union(u) = &data {
        return Err(syn::Error::new(
            u.union_token.span(),
            "`NotSensitiveDisplay` cannot be derived for unions",
        ));
    }

    reject_sensitivity_attrs(&attrs, &data, "NotSensitiveDisplay")?;

    let crate_root = crate_root();

    // Generate the RedactableWithMapper no-op passthrough impl
    // This is always generated, allowing NotSensitiveDisplay to be used inside Sensitive containers
    let (container_impl_generics, container_ty_generics, container_where_clause) =
        generics.split_for_impl();
    let container_impl = quote! {
        impl #container_impl_generics #crate_root::RedactableWithMapper for #ident #container_ty_generics #container_where_clause {
            fn redact_with<M: #crate_root::RedactableMapper>(self, _mapper: &M) -> Self {
                self
            }
        }
    };

    // Always delegate to Display::fmt (no template parsing for NotSensitiveDisplay)
    // Add Display bound to generics for RedactableWithFormatter impl
    let mut display_generics = generics.clone();
    let display_where_clause = display_generics.make_where_clause();
    // Collect type parameters that need Display bound
    for param in generics.type_params() {
        let ident = &param.ident;
        display_where_clause
            .predicates
            .push(syn::parse_quote!(#ident: ::core::fmt::Display));
    }

    let (display_impl_generics, display_ty_generics, display_where_clause) =
        display_generics.split_for_impl();

    // RedactableWithFormatter impl - delegates to Display
    let redacted_display_impl = quote! {
        impl #display_impl_generics #crate_root::RedactableWithFormatter for #ident #display_ty_generics #display_where_clause {
            fn fmt_redacted(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
                ::core::fmt::Display::fmt(self, f)
            }
        }
    };

    // slog impl
    #[cfg(feature = "slog")]
    let slog_impl = {
        let slog_crate = slog_crate()?;
        let mut slog_generics = generics.clone();
        let (_, ty_generics, _) = slog_generics.split_for_impl();
        let self_ty: syn::Type = syn::parse_quote!(#ident #ty_generics);
        slog_generics
            .make_where_clause()
            .predicates
            .push(syn::parse_quote!(#self_ty: #crate_root::RedactableWithFormatter));
        let (slog_impl_generics, slog_ty_generics, slog_where_clause) =
            slog_generics.split_for_impl();
        quote! {
            impl #slog_impl_generics #slog_crate::Value for #ident #slog_ty_generics #slog_where_clause {
                fn serialize(
                    &self,
                    _record: &#slog_crate::Record<'_>,
                    key: #slog_crate::Key,
                    serializer: &mut dyn #slog_crate::Serializer,
                ) -> #slog_crate::Result {
                    let redacted = #crate_root::RedactableWithFormatter::redacted_display(self);
                    serializer.emit_arguments(key, &format_args!("{}", redacted))
                }
            }

            impl #slog_impl_generics #crate_root::slog::SlogRedacted for #ident #slog_ty_generics #slog_where_clause {}
        }
    };

    #[cfg(not(feature = "slog"))]
    let slog_impl = quote! {};

    // tracing impl - uses the original generics (no extra Display bounds needed for marker trait)
    #[cfg(feature = "tracing")]
    let tracing_impl = {
        let (tracing_impl_generics, tracing_ty_generics, tracing_where_clause) =
            generics.split_for_impl();
        quote! {
            impl #tracing_impl_generics #crate_root::tracing::TracingRedacted for #ident #tracing_ty_generics #tracing_where_clause {}
        }
    };

    #[cfg(not(feature = "tracing"))]
    let tracing_impl = quote! {};

    Ok(quote! {
        #container_impl
        #redacted_display_impl
        #slog_impl
        #tracing_impl
    })
}

/// Derives `redactable::RedactableWithFormatter` using a display template.
///
/// This generates a redacted string representation without requiring `Clone`.
/// Unannotated fields use `RedactableWithFormatter` by default (passthrough for scalars,
/// redacted display for nested `SensitiveDisplay` types).
///
/// # Field Annotations
///
/// - *(none)*: Uses `RedactableWithFormatter` (requires the field type to implement it)
/// - `#[sensitive(Policy)]`: Apply the policy's redaction rules
/// - `#[not_sensitive]`: Render raw via `Display` (use for types without `RedactableWithFormatter`)
///
/// The display template is taken from `#[error("...")]` (thiserror-style) or from
/// doc comments (displaydoc-style). If neither is present, the derive fails.
///
/// Fields are redacted by reference, so field types do not need `Clone`.
///
/// # Generated Impls
///
/// - `RedactableWithFormatter`: always generated.
/// - `Debug`: redacted in production, actual values in test/testing builds.
/// - `slog::Value` + `SlogRedacted`: emits the redacted display string (requires `slog` feature).
///   Skipped when `#[sensitive(dual)]` is set (Sensitive provides them instead).
/// - `TracingRedacted`: marker trait (requires `tracing` feature).
///   Skipped when `#[sensitive(dual)]` is set.
#[proc_macro_derive(SensitiveDisplay, attributes(sensitive, not_sensitive, error))]
pub fn derive_sensitive_display(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    match expand(input, DeriveKind::SensitiveDisplay) {
        Ok(tokens) => tokens.into(),
        Err(err) => err.into_compile_error().into(),
    }
}

/// Returns the token stream to reference the redactable crate root.
///
/// Handles crate renaming (e.g., `my_redact = { package = "redactable", ... }`)
/// and internal usage (when derive is used inside the redactable crate itself).
fn crate_root() -> proc_macro2::TokenStream {
    match crate_name("redactable") {
        Ok(FoundCrate::Itself) => quote! { crate },
        Ok(FoundCrate::Name(name)) => {
            let ident = format_ident!("{}", name);
            quote! { ::#ident }
        }
        Err(_) => quote! { ::redactable },
    }
}

/// Returns the token stream to reference the slog crate root.
///
/// Handles crate renaming (e.g., `my_slog = { package = "slog", ... }`).
/// If the top-level `slog` crate is not available, falls back to the
/// `REDACTABLE_SLOG_CRATE` env var, which should be a path like `my_log::slog`.
#[cfg(feature = "slog")]
fn slog_crate() -> Result<proc_macro2::TokenStream> {
    match crate_name("slog") {
        Ok(FoundCrate::Itself) => Ok(quote! { crate }),
        Ok(FoundCrate::Name(name)) => {
            let ident = format_ident!("{}", name);
            Ok(quote! { ::#ident })
        }
        Err(_) => {
            let env_value = std::env::var("REDACTABLE_SLOG_CRATE").map_err(|_| {
                syn::Error::new(
                    Span::call_site(),
                    "slog support is enabled, but no top-level `slog` crate was found. \
Set the REDACTABLE_SLOG_CRATE env var to a path (e.g., `my_log::slog`) or add \
`slog` as a direct dependency.",
                )
            })?;
            let path = syn::parse_str::<syn::Path>(&env_value).map_err(|_| {
                syn::Error::new(
                    Span::call_site(),
                    format!("REDACTABLE_SLOG_CRATE must be a valid Rust path (got `{env_value}`)"),
                )
            })?;
            Ok(quote! { #path })
        }
    }
}

fn crate_path(item: &str) -> proc_macro2::TokenStream {
    let root = crate_root();
    let item_ident = syn::parse_str::<syn::Path>(item).expect("redactable crate path should parse");
    quote! { #root::#item_ident }
}

/// Output produced by struct/enum derive logic for `Sensitive`.
///
/// Shared by `derive_struct`, `derive_enum`, and the top-level `expand()`.
pub(crate) struct DeriveOutput {
    pub(crate) redaction_body: TokenStream,
    pub(crate) used_generics: Vec<Ident>,
    pub(crate) policy_applicable_generics: Vec<Ident>,
    pub(crate) debug_redacted_body: TokenStream,
    pub(crate) debug_redacted_generics: Vec<Ident>,
    pub(crate) debug_unredacted_body: TokenStream,
    pub(crate) debug_unredacted_generics: Vec<Ident>,
}

struct DebugOutput {
    body: TokenStream,
    generics: Vec<Ident>,
}

/// Which derive macro invoked `expand()`.
///
/// Controls what impls are generated: `Sensitive` emits `RedactableWithMapper` (structural
/// traversal), while `SensitiveDisplay` emits `RedactableWithFormatter` (display formatting).
enum DeriveKind {
    /// `#[derive(Sensitive)]` — structural redaction via `RedactableWithMapper`.
    Sensitive,
    /// `#[derive(SensitiveDisplay)]` — display formatting via `RedactableWithFormatter`.
    SensitiveDisplay,
}

#[allow(clippy::too_many_lines)]
fn expand(input: DeriveInput, kind: DeriveKind) -> Result<TokenStream> {
    let DeriveInput {
        ident,
        generics,
        data,
        attrs,
        ..
    } = input;

    let ContainerOptions { dual } = parse_container_options(&attrs)?;

    let crate_root = crate_root();

    if matches!(kind, DeriveKind::SensitiveDisplay) {
        let redacted_display_output = derive_redacted_display(&ident, &data, &attrs, &generics)?;
        let redacted_display_generics =
            add_display_bounds(generics.clone(), &redacted_display_output.display_generics);
        let redacted_display_generics = add_debug_bounds(
            redacted_display_generics,
            &redacted_display_output.debug_generics,
        );
        let redacted_display_generics = add_policy_applicable_ref_bounds(
            redacted_display_generics,
            &redacted_display_output.policy_ref_generics,
        );
        let redacted_display_generics = add_redacted_display_bounds(
            redacted_display_generics,
            &redacted_display_output.nested_generics,
        );
        let (display_impl_generics, display_ty_generics, display_where_clause) =
            redacted_display_generics.split_for_impl();
        let redacted_display_body = redacted_display_output.body;
        let redacted_display_impl = quote! {
            impl #display_impl_generics #crate_root::RedactableWithFormatter for #ident #display_ty_generics #display_where_clause {
                fn fmt_redacted(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
                    #redacted_display_body
                }
            }
        };
        let to_redacted_output_impl = quote! {
            impl #display_impl_generics #crate_root::ToRedactedOutput for #ident #display_ty_generics #display_where_clause {
                fn to_redacted_output(&self) -> #crate_root::RedactedOutput {
                    #crate_root::RedactedOutput::Text(
                        #crate_root::RedactableWithFormatter::redacted_display(self).to_string(),
                    )
                }
            }
        };

        let debug_output = derive_unredacted_debug(&ident, &data, &generics)?;
        let debug_unredacted_generics = add_debug_bounds(generics.clone(), &debug_output.generics);
        let (
            debug_unredacted_impl_generics,
            debug_unredacted_ty_generics,
            debug_unredacted_where_clause,
        ) = debug_unredacted_generics.split_for_impl();
        let (debug_redacted_impl_generics, debug_redacted_ty_generics, debug_redacted_where_clause) =
            redacted_display_generics.split_for_impl();
        let debug_unredacted_body = debug_output.body;
        let debug_impl = quote! {
            #[cfg(any(test, feature = "testing"))]
            impl #debug_unredacted_impl_generics ::core::fmt::Debug for #ident #debug_unredacted_ty_generics #debug_unredacted_where_clause {
                fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
                    #debug_unredacted_body
                }
            }

            #[cfg(not(any(test, feature = "testing")))]
            impl #debug_redacted_impl_generics ::core::fmt::Debug for #ident #debug_redacted_ty_generics #debug_redacted_where_clause {
                fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
                    #crate_root::RedactableWithFormatter::fmt_redacted(self, f)
                }
            }
        };

        // In dual mode, Sensitive provides slog and tracing impls — skip them here.
        let slog_impl = if dual {
            quote! {}
        } else {
            #[cfg(feature = "slog")]
            {
                let slog_crate = slog_crate()?;
                let mut slog_generics = generics;
                let (_, ty_generics, _) = slog_generics.split_for_impl();
                let self_ty: syn::Type = parse_quote!(#ident #ty_generics);
                slog_generics
                    .make_where_clause()
                    .predicates
                    .push(parse_quote!(#self_ty: #crate_root::RedactableWithFormatter));
                let (slog_impl_generics, slog_ty_generics, slog_where_clause) =
                    slog_generics.split_for_impl();
                quote! {
                    impl #slog_impl_generics #slog_crate::Value for #ident #slog_ty_generics #slog_where_clause {
                        fn serialize(
                            &self,
                            _record: &#slog_crate::Record<'_>,
                            key: #slog_crate::Key,
                            serializer: &mut dyn #slog_crate::Serializer,
                        ) -> #slog_crate::Result {
                            let redacted = #crate_root::RedactableWithFormatter::redacted_display(self);
                            serializer.emit_arguments(key, &format_args!("{}", redacted))
                        }
                    }

                    impl #slog_impl_generics #crate_root::slog::SlogRedacted for #ident #slog_ty_generics #slog_where_clause {}
                }
            }

            #[cfg(not(feature = "slog"))]
            {
                quote! {}
            }
        };

        let tracing_impl = if dual {
            quote! {}
        } else {
            #[cfg(feature = "tracing")]
            {
                let (tracing_impl_generics, tracing_ty_generics, tracing_where_clause) =
                    redacted_display_generics.split_for_impl();
                quote! {
                    impl #tracing_impl_generics #crate_root::tracing::TracingRedacted for #ident #tracing_ty_generics #tracing_where_clause {}
                }
            }

            #[cfg(not(feature = "tracing"))]
            {
                quote! {}
            }
        };

        return Ok(quote! {
            #redacted_display_impl
            #to_redacted_output_impl
            #debug_impl
            #slog_impl
            #tracing_impl
        });
    }

    // Only DeriveKind::Sensitive reaches this point (SensitiveDisplay returns early above).

    let derive_output = match data {
        Data::Struct(data) => derive_struct(&ident, data, &generics)?,
        Data::Enum(data) => derive_enum(&ident, data, &generics)?,
        Data::Union(u) => {
            return Err(syn::Error::new(
                u.union_token.span(),
                "`Sensitive` cannot be derived for unions",
            ));
        }
    };

    let policy_generics = add_container_bounds(generics.clone(), &derive_output.used_generics);
    let policy_generics =
        add_policy_applicable_bounds(policy_generics, &derive_output.policy_applicable_generics);
    let (impl_generics, ty_generics, where_clause) = policy_generics.split_for_impl();
    let debug_redacted_generics =
        add_debug_bounds(generics.clone(), &derive_output.debug_redacted_generics);
    let (debug_redacted_impl_generics, debug_redacted_ty_generics, debug_redacted_where_clause) =
        debug_redacted_generics.split_for_impl();
    let debug_unredacted_generics =
        add_debug_bounds(generics.clone(), &derive_output.debug_unredacted_generics);
    let (
        debug_unredacted_impl_generics,
        debug_unredacted_ty_generics,
        debug_unredacted_where_clause,
    ) = debug_unredacted_generics.split_for_impl();
    let redaction_body = &derive_output.redaction_body;
    let debug_redacted_body = &derive_output.debug_redacted_body;
    let debug_unredacted_body = &derive_output.debug_unredacted_body;
    // In dual mode, SensitiveDisplay provides Debug — skip it here.
    let debug_impl = if dual {
        quote! {}
    } else {
        quote! {
            #[cfg(any(test, feature = "testing"))]
            impl #debug_unredacted_impl_generics ::core::fmt::Debug for #ident #debug_unredacted_ty_generics #debug_unredacted_where_clause {
                fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
                    #debug_unredacted_body
                }
            }

            #[cfg(not(any(test, feature = "testing")))]
            impl #debug_redacted_impl_generics ::core::fmt::Debug for #ident #debug_redacted_ty_generics #debug_redacted_where_clause {
                fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
                    #debug_redacted_body
                }
            }
        }
    };

    #[cfg(feature = "slog")]
    let slog_impl = {
        let slog_crate = slog_crate()?;
        let mut slog_generics = generics;
        let slog_where_clause = slog_generics.make_where_clause();
        let self_ty: syn::Type = parse_quote!(#ident #ty_generics);
        slog_where_clause
            .predicates
            .push(parse_quote!(#self_ty: ::core::clone::Clone));
        // SlogRedactedExt requires Self: Serialize, so we add this bound to enable
        // generic types to work with slog when their type parameters implement Serialize.
        slog_where_clause
            .predicates
            .push(parse_quote!(#self_ty: ::serde::Serialize));
        slog_where_clause
            .predicates
            .push(parse_quote!(#self_ty: #crate_root::slog::SlogRedactedExt));
        let (slog_impl_generics, slog_ty_generics, slog_where_clause) =
            slog_generics.split_for_impl();
        quote! {
            impl #slog_impl_generics #slog_crate::Value for #ident #slog_ty_generics #slog_where_clause {
                fn serialize(
                    &self,
                    _record: &#slog_crate::Record<'_>,
                    key: #slog_crate::Key,
                    serializer: &mut dyn #slog_crate::Serializer,
                ) -> #slog_crate::Result {
                    let redacted = #crate_root::slog::SlogRedactedExt::slog_redacted_json(self.clone());
                    #slog_crate::Value::serialize(&redacted, _record, key, serializer)
                }
            }

            impl #slog_impl_generics #crate_root::slog::SlogRedacted for #ident #slog_ty_generics #slog_where_clause {}
        }
    };

    #[cfg(not(feature = "slog"))]
    let slog_impl = quote! {};

    #[cfg(feature = "tracing")]
    let tracing_impl = quote! {
        impl #impl_generics #crate_root::tracing::TracingRedacted for #ident #ty_generics #where_clause {}
    };

    #[cfg(not(feature = "tracing"))]
    let tracing_impl = quote! {};

    let trait_impl = quote! {
        impl #impl_generics #crate_root::RedactableWithMapper for #ident #ty_generics #where_clause {
            fn redact_with<M: #crate_root::RedactableMapper>(self, mapper: &M) -> Self {
                use #crate_root::RedactableWithMapper as _;
                #redaction_body
            }
        }

        #debug_impl

        #slog_impl

        #tracing_impl
    };
    Ok(trait_impl)
}

fn derive_unredacted_debug(
    name: &Ident,
    data: &Data,
    generics: &syn::Generics,
) -> Result<DebugOutput> {
    match data {
        Data::Struct(data) => Ok(derive_unredacted_debug_struct(name, data, generics)),
        Data::Enum(data) => Ok(derive_unredacted_debug_enum(name, data, generics)),
        Data::Union(u) => Err(syn::Error::new(
            u.union_token.span(),
            "`SensitiveDisplay` cannot be derived for unions",
        )),
    }
}

fn derive_unredacted_debug_struct(
    name: &Ident,
    data: &DataStruct,
    generics: &syn::Generics,
) -> DebugOutput {
    let mut debug_generics = Vec::new();
    match &data.fields {
        Fields::Named(fields) => {
            let mut bindings = Vec::new();
            let mut debug_fields = Vec::new();
            for field in &fields.named {
                let ident = field
                    .ident
                    .clone()
                    .expect("named field should have identifier");
                bindings.push(ident.clone());
                collect_generics_from_type(&field.ty, generics, &mut debug_generics);
                debug_fields.push(quote! {
                    debug.field(stringify!(#ident), #ident);
                });
            }
            DebugOutput {
                body: quote! {
                    match self {
                        Self { #(#bindings),* } => {
                            let mut debug = f.debug_struct(stringify!(#name));
                            #(#debug_fields)*
                            debug.finish()
                        }
                    }
                },
                generics: debug_generics,
            }
        }
        Fields::Unnamed(fields) => {
            let mut bindings = Vec::new();
            let mut debug_fields = Vec::new();
            for (index, field) in fields.unnamed.iter().enumerate() {
                let ident = format_ident!("field_{index}");
                bindings.push(ident.clone());
                collect_generics_from_type(&field.ty, generics, &mut debug_generics);
                debug_fields.push(quote! {
                    debug.field(#ident);
                });
            }
            DebugOutput {
                body: quote! {
                    match self {
                        Self ( #(#bindings),* ) => {
                            let mut debug = f.debug_tuple(stringify!(#name));
                            #(#debug_fields)*
                            debug.finish()
                        }
                    }
                },
                generics: debug_generics,
            }
        }
        Fields::Unit => DebugOutput {
            body: quote! {
                f.write_str(stringify!(#name))
            },
            generics: debug_generics,
        },
    }
}

fn derive_unredacted_debug_enum(
    name: &Ident,
    data: &DataEnum,
    generics: &syn::Generics,
) -> DebugOutput {
    let mut debug_generics = Vec::new();
    let mut debug_arms = Vec::new();
    for variant in &data.variants {
        let variant_ident = &variant.ident;
        match &variant.fields {
            Fields::Unit => {
                debug_arms.push(quote! {
                    #name::#variant_ident => f.write_str(stringify!(#name::#variant_ident))
                });
            }
            Fields::Named(fields) => {
                let mut bindings = Vec::new();
                let mut debug_fields = Vec::new();
                for field in &fields.named {
                    let ident = field
                        .ident
                        .clone()
                        .expect("named field should have identifier");
                    bindings.push(ident.clone());
                    collect_generics_from_type(&field.ty, generics, &mut debug_generics);
                    debug_fields.push(quote! {
                        debug.field(stringify!(#ident), #ident);
                    });
                }
                debug_arms.push(quote! {
                    #name::#variant_ident { #(#bindings),* } => {
                        let mut debug = f.debug_struct(stringify!(#name::#variant_ident));
                        #(#debug_fields)*
                        debug.finish()
                    }
                });
            }
            Fields::Unnamed(fields) => {
                let mut bindings = Vec::new();
                let mut debug_fields = Vec::new();
                for (index, field) in fields.unnamed.iter().enumerate() {
                    let ident = format_ident!("field_{index}");
                    bindings.push(ident.clone());
                    collect_generics_from_type(&field.ty, generics, &mut debug_generics);
                    debug_fields.push(quote! {
                        debug.field(#ident);
                    });
                }
                debug_arms.push(quote! {
                    #name::#variant_ident ( #(#bindings),* ) => {
                        let mut debug = f.debug_tuple(stringify!(#name::#variant_ident));
                        #(#debug_fields)*
                        debug.finish()
                    }
                });
            }
        }
    }
    DebugOutput {
        body: quote! {
            match self {
                #(#debug_arms),*
            }
        },
        generics: debug_generics,
    }
}