logo
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
#[cfg(feature = "span")]
use miette::SourceSpan;
use std::{fmt::Display, str::FromStr};

use crate::{parser, KdlError, KdlIdentifier, KdlValue};

/// KDL Entries are the "arguments" to KDL nodes: either a (positional)
/// [`Argument`](https://github.com/kdl-org/kdl/blob/main/SPEC.md#argument) or
/// a (key/value)
/// [`Property`](https://github.com/kdl-org/kdl/blob/main/SPEC.md#property)
#[derive(Debug, Clone)]
pub struct KdlEntry {
    pub(crate) leading: Option<String>,
    pub(crate) ty: Option<KdlIdentifier>,
    pub(crate) value: KdlValue,
    pub(crate) value_repr: Option<String>,
    pub(crate) name: Option<KdlIdentifier>,
    pub(crate) trailing: Option<String>,
    #[cfg(feature = "span")]
    pub(crate) span: SourceSpan,
}

impl PartialEq for KdlEntry {
    fn eq(&self, other: &Self) -> bool {
        self.leading == other.leading
            && self.ty == other.ty
            && self.value == other.value
            && self.value_repr == other.value_repr
            && self.name == other.name
            && self.trailing == other.trailing
        // intentionally omitted: self.span == other.span
    }
}

impl KdlEntry {
    /// Creates a new Argument (positional) KdlEntry.
    pub fn new(value: impl Into<KdlValue>) -> Self {
        KdlEntry {
            leading: None,
            ty: None,
            value: value.into(),
            value_repr: None,
            name: None,
            trailing: None,
            #[cfg(feature = "span")]
            span: SourceSpan::from(0..0),
        }
    }

    /// Gets a reference to this entry's name, if it's a property entry.
    pub fn name(&self) -> Option<&KdlIdentifier> {
        self.name.as_ref()
    }

    /// Gets the entry's value.
    pub fn value(&self) -> &KdlValue {
        &self.value
    }

    /// Gets a mutable reference to this entry's value.
    pub fn value_mut(&mut self) -> &mut KdlValue {
        &mut self.value
    }

    /// Sets the entry's value.
    pub fn set_value(&mut self, value: impl Into<KdlValue>) {
        self.value = value.into();
    }

    /// Gets this entry's span.
    ///
    /// This value will be properly initialized when created via [`KdlDocument::parse`]
    /// but may become invalidated if the document is mutated. We do not currently
    /// guarantee this to yield any particularly consistent results at that point.
    #[cfg(feature = "span")]
    pub fn span(&self) -> &SourceSpan {
        &self.span
    }

    /// Gets a mutable reference to this entry's span.
    #[cfg(feature = "span")]
    pub fn span_mut(&mut self) -> &mut SourceSpan {
        &mut self.span
    }

    /// Sets this entry's span.
    #[cfg(feature = "span")]
    pub fn set_span(&mut self, span: impl Into<SourceSpan>) {
        self.span = span.into();
    }

    /// Gets the entry's type.
    pub fn ty(&self) -> Option<&KdlIdentifier> {
        self.ty.as_ref()
    }

    /// Gets a mutable reference to this entry's type.
    pub fn ty_mut(&mut self) -> Option<&mut KdlIdentifier> {
        self.ty.as_mut()
    }

    /// Sets the entry's type.
    pub fn set_ty(&mut self, ty: impl Into<KdlIdentifier>) {
        self.ty = Some(ty.into());
    }

    /// Creates a new Property (key/value) KdlEntry.
    pub fn new_prop(key: impl Into<KdlIdentifier>, value: impl Into<KdlValue>) -> Self {
        KdlEntry {
            leading: None,
            ty: None,
            value: value.into(),
            value_repr: None,
            name: Some(key.into()),
            trailing: None,
            #[cfg(feature = "span")]
            span: SourceSpan::from(0..0),
        }
    }

    /// Gets leading text (whitespace, comments) for this KdlEntry.
    pub fn leading(&self) -> Option<&str> {
        self.leading.as_deref()
    }

    /// Sets leading text (whitespace, comments) for this KdlEntry.
    pub fn set_leading(&mut self, leading: impl Into<String>) {
        self.leading = Some(leading.into());
    }

    /// Gets trailing text (whitespace, comments) for this KdlEntry.
    pub fn trailing(&self) -> Option<&str> {
        self.trailing.as_deref()
    }

    /// Sets trailing text (whitespace, comments) for this KdlEntry.
    pub fn set_trailing(&mut self, trailing: impl Into<String>) {
        self.trailing = Some(trailing.into());
    }

    /// Clears leading and trailing text (whitespace, comments), as well as
    /// resetting this entry's value to its default representation.
    pub fn clear_fmt(&mut self) {
        self.leading = None;
        self.trailing = None;
        self.value_repr = None;
        if let Some(ty) = &mut self.ty {
            ty.clear_fmt();
        }
        if let Some(name) = &mut self.name {
            name.clear_fmt();
        }
    }

