/
token_list.rs
57 lines (48 loc) · 1.46 KB
/
token_list.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
use lib_ruby_parser::Token;
pub(crate) struct TokenList {
pub(crate) tokens: Vec<Token>,
}
fn token_value(token: &Token) -> String {
token.to_string_lossy()
}
impl TokenList {
fn tok_name_length(&self) -> usize {
self.tokens
.iter()
.map(|tok| format!("{:?}", tok.token_name()).len())
.max()
.unwrap_or(0)
+ 2
}
fn tok_value_length(&self) -> usize {
self.tokens
.iter()
.map(|tok| format!("{:?}", token_value(tok)).len())
.max()
.unwrap_or(0)
+ 2
}
}
fn rpad<T: Sized + std::fmt::Debug>(value: &T, total_width: usize) -> String {
format!("{:width$}", format!("{:?}, ", value), width = total_width)
}
impl std::fmt::Debug for TokenList {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let tok_name_length = self.tok_name_length();
let tok_value_length = self.tok_value_length();
let tokens = self
.tokens
.iter()
.map(|token| {
let name = rpad(&token.token_name(), tok_name_length);
let value = rpad(&token_value(token), tok_value_length);
format!(
" :{}{}[{}, {}]",
name, value, token.loc.begin, token.loc.end,
)
})
.collect::<Vec<_>>()
.join("\n");
write!(f, "[\n{}\n]", tokens)
}
}