kdlite 0.1.1

Small streaming KDL parser (based on just-kdl)
Documentation
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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
// SPDX-License-Identifier: MIT OR Apache-2.0
//! document tree structures, start at [`Document`]

use std::borrow::Cow;
use std::cell::Cell;
use std::collections::HashSet;
use std::convert::Infallible;
use std::fmt;
use std::num::FpCategory;
use std::ops::{Index, IndexMut};

use crate::stream::{Error, Event, Parser};
use crate::{cow_static, IdentDisplay};

fn maybe_debug<T: fmt::Debug>(value: Option<&T>) -> &dyn fmt::Debug {
  match value {
    Some(value) => value,
    None => &None::<Infallible>,
  }
}

/// A `document` or `nodes` element, a container of [`Node`]
#[derive(Default, Clone, PartialEq, Eq, Hash)]
pub struct Document<'text> {
  /// The nodes in this document, in order
  pub nodes: Vec<Node<'text>>,
}

impl<'text> Document<'text> {
  /// Create a document with no children
  pub fn new() -> Self {
    Self::default()
  }
  /// Convert into an owned value
  pub fn into_owned(self) -> Document<'static> {
    Document {
      nodes: self.nodes.into_iter().map(Node::into_owned).collect(),
    }
  }
  /// Iterator over every node with a particular name
  pub fn get<'a, 'b>(&'a self, name: &'b str) -> impl Iterator<Item = &'a Node<'text>> + 'b
  where
    'text: 'a,
    'a: 'b,
  {
    self.nodes.iter().filter(move |node| node.name() == name)
  }
  /// Mutable iterator over every node with a particular name
  pub fn get_mut<'a, 'b>(&'a mut self, name: &'b str) -> impl Iterator<Item = &'a mut Node<'text>> + 'b
  where
    'text: 'a,
    'a: 'b,
  {
    self.nodes.iter_mut().filter(move |node| node.name() == name)
  }
  pub fn parse(text: &'text str) -> Result<Self, Error> {
    Ok(Parser::new(text).collect::<Result<Vec<_>, _>>()?.into_iter().collect())
  }
}

impl fmt::Debug for Document<'_> {
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    f.write_str("Document ")?;
    f.debug_list().entries(&self.nodes).finish()
  }
}
impl fmt::Display for Document<'_> {
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    let mut iter = self.nodes.iter();
    if let Some(first) = iter.next() {
      write!(f, "{first}")?;
      for node in iter {
        write!(f, "\n{node}")?;
      }
    }
    Ok(())
  }
}
/// Currently panic's if the iterator is invalid, oh well
impl<'text> FromIterator<Event<'text>> for Document<'text> {
  fn from_iter<T: IntoIterator<Item = Event<'text>>>(iter: T) -> Self {
    let mut stack = vec![Document::new()];
    for event in iter {
      match event {
        Event::Node { r#type, name } => {
          let mut node = Node::new(name);
          node.set_type_hint(r#type);
          stack.last_mut().unwrap().nodes.push(node);
        }
        Event::Entry { r#type, key, value } => {
          let mut entry = Entry::new_value(value);
          entry.set_key(key);
          entry.set_type_hint(r#type);
          stack.last_mut().unwrap().nodes.last_mut().unwrap().entries.push(entry);
        }
        Event::Begin => stack.push(Document::new()),
        Event::End => {
          let children = stack.pop().unwrap();
          stack.last_mut().unwrap().nodes.last_mut().unwrap().children = Some(children);
        }
      }
    }
    let document = stack.pop().unwrap();
    assert!(stack.is_empty(), "invalid iterator stream");
    document
  }
}

/// A `node` element
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct Node<'text> {
  r#type: Option<Cow<'text, str>>,
  name: Cow<'text, str>,
  /// The node's entries in order
  pub entries: Vec<Entry<'text>>,
  /// The node's child document
  pub children: Option<Document<'text>>,
}

