babbel_yaml 0.1.0

Fast, modular YAML 1.2 parser and emitter with anchors, aliases, and tags
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
//! YAML Node Inspection & Introspection
//!
//! Utilities for examining, summarizing, and introspecting YAML node structure, types, and content.
//! Includes helpers for type detection, value extraction, and node traversal for debugging and analysis.
//!
//! Copyright (c) 2026 YAML Library Developers

use alloc::format;
use alloc::string::{String, ToString};
use alloc::vec::Vec;

use crate::nodes::node::{Node, Numeric};
use crate::utils::streaming::NodeIteratorExt;

/// Node type information
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NodeType {
    Null,
    Boolean,
    Integer,
    Float,
    String,
    Array,
    Mapping,
    Set,
    Document,
    Documents,
    Tagged,
    Anchored,
    Alias,
    Comment,
}

impl NodeType {
    /// Get the type name as a string
    pub fn as_str(&self) -> &'static str {
        match self {
            NodeType::Null => "null",
            NodeType::Boolean => "boolean",
            NodeType::Integer => "integer",
            NodeType::Float => "float",
            NodeType::String => "string",
            NodeType::Array => "array",
            NodeType::Mapping => "mapping",
            NodeType::Set => "set",
            NodeType::Document => "document",
            NodeType::Documents => "documents",
            NodeType::Tagged => "tagged",
            NodeType::Anchored => "anchored",
            NodeType::Alias => "alias",
            NodeType::Comment => "comment",
        }
    }

    /// Check if this is a scalar type
    pub fn is_scalar(&self) -> bool {
        matches!(
            self,
            NodeType::Null
                | NodeType::Boolean
                | NodeType::Integer
                | NodeType::Float
                | NodeType::String
        )
    }

    /// Check if this is a collection type
    pub fn is_collection(&self) -> bool {
        matches!(self, NodeType::Array | NodeType::Mapping | NodeType::Set)
    }
}

/// Get the type of a node
pub fn node_type(node: &Node) -> NodeType {
    match node {
        Node::None => NodeType::Null,
        Node::Boolean(_) => NodeType::Boolean,
        Node::Number(
            Numeric::Integer(_)
            | Numeric::UInteger(_)
            | Numeric::Int32(_)
            | Numeric::UInt32(_)
            | Numeric::Int16(_)
            | Numeric::UInt16(_)
            | Numeric::Int8(_)
            | Numeric::Byte(_)
            | Numeric::UInt8(_),
        ) => NodeType::Integer,
        Node::Number(Numeric::Float(_)) => NodeType::Float,
        Node::Str(_, _, _) => NodeType::String,
        Node::Array(_) => NodeType::Array,
        Node::Mapping(_) => NodeType::Mapping,
        Node::Set(_) => NodeType::Set,
        Node::Document(_) => NodeType::Document,
        Node::Documents(_) => NodeType::Documents,
        Node::Tagged(_, _) => NodeType::Tagged,
        Node::Anchored(_, _) => NodeType::Anchored,
        Node::Alias(_) => NodeType::Alias,
        Node::Comment(_) => NodeType::Comment,
    }
}

/// Detailed node information
#[derive(Debug, Clone)]
pub struct NodeInfo {
    pub node_type: NodeType,
    pub size: usize,
    pub depth: usize,
    pub has_tag: bool,
    pub has_anchor: bool,
    pub is_alias: bool,
    pub summary: String,
}

impl NodeInfo {
    /// Create node information for a given node
    pub fn new(node: &Node) -> Self {
        Self {
            node_type: node_type(node),
            size: node_size(node),
            depth: node_depth(node),
            has_tag: has_tag(node),
            has_anchor: has_anchor(node),
            is_alias: matches!(node, Node::Alias(_)),
            summary: node_summary(node),
        }
    }

    /// Format as a readable string
    pub fn format(&self) -> String {
        format!(
            "Type: {}, Size: {}, Depth: {}, Tag: {}, Anchor: {}, Alias: {}\n{}",
            self.node_type.as_str(),
            self.size,
            self.depth,
            self.has_tag,
            self.has_anchor,
            self.is_alias,
            self.summary
        )
    }
}

/// Get the size (number of child nodes) of a node
pub fn node_size(node: &Node) -> usize {
    match node {
        Node::Array(items) => items.len(),
        Node::Mapping(pairs) => pairs.len(),
        Node::Set(items) => items.len(),
        Node::Document(items) => items.len(),
        Node::Documents(docs) => docs.len(),
        _ => 0,
    }
}

