qubit-redact-derive 0.3.0

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
// =============================================================================
//    Copyright (c) 2025 - 2026 Haixing Hu.
//
//    SPDX-License-Identifier: Apache-2.0
//
//    Licensed under the Apache License, Version 2.0.
// =============================================================================
//! Parser for the supported Serde container attribute allowlist.

use syn::{
    Attribute,
    Data,
    DeriveInput,
    Ident,
    LitStr,
    Meta,
    Token,
};

use crate::{
    serde_container_attributes::SerdeContainerAttributes,
    serde_rename_rule::SerdeRenameRule,
};

/// Incremental state for Serde container attribute parsing.
///
/// # Type Parameters
///
/// * `'input` - Lifetime of the borrowed derive input being parsed.
pub(crate) struct SerdeContainerAttributeParser<'input> {
    /// Complete derive input that owns the parsed attributes.
    input: &'input DeriveInput,
    /// Optional explicit serialized container name.
    name: Option<String>,
    /// Optional struct-field or enum-variant rename rule.
    rename_all: Option<SerdeRenameRule>,
    /// Optional enum variant-field rename rule.
    rename_all_fields: Option<SerdeRenameRule>,
    /// Optional internal or adjacent enum tag.
    tag: Option<LitStr>,
    /// Optional adjacent enum content key.
    content: Option<LitStr>,
    /// Optional bare untagged attribute path.
    untagged: Option<syn::Path>,
}

impl<'input> SerdeContainerAttributeParser<'input> {
    /// Parses supported Serde container controls into validated attributes.
    ///
    /// # Parameters
    ///
    /// * `input` - Complete derive input carrying container attributes.
    /// * `enabled` - Whether `#[redact(serde)]` requested parsing.
    ///
    /// # Returns
    ///
    /// Validated serialization attributes, or default attributes when parsing
    /// is disabled.
    ///
    /// # Errors
    ///
    /// Returns targeted errors for malformed, duplicate, enum-only, or
    /// unsupported controls and incompatible enum representations.
    ///
    /// # Panics
    ///
    /// Panics only if `syn` supplies a nested metadata path without any
    /// segments, which violates the `ParseNestedMeta` path invariant.
    pub(crate) fn parse(
        input: &'input DeriveInput,
        enabled: bool,
    ) -> syn::Result<SerdeContainerAttributes> {
        let mut parser = Self::new(input);
        parser.parse_attributes(enabled)?;
        parser.finish()
    }

    /// Creates an empty parser for one derive input.
    ///
    /// # Parameters
    ///
    /// * `input` - Complete derive input carrying container attributes.
    ///
    /// # Returns
    ///
    /// Parser state with no controls collected.
    #[must_use]
    #[inline(always)]
    fn new(input: &'input DeriveInput) -> Self {
        Self {
            input,
            name: None,
            rename_all: None,
            rename_all_fields: None,
            tag: None,
            content: None,
            untagged: None,
        }
    }

    /// Parses every supported Serde container attribute when enabled.
    ///
    /// # Parameters
    ///
    /// * `enabled` - Whether `#[redact(serde)]` requested parsing.
    ///
    /// # Errors
    ///
    /// Returns the first malformed or unsupported Serde attribute error.
    fn parse_attributes(&mut self, enabled: bool) -> syn::Result<()> {
        if !enabled {
            return Ok(());
        }
        for attribute in &self.input.attrs {
            if attribute.path().is_ident("serde") {
                self.parse_attribute(attribute)?;
            }
        }
        Ok(())
    }

    /// Parses one `#[serde(...)]` container attribute.
    ///
    /// # Parameters
    ///
    /// * `attribute` - Serde attribute selected from the derive input.
    ///
    /// # Errors
    ///
    /// Returns an error when the attribute is not list-shaped or contains an
    /// unsupported nested control.
    fn parse_attribute(&mut self, attribute: &Attribute) -> syn::Result<()> {
        let Meta::List(_) = &attribute.meta else {
            return Err(syn::Error::new_spanned(
                attribute,
                format!(
                    "Redact serde for `{}` expects `#[serde(...)]`",
                    self.input.ident,
                ),
            ));
        };
        attribute.parse_nested_meta(|meta| self.parse_nested_attribute(meta))
    }

