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
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
//! `nom-tracable` is an extension of [nom](https://docs.rs/nom) to trace parser.
//!
//! ## Examples
//!
//! The following example show a quick example.
//!
//! ```
//! use nom::character::complete::*;
//! use nom::IResult;
//! use nom_locate::LocatedSpan;
//! use nom_tracable::{tracable_parser, TracableInfo};
//!
//! // Input type must implement trait Tracable
//! // nom_locate::LocatedSpan<T, TracableInfo> implements it.
//! type Span<'a> = LocatedSpan<&'a str, TracableInfo>;
//!
//! // Apply tracable_parser by custom attribute
//! #[tracable_parser]
//! pub fn term(s: Span) -> IResult<Span, String> {
//!     let (s, x) = char('1')(s)?;
//!     Ok((s, x.to_string()))
//! }
//!
//! #[test]
//! fn test() {
//!     // Configure trace setting
//!     let info = TracableInfo::new().forward(true).backward(true);
//!     let ret = term(LocatedSpan::new_extra("1", info));
//!     assert_eq!("\"1\"", format!("{:?}", ret.unwrap().1));
//! }
//! ```

#[cfg(feature = "trace")]
use nom::IResult;
/// Custom attribute to enable trace
pub use nom_tracable_macros::tracable_parser;
use std::{collections::HashMap, io::Write};

/// Trait to indicate the type can display as fragment.
pub trait FragmentDisplay {
    fn display(&self, width: usize) -> String;
}

impl FragmentDisplay for &[u8] {
    fn display(&self, width: usize) -> String {
        self.iter()
            .take(width / 2)
            .map(|x| format!("{:>02X}", x))
            .collect()
    }
}

impl FragmentDisplay for &str {
    fn display(&self, width: usize) -> String {
        self.lines()
            .next()
            .unwrap_or_else(|| "")
            .chars()
            .take(width)
            .collect()
    }
}

/// Trait to indicate the type has information for tracing.
pub trait Tracable: HasTracableInfo {
    fn inc_depth(self) -> Self;
    fn dec_depth(self) -> Self;
    fn format(&self) -> String;
    fn header(&self) -> String;
}

/// Trait to indicate `TracableInfo` is provided.
pub trait HasTracableInfo {
    fn get_tracable_info(&self) -> TracableInfo;
    fn set_tracable_info(self, info: TracableInfo) -> Self;
}

/// Struct to have trace configuration.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct TracableInfo {
    #[cfg(feature = "trace")]
    pub depth: usize,
    #[cfg(feature = "trace")]
    pub forward: bool,
    #[cfg(feature = "trace")]
    pub backward: bool,
    #[cfg(feature = "trace")]
    pub custom: bool,
    #[cfg(feature = "trace")]
    pub color: bool,
    #[cfg(feature = "trace")]
    pub count_width: usize,
    #[cfg(feature = "trace")]
    pub parser_width: usize,
    #[cfg(feature = "trace")]
    pub fragment_width: usize,
    #[cfg(feature = "trace")]
    pub fold: u64,
}

impl Default for TracableInfo {
    fn default() -> Self {
        TracableInfo {
            #[cfg(feature = "trace")]
            depth: 0,
            #[cfg(feature = "trace")]
            forward: true,
            #[cfg(feature = "trace")]
            backward: true,
            #[cfg(feature = "trace")]
            custom: true,
            #[cfg(feature = "trace")]
            color: true,
            #[cfg(feature = "trace")]
            count_width: 10,
            #[cfg(feature = "trace")]
            parser_width: 96,
            #[cfg(feature = "trace")]
            fragment_width: 96,
            #[cfg(feature = "trace")]
            fold: 0,
        }
    }
}

#[cfg(feature = "trace")]
impl TracableInfo {
    pub fn new() -> Self {
        TracableInfo::default()
    }

    pub fn depth(mut self, x: usize) -> Self {
        self.depth = x;
        self
    }

    /// Set whether forward trace is displayed.
    pub fn forward(mut self, x: bool) -> Self {
        self.forward = x;
        self
    }

    /// Set whether backward trace is displayed.
    pub fn backward(mut self, x: bool) -> Self {
        self.backward = x;
        self
    }

    /// Set whether custom trace is displayed.
    pub fn custom(mut self, x: bool) -> Self {
        self.custom = x;
        self
    }

