Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rollup of 5 pull requests #138532

Merged
merged 12 commits into from
Mar 15, 2025
Merged
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
16 changes: 16 additions & 0 deletions compiler/rustc_borrowck/src/type_check/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1773,6 +1773,22 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> {
{
span_mirbug!(self, constant, "bad static type {:?} ({:?})", constant, terr);
}
} else if let Const::Ty(_, ct) = constant.const_
&& let ty::ConstKind::Param(p) = ct.kind()
{
let body_def_id = self.universal_regions.defining_ty.def_id();
let const_param = tcx.generics_of(body_def_id).const_param(p, tcx);
self.ascribe_user_type(
constant.const_.ty(),
ty::UserType::new(ty::UserTypeKind::TypeOf(
const_param.def_id,
UserArgs {
args: self.universal_regions.defining_ty.args(),
user_self_ty: None,
},
)),
locations.span(self.body),
);
}

if let ty::FnDef(def_id, args) = *constant.const_.ty().kind() {
Expand Down
14 changes: 14 additions & 0 deletions compiler/rustc_borrowck/src/universal_regions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,20 @@ impl<'tcx> DefiningTy<'tcx> {
| DefiningTy::GlobalAsm(def_id) => def_id,
}
}

/// Returns the args of the `DefiningTy`. These are equivalent to the identity
/// substs of the body, but replaced with region vids.
pub(crate) fn args(&self) -> ty::GenericArgsRef<'tcx> {
match *self {
DefiningTy::Closure(_, args)
| DefiningTy::Coroutine(_, args)
| DefiningTy::CoroutineClosure(_, args)
| DefiningTy::FnDef(_, args)
| DefiningTy::Const(_, args)
| DefiningTy::InlineConst(_, args) => args,
DefiningTy::GlobalAsm(_) => ty::List::empty(),
}
}
}

