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 numberDiff line numberDiff line change
Expand Up@@ -566,13 +566,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
9 changes: 0 additions & 9 deletions compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -639,15 +639,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 numberDiff line numberDiff line change
Expand Up@@ -285,7 +285,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
29 changes: 4 additions & 25 deletions compiler/rustc_attr_parsing/src/session_diagnostics.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -108,42 +108,21 @@ 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,
}

#[derive(Diagnostic)]
#[diag(
"{$name ->
[panic_impl] `#[panic_handler]`
*[other] `{$name}` lang item
} function is not allowed to have `#[track_caller]`"
)]
#[diag("`{$name}` lang item function is not allowed to have `#[track_caller]`")]
pub(crate) struct TrackCallerOnLangItem {
#[primary_span]
pub attr_span: Span,
pub name: Symbol,
#[label(
"{$name ->
[panic_impl] `#[panic_handler]`
*[other] `{$name}` lang item
} function is not allowed to have `#[track_caller]`"
)]
#[label("`{$name}` lang item function is not allowed to have `#[track_caller]`")]
pub sig_span: Span,
}

Expand Down
7 changes: 7 additions & 0 deletions compiler/rustc_builtin_macros/src/diagnostics.rs
Original file line numberDiff line numberDiff 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 numberDiff line numberDiff line change
Expand Up@@ -226,6 +226,9 @@ fn split_attrs(
Some(sym::track_caller) => {
foreign_item_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 numberDiff line numberDiff line change
Expand Up@@ -44,6 +44,7 @@ mod global_allocator;
mod iter;
mod log_syntax;
mod offload;
mod panic_handler;
mod pattern_type;
mod source_util;
mod test;
Expand DownExpand Up@@ -122,6 +123,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 numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
use rustc_ast::{self as ast, AttrArgs, AttrItem, 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::Default,
path: ecx.path_global(span, ecx.std_path(&[sym::panicking, sym::panic_handler])),
args: AttrArgs::Empty,
span,
},
None,
AttrStyle::Outer,
span,
));

vec![item]
}
14 changes: 14 additions & 0 deletions compiler/rustc_codegen_cranelift/example/mini_core.rs
Original file line numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff line change
Expand Up@@ -6,6 +6,7 @@
extern_types,
decl_macro,
rustc_attrs,
rustc_private,
transparent_unions,
auto_traits,
freeze_impls,
Expand DownExpand 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff line change
Expand Up@@ -292,9 +292,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::ForeignFn, 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 numberDiff line numberDiff line change
Expand Up@@ -24,6 +24,5 @@ macro_rules! weak_lang_items {
}

weak_lang_items! {
PanicImpl, rust_begin_unwind;
EhPersonality, rust_eh_personality;
}
63 changes: 0 additions & 63 deletions compiler/rustc_hir_typeck/src/check.rs
Original file line numberDiff line numberDiff 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 DownExpand 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 numberDiff line numberDiff line change
Expand Up@@ -781,10 +781,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 numberDiff line numberDiff line change
Expand Up@@ -341,8 +341,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 numberDiff line numberDiff line change
Expand Up@@ -740,7 +740,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 numberDiff line numberDiff 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
4 changes: 0 additions & 4 deletions compiler/rustc_middle/src/queries.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1834,10 +1834,6 @@ rustc_queries! {
desc { "checking if the crate has_alloc_error_handler" }
separate_provide_extern
}
query has_panic_handler(_: CrateNum) -> bool {
desc { "checking if the crate has_panic_handler" }
separate_provide_extern
}
query is_profiler_runtime(_: CrateNum) -> bool {
desc { "checking if a crate is `#![profiler_runtime]`" }
separate_provide_extern
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Use EII for #[panic_handler] by bjorn3 · Pull Request #159016 · rust-lang/rust · GitHub
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 numberDiff line numberDiff line change
Expand Up@@ -566,13 +566,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
9 changes: 0 additions & 9 deletions compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -639,15 +639,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 numberDiff line numberDiff line change
Expand Up@@ -285,7 +285,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
29 changes: 4 additions & 25 deletions compiler/rustc_attr_parsing/src/session_diagnostics.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -108,42 +108,21 @@ 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,
}

