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 assert #101

Closed
Closed
Show file tree
Hide file tree
Changes from 3 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
41 changes: 41 additions & 0 deletions crates/cairo-lint-core/src/fix.rs
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,7 @@ impl Fixer {
CairoLintKind::LoopMatchPopFront => {
self.fix_loop_match_pop_front(db, plugin_diag.stable_ptr.lookup(db.upcast()))
}
CairoLintKind::ManualAssert => self.fix_if_then_panic(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 @@ -378,4 +379,44 @@ impl Fixer {
expr.if_block(db).as_syntax_node().get_text(db),
)
}

pub fn fix_if_then_panic(&self, db: &dyn SyntaxGroup, node: SyntaxNode) -> String {
let if_expr = ExprIf::from_syntax_node(db, node.clone());
let condition = if let Condition::Expr(expr) = if_expr.condition(db) {
expr
} else {
panic!("Unexpected condition type");
};

let block_expr = if_expr.if_block(db);
let statements = block_expr.statements(db).elements(db);

if let Some(Statement::Expr(statement_expr)) = statements.first() {
if let Expr::InlineMacro(inline_macro) = &statement_expr.expr(db) {
let panic_message = inline_macro.arguments(db).as_syntax_node().get_text_without_trivia(db);
let condition_text = condition.as_syntax_node().get_text_without_trivia(db);
let assert_condition = condition_text.trim_start_matches('!');
Copy link
Contributor

Choose a reason for hiding this comment

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

don't do that, take the if condition from the Expr::If


let main_expression = if let Some(pos) = assert_condition.find(".is_empty()") {
&assert_condition[..pos]
} else {
assert_condition
};

let indentation = node.get_text(db).chars().take_while(|c| c.is_whitespace()).collect::<String>();

let assert_macro = format!(
"{}assert!({}, \"{}: {{:?}}\", {});\n",
indentation,
assert_condition,
panic_message.trim_matches(&['(', ')'][..]).replace("\"", "").trim(),
main_expression,
);

return assert_macro;
}
}

node.get_text(db).to_string()
}
}
34 changes: 34 additions & 0 deletions crates/cairo-lint-core/src/lints/manual/manual_assert.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
use cairo_lang_defs::plugin::PluginDiagnostic;
use cairo_lang_diagnostics::Severity;
use cairo_lang_syntax::node::ast::{Condition, Expr, ExprBlock, ExprIf, Statement};
use cairo_lang_syntax::node::db::SyntaxGroup;
use cairo_lang_syntax::node::{TypedStablePtr, TypedSyntaxNode};

pub const MANUAL_ASSERT: &str = "`assert!` is simpler than `if`-then-`panic!`";

pub fn contains_panic(db: &dyn SyntaxGroup, block_expr: &ExprBlock) -> bool {
let statements = block_expr.statements(db).elements(db);
if let Statement::Expr(statement_expr) = &statements[0] {
if let Expr::InlineMacro(inline_macro) = &statement_expr.expr(db) {
let macro_name: String = inline_macro.path(db).node.clone().get_text_without_trivia(db);
if macro_name == "panic" {
return true;
}
}
}
false
}

pub fn check_if_then_panic(db: &dyn SyntaxGroup, expr: &ExprIf, diagnostics: &mut Vec<PluginDiagnostic>) {
let condition = expr.condition(db);
let block_expr = expr.if_block(db);
if let Condition::Expr(_condition_expr) = condition
&& contains_panic(db, &block_expr)
{
diagnostics.push(PluginDiagnostic {
stable_ptr: expr.stable_ptr().untyped(),
message: MANUAL_ASSERT.to_string(),
severity: Severity::Warning,
});
}
}
1 change: 1 addition & 0 deletions crates/cairo-lint-core/src/lints/manual/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pub mod manual_assert;
1 change: 1 addition & 0 deletions crates/cairo-lint-core/src/lints/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,5 @@ pub mod double_parens;
pub mod duplicate_underscore_args;
pub mod ifs;
pub mod loops;
pub mod manual;
pub mod single_match;
20 changes: 15 additions & 5 deletions crates/cairo-lint-core/src/plugin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use cairo_lang_syntax::node::kind::SyntaxKind;
use cairo_lang_syntax::node::{TypedStablePtr, TypedSyntaxNode};

use crate::lints::ifs::*;
use crate::lints::manual::manual_assert;
use crate::lints::{
bool_comparison, breaks, double_comparison, double_parens, duplicate_underscore_args, loops, single_match,
};
Expand All @@ -32,6 +33,7 @@ pub enum CairoLintKind {
CollapsibleIfElse,
DuplicateUnderscoreArgs,
LoopMatchPopFront,
ManualAssert,
Unknown,
}

Expand All @@ -49,6 +51,7 @@ pub fn diagnostic_kind_from_message(message: &str) -> CairoLintKind {
collapsible_if_else::COLLAPSIBLE_IF_ELSE => CairoLintKind::CollapsibleIfElse,
duplicate_underscore_args::DUPLICATE_UNDERSCORE_ARGS => CairoLintKind::DuplicateUnderscoreArgs,
loops::LOOP_MATCH_POP_FRONT => CairoLintKind::LoopMatchPopFront,
manual_assert::MANUAL_ASSERT => CairoLintKind::ManualAssert,
_ => CairoLintKind::Unknown,
}
}
Expand Down Expand Up @@ -93,11 +96,18 @@ impl AnalyzerPlugin for CairoLint {
&mut diags,
),
SyntaxKind::StatementBreak => breaks::check_break(db.upcast(), node, &mut diags),
SyntaxKind::ExprIf => equatable_if_let::check_equatable_if_let(
db.upcast(),
&ExprIf::from_syntax_node(db.upcast(), node),
&mut diags,
),
SyntaxKind::ExprIf => {
equatable_if_let::check_equatable_if_let(
db.upcast(),
&ExprIf::from_syntax_node(db.upcast(), node.clone()),
&mut diags,
);
manual_assert::check_if_then_panic(
db.upcast(),
&ExprIf::from_syntax_node(db.upcast(), node.clone()),
&mut diags,
);
}
SyntaxKind::ExprBinary => {
let expr_binary = ExprBinary::from_syntax_node(db.upcast(), node);
bool_comparison::check_bool_comparison(db.upcast(), &expr_binary, &mut diags);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
//! > check-if-then

//! > cairo_code
fn main() {
let sad_people: Array<u32> = array![];
if !sad_people.is_empty() {
panic!("there are sad people");
}
}

//! > diagnostics
warning: Plugin diagnostic: `assert!` is simpler than `if`-then-`panic!`
--> lib.cairo:4:5
|
4 | if !sad_people.is_empty() {
| _____-
5 | | panic!("there are sad people");
6 | | }
| |_____-
|

//! > fixed
fn main() {
let sad_people: Array<u32> = array![];
assert!(sad_people.is_empty(), "there are sad people: {:?}", sad_people);
}
2 changes: 2 additions & 0 deletions crates/cairo-lint-core/tests/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -153,3 +153,5 @@ test_file!(
"Else if with multiple statements",
"Else if inside loop"
);

test_file!(manual_assert, manual_assert, "check-if-then");
Loading