Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add remove_if_expression rule #208

Closed
wants to merge 7 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions src/rules/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ mod remove_call_match;
mod remove_comments;
mod remove_compound_assign;
mod remove_debug_profiling;
mod remove_if_expression;
mod remove_interpolated_string;
mod remove_nil_declarations;
mod remove_spaces;
Expand Down Expand Up @@ -47,6 +48,7 @@ pub use remove_assertions::*;
pub use remove_comments::*;
pub use remove_compound_assign::*;
pub use remove_debug_profiling::*;
pub use remove_if_expression::*;
pub use remove_interpolated_string::*;
pub use remove_nil_declarations::*;
pub use remove_spaces::*;
Expand Down Expand Up @@ -214,6 +216,7 @@ pub fn get_default_rules() -> Vec<Box<dyn Rule>> {
Box::<RemoveNilDeclaration>::default(),
Box::<RenameVariables>::default(),
Box::<RemoveFunctionCallParens>::default(),
Box::<RemoveIfExpression>::default(),
]
}

Expand Down Expand Up @@ -242,6 +245,7 @@ pub fn get_all_rule_names() -> Vec<&'static str> {
REMOVE_UNUSED_VARIABLE_RULE_NAME,
REMOVE_UNUSED_WHILE_RULE_NAME,
RENAME_VARIABLES_RULE_NAME,
REMOVE_IF_EXPRESSION_RULE_NAME,
]
}

Expand Down Expand Up @@ -275,6 +279,7 @@ impl FromStr for Box<dyn Rule> {
REMOVE_UNUSED_VARIABLE_RULE_NAME => Box::<RemoveUnusedVariable>::default(),
REMOVE_UNUSED_WHILE_RULE_NAME => Box::<RemoveUnusedWhile>::default(),
RENAME_VARIABLES_RULE_NAME => Box::<RenameVariables>::default(),
REMOVE_IF_EXPRESSION_RULE_NAME => Box::<RemoveIfExpression>::default(),
_ => return Err(format!("invalid rule name: {}", string)),
};

Expand Down
116 changes: 116 additions & 0 deletions src/rules/remove_if_expression.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
use crate::nodes::{
self, BinaryExpression, Block, ElseIfExpressionBranch, Expression, IndexExpression,
ParentheseExpression, TableEntry, TableExpression,
};
use crate::process::{DefaultVisitor, NodeProcessor, NodeVisitor};
use crate::rules::{
Context, FlawlessRule, RuleConfiguration, RuleConfigurationError, RuleProperties,
};

use super::verify_no_rule_properties;

#[derive(Default)]
struct Processor {}

fn process(
condition: &Expression,
result: &Expression,
else_result: &Expression,
branches: &Vec<&ElseIfExpressionBranch>,
) -> Expression {
let result_parenthese = ParentheseExpression::new(result.clone());
let result_table = TableExpression::new(vec![TableEntry::Value(result_parenthese.into())]);
let if_bin = BinaryExpression::new(nodes::BinaryOperator::And, condition.clone(), result_table);
let bin_right: Expression = if branches.len() > 0 {
let b = branches[0];
let elseif_result = process(
b.get_condition(),
b.get_result(),
else_result,
&branches[1..].to_vec(),
);
let elseif_result_table = TableExpression::new(vec![TableEntry::Value(elseif_result)]);
elseif_result_table.into()
} else {
let else_result_parenthese = ParentheseExpression::new(else_result.clone());
let else_result_table =
TableExpression::new(vec![TableEntry::Value(else_result_parenthese.into())]);
else_result_table.into()
};
let bin = BinaryExpression::new(nodes::BinaryOperator::Or, if_bin, bin_right);
let bin_parenthese = ParentheseExpression::new(Expression::Binary(Box::new(bin)));
IndexExpression::new(bin_parenthese, 1).into()
}

impl NodeProcessor for Processor {
fn process_expression(&mut self, expression: &mut Expression) {
if let Expression::If(if_exp) = expression {
let translated_exp = process(
if_exp.get_condition(),
if_exp.get_result(),
if_exp.get_else_result(),
&if_exp.iter_branches().collect(),
);
*expression = translated_exp;
}
}
}

pub const REMOVE_IF_EXPRESSION_RULE_NAME: &str = "remove_if_expression";

/// A rule that removes trailing `nil` in local assignments.
#[derive(Debug, Default, PartialEq, Eq)]
pub struct RemoveIfExpression {}

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

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

Ok(())
}

fn get_name(&self) -> &'static str {
REMOVE_IF_EXPRESSION_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() -> RemoveIfExpression {
RemoveIfExpression::default()
}

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

assert_json_snapshot!("default_remove_if_expression", rule);
}

#[test]
fn configure_with_extra_field_error() {
let result = json5::from_str::<Box<dyn Rule>>(
r#"{
rule: 'remove_if_expression',
prop: "something",
}"#,
);
pretty_assertions::assert_eq!(result.unwrap_err().to_string(), "unexpected field 'prop'");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
source: src/rules/remove_continue.rs
expression: rule
---
"remove_continue"
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
source: src/rules/remove_if_expression.rs
expression: rule
---
"remove_if_expression"
Original file line number Diff line number Diff line change
Expand Up @@ -25,5 +25,6 @@ expression: rule_names
"remove_unused_if_branch",
"remove_unused_variable",
"remove_unused_while",
"rename_variables"
"rename_variables",
"remove_if_expression"
]
Original file line number Diff line number Diff line change
Expand Up @@ -15,5 +15,6 @@ expression: rules
"convert_index_to_field",
"remove_nil_declaration",
"rename_variables",
"remove_function_call_parens"
"remove_function_call_parens",
"remove_if_expression"
]
1 change: 1 addition & 0 deletions tests/rule_tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,7 @@ mod remove_comments;
mod remove_compound_assignment;
mod remove_debug_profiling;
mod remove_empty_do;
mod remove_if_expression;
mod remove_interpolated_string;
mod remove_method_definition;
mod remove_nil_declaration;
Expand Down
25 changes: 25 additions & 0 deletions tests/rule_tests/remove_if_expression.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
use darklua_core::rules::{RemoveIfExpression, Rule};

test_rule!(
remove_if_expression,
RemoveIfExpression::default(),
assign_if_expression("local a = if true then 1 else 2") => "local a = (true and {(1)} or {(2)})[1]",
assign_if_expression_with_elseif("local a = if true then 1 elseif false then 2 else 3") => "local a = (true and {(1)} or {(false and {(2)} or {(3)})[1]})[1]",
if_expression_with_varargs("local function f(...: string) return if condition(...) then ... else transform(...) end") => "local function f(...: string) return (condition(...) and {(...)} or {(transform(...))})[1] end",
if_expression_with_varargs_elseif("local function f(...: string) return if condition(...) then ... elseif condition(...) then ... else transform(...) end") => "local function f(...: string) return (condition(...) and {(...)} or {(condition(...) and {(...)} or {(transform(...))})[1]})[1] end"
);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's add more tests! For example, we need to treat function calls and ... in a specific way to make sure we are not returning multiple values. For that we need to wrap them in parentheses.


#[test]
fn deserialize_from_object_notation() {
json5::from_str::<Box<dyn Rule>>(
r#"{
rule: 'remove_if_expression',
}"#,
)
.unwrap();
}

#[test]
fn deserialize_from_string() {
json5::from_str::<Box<dyn Rule>>("'remove_if_expression'").unwrap();
}