/// Get the maximum depth of a node tree
pub fn node_depth(node: &Node) -> usize {
    match node {
        Node::Array(items) => 1 + items.iter().map(node_depth).max().unwrap_or(0),
        Node::Mapping(pairs) => {
            1 + pairs
                .iter()
                .map(|(k, v)| node_depth(k).max(node_depth(v)))
                .max()
                .unwrap_or(0)
        }
        Node::Set(items) => 1 + items.iter().map(node_depth).max().unwrap_or(0),
        Node::Document(items) => 1 + items.iter().map(node_depth).max().unwrap_or(0),
        Node::Documents(docs) => 1 + docs.iter().map(node_depth).max().unwrap_or(0),
        Node::Tagged(inner, _) => 1 + node_depth(inner),
        Node::Anchored(inner, _) => 1 + node_depth(inner),
        _ => 1,
    }
}

/// Check if a node has a tag
pub fn has_tag(node: &Node) -> bool {
    matches!(node, Node::Tagged(_, _))
}

/// Check if a node has an anchor
pub fn has_anchor(node: &Node) -> bool {
    matches!(node, Node::Anchored(_, _))
}

/// Get a summary string for a node
pub fn node_summary(node: &Node) -> String {
    match node {
        Node::None => "null".to_string(),
        Node::Boolean(b) => format!("Boolean: {}", b),
        Node::Number(n) => format!("Number: {:?}", n),
        Node::Str(s, _, _) => {
            if s.len() > 50 {
                format!("String: \"{}...\" ({} chars)", &s[..47], s.len())
            } else {
                format!("String: \"{}\"", s)
            }
        }
        Node::Array(items) => format!("Array with {} items", items.len()),
        Node::Mapping(pairs) => format!("Mapping with {} pairs", pairs.len()),
        Node::Set(items) => format!("Set with {} items", items.len()),
        Node::Document(items) => format!("Document with {} nodes", items.len()),
        Node::Documents(docs) => format!("Documents: {} documents", docs.len()),
        Node::Tagged(inner, tag) => format!("Tagged {:?}: {}", tag, node_summary(inner)),
        Node::Anchored(inner, anchor) => format!("Anchored {:?}: {}", anchor, node_summary(inner)),
        Node::Alias(name) => format!("Alias: *{}", name),
        Node::Comment(text) => format!("Comment: # {}", text),
    }
}

/// Pretty-print node structure as a tree
pub fn print_tree(node: &Node) -> String {
    let mut output = String::new();
    print_tree_impl(node, 0, "", &mut output);
    output
}

fn print_tree_impl(node: &Node, depth: usize, prefix: &str, output: &mut String) {
    let indent = "  ".repeat(depth);
    let type_str = node_type(node).as_str();

    output.push_str(&format!("{}{}{}\n", indent, prefix, type_str));

    match node {
        Node::Array(items) => {
            for (i, item) in items.iter().enumerate() {
                print_tree_impl(item, depth + 1, &format!("[{}]: ", i), output);
            }
        }
        Node::Mapping(pairs) => {
            for (k, v) in pairs {
                let key_summary = match k {
                    Node::Str(s, _, _) => s.clone(),
                    _ => format!("{:?}", k),
                };
                output.push_str(&format!("{}  {}: ", indent, key_summary));
                print_tree_impl(v, depth + 1, "", output);
            }
        }
        Node::Set(items) => {
            for item in items {
                print_tree_impl(item, depth + 1, "- ", output);
            }
        }
        Node::Document(items) => {
            for item in items {
                print_tree_impl(item, depth + 1, "", output);
            }
        }
        Node::Documents(docs) => {
            for (i, doc) in docs.iter().enumerate() {
                print_tree_impl(doc, depth + 1, &format!("doc[{}]: ", i), output);
            }
        }
        Node::Tagged(inner, tag) => {
            output.push_str(&format!("{}  tag: {:?}\n", indent, tag));
            print_tree_impl(inner, depth + 1, "", output);
        }
        Node::Anchored(inner, anchor) => {
            output.push_str(&format!("{}  anchor: {:?}\n", indent, anchor));
            print_tree_impl(inner, depth + 1, "", output);
        }
        Node::Str(s, _, _) => {
            if s.len() > 40 {
                output.push_str(&format!("{}  \"{}...\"\n", indent, &s[..37]));
            } else {
                output.push_str(&format!("{}  \"{}\"\n", indent, s));
            }
        }
        Node::Number(n) => {
            output.push_str(&format!("{}  {:?}\n", indent, n));
        }
        Node::Boolean(b) => {
            output.push_str(&format!("{}  {}\n", indent, b));
        }
        Node::Alias(name) => {
            output.push_str(&format!("{}  *{}\n", indent, name));
        }
        Node::Comment(text) => {
            output.push_str(&format!("{}  # {}\n", indent, text));
        }
        Node::None => {
            output.push_str(&format!("{}  null\n", indent));
        }
    }
}

