diff --git a/crates/ide-diagnostics/src/handlers/missing_unsafe.rs b/crates/ide-diagnostics/src/handlers/missing_unsafe.rs index 4bb64747f5bb..51a0641b90d9 100644 --- a/crates/ide-diagnostics/src/handlers/missing_unsafe.rs +++ b/crates/ide-diagnostics/src/handlers/missing_unsafe.rs @@ -50,7 +50,12 @@ fn fixes(ctx: &DiagnosticsContext<'_>, d: &hir::MissingUnsafe) -> Option Option bool { + let node = expr.syntax(); + node.ancestors() + .skip(1) + .take_while(|it| it.text_range().start() == node.text_range().start()) + .map_while(ast::Expr::cast) + .last() + .and_then(|it| Some(it.syntax().parent()?.kind())) + .is_some_and(|kind| ast::ExprStmt::can_cast(kind) || ast::StmtList::can_cast(kind)) +} + #[cfg(test)] mod tests { use crate::tests::{check_diagnostics, check_fix, check_no_fix}; @@ -527,6 +543,27 @@ fn main() { ) } + #[test] + fn needs_parentheses_for_unambiguous() { + check_fix( + r#" +//- minicore: copy +static mut STATIC_MUT: u8 = 0; + +fn foo() -> u8 { + STATIC_MUT$0 * 2 +} +"#, + r#" +static mut STATIC_MUT: u8 = 0; + +fn foo() -> u8 { + (unsafe { STATIC_MUT }) * 2 +} +"#, + ) + } + #[test] fn ref_to_unsafe_expr() { check_fix(