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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
//! Debugging utilities for YAML library development.
//!
//! This module provides debug levels, context tracking, and helper functions
//! for internal development and troubleshooting of the YAML library.
//!
//! (c) 2026 YAML Library Developers

use alloc::format;
use alloc::string::String;
use alloc::vec::Vec;

use crate::nodes::node::Node;

/// Debug level for controlling output verbosity
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum DebugLevel {
    None = 0,
    Error = 1,
    Warn = 2,
    Info = 3,
    Debug = 4,
    Trace = 5,
}

/// Debug context for tracking execution flow
#[derive(Debug, Clone)]
pub struct DebugContext {
    level: DebugLevel,
    logs: Vec<String>,
    breakpoints: Vec<String>,
}

impl DebugContext {
    /// Create a new debug context
    pub fn new(level: DebugLevel) -> Self {
        Self {
            level,
            logs: Vec::new(),
            breakpoints: Vec::new(),
        }
    }

    /// Create with info level
    pub fn with_info() -> Self {
        Self::new(DebugLevel::Info)
    }

    /// Create with debug level
    pub fn with_debug() -> Self {
        Self::new(DebugLevel::Debug)
    }

    /// Create with trace level
    pub fn with_trace() -> Self {
        Self::new(DebugLevel::Trace)
    }

    /// Set debug level
    pub fn set_level(&mut self, level: DebugLevel) {
        self.level = level;
    }

    /// Get current debug level
    pub fn level(&self) -> DebugLevel {
        self.level
    }

    /// Log a message at the specified level
    pub fn log(&mut self, level: DebugLevel, message: String) {
        if level <= self.level {
            self.logs.push(format!("[{:?}] {}", level, message));
        }
    }

    /// Log error message
    pub fn error(&mut self, message: String) {
        self.log(DebugLevel::Error, message);
    }

    /// Log warning message
    pub fn warn(&mut self, message: String) {
        self.log(DebugLevel::Warn, message);
    }

    /// Log info message
    pub fn info(&mut self, message: String) {
        self.log(DebugLevel::Info, message);
    }

    /// Log debug message
    pub fn debug(&mut self, message: String) {
        self.log(DebugLevel::Debug, message);
    }

    /// Log trace message
    pub fn trace(&mut self, message: String) {
        self.log(DebugLevel::Trace, message);
    }

    /// Add a breakpoint
    pub fn add_breakpoint(&mut self, name: String) {
        self.breakpoints.push(name);
    }

    /// Check if a breakpoint exists
    pub fn has_breakpoint(&self, name: &str) -> bool {
        self.breakpoints.iter().any(|bp| bp == name)
    }

    /// Get all logs
    pub fn logs(&self) -> &[String] {
        &self.logs
    }

    /// Get all breakpoints
    pub fn breakpoints(&self) -> &[String] {
        &self.breakpoints
    }

    /// Clear all logs
    pub fn clear_logs(&mut self) {
        self.logs.clear();
    }

    /// Clear all breakpoints
    pub fn clear_breakpoints(&mut self) {
        self.breakpoints.clear();
    }

    /// Format all logs as a string
    pub fn format_logs(&self) -> String {
        self.logs.join("\n")
    }
}

impl Default for DebugContext {
    fn default() -> Self {
        Self::new(DebugLevel::Info)
    }
}

/// Node debugger for inspecting node operations
pub struct NodeDebugger {
    context: DebugContext,
    trace_enabled: bool,
}

impl NodeDebugger {
    /// Create a new node debugger
    pub fn new() -> Self {
        Self {
            context: DebugContext::with_debug(),
            trace_enabled: false,
        }
    }

    /// Create with tracing enabled
    pub fn with_trace() -> Self {
        Self {
            context: DebugContext::with_trace(),
            trace_enabled: true,
        }
    }

    /// Enable tracing
    pub fn enable_trace(&mut self) {
        self.trace_enabled = true;
        self.context.set_level(DebugLevel::Trace);
    }

    /// Disable tracing
    pub fn disable_trace(&mut self) {
        self.trace_enabled = false;
    }

    /// Get the debug context
    pub fn context(&self) -> &DebugContext {
        &self.context
    }