#[derive(Diagnostic)]
#[diag(
"{$name ->
[panic_impl] `#[panic_handler]`
*[other] `{$name}` lang item
} function is not allowed to have `#[track_caller]`"
)]
#[diag("`{$name}` lang item function is not allowed to have `#[track_caller]`")]
pub(crate) struct TrackCallerOnLangItem {
#[primary_span]
pub attr_span: Span,
pub name: Symbol,
#[label(
"{$name ->
[panic_impl] `#[panic_handler]`
*[other] `{$name}` lang item
} function is not allowed to have `#[track_caller]`"
)]
#[label("`{$name}` lang item function is not allowed to have `#[track_caller]`")]
pub sig_span: Span,
}

Expand Down
7 changes: 7 additions & 0 deletions compiler/rustc_builtin_macros/src/diagnostics.rs
Original file line numberDiff line numberDiff 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 numberDiff line numberDiff line change
Expand Up@@ -226,6 +226,9 @@ fn split_attrs(
Some(sym::track_caller) => {
foreign_item_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 numberDiff line numberDiff line change
Expand Up@@ -44,6 +44,7 @@ mod global_allocator;
mod iter;
mod log_syntax;
mod offload;
mod panic_handler;
mod pattern_type;
mod source_util;
mod test;
Expand DownExpand Up@@ -122,6 +123,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 numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
use rustc_ast::{self as ast, AttrArgs, AttrItem, 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::Default,
path: ecx.path_global(span, ecx.std_path(&[sym::panicking, sym::panic_handler])),
args: AttrArgs::Empty,
span,
},
None,
AttrStyle::Outer,
span,
));

vec![item]
}
14 changes: 14 additions & 0 deletions compiler/rustc_codegen_cranelift/example/mini_core.rs
Original file line numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff line change
Expand Up@@ -6,6 +6,7 @@
extern_types,
decl_macro,
rustc_attrs,
rustc_private,
transparent_unions,
auto_traits,
freeze_impls,
Expand DownExpand 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff line change
Expand Up@@ -292,9 +292,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::ForeignFn, 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 numberDiff line numberDiff line change
Expand Up@@ -24,6 +24,5 @@ macro_rules! weak_lang_items {
}

weak_lang_items! {
PanicImpl, rust_begin_unwind;
EhPersonality, rust_eh_personality;
}
63 changes: 0 additions & 63 deletions compiler/rustc_hir_typeck/src/check.rs
Original file line numberDiff line numberDiff 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 DownExpand 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 numberDiff line numberDiff line change
Expand Up@@ -781,10 +781,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 numberDiff line numberDiff line change
Expand Up@@ -341,8 +341,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 numberDiff line numberDiff line change
Expand Up@@ -740,7 +740,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 numberDiff line numberDiff 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
4 changes: 0 additions & 4 deletions compiler/rustc_middle/src/queries.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1834,10 +1834,6 @@ rustc_queries! {
desc { "checking if the crate has_alloc_error_handler" }
separate_provide_extern
}
query has_panic_handler(_: CrateNum) -> bool {
desc { "checking if the crate has_panic_handler" }
separate_provide_extern
}
query is_profiler_runtime(_: CrateNum) -> bool {
desc { "checking if a crate is `#![profiler_runtime]`" }
separate_provide_extern
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Use EII for #[panic_handler] by bjorn3 · Pull Request #159016 · rust-lang/rust · GitHub
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 numberDiff line numberDiff line change
Expand Up@@ -566,13 +566,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
9 changes: 0 additions & 9 deletions compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -639,15 +639,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 numberDiff line numberDiff line change
Expand Up@@ -285,7 +285,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
29 changes: 4 additions & 25 deletions compiler/rustc_attr_parsing/src/session_diagnostics.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -108,42 +108,21 @@ 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,
}

#[derive(Diagnostic)]
#[diag(
"{$name ->
[panic_impl] `#[panic_handler]`
*[other] `{$name}` lang item
} function is not allowed to have `#[track_caller]`"
)]
#[diag("`{$name}` lang item function is not allowed to have `#[track_caller]`")]
pub(crate) struct TrackCallerOnLangItem {
#[primary_span]
pub attr_span: Span,
pub name: Symbol,
#[label(
"{$name ->
[panic_impl] `#[panic_handler]`
*[other] `{$name}` lang item
} function is not allowed to have `#[track_caller]`"
)]
#[label("`{$name}` lang item function is not allowed to have `#[track_caller]`")]
pub sig_span: Span,
}

