aboutsummaryrefslogtreecommitdiff
path: root/src/trace/internals.rs
blob: 136d21bdf255447595971a7cfbcfd75719b3eee9 (plain)
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
#![cfg(feature = "std")]

use std::io::Write;

use crate::error::ErrMode;
use crate::stream::Stream;

pub struct Depth {
    depth: usize,
    inc: bool,
}

impl Depth {
    pub fn new() -> Self {
        let depth = DEPTH.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
        let inc = true;
        Self { depth, inc }
    }

    pub fn existing() -> Self {
        let depth = DEPTH.load(std::sync::atomic::Ordering::SeqCst);
        let inc = false;
        Self { depth, inc }
    }
}

impl Drop for Depth {
    fn drop(&mut self) {
        if self.inc {
            let _ = DEPTH.fetch_sub(1, std::sync::atomic::Ordering::SeqCst);
        }
    }
}

impl AsRef<usize> for Depth {
    #[inline(always)]
    fn as_ref(&self) -> &usize {
        &self.depth
    }
}

impl crate::lib::std::ops::Deref for Depth {
    type Target = usize;

    #[inline(always)]
    fn deref(&self) -> &Self::Target {
        &self.depth
    }
}

static DEPTH: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);

pub enum Severity {
    Success,
    Backtrack,
    Cut,
    Incomplete,
}

impl Severity {
    pub fn with_result<T, E>(result: &Result<T, ErrMode<E>>) -> Self {
        match result {
            Ok(_) => Self::Success,
            Err(ErrMode::Backtrack(_)) => Self::Backtrack,
            Err(ErrMode::Cut(_)) => Self::Cut,
            Err(ErrMode::Incomplete(_)) => Self::Incomplete,
        }
    }
}

pub fn start<I: Stream>(
    depth: usize,
    name: &dyn crate::lib::std::fmt::Display,
    count: usize,
    input: &I,
) {
    let gutter_style = anstyle::Style::new().bold();
    let input_style = anstyle::Style::new().underline();
    let eof_style = anstyle::Style::new().fg_color(Some(anstyle::AnsiColor::Cyan.into()));

    let (call_width, input_width) = column_widths();

    let count = if 0 < count {
        format!(":{count}")
    } else {
        "".to_owned()
    };
    let call_column = format!("{:depth$}> {name}{count}", "");

    // The debug version of `slice` might be wider, either due to rendering one byte as two nibbles or
    // escaping in strings.
    let mut debug_slice = format!("{:#?}", input.raw());
    let (debug_slice, eof) = if let Some(debug_offset) = debug_slice
        .char_indices()
        .enumerate()
        .find_map(|(pos, (offset, _))| (input_width <= pos).then_some(offset))
    {
        debug_slice.truncate(debug_offset);
        let eof = "";
        (debug_slice, eof)
    } else {
        let eof = if debug_slice.chars().count() < input_width {
            "∅"
        } else {
            ""
        };
        (debug_slice, eof)
    };

    let writer = anstream::stderr();
    let mut writer = writer.lock();
    let _ = writeln!(
        writer,
        "{call_column:call_width$} {gutter_style}|{gutter_reset} {input_style}{debug_slice}{input_reset}{eof_style}{eof}{eof_reset}",
        gutter_style=gutter_style.render(),
        gutter_reset=gutter_style.render_reset(),
        input_style=input_style.render(),
        input_reset=input_style.render_reset(),
        eof_style=eof_style.render(),
        eof_reset=eof_style.render_reset(),
    );
}

pub fn end(
    depth: usize,
    name: &dyn crate::lib::std::fmt::Display,
    count: usize,
    consumed: usize,
    severity: Severity,
) {
    let gutter_style = anstyle::Style::new().bold();

    let (call_width, _) = column_widths();

    let count = if 0 < count {
        format!(":{count}")
    } else {
        "".to_owned()
    };
    let call_column = format!("{:depth$}< {name}{count}", "");

    let (status_style, status) = match severity {
        Severity::Success => {
            let style = anstyle::Style::new().fg_color(Some(anstyle::AnsiColor::Green.into()));
            let status = format!("+{}", consumed);
            (style, status)
        }
        Severity::Backtrack => (
            anstyle::Style::new().fg_color(Some(anstyle::AnsiColor::Yellow.into())),
            "backtrack".to_owned(),
        ),
        Severity::Cut => (
            anstyle::Style::new().fg_color(Some(anstyle::AnsiColor::Red.into())),
            "cut".to_owned(),
        ),
        Severity::Incomplete => (
            anstyle::Style::new().fg_color(Some(anstyle::AnsiColor::Red.into())),
            "incomplete".to_owned(),
        ),
    };

    let writer = anstream::stderr();
    let mut writer = writer.lock();
    let _ = writeln!(
        writer,
        "{status_style}{call_column:call_width$}{status_reset} {gutter_style}|{gutter_reset} {status_style}{status}{status_reset}",
        gutter_style=gutter_style.render(),
        gutter_reset=gutter_style.render_reset(),
        status_style=status_style.render(),
        status_reset=status_style.render_reset(),
    );
}

pub fn result(depth: usize, name: &dyn crate::lib::std::fmt::Display, severity: Severity) {
    let gutter_style = anstyle::Style::new().bold();

    let (call_width, _) = column_widths();

    let call_column = format!("{:depth$}| {name}", "");

    let (status_style, status) = match severity {
        Severity::Success => (
            anstyle::Style::new().fg_color(Some(anstyle::AnsiColor::Green.into())),
            "",
        ),
        Severity::Backtrack => (
            anstyle::Style::new().fg_color(Some(anstyle::AnsiColor::Yellow.into())),
            "backtrack",
        ),
        Severity::Cut => (
            anstyle::Style::new().fg_color(Some(anstyle::AnsiColor::Red.into())),
            "cut",
        ),
        Severity::Incomplete => (
            anstyle::Style::new().fg_color(Some(anstyle::AnsiColor::Red.into())),
            "incomplete",
        ),
    };

    let writer = anstream::stderr();
    let mut writer = writer.lock();
    let _ = writeln!(
        writer,
        "{status_style}{call_column:call_width$}{status_reset} {gutter_style}|{gutter_reset} {status_style}{status}{status_reset}",
        gutter_style=gutter_style.render(),
        gutter_reset=gutter_style.render_reset(),
        status_style=status_style.render(),
        status_reset=status_style.render_reset(),
    );
}

fn column_widths() -> (usize, usize) {
    let term_width = term_width();

    let min_call_width = 40;
    let min_input_width = 20;
    let decor_width = 3;
    let extra_width = term_width
        .checked_sub(min_call_width + min_input_width + decor_width)
        .unwrap_or_default();
    let call_width = min_call_width + 2 * extra_width / 3;
    let input_width = min_input_width + extra_width / 3;

    (call_width, input_width)
}

fn term_width() -> usize {
    columns_env().or_else(query_width).unwrap_or(80)
}

fn query_width() -> Option<usize> {
    use is_terminal::IsTerminal;
    if std::io::stderr().is_terminal() {
        terminal_size::terminal_size().map(|(w, _h)| w.0.into())
    } else {
        None
    }
}

fn columns_env() -> Option<usize> {
    std::env::var("COLUMNS")
        .ok()
        .and_then(|c| c.parse::<usize>().ok())
}