    /// Set whether color is enabled.
    pub fn color(mut self, x: bool) -> Self {
        self.color = x;
        self
    }

    /// Set the width of forward/backward count.
    pub fn count_width(mut self, x: usize) -> Self {
        self.count_width = x;
        self
    }

    /// Set the width of parser name.
    pub fn parser_width(mut self, x: usize) -> Self {
        self.parser_width = x;
        self
    }

    /// Set the width of fragment.
    pub fn fragment_width(mut self, x: usize) -> Self {
        self.fragment_width = x;
        self
    }

    /// Set the name of folding parser.
    pub fn fold(mut self, x: &str) -> Self {
        let index =
            crate::TRACABLE_STORAGE.with(|storage| storage.borrow_mut().get_parser_index(x));

        let val = 1u64 << index;
        let mask = !(1u64 << index);

        self.fold = (self.fold & mask) | val;
        self
    }

    fn folded(self, x: &str) -> bool {
        let index =
            crate::TRACABLE_STORAGE.with(|storage| storage.borrow_mut().get_parser_index(x));

        if index < 64 {
            ((self.fold >> index) & 1u64) == 1u64
        } else {
            false
        }
    }
}

#[cfg(not(feature = "trace"))]
impl TracableInfo {
    pub fn new() -> Self {
        TracableInfo::default()
    }

    pub fn forward(self, _x: bool) -> Self {
        self
    }

    pub fn backward(self, _x: bool) -> Self {
        self
    }

    pub fn custom(self, _x: bool) -> Self {
        self
    }

    pub fn color(self, _x: bool) -> Self {
        self
    }

    pub fn count_width(self, _x: usize) -> Self {
        self
    }

    pub fn parser_width(self, _x: usize) -> Self {
        self
    }

    pub fn fragment_width(self, _x: usize) -> Self {
        self
    }

    pub fn fold(self, _x: &str) -> Self {
        self
    }
}

impl HasTracableInfo for TracableInfo {
    fn get_tracable_info(&self) -> TracableInfo {
        *self
    }

    fn set_tracable_info(self, info: TracableInfo) -> Self {
        info
    }
}

#[cfg(feature = "trace")]
impl<T, U: HasTracableInfo> HasTracableInfo for nom_locate::LocatedSpan<T, U> {
    fn get_tracable_info(&self) -> TracableInfo {
        self.extra.get_tracable_info()
    }

    fn set_tracable_info(mut self, info: TracableInfo) -> Self {
        self.extra = self.extra.set_tracable_info(info);
        self
    }
}

#[cfg(feature = "trace")]
impl<T: FragmentDisplay + nom::AsBytes, U: HasTracableInfo> Tracable
    for nom_locate::LocatedSpan<T, U>
{
    fn inc_depth(self) -> Self {
        let info = self.get_tracable_info();
        let info = info.depth(info.depth + 1);
        self.set_tracable_info(info)
    }

    fn dec_depth(self) -> Self {
        let info = self.get_tracable_info();
        let info = info.depth(info.depth - 1);
        self.set_tracable_info(info)
    }

    fn format(&self) -> String {
        let info = self.get_tracable_info();
        let fragment = self.fragment().display(info.fragment_width);
        format!("{:<8} : {}", self.location_offset(), fragment)
    }

    fn header(&self) -> String {
        format!("{:<8} : {}", "offset", "fragment")
    }
}

#[derive(Debug, Default)]
struct TracableStorage {
    forward_count: usize,
    backward_count: usize,
    parser_indexes: HashMap<String, usize>,
    parser_index_next: usize,
    histogram: HashMap<String, usize>,
    cumulative_histogram: HashMap<String, usize>,
    cumulative_working: HashMap<(String, usize), usize>,
}

#[allow(dead_code)]
impl TracableStorage {
    fn new() -> Self {
        TracableStorage::default()
    }

    fn init(&mut self) {
        self.forward_count = 0;
        self.backward_count = 0;
        self.histogram.clear();
        self.cumulative_histogram.clear();
        self.cumulative_working.clear();
    }

    fn get_forward_count(&self) -> usize {
        self.forward_count
    }

    fn get_backward_count(&self) -> usize {
        self.backward_count
    }

    fn inc_forward_count(&mut self) {
        self.forward_count += 1
    }