impl<'text> Node<'text> {
  /// Create a new node with a name
  pub fn new(name: impl Into<Cow<'text, str>>) -> Self {
    Self {
      r#type: None,
      name: name.into(),
      entries: Vec::new(),
      children: None,
    }
  }
  /// Convert into an owned value
  pub fn into_owned(self) -> Node<'static> {
    Node {
      r#type: self.r#type.map(cow_static),
      name: cow_static(self.name),
      entries: self.entries.into_iter().map(Entry::into_owned).collect(),
      children: self.children.map(Document::into_owned),
    }
  }
  /// Get the node's name
  pub fn name(&self) -> &str {
    &self.name
  }
  /// Set the node's name
  pub fn set_name(&mut self, name: impl Into<Cow<'text, str>>) {
    self.name = name.into();
  }
  /// Get the node's type hint
  pub fn type_hint(&self) -> Option<&str> {
    self.r#type.as_deref()
  }
  /// Set the node's type hint
  pub fn set_type_hint(&mut self, r#type: Option<impl Into<Cow<'text, str>>>) {
    self.r#type = r#type.map(Into::into);
  }
  /// Get a specific entry
  pub fn entry<'key>(&self, key: impl Into<EntryKey<'key>>) -> Option<&Entry<'text>> {
    key.into().seek(self.entries.iter(), |ent| ent.key.as_deref())
  }
  /// Mutably get a specific entry
  pub fn entry_mut<'key>(&mut self, key: impl Into<EntryKey<'key>>) -> Option<&mut Entry<'text>> {
    key.into().seek(self.entries.iter_mut(), |ent| ent.key.as_deref())
  }
  /// Normalize node to kdl spec:
  /// - Empty children block gets removed
  /// - Normalize child nodes
  /// - Duplicate properties are removed
  pub fn normalize(&mut self) {
    if let Some(children) = &mut self.children {
      if children.nodes.is_empty() {
        self.children = None;
      } else {
        for node in &mut children.nodes {
          node.normalize();
        }
      }
    }
    // TODO: this is simply an unlikely string-pointer
    // consider a real way to get a fake/random string pointer
    let marker = &"\0temp"[5..];
    // two-pass approach to remove duplicate props
    let mut seen = HashSet::new();
    for entry in self.entries.iter_mut().rev() {
      if let Some(key) = &mut entry.key {
        if seen.contains(key) {
          *key = Cow::Borrowed(marker);
        } else {
          seen.insert(&*key);
        }
      }
    }
    self.entries.retain(|ent| {
      !ent
        .key
        .as_ref()
        .is_some_and(|key| std::ptr::eq(key.as_ptr(), marker.as_ptr()) && key.is_empty())
    });
  }
}

impl fmt::Debug for Node<'_> {
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    f.debug_struct("Node")
      .field("type", maybe_debug(self.type_hint().as_ref()))
      .field("name", &self.name)
      .field("props", &self.entries)
      .field("children", maybe_debug(self.children.as_ref()))
      .finish()
  }
}
impl fmt::Display for Node<'_> {
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    if let Some(r#type) = &self.r#type {
      write!(f, "({})", IdentDisplay(r#type))?;
    }
    fmt::Display::fmt(&IdentDisplay(&self.name), f)?;
    for entry in &self.entries {
      write!(f, " {entry}")?;
    }
    if let Some(children) = &self.children {
      // make rust fmt do indents for me
      struct Children<'this>(&'this Document<'this>, Cell<bool>);
      impl fmt::Debug for Children<'_> {
        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
          fmt::Display::fmt(self.0, f)?;
          // really stupid hack to have debug_set not print the trailing comma
          // (while not ignoring real errors!)
          self.1.set(true);
          Err(fmt::Error)
        }
      }
      struct Block<'this>(&'this Document<'this>);
      impl fmt::Debug for Block<'_> {
        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
          let children = Children(self.0, Cell::new(false));
          let result = f.debug_set().entry(&children).finish();
          if children.1.get() {
            Ok(())
          } else {
            result
          }
        }
      }
      f.write_str(" ")?;
      write!(f, "{:#?}\n}}", Block(children))?;
    }
    Ok(())
  }
}
impl<'key, 'text, T: Into<EntryKey<'key>>> Index<T> for Node<'text> {
  type Output = Entry<'text>;
  fn index(&self, index: T) -> &Self::Output {
    let key = index.into();
    self
      .entry(key)
      .unwrap_or_else(|| panic!("Key {key:?} does not exist in node"))
  }
}
impl<'key, 'text, T: Into<EntryKey<'key>>> IndexMut<T> for Node<'text> {
  fn index_mut(&mut self, index: T) -> &mut Self::Output {
    let key = index.into();
    self
      .entry_mut(key)
      .unwrap_or_else(|| panic!("Key {key:?} does not exist in node"))
  }
}

