Skip to content

Commit

Permalink
Avoid suggesting to add unsafe when the extern block is already unsafe
Browse files Browse the repository at this point in the history
  • Loading branch information
spastorino committed Jun 29, 2024
1 parent a62cbda commit b18f6c6
Show file tree
Hide file tree
Showing 4 changed files with 18 additions and 12 deletions.
2 changes: 2 additions & 0 deletions compiler/rustc_ast_passes/messages.ftl
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,8 @@ ast_passes_extern_fn_qualifiers = functions in `extern` blocks cannot have quali
.suggestion = remove this qualifier
ast_passes_extern_invalid_safety = items in unadorned `extern` blocks cannot have safety qualifiers
ast_passes_extern_invalid_safety_with_suggestion = items in unadorned `extern` blocks cannot have safety qualifiers
.suggestion = add unsafe to this `extern` block
ast_passes_extern_item_ascii = items in `extern` blocks cannot use non-ascii identifiers
Expand Down
16 changes: 9 additions & 7 deletions compiler/rustc_ast_passes/src/ast_validation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -459,13 +459,15 @@ impl<'a> AstValidator<'a> {
fn check_item_safety(&self, span: Span, safety: Safety) {
match self.extern_mod_safety {
Some(extern_safety) => {
if matches!(safety, Safety::Unsafe(_) | Safety::Safe(_))
&& (extern_safety == Safety::Default || !self.features.unsafe_extern_blocks)
{
self.dcx().emit_err(errors::InvalidSafetyOnExtern {
item_span: span,
block: self.current_extern_span().shrink_to_lo(),
});
if matches!(safety, Safety::Unsafe(_) | Safety::Safe(_)) {
if extern_safety == Safety::Default {
self.dcx().emit_err(errors::InvalidSafetyOnExternWithSuggestion {
item_span: span,
block: self.current_extern_span().shrink_to_lo(),
});
} else if !self.features.unsafe_extern_blocks {
self.dcx().emit_err(errors::InvalidSafetyOnExtern { item_span: span });
}
}
}
None => {
Expand Down
7 changes: 7 additions & 0 deletions compiler/rustc_ast_passes/src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,13 @@ pub enum ExternBlockSuggestion {
pub struct InvalidSafetyOnExtern {
#[primary_span]
pub item_span: Span,
}

#[derive(Diagnostic)]
#[diag(ast_passes_extern_invalid_safety_with_suggestion)]
pub struct InvalidSafetyOnExternWithSuggestion {
#[primary_span]
pub item_span: Span,
#[suggestion(code = "unsafe ", applicability = "machine-applicable", style = "verbose")]
pub block: Span,
}
Expand Down
5 changes: 0 additions & 5 deletions tests/ui/parser/unsafe-foreign-mod-2.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,6 @@ error: items in unadorned `extern` blocks cannot have safety qualifiers
|
LL | unsafe fn foo();
| ^^^^^^^^^^^^^^^^
|
help: add unsafe to this `extern` block
|
LL | unsafe extern "C" unsafe {
| ++++++

error: aborting due to 3 previous errors

0 comments on commit b18f6c6

Please sign in to comment.