darklua_core/rules/
remove_spaces.rs

1use crate::nodes::*;
2use crate::process::{DefaultVisitor, NodeProcessor, NodeVisitor};
3use crate::rules::{
4    Context, FlawlessRule, RuleConfiguration, RuleConfigurationError, RuleProperties,
5};
6
7use super::verify_no_rule_properties;
8
9#[derive(Debug, Default)]
10pub(crate) struct RemoveWhitespacesProcessor {}
11
12impl NodeProcessor for RemoveWhitespacesProcessor {
13    fn process_block(&mut self, block: &mut Block) {
14        block.clear_whitespaces();
15    }
16
17    fn process_function_call(&mut self, call: &mut FunctionCall) {
18        call.clear_whitespaces();
19        call.mutate_arguments().clear_whitespaces();
20    }
21
22    fn process_assign_statement(&mut self, assign: &mut AssignStatement) {
23        assign.clear_whitespaces();
24    }
25
26    fn process_compound_assign_statement(&mut self, assign: &mut CompoundAssignStatement) {
27        assign.clear_whitespaces();
28    }
29
30    fn process_do_statement(&mut self, statement: &mut DoStatement) {
31        statement.clear_whitespaces();
32    }
33
34    fn process_function_statement(&mut self, function: &mut FunctionStatement) {
35        function.clear_whitespaces();
36    }
37
38    fn process_generic_for_statement(&mut self, generic_for: &mut GenericForStatement) {
39        generic_for.clear_whitespaces();
40    }
41
42    fn process_if_statement(&mut self, if_statement: &mut IfStatement) {
43        if_statement.clear_whitespaces();
44    }
45
46    fn process_last_statement(&mut self, statement: &mut LastStatement) {
47        match statement {
48            LastStatement::Break(token) | LastStatement::Continue(token) => {
49                if let Some(token) = token {
50                    token.clear_whitespaces();
51                }
52            }
53            LastStatement::Return(statement) => statement.clear_whitespaces(),
54        }
55    }
56
57    fn process_local_assign_statement(&mut self, assign: &mut LocalAssignStatement) {
58        assign.clear_whitespaces();
59    }
60
61    fn process_local_function_statement(&mut self, function: &mut LocalFunctionStatement) {
62        function.clear_whitespaces();
63    }
64
65    fn process_numeric_for_statement(&mut self, numeric_for: &mut NumericForStatement) {
66        numeric_for.clear_whitespaces();
67    }
68
69    fn process_repeat_statement(&mut self, repeat: &mut RepeatStatement) {
70        repeat.clear_whitespaces();
71    }
72
73    fn process_while_statement(&mut self, statement: &mut WhileStatement) {
74        statement.clear_whitespaces();
75    }
76
77    fn process_type_declaration(&mut self, type_declaration: &mut TypeDeclarationStatement) {
78        type_declaration.clear_whitespaces();
79    }
80
81    fn process_expression(&mut self, expression: &mut Expression) {
82        match expression {
83            Expression::False(token)
84            | Expression::Nil(token)
85            | Expression::True(token)
86            | Expression::VariableArguments(token) => {
87                if let Some(token) = token {
88                    token.clear_whitespaces()
89                }
90            }
91            Expression::Binary(_)
92            | Expression::Call(_)
93            | Expression::Field(_)
94            | Expression::Function(_)
95            | Expression::Identifier(_)
96            | Expression::If(_)
97            | Expression::Index(_)
98            | Expression::Number(_)
99            | Expression::Parenthese(_)
100            | Expression::String(_)
101            | Expression::InterpolatedString(_)
102            | Expression::Table(_)
103            | Expression::Unary(_)
104            | Expression::TypeCast(_) => {}
105        }
106    }
107
108    fn process_binary_expression(&mut self, binary: &mut BinaryExpression) {
109        binary.clear_whitespaces();
110    }
111
112    fn process_field_expression(&mut self, field: &mut FieldExpression) {
113        field.clear_whitespaces();
114    }
115
116    fn process_function_expression(&mut self, function: &mut FunctionExpression) {
117        function.clear_whitespaces();
118    }
119
120    fn process_if_expression(&mut self, if_expression: &mut IfExpression) {
121        if_expression.clear_whitespaces();
122    }
123
124    fn process_variable_expression(&mut self, identifier: &mut Identifier) {
125        identifier.clear_whitespaces();
126    }
127
128    fn process_index_expression(&mut self, index: &mut IndexExpression) {
129        index.clear_whitespaces();
130    }
131
132    fn process_number_expression(&mut self, number: &mut NumberExpression) {
133        number.clear_whitespaces();
134    }
135
136    fn process_parenthese_expression(&mut self, expression: &mut ParentheseExpression) {
137        expression.clear_whitespaces();
138    }
139
140    fn process_string_expression(&mut self, string: &mut StringExpression) {
141        string.clear_whitespaces();
142    }
143
144    fn process_table_expression(&mut self, table: &mut TableExpression) {
145        table.clear_whitespaces();
146    }
147
148    fn process_unary_expression(&mut self, unary: &mut UnaryExpression) {
149        unary.clear_whitespaces();
150    }
151
152    fn process_interpolated_string_expression(
153        &mut self,
154        string: &mut InterpolatedStringExpression,
155    ) {
156        string.clear_whitespaces();
157    }
158
159    fn process_type_cast_expression(&mut self, type_cast: &mut TypeCastExpression) {
160        type_cast.clear_whitespaces();
161    }
162
163    fn process_prefix_expression(&mut self, _: &mut Prefix) {}
164
165    fn process_type(&mut self, r#type: &mut Type) {
166        match r#type {
167            Type::True(token) | Type::False(token) | Type::Nil(token) => {
168                if let Some(token) = token {
169                    token.clear_whitespaces();
170                }
171            }
172            _ => {}
173        }
174    }
175
176    fn process_type_name(&mut self, type_name: &mut TypeName) {
177        type_name.clear_whitespaces();
178    }
179
180    fn process_type_field(&mut self, type_field: &mut TypeField) {
181        type_field.clear_whitespaces();
182    }
183
184    fn process_string_type(&mut self, string_type: &mut StringType) {
185        string_type.clear_whitespaces();
186    }
187
188    fn process_array_type(&mut self, array: &mut ArrayType) {
189        array.clear_whitespaces();
190    }
191
192    fn process_table_type(&mut self, table: &mut TableType) {
193        table.clear_whitespaces();
194    }
195
196    fn process_expression_type(&mut self, expression_type: &mut ExpressionType) {
197        expression_type.clear_whitespaces();
198    }
199
200    fn process_parenthese_type(&mut self, parenthese_type: &mut ParentheseType) {
201        parenthese_type.clear_whitespaces();
202    }
203
204    fn process_function_type(&mut self, function_type: &mut FunctionType) {
205        function_type.clear_whitespaces();
206    }
207
208    fn process_optional_type(&mut self, optional: &mut OptionalType) {
209        optional.clear_whitespaces();
210    }
211
212    fn process_intersection_type(&mut self, intersection: &mut IntersectionType) {
213        intersection.clear_whitespaces();
214    }
215
216    fn process_union_type(&mut self, union: &mut UnionType) {
217        union.clear_whitespaces();
218    }
219
220    fn process_type_pack(&mut self, type_pack: &mut TypePack) {
221        type_pack.clear_whitespaces();
222    }
223
224    fn process_generic_type_pack(&mut self, generic_type_pack: &mut GenericTypePack) {
225        generic_type_pack.clear_whitespaces();
226    }
227
228    fn process_variadic_type_pack(&mut self, variadic_type_pack: &mut VariadicTypePack) {
229        variadic_type_pack.clear_whitespaces();
230    }
231}
232
233pub const REMOVE_SPACES_RULE_NAME: &str = "remove_spaces";
234
235/// A rule that removes whitespaces associated with AST nodes.
236#[derive(Debug, Default, PartialEq, Eq)]
237pub struct RemoveSpaces {}
238
239impl FlawlessRule for RemoveSpaces {
240    fn flawless_process(&self, block: &mut Block, _: &Context) {
241        let mut processor = RemoveWhitespacesProcessor::default();
242        DefaultVisitor::visit_block(block, &mut processor);
243    }
244}
245
246impl RuleConfiguration for RemoveSpaces {
247    fn configure(&mut self, properties: RuleProperties) -> Result<(), RuleConfigurationError> {
248        verify_no_rule_properties(&properties)?;
249        Ok(())
250    }
251
252    fn get_name(&self) -> &'static str {
253        REMOVE_SPACES_RULE_NAME
254    }
255
256    fn serialize_to_properties(&self) -> RuleProperties {
257        RuleProperties::new()
258    }
259}
260
261#[cfg(test)]
262mod test {
263    use super::*;
264    use crate::{
265        generator::{LuaGenerator, TokenBasedLuaGenerator},
266        rules::{ContextBuilder, Rule},
267        Parser, Resources,
268    };
269
270    use insta::assert_json_snapshot;
271
272    fn new_rule() -> RemoveSpaces {
273        RemoveSpaces::default()
274    }
275
276    #[test]
277    fn serialize_default_rule() {
278        let rule: Box<dyn Rule> = Box::new(new_rule());
279
280        assert_json_snapshot!("default_remove_spaces", rule);
281    }
282
283    #[test]
284    fn configure_with_extra_field_error() {
285        let result = json5::from_str::<Box<dyn Rule>>(
286            r#"{
287            rule: 'remove_spaces',
288            prop: "something",
289        }"#,
290        );
291        pretty_assertions::assert_eq!(result.unwrap_err().to_string(), "unexpected field 'prop'");
292    }
293
294    #[test]
295    fn remove_spaces_in_code() {
296        let code = include_str!("../../tests/test_cases/spaces_and_comments.lua");
297
298        let parser = Parser::default().preserve_tokens();
299
300        let mut block = parser.parse(code).expect("unable to parse code");
301
302        RemoveSpaces::default().flawless_process(
303            &mut block,
304            &ContextBuilder::new(".", &Resources::from_memory(), code).build(),
305        );
306
307        let mut generator = TokenBasedLuaGenerator::new(code);
308
309        generator.write_block(&block);
310
311        let code_output = &generator.into_string();
312
313        insta::assert_snapshot!("remove_spaces_in_code", code_output);
314    }
315}