Expand Down
7 changes: 7 additions & 0 deletions compiler/rustc_builtin_macros/src/diagnostics.rs
Original file line numberDiff line numberDiff 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 numberDiff line numberDiff line change
Expand Up@@ -226,6 +226,9 @@ fn split_attrs(
Some(sym::track_caller) => {
foreign_item_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 numberDiff line numberDiff line change
Expand Up@@ -44,6 +44,7 @@ mod global_allocator;
mod iter;
mod log_syntax;
mod offload;
mod panic_handler;
mod pattern_type;
mod source_util;
mod test;
Expand DownExpand Up@@ -122,6 +123,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 numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
use rustc_ast::{self as ast, AttrArgs, AttrItem, 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::Default,
path: ecx.path_global(span, ecx.std_path(&[sym::panicking, sym::panic_handler])),
args: AttrArgs::Empty,
span,
},
None,
AttrStyle::Outer,
span,
));

vec![item]
}
14 changes: 14 additions & 0 deletions compiler/rustc_codegen_cranelift/example/mini_core.rs
Original file line numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff line change
Expand Up@@ -6,6 +6,7 @@
extern_types,
decl_macro,
rustc_attrs,
rustc_private,
transparent_unions,
auto_traits,
freeze_impls,
Expand DownExpand 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff line change
Expand Up@@ -292,9 +292,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::ForeignFn, 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 numberDiff line numberDiff line change
Expand Up@@ -24,6 +24,5 @@ macro_rules! weak_lang_items {
}

weak_lang_items! {
PanicImpl, rust_begin_unwind;
EhPersonality, rust_eh_personality;
}
63 changes: 0 additions & 63 deletions compiler/rustc_hir_typeck/src/check.rs
Original file line numberDiff line numberDiff 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 DownExpand 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 numberDiff line numberDiff line change
Expand Up@@ -781,10 +781,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 numberDiff line numberDiff line change
Expand Up@@ -341,8 +341,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 numberDiff line numberDiff line change
Expand Up@@ -740,7 +740,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 numberDiff line numberDiff 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
4 changes: 0 additions & 4 deletions compiler/rustc_middle/src/queries.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1834,10 +1834,6 @@ rustc_queries! {
desc { "checking if the crate has_alloc_error_handler" }
separate_provide_extern
}
query has_panic_handler(_: CrateNum) -> bool {
desc { "checking if the crate has_panic_handler" }
separate_provide_extern
}
query is_profiler_runtime(_: CrateNum) -> bool {
desc { "checking if a crate is `#![profiler_runtime]`" }
separate_provide_extern
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Use EII for #[panic_handler] by bjorn3 · Pull Request #159016 · rust-lang/rust · GitHub
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 numberDiff line numberDiff line change
Expand Up@@ -566,13 +566,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
9 changes: 0 additions & 9 deletions compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -639,15 +639,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 numberDiff line numberDiff line change
Expand Up@@ -285,7 +285,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
29 changes: 4 additions & 25 deletions compiler/rustc_attr_parsing/src/session_diagnostics.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -108,42 +108,21 @@ 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,
}

#[derive(Diagnostic)]
#[diag(
"{$name ->
[panic_impl] `#[panic_handler]`
*[other] `{$name}` lang item
} function is not allowed to have `#[track_caller]`"
)]
#[diag("`{$name}` lang item function is not allowed to have `#[track_caller]`")]
pub(crate) struct TrackCallerOnLangItem {
#[primary_span]
pub attr_span: Span,
pub name: Symbol,
#[label(
"{$name ->
[panic_impl] `#[panic_handler]`
*[other] `{$name}` lang item
} function is not allowed to have `#[track_caller]`"
)]
#[label("`{$name}` lang item function is not allowed to have `#[track_caller]`")]
pub sig_span: Span,
}

Expand Down
7 changes: 7 additions & 0 deletions compiler/rustc_builtin_macros/src/diagnostics.rs
Original file line numberDiff line numberDiff 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 numberDiff line numberDiff line change
Expand Up@@ -226,6 +226,9 @@ fn split_attrs(
Some(sym::track_caller) => {
foreign_item_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 numberDiff line numberDiff line change
Expand Up@@ -44,6 +44,7 @@ mod global_allocator;
mod iter;
mod log_syntax;
mod offload;
mod panic_handler;
mod pattern_type;
mod source_util;
mod test;
Expand DownExpand Up@@ -122,6 +123,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 numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
use rustc_ast::{self as ast, AttrArgs, AttrItem, 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::Default,
path: ecx.path_global(span, ecx.std_path(&[sym::panicking, sym::panic_handler])),
args: AttrArgs::Empty,
span,
},
None,
AttrStyle::Outer,
span,
));

