syntree/print.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
//! Helper utilities for pretty-printing trees.
#![cfg(feature = "std")]
#![cfg_attr(docsrs, doc(cfg(feature = "std")))]
use std::fmt;
use std::io::{Error, Write};
use crate::flavor::Flavor;
use crate::span::Span;
use crate::tree::Tree;
/// Pretty-print a tree without a source.
///
/// This will replace all source references with `+`. If you have a source
/// available you can use [`print_with_source`] instead.
///
/// # Examples
///
/// ```
/// #[derive(Debug, Clone, Copy)]
/// enum Syntax {
/// NUMBER,
/// WHITESPACE,
/// OPERATOR,
/// PLUS,
/// }
///
/// use Syntax::*;
///
/// let tree = syntree::tree! {
/// NUMBER => {
/// (NUMBER, 3),
/// },
/// (WHITESPACE, 1),
/// OPERATOR => {
/// (PLUS, 1)
/// },
/// (WHITESPACE, 1),
/// NUMBER => {
/// (NUMBER, 2),
/// },
/// };
///
/// let mut s = Vec::new();
/// syntree::print::print(&mut s, &tree)?;
/// # let s = String::from_utf8(s)?;
/// # assert_eq!(s, "NUMBER@0..3\n NUMBER@0..3 +\nWHITESPACE@3..4 +\nOPERATOR@4..5\n PLUS@4..5 +\nWHITESPACE@5..6 +\nNUMBER@6..8\n NUMBER@6..8 +\n");
/// # Ok::<_, Box<dyn core::error::Error>>(())
/// ```
///
/// This would write:
///
/// ```text
/// NUMBER@0..3
/// NUMBER@0..3 +
/// WHITESPACE@3..4 +
/// OPERATOR@4..5
/// PLUS@4..5 +
/// WHITESPACE@5..6 +
/// NUMBER@6..8
/// NUMBER@6..8 +
/// ```
pub fn print<O, T, F>(o: O, tree: &Tree<T, F>) -> Result<(), Error>
where
O: Write,
T: Copy + fmt::Debug,
F: Flavor<Index: fmt::Display>,
{
print_with_lookup(o, tree, |_| None)
}
/// Pretty-print a tree with the source spans printed.
///
/// # Examples
///
/// ```
/// #[derive(Debug, Clone, Copy)]
/// enum Syntax {
/// NUMBER,
/// WHITESPACE,
/// OPERATOR,
/// PLUS,
/// }
///
/// use Syntax::*;
///
/// let source = "128 + 64";
///
/// let tree = syntree::tree! {
/// NUMBER => {
/// (NUMBER, 3),
/// },
/// (WHITESPACE, 1),
/// OPERATOR => {
/// (PLUS, 1)
/// },
/// (WHITESPACE, 1),
/// NUMBER => {
/// (NUMBER, 2),
/// },
/// };
///
/// let mut s = Vec::new();
/// syntree::print::print_with_source(&mut s, &tree, source)?;
/// # let s = String::from_utf8(s)?;
/// # assert_eq!(s, "NUMBER@0..3\n NUMBER@0..3 \"128\"\nWHITESPACE@3..4 \" \"\nOPERATOR@4..5\n PLUS@4..5 \"+\"\nWHITESPACE@5..6 \" \"\nNUMBER@6..8\n NUMBER@6..8 \"64\"\n");
/// # Ok::<_, Box<dyn core::error::Error>>(())
/// ```
///
/// This would write:
///
/// ```text
/// NUMBER@0..3
/// NUMBER@0..3 "128"
/// WHITESPACE@3..4 " "
/// OPERATOR@4..5
/// PLUS@4..5 "+"
/// WHITESPACE@5..6 " "
/// NUMBER@6..8
/// NUMBER@6..8 "64"
/// ```
pub fn print_with_source<O, T, F>(o: O, tree: &Tree<T, F>, source: &str) -> Result<(), Error>
where
O: Write,
T: Copy + fmt::Debug,
F: Flavor<Index: fmt::Display>,
{
print_with_lookup(o, tree, |span| source.get(span.range()))
}
fn print_with_lookup<'a, O, T, F>(
mut o: O,
tree: &Tree<T, F>,
source: impl Fn(&Span<F::Index>) -> Option<&'a str>,
) -> Result<(), Error>
where
O: Write,
T: Copy + fmt::Debug,
F: Flavor<Index: fmt::Display>,
{
for (depth, node) in tree.walk().with_depths() {
let n = (depth * 2) as usize;
let data = node.value();
let span = node.span();
if node.has_children() {
writeln!(o, "{:n$}{:?}@{}", "", data, span)?;
} else if let Some(source) = source(span) {
writeln!(o, "{:n$}{:?}@{} {:?}", "", data, span, source)?;
} else {
writeln!(o, "{:n$}{:?}@{} +", "", data, span)?;
}
}
Ok(())
}