nom-tracer 1.0.1

Extension of nom to trace parser execution
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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
// Copyright (c) Hexbee
// SPDX-License-Identifier: Apache-2.0

#[cfg(feature = "trace")]
use crate::tags::TraceTags;
#[cfg(feature = "trace-silencing")]
use crate::traces::Trace;
#[cfg(feature = "trace-context")]
use nom::error::ContextError;
use {
    nom::{IResult, Parser},
    std::fmt::Debug,
};

#[cfg(feature = "trace-color")]
#[allow(dead_code)]
pub(crate) mod ansi;
#[cfg(feature = "trace")]
pub mod events;
#[cfg(feature = "trace")]
pub mod tags;
#[cfg(feature = "trace")]
pub mod traces;

pub mod macros;

pub const DEFAULT_TAG: &str = "default";

thread_local! {
    /// Thread-local storage for the global [TraceTags].
    ///
    /// [TRACE_TAGS] provides a thread-safe way to access and modify the global trace list.
    /// It's implemented as thread-local storage, ensuring that each thread has its own
    /// independent trace list. This allows for concurrent tracing in multithreaded applications
    /// without the need for explicit synchronization.
    ///
    /// The [RefCell](std::cell::RefCell) allows for interior mutability, so the [TraceTags] can be
    /// modified even when accessed through a shared reference.
    ///
    /// Usage of [TRACE_TAGS] is typically wrapped in the [tr] and [tr_tag_ctx] functions,
    /// which provide a more convenient interface for adding trace events.
    #[cfg(feature = "trace")]
    pub static TRACE_TAGS: std::cell::RefCell<TraceTags> = std::cell::RefCell::new(TraceTags::new());

    /// Thread-local storage for silent tracing (used with trace-silencing feature)
    #[cfg(feature = "trace-silencing")]
    pub static TRACE_SILENT: std::cell::RefCell<Trace> = std::cell::RefCell::new(Trace::default());

    /// Thread-local storage for tree silence levels (used with trace-silencing feature)
    #[cfg(feature = "trace-silencing")]
    pub static TREE_SILENCE_LEVELS: std::cell::RefCell<Vec<usize>> = const { std::cell::RefCell::new(vec![]) };
}

#[cfg(feature = "trace-context")]
pub trait TraceError<I>: Debug + ContextError<I> {}
#[cfg(feature = "trace-context")]
impl<I, E> TraceError<I> for E where E: Debug + ContextError<I> {}

#[cfg(not(feature = "trace-context"))]
pub trait TraceError<I>: Debug {}
#[cfg(not(feature = "trace-context"))]
impl<I, E> TraceError<I> for E where E: Debug {}

/// Main tracing function that wraps a parser with tracing functionality.
///
/// This function is the core of nom-tracer. It wraps a parser and adds tracing capabilities,
/// recording the parser's execution path and results.
///
/// # Arguments
///
/// * `tag` - A static string used to categorize the trace events.
/// * `context` - An optional static string providing additional context for the trace.
/// * `name` - A static string identifying the parser being traced.
/// * `parser` - The parser function to be wrapped with tracing.
pub fn tr<I, O, E, F>(
    #[cfg(feature = "trace")] tag: &'static str,
    #[cfg(not(feature = "trace"))] _tag: &'static str,
    #[cfg(any(feature = "trace", feature = "trace-context"))] context: Option<&'static str>,
    #[cfg(not(any(feature = "trace", feature = "trace-context")))] _context: Option<&'static str>,
    #[cfg(feature = "trace")] name: &'static str,
    #[cfg(not(feature = "trace"))] _name: &'static str,
    mut parser: F,
) -> impl FnMut(I) -> IResult<I, O, E>
where
    I: AsRef<str>,
    F: Parser<I, O, E>,
    I: Clone,
    O: Debug,
    E: TraceError<I>,
{
    #[cfg(feature = "trace")]
    {
        move |input: I| {
            let input1 = input.clone();
            let input2 = input.clone();
            #[cfg(feature = "trace-context")]
            let input3 = input.clone();

            #[cfg(feature = "trace-silencing")]
            let silent = TREE_SILENCE_LEVELS.with(|levels| !levels.borrow().is_empty());

            #[cfg(feature = "trace-silencing")]
            if silent {
                TRACE_SILENT.with(|trace| {
                    (*trace.borrow_mut()).open(context, input1, name, true);
                });
            } else {
                TRACE_TAGS.with(|tags| {
                    (*tags.borrow_mut()).open(tag, context, input1, name, false);
                });
            };
            #[cfg(not(feature = "trace-silencing"))]
            TRACE_TAGS.with(|tags| {
                (*tags.borrow_mut()).open(tag, context, input1, name, false);
            });

            let res = parser.parse(input);

            #[cfg(feature = "trace-silencing")]
            if silent {
                TRACE_SILENT.with(|trace| {
                    (*trace.borrow_mut()).close(context, input2, name, &res, true);
                });
            } else {
                TRACE_TAGS.with(|tags| {
                    (*tags.borrow_mut()).close(tag, context, input2, name, &res, false);
                });
            }

            #[cfg(not(feature = "trace-silencing"))]
            TRACE_TAGS.with(|tags| {
                (*tags.borrow_mut()).close(tag, context, input2, name, &res, false);
            });

            #[cfg(not(feature = "trace-context"))]
            return res;

            #[cfg(feature = "trace-context")]
            if let Some(context) = context {
                add_context_to_err(context, input3, res)
            } else {
                res
            }
        }
    }

    #[cfg(not(feature = "trace"))]
    {
        #[cfg(feature = "trace-context")]
        {
            move |input: I| {
                if let Some(context) = context {
                    add_context_to_err(context, input.clone(), parser.parse(input))
                } else {
                    parser.parse(input)
                }
            }
        }

        #[cfg(not(feature = "trace-context"))]
        move |input: I| parser.parse(input)
    }
}