vec![item]
}
14 changes: 14 additions & 0 deletions compiler/rustc_codegen_cranelift/example/mini_core.rs
Original file line numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff line change
Expand Up@@ -6,6 +6,7 @@
extern_types,
decl_macro,
rustc_attrs,
rustc_private,
transparent_unions,
auto_traits,
freeze_impls,
Expand DownExpand 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff line change
Expand Up@@ -292,9 +292,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::ForeignFn, 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 numberDiff line numberDiff line change
Expand Up@@ -24,6 +24,5 @@ macro_rules! weak_lang_items {
}

weak_lang_items! {
PanicImpl, rust_begin_unwind;
EhPersonality, rust_eh_personality;
}
63 changes: 0 additions & 63 deletions compiler/rustc_hir_typeck/src/check.rs
Original file line numberDiff line numberDiff 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 DownExpand 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 numberDiff line numberDiff line change
Expand Up@@ -781,10 +781,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 numberDiff line numberDiff line change
Expand Up@@ -341,8 +341,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 numberDiff line numberDiff line change
Expand Up@@ -740,7 +740,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 numberDiff line numberDiff 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
4 changes: 0 additions & 4 deletions compiler/rustc_middle/src/queries.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1834,10 +1834,6 @@ rustc_queries! {
desc { "checking if the crate has_alloc_error_handler" }
separate_provide_extern
}
query has_panic_handler(_: CrateNum) -> bool {
desc { "checking if the crate has_panic_handler" }
separate_provide_extern
}
query is_profiler_runtime(_: CrateNum) -> bool {
desc { "checking if a crate is `#![profiler_runtime]`" }
separate_provide_extern
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' Use EII for #[panic_handler] by bjorn3 · Pull Request #159016 · rust-lang/rust · GitHub
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 numberDiff line numberDiff line change
Expand Up@@ -566,13 +566,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
9 changes: 0 additions & 9 deletions compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -639,15 +639,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 numberDiff line numberDiff line change
Expand Up@@ -285,7 +285,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
29 changes: 4 additions & 25 deletions compiler/rustc_attr_parsing/src/session_diagnostics.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -108,42 +108,21 @@ 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,
}

#[derive(Diagnostic)]
#[diag(
"{$name ->
[panic_impl] `#[panic_handler]`
*[other] `{$name}` lang item
} function is not allowed to have `#[track_caller]`"
)]
#[diag("`{$name}` lang item function is not allowed to have `#[track_caller]`")]
pub(crate) struct TrackCallerOnLangItem {
#[primary_span]
pub attr_span: Span,
pub name: Symbol,
#[label(
"{$name ->
[panic_impl] `#[panic_handler]`
*[other] `{$name}` lang item
} function is not allowed to have `#[track_caller]`"
)]
#[label("`{$name}` lang item function is not allowed to have `#[track_caller]`")]
pub sig_span: Span,
}

Expand Down
7 changes: 7 additions & 0 deletions compiler/rustc_builtin_macros/src/diagnostics.rs
Original file line numberDiff line numberDiff 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 numberDiff line numberDiff line change
Expand Up@@ -226,6 +226,9 @@ fn split_attrs(
Some(sym::track_caller) => {
foreign_item_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 numberDiff line numberDiff line change
Expand Up@@ -44,6 +44,7 @@ mod global_allocator;
mod iter;
mod log_syntax;
mod offload;
mod panic_handler;
mod pattern_type;
mod source_util;
mod test;
Expand DownExpand Up@@ -122,6 +123,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 numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
use rustc_ast::{self as ast, AttrArgs, AttrItem, 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::Default,
path: ecx.path_global(span, ecx.std_path(&[sym::panicking, sym::panic_handler])),
args: AttrArgs::Empty,
span,
},
None,
AttrStyle::Outer,
span,
));

