Skip to content
Draft
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
10 changes: 3 additions & 7 deletions compiler/rustc_attr_parsing/src/attributes/codegen_attrs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -548,13 +548,9 @@ impl CombineAttributeParser for TargetFeatureParser {
// `#[target_feature]` is incompatible with lang item functions,
// except on WASM where calling target-feature functions is safe (see #84988).
if !cx.sess().target.is_like_wasm && !cx.sess().opts.actually_rustdoc {
// `#[panic_handler]` is checked first so it takes priority in the diagnostic.
let lang_kind = cx
.all_attrs
.iter()
.find_map(|a| [sym::panic_handler, sym::lang].into_iter().find(|&s| a.word_is(s)));
if let Some(kind) = lang_kind {
cx.emit_err(TargetFeatureOnLangItem { attr_span, kind, item_span: cx.target_span });
let is_lang_item = cx.all_attrs.iter().any(|a| a.word_is(sym::lang));
if is_lang_item {
cx.emit_err(TargetFeatureOnLangItem { attr_span, item_span: cx.target_span });
}
}
}
Expand Down
13 changes: 1 addition & 12 deletions compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -589,9 +589,7 @@ impl SingleAttributeParser for LangParser {
}

// Check the target
let allowed_targets: &[_] = if lang_item == LangItem::PanicImpl {
&[Allow(Target::Fn), Allow(Target::ForeignFn)]
} else if lang_item.is_weak_only() {
let allowed_targets: &[_] = if lang_item.is_weak_only() {
&[Allow(Target::ForeignFn)]
} else {
&[Allow(lang_item.target())]
Expand All @@ -617,15 +615,6 @@ impl NoArgsAttributeParser for RustcHasIncoherentInherentImplsParser {
const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::RustcHasIncoherentInherentImpls;
}

pub(crate) struct PanicHandlerParser;

impl NoArgsAttributeParser for PanicHandlerParser {
const PATH: &[Symbol] = &[sym::panic_handler];
const ALLOWED_TARGETS: AllowedTargets<'_> = AllowedTargets::AllowList(&[Allow(Target::Fn)]);
const STABILITY: AttributeStability = AttributeStability::Stable;
const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::Lang(LangItem::PanicImpl);
}

pub(crate) struct RustcNounwindParser;

impl NoArgsAttributeParser for RustcNounwindParser {
Expand Down
1 change: 0 additions & 1 deletion compiler/rustc_attr_parsing/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -262,7 +262,6 @@ attribute_parsers!(
Single<WithoutArgs<NoMangleParser>>,
Single<WithoutArgs<NoStdParser>>,
Single<WithoutArgs<NonExhaustiveParser>>,
Single<WithoutArgs<PanicHandlerParser>>,
Single<WithoutArgs<PanicRuntimeParser>>,
Single<WithoutArgs<PinV2Parser>>,
Single<WithoutArgs<PreludeImportParser>>,
Expand Down
15 changes: 2 additions & 13 deletions compiler/rustc_attr_parsing/src/session_diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,22 +81,11 @@ pub(crate) struct DocAttributeNotAttribute {
}

#[derive(Diagnostic)]
#[diag(
"`#[target_feature]` cannot be applied to a {$kind ->
[panic_handler] `#[panic_handler]`
*[other] lang item
} function"
)]
#[diag("`#[target_feature]` cannot be applied to a lang item function")]
pub(crate) struct TargetFeatureOnLangItem {
#[primary_span]
pub attr_span: Span,
pub kind: Symbol,
#[label(
"{$kind ->
[panic_handler] `#[panic_handler]`
*[other] lang item
} function is not allowed to have `#[target_feature]`"
)]
#[label("lang item function is not allowed to have `#[target_feature]`")]
pub item_span: Span,
}

Expand Down
7 changes: 7 additions & 0 deletions compiler/rustc_builtin_macros/src/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,13 @@ pub(crate) struct AllocErrorMustBeFn {
pub(crate) span: Span,
}

#[derive(Diagnostic)]
#[diag("panic_handler must be a function")]
pub(crate) struct PanicHandlerMustBeFn {
#[primary_span]
pub(crate) span: Span,
}