    /// Parses one nested Serde container control.
    ///
    /// # Parameters
    ///
    /// * `meta` - Nested Serde metadata item.
    ///
    /// # Errors
    ///
    /// Returns a targeted error for duplicate, malformed, or unsupported
    /// controls.
    fn parse_nested_attribute(
        &mut self,
        meta: syn::meta::ParseNestedMeta<'_>,
    ) -> syn::Result<()> {
        if meta.path.is_ident("rename") {
            parse_name(&meta, &self.input.ident, "rename", &mut self.name)
        } else if meta.path.is_ident("rename_all") {
            parse_rule(
                &meta,
                &self.input.ident,
                "rename_all",
                &mut self.rename_all,
            )
        } else if meta.path.is_ident("rename_all_fields") {
            self.parse_rename_all_fields(meta)
        } else if meta.path.is_ident("tag") {
            self.parse_tag(meta)
        } else if meta.path.is_ident("content") {
            self.parse_content(meta)
        } else if meta.path.is_ident("untagged") {
            self.parse_untagged(meta)
        } else {
            Err(self.unsupported_control_error(meta))
        }
    }

    /// Parses the enum-only `rename_all_fields` control.
    ///
    /// # Parameters
    ///
    /// * `meta` - Nested `rename_all_fields` metadata item.
    ///
    /// # Errors
    ///
    /// Returns an error when the input is not an enum or the rule is invalid
    /// or repeated.
    fn parse_rename_all_fields(
        &mut self,
        meta: syn::meta::ParseNestedMeta<'_>,
    ) -> syn::Result<()> {
        require_enum(&meta, self.input, "rename_all_fields")?;
        parse_rule(
            &meta,
            &self.input.ident,
            "rename_all_fields",
            &mut self.rename_all_fields,
        )
    }

    /// Parses the enum-only `tag` control.
    ///
    /// # Parameters
    ///
    /// * `meta` - Nested `tag` metadata item.
    ///
    /// # Errors
    ///
    /// Returns an error when the input is not an enum or the tag is invalid or
    /// repeated.
    fn parse_tag(
        &mut self,
        meta: syn::meta::ParseNestedMeta<'_>,
    ) -> syn::Result<()> {
        require_enum(&meta, self.input, "tag")?;
        parse_literal(&meta, &self.input.ident, "tag", &mut self.tag)
    }

    /// Parses the enum-only `content` control.
    ///
    /// # Parameters
    ///
    /// * `meta` - Nested `content` metadata item.
    ///
    /// # Errors
    ///
    /// Returns an error when the input is not an enum or the content key is
    /// invalid or repeated.
    fn parse_content(
        &mut self,
        meta: syn::meta::ParseNestedMeta<'_>,
    ) -> syn::Result<()> {
        require_enum(&meta, self.input, "content")?;
        parse_literal(&meta, &self.input.ident, "content", &mut self.content)
    }

    /// Parses one bare enum-only `untagged` control.
    ///
    /// # Parameters
    ///
    /// * `meta` - Nested `untagged` metadata item.
    ///
    /// # Errors
    ///
    /// Returns an error when the input is not an enum, the control has a value,
    /// or the control is repeated.
    fn parse_untagged(
        &mut self,
        meta: syn::meta::ParseNestedMeta<'_>,
    ) -> syn::Result<()> {
        require_enum(&meta, self.input, "untagged")?;
        if meta.input.peek(Token![=]) || meta.input.peek(syn::token::Paren) {
            return Err(meta.error(format!(
                "Redact serde for `{}` requires bare `untagged`",
                self.input.ident,
            )));
        }
        if self.untagged.is_some() {
            return Err(meta.error(format!(
                "Redact serde for `{}` repeats `untagged`",
                self.input.ident,
            )));
        }
        self.untagged = Some(meta.path);
        Ok(())
    }

    /// Builds the existing attribute value from collected parser state.
    ///
    /// # Returns
    ///
    /// Validated attributes ready for macro expansion.
    ///
    /// # Errors
    ///
    /// Returns the targeted error for an invalid enum representation.
    fn finish(self) -> syn::Result<SerdeContainerAttributes> {
        SerdeContainerAttributes::from_parts(
            self.input,
            self.name,
            self.rename_all,
            self.rename_all_fields,
            self.tag,
            self.content,
            self.untagged,
        )
    }

