qubit-redact-derive 0.8.1

Derive macros for qubit-redact domain-object formatting
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
// =============================================================================
//    Copyright (c) 2025 - 2026 Haixing Hu.
//
//    SPDX-License-Identifier: Apache-2.0
//
//    Licensed under the Apache License, Version 2.0.
// =============================================================================
//! Generic capability bounds inferred from selected field modes.

use std::collections::BTreeSet;

use proc_macro2::Span;
use proc_macro2::TokenStream;
use proc_macro2::TokenTree;
use quote::ToTokens;
use quote::format_ident;
use quote::quote;
use syn::Data;
use syn::DeriveInput;
use syn::Field;
use syn::GenericArgument;
use syn::GenericParam;
use syn::Generics;
use syn::Ident;
use syn::Lifetime;
use syn::Meta;
use syn::Path;
use syn::PathArguments;
use syn::Token;
use syn::Type;
use syn::WhereClause;
use syn::WherePredicate;
use syn::parse_quote;
use syn::punctuated::Punctuated;
use syn::token::Comma;

use crate::model::ContainerData;
use crate::model::FieldMode;
use crate::model::FieldsData;
/// Adds capability bounds needed by borrowing redaction.
///
/// Bounds are added only when a field type refers to one of the input's type
/// parameters. Concrete fields retain the compact impl that existed before
/// bound inference was introduced. Map and JSON modes use the runtime
/// capability traits, preserving their field-type-specific diagnostics.
///
/// # Parameters
///
/// * `generics` - Input generics plus bounds required by the redaction impl.
/// * `model` - Parsed fields and their selected redaction modes.
/// * `runtime` - Resolved path to the runtime crate.
pub(crate) fn add_redact_bounds(generics: &mut Generics, model: &ContainerData<'_>, runtime: &Path) {
    for_each_field(model, &mut |field, mode, _serialize_with| match mode {
        FieldMode::Unmarked => {
            add_trait_bound(generics, field, quote!(::core::fmt::Debug));
        }
        FieldMode::KeyedBy(_) => {
            add_trait_bound(generics, field, quote!(::core::fmt::Debug));
            add_trait_bound(generics, field, quote!(#runtime::domain::RedactLevelValue));
        }
        FieldMode::DisplayLevel(_) => add_trait_bound(generics, field, quote!(::core::fmt::Display)),
        FieldMode::Level(_) => {
            add_trait_bound(generics, field, quote!(#runtime::domain::RedactLevelValue));
        }
        FieldMode::Nested => {
            add_trait_bound(generics, field, quote!(#runtime::Redact));
        }
        FieldMode::Map => add_trait_bound(generics, field, quote!(#runtime::domain::RedactMapValue)),
        FieldMode::MapLevels { .. } => add_trait_bound(generics, field, quote!(#runtime::domain::RedactMapKeyValue)),
        FieldMode::Json => add_trait_bound(generics, field, quote!(#runtime::domain::RedactJsonValue)),
        FieldMode::Skip => {}
    });
}

/// Visits every parsed field without exposing the container representation to
/// each bound-inference caller.
///
/// # Parameters
///
/// * `model` - Parsed struct or enum to visit.
/// * `callback` - Visitor receiving the source field, redaction mode, and
///   optional adapter.
fn for_each_field(model: &ContainerData<'_>, callback: &mut impl FnMut(&Field, &FieldMode, Option<&Path>)) {
    match model {
        ContainerData::Struct(fields) => for_each_fields(fields, callback),
        ContainerData::Enum(variants) => {
            for variant in variants {
                for_each_fields(variant.fields(), callback);
            }
        }
    }
}

/// Visits one parsed field collection.
///
/// # Parameters
///
/// * `fields` - Named, tuple, or unit field collection.
/// * `callback` - Visitor receiving each field and its validated controls.
fn for_each_fields(fields: &FieldsData<'_>, callback: &mut impl FnMut(&Field, &FieldMode, Option<&Path>)) {
    match fields {
        FieldsData::Named(fields) => {
            for field in fields {
                callback(
                    field.field(),
                    field.attributes().mode(),
                    field.serde_attributes().serialize_with(),
                );
            }
        }
        FieldsData::Unnamed(fields) => {
            for field in fields {
                callback(
                    field.field(),
                    field.attributes().mode(),
                    field.serde_attributes().serialize_with(),
                );
            }
        }
        FieldsData::Unit => {}
    }
}

/// Adds one trait predicate when the field type uses an input type parameter.
///
/// # Parameters
///
/// * `generics` - Generic declaration to extend without duplicate predicates.
/// * `field` - Field whose type may need a capability bound.
/// * `trait_path` - Capability trait expressed as generated tokens.
fn add_trait_bound(generics: &mut Generics, field: &Field, trait_path: TokenStream) {
    if !uses_type_parameter(generics, &field.ty) {
        return;
    }
    let field_type = &field.ty;
    let predicate: WherePredicate = parse_quote!(#field_type: #trait_path);
    let candidate = predicate.to_token_stream().to_string();
    let where_clause = generics.make_where_clause();
    if where_clause
        .predicates
        .iter()
        .any(|item| item.to_token_stream().to_string() == candidate)
    {
        return;
    }
    where_clause.predicates.push(predicate);
}

/// Returns whether a field type contains an input type parameter identifier.
///
/// # Parameters
///
/// * `generics` - Input declaration supplying candidate type parameters.
/// * `field_type` - Field type to inspect recursively.
///
/// # Returns
///
/// `true` when any field-type token names an input type parameter.
#[must_use]
fn uses_type_parameter(generics: &Generics, field_type: &impl ToTokens) -> bool {
    let parameters: Vec<String> = generics
        .params
        .iter()
        .filter_map(|parameter| {
            let GenericParam::Type(parameter) = parameter else {
                return None;
            };
            Some(parameter.ident.to_string())
        })
        .collect();
    token_stream_uses_parameter(field_type.to_token_stream(), &parameters)
}

/// Selects the input generic parameters referenced by one field type.
///
/// The returned generics retain only parameters and where predicates needed by
/// the field. Generated local carrier items can therefore introduce their own
/// generic parameters instead of capturing the surrounding impl's parameters.
///
/// # Parameters
///
/// * `generics` - Input generic parameters and where predicates.
/// * `field_type` - Field type whose referenced parameters are retained.
///
/// # Returns
///
/// Filtered generics containing referenced parameters and transitively related
/// inline bounds and where predicates.
#[must_use]
pub(crate) fn generics_for_field(generics: &Generics, field_type: &Type) -> Generics {
    let parameter_names = generic_parameter_names(generics);
    let mut used = BTreeSet::new();
    collect_parameter_names(field_type.to_token_stream(), &parameter_names, &mut used);

    loop {
        let mut changed = false;
        for parameter in &generics.params {
            if used.contains(&generic_parameter_name(parameter)) {
                for name in parameter_names_in(parameter, &parameter_names) {
                    changed |= used.insert(name);
                }
            }
        }
        if let Some(where_clause) = &generics.where_clause {
            for predicate in &where_clause.predicates {
                let names = parameter_names_in(predicate, &parameter_names);
                if names.iter().any(|name| used.contains(name)) {
                    changed |= names.iter().any(|name| used.insert(name.clone()));
                }
            }
        }
        if !changed {
            break;
        }
    }

    let mut filtered = generics.clone();
    filtered.params = generics
        .params
        .iter()
        .filter(|parameter| used.contains(&generic_parameter_name(parameter)))
        .cloned()
        .collect();
    filtered.where_clause = filtered.where_clause.and_then(|where_clause| {
        let predicates: Punctuated<WherePredicate, Comma> = where_clause
            .predicates
            .into_iter()
            .filter(|predicate| {
                let names = parameter_names_in(predicate, &parameter_names);
                names.iter().any(|name| used.contains(name))
            })
            .collect();
        if predicates.is_empty() {
            None
        } else {
            Some(WhereClause {
                where_token: where_clause.where_token,
                predicates,
            })
        }
    });
    filtered
}

/// Creates an identifier that cannot collide with an input generic parameter.
///
/// # Parameters
///
/// * `generics` - Input declaration supplying occupied parameter names.
/// * `base` - Valid Rust identifier to use directly or suffix with an integer.
///
/// # Returns
///
/// An available identifier based on `base`.
///
/// # Panics
///
/// Panics if `base` is not a valid identifier or every generated suffix is
/// occupied.
#[must_use]
pub(crate) fn fresh_identifier(generics: &Generics, base: &str) -> Ident {
    let used = generic_parameter_names(generics);
    if !used.contains(base) {
        return format_ident!("{base}");
    }
    (0..)
        .map(|index| format_ident!("{base}_{index}"))
        .find(|candidate| !used.contains(&candidate.to_string()))
        .expect("an unused generated identifier should always exist")
}

/// Creates a lifetime that cannot collide with an input generic lifetime.
///
/// # Parameters
///
/// * `generics` - Input declaration supplying occupied parameter names.
///
/// # Returns
///
/// A fresh lifetime beginning with `__qubit_redact_lifetime`.
///
/// # Panics
///
/// Panics only if every generated numeric suffix is occupied.
#[must_use]
pub(crate) fn fresh_lifetime(generics: &Generics) -> Lifetime {
    let used = generic_parameter_names(generics);
    let base = "__qubit_redact_lifetime";
    let name = if !used.contains(base) {
        base.to_owned()
    } else {
        (0..)
            .map(|index| format!("{base}_{index}"))
            .find(|candidate| !used.contains(candidate))
            .expect("an unused generated lifetime should always exist")
    };
    Lifetime::new(&format!("'{name}"), Span::call_site())
}

/// Returns generic parameter names declared by one input.
///
/// # Parameters
///
/// * `generics` - Declaration whose type, lifetime, and const names are
///   collected.
///
/// # Returns
///
/// The set of declared names without lifetime apostrophes.
#[must_use]
fn generic_parameter_names(generics: &Generics) -> BTreeSet<String> {
    generics.params.iter().map(generic_parameter_name).collect()
}

/// Returns the textual name of one type, lifetime, or const parameter.
///
/// # Parameters
///
/// * `parameter` - Generic parameter to name.
///
/// # Returns
///
/// The parameter identifier without a lifetime apostrophe.
#[must_use]
fn generic_parameter_name(parameter: &GenericParam) -> String {
    match parameter {
        GenericParam::Type(parameter) => parameter.ident.to_string(),
        GenericParam::Const(parameter) => parameter.ident.to_string(),
        GenericParam::Lifetime(parameter) => parameter.lifetime.ident.to_string(),
    }
}

/// Returns generic names used by one token stream.
///
/// # Parameters
///
/// * `tokens` - Syntax tokens to inspect recursively.
/// * `candidates` - Generic parameter names eligible for inclusion.
///
/// # Returns
///
/// Candidate names occurring in the token stream.
#[must_use]
fn parameter_names_in(tokens: &impl ToTokens, candidates: &BTreeSet<String>) -> BTreeSet<String> {
    let mut names = BTreeSet::new();
    collect_parameter_names(tokens.to_token_stream(), candidates, &mut names);
    names
}

/// Recursively collects candidate generic names from token groups.
///
/// # Parameters
///
/// * `tokens` - Token stream to inspect.
/// * `candidates` - Declared generic names eligible for inclusion.
/// * `names` - Destination set extended with matching identifiers.
fn collect_parameter_names(tokens: TokenStream, candidates: &BTreeSet<String>, names: &mut BTreeSet<String>) {
    for token in tokens {
        match token {
            TokenTree::Ident(identifier) => {
                let name = identifier.to_string();
                if candidates.contains(&name) {
                    names.insert(name);
                }
            }
            TokenTree::Group(group) => {
                collect_parameter_names(group.stream(), candidates, names);
            }
            TokenTree::Punct(_) | TokenTree::Literal(_) => {}
        }
    }
}

/// Searches a field type's token stream for an input type parameter.
///
/// # Parameters
///
/// * `tokens` - Field-type token stream to inspect recursively.
/// * `parameters` - Candidate input type parameter names.
///
/// # Returns
///
/// `true` if any identifier matches a candidate type parameter.
#[must_use]
fn token_stream_uses_parameter(tokens: TokenStream, parameters: &[String]) -> bool {
    tokens.into_iter().any(|token| match token {
        TokenTree::Ident(identifier) => {
            let name = identifier.to_string();
            parameters.iter().any(|parameter| parameter == &name)
        }
        TokenTree::Group(group) => token_stream_uses_parameter(group.stream(), parameters),
        TokenTree::Punct(_) | TokenTree::Literal(_) => false,
    })
}

/// Replaces generated self-recursive field bounds with the independent stored
/// type bounds, preserving the original declaration's explicit predicates.
pub(crate) fn non_recursive_predicates(input: &DeriveInput, predicate: WherePredicate) -> Vec<WherePredicate> {
    let WherePredicate::Type(bound) = &predicate else {
        return vec![predicate];
    };
    let name = &input.ident;
    let (_, arguments, _) = input.generics.split_for_impl();
    let target = quote!(#name #arguments).to_string();
    let Some(types) = recursive_types(&bound.bounded_ty, &target) else {
        return vec![predicate];
    };
    types
        .into_iter()
        .map(|ty| {
            let mut replacement = bound.clone();
            replacement.bounded_ty = ty.clone();
            WherePredicate::Type(replacement)
        })
        .collect()
}

/// Recognizes recursion only through ordinary standard storage wrappers.
fn recursive_types<'a>(ty: &'a Type, target: &str) -> Option<Vec<&'a Type>> {
    let rendered = ty.to_token_stream().to_string();
    if rendered == target || rendered == "Self" {
        return Some(Vec::new());
    }
    let children: Vec<&Type> = match ty {
        Type::Path(path) if path.qself.is_none() => {
            let segment = path.path.segments.last()?;
            let root = &path.path.segments.first()?.ident;
            if path.path.segments.len() > 1 && root != "std" && root != "alloc" && root != "core" {
                return None;
            }
            if !matches!(
                segment.ident.to_string().as_str(),
                "Option"
                    | "Box"
                    | "Rc"
                    | "Arc"
                    | "Vec"
                    | "VecDeque"
                    | "LinkedList"
                    | "BTreeMap"
                    | "BTreeSet"
                    | "HashMap"
                    | "HashSet"
            ) {
                return None;
            }
            let PathArguments::AngleBracketed(arguments) = &segment.arguments else {
                return None;
            };
            arguments
                .args
                .iter()
                .filter_map(|argument| match argument {
                    GenericArgument::Type(ty) => Some(ty),
                    _ => None,
                })
                .collect()
        }
        Type::Tuple(tuple) => tuple.elems.iter().collect(),
        Type::Array(array) => vec![&array.elem],
        Type::Paren(paren) => vec![&paren.elem],
        _ => return None,
    };
    let mut found = false;
    let bounds = children
        .into_iter()
        .flat_map(|child| {
            if let Some(bounds) = recursive_types(child, target) {
                found = true;
                bounds
            } else {
                vec![child]
            }
        })
        .collect();
    found.then_some(bounds)
}

/// Keeps recursive derived values on the structured policy path so nested
/// serializers do not acquire an ever-growing BudgetSerializer type.
pub(crate) fn normalize_recursive_fields(input: &mut DeriveInput) {
    let name = &input.ident;
    let (_, arguments, _) = input.generics.split_for_impl();
    let target = quote!(#name #arguments).to_string();
    let fields: Vec<_> = match &mut input.data {
        Data::Struct(data) => data.fields.iter_mut().collect(),
        Data::Enum(data) => data
            .variants
            .iter_mut()
            .flat_map(|variant| variant.fields.iter_mut())
            .collect(),
        Data::Union(_) => return,
    };
    for field in fields {
        let custom_serializer = field
            .attrs
            .iter()
            .filter(|attribute| attribute.path().is_ident("serde"))
            .any(|attribute| {
                attribute
                    .parse_args_with(Punctuated::<Meta, Token![,]>::parse_terminated)
                    .is_ok_and(|items| {
                        items
                            .iter()
                            .any(|item| item.path().is_ident("with") || item.path().is_ident("serialize_with"))
                    })
            });
        if !custom_serializer
            && !field.attrs.iter().any(|attribute| attribute.path().is_ident("redact"))
            && recursive_types(&field.ty, &target).is_some()
        {
            field.attrs.push(parse_quote!(#[redact(nested)]));
        }
    }
}