/// A `prop` or `value` element
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct Entry<'text> {
  key: Option<Cow<'text, str>>,
  r#type: Option<Cow<'text, str>>,
  /// The value of this property
  pub value: Value<'text>,
}

impl<'text> Entry<'text> {
  /// Create an entry that represents a plain value
  pub fn new_value(value: Value<'text>) -> Self {
    Self {
      key: None,
      r#type: None,
      value,
    }
  }
  /// Create an entry that represents a named property
  pub fn new_prop(name: impl Into<Cow<'text, str>>, value: Value<'text>) -> Self {
    Self {
      key: Some(name.into()),
      r#type: None,
      value,
    }
  }
  /// Convert into an owned value
  pub fn into_owned(self) -> Entry<'static> {
    Entry {
      key: self.key.map(cow_static),
      r#type: self.r#type.map(cow_static),
      value: self.value.into_owned(),
    }
  }
  /// Get the property's key, if it has one
  pub fn key(&self) -> Option<&str> {
    self.key.as_deref()
  }
  /// Get the property's key, if it has one
  pub fn set_key(&mut self, key: Option<impl Into<Cow<'text, str>>>) {
    self.key = key.map(Into::into);
  }
  /// Get the property's type hint
  pub fn type_hint(&self) -> Option<&str> {
    self.r#type.as_deref()
  }
  /// Set the node's type hint
  pub fn set_type_hint(&mut self, r#type: Option<impl Into<Cow<'text, str>>>) {
    self.r#type = r#type.map(Into::into);
  }
}

impl fmt::Debug for Entry<'_> {
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    f.debug_struct("Property")
      .field("key", &self.key)
      .field("type", maybe_debug(self.type_hint().as_ref()))
      .field("value", &self.value)
      .finish()
  }
}
impl fmt::Display for Entry<'_> {
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    if let Some(key) = &self.key {
      write!(f, "{}=", IdentDisplay(key))?;
    }
    if let Some(r#type) = &self.r#type {
      write!(f, "({})", IdentDisplay(r#type))?;
    }
    fmt::Display::fmt(&self.value, f)
  }
}
impl<'text, K: Into<Cow<'text, str>>, V: Into<Value<'text>>> From<(K, V)> for Entry<'text> {
  fn from((name, value): (K, V)) -> Self {
    Self::new_prop(name.into(), value.into())
  }
}
impl<'text, V: Into<Value<'text>>> From<V> for Entry<'text> {
  fn from(value: V) -> Self {
    Self::new_value(value.into())
  }
}

/// A numeric or textual key to index an [`Entry`] in a [`Node`]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum EntryKey<'text> {
  Pos(usize),
  Name(&'text str),
}
impl EntryKey<'_> {
  fn seek<T>(self, mut iter: impl DoubleEndedIterator<Item = T>, name: impl Fn(&T) -> Option<&str>) -> Option<T> {
    match self {
      EntryKey::Pos(key) => iter.filter(|ent| name(ent).is_none()).nth(key),
      // right-most property overrides value
      EntryKey::Name(key) => iter.rfind(|ent| name(ent) == Some(key)),
    }
  }
}
impl From<usize> for EntryKey<'_> {
  fn from(value: usize) -> Self {
    Self::Pos(value)
  }
}
impl<'text> From<&'text str> for EntryKey<'text> {
  fn from(value: &'text str) -> Self {
    Self::Name(value)
  }
}

fn norm_float(v: f64) -> u64 {
  match v.classify() {
    FpCategory::Nan => u64::MAX,
    FpCategory::Zero => 0,
    FpCategory::Infinite | FpCategory::Subnormal | FpCategory::Normal => v.to_bits(),
  }
}

