1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
use crate::nodes::{Block, DoStatement, IfStatement, Statement};
use crate::process::{DefaultVisitor, Evaluator, NodeProcessor, NodeVisitor};
use crate::rules::{
    Context, FlawlessRule, RuleConfiguration, RuleConfigurationError, RuleProperties,
};

use std::mem;

use super::verify_no_rule_properties;

enum FilterResult {
    Keep,
    Remove,
    Replace(Block),
}

#[derive(Debug, Clone, Default)]
struct IfFilter {
    evaluator: Evaluator,
}

impl IfFilter {
    fn filter(&self, statement: &mut IfStatement) -> FilterResult {
        let found_always_true_branch = self.filter_branches(statement);

        if found_always_true_branch {
            statement.take_else_block();
        }

        let branch_count = statement.branch_count();

        if branch_count == 0 {
            if let Some(block) = statement.take_else_block() {
                if block.is_empty() {
                    FilterResult::Remove
                } else {
                    FilterResult::Replace(block)
                }
            } else {
                FilterResult::Remove
            }
        } else if found_always_true_branch && branch_count == 1 {
            let branch = statement.mutate_branches().iter_mut().next().unwrap();

            if !self.evaluator.has_side_effects(branch.get_condition()) {
                let mut branch_block = Block::default();
                mem::swap(branch.mutate_block(), &mut branch_block);

                FilterResult::Replace(branch_block)
            } else {
                FilterResult::Keep
            }
        } else {
            FilterResult::Keep
        }
    }

    fn filter_branches(&self, statement: &mut IfStatement) -> bool {
        let branches = statement.mutate_branches();
        let mut found_always_true_branch = false;
        let mut i = 0;

        while i != branches.len() {
            if found_always_true_branch {
                branches.remove(i);
            } else {
                let branch = branches.get_mut(i).unwrap();
                let condition = branch.get_condition();
                let is_truthy = self.evaluator.evaluate(condition).is_truthy();

                if let Some(is_truthy) = is_truthy {
                    if is_truthy {
                        found_always_true_branch = true;
                        i += 1;
                    } else {
                        let side_effects = self.evaluator.has_side_effects(condition);

                        if side_effects {
                            // only need to clear if there are side effects because it means
                            // that we are keeping the branch just for the condition
                            branch.mutate_block().clear();
                            i += 1;
                        } else {
                            branches.remove(i);
                        }
                    }
                } else {
                    i += 1;
                }
            }
        }

        found_always_true_branch
    }
}

impl NodeProcessor for IfFilter {
    fn process_block(&mut self, block: &mut Block) {
        block.filter_statements(|statement| {
            let result = match statement {
                Statement::If(if_statement) => self.filter(if_statement),
                _ => FilterResult::Keep,
            };

            match result {
                FilterResult::Keep => true,
                FilterResult::Remove => false,
                FilterResult::Replace(block) => {
                    *statement = DoStatement::new(block).into();
                    true
                }
            }
        });
    }
}

pub const REMOVE_UNUSED_IF_BRANCH_RULE_NAME: &str = "remove_unused_if_branch";

/// A rule that removes unused if branches. It can also turn a if statement into a do block
/// statement.
#[derive(Debug, Default, PartialEq, Eq)]
pub struct RemoveUnusedIfBranch {}

impl FlawlessRule for RemoveUnusedIfBranch {
    fn flawless_process(&self, block: &mut Block, _: &mut Context) {
        let mut processor = IfFilter::default();
        DefaultVisitor::visit_block(block, &mut processor);
    }
}

impl RuleConfiguration for RemoveUnusedIfBranch {
    fn configure(&mut self, properties: RuleProperties) -> Result<(), RuleConfigurationError> {
        verify_no_rule_properties(&properties)?;

        Ok(())
    }

    fn get_name(&self) -> &'static str {
        REMOVE_UNUSED_IF_BRANCH_RULE_NAME
    }

    fn serialize_to_properties(&self) -> RuleProperties {
        RuleProperties::new()
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::rules::Rule;

    use insta::assert_json_snapshot;

    fn new_rule() -> RemoveUnusedIfBranch {
        RemoveUnusedIfBranch::default()
    }

    #[test]
    fn serialize_default_rule() {
        let rule: Box<dyn Rule> = Box::new(new_rule());

        assert_json_snapshot!("default_remove_unused_if_branch", rule);
    }
}