/// Function to silence tracing for a subtree of parsers.
///
/// This is used to reduce noise in the trace output for well-tested or less interesting
/// parts of the parser.
///
/// # Arguments
///
/// * `tag` - A static string used to categorize the trace events.
/// * `context` - An optional static string providing additional context for the trace.
/// * `name` - A static string identifying the parser being silenced.
/// * `parser` - The parser function to be silenced.
#[cfg(feature = "trace-silencing")]
pub fn silence_tree<I, O, E, F>(
    tag: &'static str,
    context: Option<&'static str>,
    name: &'static str,
    mut parser: F,
) -> impl FnMut(I) -> IResult<I, O, E>
where
    I: AsRef<str>,
    F: Parser<I, O, E>,
    I: Clone,
    O: Debug,
    E: TraceError<I>,
{
    move |input: I| {
        let input1 = input.clone();
        let input2 = input.clone();
        let input3 = input.clone();

        let silent_cut_level = TRACE_SILENT.with(|tags| tags.borrow_mut().level);
        let cut_level = TRACE_TAGS.with(|tags| (*tags.borrow_mut()).level_for_tag(tag));
        let cut_level = silent_cut_level.max(cut_level);

        TREE_SILENCE_LEVELS.with(|levels| {
            (*levels.borrow_mut()).push(cut_level);
        });

        TRACE_SILENT.with(|trace| {
            (*trace.borrow_mut()).set_level(cut_level);
            (*trace.borrow_mut()).open(context, input1, name, true);
        });

        let res = parser.parse(input);

        TRACE_SILENT.with(|trace| {
            (*trace.borrow_mut()).close(context, input2, name, &res, true);
        });

        TREE_SILENCE_LEVELS.with(|levels| {
            (*levels.borrow_mut()).pop();
        });

        #[cfg(feature = "trace-context")]
        return add_context_to_err(name, input3, res);

        #[cfg(not(feature = "trace-context"))]
        res
    }
}

/// Helper function to add context to error results.
///
/// This is used when the trace-context feature is enabled to provide more
/// detailed error information.
#[cfg(feature = "trace-context")]
fn add_context_to_err<I, O, E>(
    name: &'static str,
    input: I,
    res: IResult<I, O, E>,
) -> IResult<I, O, E>
where
    I: AsRef<str>,
    I: Clone,
    O: Debug,
    E: TraceError<I>,
{
    match res {
        Ok(o) => Ok(o),
        Err(nom::Err::Error(e)) => Err(nom::Err::Error(E::add_context(input, name, e))),
        Err(nom::Err::Failure(e)) => Err(nom::Err::Failure(E::add_context(input, name, e))),
        Err(nom::Err::Incomplete(i)) => Err(nom::Err::Incomplete(i)),
    }
}

/// Retrieves the trace for a specific tag.
///
/// # Arguments
///
/// * `tag` - A static string identifying the tag for which to retrieve the trace.
///
/// # Returns
///
/// Returns a string representation of the trace, or a message if no trace is found.
pub fn get_trace_for_tag(
    #[cfg(feature = "trace")] tag: &'static str,
    #[cfg(not(feature = "trace"))] _tag: &'static str,
) -> Option<String> {
    #[cfg(feature = "trace")]
    {
        TRACE_TAGS.with(|trace| trace.borrow().traces.get(tag).map(ToString::to_string))
    }

    #[cfg(not(feature = "trace"))]
    None
}

