Debian Codegraph @

src/derive_debug/type_detection.rs

raw symbols SCIP
1 use super::HowToFmt;
2
3 use syn::Type;
4
5 pub(super) fn detect_type_formatting(ty: &Type) -> HowToFmt {
6 let ty = unwrap_reference(ty);
7
8 // println!("{:?} {}", ty, ty.to_token_stream());
9
10 match ty {
11 Type::Array { .. } | Type::Slice { .. } => HowToFmt::Slice,
12 Type::Path(ty) if ty.qself.is_none() && is_path_an_option(&ty.path) => HowToFmt::Option_,
13 _ => HowToFmt::Regular,
14 }
15 }
16
17 fn unwrap_reference(mut ty: &Type) -> &Type {
18 loop {
19 match ty {
20 Type::Reference(next) => ty = &*next.elem,
21 Type::Group(next) => ty = &*next.elem,
22 Type::Paren(next) => ty = &*next.elem,
23 _ => break,
24 }
25 }
26 ty
27 }
28
29 fn is_path_an_option(path: &syn::Path) -> bool {
30 let segments = &path.segments;
31
32 if segments[0].ident == "Option" {
33 return true;
34 }
35
36 if segments.len() < 3 {
37 return false;
38 }
39
40 let thecrate = &segments[0].ident;
41
42 (thecrate == "core" || thecrate == "alloc" || thecrate == "std")
43 && segments[1].ident == "option"
44 && segments[2].ident == "Option"
45 }
46
47 /// Parses the type as an identifier, or the last identifier of a path.
48 pub(super) fn parse_type_as_ident(ty: &Type) -> Result<&syn::Ident, crate::Error> {
49 let ty = unwrap_reference(ty);
50 match ty {
51 Type::Path(typath) if typath.qself.is_none() && !typath.path.segments.is_empty() => {
52 Ok(&typath.path.segments.last().unwrap().ident)
53 }
54 _ => Err(spanned_err!(ty, "expected a struct or enum")),
55 }
56 }