Skip to content

Commit 8954863

Browse files
committed
Auto merge of rust-lang#157504 - jhpratt:rollup-cOVIb3M, r=jhpratt
Rollup of 12 pull requests Successful merges: - rust-lang#157467 (stdarch subtree update) - rust-lang#155453 (apply Cortex-A53 errata 843419 mitigation to the AArch64 Linux targets) - rust-lang#156798 (delegation: do not always generate first argument) - rust-lang#157438 (rustdoc: don't link doc(hidden) associated type projections) - rust-lang#157450 (mark `Encode`, `Decode`, `Mark` impls as `#[inline]`) - rust-lang#157190 (Silence recursive RUSTC_LOG_FORMAT_JSON messages) - rust-lang#157396 (Add @aapoalas to libs review rotation) - rust-lang#157470 (Avoid ICE when emitting TargetMachine config errors) - rust-lang#157474 (Forbid optimize(none) with inline(always) or inline.) - rust-lang#157475 (Add a smoke test for the optimize attribute.) - rust-lang#157479 (Warn when `#[macro_use]` or `#[macro_escape]` is used on the crate root) - rust-lang#157486 (Remove unused attributes from issue-29485.rs.) Failed merges: - rust-lang#157485 (Rename `errors.rs` file to `diagnostics.rs`)
2 parents ac6f3a3 + 6169a62 commit 8954863

95 files changed

Lines changed: 6524 additions & 1742 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

compiler/rustc_ast/src/ast.rs

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3908,6 +3908,13 @@ pub struct EiiImpl {
39083908
pub is_default: bool,
39093909
}
39103910

