nom_tracer/
lib.rs

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
// Copyright (c) Hexbee
// SPDX-License-Identifier: Apache-2.0

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

mod events;
mod macros;
mod traces;

/// The default tag used when no specific tag is provided.
#[cfg(feature = "trace")]
pub const DEFAULT_TAG: &str = "default";

thread_local! {
    /// Thread-local storage for the global [TraceList].
    ///
    /// [NOM_TRACE] 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 [TraceList] can be
    /// modified even when accessed through a shared reference.
    ///
    /// Usage of [NOM_TRACE] 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 NOM_TRACE: std::cell::RefCell<TraceList> = ::std::cell::RefCell::new(TraceList::new());
}

/// A collection of traces, each associated with a tag.
///
/// The tag system allows for multiple independent traces to be maintained simultaneously.
/// Each tag corresponds to a separate `Trace` instance, allowing for organization and
/// separation of trace events based on different criteria (e.g., parser type, subsystem, etc.).
#[cfg(feature = "trace")]
#[derive(Default)]
pub struct TraceList {
    pub traces: HashMap<&'static str, Trace>,
}

#[cfg(feature = "trace")]
impl TraceList {
    /// Creates a new [TraceList] with a default trace.
    ///
    /// The default trace is associated with the `DEFAULT_TAG`.
    pub fn new() -> Self {
        let mut traces = HashMap::new();
        traces.insert(
            DEFAULT_TAG,
            Trace {
                events: Vec::new(),
                level: 0,
                active: true,
            },
        );

        TraceList { traces }
    }

    /// Resets the trace for the given tag.
    ///
    /// This clears all events and resets the nesting level for the specified trace.
    /// If the trace doesn't exist, a new one is created and inserted.
    pub fn reset(&mut self, tag: &'static str) {
        let t = self.traces.entry(tag).or_insert(Trace {
            events: Vec::new(),
            level: 0,
            active: true,
        });
        t.reset();
    }

    /// Returns the trace for the given tag as a string, if it exists.
    pub fn get_trace(&self, tag: &'static str) -> Option<String> {
        self.traces.get(tag).map(|t| t.to_string())
    }

    /// Activates the trace for the given tag.
    ///
    /// Activated traces will record events.
    /// If the trace doesn't exist, a new one is created and activated.
    pub fn activate(&mut self, tag: &'static str) {
        let t = self.traces.entry(tag).or_insert(Trace {
            events: Vec::new(),
            level: 0,
            active: true,
        });
        t.active = true;
    }

    /// Deactivates the trace for the given tag.
    ///
    /// Deactivated traces will not record events, but will retain previously recorded events.
    /// If the trace doesn't exist, a new one is created (but left inactive).
    pub fn deactivate(&mut self, tag: &'static str) {
        let t = self.traces.entry(tag).or_insert(Trace {
            events: Vec::new(),
            level: 0,
            active: true,
        });
        t.active = false;
    }

    /// Opens a new trace event for the given tag.
    ///
    /// This increases the nesting level for the trace and records an 'open' event.
    /// The hierarchical structure of parsing is represented by these nested open/close events.
    pub fn open<I>(
        &mut self,
        tag: &'static str,
        context: Option<&'static str>,
        input: I,
        location: &'static str,
    ) where
        I: AsRef<str>,
    {
        let t = self.traces.entry(tag).or_insert(Trace {
            events: Vec::new(),
            level: 0,
            active: true,
        });
        t.open(context, input, location);
    }

    /// Closes the current trace event for the given tag.
    ///
    /// This decreases the nesting level for the trace and records a 'close' event,
    /// including the result of the parsing operation (success, error, etc.).
    /// The hierarchical structure is maintained by matching each 'close' with a previous 'open'.
    pub fn close<I, O: Debug, E: Debug>(
        &mut self,
        tag: &'static str,
        context: Option<&'static str>,
        input: I,
        location: &'static str,
        result: &IResult<I, O, E>,
    ) where
        I: AsRef<str>,
    {
        let t = self.traces.entry(tag).or_insert(Trace {
            events: Vec::new(),
            level: 0,
            active: true,
        });
        t.close(context, input, location, result);
    }
}

#[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 {}