/// The value of an [`Entry`]
#[derive(Clone)]
pub enum Value<'text> {
  /// A textual value
  String(Cow<'text, str>),
  /// An integer value
  Integer(i128),
  /// A floating-point number value
  Float(f64),
  /// A boolean value
  Bool(bool),
  /// The `#null` value
  Null,
}

impl Value<'_> {
  /// Convert into an owned value
  pub fn into_owned(self) -> Value<'static> {
    match self {
      Self::String(value) => Value::String(cow_static(value)),
      Self::Integer(value) => Value::Integer(value),
      Self::Float(value) => Value::Float(value),
      Self::Bool(value) => Value::Bool(value),
      Self::Null => Value::Null,
    }
  }
  // TODO: maybe some helper methods?
}

impl fmt::Debug for Value<'_> {
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    match self {
      Self::String(value) => fmt::Debug::fmt(&**value, f),
      Self::Integer(value) => fmt::Debug::fmt(value, f),
      Self::Float(value) => fmt::Debug::fmt(value, f),
      Self::Bool(true) => f.write_str("#true"),
      Self::Bool(false) => f.write_str("#false"),
      Self::Null => f.write_str("#null"),
    }
  }
}
impl fmt::Display for Value<'_> {
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    match self {
      Value::String(value) => fmt::Display::fmt(&IdentDisplay(value), f),
      Value::Integer(value) => fmt::Display::fmt(value, f),
      Value::Float(value) => match value.classify() {
        FpCategory::Nan => f.write_str("#nan"),
        FpCategory::Infinite => f.write_str(if value.is_sign_negative() { "#-inf" } else { "#inf" }),
        FpCategory::Zero | FpCategory::Subnormal | FpCategory::Normal => {
          // use debug fmt to ensure that floats get re-parsed as floats
          fmt::Debug::fmt(&value, f)
        }
      },
      Value::Bool(true) => f.write_str("#true"),
      Value::Bool(false) => f.write_str("#false"),
      Value::Null => f.write_str("#null"),
    }
  }
}
impl PartialEq for Value<'_> {
  fn eq(&self, other: &Self) -> bool {
    match (self, other) {
      (Self::String(l), Self::String(r)) => l == r,
      (Self::Integer(l), Self::Integer(r)) => l == r,
      (Self::Float(l), Self::Float(r)) => norm_float(*l) == norm_float(*r),
      (Self::Bool(l), Self::Bool(r)) => l == r,
      (Self::Null, Self::Null) => true,
      _ => false,
    }
  }
}
impl Eq for Value<'_> {}
impl std::hash::Hash for Value<'_> {
  fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
    match self {
      Value::String(value) => {
        state.write_u8(0);
        value.hash(state);
      }
      Value::Integer(value) => {
        state.write_u8(1);
        value.hash(state);
      }
      Value::Float(value) => {
        state.write_u8(2);
        norm_float(*value).hash(state);
      }
      Value::Bool(value) => {
        state.write_u8(3);
        value.hash(state);
      }
      Value::Null => {
        state.write_u8(4);
      }
    }
  }
}
impl<'text> From<&'text str> for Value<'text> {
  fn from(value: &'text str) -> Self {
    Self::String(Cow::Borrowed(value))
  }
}
impl<'text> From<String> for Value<'text> {
  fn from(value: String) -> Self {
    Self::String(Cow::Owned(value))
  }
}
impl<'text> From<f64> for Value<'text> {
  fn from(value: f64) -> Self {
    Self::Float(value)
  }
}
impl<'text> From<i128> for Value<'text> {
  fn from(value: i128) -> Self {
    Self::Integer(value)
  }
}
impl<'text> From<bool> for Value<'text> {
  fn from(value: bool) -> Self {
    Self::Bool(value)
  }
}
impl<'text> From<()> for Value<'text> {
  fn from((): ()) -> Self {
    Self::Null
  }
}
impl<'text, T: Into<Value<'text>>> From<Option<T>> for Value<'text> {
  fn from(value: Option<T>) -> Self {
    match value {
      Some(v) => v.into(),
      _ => Self::Null,
    }
  }
}