darklua_core/rules/
remove_method_call.rs

1use crate::nodes::{Block, Expression, FieldExpression, FunctionCall, Prefix};
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)]
10struct Processor {}
11
12impl NodeProcessor for Processor {
13    fn process_expression(&mut self, expression: &mut Expression) {
14        if let Expression::Call(call) = expression {
15            self.process_function_call(call);
16        }
17    }
18
19    fn process_function_call(&mut self, call: &mut FunctionCall) {
20        if !call.has_method() {
21            return;
22        }
23
24        let replace_with: Option<Prefix> = match call.get_prefix() {
25            Prefix::Identifier(identifier) => Some(identifier.clone().into()),
26            Prefix::Parenthese(parenthese) => match *parenthese.inner_expression() {
27                Expression::If(_)
28                | Expression::Index(_)
29                | Expression::Field(_)
30                | Expression::Function(_)
31                | Expression::Binary(_)
32                | Expression::Table(_)
33                | Expression::Unary(_)
34                | Expression::VariableArguments(_)
35                | Expression::TypeCast(_)
36                | Expression::InterpolatedString(_)
37                | Expression::Parenthese(_)
38                | Expression::Call(_) => None,
39
40                Expression::Nil(_)
41                | Expression::True(_)
42                | Expression::False(_)
43                | Expression::String(_)
44                | Expression::Number(_)
45                | Expression::Identifier(_) => Some(parenthese.inner_expression().clone().into()),
46            },
47            _ => None,
48        };
49
50        if let Some(new_prefix) = replace_with {
51            let method_name = call
52                .take_method()
53                .expect("method name is expected to exist");
54
55            *call.mutate_prefix() = FieldExpression::new(new_prefix.clone(), method_name).into();
56            call.mutate_arguments()
57                .insert(0, Expression::from(new_prefix));
58        }
59    }
60}
61
62pub const REMOVE_METHOD_CALL_RULE_NAME: &str = "remove_method_call";
63
64/// A rule that converts method calls with identifier prefixes to regular function calls.
65///
66/// This rule transforms calls like `obj:method()` to `obj.method()` when the prefix
67/// is a simple identifier.
68#[derive(Debug, Default, PartialEq, Eq)]
69pub struct RemoveMethodCall {}
70
71impl FlawlessRule for RemoveMethodCall {
72    fn flawless_process(&self, block: &mut Block, _: &Context) {
73        let mut processor = Processor::default();
74        DefaultVisitor::visit_block(block, &mut processor);
75    }
76}
77
78impl RuleConfiguration for RemoveMethodCall {
79    fn configure(&mut self, properties: RuleProperties) -> Result<(), RuleConfigurationError> {
80        verify_no_rule_properties(&properties)?;
81        Ok(())
82    }
83
84    fn get_name(&self) -> &'static str {
85        REMOVE_METHOD_CALL_RULE_NAME
86    }
87
88    fn serialize_to_properties(&self) -> RuleProperties {
89        RuleProperties::new()
90    }
91}
92
93#[cfg(test)]
94mod test {
95    use super::*;
96    use crate::rules::Rule;
97
98    use insta::assert_json_snapshot;
99
100    fn new_rule() -> RemoveMethodCall {
101        RemoveMethodCall::default()
102    }
103
104    #[test]
105    fn serialize_default_rule() {
106        let rule: Box<dyn Rule> = Box::new(new_rule());
107
108        assert_json_snapshot!("default_remove_method_call", rule);
109    }
110
111    #[test]
112    fn configure_with_extra_field_error() {
113        let result = json5::from_str::<Box<dyn Rule>>(
114            r#"{
115            rule: 'remove_method_call',
116            prop: "something",
117        }"#,
118        );
119        pretty_assertions::assert_eq!(result.unwrap_err().to_string(), "unexpected field 'prop'");
120    }
121}