|
1 |
| -use emmylua_parser::{LuaAst, LuaAstNode}; |
| 1 | +mod syntax_node_change; |
| 2 | + |
| 3 | +use std::collections::HashMap; |
| 4 | + |
| 5 | +use emmylua_parser::{LuaAst, LuaAstNode, LuaSyntaxId}; |
2 | 6 | use rowan::NodeOrToken;
|
3 | 7 |
|
| 8 | +use crate::format::syntax_node_change::TokenNodeChange; |
| 9 | + |
4 | 10 | #[allow(unused)]
|
5 | 11 | #[derive(Debug)]
|
6 | 12 | pub struct LuaFormatter {
|
7 | 13 | root: LuaAst,
|
| 14 | + token_changes: HashMap<LuaSyntaxId, TokenNodeChange>, |
8 | 15 | }
|
9 | 16 |
|
10 | 17 | #[allow(unused)]
|
11 | 18 | impl LuaFormatter {
|
12 | 19 | pub fn new(root: LuaAst) -> Self {
|
13 |
| - Self { root } |
| 20 | + Self { |
| 21 | + root, |
| 22 | + token_changes: HashMap::new(), |
| 23 | + } |
| 24 | + } |
| 25 | + |
| 26 | + pub fn add_token_change(&mut self, syntax_id: LuaSyntaxId, change: TokenNodeChange) { |
| 27 | + self.token_changes.insert(syntax_id, change); |
| 28 | + } |
| 29 | + |
| 30 | + pub fn get_token_change(&self, syntax_id: &LuaSyntaxId) -> Option<&TokenNodeChange> { |
| 31 | + self.token_changes.get(syntax_id) |
14 | 32 | }
|
15 | 33 |
|
16 | 34 | pub fn get_formatted_text(&self) -> String {
|
17 | 35 | let mut formatted_text = String::new();
|
18 | 36 | for node_or_token in self.root.syntax().descendants_with_tokens() {
|
19 | 37 | if let NodeOrToken::Token(token) = node_or_token {
|
20 |
| - formatted_text.push_str(&token.text()); |
| 38 | + let syntax_id = LuaSyntaxId::from_token(&token); |
| 39 | + if let Some(change) = self.token_changes.get(&syntax_id) { |
| 40 | + match change { |
| 41 | + TokenNodeChange::Remove => continue, |
| 42 | + TokenNodeChange::AddLeft(s) => { |
| 43 | + formatted_text.push_str(s); |
| 44 | + formatted_text.push_str(&token.text()); |
| 45 | + } |
| 46 | + TokenNodeChange::AddRight(s) => { |
| 47 | + formatted_text.push_str(&token.text()); |
| 48 | + formatted_text.push_str(s); |
| 49 | + } |
| 50 | + TokenNodeChange::ReplaceWith(s) => { |
| 51 | + formatted_text.push_str(s); |
| 52 | + } |
| 53 | + } |
| 54 | + } else { |
| 55 | + formatted_text.push_str(&token.text()); |
| 56 | + } |
21 | 57 | }
|
22 | 58 | }
|
23 | 59 |
|
|
0 commit comments