/// Prints the trace for a specific tag.
///
/// # Arguments
///
/// * `tag` - A static string identifying the tag for which to print the trace.
pub fn print_trace_for_tag(tag: &'static str) {
    print(get_trace_for_tag(tag).unwrap_or(format!("No trace found for tag '{}'", tag)));
}

/// Helper function to for unbuffered output.
///
/// # Arguments
///
/// * `s` - The string to be printed.
pub(crate) fn print<I: AsRef<str>>(s: I) {
    use std::io::Write;
    let stdout = std::io::stdout();
    let mut handle = stdout.lock();
    write!(handle, "{}", s.as_ref()).unwrap();
}

#[cfg(test)]
mod tests {
    use {
        super::*,
        nom::{bytes::complete::tag, error::VerboseError},
    };

    #[cfg(feature = "trace")]
    mod trace_tests {
        use {super::*, nom::sequence::tuple};

        #[test]
        fn test_tr_no_context() {
            let mut parser = tr(
                DEFAULT_TAG,
                None,
                "test_parser",
                tag::<_, _, VerboseError<_>>("hello"),
            );
            let result = parser("hello world");
            assert!(result.is_ok());

            let trace = get_trace_for_tag(DEFAULT_TAG).unwrap();
            assert!(trace.contains("test_parser"));
            assert!(trace.contains("hello world"));
            assert!(trace.contains("-> Ok"));
        }

        #[test]
        fn test_tr_context() {
            let mut parser = tr(
                DEFAULT_TAG,
                Some("context"),
                "test_parser",
                tag::<_, _, VerboseError<_>>("hello"),
            );
            let result = parser("hello world");
            assert!(result.is_ok());

            let trace = get_trace_for_tag(DEFAULT_TAG).unwrap();
            assert!(trace.contains("test_parser"));
            assert!(trace.contains("context"));
            assert!(trace.contains("hello world"));
            assert!(trace.contains("-> Ok"));
        }

        #[test]
        fn test_nested_traces() {
            fn parse_nested(input: &str) -> IResult<&str, (&str, &str)> {
                tr(
                    DEFAULT_TAG,
                    None,
                    "outer",
                    tuple((
                        tr(DEFAULT_TAG, None, "inner_a", tag("a")),
                        tr(DEFAULT_TAG, None, "inner_b", tag("b")),
                    )),
                )(input)
            }

            let traced_parser = parse_nested;
            let result = traced_parser("ab");
            assert!(result.is_ok());

            let trace = get_trace_for_tag(DEFAULT_TAG).unwrap();
            assert!(trace.contains("outer"));
            assert!(trace.contains("inner_a"));
            assert!(trace.contains("inner_b"));
        }

        #[test]
        fn test_get_trace_for_tag() {
            let mut parser = tr(
                DEFAULT_TAG,
                None,
                "test_parser",
                tag::<_, _, VerboseError<_>>("hello"),
            );
            let _ = parser("hello world");

            let trace = get_trace_for_tag(DEFAULT_TAG).unwrap();
            assert!(trace.contains("test_parser"));
            assert!(trace.contains("hello world"));
        }

        #[test]
        fn test_get_trace_for_nonexistent_tag() {
            let trace = get_trace_for_tag("nonexistent");
            assert!(trace.is_none());
        }
    }

    #[cfg(feature = "trace-silencing")]
    mod trace_silencing_tests {
        use {super::*, nom::sequence::tuple};

        #[test]
        fn test_silence_tree() {
            let mut parser = silence_tree(
                DEFAULT_TAG,
                Some("context"),
                "silent_parser",
                tag::<_, _, VerboseError<_>>("hello"),
            );
            let result = parser("hello world");
            assert!(result.is_ok());

            let trace = get_trace_for_tag(DEFAULT_TAG).unwrap();
            assert!(!trace.contains("silent_parser"));
        }

        #[test]
        fn test_silence_tree_with_nested_parsers() {
            let mut outer_parser = tr(
                DEFAULT_TAG,
                None,
                "outer_parser",
                silence_tree(
                    DEFAULT_TAG,
                    None,
                    "inner_parser",
                    tr(
                        DEFAULT_TAG,
                        None,
                        "inner",
                        tag::<_, _, VerboseError<_>>("hello"),
                    ),
                ),
            );

            let result = outer_parser("hello world");
            assert!(result.is_ok());

            let trace = get_trace_for_tag(DEFAULT_TAG).unwrap();
            assert!(trace.contains("outer_parser"));
            assert!(!trace.contains("inner_parser"));
        }