#[derive(Debug)]
Expand Down
47 changes: 41 additions & 6 deletions compiler/rustc_codegen_ssa/src/back/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -137,12 +137,42 @@ impl Command {
/// Returns a `true` if we're pretty sure that this'll blow OS spawn limits,
/// or `false` if we should attempt to spawn and see what the OS says.
pub(crate) fn very_likely_to_exceed_some_spawn_limit(&self) -> bool {
// We mostly only care about Windows in this method, on Unix the limits
// can be gargantuan anyway so we're pretty unlikely to hit them
if cfg!(unix) {
#[cfg(not(any(windows, unix)))]
{
return false;
}

// On Unix the limits can be gargantuan anyway so we're pretty
// unlikely to hit them, but might still exceed it.
// We consult ARG_MAX here to get an estimate.
#[cfg(unix)]
{
let ptr_size = mem::size_of::<usize>();
// arg + \0 + pointer
let args_size = self.args.iter().fold(0usize, |acc, a| {
let arg = a.as_encoded_bytes().len();
let nul = 1;
acc.saturating_add(arg).saturating_add(nul).saturating_add(ptr_size)
});
// key + `=` + value + \0 + pointer
let envs_size = self.env.iter().fold(0usize, |acc, (k, v)| {
let k = k.as_encoded_bytes().len();
let eq = 1;
let v = v.as_encoded_bytes().len();
let nul = 1;
acc.saturating_add(k)
.saturating_add(eq)
.saturating_add(v)
.saturating_add(nul)
.saturating_add(ptr_size)
});
let arg_max = match unsafe { libc::sysconf(libc::_SC_ARG_MAX) } {
-1 => return false, // Go to OS anyway.
max => max as usize,
};
return args_size.saturating_add(envs_size) > arg_max;
}

// Ok so on Windows to spawn a process is 32,768 characters in its
// command line [1]. Unfortunately we don't actually have access to that
// as it's calculated just before spawning. Instead we perform a
Expand All @@ -165,9 +195,14 @@ impl Command {
//
// [1]: https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createprocessa
// [2]: https://devblogs.microsoft.com/oldnewthing/?p=41553

let estimated_command_line_len = self.args.iter().map(|a| a.len()).sum::<usize>();
estimated_command_line_len > 1024 * 6
#[cfg(windows)]
{
let estimated_command_line_len = self
.args
.iter()
.fold(0usize, |acc, a| acc.saturating_add(a.as_encoded_bytes().len()));
return estimated_command_line_len > 1024 * 6;
}
}
}

Expand Down
6 changes: 6 additions & 0 deletions compiler/rustc_data_structures/src/unord.rs
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,12 @@ impl<V: Eq + Hash> UnordSet<V> {
self.inner.is_empty()
}

/// If the set has only one element, returns it, otherwise returns `None`.
#[inline]
pub fn get_only(&self) -> Option<&V> {
if self.inner.len() == 1 { self.inner.iter().next() } else { None }
}

#[inline]
pub fn insert(&mut self, v: V) -> bool {
self.inner.insert(v)
Expand Down
3 changes: 2 additions & 1 deletion compiler/rustc_middle/src/ty/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet};
use rustc_data_structures::intern::Interned;
use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
use rustc_data_structures::steal::Steal;
use rustc_data_structures::unord::UnordMap;
use rustc_errors::{Diag, ErrorGuaranteed};
use rustc_hir::LangItem;
use rustc_hir::def::{CtorKind, CtorOf, DefKind, DocLinkResMap, LifetimeRes, Res};
Expand Down Expand Up @@ -168,7 +169,7 @@ pub struct ResolverGlobalCtxt {
/// Item with a given `LocalDefId` was defined during macro expansion with ID `ExpnId`.
pub expn_that_defined: FxHashMap<LocalDefId, ExpnId>,
pub effective_visibilities: EffectiveVisibilities,
pub extern_crate_map: FxHashMap<LocalDefId, CrateNum>,
pub extern_crate_map: UnordMap<LocalDefId, CrateNum>,
pub maybe_unused_trait_imports: FxIndexSet<LocalDefId>,
pub module_children: LocalDefIdMap<Vec<ModChild>>,
pub glob_map: FxHashMap<LocalDefId, FxHashSet<Symbol>>,
Expand Down
41 changes: 39 additions & 2 deletions compiler/rustc_mir_transform/src/coroutine/by_move_body.rs
Original file line number Diff line number Diff line change
Expand Up @@ -178,17 +178,18 @@ pub(crate) fn coroutine_by_move_body_def_id<'tcx>(
),
};

(
Some((
FieldIdx::from_usize(child_field_idx + num_args),
(
FieldIdx::from_usize(parent_field_idx + num_args),
parent_capture_ty,
peel_deref,
child_precise_captures,
),
)
))
},
)
.flatten()
.collect();

if coroutine_kind == ty::ClosureKind::FnOnce {
Expand Down Expand Up @@ -312,10 +313,46 @@ impl<'tcx> MutVisitor<'tcx> for MakeByMoveBody<'tcx> {
self.super_place(place, context, location);
}

fn visit_statement(&mut self, statement: &mut mir::Statement<'tcx>, location: mir::Location) {
// Remove fake borrows of closure captures if that capture has been
// replaced with a by-move version of that capture.
//
// For example, imagine we capture `Foo` in the parent and `&Foo`
// in the child. We will emit two fake borrows like:
//
// ```
// _2 = &fake shallow (*(_1.0: &Foo));
// _3 = &fake shallow (_1.0: &Foo);
// ```
//
// However, since this transform is responsible for replacing
// `_1.0: &Foo` with `_1.0: Foo`, that makes the second fake borrow
// obsolete, and we should replace it with a nop.
//
// As a side-note, we don't actually even care about fake borrows
// here at all since they're fully a MIR borrowck artifact, and we
// don't need to borrowck by-move MIR bodies. But it's best to preserve
// as much as we can between these two bodies :)
if let mir::StatementKind::Assign(box (_, rvalue)) = &statement.kind
&& let mir::Rvalue::Ref(_, mir::BorrowKind::Fake(mir::FakeBorrowKind::Shallow), place) =
rvalue
&& let mir::PlaceRef {
local: ty::CAPTURE_STRUCT_LOCAL,
projection: [mir::ProjectionElem::Field(idx, _)],
} = place.as_ref()
&& let Some(&(_, _, true, _)) = self.field_remapping.get(&idx)
{
statement.kind = mir::StatementKind::Nop;
}

self.super_statement(statement, location);
}