3911+
#[derive(Clone, Encodable, Decodable, Debug, Walkable, PartialEq, Eq)]
3912+
pub enum DelegationSource {
3913+
Single,
3914+
List,
3915+
Glob,
3916+
}
3917+
39113918
#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
39123919
pub struct Delegation {
39133920
/// Path resolution id.
@@ -3918,7 +3925,7 @@ pub struct Delegation {
39183925
pub rename: Option<Ident>,
39193926
pub body: Option<Box<Block>>,
39203927
/// The item was expanded from a glob delegation item.
3921-
pub from_glob: bool,
3928+
pub source: DelegationSource,
39223929
}
39233930

39243931
impl Delegation {

compiler/rustc_ast/src/visit.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -431,6 +431,7 @@ macro_rules! common_visitor_and_walkers {
431431
Delegation,
432432
DelegationMac,
433433
DelegationSuffixes,
434+
DelegationSource,
434435
DelimArgs,
435436
DelimSpan,
436437
EnumDef,

compiler/rustc_ast_lowering/src/delegation.rs

Lines changed: 92 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -37,24 +37,29 @@
3737
//! also be emitted during HIR ty lowering.
3838
3939
use std::iter;
40+
use std::ops::ControlFlow;
4041

4142
use ast::visit::Visitor;
4243
use hir::def::{DefKind, Res};
4344
use hir::{BodyId, HirId};
4445
use rustc_abi::ExternAbi;
4546
use rustc_ast as ast;
47+
use rustc_ast::node_id::NodeMap;
4648
use rustc_ast::*;
4749
use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
4850
use rustc_hir::attrs::{AttributeKind, InlineAttr};
4951
use rustc_hir::def_id::{DefId, LocalDefId};
5052
use rustc_hir::{self as hir, FnDeclFlags};
5153
use rustc_middle::span_bug;
52-
use rustc_middle::ty::{Asyncness, TyCtxt};
54+
use rustc_middle::ty::{Asyncness, PerOwnerResolverData, TyCtxt};
5355
use rustc_span::symbol::kw;
5456
use rustc_span::{ErrorGuaranteed, Ident, Span, Symbol};
5557

5658
use crate::delegation::generics::{GenericsGenerationResult, GenericsGenerationResults};
57-
use crate::errors::{CycleInDelegationSignatureResolution, UnresolvedDelegationCallee};
59+
use crate::errors::{
60+
CycleInDelegationSignatureResolution, DelegationAttemptedBlockWithDefsDeletion,
61+
DelegationBlockSpecifiedWhenNoParams, UnresolvedDelegationCallee,
62+
};
5863
use crate::{
5964
AllowReturnTypeNotation, ImplTraitContext, ImplTraitPosition, LoweringContext, ParamMode,
6065
ResolverAstLoweringExt, index_crate,
@@ -198,10 +203,14 @@ impl<'hir> LoweringContext<'_, 'hir> {
198203

199204
let (param_count, c_variadic) = self.param_count(sig_id);
200205

206+
if !self.check_block_soundness(delegation, sig_id, is_method, param_count) {
207+
return self.generate_delegation_error(span, delegation);
208+
}
209+
201210
let mut generics = self.uplift_delegation_generics(delegation, sig_id, is_method);
202211

203212
let (body_id, call_expr_id) =
204-
self.lower_delegation_body(delegation, is_method, param_count, &mut generics, span);
213+
self.lower_delegation_body(delegation, sig_id, param_count, &mut generics, span);
205214

206215
let decl = self.lower_delegation_decl(
207216
sig_id,
@@ -227,6 +236,82 @@ impl<'hir> LoweringContext<'_, 'hir> {
227236
DelegationResults { body_id, sig, ident, generics }
228237
}
229238

239+
fn check_block_soundness(
240+
&self,
241+
delegation: &Delegation,
242+
sig_id: DefId,
243+
is_method: bool,
244+
param_count: usize,
245+
) -> bool {
246+
let Some(block) = delegation.body.as_ref() else { return true };
247+
let should_generate_block = self.should_generate_block(delegation, sig_id, is_method);
248+
249+
// Report an error if user has explicitly specified delegation's target expression
250+
// in a single delegation when reused function has no params.
251+
if param_count == 0 && should_generate_block {
252+
self.dcx().emit_err(DelegationBlockSpecifiedWhenNoParams { span: block.span });
253+
return false;
254+
}
255+
256+
struct DefinitionsFinder<'a> {
257+
all_owners: &'a NodeMap<PerOwnerResolverData<'a>>,
258+
// `self.owner.node_id_to_def_id`
259+
nested_def_ids: &'a NodeMap<LocalDefId>,
260+
}
261+
262+
impl<'a> ast::visit::Visitor<'a> for DefinitionsFinder<'a> {
263+
type Result = ControlFlow<()>;
264+
265+
fn visit_id(&mut self, id: NodeId) -> Self::Result {
266+
/*
267+
(from `tests\ui\delegation\target-expr-removal-defs-inside.rs`):
268+
```rust
269+
reuse impl Trait for S1 {
270+
some::path::<{ fn foo() {} }>::xd();
271+
fn foo() {}
272+
self.0
273+
}
274+
```
275+
276+
Constant from unresolved path will be in `nested_owners`,
277+
`fn foo() {}` will not be in `nested_owners` but will be in `owners`,
278+
both have `LocalDefId`, so we check those two maps.
279+
*/
280+
match self.all_owners.contains_key(&id) || self.nested_def_ids.contains_key(&id) {
281+
true => ControlFlow::Break(()),
282+
false => ControlFlow::Continue(()),
283+
}
284+
}
285+
}
286+
287+
let mut collector = DefinitionsFinder {
288+
all_owners: &self.resolver.owners,
289+
nested_def_ids: &self.owner.node_id_to_def_id,
290+
};
291+
292+
let contains_defs = collector.visit_block(block).is_break();
293+
294+
// If there are definitions inside and we can't delete target expression, so report an error.
295+
// FIXME(fn_delegation): support deletion of target expression with defs inside.
296+
if !should_generate_block && contains_defs {
297+
self.dcx().emit_err(DelegationAttemptedBlockWithDefsDeletion { span: block.span });
298+
return false;
299+
}
300+
301+
true
302+
}
303+
304+
fn should_generate_block(
305+
&self,
306+
delegation: &Delegation,
307+
sig_id: DefId,
308+
is_method: bool,
309+
) -> bool {
310+
is_method
311+
|| matches!(self.tcx.def_kind(sig_id), DefKind::Fn)
312+
|| matches!(delegation.source, DelegationSource::Single)
313+
}
314+
230315
fn add_attrs_if_needed(&mut self, span: Span, sig_id: DefId) {
231316
let new_attrs =
232317
self.create_new_attrs(ATTRS_ADDITIONS, span, sig_id, self.attrs.get(&PARENT_ID));
@@ -415,7 +500,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
415500
fn lower_delegation_body(
416501
&mut self,
417502
delegation: &Delegation,
418-
is_method: bool,
503+
sig_id: DefId,
419504
param_count: usize,
420505
generics: &mut GenericsGenerationResults<'hir>,
421506
span: Span,
@@ -428,6 +513,8 @@ impl<'hir> LoweringContext<'_, 'hir> {
428513
let mut args: Vec<hir::Expr<'_>> = Vec::with_capacity(param_count);
429514
let mut stmts: &[hir::Stmt<'hir>] = &[];
430515

516+
let is_method = this.is_method(sig_id, span);
517+
431518
for idx in 0..param_count {
432519
let (param, pat_node_id) = this.generate_param(is_method, idx, span);
433520
parameters.push(param);
@@ -437,6 +524,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
437524

438525
let arg = if let Some(block) = block
439526
&& idx == 0
527+
&& this.should_generate_block(delegation, sig_id, is_method)
440528
{
441529
let mut self_resolver = SelfResolver {
442530
ctxt: this,
@@ -467,17 +555,6 @@ impl<'hir> LoweringContext<'_, 'hir> {
467555
args.push(arg);
468556
}
469557

470-
// If we have no params in signature function but user still wrote some code in
471-
// delegation body, then add this code as first arg, eventually an error will be shown,
472-
// also nested delegations may need to access information about this code (#154332),
473-
// so it is better to leave this code as opposed to bodies of extern functions,
474-
// which are completely erased from existence.
475-
if param_count == 0
476-
&& let Some(block) = block
477-
{
478-
args.push(this.lower_block_expr(&block));
479-
}
480-
481558
let (final_expr, hir_id) =
482559
this.finalize_body_lowering(delegation, stmts, args, generics, span);
483560

compiler/rustc_ast_lowering/src/errors.rs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -535,3 +535,17 @@ pub(crate) struct CycleInDelegationSignatureResolution {
535535
#[primary_span]
536536
pub span: Span,
537537
}
538+
539+
#[derive(Diagnostic)]
540+
#[diag("delegation's target expression is specified for function with no params")]
541+
pub(crate) struct DelegationBlockSpecifiedWhenNoParams {
542+
#[primary_span]
543+
pub span: Span,
544+
}
545+
546+
#[derive(Diagnostic)]
547+
#[diag("attempted to delete delegation's target expression that contains definitions inside")]
548+
pub(crate) struct DelegationAttemptedBlockWithDefsDeletion {
549+
#[primary_span]
550+
pub span: Span,
551+
}

compiler/rustc_attr_parsing/src/attributes/macro_attrs.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,6 @@ const MACRO_USE_TEMPLATE: AttributeTemplate = template!(
3535
const MACRO_USE_ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowListWarnRest(&[
3636
Allow(Target::Mod),
3737
Allow(Target::ExternCrate),
38-
Allow(Target::Crate),
3938
Error(Target::WherePredicate),
4039
]);
4140

compiler/rustc_codegen_llvm/src/errors.rs

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,9 +24,12 @@ pub(crate) struct ParseTargetMachineConfig<'a>(pub LlvmError<'a>);
2424

2525
impl<G: EmissionGuarantee> Diagnostic<'_, G> for ParseTargetMachineConfig<'_> {
2626
fn into_diag(self, dcx: DiagCtxtHandle<'_>, level: Level) -> Diag<'_, G> {
27-
let diag: Diag<'_, G> = self.0.into_diag(dcx, level);
27+
// Reuse the formatted primary message from `LlvmError` without emitting it.
28+
let diag: Diag<'_, ()> = self.0.into_diag(dcx, level);
2829
let (message, _) = diag.messages.first().expect("`LlvmError` with no message");
29-
let message = format_diag_message(message, &diag.args);
30+
let message = format_diag_message(message, &diag.args).into_owned();
31+
diag.cancel();
32+
3033
Diag::new(
3134
dcx,
3235
level,

compiler/rustc_expand/src/expand.rs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2066,7 +2066,11 @@ fn build_single_delegations<'a, Node: InvocationCollectorNode>(
20662066
ident: rename.unwrap_or(ident),
20672067
rename,
20682068
body: deleg.body.clone(),
2069-
from_glob,
2069+
source: if from_glob {
2070+
ast::DelegationSource::Glob
2071+
} else {
2072+
ast::DelegationSource::List
2073+
},
20702074
})),
20712075
tokens: None,
20722076
}

compiler/rustc_log/src/lib.rs

Lines changed: 106 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,19 +33,20 @@
3333
//! debugging, you can make changes inside those crates and quickly run main.rs
3434
//! to read the debug logs.
3535
36+
use std::cell::Cell;
3637
use std::env::{self, VarError};
3738
use std::fmt::{self, Display};
3839
use std::fs::File;
3940
use std::io::{self, IsTerminal};
4041
use std::sync::Mutex;
4142

4243
use tracing::dispatcher::SetGlobalDefaultError;
43-
use tracing::{Event, Subscriber};
44+
use tracing::{Event, Subscriber, span};
4445
use tracing_subscriber::filter::{Directive, EnvFilter, LevelFilter};
4546
use tracing_subscriber::fmt::FmtContext;
4647
use tracing_subscriber::fmt::format::{self, FmtSpan, FormatEvent, FormatFields};
4748
use tracing_subscriber::fmt::writer::BoxMakeWriter;
48-
use tracing_subscriber::layer::SubscriberExt;
49+
use tracing_subscriber::layer::{Context, SubscriberExt};
4950
use tracing_subscriber::{Layer, Registry};
5051
// Re-export tracing
5152
pub use {tracing, tracing_core, tracing_subscriber};
@@ -175,6 +176,7 @@ where
175176
.with_thread_ids(verbose_thread_ids)
176177
.with_thread_names(verbose_thread_ids)
177178
.with_span_events(FmtSpan::ACTIVE);
179+
let fmt_layer = NonrecursiveLayer { inner: fmt_layer };
178180
Layer::boxed(fmt_layer)
179181
} else {
180182
let mut layer = tracing_tree::HierarchicalLayer::default()
@@ -286,3 +288,105 @@ impl From<SetGlobalDefaultError> for Error {
286288
Error::AlreadyInit(tracing_error)
287289
}
288290
}
291+
292+
thread_local! {
293+
static NONRECURSIVE_GUARD_LOCK: Cell<bool> = const { Cell::new(false) };
294+
}
295+
296+
struct NonrecursiveGuard;
297+
298+
impl NonrecursiveGuard {
299+
fn lock() -> Option<NonrecursiveGuard> {
300+
if !NONRECURSIVE_GUARD_LOCK.replace(true) { Some(NonrecursiveGuard) } else { None }
301+
}
302+
}
303+
304+
impl Drop for NonrecursiveGuard {
305+
fn drop(&mut self) {
306+
NONRECURSIVE_GUARD_LOCK.set(false);
307+
}
308+
}
309+
310+
/// Many debug messages that rustc emits produce additional debug messages when formatting the
311+
/// arguments to the original debug message. [`tracing_tree::HierarchicalLayer`] (used by the
312+
/// default output format) filters these out, but [`tracing_subscriber::fmt::format::Json`] (used by
313+
/// `RUSTC_LOG_FORMAT_JSON`) does not. So, implement a simple recursion check to filter these
314+
/// messages out.
315+
struct NonrecursiveLayer<S> {
316+
inner: S,
317+
}
318+
319+
impl<S: Subscriber, L: Layer<S>> Layer<S> for NonrecursiveLayer<L> {
320+
fn on_register_dispatch(&self, subscriber: &tracing::Dispatch) {
321+
self.inner.on_register_dispatch(subscriber)
322+
}
323+
324+
fn on_layer(&mut self, subscriber: &mut S) {
325+
self.inner.on_layer(subscriber)
326+
}
327+
328+
fn register_callsite(
329+
&self,
330+
metadata: &'static tracing::Metadata<'static>,
331+
) -> tracing_core::Interest {
332+
self.inner.register_callsite(metadata)
333+
}
334+
335+
fn enabled(&self, metadata: &tracing::Metadata<'_>, ctx: Context<'_, S>) -> bool {
336+
self.inner.enabled(metadata, ctx)
337+
}
338+
339+
fn on_new_span(&self, attrs: &span::Attributes<'_>, id: &span::Id, ctx: Context<'_, S>) {
340+
if let Some(_) = NonrecursiveGuard::lock() {
341+
self.inner.on_new_span(attrs, id, ctx)
342+
}
343+
}
344+
345+
fn on_record(&self, span: &span::Id, values: &span::Record<'_>, ctx: Context<'_, S>) {
346+
if let Some(_) = NonrecursiveGuard::lock() {
347+
self.inner.on_record(span, values, ctx)
348+
}
349+
}
350+
351+
fn on_follows_from(&self, span: &span::Id, follows: &span::Id, ctx: Context<'_, S>) {
352+
if let Some(_) = NonrecursiveGuard::lock() {
353+
self.inner.on_follows_from(span, follows, ctx)
354+
}
355+
}
356+
357+
fn event_enabled(&self, event: &Event<'_>, ctx: Context<'_, S>) -> bool {
358+
if let Some(_) = NonrecursiveGuard::lock() {
359+
self.inner.event_enabled(event, ctx)
360+
} else {
361+
false
362+
}
363+
}
364+
365+
fn on_event(&self, event: &Event<'_>, ctx: Context<'_, S>) {
366+
if let Some(_) = NonrecursiveGuard::lock() {
367+
self.inner.on_event(event, ctx)
368+
}
369+
}
370+
371+
fn on_enter(&self, id: &span::Id, ctx: Context<'_, S>) {
372+
if let Some(_) = NonrecursiveGuard::lock() {
373+
self.inner.on_enter(id, ctx)
374+
}
375+
}
376+
377+
fn on_exit(&self, id: &span::Id, ctx: Context<'_, S>) {
378+
if let Some(_) = NonrecursiveGuard::lock() {
379+
self.inner.on_exit(id, ctx)
380+
}
381+
}
382+
383+
fn on_close(&self, id: span::Id, ctx: Context<'_, S>) {
384+
if let Some(_) = NonrecursiveGuard::lock() {
385+
self.inner.on_close(id, ctx)
386+
}
387+
}
388+
389+
fn on_id_change(&self, old: &span::Id, new: &span::Id, ctx: Context<'_, S>) {
390+
self.inner.on_id_change(old, new, ctx)
391+
}
392+
}

0 commit comments

Comments
 (0)