    fn inc_backward_count(&mut self) {
        self.backward_count += 1
    }

    fn inc_histogram(&mut self, key: &str) {
        let next = if let Some(x) = self.histogram.get(key) {
            x + 1
        } else {
            1
        };
        self.histogram.insert(String::from(key), next);
    }

    fn inc_cumulative_histogram(&mut self, key: &str, cnt: usize) {
        let next = if let Some(x) = self.cumulative_histogram.get(key) {
            x + cnt
        } else {
            cnt
        };
        self.cumulative_histogram.insert(String::from(key), next);
    }

    fn add_cumulative(&mut self, key: &str, depth: usize) {
        self.cumulative_working
            .insert((String::from(key), depth), 0);
    }

    fn inc_cumulative(&mut self) {
        for val in self.cumulative_working.values_mut() {
            *val = *val + 1;
        }
    }

    fn del_cumulative(&mut self, key: &str, depth: usize) {
        self.cumulative_working.remove(&(key.to_string(), depth));
    }

    fn get_cumulative(&mut self, key: &str, depth: usize) -> Option<&usize> {
        self.cumulative_working.get(&(key.to_string(), depth))
    }

    fn get_parser_index(&mut self, key: &str) -> usize {
        if let Some(x) = self.parser_indexes.get(key) {
            *x
        } else {
            let new_index = self.parser_index_next;
            self.parser_index_next += 1;
            self.parser_indexes.insert(String::from(key), new_index);
            new_index
        }
    }
}

#[cfg(feature = "trace")]
thread_local!(
    static TRACABLE_STORAGE: core::cell::RefCell<crate::TracableStorage> = {
        core::cell::RefCell::new(crate::TracableStorage::new())
    }
);

/// Show histogram of parser call count.
///
/// The statistics information to generate histogram is reset at each parser call.
/// Therefore `histogram` should be called before next parser call.
/// The information is thread independent because it is stored at thread local storage.
///
/// ```
/// # use nom::character::complete::*;
/// # use nom::IResult;
/// # use nom_locate::LocatedSpan;
/// # use nom_tracable::{cumulative_histogram, tracable_parser, TracableInfo};
/// #
/// # type Span<'a> = LocatedSpan<&'a str, TracableInfo>;
/// #
/// # #[tracable_parser]
/// # pub fn term(s: Span) -> IResult<Span, String> {
/// #     let (s, x) = char('1')(s)?;
/// #     Ok((s, x.to_string()))
/// # }
/// #
/// # #[test]
/// # fn test() {
///     let ret = term(LocatedSpan::new_extra("1", TracableInfo::new()));
///     histogram(); // Show histogram of "1" parsing
///
///     let ret = term(LocatedSpan::new_extra("11", TracableInfo::new()));
///     histogram(); // Show histogram of "11" parsing
/// # }
/// ```
pub fn histogram() {
    histogram_internal();
}

#[cfg(feature = "trace")]
fn histogram_internal() {
    crate::TRACABLE_STORAGE.with(|storage| {
        let storage = storage.borrow();
        show_histogram("histogram", &storage.histogram);
    });
}

#[cfg(not(feature = "trace"))]
fn histogram_internal() {}

/// Show cumulative histogram of parser call count.
///
/// The call count includes the counts of children parsers.
///
/// The statistics information to generate histogram is reset at each parser call.
/// Therefore `cumulative_histogram` should be called before next parser call.
/// The information is thread independent because it is stored at thread local storage.
///
/// ```
/// # use nom::character::complete::*;
/// # use nom::IResult;
/// # use nom_locate::LocatedSpan;
/// # use nom_tracable::{cumulative_histogram, tracable_parser, TracableInfo};
/// #
/// # type Span<'a> = LocatedSpan<&'a str, TracableInfo>;
/// #
/// # #[tracable_parser]
/// # pub fn term(s: Span) -> IResult<Span, String> {
/// #     let (s, x) = char('1')(s)?;
/// #     Ok((s, x.to_string()))
/// # }
/// #
/// # #[test]
/// # fn test() {
///     let ret = term(LocatedSpan::new_extra("1", TracableInfo::new()));
///     cumulative_histogram(); // Show cumulative histogram of "1" parsing
///
///     let ret = term(LocatedSpan::new_extra("11", TracableInfo::new()));
///     cumulative_histogram(); // Show cumulative histogram of "11" parsing
/// # }
/// ```
pub fn cumulative_histogram() {
    cumulative_histogram_internal();
}

