traitDebug Implement the std::fmt::Debug trait.

- Based on the Display trait, but includes whitespace.
- The format of each line is slightly different, with `@line:123`
  appearing before the token's string.
  - This is to reduce the chances of grep-based tools getting confused.
  - This also makes it easier to display whitespace/comments.
- No additional testcases are added, same as Display.
- Tested via local build in svlint development.
This commit is contained in:
damc 2022-11-08 18:03:48 +01:00
parent 6c28a6157d
commit a9302e7f90

View File

@ -114,6 +114,63 @@ impl fmt::Display for SyntaxTree {
}
}
impl fmt::Debug for SyntaxTree {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
enum WS {
NotWhitespace,
Newline,
Space,
Comment,
CompilerDirective,
}
let mut ws: WS = WS::NotWhitespace;
let mut depth = 0;
let mut ret = String::from("");
for node in self.into_iter().event() {
match node {
NodeEvent::Enter(RefNode::Locate(locate)) => {
let (pre, t, post) = match ws {
WS::Newline => ("<<<<<", "NewlineToken", ">>>>>"),
WS::Space => ("<<<<<", "SpaceToken", ">>>>>"),
WS::Comment => ("<<<<<", "CommentToken", ">>>>>"),
_ => ("", "Token", ""),
};
ret.push_str(&format!(
"{}{} @line:{}: {}{}{}\n",
" ".repeat(depth),
t,
locate.line,
pre,
self.get_str(locate).unwrap(),
post,
));
depth += 1;
}
NodeEvent::Enter(x) => {
match x {
RefNode::WhiteSpace(WhiteSpace::Newline(_)) => { ws = WS::Newline; }
RefNode::WhiteSpace(WhiteSpace::Space(_)) => { ws = WS::Space; }
RefNode::WhiteSpace(WhiteSpace::Comment(_)) => { ws = WS::Comment; }
RefNode::WhiteSpace(WhiteSpace::CompilerDirective(_)) => { ws = WS::CompilerDirective; }
_ => {}
}
ret.push_str(&format!("{}{}\n", " ".repeat(depth), x));
depth += 1;
}
NodeEvent::Leave(x) => {
match x {
RefNode::WhiteSpace(_) => {}
_ => { ws = WS::NotWhitespace; }
}
depth -= 1;
}
}
}
write!(f, "{}", ret)
}
}
impl<'a> IntoIterator for &'a SyntaxTree {
type Item = RefNode<'a>;
type IntoIter = Iter<'a>;