1use std::cmp;
2use std::collections::HashMap;
3
4use crate::lexer::token::Token;
5use crate::lexer::token::TokenKind;
6
7pub fn print(tokens: &[Token]) -> String {
31 let mut lines: HashMap<usize, Vec<&Token>> = HashMap::new();
32 let mut max_line = 0;
33
34 for token in tokens {
35 lines.entry(token.span.line).or_default().push(token);
36 max_line = cmp::max(max_line, token.span.line);
37 }
38
39 let mut output = vec![];
40 let mut last = 0;
41
42 for line in 1..=max_line {
43 if line < last {
44 continue;
45 }
46
47 last = line;
48 let representation = match lines.get(&line) {
49 Some(tokens) => {
50 let mut representation = "".to_owned();
51
52 for token in tokens {
53 if token.kind == TokenKind::Eof {
54 break;
55 }
56
57 let repeat = token.span.column - representation.len() - 1;
58
59 representation.push_str(&" ".repeat(repeat));
60 representation.push_str(&token.value.to_string());
61 }
62
63 let mut result = vec![];
64 let lines = representation.lines();
65 last += lines.clone().count();
66 for line in lines {
67 result.push(line);
68 }
69
70 result.join("\n")
71 }
72 None => "".to_owned(),
73 };
74
75 output.push(representation);
76 }
77
78 output.join("\n")
79}