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
use std::{collections::HashMap, convert::TryFrom, fmt};

use crate::TryFromKdlNodeValueError;

/// A node representing the smallest unit of a KDL document.
///
/// The anatomy of a node:
/// ```text
/// name "value" property_key="property value" {
///     child
/// }
/// ```
///
/// ## Example
///
/// ```
/// use kdl::{KdlNode, KdlValue};
/// use std::collections::HashMap;
///
/// const DOCUMENT: &str = r#"
/// name "value" property_key="property value" {
///     child
/// }
/// "#;
///
/// assert_eq!(
///     kdl::parse_document(DOCUMENT).unwrap(),
///     vec![
///         KdlNode {
///             name: String::from("name"),
///             values: vec![KdlValue::String("value".into())],
///             properties: {
///                 let mut temp = HashMap::new();
///                 temp.insert(
///                     String::from("property_key"),
///                     KdlValue::String("property value".into())
///                 );
///                 temp
///             },
///             children: vec![
///                 KdlNode {
///                     name: String::from("child"),
///                     ..Default::default()
///                 }
///             ],
///         }
///     ]
/// )
/// ```
#[derive(Default, Debug, Clone, PartialEq)]
pub struct KdlNode {
    pub name: String,
    pub values: Vec<KdlValue>,
    pub properties: HashMap<String, KdlValue>,
    pub children: Vec<KdlNode>,
}

/// A value present in either a node's values or in a node's properties.
#[derive(Debug, Clone, PartialEq)]
pub enum KdlValue {
    Int(i64),
    Float(f64),
    String(String),
    Boolean(bool),
    Null,
}

impl fmt::Display for KdlNode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.write(f, 0)
    }
}

impl KdlNode {
    fn write(&self, f: &mut fmt::Formatter<'_>, indent: usize) -> fmt::Result {
        write!(f, "{:indent$}", "", indent = indent)?;

        display_identifier(f, &self.name)?;
        for arg in &self.values {
            write!(f, " {}", arg)?;
        }
        for (prop, value) in &self.properties {
            write!(f, " ")?;
            display_identifier(f, prop)?;
            write!(f, "={}", value)?;
        }

        if self.children.is_empty() {
            return Ok(());
        }

        writeln!(f, " {{")?;
        for child in &self.children {
            child.write(f, indent + 4)?;
            writeln!(f)?;
        }
        write!(f, "{:indent$}}}", "", indent = indent)?;

        Ok(())
    }
}
impl fmt::Display for KdlValue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        use KdlValue::*;
        match self {
            Int(x) => write!(f, "{}", x),
            Float(x) => write!(f, "{}", x),
            String(x) => display_string(f, x),
            Boolean(x) => write!(f, "{}", x),
            Null => write!(f, "null"),
        }
    }
}

fn display_identifier(f: &mut fmt::Formatter<'_>, s: &str) -> fmt::Result {
    if let Ok(("", identifier)) = crate::parser::bare_identifier(s) {
        write!(f, "{}", identifier)
    } else {
        display_string(f, s)
    }
}

fn display_string(f: &mut fmt::Formatter<'_>, s: &str) -> fmt::Result {
    write!(f, "\"")?;
    for c in s.chars() {
        match crate::parser::ESCAPE_CHARS.1.get(&c) {
            None => write!(f, "{}", c)?,
            Some(c) => write!(f, "\\{}", c)?,
        }
    }
    write!(f, "\"")?;
    Ok(())
}

// Support conversions from base types into KdlNodeValue

impl From<i64> for KdlValue {
    fn from(v: i64) -> Self {
        Self::Int(v)
    }
}

impl From<f64> for KdlValue {
    fn from(v: f64) -> Self {
        Self::Float(v)
    }
}

impl From<String> for KdlValue {
    fn from(v: String) -> Self {
        Self::String(v)
    }
}

impl From<&str> for KdlValue {
    fn from(v: &str) -> Self {
        Self::String(v.to_owned())
    }
}

impl From<bool> for KdlValue {
    fn from(v: bool) -> Self {
        Self::Boolean(v)
    }
}

impl<T> From<Option<T>> for KdlValue
where
    T: Into<KdlValue>,
{
    fn from(v: Option<T>) -> Self {
        v.map_or(KdlValue::Null, |v| v.into())
    }
}

// Support reverse conversions using TryFrom

// Synthesizes a TryFrom impl for both the base type and an Option variant.
//
// We need the Option variant because we can't write a blanket impl due to the existing
//   impl<T, U> TryFrom<U> for T where U: Into<T>
// even though KdlNodeValue does not implement Into<Option<_>>.
macro_rules! impl_try_from {
    (<$($lt:lifetime)?> $source:ty => $typ:ty, $($good:pat => $value:expr),+; $($bad:ident),+) => {
        impl<$($lt)?> TryFrom<$source> for $typ {
            type Error = TryFromKdlNodeValueError;
            fn try_from(value: $source) -> Result<Self, Self::Error> {
                match value {
                    $( $good => Ok($value), )+
                    $( KdlValue::$bad(_) => Err(TryFromKdlNodeValueError {
                        expected: stringify!($typ),
                        variant: stringify!($bad)
                    }), )+
                    KdlValue::Null => Err(TryFromKdlNodeValueError {
                        expected: stringify!($typ),
                        variant: "Null"
                    }),
                }
            }
        }
        impl<$($lt)?> TryFrom<$source> for Option<$typ> {
            type Error = TryFromKdlNodeValueError;
            fn try_from(value: $source) -> Result<Self, Self::Error> {
                match value {
                    $( $good => Ok(Some($value)), )+
                    $( KdlValue::$bad(_) => Err(TryFromKdlNodeValueError {
                        expected: concat!("Option::<", stringify!($typ), ">"),
                        variant: stringify!($bad)
                    }), )+
                    KdlValue::Null => Ok(None),
                }
            }
        }
    };
    (& $($lt:lifetime)?, $typ:ty, $($tt:tt)*) => {
        impl_try_from!(<$($lt)?> & $($lt)? KdlValue => $typ, $($tt)*);
    };
    ($typ:ty, $($tt:tt)*) => {
        impl_try_from!(<> KdlValue => $typ, $($tt)*);
    };
}