fn visit_local_decl(&mut self, local: mir::Local, local_decl: &mut mir::LocalDecl<'tcx>) {
// Replace the type of the self arg.
if local == ty::CAPTURE_STRUCT_LOCAL {
local_decl.ty = self.by_move_coroutine_ty;
}
self.super_local_decl(local, local_decl);
}
}
1 change: 1 addition & 0 deletions compiler/rustc_resolve/src/build_reduced_graph.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1115,6 +1115,7 @@ impl<'a, 'ra, 'tcx> BuildReducedGraphVisitor<'a, 'ra, 'tcx> {
}
});
} else {
#[allow(rustc::potential_query_instability)] // FIXME
for ident in single_imports.iter().cloned() {
let result = self.r.maybe_resolve_ident_in_module(
ModuleOrUniformRoot::Module(module),
Expand Down
15 changes: 5 additions & 10 deletions compiler/rustc_resolve/src/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use rustc_ast::{
};
use rustc_ast_pretty::pprust;
use rustc_data_structures::fx::FxHashSet;
use rustc_data_structures::unord::UnordSet;
use rustc_errors::codes::*;
use rustc_errors::{
Applicability, Diag, DiagCtxtHandle, ErrorGuaranteed, MultiSpan, SuggestionStyle,
Expand Down Expand Up @@ -1467,6 +1468,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
return;
}

#[allow(rustc::potential_query_instability)] // FIXME
let unused_macro = self.unused_macros.iter().find_map(|(def_id, (_, unused_ident))| {
if unused_ident.name == ident.name { Some((def_id, unused_ident)) } else { None }
});
Expand Down Expand Up @@ -2863,18 +2865,11 @@ fn show_candidates(
} else {
// Get the unique item kinds and if there's only one, we use the right kind name
// instead of the more generic "items".
let mut kinds = accessible_path_strings
let kinds = accessible_path_strings
.iter()
.map(|(_, descr, _, _, _)| *descr)
.collect::<FxHashSet<&str>>()
.into_iter();
let kind = if let Some(kind) = kinds.next()
&& let None = kinds.next()
{
kind
} else {
"item"
};
.collect::<UnordSet<&str>>();
let kind = if let Some(kind) = kinds.get_only() { kind } else { "item" };
let s = if kind.ends_with('s') { "es" } else { "s" };

("one of these", kind, s, String::new(), "")
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_resolve/src/ident.rs
Original file line number Diff line number Diff line change
Expand Up @@ -946,6 +946,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {

// Check if one of single imports can still define the name,
// if it can then our result is not determined and can be invalidated.
#[allow(rustc::potential_query_instability)] // FIXME
for single_import in &resolution.single_imports {
if ignore_import == Some(*single_import) {
// This branch handles a cycle in single imports.
Expand Down
24 changes: 12 additions & 12 deletions compiler/rustc_resolve/src/late.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ use rustc_ast::visit::{
};
use rustc_ast::*;
use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap};
use rustc_data_structures::unord::{UnordMap, UnordSet};
use rustc_errors::codes::*;
use rustc_errors::{
Applicability, DiagArgValue, ErrorGuaranteed, IntoDiagArg, StashKey, Suggestions,
Expand Down Expand Up @@ -47,8 +48,6 @@ mod diagnostics;

type Res = def::Res<NodeId>;

type IdentMap<T> = FxHashMap<Ident, T>;

use diagnostics::{ElisionFnParameter, LifetimeElisionCandidate, MissingLifetime};

#[derive(Copy, Clone, Debug)]
Expand Down Expand Up @@ -273,8 +272,8 @@ impl RibKind<'_> {
/// resolving, the name is looked up from inside out.
#[derive(Debug)]
pub(crate) struct Rib<'ra, R = Res> {
pub bindings: IdentMap<R>,
pub patterns_with_skipped_bindings: FxHashMap<DefId, Vec<(Span, Result<(), ErrorGuaranteed>)>>,
pub bindings: FxHashMap<Ident, R>,
pub patterns_with_skipped_bindings: UnordMap<DefId, Vec<(Span, Result<(), ErrorGuaranteed>)>>,
pub kind: RibKind<'ra>,
}

Expand Down Expand Up @@ -1605,12 +1604,12 @@ impl<'a, 'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
// for better diagnostics.
let mut forward_ty_ban_rib_const_param_ty = Rib {
bindings: forward_ty_ban_rib.bindings.clone(),
patterns_with_skipped_bindings: FxHashMap::default(),
patterns_with_skipped_bindings: Default::default(),
kind: RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::ConstParamTy),
};
let mut forward_const_ban_rib_const_param_ty = Rib {
bindings: forward_const_ban_rib.bindings.clone(),
patterns_with_skipped_bindings: FxHashMap::default(),
patterns_with_skipped_bindings: Default::default(),
kind: RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::ConstParamTy),
};
// We'll ban these with a `ConstParamTy` rib, so just clear these ribs for better
Expand Down Expand Up @@ -2334,7 +2333,7 @@ impl<'a, 'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
let local_candidates = self.lifetime_elision_candidates.take();

if let Some(candidates) = local_candidates {
let distinct: FxHashSet<_> = candidates.iter().map(|(res, _)| *res).collect();
let distinct: UnordSet<_> = candidates.iter().map(|(res, _)| *res).collect();
let lifetime_count = distinct.len();
if lifetime_count != 0 {
parameter_info.push(ElisionFnParameter {
Expand All @@ -2358,14 +2357,13 @@ impl<'a, 'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
}
}));
}
let mut distinct_iter = distinct.into_iter();
if let Some(res) = distinct_iter.next() {
if !distinct.is_empty() {
match elision_lifetime {
// We are the first parameter to bind lifetimes.
Elision::None => {
if distinct_iter.next().is_none() {
if let Some(res) = distinct.get_only() {
// We have a single lifetime => success.
elision_lifetime = Elision::Param(res)
elision_lifetime = Elision::Param(*res)
} else {
// We have multiple lifetimes => error.
elision_lifetime = Elision::Err;
Expand Down Expand Up @@ -2890,6 +2888,7 @@ impl<'a, 'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
break;
}

#[allow(rustc::potential_query_instability)] // FIXME
seen_bindings
.extend(parent_rib.bindings.keys().map(|ident| (*ident, ident.span)));
}
Expand Down Expand Up @@ -4004,7 +4003,7 @@ impl<'a, 'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
}
}

fn innermost_rib_bindings(&mut self, ns: Namespace) -> &mut IdentMap<Res> {
fn innermost_rib_bindings(&mut self, ns: Namespace) -> &mut FxHashMap<Ident, Res> {
&mut self.ribs[ns].last_mut().unwrap().bindings
}

Expand Down Expand Up @@ -5202,6 +5201,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
let mut late_resolution_visitor = LateResolutionVisitor::new(self);
late_resolution_visitor.resolve_doc_links(&krate.attrs, MaybeExported::Ok(CRATE_NODE_ID));
visit::walk_crate(&mut late_resolution_visitor, krate);
#[allow(rustc::potential_query_instability)] // FIXME
for (id, span) in late_resolution_visitor.diag_metadata.unused_labels.iter() {
self.lint_buffer.buffer_lint(
lint::builtin::UNUSED_LABELS,
Expand Down
Loading
Loading