vec![item]
}
14 changes: 14 additions & 0 deletions compiler/rustc_codegen_cranelift/example/mini_core.rs
Original file line numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff line change
Expand Up@@ -6,6 +6,7 @@
extern_types,
decl_macro,
rustc_attrs,
rustc_private,
transparent_unions,
auto_traits,
freeze_impls,
Expand DownExpand 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff line change
Expand Up@@ -292,9 +292,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::ForeignFn, 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 numberDiff line numberDiff line change
Expand Up@@ -24,6 +24,5 @@ macro_rules! weak_lang_items {
}

weak_lang_items! {
PanicImpl, rust_begin_unwind;
EhPersonality, rust_eh_personality;
}
63 changes: 0 additions & 63 deletions compiler/rustc_hir_typeck/src/check.rs
Original file line numberDiff line numberDiff 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 DownExpand 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 numberDiff line numberDiff line change
Expand Up@@ -781,10 +781,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 numberDiff line numberDiff line change
Expand Up@@ -341,8 +341,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 numberDiff line numberDiff line change
Expand Up@@ -740,7 +740,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 numberDiff line numberDiff 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
4 changes: 0 additions & 4 deletions compiler/rustc_middle/src/queries.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1834,10 +1834,6 @@ rustc_queries! {
desc { "checking if the crate has_alloc_error_handler" }
separate_provide_extern
}
query has_panic_handler(_: CrateNum) -> bool {
desc { "checking if the crate has_panic_handler" }
separate_provide_extern
}
query is_profiler_runtime(_: CrateNum) -> bool {
desc { "checking if a crate is `#![profiler_runtime]`" }
separate_provide_extern
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Use EII for #[panic_handler] by bjorn3 · Pull Request #159016 · rust-lang/rust · GitHub
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 numberDiff line numberDiff line change
Expand Up@@ -566,13 +566,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
9 changes: 0 additions & 9 deletions compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -639,15 +639,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 numberDiff line numberDiff line change
Expand Up@@ -285,7 +285,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
29 changes: 4 additions & 25 deletions compiler/rustc_attr_parsing/src/session_diagnostics.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -108,42 +108,21 @@ 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,
}

#[derive(Diagnostic)]
#[diag(
"{$name ->
[panic_impl] `#[panic_handler]`
*[other] `{$name}` lang item
} function is not allowed to have `#[track_caller]`"
)]
#[diag("`{$name}` lang item function is not allowed to have `#[track_caller]`")]
pub(crate) struct TrackCallerOnLangItem {
#[primary_span]
pub attr_span: Span,
pub name: Symbol,
#[label(
"{$name ->
[panic_impl] `#[panic_handler]`
*[other] `{$name}` lang item
} function is not allowed to have `#[track_caller]`"
)]
#[label("`{$name}` lang item function is not allowed to have `#[track_caller]`")]
pub sig_span: Span,
}

Expand Down
7 changes: 7 additions & 0 deletions compiler/rustc_builtin_macros/src/diagnostics.rs
Original file line numberDiff line numberDiff 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 numberDiff line numberDiff line change
Expand Up@@ -226,6 +226,9 @@ fn split_attrs(
Some(sym::track_caller) => {
foreign_item_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 numberDiff line numberDiff line change
Expand Up@@ -44,6 +44,7 @@ mod global_allocator;
mod iter;
mod log_syntax;
mod offload;
mod panic_handler;
mod pattern_type;
mod source_util;
mod test;
Expand DownExpand Up@@ -122,6 +123,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 numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
use rustc_ast::{self as ast, AttrArgs, AttrItem, 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::Default,
path: ecx.path_global(span, ecx.std_path(&[sym::panicking, sym::panic_handler])),
args: AttrArgs::Empty,
span,
},
None,
AttrStyle::Outer,
span,
));

vec![item]
}
14 changes: 14 additions & 0 deletions compiler/rustc_codegen_cranelift/example/mini_core.rs
Original file line numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff line change
Expand Up@@ -6,6 +6,7 @@
extern_types,
decl_macro,
rustc_attrs,
rustc_private,
transparent_unions,
auto_traits,
freeze_impls,
Expand DownExpand 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff line change
Expand Up@@ -292,9 +292,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::ForeignFn, 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 numberDiff line numberDiff line change
Expand Up@@ -24,6 +24,5 @@ macro_rules! weak_lang_items {
}

