|
7 | 7 | // option. All files in the project carrying such notice may not be copied, |
8 | 8 | // modified, or distributed except according to those terms. |
9 | 9 |
|
| 10 | +use alloc::format; |
10 | 11 | use alloc::rc::Rc; |
11 | 12 | #[cfg(feature = "pretty-print")] |
12 | 13 | use alloc::string::String; |
@@ -339,7 +340,30 @@ impl<R: RuleType> fmt::Debug for Pair<'_, R> { |
339 | 340 |
|
340 | 341 | impl<R: RuleType> fmt::Display for Pair<'_, R> { |
341 | 342 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
342 | | - write!(f, "{}", self.as_str()) |
| 343 | + if f.alternate() { |
| 344 | + let rule = self.as_rule(); |
| 345 | + let start = self.pos(self.start); |
| 346 | + let end = self.pos(self.pair()); |
| 347 | + let mut pairs = self.clone().into_inner().peekable(); |
| 348 | + |
| 349 | + if pairs.peek().is_none() { |
| 350 | + write!(f, "{:?}({}, {})", rule, start, end) |
| 351 | + } else { |
| 352 | + write!( |
| 353 | + f, |
| 354 | + "{:?}({}, {}, [{}])", |
| 355 | + rule, |
| 356 | + start, |
| 357 | + end, |
| 358 | + pairs |
| 359 | + .map(|pair| format!("{:#}", pair)) |
| 360 | + .collect::<Vec<_>>() |
| 361 | + .join(", ") |
| 362 | + ) |
| 363 | + } |
| 364 | + } else { |
| 365 | + write!(f, "{}", self.as_str()) |
| 366 | + } |
343 | 367 | } |
344 | 368 | } |
345 | 369 |
|
@@ -388,7 +412,7 @@ impl<R: RuleType> ::serde::Serialize for Pair<'_, R> { |
388 | 412 |
|
389 | 413 | #[cfg(test)] |
390 | 414 | mod tests { |
391 | | - use crate::alloc::string::ToString; |
| 415 | + use crate::alloc::{borrow::ToOwned, format, string::ToString}; |
392 | 416 | use crate::macros::tests::*; |
393 | 417 | use crate::parser::Parser; |
394 | 418 |
|
@@ -446,4 +470,10 @@ mod tests { |
446 | 470 |
|
447 | 471 | assert_eq!(pair.to_string(), pair.as_str().to_string()); |
448 | 472 | } |
| 473 | + #[test] |
| 474 | + fn alternate_format() { |
| 475 | + let pair = AbcParser::parse(Rule::a, "abcde").unwrap().next().unwrap(); |
| 476 | + assert_eq!(format!("{}", pair), "abc".to_owned()); |
| 477 | + assert_eq!(format!("{:#}", pair), "a(0, 3, [b(1, 2)])".to_owned()); |
| 478 | + } |
449 | 479 | } |
0 commit comments