Skip to main content

darklua_core/rules/
remove_nil_declarations.rs

1use crate::nodes::{AssignmentKind, Block, Expression, VariableAssignment};
2use crate::process::{DefaultVisitor, Evaluator, NodeProcessor, NodeVisitor};
3use crate::rules::{
4    Context, FlawlessRule, RuleConfiguration, RuleConfigurationError, RuleMetadata, RuleProperties,
5};
6
7use super::verify_no_rule_properties;
8
9#[derive(Default)]
10struct Processor {
11    evaluator: Evaluator,
12}
13
14impl NodeProcessor for Processor {
15    fn process_local_assign_statement(&mut self, assignment: &mut VariableAssignment) {
16        if let AssignmentKind::Const = assignment.get_assignment_kind() {
17            return;
18        }
19
20        {
21            let mut pop_extra_value_at = Vec::new();
22            for (index, extra_value) in assignment
23                .iter_values()
24                .enumerate()
25                .skip(assignment.variables_len())
26            {
27                if !self.evaluator.has_side_effects(extra_value) {
28                    pop_extra_value_at.push(index);
29                }
30            }
31
32            for index in pop_extra_value_at.into_iter().rev() {
33                assignment.remove_value(index);
34            }
35        }
36
37        if assignment.values_len() > assignment.variables_len() {
38            return;
39        }
40
41        let has_nil_value = assignment
42            .iter_values()
43            .any(|value| matches!(value, Expression::Nil(_)));
44
45        if !has_nil_value {
46            return;
47        }
48
49        if assignment.variables_len() > assignment.values_len()
50            && assignment
51                .last_value()
52                .filter(|last_value| self.evaluator.can_return_multiple_values(last_value))
53                .is_some()
54        {
55            return;
56        }
57
58        let mut remove_values_at = Vec::new();
59        for (index, value) in assignment.iter_values().enumerate() {
60            if matches!(value, Expression::Nil(_)) {
61                remove_values_at.push(index);
62            }
63        }
64
65        let insert_variables: Vec<_> = remove_values_at
66            .into_iter()
67            .rev()
68            .filter_map(|index| {
69                assignment.remove_value(index);
70                assignment.remove_variable(index)
71            })
72            .collect();
73
74        for variable in insert_variables.into_iter().rev() {
75            assignment.push_variable(variable);
76        }
77
78        if let Some(last_value) = assignment.last_value() {
79            if self.evaluator.can_return_multiple_values(last_value) {
80                let new_value = assignment.pop_value().unwrap().in_parentheses();
81                assignment.push_value(new_value);
82            }
83        }
84    }
85}
86
87pub const REMOVE_NIL_DECLARATION_RULE_NAME: &str = "remove_nil_declaration";
88
89/// A rule that removes trailing `nil` in local assignments.
90#[derive(Debug, Default, PartialEq, Eq)]
91pub struct RemoveNilDeclaration {
92    metadata: RuleMetadata,
93}
94
95impl FlawlessRule for RemoveNilDeclaration {
96    fn flawless_process(&self, block: &mut Block, _: &Context) {
97        let mut processor = Processor::default();
98        DefaultVisitor::visit_block(block, &mut processor);
99    }
100}
101
102impl RuleConfiguration for RemoveNilDeclaration {
103    fn configure(&mut self, properties: RuleProperties) -> Result<(), RuleConfigurationError> {
104        verify_no_rule_properties(&properties)?;
105
106        Ok(())
107    }
108
109    fn get_name(&self) -> &'static str {
110        REMOVE_NIL_DECLARATION_RULE_NAME
111    }
112
113    fn serialize_to_properties(&self) -> RuleProperties {
114        RuleProperties::new()
115    }
116
117    fn set_metadata(&mut self, metadata: RuleMetadata) {
118        self.metadata = metadata;
119    }
120
121    fn metadata(&self) -> &RuleMetadata {
122        &self.metadata
123    }
124}
125
126#[cfg(test)]
127mod test {
128    use super::*;
129    use crate::rules::Rule;
130
131    use insta::assert_json_snapshot;
132
133    fn new_rule() -> RemoveNilDeclaration {
134        RemoveNilDeclaration::default()
135    }
136
137    #[test]
138    fn serialize_default_rule() {
139        let rule: Box<dyn Rule> = Box::new(new_rule());
140
141        assert_json_snapshot!(rule, @r###""remove_nil_declaration""###);
142    }
143
144    #[test]
145    fn configure_with_extra_field_error() {
146        let result = json5::from_str::<Box<dyn Rule>>(
147            r#"{
148            rule: 'remove_nil_declaration',
149            prop: "something",
150        }"#,
151        );
152        insta::assert_snapshot!(result.unwrap_err().to_string(), @"unexpected field 'prop' at line 1 column 1");
153    }
154}