    /// Get mutable debug context
    pub fn context_mut(&mut self) -> &mut DebugContext {
        &mut self.context
    }

    /// Debug a node access operation
    pub fn debug_access(&mut self, path: &str, node: &Node) {
        let msg = format!(
            "Access: {} -> {:?}",
            path,
            crate::devtools::inspect::node_type(node)
        );
        self.context.debug(msg);
    }

    /// Debug a node creation operation
    pub fn debug_create(&mut self, node: &Node) {
        let msg = format!("Create: {:?}", crate::devtools::inspect::node_type(node));
        self.context.debug(msg);
    }

    /// Debug a node modification operation
    pub fn debug_modify(&mut self, path: &str, old: &Node, new: &Node) {
        let msg = format!(
            "Modify: {} from {:?} to {:?}",
            path,
            crate::devtools::inspect::node_type(old),
            crate::devtools::inspect::node_type(new)
        );
        self.context.debug(msg);
    }

    /// Trace node traversal
    pub fn trace_visit(&mut self, depth: usize, node: &Node) {
        if self.trace_enabled {
            let indent = "  ".repeat(depth);
            let msg = format!(
                "{}Visit: {:?}",
                indent,
                crate::devtools::inspect::node_type(node)
            );
            self.context.trace(msg);
        }
    }

    /// Get formatted logs
    pub fn logs(&self) -> String {
        self.context.format_logs()
    }

    /// Clear all logs
    pub fn clear(&mut self) {
        self.context.clear_logs();
        self.context.clear_breakpoints();
    }
}

impl Default for NodeDebugger {
    fn default() -> Self {
        Self::new()
    }
}

/// Assertion helper for debugging
pub struct DebugAssert;

impl DebugAssert {
    /// Assert node type
    pub fn assert_type(
        node: &Node,
        expected: crate::devtools::inspect::NodeType,
    ) -> Result<(), String> {
        let actual = crate::devtools::inspect::node_type(node);
        if actual == expected {
            Ok(())
        } else {
            Err(format!(
                "Type assertion failed: expected {:?}, got {:?}",
                expected, actual
            ))
        }
    }

    /// Assert node has specific size
    pub fn assert_size(node: &Node, expected: usize) -> Result<(), String> {
        let actual = crate::devtools::inspect::node_size(node);
        if actual == expected {
            Ok(())
        } else {
            Err(format!(
                "Size assertion failed: expected {}, got {}",
                expected, actual
            ))
        }
    }

    /// Assert node has maximum depth
    pub fn assert_max_depth(node: &Node, max_depth: usize) -> Result<(), String> {
        let actual = crate::devtools::inspect::node_depth(node);
        if actual <= max_depth {
            Ok(())
        } else {
            Err(format!(
                "Depth assertion failed: expected <= {}, got {}",
                max_depth, actual
            ))
        }
    }

    /// Assert node is scalar
    pub fn assert_scalar(node: &Node) -> Result<(), String> {
        let node_type = crate::devtools::inspect::node_type(node);
        if node_type.is_scalar() {
            Ok(())
        } else {
            Err(format!("Scalar assertion failed: node is {:?}", node_type))
        }
    }