impl_try_from!(i64, KdlValue::Int(v) => v; Float, String, Boolean);
impl_try_from!(&, i64, KdlValue::Int(v) => *v; Float, String, Boolean);
impl_try_from!(f64, KdlValue::Float(v) => v; Int, String, Boolean);
impl_try_from!(&, f64, KdlValue::Float(v) => *v; Int, String, Boolean);
impl_try_from!(String, KdlValue::String(v) => v; Int, Float, Boolean);
impl_try_from!(&'a, &'a str, KdlValue::String(v) => &v[..]; Int, Float, Boolean);
impl_try_from!(bool, KdlValue::Boolean(v) => v; Int, Float, String);
impl_try_from!(&, bool, KdlValue::Boolean(v) => *v; Int, Float, String);

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

    #[test]
    fn display_value() {
        assert_eq!("1", format!("{}", KdlValue::Int(1)));
        assert_eq!("1.5", format!("{}", KdlValue::Float(1.5)));
        assert_eq!("true", format!("{}", KdlValue::Boolean(true)));
        assert_eq!("false", format!("{}", KdlValue::Boolean(false)));
        assert_eq!("null", format!("{}", KdlValue::Null));
        assert_eq!(
            r#""foo""#,
            format!("{}", KdlValue::String("foo".to_owned()))
        );
        assert_eq!(
            r#""foo \"bar\" baz""#,
            format!("{}", KdlValue::String(r#"foo "bar" baz"#.to_owned()))
        );
    }

    #[test]
    fn display_node() {
        let mut value = KdlNode {
            name: "foo".into(),
            values: vec![1.into(), "two".into()],
            properties: HashMap::new(),
            children: vec![],
        };

        value.properties.insert("three".to_owned(), 3.into());

        assert_eq!(r#"foo 1 "two" three=3"#, format!("{}", value));
    }

    #[test]
    fn display_nested_node() {
        let value = KdlNode {
            name: "a1".into(),
            values: vec!["a".into(), 1.into()],
            properties: HashMap::new(),
            children: vec![
                KdlNode {
                    name: "b1".into(),
                    values: vec!["b".into(), 1.into()],
                    properties: HashMap::new(),
                    children: vec![KdlNode {
                        name: "c1".into(),
                        values: vec!["c".into(), 1.into()],
                        properties: HashMap::new(),
                        children: vec![],
                    }],
                },
                KdlNode {
                    name: "b2".into(),
                    values: vec!["b".into(), 2.into()],
                    properties: HashMap::new(),
                    children: vec![KdlNode {
                        name: "c2".into(),
                        values: vec!["c".into(), 2.into()],
                        properties: HashMap::new(),
                        children: vec![],
                    }],
                },
            ],
        };

        assert_eq!(
            r#"
a1 "a" 1 {
    b1 "b" 1 {
        c1 "c" 1
    }
    b2 "b" 2 {
        c2 "c" 2
    }
}"#,
            format!("\n{}", value)
        );
    }

    #[test]
    fn from() {
        assert_eq!(KdlValue::from(1), KdlValue::Int(1));
        assert_eq!(KdlValue::from(1.5), KdlValue::Float(1.5));
        assert_eq!(
            KdlValue::from("foo".to_owned()),
            KdlValue::String("foo".to_owned())
        );
        assert_eq!(KdlValue::from("bar"), KdlValue::String("bar".to_owned()));
        assert_eq!(KdlValue::from(true), KdlValue::Boolean(true));

        assert_eq!(KdlValue::from(None::<i64>), KdlValue::Null);
        assert_eq!(KdlValue::from(Some(1)), KdlValue::Int(1));
    }

    #[test]
    fn try_from_success() {
        assert_eq!(i64::try_from(KdlValue::Int(1)), Ok(1));
        assert_eq!(i64::try_from(&KdlValue::Int(1)), Ok(1));
        assert_eq!(f64::try_from(KdlValue::Float(1.5)), Ok(1.5));
        assert_eq!(f64::try_from(&KdlValue::Float(1.5)), Ok(1.5));
        assert_eq!(
            String::try_from(KdlValue::String("foo".to_owned())),
            Ok("foo".to_owned())
        );
        assert_eq!(
            <&str as TryFrom<_>>::try_from(&KdlValue::String("foo".to_owned())),
            Ok("foo")
        );
        assert_eq!(bool::try_from(KdlValue::Boolean(true)), Ok(true));
        assert_eq!(bool::try_from(&KdlValue::Boolean(true)), Ok(true));

        assert_eq!(Option::<i64>::try_from(KdlValue::Int(1)), Ok(Some(1)));
        assert_eq!(Option::<i64>::try_from(KdlValue::Null), Ok(None));
    }

    #[test]
    fn try_from_failure() {
        // We don't expose the internal format of the error type, so let's just test the message
        // for a couple of cases.
        assert_eq!(
            format!("{}", i64::try_from(KdlValue::Float(1.5)).unwrap_err()),
            "Failed to convert from KdlNodeValue::Float to i64."
        );
        assert_eq!(
            format!(
                "{}",
                Option::<i64>::try_from(KdlValue::Float(1.5)).unwrap_err()
            ),
            "Failed to convert from KdlNodeValue::Float to Option::<i64>."
        );
    }
}