/// Wraps a parser with tracing, using the default tag.
///
/// This is the simplest tracing function, which wraps a parser with tracing functionality
/// using the default tag. It's ideal for basic tracing needs when you don't need to
/// categorize traces or add additional context.
///
/// # Arguments
///
/// * `name` - A static string identifying the parser.
/// * `parser` - The parser to be wrapped.
///
/// # Example
///
/// ```
/// use nom_tracer::tr;
/// use nom::bytes::complete::tag;
/// use nom::IResult;
///
/// fn parse_hello(input: &str) -> IResult<&str, &str> {
///     tr("parse_hello", tag("hello"))(input)
/// }
///
/// let result = parse_hello("hello world");
/// assert_eq!(result, Ok((" world", "hello")));
/// ```
#[allow(unused_mut)]
#[allow(unused_variables)]
pub fn tr<I, O, E, F>(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")]
    {
        tr_tag_ctx(DEFAULT_TAG, None, name, parser)
    }

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

/// Wraps a parser with tracing, using the default tag and a context.
///
/// This function is similar to [tr], but it allows you to specify a context
/// string that provides additional information about the parser's purpose or role.
///
/// # Arguments
///
/// * `name` - A static string identifying the parser.
/// * `context` - A static string providing context for the parser.
/// * `parser` - The parser to be wrapped.
///
/// # Example
///
/// ```
/// use nom_tracer::tr_ctx;
/// use nom::bytes::complete::tag;
/// use nom::IResult;
///
/// fn parse_greeting(input: &str) -> IResult<&str, &str> {
///     tr_ctx("parse_greeting", "Greeting parser", tag("hello"))(input)
/// }
///
/// let result = parse_greeting("hello world");
/// assert_eq!(result, Ok((" world", "hello")));
/// ```
#[allow(unused_mut)]
#[allow(unused_variables)]
pub fn tr_ctx<I, O, E, F>(
    name: &'static str,
    context: &'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")]
    {
        tr_tag_ctx(DEFAULT_TAG, Some(context), name, parser)
    }

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

/// Wraps a parser with tracing, using a specified tag.
///
/// This function allows you to organize traces into different categories or groups
/// by specifying a custom tag.
///
/// # Arguments
///
/// * `tag` - A static string used to categorize the trace.
/// * `name` - A static string identifying the parser.
/// * `parser` - The parser to be wrapped.
///
/// # Example
///
/// ```
/// use nom_tracer::tr_tag;
/// use nom::character::complete::digit1;
/// use nom::IResult;
///
/// fn parse_number(input: &str) -> IResult<&str, &str> {
///     tr_tag("numeric", "parse_number", digit1)(input)
/// }
///
/// let result = parse_number("123 abc");
/// assert_eq!(result, Ok((" abc", "123")));
/// ```
#[allow(unused_variables)]
#[allow(unused_mut)]
pub fn tr_tag<I, O, E, F>(
    tag: &'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>,
{
    #[cfg(feature = "trace")]
    {
        tr_tag_ctx(tag, None, name, parser)
    }

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

/// Wraps a parser with tracing, using a specified tag and optional context.
///
/// This is the most flexible tracing function, allowing you to specify both a custom tag
/// and an optional context.
///
/// # Arguments
///
/// * `tag` - A static string used to categorize the trace.
/// * `context` - An optional static string providing context for the parser.
/// * `name` - A static string identifying the parser.
/// * `parser` - The parser to be wrapped.
///
/// # Example
///
/// ```
/// use nom_tracer::tr_tag_ctx;
/// use nom::bytes::complete::tag;
/// use nom::IResult;
///
/// fn parse_complex(input: &str) -> IResult<&str, &str> {
///     tr_tag_ctx("complex", Some("Complex parser section"), "parse_complex", tag("complex"))(input)
/// }
///
/// let result = parse_complex("complex input");
/// assert_eq!(result, Ok((" input", "complex")));
/// ```
#[allow(unused_variables)]
pub fn tr_tag_ctx<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>,
{
    #[cfg(feature = "trace")]
    {
        move |input: I| {
            let input1 = input.clone();
            let input2 = input.clone();
            let input3 = input.clone();

            NOM_TRACE.with(|trace| {
                (*trace.borrow_mut()).open(tag, context, input1, name);
            });

            let res = parser.parse(input);

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

            #[cfg(feature = "trace-context")]
            {
                match res {
                    Ok(o) => Ok(o),
                    Err(nom::Err::Error(e)) => {
                        Err(nom::Err::Error(E::add_context(input3, name, e)))
                    }
                    Err(nom::Err::Failure(e)) => {
                        Err(nom::Err::Failure(E::add_context(input3, name, e)))
                    }
                    Err(nom::Err::Incomplete(i)) => Err(nom::Err::Incomplete(i)),
                }
            }
            #[cfg(not(feature = "trace-context"))]
            {
                res
            }
        }
    }

    #[cfg(not(feature = "trace"))]
    {
        #[cfg(feature = "trace-context")]
        {
            move |input: I| match parser.parse(input.clone()) {
                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)),
            }
        }
        #[cfg(not(feature = "trace-context"))]
        {
            move |input: I| parser.parse(input)
        }
    }
}

/// Gets the trace for the default tag.
///
/// When the "trace" feature is not enabled, this function always returns an empty string.
///
/// # Example
///
/// ```
/// # use nom::bytes::complete::tag;
/// # use nom::IResult;
/// # use nom_tracer::{get_trace, tr};
///
/// fn parse_hello(input: &str) -> IResult<&str, &str> {
///     tr("parse_hello", tag("hello"))(input)
/// }
///
/// let _ = parse_hello("hello world");
/// let trace = get_trace();
/// println!("Default trace:\n{}", trace);
/// ```
pub fn get_trace() -> String {
    #[cfg(feature = "trace")]
    {
        get_trace_for_tag(DEFAULT_TAG)
    }

    #[cfg(not(feature = "trace"))]
    {
        String::new()
    }
}

/// Gets the trace for a specified tag.
///
/// When the "trace" feature is not enabled, this function always returns an empty string.
///
/// If no trace exists for the given tag, returns an error message.
///
/// # Example
///
/// ```
/// # use nom::bytes::complete::tag;
/// # use nom::IResult;
/// # use nom_tracer::{get_trace_for_tag, tr_tag_ctx};
///
/// fn parse_world(input: &str) -> IResult<&str, &str> {
///     tr_tag_ctx("greeting",None, "parse_world", tag("world"))(input)
/// }
///
/// let _ = parse_world("world hello");
/// let trace = get_trace_for_tag("greeting");
/// println!("Greeting trace:\n{}", trace);
///
/// // Trying to get a trace for a non-existent tag
/// let non_existent_trace = get_trace_for_tag("non_existent");
/// println!("Non-existent trace: {}", non_existent_trace);
/// ```
pub fn get_trace_for_tag(tag: &'static str) -> String {
    #[cfg(feature = "trace")]
    {
        NOM_TRACE.with(|trace| {
            if let Some(trace) = trace.borrow().traces.get(tag) {
                trace.to_string()
            } else {
                format!("No trace found for tag '{}'", tag)
            }
        })
    }

    #[cfg(not(feature = "trace"))]
    {
        let _ = tag;
        String::new()
    }
}

/// Prints the entire trace for the default tag to the console.
///
/// This function retrieves the trace for the default tag using `get_trace()`
/// and prints it to the console using the `print()` function.
///
/// # Examples
///
/// ```
/// use nom_tracer::{trace, print_trace};
/// use nom::bytes::complete::tag;
///
/// let _ = trace!(tag::<&str, &str, nom::error::VerboseError<_>>("hello"))("hello world");
/// print_trace();
/// ```
pub fn print_trace() {
    print(get_trace());
}

/// Prints the trace for a specific tag to the console.
///
/// This function retrieves the trace for the specified tag using `get_trace_for_tag()`
/// and prints it to the console using the `print()` function.
///
/// # Arguments
///
/// * `tag` - A static string slice representing the tag for which to print the trace.
///
/// # Examples
///
/// ```
/// use nom_tracer::{trace, print_trace_for_tag};
/// use nom::bytes::complete::tag;
///
/// let _ = trace!(my_tag, tag::<&str, &str, nom::error::VerboseError<_>>("hello"))("hello world");
/// print_trace_for_tag("my_tag");
/// ```
pub fn print_trace_for_tag(tag: &'static str) {
    print(get_trace_for_tag(tag));
}

pub(crate) fn print<I: AsRef<str>>(s: I) {
    use std::io::Write;

    #[cfg(feature = "trace-color")]
    {
        use termcolor::{ColorChoice, StandardStream};
        let mut handle = StandardStream::stdout(ColorChoice::Always);
        write!(handle, "{}", s.as_ref()).unwrap();
    }

    #[cfg(not(feature = "trace-color"))]
    {
        let stdout = std::io::stdout();
        let mut handle = stdout.lock();
        write!(handle, "{}", s.as_ref()).unwrap();
    }
}

#[cfg(all(test, feature = "trace"))]
mod tests {
    use super::*;

    #[test]
    fn test_trace_list_new() {
        let trace_list = TraceList::new();
        assert!(trace_list.traces.contains_key(DEFAULT_TAG));
    }

    #[test]
    fn test_trace_list_reset() {
        let mut trace_list = TraceList::new();
        trace_list.open(DEFAULT_TAG, None, "input", "location");
        trace_list.reset(DEFAULT_TAG);
        assert_eq!(trace_list.traces[DEFAULT_TAG].events.len(), 0);
        assert_eq!(trace_list.traces[DEFAULT_TAG].level, 0);
    }

    #[test]
    fn test_trace_list_activate_deactivate() {
        let mut trace_list = TraceList::new();
        trace_list.deactivate(DEFAULT_TAG);
        assert!(!trace_list.traces[DEFAULT_TAG].active);
        trace_list.activate(DEFAULT_TAG);
        assert!(trace_list.traces[DEFAULT_TAG].active);
    }
}