#[cfg(feature = "trace")]
fn cumulative_histogram_internal() {
    crate::TRACABLE_STORAGE.with(|storage| {
        let storage = storage.borrow();
        show_histogram("cumulative histogram", &storage.cumulative_histogram);
    });
}

#[cfg(not(feature = "trace"))]
fn cumulative_histogram_internal() {}

#[allow(dead_code)]
fn show_histogram(title: &str, map: &HashMap<String, usize>) {
    let mut result = Vec::new();
    let mut max_parser_len = "parser".len();
    let mut max_count = 0;
    let mut max_count_len = "count".len();
    for (p, c) in map {
        result.push((p, c));
        max_parser_len = max_parser_len.max(p.len());
        max_count = max_count.max(*c);
        max_count_len = max_count_len.max(format!("{}", c).len());
    }

    result.sort_by(|a, b| b.1.partial_cmp(a.1).unwrap());

    let bar_length = 50;

    let mut lock = if cfg!(feature = "stderr") {
        Box::new(std::io::stderr().lock()) as Box<dyn Write>
    } else {
        Box::new(std::io::stdout().lock()) as Box<dyn Write>
    };

    writeln!(
        lock,
        "\n{:<parser$} | {:<bar$} | {}",
        "parser",
        title,
        "count",
        parser = max_parser_len,
        bar = bar_length,
    )
    .unwrap();

    writeln!(
        lock,
        "{:<parser$} | {:<bar$} | {}",
        "-".repeat(max_parser_len),
        "-".repeat(bar_length),
        "-".repeat(max_count_len),
        parser = max_parser_len,
        bar = bar_length,
    )
    .unwrap();

    for (p, c) in &result {
        let bar = *c * bar_length / max_count;
        if bar > 0 {
            writeln!(
                lock,
                "{:<parser$} | {}{} | {}",
                p,
                ".".repeat(bar),
                " ".repeat(bar_length - bar),
                c,
                parser = max_parser_len,
            )
            .unwrap();
        }
    }
    writeln!(lock, "").unwrap()
}

/// Function to display forward trace.
/// This is inserted by `#[tracable_parser]`.
#[cfg(feature = "trace")]
pub fn forward_trace<T: Tracable>(input: T, name: &str) -> (TracableInfo, T) {
    let info = input.get_tracable_info();
    let depth = info.depth;

    let mut lock = if cfg!(feature = "stderr") {
        Box::new(std::io::stderr().lock()) as Box<dyn Write>
    } else {
        Box::new(std::io::stdout().lock()) as Box<dyn Write>
    };

    if depth == 0 {
        crate::TRACABLE_STORAGE.with(|storage| {
            storage.borrow_mut().init();
        });
        let forward_backword = if info.forward & info.backward {
            format!(
                "{:<count_width$} {:<count_width$}",
                "forward",
                "backward",
                count_width = info.count_width
            )
        } else if info.forward {
            format!(
                "{:<count_width$}",
                "forward",
                count_width = info.count_width
            )
        } else {
            format!(
                "{:<count_width$}",
                "backward",
                count_width = info.count_width
            )
        };

        let control_witdh = if info.color { 11 } else { 0 };

        writeln!(
            lock,
            "\n{} : {:<parser_width$} : {}",
            forward_backword,
            "parser",
            input.header(),
            parser_width = info.parser_width - control_witdh,
        )
        .unwrap();
    }

    if info.forward {
        let forward_count = crate::TRACABLE_STORAGE.with(|storage| {
            storage.borrow_mut().inc_forward_count();
            storage.borrow().get_forward_count()
        });

        let forward_backword = if info.backward {
            format!(
                "{:<count_width$} {:<count_width$}",
                forward_count,
                "",
                count_width = info.count_width
            )
        } else {
            format!(
                "{:<count_width$}",
                forward_count,
                count_width = info.count_width
            )
        };

        let color = if info.color { "\u{001b}[1;37m" } else { "" };
        let reset = if info.color { "\u{001b}[0m" } else { "" };
        let folded = if info.folded(name) { "+" } else { " " };

        writeln!(
            lock,
            "{} : {:<parser_width$} : {}",
            forward_backword,
            format!(
                "{}{}-> {} {}{}",
                color,
                " ".repeat(depth),
                name,
                folded,
                reset
            ),
            input.format(),
            parser_width = info.parser_width,
        )
        .unwrap();
    }

    crate::TRACABLE_STORAGE.with(|storage| {
        storage.borrow_mut().inc_histogram(name);
        storage.borrow_mut().add_cumulative(name, depth);
        storage.borrow_mut().inc_cumulative();
    });

    let input = if info.folded(name) {
        let info = info.forward(false).backward(false).custom(false);
        input.set_tracable_info(info)
    } else {
        input
    };

    let input = input.inc_depth();
    (info, input)
}