    /// Gets the custom string representation for this KdlEntry's [`KdlValue`].
    pub fn value_repr(&self) -> Option<&str> {
        self.value_repr.as_deref()
    }

    /// Sets a custom string representation for this KdlEntry's [`KdlValue`].
    pub fn set_value_repr(&mut self, repr: impl Into<String>) {
        self.value_repr = Some(repr.into());
    }

    /// Length of this entry when rendered as a string.
    pub fn len(&self) -> usize {
        format!("{}", self).len()
    }

    /// Returns true if this entry is completely empty (including whitespace).
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Auto-formats this entry.
    pub fn fmt(&mut self) {
        self.leading = None;
        self.trailing = None;
        self.value_repr = None;
        if let Some(name) = &mut self.name {
            name.fmt();
        }
    }
}

impl Display for KdlEntry {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if let Some(leading) = &self.leading {
            write!(f, "{}", leading)?;
        }
        if let Some(name) = &self.name {
            write!(f, "{}=", name)?;
        }
        if let Some(ty) = &self.ty {
            write!(f, "({})", ty)?;
        }
        if let Some(repr) = &self.value_repr {
            write!(f, "{}", repr)?;
        } else {
            write!(f, "{}", self.value)?;
        }
        if let Some(trailing) = &self.trailing {
            write!(f, "{}", trailing)?;
        }
        Ok(())
    }
}

impl<T> From<T> for KdlEntry
where
    T: Into<KdlValue>,
{
    fn from(value: T) -> Self {
        KdlEntry::new(value)
    }
}

impl<K, V> From<(K, V)> for KdlEntry
where
    K: Into<KdlIdentifier>,
    V: Into<KdlValue>,
{
    fn from((key, value): (K, V)) -> Self {
        KdlEntry::new_prop(key, value)
    }
}

impl FromStr for KdlEntry {
    type Err = KdlError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let kdl_parser = parser::KdlParser::new(s);
        kdl_parser.parse(parser::entry_with_trailing(&kdl_parser))
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn reset_value_repr() -> miette::Result<()> {
        let mut left_entry: KdlEntry = "   name=1.03e2".parse()?;
        let mut right_entry: KdlEntry = "   name=103.0".parse()?;
        assert_ne!(left_entry, right_entry);
        left_entry.clear_fmt();
        right_entry.clear_fmt();
        assert_eq!(left_entry, right_entry);
        Ok(())
    }

    #[test]
    fn new() {
        let entry = KdlEntry::new(42);
        assert_eq!(
            entry,
            KdlEntry {
                leading: None,
                ty: None,
                value: KdlValue::Base10(42),
                value_repr: None,
                name: None,
                trailing: None,
                #[cfg(feature = "span")]
                span: SourceSpan::from(0..0),
            }
        );

        let entry = KdlEntry::new_prop("name", 42);
        assert_eq!(
            entry,
            KdlEntry {
                leading: None,
                ty: None,
                value: KdlValue::Base10(42),
                value_repr: None,
                name: Some("name".into()),
                trailing: None,
                #[cfg(feature = "span")]
                span: SourceSpan::from(0..0),
            }
        );
    }

    #[test]
    fn parsing() -> miette::Result<()> {
        let entry: KdlEntry = " \\\n (\"m\\\"eh\")0xDEADbeef\t\\\n".parse()?;
        assert_eq!(
            entry,
            KdlEntry {
                leading: Some(" \\\n ".into()),
                ty: Some("\"m\\\"eh\"".parse()?),
                value: KdlValue::Base16(0xdeadbeef),
                value_repr: Some("0xDEADbeef".into()),
                name: None,
                trailing: Some("\t\\\n".into()),
                #[cfg(feature = "span")]
                span: SourceSpan::from(0..0),
            }
        );

        let entry: KdlEntry = " \\\n \"foo\"=(\"m\\\"eh\")0xDEADbeef\t\\\n".parse()?;
        assert_eq!(
            entry,
            KdlEntry {
                leading: Some(" \\\n ".into()),
                ty: Some("\"m\\\"eh\"".parse()?),
                value: KdlValue::Base16(0xdeadbeef),
                value_repr: Some("0xDEADbeef".into()),
                name: Some("\"foo\"".parse()?),
                trailing: Some("\t\\\n".into()),
                #[cfg(feature = "span")]
                span: SourceSpan::from(0..0),
            }
        );

        Ok(())
    }

    #[test]
    fn display() {
        let entry = KdlEntry::new(KdlValue::Base10(42));
        assert_eq!(format!("{}", entry), "42");

        let entry = KdlEntry::new_prop("name", KdlValue::Base10(42));
        assert_eq!(format!("{}", entry), "name=42");
    }
}