    /// Builds the unsupported-control diagnostic for one metadata item.
    ///
    /// # Parameters
    ///
    /// * `meta` - Unsupported nested Serde metadata item.
    ///
    /// # Returns
    ///
    /// The targeted diagnostic explaining the supported allowlist.
    ///
    /// # Panics
    ///
    /// Panics only if `syn` supplies a nested metadata path without any
    /// segments, which violates the `ParseNestedMeta` path invariant.
    fn unsupported_control_error(
        &self,
        meta: syn::meta::ParseNestedMeta<'_>,
    ) -> syn::Error {
        let key = meta
            .path
            .segments
            .last()
            .expect("syn nested meta paths always contain a segment")
            .ident
            .to_string();
        meta.error(format!(
            "Redact serde for `{}` does not support container `{key}` because it can change value paths or bypass redaction; use only `rename`, `rename_all`, `rename_all_fields`, `tag`, `content`, or `untagged`",
            self.input.ident,
        ))
    }
}

/// Requires one Serde control to appear on an enum.
///
/// # Parameters
///
/// * `meta` - Nested attribute item used as the error span.
/// * `input` - Complete derive input.
/// * `name` - Enum-only control name.
///
/// # Errors
///
/// Returns a targeted error when the derive input is not an enum.
fn require_enum(
    meta: &syn::meta::ParseNestedMeta<'_>,
    input: &DeriveInput,
    name: &str,
) -> syn::Result<()> {
    if matches!(input.data, Data::Enum(_)) {
        Ok(())
    } else {
        Err(meta.error(format!(
            "Redact serde for `{}` allows `{name}` only on enums",
            input.ident,
        )))
    }
}

/// Parses one unique string name.
///
/// # Parameters
///
/// * `meta` - Nested attribute item carrying the string literal.
/// * `type_name` - Derived type used in diagnostics.
/// * `name` - Supported control name.
/// * `output` - Destination for the parsed name.
///
/// # Errors
///
/// Returns an error when the control is repeated or its value is not a string.
fn parse_name(
    meta: &syn::meta::ParseNestedMeta<'_>,
    type_name: &Ident,
    name: &str,
    output: &mut Option<String>,
) -> syn::Result<()> {
    if output.is_some() {
        return Err(meta.error(format!(
            "Redact serde for `{type_name}` repeats `{name}`",
        )));
    }
    let mut literal = None;
    parse_literal(meta, type_name, name, &mut literal)?;
    *output = literal.map(|literal| literal.value());
    Ok(())
}

/// Parses one unique rename rule.
///
/// # Parameters
///
/// * `meta` - Nested attribute item carrying the rule literal.
/// * `type_name` - Derived type used in diagnostics.
/// * `name` - Supported control name.
/// * `output` - Destination for the parsed rename rule.
///
/// # Errors
///
/// Returns an error when the control is repeated or the rule is unsupported.
fn parse_rule(
    meta: &syn::meta::ParseNestedMeta<'_>,
    type_name: &Ident,
    name: &str,
    output: &mut Option<SerdeRenameRule>,
) -> syn::Result<()> {
    if output.is_some() {
        return Err(meta.error(format!(
            "Redact serde for `{type_name}` repeats `{name}`",
        )));
    }
    let literal: LitStr = meta.value()?.parse()?;
    *output = Some(SerdeRenameRule::parse(&literal)?);
    Ok(())
}

/// Parses one unique string literal while retaining its diagnostic span.
///
/// # Parameters
///
/// * `meta` - Nested attribute item carrying the literal.
/// * `type_name` - Derived type used in diagnostics.
/// * `name` - Supported control name.
/// * `output` - Destination for the parsed literal.
///
/// # Errors
///
/// Returns an error when the control is repeated or its value is not a string.
fn parse_literal(
    meta: &syn::meta::ParseNestedMeta<'_>,
    type_name: &Ident,
    name: &str,
    output: &mut Option<LitStr>,
) -> syn::Result<()> {
    if output.is_some() {
        return Err(meta.error(format!(
            "Redact serde for `{type_name}` repeats `{name}`",
        )));
    }
    *output = Some(meta.value()?.parse()?);
    Ok(())
}