Skip to main content

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, RuleMetadata, 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    metadata: RuleMetadata,
71}
72
73impl FlawlessRule for RemoveMethodCall {
74    fn flawless_process(&self, block: &mut Block, _: &Context) {
75        let mut processor = Processor::default();
76        DefaultVisitor::visit_block(block, &mut processor);
77    }
78}
79
80impl RuleConfiguration for RemoveMethodCall {
81    fn configure(&mut self, properties: RuleProperties) -> Result<(), RuleConfigurationError> {
82        verify_no_rule_properties(&properties)?;
83        Ok(())
84    }
85
86    fn get_name(&self) -> &'static str {
87        REMOVE_METHOD_CALL_RULE_NAME
88    }
89
90    fn serialize_to_properties(&self) -> RuleProperties {
91        RuleProperties::new()
92    }
93
94    fn set_metadata(&mut self, metadata: RuleMetadata) {
95        self.metadata = metadata;
96    }
97
98    fn metadata(&self) -> &RuleMetadata {
99        &self.metadata
100    }
101}
102
103#[cfg(test)]
104mod test {
105    use super::*;
106    use crate::rules::Rule;
107
108    use insta::assert_json_snapshot;
109
110    fn new_rule() -> RemoveMethodCall {
111        RemoveMethodCall::default()
112    }
113
114    #[test]
115    fn serialize_default_rule() {
116        let rule: Box<dyn Rule> = Box::new(new_rule());
117
118        assert_json_snapshot!(rule, @r###""remove_method_call""###);
119    }
120
121    #[test]
122    fn configure_with_extra_field_error() {
123        let result = json5::from_str::<Box<dyn Rule>>(
124            r#"{
125            rule: 'remove_method_call',
126            prop: "something",
127        }"#,
128        );
129        insta::assert_snapshot!(result.unwrap_err().to_string(), @"unexpected field 'prop' at line 1 column 1");
130    }
131}