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

feat: add manual unwrap or lint #127

Closed
wants to merge 2 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
104 changes: 103 additions & 1 deletion crates/cairo-lint-core/src/fix.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use cairo_lang_filesystem::span::TextSpan;
use cairo_lang_semantic::diagnostic::SemanticDiagnosticKind;
use cairo_lang_semantic::SemanticDiagnostic;
use cairo_lang_syntax::node::ast::{
BlockOrIf, Condition, ElseClause, Expr, ExprBinary, ExprIf, ExprLoop, ExprMatch, OptionElseClause,
BlockOrIf, Condition, ElseClause, Expr, ExprBinary, ExprIf, ExprLoop, ExprMatch, MatchArm, OptionElseClause,
OptionPatternEnumInnerPattern, Pattern, Statement,
};
use cairo_lang_syntax::node::db::SyntaxGroup;
Expand Down Expand Up @@ -187,6 +187,7 @@ impl Fixer {
CairoLintKind::ManualIsSome => self.fix_manual_is_some(db, plugin_diag.stable_ptr.lookup(db.upcast())),
CairoLintKind::ManualExpect => self.fix_manual_expect(db, plugin_diag.stable_ptr.lookup(db.upcast())),
CairoLintKind::ManualIsNone => self.fix_manual_is_none(db, plugin_diag.stable_ptr.lookup(db.upcast())),
CairoLintKind::ManualUnwrapOr => self.fix_manual_unwrap_or(db, plugin_diag.stable_ptr.lookup(db.upcast())),
_ => return None,
};
Some((semantic_diag.stable_location.syntax_node(db.upcast()), new_text))
Expand Down Expand Up @@ -544,4 +545,105 @@ impl Fixer {

format!("{option_var_name}.expect({none_arm_err})")
}

/// Rewrites a manual match expression for `Option<T>` or `Result<T, E>` into a more concise
/// `unwrap_or`.
///
/// Simplifies an expression by converting a manual match that checks `Option::Some` or
/// `Result::Ok` and provides a default for `Option::None` or `Result::Err` into an `unwrap_or`
/// statement.
///
/// # Arguments
///
/// * `db` - Reference to the `SyntaxGroup` for accessing the syntax tree.
/// * `node` - The `SyntaxNode` containing the match expression.
///
/// # Returns
///
/// A `String` representing the refactored expression with `unwrap_or`.
pub fn fix_manual_unwrap_or(&self, db: &dyn SyntaxGroup, node: SyntaxNode) -> String {
let expr_match = if let Expr::Match(expr_match) = Expr::from_syntax_node(db, node.clone()) {
expr_match
} else {
panic!("Expected a match expression");
};

let var_name = match expr_match.expr(db) {
Expr::Path(path_expr) => path_expr.as_syntax_node().get_text_without_trivia(db),
_ => panic!("Expected a variable or path in match expression"),
};

let arms = expr_match.arms(db).elements(db);
if arms.len() != 2 {
panic!("Expected exactly two arms in the match expression");
}

let first_arm = &arms[0];
let second_arm = &arms[1];

let first_pattern = &first_arm.patterns(db).elements(db)[0];
let second_pattern = &second_arm.patterns(db).elements(db)[0];

if let Some(default_value) =
Self::extract_default_value_for_option(db, first_pattern, second_pattern, second_arm)
{
return indent_snippet(
&format!("{}.unwrap_or({})", var_name, default_value),
node.get_text(db).chars().take_while(|c| c.is_whitespace()).collect::<String>().len() / 4,
);
}

if let Some(default_value) =
Self::extract_default_value_for_result(db, first_pattern, second_pattern, second_arm)
{
return indent_snippet(
&format!("{}.unwrap_or({})", var_name, default_value),
node.get_text(db).chars().take_while(|c| c.is_whitespace()).collect::<String>().len() / 4,
);
}

expr_match.as_syntax_node().get_text_without_trivia(db)
}

fn extract_default_value_for_option(
db: &dyn SyntaxGroup,
first_pattern: &Pattern,
second_pattern: &Pattern,
second_arm: &MatchArm,
) -> Option<String> {
let is_some = Self::match_enum_pattern(db, first_pattern, "Option::Some");
let is_none = Self::match_enum_pattern(db, second_pattern, "Option::None");

if is_some && is_none {
Some(second_arm.expression(db).as_syntax_node().get_text_without_trivia(db))
} else {
None
}
}

fn extract_default_value_for_result(
db: &dyn SyntaxGroup,
first_pattern: &Pattern,
second_pattern: &Pattern,
second_arm: &MatchArm,
) -> Option<String> {
let is_ok = Self::match_enum_pattern(db, first_pattern, "Result::Ok");
let is_err = Self::match_enum_pattern(db, second_pattern, "Result::Err");

if is_ok && is_err {
Some(second_arm.expression(db).as_syntax_node().get_text_without_trivia(db))
} else {
None
}
}

fn match_enum_pattern(db: &dyn SyntaxGroup, pattern: &Pattern, expected: &str) -> bool {
match pattern {
Pattern::Enum(enum_pattern) => {
let enum_name = enum_pattern.path(db).as_syntax_node().get_text_without_trivia(db);
enum_name.as_str() == expected
}
_ => false,
}
}
}
79 changes: 79 additions & 0 deletions crates/cairo-lint-core/src/lints/manual/manual_unwrap_or.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
use cairo_lang_defs::plugin::PluginDiagnostic;
use cairo_lang_diagnostics::Severity;
use cairo_lang_syntax::node::ast::{ExprMatch, Pattern};
use cairo_lang_syntax::node::db::SyntaxGroup;
use cairo_lang_syntax::node::TypedSyntaxNode;

