Skip to content

Commit 0908f17

Browse files
committed
Auto merge of #118543 - matthiaskrgr:rollup-0kl4o90, r=matthiaskrgr
Rollup of 4 pull requests Successful merges: - #118514 (rustc_hir_typeck: Fix ICE when probing for non-ASCII function alternative) - #118524 (Add more information to StableMIR Instance) - #118528 (replace `once_cell::sync::OnceCell` with std `OnceLock`) - #118539 (move packed-struct tests into packed/ folder) r? `@ghost` `@rustbot` modify labels: rollup
2 parents 4e3dc97 + 613f4ec commit 0908f17

File tree

19 files changed

+163
-40
lines changed

19 files changed

+163
-40
lines changed

compiler/rustc_hir_typeck/src/method/probe.rs

+4-3
Original file line numberDiff line numberDiff line change
@@ -1799,9 +1799,10 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> {
17991799
.iter()
18001800
.find(|cand| self.matches_by_doc_alias(cand.def_id))
18011801
.map(|cand| cand.name)
1802-
})
1803-
.unwrap();
1804-
Ok(applicable_close_candidates.into_iter().find(|method| method.name == best_name))
1802+
});
1803+
Ok(best_name.and_then(|best_name| {
1804+
applicable_close_candidates.into_iter().find(|method| method.name == best_name)
1805+
}))
18051806
}
18061807
})
18071808
}

compiler/rustc_smir/src/rustc_smir/context.rs

+22-2
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
//! This trait is currently the main interface between the Rust compiler,
44
//! and the `stable_mir` crate.
55
6+
use rustc_middle::ty;
67
use rustc_middle::ty::print::{with_forced_trimmed_paths, with_no_trimmed_paths};
78
use rustc_middle::ty::{GenericPredicates, Instance, ParamEnv, ScalarInt, ValTree};
89
use rustc_span::def_id::LOCAL_CRATE;
@@ -12,9 +13,9 @@ use stable_mir::mir::mono::{InstanceDef, StaticDef};
1213
use stable_mir::mir::Body;
1314
use stable_mir::ty::{
1415
AdtDef, AdtKind, Allocation, ClosureDef, ClosureKind, Const, FnDef, GenericArgs, LineInfo,
15-
RigidTy, Span, TyKind,
16+
PolyFnSig, RigidTy, Span, TyKind,
1617
};
17-
use stable_mir::{self, Crate, CrateItem, Error, Filename, ItemKind, Symbol};
18+
use stable_mir::{self, Crate, CrateItem, DefId, Error, Filename, ItemKind, Symbol};
1819
use std::cell::RefCell;
1920

2021
use crate::rustc_internal::{internal, RustcInternal};
@@ -39,6 +40,12 @@ impl<'tcx> Context for TablesWrapper<'tcx> {
3940
tables.tcx.instance_mir(rustc_middle::ty::InstanceDef::Item(def_id)).stable(&mut tables)
4041
}
4142

