Debian Codegraph @

debian/rust-vendor/winnow/src/combinator/debug/internals.rs

raw
1 #![cfg(feature = "std")]
2
3 use std::io::Write;
4
5 use crate::error::ParserError;
6 use crate::stream::Stream;
7 use crate::{Parser, Result};
8
9 pub(crate) struct Trace<P, D, I, O, E>
10 where
11 P: Parser<I, O, E>,
12 I: Stream,
13 D: std::fmt::Display,
14 E: ParserError<I>,
15 {
16 parser: P,
17 name: D,
18 call_count: usize,
19 marker: core::marker::PhantomData<(I, O, E)>,
20 }
21
22 impl<P, D, I, O, E> Trace<P, D, I, O, E>
23 where
24 P: Parser<I, O, E>,
25 I: Stream,
26 D: std::fmt::Display,
27 E: ParserError<I>,
28 {
29 #[inline(always)]
30 pub(crate) fn new(parser: P, name: D) -> Self {
31 Self {
32 parser,
33 name,
34 call_count: 0,
35 marker: Default::default(),
36 }
37 }
38 }
39
40 impl<P, D, I, O, E> Parser<I, O, E> for Trace<P, D, I, O, E>
41 where
42 P: Parser<I, O, E>,
43 I: Stream,
44 D: std::fmt::Display,
45 E: ParserError<I>,
46 {
47 #[inline]
48 fn parse_next(&mut self, i: &mut I) -> Result<O, E> {
49 let depth = Depth::new();
50 let original = i.checkpoint();
51 start(*depth, &self.name, self.call_count, i);
52
53 let res = self.parser.parse_next(i);
54
55 let consumed = i.offset_from(&original);
56 let severity = Severity::with_result(&res);
57 end(*depth, &self.name, self.call_count, consumed, severity);
58 self.call_count += 1;
59
60 res
61 }
62 }
63
64 pub(crate) struct Depth {
65 depth: usize,
66 inc: bool,
67 }
68
69 impl Depth {
70 pub(crate) fn new() -> Self {
71 let depth = DEPTH.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
72 let inc = true;
73 Self { depth, inc }
74 }
75
76 pub(crate) fn existing() -> Self {
77 let depth = DEPTH.load(std::sync::atomic::Ordering::SeqCst);
78 let inc = false;
79 Self { depth, inc }
80 }
81 }
82
83 impl Drop for Depth {
84 fn drop(&mut self) {
85 if self.inc {
86 let _ = DEPTH.fetch_sub(1, std::sync::atomic::Ordering::SeqCst);
87 }
88 }
89 }
90
91 impl AsRef<usize> for Depth {
92 #[inline(always)]
93 fn as_ref(&self) -> &usize {
94 &self.depth
95 }
96 }
97
98 impl core::ops::Deref for Depth {
99 type Target = usize;
100
101 #[inline(always)]
102 fn deref(&self) -> &Self::Target {
103 &self.depth
104 }
105 }
106
107 static DEPTH: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
108
109 pub(crate) enum Severity {
110 Success,
111 Backtrack,
112 Cut,
113 Incomplete,
114 }
115
116 impl Severity {
117 pub(crate) fn with_result<T, I: Stream, E: ParserError<I>>(result: &Result<T, E>) -> Self {
118 match result {
119 Ok(_) => Self::Success,
120 Err(e) if e.is_backtrack() => Self::Backtrack,
121 Err(e) if e.is_incomplete() => Self::Incomplete,
122 _ => Self::Cut,
123 }
124 }
125 }
126
127 pub(crate) fn start<I: Stream>(
128 depth: usize,
129 name: &dyn core::fmt::Display,
130 count: usize,
131 input: &I,
132 ) {
133 let gutter_style = anstyle::Style::new().bold();
134 let input_style = anstyle::Style::new().underline();
135 let eof_style = anstyle::Style::new().fg_color(Some(anstyle::AnsiColor::Cyan.into()));
136
137 let (call_width, input_width) = column_widths();
138
139 let count = if 0 < count {
140 format!(":{count}")
141 } else {
142 "".to_owned()
143 };
144 let call_column = format!("{:depth$}> {name}{count}", "");
145
146 // The debug version of `slice` might be wider, either due to rendering one byte as two nibbles or
147 // escaping in strings.
148 let mut debug_slice = format!("{:?}", crate::util::from_fn(|f| input.trace(f)));
149 let (debug_slice, eof) = if let Some(debug_offset) = debug_slice
150 .char_indices()
151 .enumerate()
152 .find_map(|(pos, (offset, _))| (input_width <= pos).then_some(offset))
153 {
154 debug_slice.truncate(debug_offset);
155 let eof = "";
156 (debug_slice, eof)
157 } else {
158 let eof = if debug_slice.chars().count() < input_width {
159 "∅"
160 } else {
161 ""
162 };
163 (debug_slice, eof)
164 };
165
166 let writer = anstream::stderr();
167 let mut writer = writer.lock();
168 let _ = writeln!(
169 writer,
170 "{call_column:call_width$} {gutter_style}|{gutter_reset} {input_style}{debug_slice}{input_reset}{eof_style}{eof}{eof_reset}",
171 gutter_style=gutter_style.render(),
172 gutter_reset=gutter_style.render_reset(),
173 input_style=input_style.render(),
174 input_reset=input_style.render_reset(),
175 eof_style=eof_style.render(),
176 eof_reset=eof_style.render_reset(),
177 );
178 }
179
180 pub(crate) fn end(
181 depth: usize,
182 name: &dyn core::fmt::Display,
183 count: usize,
184 consumed: usize,
185 severity: Severity,
186 ) {
187 let gutter_style = anstyle::Style::new().bold();
188
189 let (call_width, _) = column_widths();
190
191 let count = if 0 < count {
192 format!(":{count}")
193 } else {
194 "".to_owned()
195 };
196 let call_column = format!("{:depth$}< {name}{count}", "");
197
198 let (status_style, status) = match severity {
199 Severity::Success => {
200 let style = anstyle::Style::new().fg_color(Some(anstyle::AnsiColor::Green.into()));
201 let status = format!("+{consumed}");
202 (style, status)
203 }
204 Severity::Backtrack => (
205 anstyle::Style::new().fg_color(Some(anstyle::AnsiColor::Yellow.into())),
206 "backtrack".to_owned(),
207 ),
208 Severity::Cut => (
209 anstyle::Style::new().fg_color(Some(anstyle::AnsiColor::Red.into())),
210 "cut".to_owned(),
211 ),
212 Severity::Incomplete => (
213 anstyle::Style::new().fg_color(Some(anstyle::AnsiColor::Red.into())),
214 "incomplete".to_owned(),
215 ),
216 };
217
218 let writer = anstream::stderr();
219 let mut writer = writer.lock();
220 let _ = writeln!(
221 writer,
222 "{status_style}{call_column:call_width$}{status_reset} {gutter_style}|{gutter_reset} {status_style}{status}{status_reset}",
223 gutter_style=gutter_style.render(),
224 gutter_reset=gutter_style.render_reset(),
225 status_style=status_style.render(),
226 status_reset=status_style.render_reset(),
227 );
228 }
229
230 pub(crate) fn result(depth: usize, name: &dyn core::fmt::Display, severity: Severity) {
231 let gutter_style = anstyle::Style::new().bold();
232
233 let (call_width, _) = column_widths();
234
235 let call_column = format!("{:depth$}| {name}", "");
236
237 let (status_style, status) = match severity {
238 Severity::Success => (
239 anstyle::Style::new().fg_color(Some(anstyle::AnsiColor::Green.into())),
240 "",
241 ),
242 Severity::Backtrack => (
243 anstyle::Style::new().fg_color(Some(anstyle::AnsiColor::Yellow.into())),
244 "backtrack",
245 ),
246 Severity::Cut => (
247 anstyle::Style::new().fg_color(Some(anstyle::AnsiColor::Red.into())),
248 "cut",
249 ),
250 Severity::Incomplete => (
251 anstyle::Style::new().fg_color(Some(anstyle::AnsiColor::Red.into())),
252 "incomplete",
253 ),
254 };
255
256 let writer = anstream::stderr();
257 let mut writer = writer.lock();
258 let _ = writeln!(
259 writer,
260 "{status_style}{call_column:call_width$}{status_reset} {gutter_style}|{gutter_reset} {status_style}{status}{status_reset}",
261 gutter_style=gutter_style.render(),
262 gutter_reset=gutter_style.render_reset(),
263 status_style=status_style.render(),
264 status_reset=status_style.render_reset(),
265 );
266 }
267
268 fn column_widths() -> (usize, usize) {
269 let term_width = term_width();
270
271 let min_call_width = 40;
272 let min_input_width = 20;
273 let decor_width = 3;
274 let extra_width = term_width.saturating_sub(min_call_width + min_input_width + decor_width);
275 let call_width = min_call_width + 2 * extra_width / 3;
276 let input_width = min_input_width + extra_width / 3;
277
278 (call_width, input_width)
279 }
280
281 fn term_width() -> usize {
282 columns_env().or_else(query_width).unwrap_or(80)
283 }
284
285 fn query_width() -> Option<usize> {
286 use is_terminal_polyfill::IsTerminal;
287 if std::io::stderr().is_terminal() {
288 terminal_size::terminal_size().map(|(w, _h)| w.0.into())
289 } else {
290 None
291 }
292 }
293
294 fn columns_env() -> Option<usize> {
295 std::env::var("COLUMNS")
296 .ok()
297 .and_then(|c| c.parse::<usize>().ok())
298 }