/// Find all nodes of a specific type using depth-first traversal
pub fn find_by_type(node: &Node, target_type: NodeType) -> Vec<&Node> {
    node.iter_depth_first()
        .filter(|n| node_type(n) == target_type)
        .collect()
}

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

    #[test]
    fn test_node_type() {
        assert_eq!(node_type(&Node::None), NodeType::Null);
        assert_eq!(node_type(&Node::from(true)), NodeType::Boolean);
        assert_eq!(node_type(&Node::from(42)), NodeType::Integer);
        assert_eq!(node_type(&Node::from("test")), NodeType::String);
        assert_eq!(node_type(&Node::Array(vec![])), NodeType::Array);
    }

    #[test]
    fn test_node_size() {
        assert_eq!(
            node_size(&Node::Array(vec![Node::from(1), Node::from(2)])),
            2
        );
        assert_eq!(node_size(&Node::from("test")), 0);
    }

    #[test]
    fn test_node_depth() {
        let shallow = Node::from("test");
        assert_eq!(node_depth(&shallow), 1);

        let nested = Node::Array(vec![Node::Array(vec![Node::from("deep")])]);
        assert_eq!(node_depth(&nested), 3);
    }

    #[test]
    fn test_node_info() {
        let node = Node::Array(vec![Node::from(1), Node::from(2), Node::from(3)]);
        let info = NodeInfo::new(&node);

        assert_eq!(info.node_type, NodeType::Array);
        assert_eq!(info.size, 3);
        assert_eq!(info.depth, 2);
        assert!(!info.has_tag);
        assert!(!info.has_anchor);
    }

    #[test]
    fn test_node_summary() {
        assert_eq!(node_summary(&Node::None), "null");
        assert!(node_summary(&Node::from(true)).contains("Boolean"));
        assert!(node_summary(&Node::from("test")).contains("String"));
    }

    #[test]
    fn test_find_by_type() {
        let tree = Node::Array(vec![
            Node::from("hello"),
            Node::from(42),
            Node::from("world"),
        ]);

        let strings = find_by_type(&tree, NodeType::String);
        assert_eq!(strings.len(), 2);
    }

    #[test]
    fn test_print_tree() {
        let node = Node::Mapping(vec![
            (Node::from("name"), Node::from("Alice")),
            (Node::from("age"), Node::from(30)),
        ]);

        let tree = print_tree(&node);
        assert!(tree.contains("mapping"));
        assert!(tree.contains("name"));
        assert!(tree.contains("age"));
    }

    #[test]
    fn test_node_type_categories() {
        assert!(NodeType::String.is_scalar());
        assert!(NodeType::Array.is_collection());
        assert!(!NodeType::Array.is_scalar());
    }

    #[test]
    fn test_node_info_tag_anchor_alias() {
        let tagged = Node::Tagged(Box::new(Node::from("tagged")), "!tag".to_string());
        let anchored = Node::Anchored(Box::new(Node::from("anchored")), "anchor1".to_string());
        let alias = Node::Alias("alias1".to_string());
        let tagged_info = NodeInfo::new(&tagged);
        let anchored_info = NodeInfo::new(&anchored);
        let alias_info = NodeInfo::new(&alias);
        assert!(tagged_info.has_tag);
        assert!(!tagged_info.has_anchor);
        assert!(!tagged_info.is_alias);
        assert!(!anchored_info.has_tag);
        assert!(anchored_info.has_anchor);
        assert!(!anchored_info.is_alias);
        assert!(!alias_info.has_tag);
        assert!(!alias_info.has_anchor);
        assert!(alias_info.is_alias);
    }

    #[test]
    fn test_node_summary_long_string() {
        let long_str = "a".repeat(60);
        let node = Node::from(long_str.clone());
        let summary = node_summary(&node);
        assert!(summary.contains("..."));
        assert!(summary.contains(&long_str[..47]));
    }

    #[test]
    fn test_print_tree_documents() {
        let docs = Node::Documents(vec![Node::from("doc1"), Node::from("doc2")]);
        let tree = print_tree(&docs);
        assert!(tree.contains("documents"));
        assert!(tree.contains("doc[0]"));
        assert!(tree.contains("doc[1]"));
    }

    #[test]
    fn test_find_by_type_empty() {
        let node = Node::Array(vec![]);
        let found = find_by_type(&node, NodeType::Mapping);
        assert_eq!(found.len(), 0);
    }

    #[test]
    fn test_node_type_tagged_and_anchored() {
        let tagged = Node::Tagged(Box::new(Node::from("tagged")), "!tag".to_string());
        let anchored = Node::Anchored(Box::new(Node::from("anchored")), "anchor1".to_string());
        assert_eq!(node_type(&tagged), NodeType::Tagged);
        assert_eq!(node_type(&anchored), NodeType::Anchored);
    }
}