43+
fn has_body(&self, def: DefId) -> bool {
44+
let tables = self.0.borrow();
45+
let def_id = tables[def];
46+
tables.tcx.is_mir_available(def_id)
47+
}
48+
4249
fn all_trait_decls(&self) -> stable_mir::TraitDecls {
4350
let mut tables = self.0.borrow_mut();
4451
tables
@@ -195,6 +202,13 @@ impl<'tcx> Context for TablesWrapper<'tcx> {
195202
def.internal(&mut *tables).is_box()
196203
}
197204

205+
fn fn_sig(&self, def: FnDef, args: &GenericArgs) -> PolyFnSig {
206+
let mut tables = self.0.borrow_mut();
207+
let def_id = def.0.internal(&mut *tables);
208+
let sig = tables.tcx.fn_sig(def_id).instantiate(tables.tcx, args.internal(&mut *tables));
209+
sig.stable(&mut *tables)
210+
}
211+
198212
fn eval_target_usize(&self, cnst: &Const) -> Result<u64, Error> {
199213
let mut tables = self.0.borrow_mut();
200214
let mir_const = cnst.internal(&mut *tables);
@@ -266,6 +280,12 @@ impl<'tcx> Context for TablesWrapper<'tcx> {
266280
tables.tcx.symbol_name(instance).name.to_string()
267281
}
268282

283+
fn is_empty_drop_shim(&self, def: InstanceDef) -> bool {
284+
let tables = self.0.borrow_mut();
285+
let instance = tables.instances[def];
286+
matches!(instance.def, ty::InstanceDef::DropGlue(_, None))
287+
}
288+
269289
fn mono_instance(&self, item: stable_mir::CrateItem) -> stable_mir::mir::mono::Instance {
270290
let mut tables = self.0.borrow_mut();
271291
let def_id = tables[item.0];

compiler/rustc_smir/src/rustc_smir/convert/ty.rs

+3-1
Original file line numberDiff line numberDiff line change
@@ -777,7 +777,9 @@ impl<'tcx> Stable<'tcx> for ty::Instance<'tcx> {
777777
let kind = match self.def {
778778
ty::InstanceDef::Item(..) => stable_mir::mir::mono::InstanceKind::Item,
779779
ty::InstanceDef::Intrinsic(..) => stable_mir::mir::mono::InstanceKind::Intrinsic,
780-
ty::InstanceDef::Virtual(..) => stable_mir::mir::mono::InstanceKind::Virtual,
780+
ty::InstanceDef::Virtual(_def_id, idx) => {
781+
stable_mir::mir::mono::InstanceKind::Virtual { idx }
782+
}
781783
ty::InstanceDef::VTableShim(..)
782784
| ty::InstanceDef::ReifyShim(..)
783785
| ty::InstanceDef::FnPtrAddrShim(..)

compiler/stable_mir/src/compiler_interface.rs

+13-4
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,8 @@ use crate::mir::mono::{Instance, InstanceDef, StaticDef};
1010
use crate::mir::Body;
1111
use crate::ty::{
1212
AdtDef, AdtKind, Allocation, ClosureDef, ClosureKind, Const, FnDef, GenericArgs,
13-
GenericPredicates, Generics, ImplDef, ImplTrait, LineInfo, RigidTy, Span, TraitDecl, TraitDef,
14-
Ty, TyKind,
13+
GenericPredicates, Generics, ImplDef, ImplTrait, LineInfo, PolyFnSig, RigidTy, Span, TraitDecl,
14+
TraitDef, Ty, TyKind,
1515
};
1616
use crate::{
1717
mir, Crate, CrateItem, CrateItems, DefId, Error, Filename, ImplTraitDecls, ItemKind, Symbol,
@@ -24,7 +24,11 @@ pub trait Context {
2424
fn entry_fn(&self) -> Option<CrateItem>;
2525
/// Retrieve all items of the local crate that have a MIR associated with them.
2626
fn all_local_items(&self) -> CrateItems;
27+
/// Retrieve the body of a function.
28+
/// This function will panic if the body is not available.
2729
fn mir_body(&self, item: DefId) -> mir::Body;
30+
/// Check whether the body of a function is available.
31+
fn has_body(&self, item: DefId) -> bool;
2832
fn all_trait_decls(&self) -> TraitDecls;
2933
fn trait_decl(&self, trait_def: &TraitDef) -> TraitDecl;
3034
fn all_trait_impls(&self) -> ImplTraitDecls;
@@ -64,6 +68,9 @@ pub trait Context {
6468
/// Returns if the ADT is a box.
6569
fn adt_is_box(&self, def: AdtDef) -> bool;
6670

71+
/// Retrieve the function signature for the given generic arguments.
72+
fn fn_sig(&self, def: FnDef, args: &GenericArgs) -> PolyFnSig;
73+
6774
/// Evaluate constant as a target usize.
6875
fn eval_target_usize(&self, cnst: &Const) -> Result<u64, Error>;
6976

@@ -85,8 +92,7 @@ pub trait Context {
8592
/// Obtain the representation of a type.
8693
fn ty_kind(&self, ty: Ty) -> TyKind;
8794

88-
/// Get the body of an Instance.
89-
/// FIXME: Monomorphize the body.
95+
/// Get the body of an Instance which is already monomorphized.
9096
fn instance_body(&self, instance: InstanceDef) -> Option<Body>;
9197

9298
/// Get the instance type with generic substitutions applied and lifetimes erased.
@@ -98,6 +104,9 @@ pub trait Context {
98104
/// Get the instance mangled name.
99105
fn instance_mangled_name(&self, instance: InstanceDef) -> Symbol;
100106

107+
/// Check if this is an empty DropGlue shim.
108+
fn is_empty_drop_shim(&self, def: InstanceDef) -> bool;
109+
101110
/// Convert a non-generic crate item into an instance.
102111
/// This function will panic if the item is generic.
103112
fn mono_instance(&self, item: CrateItem) -> Instance;

compiler/stable_mir/src/mir/mono.rs

+34-9
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use crate::crate_def::CrateDef;
22
use crate::mir::Body;
3-
use crate::ty::{Allocation, ClosureDef, ClosureKind, FnDef, GenericArgs, IndexedVal, Ty};
3+
use crate::ty::{Allocation, ClosureDef, ClosureKind, FnDef, FnSig, GenericArgs, IndexedVal, Ty};
44
use crate::{with, CrateItem, DefId, Error, ItemKind, Opaque, Symbol};
55
use std::fmt::{Debug, Formatter};
66

@@ -27,7 +27,8 @@ pub enum InstanceKind {
2727
/// A compiler intrinsic function.
2828
Intrinsic,
2929
/// A virtual function definition stored in a VTable.
30-
Virtual,
30+
/// The `idx` field indicates the position in the VTable for this instance.
31+
Virtual { idx: usize },
3132
/// A compiler generated shim.
3233
Shim,
3334
}
@@ -106,6 +107,24 @@ impl Instance {
106107
})
107108
})
108109
}
110+
111+
/// Get this function signature with all types already instantiated.
112+
pub fn fn_sig(&self) -> FnSig {
113+
self.ty().kind().fn_sig().unwrap().skip_binder()
114+
}
115+
116+
/// Check whether this instance is an empty shim.
117+
///
118+
/// Allow users to check if this shim can be ignored when called directly.
119+
///
120+
/// We have decided not to export different types of Shims to StableMIR users, however, this
121+
/// is a query that can be very helpful for users when processing DropGlue.
122+
///
123+
/// When generating code for a Drop terminator, users can ignore an empty drop glue.
124+
/// These shims are only needed to generate a valid Drop call done via VTable.
125+
pub fn is_empty_shim(&self) -> bool {
126+
self.kind == InstanceKind::Shim && with(|cx| cx.is_empty_drop_shim(self.def))
127+
}
109128
}
110129

111130
impl Debug for Instance {
@@ -124,8 +143,6 @@ impl TryFrom<CrateItem> for Instance {
124143

125144
fn try_from(item: CrateItem) -> Result<Self, Self::Error> {
126145
with(|context| {
127-
// FIXME(celinval):
128-
// - Return `Err` if instance does not have a body.
129146
if !context.requires_monomorphization(item.0) {
130147
Ok(context.mono_instance(item))
131148
} else {
@@ -141,11 +158,13 @@ impl TryFrom<Instance> for CrateItem {
141158
type Error = crate::Error;
142159

143160
fn try_from(value: Instance) -> Result<Self, Self::Error> {
144-
if value.kind == InstanceKind::Item {
145-
Ok(CrateItem(with(|context| context.instance_def_id(value.def))))
146-
} else {
147-
Err(Error::new(format!("Item kind `{:?}` cannot be converted", value.kind)))
148-
}
161+
with(|context| {
162+
if value.kind == InstanceKind::Item && context.has_body(value.def.def_id()) {
163+
Ok(CrateItem(context.instance_def_id(value.def)))
164+
} else {
165+
Err(Error::new(format!("Item kind `{:?}` cannot be converted", value.kind)))
166+
}
167+
})
149168
}
150169
}
151170

@@ -170,6 +189,12 @@ impl From<StaticDef> for CrateItem {
170189
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
171190
pub struct InstanceDef(usize);
172191

192+
impl CrateDef for InstanceDef {
193+
fn def_id(&self) -> DefId {
194+
with(|context| context.instance_def_id(*self))
195+
}
196+
}
197+
173198
crate_def! {
174199
/// Holds information about a static variable definition.
175200
pub StaticDef;

compiler/stable_mir/src/ty.rs

+35-3
Original file line numberDiff line numberDiff line change
@@ -168,7 +168,11 @@ impl TyKind {
168168
}
169169

170170
pub fn is_unit(&self) -> bool {
171-
matches!(self, TyKind::RigidTy(RigidTy::Tuple(data)) if data.len() == 0)
171+
matches!(self, TyKind::RigidTy(RigidTy::Tuple(data)) if data.is_empty())
172+
}
173+
174+
pub fn is_bool(&self) -> bool {
175+
matches!(self, TyKind::RigidTy(RigidTy::Bool))
172176
}
173177

174178
pub fn is_trait(&self) -> bool {
@@ -187,6 +191,14 @@ impl TyKind {
187191
matches!(self, TyKind::RigidTy(RigidTy::Adt(def, _)) if def.kind() == AdtKind::Union)
188192
}
189193

194+
pub fn is_fn(&self) -> bool {
195+
matches!(self, TyKind::RigidTy(RigidTy::FnDef(..)))
196+
}
197+
198+
pub fn is_fn_ptr(&self) -> bool {
199+
matches!(self, TyKind::RigidTy(RigidTy::FnPtr(..)))
200+
}
201+
190202
pub fn trait_principal(&self) -> Option<Binder<ExistentialTraitRef>> {
191203
if let TyKind::RigidTy(RigidTy::Dynamic(predicates, _, _)) = self {
192204
if let Some(Binder { value: ExistentialPredicate::Trait(trait_ref), bound_vars }) =
@@ -227,6 +239,15 @@ impl TyKind {
227239
_ => None,
228240
}
229241
}
242+
243+
/// Get the function signature for function like types (Fn, FnPtr, Closure, Coroutine)
244+
pub fn fn_sig(&self) -> Option<PolyFnSig> {
245+
match self {
246+
TyKind::RigidTy(RigidTy::FnDef(def, args)) => Some(with(|cx| cx.fn_sig(*def, args))),
247+
TyKind::RigidTy(RigidTy::FnPtr(sig)) => Some(sig.clone()),
248+
_ => None,
249+
}
250+
}
230251
}
231252

232253
pub struct TypeAndMut {
@@ -307,8 +328,9 @@ crate_def! {
307328
}
308329

309330
impl FnDef {
310-
pub fn body(&self) -> Body {
311-
with(|ctx| ctx.mir_body(self.0))
331+
// Get the function body if available.
332+
pub fn body(&self) -> Option<Body> {
333+
with(|ctx| ctx.has_body(self.0).then(|| ctx.mir_body(self.0)))
312334
}
313335
}
314336

@@ -488,6 +510,16 @@ pub struct FnSig {
488510
pub abi: Abi,
489511
}
490512

513+
impl FnSig {
514+
pub fn output(&self) -> Ty {
515+
self.inputs_and_output[self.inputs_and_output.len() - 1]
516+
}
517+
518+
pub fn inputs(&self) -> &[Ty] {
519+
&self.inputs_and_output[..self.inputs_and_output.len() - 1]
520+
}
521+
}
522+
491523
#[derive(Clone, PartialEq, Eq, Debug)]
492524
pub enum Abi {
493525
Rust,

src/bootstrap/src/core/builder.rs

+5-6
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ use std::io::{BufRead, BufReader};
1010
use std::ops::Deref;
1111
use std::path::{Path, PathBuf};
1212
use std::process::Command;
13+
use std::sync::OnceLock;
1314
use std::time::{Duration, Instant};
1415

1516
use crate::core::build_steps::llvm;
@@ -25,12 +26,10 @@ use crate::EXTRA_CHECK_CFGS;
2526
use crate::{Build, CLang, DocTests, GitRepo, Mode};
2627

2728
pub use crate::Compiler;
28-
// FIXME:
29-
// - use std::lazy for `Lazy`
30-
// - use std::cell for `OnceCell`
31-
// Once they get stabilized and reach beta.
29+
3230
use clap::ValueEnum;
33-
use once_cell::sync::{Lazy, OnceCell};
31+
// FIXME: replace with std::lazy after it gets stabilized and reaches beta
32+
use once_cell::sync::Lazy;
3433

3534
#[cfg(test)]
3635
#[path = "../tests/builder.rs"]
@@ -496,7 +495,7 @@ impl<'a> ShouldRun<'a> {
496495
///
497496
/// [`path`]: ShouldRun::path
498497
pub fn paths(mut self, paths: &[&str]) -> Self {
499-
static SUBMODULES_PATHS: OnceCell<Vec<String>> = OnceCell::new();
498+
static SUBMODULES_PATHS: OnceLock<Vec<String>> = OnceLock::new();
500499

501500
let init_submodules_paths = |src: &PathBuf| {
502501
let file = File::open(src.join(".gitmodules")).unwrap();

src/bootstrap/src/core/config/config.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ use std::io::IsTerminal;
1717
use std::path::{Path, PathBuf};
1818
use std::process::Command;
1919
use std::str::FromStr;
20+
use std::sync::OnceLock;
2021

2122
use crate::core::build_steps::compile::CODEGEN_BACKEND_PREFIX;
2223
use crate::core::build_steps::llvm;
@@ -25,7 +26,6 @@ use crate::utils::cache::{Interned, INTERNER};
2526
use crate::utils::channel::{self, GitInfo};
2627
use crate::utils::helpers::{exe, output, t};
2728
use build_helper::exit;
28-
use once_cell::sync::OnceCell;
2929
use semver::Version;
3030
use serde::{Deserialize, Deserializer};
3131
use serde_derive::Deserialize;
@@ -1907,7 +1907,7 @@ impl Config {
19071907
}
19081908

19091909
pub(crate) fn download_rustc_commit(&self) -> Option<&str> {
1910-
static DOWNLOAD_RUSTC: OnceCell<Option<String>> = OnceCell::new();
1910+
static DOWNLOAD_RUSTC: OnceLock<Option<String>> = OnceLock::new();
19111911
if self.dry_run() && DOWNLOAD_RUSTC.get().is_none() {
19121912
// avoid trying to actually download the commit
19131913
return self.download_rustc_commit.as_deref();

src/bootstrap/src/core/download.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -5,18 +5,18 @@ use std::{
55
io::{BufRead, BufReader, BufWriter, ErrorKind, Write},
66
path::{Path, PathBuf},
77
process::{Command, Stdio},
8+
sync::OnceLock,
89
};
910

1011
use build_helper::ci::CiEnv;
11-
use once_cell::sync::OnceCell;
1212
use xz2::bufread::XzDecoder;
1313

1414
use crate::core::build_steps::llvm::detect_llvm_sha;
1515
use crate::core::config::RustfmtMetadata;
1616
use crate::utils::helpers::{check_run, exe, program_out_of_date};
1717
use crate::{t, Config};
1818

19-
static SHOULD_FIX_BINS_AND_DYLIBS: OnceCell<bool> = OnceCell::new();
19+
static SHOULD_FIX_BINS_AND_DYLIBS: OnceLock<bool> = OnceLock::new();
2020

2121
/// `Config::try_run` wrapper for this module to avoid warnings on `try_run`, since we don't have access to a `builder` yet.
2222
fn try_run(config: &Config, cmd: &mut Command) -> Result<(), ()> {
@@ -131,7 +131,7 @@ impl Config {
131131
println!("attempting to patch {}", fname.display());
132132

133133
// Only build `.nix-deps` once.
134-
static NIX_DEPS_DIR: OnceCell<PathBuf> = OnceCell::new();
134+
static NIX_DEPS_DIR: OnceLock<PathBuf> = OnceLock::new();
135135
let mut nix_build_succeeded = true;
136136
let nix_deps_dir = NIX_DEPS_DIR.get_or_init(|| {
137137
// Run `nix-build` to "build" each dependency (which will likely reuse

0 commit comments

Comments
 (0)