        #[test]
        fn test_nested_silence_tree() {
            #[allow(clippy::type_complexity)]
            fn nested_parser(
                input: &str,
            ) -> IResult<&str, (&str, (&str, &str), &str), VerboseError<&str>> {
                trace!(
                    "outer",
                    tuple((
                        trace!("first", tag::<_, _, VerboseError<&str>>("a")),
                        silence_tree!(
                            "silent",
                            tuple((
                                trace!("second", tag("b")),
                                silence_tree!("inner_silent", trace!("third", tag("c"))),
                            ))
                        ),
                        trace!("fourth", tag("d")),
                    ))
                )(input)
            }

            // Run the parser
            let result = nested_parser("abcd");
            assert!(result.is_ok());

            // Get the trace
            let trace = get_trace!().unwrap();
            println!("{}", trace);

            // Check that the trace contains the expected elements
            assert!(trace.contains("outer"));
            assert!(trace.contains("first"));
            assert!(trace.contains("fourth"));

            // Check that the silenced parts are not in the trace
            assert!(!trace.contains("silent"));
            assert!(!trace.contains("second"));
            assert!(!trace.contains("inner_silent"));
            assert!(!trace.contains("third"));

            // Additional checks to ensure correct nesting behavior
            assert_eq!(trace.matches("[outer]").count(), 2); // Open and close for outer
            assert_eq!(trace.matches("[first]").count(), 2); // Open and close for first
            assert_eq!(trace.matches("[fourth]").count(), 2); // Open and close for fourth

            // The silent part should not increase the visible nesting level
            assert!(!trace.contains("| | |"));

            // Check the order of operations
            let trace_lines: Vec<&str> = trace.split('\n').collect();
            assert!(
                trace_lines
                    .iter()
                    .position(|&r| r.contains("first"))
                    .unwrap()
                    < trace_lines
                        .iter()
                        .position(|&r| r.contains("fourth"))
                        .unwrap()
            );
        }
    }

    #[cfg(all(feature = "trace", feature = "trace-context"))]
    mod trace_context_tests {
        use {
            super::*,
            nom::error::{ErrorKind, VerboseErrorKind},
        };

        #[test]
        fn test_add_context_to_err() {
            let mut parser = tr(
                DEFAULT_TAG,
                Some("context"),
                "test_parser",
                tag::<_, _, VerboseError<_>>("hello"),
            );
            let result = parser("world");

            assert!(result.is_err());

            if let Err(nom::Err::Error(e)) = result {
                assert_eq!(e.errors.len(), 2);
                assert_eq!(e.errors[1].1, VerboseErrorKind::Context("context"));
                assert_eq!(e.errors[0].1, VerboseErrorKind::Nom(ErrorKind::Tag));
            } else {
                panic!("Expected Err(nom::Err::Error)");
            }
        }
    }

    #[cfg(not(feature = "trace"))]
    mod no_trace_tests {
        use {
            super::*,
            nom::error::{ErrorKind, VerboseErrorKind},
        };

        #[test]
        fn test_tr_without_trace() {
            let mut parser = tr(
                DEFAULT_TAG,
                Some("context"),
                "test_parser",
                tag::<_, _, VerboseError<_>>("hello"),
            );
            let result = parser("hello world");
            assert!(result.is_ok());
            assert_eq!(result, Ok((" world", "hello")));
        }

        #[test]
        fn test_get_trace_for_tag_without_trace() {
            assert!(get_trace_for_tag(DEFAULT_TAG).is_none());
        }

        #[cfg(feature = "trace-context")]
        mod context_without_trace_tests {
            use {
                super::*,
                nom::error::{ErrorKind, VerboseErrorKind},
            };

            #[test]
            fn test_context_addition_without_trace() {
                let mut parser = tr(
                    DEFAULT_TAG,
                    Some("context"),
                    "test_parser",
                    tag::<_, _, VerboseError<_>>("hello"),
                );
                let result = parser("world");

                assert!(result.is_err());

                if let Err(nom::Err::Error(e)) = result {
                    assert_eq!(e.errors.len(), 2);
                    assert_eq!(e.errors[1].1, VerboseErrorKind::Context("context"));
                    assert_eq!(e.errors[0].1, VerboseErrorKind::Nom(ErrorKind::Tag));
                } else {
                    panic!("Expected Err(nom::Err::Error)");
                }
            }
        }

        #[cfg(not(feature = "trace-context"))]
        #[test]
        fn test_error_without_trace_and_context() {
            let mut parser = tr(
                DEFAULT_TAG,
                Some("context"),
                "test_parser",
                tag::<_, _, VerboseError<_>>("hello"),
            );
            let result = parser("world");

            assert!(result.is_err());

            if let Err(nom::Err::Error(e)) = result {
                println!("{:?}", e);
                assert_eq!(e.errors.len(), 1);
                assert_eq!(e.errors[0].1, VerboseErrorKind::Nom(ErrorKind::Tag));
            } else {
                panic!("Expected Err(nom::Err::Error)");
            }
        }
    }
}