    /// Assert node is collection
    pub fn assert_collection(node: &Node) -> Result<(), String> {
        let node_type = crate::devtools::inspect::node_type(node);
        if node_type.is_collection() {
            Ok(())
        } else {
            Err(format!(
                "Collection assertion failed: node is {:?}",
                node_type
            ))
        }
    }
}

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

    #[test]
    fn test_debug_level_ordering() {
        assert!(DebugLevel::Error < DebugLevel::Warn);
        assert!(DebugLevel::Warn < DebugLevel::Info);
        assert!(DebugLevel::Info < DebugLevel::Debug);
        assert!(DebugLevel::Debug < DebugLevel::Trace);
    }

    #[test]
    fn test_debug_context() {
        let mut ctx = DebugContext::new(DebugLevel::Info);

        ctx.error("Error message".to_string());
        ctx.info("Info message".to_string());
        ctx.debug("Debug message".to_string());

        let logs = ctx.logs();
        assert_eq!(logs.len(), 2); // Error and Info, but not Debug
        assert!(logs[0].contains("Error"));
        assert!(logs[1].contains("Info"));
    }

    #[test]
    fn test_breakpoints() {
        let mut ctx = DebugContext::new(DebugLevel::Debug);

        ctx.add_breakpoint("parse_start".to_string());
        ctx.add_breakpoint("parse_end".to_string());

        assert!(ctx.has_breakpoint("parse_start"));
        assert!(ctx.has_breakpoint("parse_end"));
        assert!(!ctx.has_breakpoint("unknown"));

        ctx.clear_breakpoints();
        assert!(!ctx.has_breakpoint("parse_start"));
    }

    #[test]
    fn test_node_debugger() {
        let mut debugger = NodeDebugger::new();
        let node = Node::from("test");

        debugger.debug_create(&node);
        debugger.debug_access("/path/to/node", &node);

        let logs = debugger.logs();
        assert!(logs.contains("Create"));
        assert!(logs.contains("Access"));
    }

    #[test]
    fn test_debug_assert_type() {
        use crate::devtools::inspect::NodeType;

        let node = Node::from("test");
        assert!(DebugAssert::assert_type(&node, NodeType::String).is_ok());
        assert!(DebugAssert::assert_type(&node, NodeType::Integer).is_err());
    }

    #[test]
    fn test_debug_assert_size() {
        let node = Node::Array(vec![Node::from(1), Node::from(2)]);
        assert!(DebugAssert::assert_size(&node, 2).is_ok());
        assert!(DebugAssert::assert_size(&node, 3).is_err());
    }

    #[test]
    fn test_debug_assert_scalar() {
        assert!(DebugAssert::assert_scalar(&Node::from("test")).is_ok());
        assert!(DebugAssert::assert_scalar(&Node::Array(vec![])).is_err());
    }

    #[test]
    fn test_trace_enabled() {
        let mut debugger = NodeDebugger::with_trace();
        assert!(debugger.trace_enabled);

        debugger.disable_trace();
        assert!(!debugger.trace_enabled);
    }

    #[test]
    fn test_debug_context_log_levels() {
        let mut ctx = DebugContext::new(DebugLevel::Trace);
        ctx.error("Error".to_string());
        ctx.warn("Warn".to_string());
        ctx.info("Info".to_string());
        ctx.debug("Debug".to_string());
        ctx.trace("Trace".to_string());
        let logs = ctx.logs();
        assert_eq!(logs.len(), 5);
        assert!(logs[0].contains("Error"));
        assert!(logs[1].contains("Warn"));
        assert!(logs[2].contains("Info"));
        assert!(logs[3].contains("Debug"));
        assert!(logs[4].contains("Trace"));
    }

    #[test]
    fn test_debug_context_clear_logs() {
        let mut ctx = DebugContext::new(DebugLevel::Debug);
        ctx.info("Info message".to_string());
        ctx.debug("Debug message".to_string());
        assert!(!ctx.logs().is_empty());
        ctx.clear_logs();
        assert!(ctx.logs().is_empty());
    }

    #[test]
    fn test_node_debugger_trace_visit() {
        let mut debugger = NodeDebugger::with_trace();
        let node = Node::from("test");
        debugger.trace_visit(2, &node);
        let logs = debugger.logs();
        assert!(logs.contains("Visit"));
        assert!(logs.contains("  ")); // Indentation for depth
    }

    #[test]
    fn test_debug_assert_max_depth() {
        let node = Node::Array(vec![Node::from(1), Node::Array(vec![Node::from(2)])]);
        let depth = crate::devtools::inspect::node_depth(&node);
        println!("Actual depth: {}", depth);
        assert!(DebugAssert::assert_max_depth(&node, depth).is_ok());
        assert!(DebugAssert::assert_max_depth(&node, depth - 1).is_err());
    }

    #[test]
    fn test_debug_assert_collection() {
        let node = Node::Array(vec![Node::from(1)]);
        assert!(DebugAssert::assert_collection(&node).is_ok());
        assert!(DebugAssert::assert_collection(&Node::from("test")).is_err());
    }
}