weak_lang_items! {
PanicImpl, rust_begin_unwind;
EhPersonality, rust_eh_personality;
}
63 changes: 0 additions & 63 deletions compiler/rustc_hir_typeck/src/check.rs
Original file line numberDiff line numberDiff 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 DownExpand 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 numberDiff line numberDiff line change
Expand Up@@ -781,10 +781,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 numberDiff line numberDiff line change
Expand Up@@ -341,8 +341,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 numberDiff line numberDiff line change
Expand Up@@ -740,7 +740,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 numberDiff line numberDiff 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
4 changes: 0 additions & 4 deletions compiler/rustc_middle/src/queries.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1834,10 +1834,6 @@ rustc_queries! {
desc { "checking if the crate has_alloc_error_handler" }
separate_provide_extern
}
query has_panic_handler(_: CrateNum) -> bool {
desc { "checking if the crate has_panic_handler" }
separate_provide_extern
}
query is_profiler_runtime(_: CrateNum) -> bool {
desc { "checking if a crate is `#![profiler_runtime]`" }
separate_provide_extern
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Use EII for #[panic_handler] by bjorn3 · Pull Request #159016 · rust-lang/rust · GitHub
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 numberDiff line numberDiff line change
Expand Up@@ -566,13 +566,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
9 changes: 0 additions & 9 deletions compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -639,15 +639,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 numberDiff line numberDiff line change
Expand Up@@ -285,7 +285,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
29 changes: 4 additions & 25 deletions compiler/rustc_attr_parsing/src/session_diagnostics.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -108,42 +108,21 @@ 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,
}

#[derive(Diagnostic)]
#[diag(
"{$name ->
[panic_impl] `#[panic_handler]`
*[other] `{$name}` lang item
} function is not allowed to have `#[track_caller]`"
)]
#[diag("`{$name}` lang item function is not allowed to have `#[track_caller]`")]
pub(crate) struct TrackCallerOnLangItem {
#[primary_span]
pub attr_span: Span,
pub name: Symbol,
#[label(
"{$name ->
[panic_impl] `#[panic_handler]`
*[other] `{$name}` lang item
} function is not allowed to have `#[track_caller]`"
)]
#[label("`{$name}` lang item function is not allowed to have `#[track_caller]`")]
pub sig_span: Span,
}

Expand Down
7 changes: 7 additions & 0 deletions compiler/rustc_builtin_macros/src/diagnostics.rs
Original file line numberDiff line numberDiff 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 numberDiff line numberDiff line change
Expand Up@@ -226,6 +226,9 @@ fn split_attrs(
Some(sym::track_caller) => {
foreign_item_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 numberDiff line numberDiff line change
Expand Up@@ -44,6 +44,7 @@ mod global_allocator;
mod iter;
mod log_syntax;
mod offload;
mod panic_handler;
mod pattern_type;
mod source_util;
mod test;
Expand DownExpand Up@@ -122,6 +123,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 numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
use rustc_ast::{self as ast, AttrArgs, AttrItem, 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::Default,
path: ecx.path_global(span, ecx.std_path(&[sym::panicking, sym::panic_handler])),
args: AttrArgs::Empty,
span,
},
None,
AttrStyle::Outer,
span,
));

vec![item]
}
14 changes: 14 additions & 0 deletions compiler/rustc_codegen_cranelift/example/mini_core.rs
Original file line numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff line change
Expand Up@@ -6,6 +6,7 @@
extern_types,
decl_macro,
rustc_attrs,
rustc_private,
transparent_unions,
auto_traits,
freeze_impls,
Expand DownExpand 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff line change
Expand Up@@ -292,9 +292,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::ForeignFn, 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 numberDiff line numberDiff line change
Expand Up@@ -24,6 +24,5 @@ macro_rules! weak_lang_items {
}