pub const MANUAL_UNWRAP_OR: &str =
"Manual match for Option<T> or Result<T, E> detected. Consider using unwrap_or instead.";

pub fn check_manual_unwrap_or(db: &dyn SyntaxGroup, expr_match: &ExprMatch, diagnostics: &mut Vec<PluginDiagnostic>) {
let arms = expr_match.arms(db).elements(db);

if arms.len() != 2 {
return;
}

let first_arm = &arms[0];
let second_arm = &arms[1];

let first_pattern = &first_arm.patterns(db).elements(db)[0];
let second_pattern = &second_arm.patterns(db).elements(db)[0];

// Check for Option::Some and Option::None
let found_option_some_none = is_option_some_none(db, first_pattern, second_pattern);

// Check for Result::Ok and Result::Err
let found_result_ok_err = is_result_ok_err(db, first_pattern, second_pattern);

// If both patterns are Some/None or Ok/Err, generate diagnosis
if found_option_some_none || found_result_ok_err {
diagnostics.push(PluginDiagnostic {
stable_ptr: expr_match.as_syntax_node().stable_ptr(),
message: MANUAL_UNWRAP_OR.to_string(),
severity: Severity::Warning,
});
}
}

// Check if the patterns are Option::Some and Option::None.
fn is_option_some_none(db: &dyn SyntaxGroup, first_pattern: &Pattern, second_pattern: &Pattern) -> bool {
let found_some = match first_pattern {
Pattern::Enum(enum_pattern) => {
let enum_name = enum_pattern.path(db).as_syntax_node().get_text_without_trivia(db);
enum_name.as_str() == "Option::Some"
}
_ => false,
};

let found_none = match second_pattern {
Pattern::Enum(enum_pattern) => {
let enum_name = enum_pattern.path(db).as_syntax_node().get_text_without_trivia(db);
enum_name.as_str() == "Option::None"
}
_ => false,
};

found_some && found_none
}

// Check if the patterns are Result::Ok and Result::Err.
fn is_result_ok_err(db: &dyn SyntaxGroup, first_pattern: &Pattern, second_pattern: &Pattern) -> bool {
let found_ok = match first_pattern {
Pattern::Enum(enum_pattern) => {
let enum_name = enum_pattern.path(db).as_syntax_node().get_text_without_trivia(db);
enum_name.as_str() == "Result::Ok"
}
_ => false,
};

let found_err = match second_pattern {
Pattern::Enum(enum_pattern) => {
let enum_name = enum_pattern.path(db).as_syntax_node().get_text_without_trivia(db);
enum_name.as_str() == "Result::Err"
}
_ => false,
};

found_ok && found_err
}
15 changes: 15 additions & 0 deletions crates/cairo-lint-core/src/lints/manual/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ pub mod manual_expect;
pub mod manual_is_none;
pub mod manual_is_some;
pub mod manual_ok_or;
pub mod manual_unwrap_or;

use cairo_lang_syntax::node::ast::{Expr, ExprMatch, MatchArm, OptionPatternEnumInnerPattern, Pattern};
use cairo_lang_syntax::node::db::SyntaxGroup;
Expand All @@ -13,6 +14,7 @@ pub enum ManualLint {
ManualIsSome,
ManualIsNone,
ManualExpect,
ManualUnwrapOr,
}
pub fn check_manual(db: &dyn SyntaxGroup, expr_match: &ExprMatch, manual_lint: ManualLint) -> bool {
let arms = expr_match.arms(db).elements(db);
Expand Down Expand Up @@ -79,6 +81,12 @@ fn check_syntax_some_arm(arm: &MatchArm, db: &dyn SyntaxGroup, manual_lint: Manu
return false;
}
},
ManualLint::ManualUnwrapOr => {
if let Expr::Path(path_expr) = arm.expression(db) {
let expr_name = path_expr.as_syntax_node().get_text_without_trivia(db);
return expr_name == "Option::Some" || expr_name == "Result::Ok";
}
}
}
false
}
Expand All @@ -105,6 +113,13 @@ fn check_syntax_none_expression(arm_expression: Expr, db: &dyn SyntaxGroup, manu
return false;
}
}
ManualLint::ManualUnwrapOr => {
// Lógica para verificar Option::None o Result::Err
if let Expr::Path(path_expr) = arm_expression {
let expr_name = path_expr.as_syntax_node().get_text_without_trivia(db);
return expr_name == "Option::None" || expr_name == "Result::Err";
}
}
}

false
Expand Down
7 changes: 7 additions & 0 deletions crates/cairo-lint-core/src/plugin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ pub enum CairoLintKind {
ManualIsSome,
ManualIsNone,
ManualExpect,
ManualUnwrapOr,
}

pub fn diagnostic_kind_from_message(message: &str) -> CairoLintKind {
Expand All @@ -67,6 +68,7 @@ pub fn diagnostic_kind_from_message(message: &str) -> CairoLintKind {
manual_is_some::MANUAL_IS_SOME => CairoLintKind::ManualIsSome,
manual_is_none::MANUAL_IS_NONE => CairoLintKind::ManualIsNone,
manual_expect::MANUAL_EXPECT => CairoLintKind::ManualExpect,
manual_unwrap_or::MANUAL_UNWRAP_OR => CairoLintKind::ManualUnwrapOr,
_ => CairoLintKind::Unknown,
}
}
Expand Down Expand Up @@ -158,6 +160,11 @@ impl AnalyzerPlugin for CairoLint {
&ExprMatch::from_syntax_node(db.upcast(), node.clone()),
&mut diags,
);
manual_unwrap_or::check_manual_unwrap_or(
db.upcast(),
&ExprMatch::from_syntax_node(db.upcast(), node.clone()),
&mut diags,
);
}
_ => continue,
}
Expand Down
Loading
Loading