Skip to content

Commit 903a8c6

Browse files
committed
feat: print fixed tokens regardless of span
stuff like punctuation doesn't need to have a valid span to know what should be printed. this makes it cheaper to build arbitrary cst's without needing to allocate string space for known grammar symbols
1 parent fa07e41 commit 903a8c6

File tree

2 files changed

+47
-1
lines changed

2 files changed

+47
-1
lines changed

crates/ltk_ritobin/src/parse/tokenizer.rs

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,35 @@ impl TokenKind {
2727
pub fn is_string(&self) -> bool {
2828
matches!(self, Self::String | Self::UnterminatedString)
2929
}
30+
31+
pub fn print_value(&self) -> Option<&'static str> {
32+
match self {
33+
TokenKind::Unknown => None,
34+
TokenKind::Eof => None,
35+
TokenKind::Newline => None,
36+
TokenKind::LParen => Some("("),
37+
TokenKind::RParen => Some(")"),
38+
TokenKind::LCurly => Some("{"),
39+
TokenKind::RCurly => Some("}"),
40+
TokenKind::LBrack => Some("["),
41+
TokenKind::RBrack => Some("]"),
42+
TokenKind::Eq => Some("="),
43+
TokenKind::Comma => Some(","),
44+
TokenKind::Colon => Some(":"),
45+
TokenKind::SemiColon => Some(";"),
46+
TokenKind::Star => Some("*"),
47+
TokenKind::Slash => Some("/"),
48+
TokenKind::Quote => Some("\""),
49+
TokenKind::String => None,
50+
TokenKind::UnterminatedString => None,
51+
TokenKind::Comment => None,
52+
TokenKind::True => Some("true"),
53+
TokenKind::False => Some("false"),
54+
TokenKind::Name => None,
55+
TokenKind::Number => None,
56+
TokenKind::HexLit => None,
57+
}
58+
}
3059
}
3160

3261
impl Display for TokenKind {

crates/ltk_ritobin/src/print/visitor.rs

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -378,8 +378,9 @@ impl<'a, W: Write> Printer<'a, W> {
378378
context: &Cst,
379379
) -> Result<(), PrintError> {
380380
let txt = self.src[token.span].trim();
381+
let print_value = token.kind.print_value();
381382

382-
if txt.is_empty() {
383+
if txt.is_empty() && print_value.is_none() {
383384
return Ok(());
384385
}
385386

@@ -414,6 +415,22 @@ impl<'a, W: Write> Printer<'a, W> {
414415
self.space();
415416
}
416417

418+
TokenKind::LBrack => {
419+
self.text("[");
420+
}
421+
TokenKind::RBrack => {
422+
self.text("]");
423+
}
424+
TokenKind::Quote => {
425+
self.text("\"");
426+
}
427+
TokenKind::False => {
428+
self.text("false");
429+
}
430+
TokenKind::True => {
431+
self.text("true");
432+
}
433+
417434
_ => {
418435
self.text(txt);
419436
}

0 commit comments

Comments
 (0)