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 convert_luau_numbers rule #257

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
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 @@ -23,6 +23,7 @@ mod remove_floor_division;
mod remove_if_expression;
mod remove_interpolated_string;
mod remove_nil_declarations;
mod remove_number_literals;
mod remove_spaces;
mod remove_types;
mod remove_unused_variable;
Expand Down Expand Up @@ -55,6 +56,7 @@ pub use remove_floor_division::*;
pub use remove_if_expression::*;
pub use remove_interpolated_string::*;
pub use remove_nil_declarations::*;
pub use remove_number_literals::*;
pub use remove_spaces::*;
pub use remove_types::*;
pub use remove_unused_variable::*;
Expand Down Expand Up @@ -235,6 +237,7 @@ pub fn get_default_rules() -> Vec<Box<dyn Rule>> {
Box::<RemoveNilDeclaration>::default(),
Box::<RenameVariables>::default(),
Box::<RemoveFunctionCallParens>::default(),
Box::<RemoveNumberLiterals>::default(),
Copy link
Contributor

Choose a reason for hiding this comment

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

I think I would not put this rule in the default rules, at least for now

]
}

Expand Down Expand Up @@ -265,6 +268,7 @@ pub fn get_all_rule_names() -> Vec<&'static str> {
RENAME_VARIABLES_RULE_NAME,
REMOVE_IF_EXPRESSION_RULE_NAME,
REMOVE_CONTINUE_RULE_NAME,
REMOVE_NUMBER_LITERALS_RULE_NAME,
]
}

Expand Down Expand Up @@ -301,6 +305,7 @@ impl FromStr for Box<dyn Rule> {
RENAME_VARIABLES_RULE_NAME => Box::<RenameVariables>::default(),
REMOVE_IF_EXPRESSION_RULE_NAME => Box::<RemoveIfExpression>::default(),
REMOVE_CONTINUE_RULE_NAME => Box::<RemoveContinue>::default(),
REMOVE_NUMBER_LITERALS_RULE_NAME => Box::<RemoveNumberLiterals>::default(),
_ => return Err(format!("invalid rule name: {}", string)),
};

Expand Down
90 changes: 90 additions & 0 deletions src/rules/remove_number_literals.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
use crate::{
nodes::{Block, DecimalNumber, Expression, NumberExpression},
process::{DefaultVisitor, NodeProcessor, NodeVisitor},
rules::{Context, FlawlessRule, RuleConfiguration, RuleConfigurationError, RuleProperties},
};

use super::verify_no_rule_properties;

#[derive(Default)]
struct Processor {}

impl NodeProcessor for Processor {
fn process_expression(&mut self, exp: &mut Expression) {
Copy link
Contributor

Choose a reason for hiding this comment

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

There is a function for number expressions you can use directly:

Suggested change
fn process_expression(&mut self, exp: &mut Expression) {
fn process_number_expression(&mut self, number: &mut NumberExpression) {

if let Expression::Number(num_exp) = exp {
match num_exp {
NumberExpression::Binary(binary) => {
let value = binary.compute_value();
*exp = DecimalNumber::new(value).into();
}
NumberExpression::Decimal(decimal) => {
let value = decimal.compute_value();
*exp = DecimalNumber::new(value).into();
}
NumberExpression::Hex(hex) => {
let value = hex.compute_value();
*exp = DecimalNumber::new(value).into();
}
}
}
}
}

pub const REMOVE_NUMBER_LITERALS_RULE_NAME: &str = "remove_number_literals";

/// A rule that removes number literals.
#[derive(Default, Debug, PartialEq, Eq)]
pub struct RemoveNumberLiterals {}

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

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

Ok(())
}

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

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

assert_json_snapshot!("default_remove_number_literals", rule);
}

#[test]
fn configure_with_extra_field_error() {
let result = json5::from_str::<Box<dyn Rule>>(
r#"{
rule: 'remove_number_literals',
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_number_literals.rs
expression: rule
---
"remove_number_literals"
Original file line number Diff line number Diff line change
Expand Up @@ -27,5 +27,6 @@ expression: rule_names
"remove_unused_while",
"rename_variables",
"remove_if_expression",
"remove_continue"
"remove_continue",
"remove_number_literals"
]
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_number_literals"
]
1 change: 1 addition & 0 deletions tests/rule_tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -435,6 +435,7 @@ mod remove_if_expression;
mod remove_interpolated_string;
mod remove_method_definition;
mod remove_nil_declaration;
mod remove_number_literals;
mod remove_types;
mod remove_unused_if_branch;
mod remove_unused_variable;
Expand Down
27 changes: 27 additions & 0 deletions tests/rule_tests/remove_number_literals.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
use darklua_core::rules::{RemoveNumberLiterals, Rule};

test_rule!(
remove_number_literals,
RemoveNumberLiterals::default(),
hexadecimal_integer_literals("local a = 0xABC local b = 0XABC")
=> "local a = 2748 local b = 2748",
binary_integer_literals("local a = 0b01010101 local b = 0B01010101")
=> "local a = 85 local b = 85",
decimal_separators("local a = 1_048_576 local b = 0xFFFF_FFFF local c = 0b_0101_0101")
=> "local a = 1048576 local b = 4294967295 local c = 85",
);

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

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