#[derive(Diagnostic)]
#[diag("macro requires a boolean expression as an argument")]
pub(crate) struct AssertRequiresBoolean {
Expand Down
3 changes: 3 additions & 0 deletions compiler/rustc_builtin_macros/src/eii.rs
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,9 @@ fn split_attrs(
foreign_item_attributes.push(attr.clone());
macro_attributes.push(attr);
}
Some(sym::rustc_diagnostic_item) => {
macro_attributes.push(attr.clone());
}
// Doc attributes should be forwarded to the macro and the foreign item, since those are
// the two items you interact with as a user.
// FIXME: idk yet how EIIs show up in docs, might want to customize
Expand Down
2 changes: 2 additions & 0 deletions compiler/rustc_builtin_macros/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ mod global_allocator;
mod iter;
mod log_syntax;
mod offload;
mod panic_handler;
mod pattern_type;
mod source_util;
mod test;
Expand Down Expand Up @@ -120,6 +121,7 @@ pub fn register_builtin_macros(resolver: &mut dyn ResolverExpand) {
eii_shared_macro: eii::eii_shared_macro,
global_allocator: global_allocator::expand,
offload_kernel: offload::expand_kernel,
panic_handler: panic_handler::expand,
test: test::expand_test,
test_case: test::expand_test_case,
unsafe_eii: eii::unsafe_eii,
Expand Down
43 changes: 43 additions & 0 deletions compiler/rustc_builtin_macros/src/panic_handler.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
use rustc_ast::{self as ast, AttrArgs, AttrItem, AttrItemKind, AttrStyle, Safety, StmtKind, attr};
use rustc_expand::base::{Annotatable, ExtCtxt};
use rustc_span::{Span, sym};

use crate::diagnostics;
use crate::util::check_builtin_macro_attribute;

pub(crate) fn expand(
ecx: &mut ExtCtxt<'_>,
span: Span,
meta_item: &ast::MetaItem,
mut item: Annotatable,
) -> Vec<Annotatable> {
check_builtin_macro_attribute(ecx, meta_item, sym::global_allocator);

// Allow using `#[panic_handler]` on an item statement
// FIXME - if we get deref patterns, use them to reduce duplication here
let attrs = if let Annotatable::Item(item) = &mut item {
&mut item.attrs
} else if let Annotatable::Stmt(stmt) = &mut item
&& let StmtKind::Item(item) = &mut stmt.kind
{
&mut item.attrs
} else {
ecx.dcx().emit_err(diagnostics::PanicHandlerMustBeFn { span: item.span() });
return vec![item];
};

attrs.push(attr::mk_attr_from_item(
&ecx.sess.psess.attr_id_generator,
AttrItem {
unsafety: Safety::Unsafe(span),
path: ecx.path_global(span, ecx.std_path(&[sym::panicking, sym::panic_handler])),
args: AttrItemKind::Unparsed(AttrArgs::Empty),
tokens: None,
},
None,
AttrStyle::Outer,
span,
));

vec![item]
}
14 changes: 14 additions & 0 deletions compiler/rustc_codegen_cranelift/example/mini_core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -835,6 +835,20 @@ struct PanicLocation {
column: u32,
}

#[track_caller]
#[lang = "panic_misaligned_pointer_dereference"] // needed by codegen for panic on misaligned pointer deref
#[rustc_nounwind] // `CheckAlignment` MIR pass requires this function to never unwind
fn panic_misaligned_pointer_dereference(_required: usize, _found: usize) -> ! {
loop {}
}

#[track_caller]
#[lang = "panic_null_pointer_dereference"] // needed by codegen for panic on null pointer deref
#[rustc_nounwind] // `CheckNull` MIR pass requires this function to never unwind
fn panic_null_pointer_dereference() -> ! {
loop {}
}

#[unsafe(no_mangle)]
#[cfg(not(all(windows, target_env = "gnu")))]
pub fn get_tls() -> u8 {
Expand Down
5 changes: 0 additions & 5 deletions compiler/rustc_codegen_gcc/example/alloc_example.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,6 @@ extern "C" {
fn puts(s: *const u8) -> i32;
}

#[panic_handler]
fn panic_handler(_: &core::panic::PanicInfo<'_>) -> ! {
core::intrinsics::abort();
}

#[alloc_error_handler]
fn alloc_error_handler(_: alloc::alloc::Layout) -> ! {
core::intrinsics::abort();
Expand Down
15 changes: 15 additions & 0 deletions compiler/rustc_codegen_gcc/example/mini_core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
extern_types,
decl_macro,
rustc_attrs,
rustc_private,
transparent_unions,
auto_traits,
freeze_impls,
Expand Down Expand Up @@ -572,6 +573,20 @@ fn panic_bounds_check(index: usize, len: usize) -> ! {
}
}

#[track_caller]
#[lang = "panic_misaligned_pointer_dereference"] // needed by codegen for panic on misaligned pointer deref
#[rustc_nounwind] // `CheckAlignment` MIR pass requires this function to never unwind
fn panic_misaligned_pointer_dereference(_required: usize, _found: usize) -> ! {
loop {}
}

#[track_caller]
#[lang = "panic_null_pointer_dereference"] // needed by codegen for panic on null pointer deref
#[rustc_nounwind] // `CheckNull` MIR pass requires this function to never unwind
fn panic_null_pointer_dereference() -> ! {
loop {}
}

#[lang = "eh_personality"]
fn eh_personality() -> ! {
loop {}
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_error_codes/src/error_codes/E0264.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ A list of available external lang items is available in
#![allow(internal_features)]

extern "C" {
#[lang = "panic_impl"] // ok!
#[lang = "eh_personality"] // ok!
fn cake();
}
```
1 change: 0 additions & 1 deletion compiler/rustc_feature/src/builtin_attrs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,6 @@ pub static BUILTIN_ATTRIBUTES: &[Symbol] = &[

// Runtime
sym::windows_subsystem,
sym::panic_handler, // RFC 2070

// Code generation:
sym::inline,
Expand Down
2 changes: 0 additions & 2 deletions compiler/rustc_hir/src/lang_items.rs
Original file line number Diff line number Diff line change
Expand Up @@ -284,9 +284,7 @@ language_item_table! {
ConstPanicFmt, sym::const_panic_fmt, const_panic_fmt, Target::Fn, GenericRequirement::None;
PanicBoundsCheck, sym::panic_bounds_check, panic_bounds_check_fn, Target::Fn, GenericRequirement::Exact(0);
PanicMisalignedPointerDereference, sym::panic_misaligned_pointer_dereference, panic_misaligned_pointer_dereference_fn, Target::Fn, GenericRequirement::Exact(0);
PanicInfo, sym::panic_info, panic_info, Target::Struct, GenericRequirement::None;
PanicLocation, sym::panic_location, panic_location, Target::Struct, GenericRequirement::None;
PanicImpl, sym::panic_impl, panic_impl, Target::Fn, GenericRequirement::None;
PanicCannotUnwind, sym::panic_cannot_unwind, panic_cannot_unwind, Target::Fn, GenericRequirement::Exact(0);
PanicInCleanup, sym::panic_in_cleanup, panic_in_cleanup, Target::Fn, GenericRequirement::Exact(0);
/// Constant panic messages, used for codegen of MIR asserts.
Expand Down
1 change: 0 additions & 1 deletion compiler/rustc_hir/src/weak_lang_items.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@ macro_rules! weak_only_lang_items {
}

weak_lang_items! {
PanicImpl, rust_begin_unwind;
EhPersonality, rust_eh_personality;
}

Expand Down
63 changes: 0 additions & 63 deletions compiler/rustc_hir_typeck/src/check.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use std::cell::RefCell;

use rustc_hir as hir;
use rustc_hir::def::DefKind;
use rustc_hir::lang_items::LangItem;
use rustc_hir_analysis::check::check_function_signature;
use rustc_infer::infer::RegionVariableOrigin;
Expand Down Expand Up @@ -149,75 +148,13 @@ pub(super) fn check_fn<'a, 'tcx>(
// we have a recursive call site and do the sadly stabilized fallback to `()`.
fcx.demand_suptype(span, ret_ty, actual_return_ty);

// Check that a function marked as `#[panic_handler]` has signature `fn(&PanicInfo) -> !`
if tcx.is_lang_item(fn_def_id.to_def_id(), LangItem::PanicImpl) {
check_panic_info_fn(tcx, fn_def_id, fn_sig);
}

if tcx.is_lang_item(fn_def_id.to_def_id(), LangItem::Start) {
check_lang_start_fn(tcx, fn_sig, fn_def_id);
}

fcx.coroutine_types
}

fn check_panic_info_fn(tcx: TyCtxt<'_>, fn_id: LocalDefId, fn_sig: ty::FnSig<'_>) {
let span = tcx.def_span(fn_id);

let DefKind::Fn = tcx.def_kind(fn_id) else {
tcx.dcx().span_err(span, "should be a function");
return;
};

let generic_counts = tcx.generics_of(fn_id).own_counts();
if generic_counts.types != 0 {
tcx.dcx().span_err(span, "should have no type parameters");
}
if generic_counts.consts != 0 {
tcx.dcx().span_err(span, "should have no const parameters");
}

let panic_info_did = tcx.require_lang_item(hir::LangItem::PanicInfo, span);

// build type `for<'a, 'b> fn(&'a PanicInfo<'b>) -> !`
let panic_info_ty = tcx
.type_of(panic_info_did)
.instantiate(
tcx,
&[ty::GenericArg::from(ty::Region::new_bound(
tcx,
ty::INNERMOST,
ty::BoundRegion { var: ty::BoundVar::from_u32(1), kind: ty::BoundRegionKind::Anon },
))],
)
.skip_norm_wip();
let panic_info_ref_ty = Ty::new_imm_ref(
tcx,
ty::Region::new_bound(
tcx,
ty::INNERMOST,
ty::BoundRegion { var: ty::BoundVar::ZERO, kind: ty::BoundRegionKind::Anon },
),
panic_info_ty,
);

let bounds = tcx.mk_bound_variable_kinds(&[
ty::BoundVariableKind::Region(ty::BoundRegionKind::Anon),
ty::BoundVariableKind::Region(ty::BoundRegionKind::Anon),
]);
let expected_sig = ty::Binder::bind_with_vars(
tcx.mk_fn_sig_rust_abi([panic_info_ref_ty], tcx.types.never, fn_sig.safety()),
bounds,
);

let _ = check_function_signature(
tcx,
ObligationCause::new(span, fn_id, ObligationCauseCode::LangFunctionType(sym::panic_impl)),
fn_id.into(),
expected_sig,
);
}

fn check_lang_start_fn<'tcx>(tcx: TyCtxt<'tcx>, fn_sig: ty::FnSig<'tcx>, def_id: LocalDefId) {
// build type `fn(main: fn() -> T, argc: isize, argv: *const *const u8, sigpipe: u8)`

Expand Down
3 changes: 1 addition & 2 deletions compiler/rustc_metadata/src/rmeta/decoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -774,10 +774,9 @@ impl MetadataBlob {
)?;
writeln!(
out,
"has_global_allocator {} has_alloc_error_handler {} has_panic_handler {} has_default_lib_allocator {}",
"has_global_allocator {} has_alloc_error_handler {} has_default_lib_allocator {}",
root.has_global_allocator,
root.has_alloc_error_handler,
root.has_panic_handler,
root.has_default_lib_allocator
)?;
writeln!(
Expand Down
2 changes: 0 additions & 2 deletions compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -332,8 +332,6 @@ provide! { tcx, def_id, other, cdata,
has_global_allocator => { cdata.root.has_global_allocator }
// FIXME: to be replaced with externally_implementable_items below
has_alloc_error_handler => { cdata.root.has_alloc_error_handler }
// FIXME: to be replaced with externally_implementable_items below
has_panic_handler => { cdata.root.has_panic_handler }

externally_implementable_items => {
cdata.get_externally_implementable_items(tcx)
Expand Down
1 change: 0 additions & 1 deletion compiler/rustc_metadata/src/rmeta/encoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -737,7 +737,6 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
edition: tcx.sess.edition(),
has_global_allocator: tcx.has_global_allocator(LOCAL_CRATE),
has_alloc_error_handler: tcx.has_alloc_error_handler(LOCAL_CRATE),
has_panic_handler: tcx.has_panic_handler(LOCAL_CRATE),
has_default_lib_allocator: find_attr!(attrs, DefaultLibAllocator),
externally_implementable_items,
proc_macro_data,
Expand Down
1 change: 0 additions & 1 deletion compiler/rustc_metadata/src/rmeta/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -257,7 +257,6 @@ pub(crate) struct CrateRoot {
edition: Edition,
has_global_allocator: bool,
has_alloc_error_handler: bool,
has_panic_handler: bool,
has_default_lib_allocator: bool,
externally_implementable_items: LazyArray<EiiMapEncodedKeyValue>,

Expand Down
5 changes: 3 additions & 2 deletions compiler/rustc_middle/src/middle/lang_items.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,8 +113,9 @@ pub fn required(tcx: TyCtxt<'_>, lang_item: LangItem) -> bool {
// symbol. Other panic runtimes ensure that the relevant symbols are
// available to link things together, but they're never exercised.
match tcx.sess.panic_strategy() {
PanicStrategy::Abort => lang_item != LangItem::EhPersonality,
PanicStrategy::Abort | PanicStrategy::ImmediateAbort => {
lang_item != LangItem::EhPersonality
}
PanicStrategy::Unwind => true,
PanicStrategy::ImmediateAbort => false,
}
}
Loading
Loading