/// Function to display backward trace.
/// This is inserted by `#[tracable_parser]`.
#[cfg(feature = "trace")]
pub fn backward_trace<T: Tracable, U, V>(
    input: IResult<T, U, V>,
    name: &str,
    info: TracableInfo,
) -> IResult<T, U, V> {
    let depth = info.depth;

    crate::TRACABLE_STORAGE.with(|storage| {
        let cnt = *storage.borrow_mut().get_cumulative(name, depth).unwrap();
        storage.borrow_mut().inc_cumulative_histogram(name, cnt);
    });

    if info.backward {
        let backward_count = crate::TRACABLE_STORAGE.with(|storage| {
            storage.borrow_mut().inc_backward_count();
            storage.borrow().get_backward_count()
        });

        let forward_backword = if info.forward {
            format!(
                "{:<count_width$} {:<count_width$}",
                "",
                backward_count,
                count_width = info.count_width
            )
        } else {
            format!(
                "{:<count_width$}",
                backward_count,
                count_width = info.count_width
            )
        };

        let color_ok = if info.color { "\u{001b}[1;32m" } else { "" };
        let color_err = if info.color { "\u{001b}[1;31m" } else { "" };
        let reset = if info.color { "\u{001b}[0m" } else { "" };
        let folded = if info.folded(name) { "+" } else { " " };

        let mut lock = if cfg!(feature = "stderr") {
            Box::new(std::io::stderr().lock()) as Box<dyn Write>
        } else {
            Box::new(std::io::stdout().lock()) as Box<dyn Write>
        };

        match input {
            Ok((s, x)) => {
                writeln!(
                    lock,
                    "{} : {:<parser_width$} : {}",
                    forward_backword,
                    format!(
                        "{}{}<- {} {}{}",
                        color_ok,
                        " ".repeat(depth),
                        name,
                        folded,
                        reset
                    ),
                    s.format(),
                    parser_width = info.parser_width,
                )
                .unwrap();

                let s = if info.folded(name) {
                    let info = s
                        .get_tracable_info()
                        .forward(info.forward)
                        .backward(info.backward)
                        .custom(info.custom);
                    s.set_tracable_info(info)
                } else {
                    s
                };

                Ok((s.dec_depth(), x))
            }
            Err(x) => {
                writeln!(
                    lock,
                    "{} : {:<parser_width$}",
                    forward_backword,
                    format!(
                        "{}{}<- {} {}{}",
                        color_err,
                        " ".repeat(depth),
                        name,
                        folded,
                        reset
                    ),
                    parser_width = info.parser_width,
                )
                .unwrap();
                Err(x)
            }
        }
    } else {
        input
    }
}

/// Function to display custom trace.
#[cfg(feature = "trace")]
pub fn custom_trace<T: Tracable>(input: &T, name: &str, message: &str, color: &str) {
    let info = input.get_tracable_info();

    if info.custom {
        let depth = info.depth;
        let forward_backword = format!(
            "{:<count_width$} {:<count_width$}",
            "",
            "",
            count_width = info.count_width
        );

        let color = if info.color { color } else { "" };
        let reset = if info.color { "\u{001b}[0m" } else { "" };

        let mut lock = if cfg!(feature = "stderr") {
            Box::new(std::io::stderr().lock()) as Box<dyn Write>
        } else {
            Box::new(std::io::stdout().lock()) as Box<dyn Write>
        };

        writeln!(
            lock,
            "{} : {:<parser_width$} : {}",
            forward_backword,
            format!("{}{}   {}{}", color, " ".repeat(depth), name, reset),
            message,
            parser_width = info.parser_width,
        )
        .unwrap();
    }
}