Skip to main content

debuggable_derive/
lib.rs

1//! Derive macro for [`debuggable`](https://docs.rs/debuggable). Use that crate instead of
2//! depending on this one directly.
3//!
4//! The derive parses `#[debuggable(...)]` attributes, validates them, and expands to one
5//! `::debuggable::__entry!` call carrying a JSON descriptor of the type
6//! (see `docs/internal/schema-v1.md`). All rendering happens in the debugger.
7
8mod emit;
9
10use emit::{Alternative, Body, Field, Only, Part, Ty, Variant};
11use proc_macro::TokenStream;
12use proc_macro2::Span;
13use syn::ext::IdentExt;
14use syn::spanned::Spanned;
15use syn::{Attribute, Data, DeriveInput, Error, Fields, GenericParam, LitStr, Result, Type};
16
17/// Derives debugger visualizers for a struct or enum. See the `debuggable` crate docs.
18#[proc_macro_derive(Debuggable, attributes(debuggable))]
19pub fn derive_debuggable(input: TokenStream) -> TokenStream {
20    let input = syn::parse_macro_input!(input as DeriveInput);
21    match expand(&input) {
22        Ok(tokens) => tokens.into(),
23        Err(e) => e.to_compile_error().into(),
24    }
25}
26
27fn expand(input: &DeriveInput) -> Result<proc_macro2::TokenStream> {
28    let ty = model(input)?;
29    Ok(emit::entry_call(&ty).parse().expect("generated tokens are valid"))
30}
31
32// ---- Attribute options --------------------------------------------------------------------
33
34/// Where an attribute appears; decides which options are allowed.
35#[derive(Clone, Copy, PartialEq)]
36enum Place {
37    Struct,
38    Enum,
39    Variant,
40    StructField,
41    VariantField,
42}
43
44#[derive(Default)]
45struct Opts {
46    summary: Option<LitStr>,
47    hide: Option<Span>,
48    rename: Option<LitStr>,
49    items: Option<Span>,
50    text: Option<Span>,
51    len: Option<LitStr>,
52    only: Option<LitStr>,
53    value: Option<LitStr>,
54    /// On a type: one `(items, len)` per `#[debuggable(items = "...", ...)]` attribute.
55    alternatives: Vec<(LitStr, Option<LitStr>)>,
56}
57
58fn opts(attrs: &[Attribute], place: Place) -> Result<Opts> {
59    let mut o = Opts::default();
60    let on_type = matches!(place, Place::Struct | Place::Enum);
61    for attr in attrs.iter().filter(|a| a.path().is_ident("debuggable")) {
62        // On a type, `items = "..."` and its `len` pair up within one attribute.
63        let (mut alt_items, mut alt_len): (Option<LitStr>, Option<LitStr>) = (None, None);
64        attr.parse_nested_meta(|m| {
65            let key = m.path.get_ident().map(|i| i.to_string()).unwrap_or_default();
66            let span = m.path.span();
67            let allowed = match key.as_str() {
68                "summary" => matches!(place, Place::Struct | Place::Variant),
69                "hide" | "rename" => matches!(place, Place::StructField | Place::VariantField),
70                "items" | "len" if on_type => true,
71                "items" | "text" | "len" | "only" | "value" => place == Place::StructField,
72                _ => {
73                    const OPTIONS: [&str; 8] = ["summary", "hide", "rename", "items", "text", "len", "only", "value"];
74                    return Err(m.error(match closest(&key, OPTIONS) {
75                        Some(best) => format!("unknown `debuggable` option `{key}`; did you mean `{best}`?"),
76                        None => "unknown `debuggable` option; expected one of: `summary`, `hide`, `rename`, `items`, `text`, `len`, `only`, `value`"
77                            .to_string(),
78                    }));
79                }
80            };
81            if !allowed {
82                return Err(Error::new(span, misplaced(&key, place)));
83            }
84            let flag = |m: &syn::meta::ParseNestedMeta, set: &mut Option<Span>| -> Result<()> {
85                if !m.input.is_empty() && !m.input.peek(syn::Token![,]) {
86                    return Err(m.error(format!("`{key}` takes no value")));
87                }
88                if set.replace(span).is_some() {
89                    return Err(Error::new(span, format!("duplicate `{key}`")));
90                }
91                Ok(())
92            };
93            let value = |m: &syn::meta::ParseNestedMeta, set: &mut Option<LitStr>| -> Result<()> {
94                let lit: LitStr = m.value()?.parse().map_err(|_| m.error(format!("expected `{key} = \"...\"`")))?;
95                if set.replace(lit).is_some() {
96                    return Err(Error::new(span, format!("duplicate `{key}`")));
97                }
98                Ok(())
99            };
100            if on_type {
101                let has_value = m.input.peek(syn::Token![=]);
102                return match key.as_str() {
103                    "items" if !has_value => Err(m.error("on a type, write `items = \"path\"` (one attribute per place the elements can be)")),
104                    "items" => value(&m, &mut alt_items),
105                    "len" => value(&m, &mut alt_len),
106                    _ => value(&m, &mut o.summary),
107                };
108            }
109            if key == "items" && m.input.peek(syn::Token![=]) {
110                return Err(m.error("on a field, write `items` without a value (`items = \"path\"` goes on the type)"));
111            }
112            match key.as_str() {
113                "summary" => value(&m, &mut o.summary),
114                "rename" => value(&m, &mut o.rename),
115                "len" => value(&m, &mut o.len),
116                "only" => value(&m, &mut o.only),
117                "value" => value(&m, &mut o.value),
118                "hide" => flag(&m, &mut o.hide),
119                "text" => flag(&m, &mut o.text),
120                _ => flag(&m, &mut o.items),
121            }
122        })?;
123        match (alt_items, alt_len) {
124            (Some(items), len) => o.alternatives.push((items, len)),
125            (None, Some(len)) => {
126                return Err(Error::new(len.span(), "`len` on a type needs `items = \"...\"` in the same attribute"))
127            }
128            (None, None) => {}
129        }
130    }
131    Ok(o)
132}
133
134fn misplaced(key: &str, place: Place) -> String {
135    match (key, place) {
136        ("summary", Place::Enum) => {
137            "`summary` on an enum goes on each variant: `#[debuggable(summary = \"...\")]` above the variant".into()
138        }
139        ("summary", _) => "`summary` is allowed on a struct or an enum variant, not on a field".into(),
140        ("items" | "text" | "len" | "only" | "value", Place::VariantField) => format!("`{key}` is not supported inside enum variants"),
141        (_, Place::Struct | Place::Enum | Place::Variant) => format!("`{key}` is allowed on fields only"),
142        _ => format!("`{key}` is not allowed here"),
143    }
144}
145
146// ---- Model building and validation ---------------------------------------------------------
147
148fn is_phantom(ty: &Type) -> bool {
149    matches!(ty, Type::Path(p) if p.qself.is_none() && p.path.segments.last().is_some_and(|s| s.ident == "PhantomData"))
150}
151
152/// Fields plus their options, validated as a group.
153fn fields(fields: &Fields, place: Place) -> Result<Vec<Field>> {
154    let mut out = Vec::new();
155    let mut items_seen = false;
156    for (i, f) in fields.iter().enumerate() {
157        let o = opts(&f.attrs, place)?;
158        if let (Some(_), Some(rename)) = (o.hide, &o.rename) {
159            return Err(Error::new(rename.span(), "a hidden field can't be renamed"));
160        }
161        if let (Some(_), Some(items)) = (o.hide, o.items) {
162            return Err(Error::new(items, "`items` already replaces the field with its elements; remove `hide`"));
163        }
164        if let (Some(_), Some(text)) = (o.items, o.text) {
165            return Err(Error::new(text, "a field can't have both `items` and `text`"));
166        }
167        for (lit, key) in [(&o.only, "only"), (&o.value, "value")] {
168            if let (Some(lit), None) = (lit, o.items) {
169                return Err(Error::new(lit.span(), format!("`{key}` needs `items` on the same field")));
170            }
171        }
172        if let (Some(len), None, None) = (&o.len, o.items, o.text) {
173            return Err(Error::new(len.span(), "`len` needs `items` or `text` on the same field"));
174        }
175        if let Some(items) = o.items {
176            if items_seen {
177                return Err(Error::new(items, "`items` may be used on only one field"));
178            }
179            items_seen = true;
180        }
181        if let Some(r) = &o.rename {
182            if r.value().is_empty() {
183                return Err(Error::new(r.span(), "`rename` needs a non-empty name"));
184            }
185        }
186        out.push(Field {
187            name: f.ident.as_ref().map(|id| id.unraw().to_string()).unwrap_or_else(|| i.to_string()),
188            hide: o.hide.is_some() || is_phantom(&f.ty),
189            rename: o.rename.map(|r| r.value()),
190            items: o.items.is_some(),
191            text: o.text.is_some(),
192            only: o.only.as_ref().map(parse_only).transpose()?,
193            value: o.value.as_ref().map(|v| parse_path(v, "value")).transpose()?,
194            len: o.len.map(|l| (l.value(), l.span())),
195        });
196    }
197    for f in &out {
198        if let Some((len, span)) = &f.len {
199            if !out.iter().any(|g| &g.name == len) {
200                return Err(Error::new(*span, unknown_field(len, &out, "`len`")));
201            }
202        }
203    }
204    Ok(out)
205}
206
207/// `a.b.0`: field names (or tuple indices) separated by dots (design 0002 §2.1).
208fn parse_path(lit: &LitStr, what: &str) -> Result<Vec<String>> {
209    parse_path_str(&lit.value(), lit, what)
210}
211
212fn parse_path_str(s: &str, lit: &LitStr, what: &str) -> Result<Vec<String>> {
213    let err = |msg: String| Error::new(lit.span(), msg);
214    if s.trim().is_empty() {
215        return Err(err(format!("`{what}` expects a field or variant name, like `\"value\"` or `\"u.value\"`")));
216    }
217    let mut out = Vec::new();
218    for seg in s.split('.') {
219        let seg = seg.trim();
220        if seg.is_empty() {
221            return Err(err(format!("empty segment in `{what}` path `{s}`")));
222        }
223        if let Some((first, rest)) = seg.split_once(char::is_whitespace) {
224            let _ = first;
225            return Err(err(format!("unexpected `{}` in `{what}`", rest.trim())));
226        }
227        let seg = seg.strip_prefix("r#").unwrap_or(seg);
228        let is_ident = syn::parse::Parser::parse_str(syn::Ident::parse_any, seg).is_ok();
229        if !(is_ident || seg.bytes().all(|b| b.is_ascii_digit())) {
230            return Err(err(format!("`{seg}` in `{what}` is not a field name")));
231        }
232        out.push(seg.to_string());
233    }
234    Ok(out)
235}
236
237/// `path` or `path & mask` (design 0002 §2.1).
238fn parse_only(lit: &LitStr) -> Result<Only> {
239    let s = lit.value();
240    let err = |msg: String| Error::new(lit.span(), msg);
241    let (path, mask) = match s.split_once('&') {
242        None => (s.as_str(), None),
243        Some((path, mask)) => {
244            let mask = mask.trim();
245            if mask.is_empty() {
246                return Err(err("`only` expects a mask after `&`, like `\"version & 1\"`".into()));
247            }
248            let parsed = match mask.strip_prefix("0x").or_else(|| mask.strip_prefix("0X")) {
249                Some(hex) => u64::from_str_radix(&hex.replace('_', ""), 16),
250                None => mask.replace('_', "").parse::<u64>(),
251            };
252            let n = parsed.map_err(|_| err(format!("`only` mask `{mask}` is not an integer")))?;
253            if n == 0 {
254                return Err(err("`only` mask must be non-zero".into()));
255            }
256            if n > (1 << 53) - 1 {
257                return Err(err("`only` mask must be at most 2^53 - 1".into()));
258            }
259            (path, Some(n))
260        }
261    };
262    if path.trim().is_empty() {
263        return Err(err("`only` expects a field or variant name, optionally `& mask`: `\"version & 1\"`".into()));
264    }
265    Ok(Only { path: parse_path_str(path, lit, "only")?, mask })
266}
267
268/// The closest candidate for a "did you mean" hint. Like rustc, allow an edit distance of
269/// at most a third of the name's length, and never suggest a name with nothing in common.
270fn closest<'a>(name: &str, candidates: impl IntoIterator<Item = &'a str>) -> Option<&'a str> {
271    /// Edit distance where swapping two adjacent characters counts as one edit, as in rustc
272    /// (optimal string alignment).
273    fn distance(a: &str, b: &str) -> usize {
274        let (a, b): (Vec<char>, Vec<char>) = (a.chars().collect(), b.chars().collect());
275        let mut d: Vec<Vec<usize>> = (0..=a.len()).map(|i| vec![i; b.len() + 1]).collect();
276        d[0] = (0..=b.len()).collect();
277        for i in 1..=a.len() {
278            for j in 1..=b.len() {
279                let cost = usize::from(a[i - 1] != b[j - 1]);
280                d[i][j] = (d[i - 1][j - 1] + cost).min(d[i - 1][j] + 1).min(d[i][j - 1] + 1);
281                if i > 1 && j > 1 && a[i - 1] == b[j - 2] && a[i - 2] == b[j - 1] {
282                    d[i][j] = d[i][j].min(d[i - 2][j - 2] + 1);
283                }
284            }
285        }
286        d[a.len()][b.len()]
287    }
288    let limit = (name.chars().count() / 3).max(1);
289    candidates
290        .into_iter()
291        .map(|c| (distance(name, c), c))
292        .filter(|&(d, _)| d <= limit && d < name.chars().count())
293        .min()
294        .map(|(_, c)| c)
295}
296
297fn unknown_field(name: &str, fields: &[Field], what: &str) -> String {
298    if fields.is_empty() {
299        return format!("{what} refers to `{name}`, but there are no fields");
300    }
301    if let Some(best) = closest(name, fields.iter().map(|f| f.name.as_str())) {
302        return format!("{what} refers to unknown field `{name}`; did you mean `{best}`?");
303    }
304    let names: Vec<String> = fields.iter().map(|f| format!("`{}`", f.name)).collect();
305    format!("{what} refers to unknown field `{name}`; available: {}", names.join(", "))
306}
307
308/// Parse a summary format string: `{field}` references, `{{`/`}}` escapes, literal text.
309fn summary(lit: &LitStr, fields: &[Field], has_items: bool) -> Result<Vec<Part>> {
310    let s = lit.value();
311    let err = |msg: String| Error::new(lit.span(), msg);
312    let mut parts = Vec::new();
313    let mut text = String::new();
314    let mut chars = s.chars().peekable();
315    while let Some(c) = chars.next() {
316        match c {
317            '{' if chars.peek() == Some(&'{') => {
318                chars.next();
319                text.push('{');
320            }
321            '}' if chars.peek() == Some(&'}') => {
322                chars.next();
323                text.push('}');
324            }
325            '{' if chars.peek() == Some(&'#') => {
326                chars.next();
327                if chars.next() != Some('}') {
328                    return Err(err("`{#` must be followed by `}`: `{#}` is the number of elements".into()));
329                }
330                if !has_items {
331                    return Err(err("`{#}` counts elements, but this type has no `items`".into()));
332                }
333                if !text.is_empty() {
334                    parts.push(Part::Lit(std::mem::take(&mut text)));
335                }
336                parts.push(Part::Count);
337            }
338            '{' => {
339                let mut name = String::new();
340                loop {
341                    match chars.next() {
342                        Some('}') => break,
343                        Some(c) if c.is_alphanumeric() || c == '_' => name.push(c),
344                        Some(':') => {
345                            return Err(err(format!(
346                                "format specs are not supported in summaries: use `{{{name}}}`"
347                            )))
348                        }
349                        Some(c) => {
350                            return Err(err(format!(
351                                "`{c}` in `{{{name}...}}`: summaries can only refer to fields by name, like `{{len}}` or `{{0}}`"
352                            )))
353                        }
354                        None => return Err(err("unclosed `{` in summary (write `{{` for a literal brace)".into())),
355                    }
356                }
357                if name.is_empty() {
358                    return Err(err("empty `{}` in summary: name a field, like `{len}`".into()));
359                }
360                let name = name.strip_prefix("r#").map(str::to_string).unwrap_or(name);
361                if !fields.iter().any(|f| f.name == name) {
362                    return Err(err(unknown_field(&name, fields, "summary")));
363                }
364                if !text.is_empty() {
365                    parts.push(Part::Lit(std::mem::take(&mut text)));
366                }
367                parts.push(Part::Field(name));
368            }
369            '}' => return Err(err("unmatched `}` in summary (write `}}` for a literal brace)".into())),
370            c => text.push(c),
371        }
372    }
373    if !text.is_empty() {
374        parts.push(Part::Lit(text));
375    }
376    Ok(parts)
377}
378
379fn model(input: &DeriveInput) -> Result<Ty> {
380    let generic = input.generics.params.iter().any(|p| !matches!(p, GenericParam::Lifetime(_)));
381    let (summary_lit, body, alts) = match &input.data {
382        Data::Struct(s) => {
383            let o = opts(&input.attrs, Place::Struct)?;
384            let fs = fields(&s.fields, Place::StructField)?;
385            let alts = alternatives(&o.alternatives)?;
386            if let (Some((lit, _)), true) = (o.alternatives.first(), fs.iter().any(|f| f.items)) {
387                return Err(Error::new(
388                    lit.span(),
389                    "use either field-level `items` or `items = \"...\"` on the type, not both",
390                ));
391            }
392            for (alt, (lit, len)) in alts.iter().zip(&o.alternatives) {
393                check_struct_path(&alt.items, lit, &fs, "`items`")?;
394                if let (Some(path), Some(len)) = (&alt.len, len) {
395                    check_struct_path(path, len, &fs, "`len`")?;
396                }
397            }
398            (o.summary, Body::Struct(fs), alts)
399        }
400        Data::Enum(e) => {
401            let o = opts(&input.attrs, Place::Enum)?;
402            let alts = alternatives(&o.alternatives)?;
403            let mut variants = Vec::new();
404            for v in &e.variants {
405                let o = opts(&v.attrs, Place::Variant)?;
406                let fs = fields(&v.fields, Place::VariantField)?;
407                let summary = o.summary.as_ref().map(|lit| summary(lit, &fs, !alts.is_empty())).transpose()?;
408                variants.push(Variant { name: v.ident.unraw().to_string(), summary, fields: fs });
409            }
410            for (alt, (lit, len)) in alts.iter().zip(&o.alternatives) {
411                check_enum_path(&alt.items, lit, &variants)?;
412                if let (Some(path), Some(len)) = (&alt.len, len) {
413                    check_enum_path(path, len, &variants)?;
414                }
415            }
416            (None, Body::Enum(variants), alts)
417        }
418        Data::Union(u) => {
419            return Err(Error::new(u.union_token.span, "`Debuggable` can't be derived for unions"));
420        }
421    };
422    let summary = match (&summary_lit, &body) {
423        (Some(lit), Body::Struct(fs)) => Some(summary(lit, fs, !alts.is_empty() || fs.iter().any(|f| f.items))?),
424        _ => None,
425    };
426    Ok(Ty { name: input.ident.unraw().to_string(), generic, summary, body, alternatives: alts })
427}
428
429/// Parse the paths of type-level `items = "..."` alternatives (design 0003).
430fn alternatives(raw: &[(LitStr, Option<LitStr>)]) -> Result<Vec<Alternative>> {
431    raw.iter()
432        .map(|(items, len)| {
433            Ok(Alternative {
434                items: parse_path(items, "items")?,
435                len: len.as_ref().map(|l| parse_path(l, "len")).transpose()?,
436            })
437        })
438        .collect()
439}
440
441/// On a struct, a path must start at one of its fields.
442fn check_struct_path(path: &[String], lit: &LitStr, fields: &[Field], what: &str) -> Result<()> {
443    if fields.iter().any(|f| f.name == path[0]) {
444        return Ok(());
445    }
446    Err(Error::new(lit.span(), unknown_field(&path[0], fields, what)))
447}
448
449/// On an enum, a path starts at a variant, then (if it goes on) one of that variant's fields.
450fn check_enum_path(path: &[String], lit: &LitStr, variants: &[Variant]) -> Result<()> {
451    let Some(v) = variants.iter().find(|v| v.name == path[0]) else {
452        let msg = match closest(&path[0], variants.iter().map(|v| v.name.as_str())) {
453            Some(best) => format!("unknown variant `{}`; did you mean `{best}`?", path[0]),
454            None => {
455                let names: Vec<String> = variants.iter().map(|v| format!("`{}`", v.name)).collect();
456                format!("unknown variant `{}`; the enum has {}", path[0], names.join(", "))
457            }
458        };
459        return Err(Error::new(lit.span(), msg));
460    };
461    match path.get(1) {
462        Some(field) if !v.fields.iter().any(|f| &f.name == field) => {
463            let mut msg = format!("variant `{}` has no field `{field}`", v.name);
464            if let Some(best) = closest(field, v.fields.iter().map(|f| f.name.as_str())) {
465                msg.push_str(&format!("; did you mean `{best}`?"));
466            }
467            Err(Error::new(lit.span(), msg))
468        }
469        _ => Ok(()),
470    }
471}
472
473#[cfg(test)]
474mod tests {
475    use super::*;
476
477    fn json(src: &str) -> String {
478        let input: DeriveInput = syn::parse_str(src).unwrap();
479        let call = emit::entry_call(&model(&input).unwrap());
480        // `::debuggable::__entry!("Name", "<json tail>");` -> the JSON tail, unescaped
481        let lit: LitStr = syn::parse_str(call.rsplit_once(", ").unwrap().1.trim_end_matches(");")).unwrap();
482        lit.value()
483    }
484
485    fn error(src: &str) -> String {
486        let input: DeriveInput = syn::parse_str(src).unwrap();
487        match model(&input) {
488            Ok(_) => panic!("expected an error for: {src}"),
489            Err(e) => e.to_string(),
490        }
491    }
492
493    #[test]
494    fn struct_with_everything() {
495        assert_eq!(
496            json(r#"#[debuggable(summary = "{len} items")] struct M<K, V> {
497                #[debuggable(items, len = "len")] slots: Vec<V>,
498                #[debuggable(hide)] free_head: u32,
499                len: u32,
500                _k: std::marker::PhantomData<K>,
501                #[debuggable(rename = "count")] n: u8,
502            }"#),
503            r#""generic":true,"kind":"struct","summary":[["field","len"],["lit"," items"]],"hide":["free_head","_k"],"rename":{"n":"count"},"items":{"field":"slots","len":"len"}}"#
504        );
505    }
506
507    #[test]
508    fn text_fields() {
509        assert_eq!(
510            json(r#"#[debuggable(summary = "{xs}")] struct S<const N: usize> {
511                #[debuggable(hide)] len: u8,
512                #[debuggable(text, len = "len", hide)] xs: [u8; N],
513                #[debuggable(text)] tag: [u8; 4],
514            }"#),
515            r#""generic":true,"kind":"struct","summary":[["field","xs"]],"hide":["len","xs"],"text":[{"field":"xs","len":"len"},{"field":"tag"}]}"#
516        );
517    }
518
519    #[test]
520    fn slots_fields() {
521        assert_eq!(
522            json(r#"#[debuggable(summary = "{len} items")] struct S<T> {
523                #[debuggable(items, len = "n", only = "version & 0x1", value = "u.r#value")] slots: Vec<T>,
524                n: usize, len: u32,
525            }"#),
526            r#""generic":true,"kind":"struct","summary":[["field","len"],["lit"," items"]],"slots":{"field":"slots","len":"n","only":{"path":["version"],"mask":1},"value":["u","value"]}}"#
527        );
528        assert_eq!(
529            json(r#"struct S { #[debuggable(items, only = "Occupied", value = "0")] e: Vec<u8> }"#),
530            r#""generic":false,"kind":"struct","slots":{"field":"e","only":{"path":["Occupied"]},"value":["0"]}}"#
531        );
532        assert_eq!(
533            // plain items: unchanged
534            json(r#"struct S { #[debuggable(items)] e: Vec<u8> }"#),
535            r#""generic":false,"kind":"struct","items":{"field":"e"}}"#
536        );
537    }
538
539    #[test]
540    fn alternatives_on_struct_and_enum() {
541        assert_eq!(
542            json(r#"#[debuggable(summary = "{#} items")]
543                #[debuggable(items = "data.Inline.0", len = "capacity")]
544                #[debuggable(items = "data.Heap.ptr", len = "data.Heap.len")]
545                struct SmallVec<A> { #[debuggable(hide)] capacity: usize, #[debuggable(hide)] data: D<A> }"#),
546            r#""generic":true,"kind":"struct","summary":[["count",""],["lit"," items"]],"hide":["capacity","data"],"alternatives":[{"items":["data","Inline","0"],"len":["capacity"]},{"items":["data","Heap","ptr"],"len":["data","Heap","len"]}]}"#
547        );
548        assert_eq!(
549            json(r#"#[debuggable(items = "Inline.0.data", len = "Inline.0.len")]
550                #[debuggable(items = "Heap.0")]
551                enum TinyVec<A> { #[debuggable(summary = "{#} items")] Inline(#[debuggable(hide)] AV<A>), Heap(#[debuggable(hide)] Vec<A>) }"#),
552            r#""generic":true,"kind":"enum","variants":{"Inline":{"summary":[["count",""],["lit"," items"]],"hide":["0"]},"Heap":{"hide":["0"]}},"alternatives":[{"items":["Inline","0","data"],"len":["Inline","0","len"]},{"items":["Heap","0"]}]}"#
553        );
554        assert_eq!(
555            // `{#}` with field-level items too
556            json(r#"#[debuggable(summary = "{#}")] struct S { #[debuggable(items)] v: Vec<u8> }"#),
557            r#""generic":false,"kind":"struct","summary":[["count",""]],"items":{"field":"v"}}"#
558        );
559    }
560
561    #[test]
562    fn enum_variants_and_defaults() {
563        assert_eq!(
564            json(r#"enum Token { #[debuggable(summary = "Ident({name})")] Ident { name: String }, #[debuggable(summary = "Num({0})")] Num(i64), Eof }"#),
565            r#""generic":false,"kind":"enum","variants":{"Ident":{"summary":[["lit","Ident("],["field","name"],["lit",")"]]},"Num":{"summary":[["lit","Num("],["field","0"],["lit",")"]]}}}"#
566        );
567        assert_eq!(json("enum E { A, B }"), r#""generic":false,"kind":"enum","variants":{}}"#);
568    }
569
570    #[test]
571    fn lifetimes_alone_are_not_generic_and_raw_idents_are_unraw() {
572        assert_eq!(
573            json(r#"#[debuggable(summary = "{type}")] struct r#S<'a> { r#type: &'a str }"#),
574            r#""generic":false,"kind":"struct","summary":[["field","type"]]}"#
575        );
576    }
577
578    #[test]
579    fn json_is_ascii_and_quote_safe() {
580        // `bs` is a backslash, so the expected JSON escapes stay visible as escapes.
581        let bs = '\\';
582        assert_eq!(
583            json(r#"#[debuggable(summary = "{0}°C ''' \"q\" {{x}}")] struct C(f32);"#),
584            format!(r#""generic":false,"kind":"struct","summary":[["field","0"],["lit","{bs}u00b0C {bs}u0027{bs}u0027{bs}u0027 {bs}"q{bs}" {{x}}"]]}}"#)
585        );
586    }
587
588    #[test]
589    fn errors() {
590        let cases = [
591            (r#"#[debuggable(sumary = "x")] struct S;"#, "unknown `debuggable` option `sumary`; did you mean `summary`?"),
592            (r#"#[debuggable(colour = "x")] struct S;"#, "expected one of: `summary`"),
593            (r#"#[debuggable(summary = "{lenght}")] struct S { length: u8 }"#, "did you mean `length`?"),
594            (r#"#[debuggable(summary = "a", summary = "b")] struct S;"#, "duplicate `summary`"),
595            (r#"#[debuggable(summary = "x")] enum E { A }"#, "goes on each variant"),
596            (r#"#[debuggable(hide)] struct S { a: u8 }"#, "fields only"),
597            (r#"struct S { #[debuggable(summary = "x")] a: u8 }"#, "not on a field"),
598            (r#"enum E { A { #[debuggable(items)] v: Vec<u8> } }"#, "not supported inside enum variants"),
599            (r#"struct S { #[debuggable(len = "n")] v: Vec<u8>, n: usize }"#, "`len` needs `items` or `text`"),
600            (r#"struct S { #[debuggable(items, text)] v: Vec<u8> }"#, "both `items` and `text`"),
601            (r#"struct S { #[debuggable(text, text)] v: Vec<u8> }"#, "duplicate `text`"),
602            (r#"struct S { #[debuggable(txt)] v: Vec<u8> }"#, "did you mean `text`?"),
603            (r#"enum E { A { #[debuggable(text)] v: Vec<u8> } }"#, "`text` is not supported inside enum variants"),
604            (r#"struct S { #[debuggable(items)] a: Vec<u8>, #[debuggable(items)] b: Vec<u8> }"#, "only one field"),
605            (r#"struct S { #[debuggable(items, len = "count")] v: Vec<u8>, n: usize }"#, "unknown field `count`; available: `v`, `n`"),
606            (r#"#[debuggable(summary = "{x}")] struct S { a: u8 }"#, "unknown field `x`; available: `a`"),
607            (r#"#[debuggable(summary = "{0}")] struct S { a: u8 }"#, "unknown field `0`"),
608            (r#"#[debuggable(summary = "{a:?}")] struct S { a: u8 }"#, "format specs are not supported"),
609            (r#"#[debuggable(summary = "{a.b}")] struct S { a: u8 }"#, "can only refer to fields by name"),
610            (r#"#[debuggable(summary = "{a")] struct S { a: u8 }"#, "unclosed `{`"),
611            (r#"#[debuggable(summary = "a}")] struct S { a: u8 }"#, "unmatched `}`"),
612            (r#"#[debuggable(summary = "{}")] struct S { a: u8 }"#, "empty `{}`"),
613            (r#"struct S { #[debuggable(hide, rename = "b")] a: u8 }"#, "hidden field can't be renamed"),
614            (r#"struct S { #[debuggable(hide, items)] a: Vec<u8> }"#, "remove `hide`"),
615            (r#"struct S { #[debuggable(hide = "yes")] a: u8 }"#, "takes no value"),
616            (r#"struct S { #[debuggable(rename = 3)] a: u8 }"#, "expected `rename = \"...\"`"),
617            (r#"struct S { #[debuggable(rename = "")] a: u8 }"#, "non-empty"),
618            (r#"union U { a: u8 }"#, "can't be derived for unions"),
619            (r#"struct S { #[debuggable(only = "x")] v: Vec<u8> }"#, "`only` needs `items`"),
620            (r#"struct S { #[debuggable(value = "x")] v: Vec<u8> }"#, "`value` needs `items`"),
621            (r#"struct S { #[debuggable(items, only = "")] v: Vec<u8> }"#, "`only` expects a field or variant name"),
622            (r#"struct S { #[debuggable(items, only = "a..b")] v: Vec<u8> }"#, "empty segment"),
623            (r#"struct S { #[debuggable(items, only = "a & 0")] v: Vec<u8> }"#, "mask must be non-zero"),
624            (r#"struct S { #[debuggable(items, only = "a & 9007199254740992")] v: Vec<u8> }"#, "at most 2^53 - 1"),
625            (r#"struct S { #[debuggable(items, only = "a &")] v: Vec<u8> }"#, "expects a mask"),
626            (r#"struct S { #[debuggable(items, only = "a b")] v: Vec<u8> }"#, "unexpected `b`"),
627            (r#"struct S { #[debuggable(items, value = "a.-b")] v: Vec<u8> }"#, "not a field name"),
628            (r#"struct S { #[debuggable(items, only = "a", only = "b")] v: Vec<u8> }"#, "duplicate `only`"),
629            (r#"struct S { #[debuggable(items, onyl = "x")] v: Vec<u8> }"#, "did you mean `only`?"),
630            (r#"#[debuggable(items = "dta.x")] struct S { data: u8 }"#, "`items` refers to unknown field `dta`; did you mean `data`?"),
631            (r#"#[debuggable(items = "Hep.0")] enum E { Heap(Vec<u8>) }"#, "unknown variant `Hep`; did you mean `Heap`?"),
632            (r#"#[debuggable(items = "Heap.x")] enum E { Heap(Vec<u8>) }"#, "variant `Heap` has no field `x`"),
633            (r#"#[debuggable(len = "n")] struct S { n: u8 }"#, "`len` on a type needs `items = \"...\"` in the same attribute"),
634            (r#"struct S { #[debuggable(items = "v")] v: Vec<u8> }"#, "on a field, write `items` without a value"),
635            (r#"#[debuggable(items = "v")] struct S { #[debuggable(items)] v: Vec<u8> }"#, "either field-level `items` or `items = \"...\"` on the type, not both"),
636            (r#"#[debuggable(summary = "{#}")] struct S { a: u8 }"#, "`{#}` counts elements, but this type has no `items`"),
637            (r#"#[debuggable(items = "v")] struct S { #[debuggable(only = "x")] v: Vec<u8> }"#, "`only` needs `items`"),
638            (r#"#[debuggable(items, len = "n")] struct S { n: u8 }"#, "on a type, write `items = \"path\"`"),
639        ];
640        for (src, want) in cases {
641            let got = error(src);
642            assert!(got.contains(want), "for {src}\n  want: {want}\n  got:  {got}");
643        }
644    }
645}