weak_lang_items! {
PanicImpl, rust_begin_unwind;
EhPersonality, rust_eh_personality;
}
63 changes: 0 additions & 63 deletions compiler/rustc_hir_typeck/src/check.rs
Original file line numberDiff line numberDiff 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 DownExpand 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 numberDiff line numberDiff line change
Expand Up@@ -781,10 +781,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 numberDiff line numberDiff line change
Expand Up@@ -341,8 +341,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 numberDiff line numberDiff line change
Expand Up@@ -740,7 +740,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 numberDiff line numberDiff 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
4 changes: 0 additions & 4 deletions compiler/rustc_middle/src/queries.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1834,10 +1834,6 @@ rustc_queries! {
desc { "checking if the crate has_alloc_error_handler" }
separate_provide_extern
}
query has_panic_handler(_: CrateNum) -> bool {
desc { "checking if the crate has_panic_handler" }
separate_provide_extern
}
query is_profiler_runtime(_: CrateNum) -> bool {
desc { "checking if a crate is `#![profiler_runtime]`" }
separate_provide_extern
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })(); Use EII for #[panic_handler] by bjorn3 · Pull Request #159016 · rust-lang/rust · GitHub
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 numberDiff line numberDiff line change
Expand Up@@ -566,13 +566,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
9 changes: 0 additions & 9 deletions compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -639,15 +639,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 numberDiff line numberDiff line change
Expand Up@@ -285,7 +285,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
29 changes: 4 additions & 25 deletions compiler/rustc_attr_parsing/src/session_diagnostics.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -108,42 +108,21 @@ 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,
}

#[derive(Diagnostic)]
#[diag(
"{$name ->
[panic_impl] `#[panic_handler]`
*[other] `{$name}` lang item
} function is not allowed to have `#[track_caller]`"
)]
#[diag("`{$name}` lang item function is not allowed to have `#[track_caller]`")]
pub(crate) struct TrackCallerOnLangItem {
#[primary_span]
pub attr_span: Span,
pub name: Symbol,
#[label(
"{$name ->
[panic_impl] `#[panic_handler]`
*[other] `{$name}` lang item
} function is not allowed to have `#[track_caller]`"
)]
#[label("`{$name}` lang item function is not allowed to have `#[track_caller]`")]
pub sig_span: Span,
}

Expand Down
7 changes: 7 additions & 0 deletions compiler/rustc_builtin_macros/src/diagnostics.rs
Original file line numberDiff line numberDiff 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 numberDiff line numberDiff line change
Expand Up@@ -226,6 +226,9 @@ fn split_attrs(
Some(sym::track_caller) => {
foreign_item_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 numberDiff line numberDiff line change
Expand Up@@ -44,6 +44,7 @@ mod global_allocator;
mod iter;
mod log_syntax;
mod offload;
mod panic_handler;
mod pattern_type;
mod source_util;
mod test;
Expand DownExpand Up@@ -122,6 +123,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 numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
use rustc_ast::{self as ast, AttrArgs, AttrItem, 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::Default,
path: ecx.path_global(span, ecx.std_path(&[sym::panicking, sym::panic_handler])),
args: AttrArgs::Empty,
span,
},
None,
AttrStyle::Outer,
span,
));

vec![item]
}
14 changes: 14 additions & 0 deletions compiler/rustc_codegen_cranelift/example/mini_core.rs
Original file line numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff line change
Expand Up@@ -6,6 +6,7 @@
extern_types,
decl_macro,
rustc_attrs,
rustc_private,
transparent_unions,
auto_traits,
freeze_impls,
Expand DownExpand 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff line change
Expand Up@@ -292,9 +292,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::ForeignFn, 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 numberDiff line numberDiff line change
Expand Up@@ -24,6 +24,5 @@ macro_rules! weak_lang_items {
}

weak_lang_items! {
PanicImpl, rust_begin_unwind;
EhPersonality, rust_eh_personality;
}
63 changes: 0 additions & 63 deletions compiler/rustc_hir_typeck/src/check.rs
Original file line numberDiff line numberDiff 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 DownExpand 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 numberDiff line numberDiff line change
Expand Up@@ -781,10 +781,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 numberDiff line numberDiff line change
Expand Up@@ -341,8 +341,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 numberDiff line numberDiff line change
Expand Up@@ -740,7 +740,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 numberDiff line numberDiff 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
4 changes: 0 additions & 4 deletions compiler/rustc_middle/src/queries.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1834,10 +1834,6 @@ rustc_queries! {
desc { "checking if the crate has_alloc_error_handler" }
separate_provide_extern
}
query has_panic_handler(_: CrateNum) -> bool {
desc { "checking if the crate has_panic_handler" }
separate_provide_extern
}
query is_profiler_runtime(_: CrateNum) -> bool {
desc { "checking if a crate is `#![profiler_runtime]`" }
separate_provide_extern
Expand Down
Loading
Loading