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
//! Infrastructure for contextual error messages
use std::fmt;

use proc_macro2::Span;

use syn::{spanned::Spanned, Ident, Member, Path};

/// Reference to a compound's parent
///
/// This reference can be converted to a hopefully-useful human-readable
/// string via [`std::fmt::Display`].
#[derive(Clone, Debug)]
pub(super) enum ParentRef {
    /// The parent is addressable by a path, e.g. a struct type or enum
    /// variant.
    Named(Path),

    /// The parent is not addressable.
    ///
    /// This is typically the case for compounds created for `ExtractDef`.
    Unnamed {
        /// The parent's ref.
        ///
        /// For extracts, this refers to the compound where the field with
        /// the extract is declared.
        parent: Box<ParentRef>,

        /// The field inside that parent.
        ///
        /// For extracts, this refers to the compound field where the extract
        /// is declared.
        field: Member,
    },

    /// The parent is not addressable, but it is also not the child of another
    /// addressable thing.
    ///
    /// This is typically the case for compounds created for `Wrapped`.
    Wrapper {
        /// A reference to something nameable
        inner: Box<ParentRef>,
    },
}

impl From<Path> for ParentRef {
    fn from(other: Path) -> Self {
        Self::Named(other)
    }
}

impl<'x> From<&'x Path> for ParentRef {
    fn from(other: &'x Path) -> Self {
        Self::Named(other.clone())
    }
}

impl ParentRef {
    /// Create a new `ParentRef` for a member inside this one.
    ///
    /// Returns a [`Self::Unnamed`] with `self` as parent and `member` as
    /// field.
    pub(crate) fn child(&self, member: Member) -> Self {
        Self::Unnamed {
            parent: Box::new(self.clone()),
            field: member,
        }
    }

    /// Create a new `ParentRef` for a wrapper of this one.
    ///
    /// Returns a [`Self::Wrapper`] with `self` as inner element.
    pub(crate) fn wrapper(&self) -> Self {
        Self::Wrapper {
            inner: Box::new(self.clone()),
        }
    }

    /// Return a span which can be used for error messages.
    ///
    /// This points at the closest [`Self::Named`] variant in the parent
    /// chain.
    #[allow(dead_code)]
    pub(crate) fn span(&self) -> Span {
        match self {
            Self::Named(p) => p.span(),
            Self::Unnamed { parent, .. } => parent.span(),
            Self::Wrapper { inner, .. } => inner.span(),
        }
    }

    /// Try to extract an ident from this ParentRef.
    pub(crate) fn try_as_ident(&self) -> Option<&Ident> {
        match self {
            Self::Named(path) => {
                if path.leading_colon.is_some() {
                    return None;
                }
                if path.segments.len() != 1 {
                    return None;
                }
                let segment = &path.segments[0];
                if !segment.arguments.is_empty() {
                    return None;
                }
                Some(&segment.ident)
            }
            _ => None,
        }
    }
}

impl fmt::Display for ParentRef {
    fn fmt<'f>(&self, f: &'f mut fmt::Formatter) -> fmt::Result {
        match self {
            Self::Named(name) => {
                let mut first = true;
                for segment in name.segments.iter() {
                    if !first {
                        write!(f, "::")?;
                    }
                    first = false;
                    write!(f, "{}", segment.ident)?;
                }
                write!(f, " element")
            }
            Self::Unnamed { parent, field } => {
                write!(f, "extraction for {} in {}", FieldName(field), parent)
            }
            Self::Wrapper { inner } => {
                write!(f, "wrapper element of {}", inner)
            }
        }
    }
}

/// Ephemeral struct to create a nice human-readable representation of
/// [`syn::Member`].
///
/// It implements [`std::fmt::Display`] for that purpose and is otherwise of
/// little use.
#[repr(transparent)]
struct FieldName<'x>(&'x Member);

impl<'x> fmt::Display for FieldName<'x> {
    fn fmt<'f>(&self, f: &'f mut fmt::Formatter) -> fmt::Result {
        match self.0 {
            Member::Named(v) => write!(f, "field '{}'", v),
            Member::Unnamed(v) => write!(f, "unnamed field {}", v.index),
        }
    }
}

/// Create a string error message for a missing child element.
///
/// `parent_name` should point at the compound which is being parsed and
/// `field` should be the field to which the child belongs.
pub(super) fn on_missing_child(parent_name: &ParentRef, field: &Member) -> String {
    format!("Missing child {} in {}.", FieldName(&field), parent_name)
}

/// Create a string error message for a duplicate child element.
///
/// `parent_name` should point at the compound which is being parsed and
/// `field` should be the field to which the child belongs.
pub(super) fn on_duplicate_child(parent_name: &ParentRef, field: &Member) -> String {
    format!(
        "{} must not have more than one child in {}.",
        parent_name,
        FieldName(&field)
    )
}

/// Create a string error message for a missing attribute.
///
/// `parent_name` should point at the compound which is being parsed and
/// `field` should be the field to which the attribute belongs.
pub(super) fn on_missing_attribute(parent_name: &ParentRef, field: &Member) -> String {
    format!(
        "Required attribute {} on {} missing.",
        FieldName(&field),
        parent_name
    )
}