Skip to content

Commit 1ab85fb

Browse files
committed
Auto merge of rust-lang#135438 - matthiaskrgr:rollup-rt2zrbz, r=matthiaskrgr
Rollup of 4 pull requests Successful merges: - rust-lang#133752 (replace copypasted ModuleLlvm::parse) - rust-lang#135245 (rustc_feature: Avoid unsafe `std::env::set_var()` in `UnstableFeatures` tests) - rust-lang#135405 (path: Move is_absolute check to sys::path) - rust-lang#135426 (Assert that `Instance::try_resolve` is only used on body-like things) r? `@ghost` `@rustbot` modify labels: rollup try-job: x86_64-mingw-1
2 parents 2ae9916 + 40f5861 commit 1ab85fb

File tree

18 files changed

+167
-122
lines changed

18 files changed

+167
-122
lines changed

compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs

+25-34
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ use rustc_middle::bug;
2020
use rustc_middle::hir::nested_filter::OnlyBodies;
2121
use rustc_middle::mir::tcx::PlaceTy;
2222
use rustc_middle::mir::{
23-
self, AggregateKind, BindingForm, BorrowKind, CallSource, ClearCrossCrate, ConstraintCategory,
23+
self, AggregateKind, BindingForm, BorrowKind, ClearCrossCrate, ConstraintCategory,
2424
FakeBorrowKind, FakeReadCause, LocalDecl, LocalInfo, LocalKind, Location, MutBorrowKind,
2525
Operand, Place, PlaceRef, ProjectionElem, Rvalue, Statement, StatementKind, Terminator,
2626
TerminatorKind, VarBindingForm, VarDebugInfoContents,
@@ -30,13 +30,13 @@ use rustc_middle::ty::{
3030
self, PredicateKind, Ty, TyCtxt, TypeSuperVisitable, TypeVisitor, Upcast,
3131
suggest_constraining_type_params,
3232
};
33-
use rustc_middle::util::CallKind;
3433
use rustc_mir_dataflow::move_paths::{InitKind, MoveOutIndex, MovePathIndex};
3534
use rustc_span::def_id::{DefId, LocalDefId};
3635
use rustc_span::hygiene::DesugaringKind;
3736
use rustc_span::{BytePos, Ident, Span, Symbol, kw, sym};
3837
use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
3938
use rustc_trait_selection::error_reporting::traits::FindExprBySpan;
39+
use rustc_trait_selection::error_reporting::traits::call_kind::CallKind;
4040
use rustc_trait_selection::infer::InferCtxtExt;
4141
use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _;
4242
use rustc_trait_selection::traits::{Obligation, ObligationCause, ObligationCtxt};
@@ -46,7 +46,7 @@ use super::explain_borrow::{BorrowExplanation, LaterUseKind};
4646
use super::{DescribePlaceOpt, RegionName, RegionNameSource, UseSpans};
4747
use crate::borrow_set::{BorrowData, TwoPhaseActivation};
4848
use crate::diagnostics::conflict_errors::StorageDeadOrDrop::LocalStorageDead;
49-
use crate::diagnostics::{CapturedMessageOpt, Instance, find_all_local_uses};
49+
use crate::diagnostics::{CapturedMessageOpt, call_kind, find_all_local_uses};
5050
use crate::prefixes::IsPrefixOf;
5151
use crate::{InitializationRequiringAction, MirBorrowckCtxt, WriteKind, borrowck_errors};
5252

@@ -305,7 +305,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
305305
}
306306

307307
if let UseSpans::FnSelfUse {
308-
kind: CallKind::DerefCoercion { deref_target, deref_target_ty, .. },
308+
kind: CallKind::DerefCoercion { deref_target_span, deref_target_ty, .. },
309309
..
310310
} = use_spans
311311
{
@@ -315,8 +315,10 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
315315
));
316316

317317
// Check first whether the source is accessible (issue #87060)
318-
if self.infcx.tcx.sess.source_map().is_span_accessible(deref_target) {
319-
err.span_note(deref_target, "deref defined here");
318+
if let Some(deref_target_span) = deref_target_span
319+
&& self.infcx.tcx.sess.source_map().is_span_accessible(deref_target_span)
320+
{
321+
err.span_note(deref_target_span, "deref defined here");
320322
}
321323
}
322324

@@ -3765,38 +3767,27 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
37653767

37663768
fn explain_deref_coercion(&mut self, loan: &BorrowData<'tcx>, err: &mut Diag<'_>) {
37673769
let tcx = self.infcx.tcx;
3768-
if let (
3769-
Some(Terminator {
3770-
kind: TerminatorKind::Call { call_source: CallSource::OverloadedOperator, .. },
3771-
..
3772-
}),
3773-
Some((method_did, method_args)),
3774-
) = (
3775-
&self.body[loan.reserve_location.block].terminator,
3776-
rustc_middle::util::find_self_call(
3770+
if let Some(Terminator { kind: TerminatorKind::Call { call_source, fn_span, .. }, .. }) =
3771+
&self.body[loan.reserve_location.block].terminator
3772+
&& let Some((method_did, method_args)) = rustc_middle::util::find_self_call(
37773773
tcx,
37783774
self.body,
37793775
loan.assigned_place.local,
37803776
loan.reserve_location.block,
3781-
),
3782-
) {
3783-
if tcx.is_diagnostic_item(sym::deref_method, method_did) {
3784-
let deref_target =
3785-
tcx.get_diagnostic_item(sym::deref_target).and_then(|deref_target| {
3786-
Instance::try_resolve(
3787-
tcx,
3788-
self.infcx.typing_env(self.infcx.param_env),
3789-
deref_target,
3790-
method_args,
3791-
)
3792-
.transpose()
3793-
});
3794-
if let Some(Ok(instance)) = deref_target {
3795-
let deref_target_ty =
3796-
instance.ty(tcx, self.infcx.typing_env(self.infcx.param_env));
3797-
err.note(format!("borrow occurs due to deref coercion to `{deref_target_ty}`"));
3798-
err.span_note(tcx.def_span(instance.def_id()), "deref defined here");
3799-
}
3777+
)
3778+
&& let CallKind::DerefCoercion { deref_target_span, deref_target_ty, .. } = call_kind(
3779+
self.infcx.tcx,
3780+
self.infcx.typing_env(self.infcx.param_env),
3781+
method_did,
3782+
method_args,
3783+
*fn_span,
3784+
call_source.from_hir_call(),
3785+
Some(self.infcx.tcx.fn_arg_names(method_did)[0]),
3786+
)
3787+
{
3788+
err.note(format!("borrow occurs due to deref coercion to `{deref_target_ty}`"));
3789+
if let Some(deref_target_span) = deref_target_span {
3790+
err.span_note(deref_target_span, "deref defined here");
38003791
}
38013792
}
38023793
}

compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,9 @@ use rustc_middle::mir::{
1616
};
1717
use rustc_middle::ty::adjustment::PointerCoercion;
1818
use rustc_middle::ty::{self, RegionVid, Ty, TyCtxt};
19-
use rustc_middle::util::CallKind;
2019
use rustc_span::{DesugaringKind, Span, kw, sym};
2120
use rustc_trait_selection::error_reporting::traits::FindExprBySpan;
21+
use rustc_trait_selection::error_reporting::traits::call_kind::CallKind;
2222
use tracing::{debug, instrument};
2323

2424
use super::{RegionName, UseSpans, find_use};

compiler/rustc_borrowck/src/diagnostics/mod.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -20,13 +20,13 @@ use rustc_middle::mir::{
2020
StatementKind, Terminator, TerminatorKind,
2121
};
2222
use rustc_middle::ty::print::Print;
23-
use rustc_middle::ty::{self, Instance, Ty, TyCtxt};
24-
use rustc_middle::util::{CallDesugaringKind, call_kind};
23+
use rustc_middle::ty::{self, Ty, TyCtxt};
2524
use rustc_mir_dataflow::move_paths::{InitLocation, LookupResult, MoveOutIndex};
2625
use rustc_span::def_id::LocalDefId;
2726
use rustc_span::source_map::Spanned;
2827
use rustc_span::{DUMMY_SP, ErrorGuaranteed, Span, Symbol, sym};
2928
use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
29+
use rustc_trait_selection::error_reporting::traits::call_kind::{CallDesugaringKind, call_kind};
3030
use rustc_trait_selection::infer::InferCtxtExt;
3131
use rustc_trait_selection::traits::{
3232
FulfillmentErrorCode, type_known_to_meet_bound_modulo_regions,
@@ -63,7 +63,7 @@ pub(crate) use mutability_errors::AccessKind;
6363
pub(crate) use outlives_suggestion::OutlivesSuggestionBuilder;
6464
pub(crate) use region_errors::{ErrorConstraintInfo, RegionErrorKind, RegionErrors};
6565
pub(crate) use region_name::{RegionName, RegionNameSource};
66-
pub(crate) use rustc_middle::util::CallKind;
66+
pub(crate) use rustc_trait_selection::error_reporting::traits::call_kind::CallKind;
6767

6868
pub(super) struct DescribePlaceOpt {
6969
including_downcast: bool,

compiler/rustc_codegen_llvm/src/back/lto.rs

+3-7
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,14 @@
11
use std::collections::BTreeMap;
22
use std::ffi::{CStr, CString};
33
use std::fs::File;
4-
use std::mem::ManuallyDrop;
54
use std::path::Path;
65
use std::sync::Arc;
76
use std::{io, iter, slice};
87

98
use object::read::archive::ArchiveFile;
109
use rustc_codegen_ssa::back::lto::{LtoModuleCodegen, SerializedModule, ThinModule, ThinShared};
1110
use rustc_codegen_ssa::back::symbol_export;
12-
use rustc_codegen_ssa::back::write::{CodegenContext, FatLtoInput, TargetMachineFactoryConfig};
11+
use rustc_codegen_ssa::back::write::{CodegenContext, FatLtoInput};
1312
use rustc_codegen_ssa::traits::*;
1413
use rustc_codegen_ssa::{ModuleCodegen, ModuleKind, looks_like_rust_object_file};
1514
use rustc_data_structures::fx::FxHashMap;
@@ -706,18 +705,15 @@ pub(crate) unsafe fn optimize_thin_module(
706705
let dcx = dcx.handle();
707706

708707
let module_name = &thin_module.shared.module_names[thin_module.idx];
709-
let tm_factory_config = TargetMachineFactoryConfig::new(cgcx, module_name.to_str().unwrap());
710-
let tm = (cgcx.tm_factory)(tm_factory_config).map_err(|e| write::llvm_err(dcx, e))?;
711708

712709
// Right now the implementation we've got only works over serialized
713710
// modules, so we create a fresh new LLVM context and parse the module
714711
// into that context. One day, however, we may do this for upstream
715712
// crates but for locally codegened modules we may be able to reuse
716713
// that LLVM Context and Module.
717-
let llcx = unsafe { llvm::LLVMRustContextCreate(cgcx.fewer_names) };
718-
let llmod_raw = parse_module(llcx, module_name, thin_module.data(), dcx)? as *const _;
714+
let module_llvm = ModuleLlvm::parse(cgcx, module_name, thin_module.data(), dcx)?;
719715
let mut module = ModuleCodegen {
720-
module_llvm: ModuleLlvm { llmod_raw, llcx, tm: ManuallyDrop::new(tm) },
716+
module_llvm,
721717
name: thin_module.name().to_string(),
722718
kind: ModuleKind::Regular,
723719
};

compiler/rustc_const_eval/src/check_consts/ops.rs

+8-4
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,11 @@ use rustc_middle::ty::{
1414
self, Closure, FnDef, FnPtr, GenericArgKind, GenericArgsRef, Param, TraitRef, Ty,
1515
suggest_constraining_type_param,
1616
};
17-
use rustc_middle::util::{CallDesugaringKind, CallKind, call_kind};
1817
use rustc_session::parse::add_feature_diagnostics;
1918
use rustc_span::{BytePos, Pos, Span, Symbol, sym};
19+
use rustc_trait_selection::error_reporting::traits::call_kind::{
20+
CallDesugaringKind, CallKind, call_kind,
21+
};
2022
use rustc_trait_selection::traits::SelectionContext;
2123
use tracing::debug;
2224

@@ -324,10 +326,12 @@ fn build_error_for_const_call<'tcx>(
324326
note_trait_if_possible(&mut err, self_ty, trait_id);
325327
err
326328
}
327-
CallKind::DerefCoercion { deref_target, deref_target_ty, self_ty } => {
329+
CallKind::DerefCoercion { deref_target_span, deref_target_ty, self_ty } => {
328330
// Check first whether the source is accessible (issue #87060)
329-
let target = if tcx.sess.source_map().is_span_accessible(deref_target) {
330-
Some(deref_target)
331+
let target = if let Some(deref_target_span) = deref_target_span
332+
&& tcx.sess.source_map().is_span_accessible(deref_target_span)
333+
{
334+
Some(deref_target_span)
331335
} else {
332336
None
333337
};

compiler/rustc_feature/src/lib.rs

+11-1
Original file line numberDiff line numberDiff line change
@@ -68,14 +68,24 @@ impl UnstableFeatures {
6868
/// If `krate` is [`Some`], then setting `RUSTC_BOOTSTRAP=krate` will enable the nightly
6969
/// features. Otherwise, only `RUSTC_BOOTSTRAP=1` will work.
7070
pub fn from_environment(krate: Option<&str>) -> Self {
71+
Self::from_environment_value(krate, std::env::var("RUSTC_BOOTSTRAP"))
72+
}
73+
74+
/// Avoid unsafe `std::env::set_var()` by allowing tests to inject
75+
/// `std::env::var("RUSTC_BOOTSTRAP")` with the `env_var_rustc_bootstrap`
76+
/// arg.
77+
fn from_environment_value(
78+
krate: Option<&str>,
79+
env_var_rustc_bootstrap: Result<String, std::env::VarError>,
80+
) -> Self {
7181
// `true` if this is a feature-staged build, i.e., on the beta or stable channel.
7282
let disable_unstable_features =
7383
option_env!("CFG_DISABLE_UNSTABLE_FEATURES").is_some_and(|s| s != "0");
7484
// Returns whether `krate` should be counted as unstable
7585
let is_unstable_crate =
7686
|var: &str| krate.is_some_and(|name| var.split(',').any(|new_krate| new_krate == name));
7787

78-
let bootstrap = std::env::var("RUSTC_BOOTSTRAP").ok();
88+
let bootstrap = env_var_rustc_bootstrap.ok();
7989
if let Some(val) = bootstrap.as_deref() {
8090
match val {
8191
val if val == "1" || is_unstable_crate(val) => return UnstableFeatures::Cheat,

compiler/rustc_feature/src/tests.rs

+10-6
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,11 @@ use super::UnstableFeatures;
22

33
#[test]
44
fn rustc_bootstrap_parsing() {
5-
let is_bootstrap = |env, krate| {
6-
std::env::set_var("RUSTC_BOOTSTRAP", env);
7-
matches!(UnstableFeatures::from_environment(krate), UnstableFeatures::Cheat)
5+
let is_bootstrap = |env: &str, krate: Option<&str>| {
6+
matches!(
7+
UnstableFeatures::from_environment_value(krate, Ok(env.to_string())),
8+
UnstableFeatures::Cheat
9+
)
810
};
911
assert!(is_bootstrap("1", None));
1012
assert!(is_bootstrap("1", Some("x")));
@@ -22,9 +24,11 @@ fn rustc_bootstrap_parsing() {
2224
assert!(!is_bootstrap("0", None));
2325

2426
// `RUSTC_BOOTSTRAP=-1` is force-stable, no unstable features allowed.
25-
let is_force_stable = |krate| {
26-
std::env::set_var("RUSTC_BOOTSTRAP", "-1");
27-
matches!(UnstableFeatures::from_environment(krate), UnstableFeatures::Disallow)
27+
let is_force_stable = |krate: Option<&str>| {
28+
matches!(
29+
UnstableFeatures::from_environment_value(krate, Ok("-1".to_string())),
30+
UnstableFeatures::Disallow
31+
)
2832
};
2933
assert!(is_force_stable(None));
3034
// Does not support specifying any crate.

compiler/rustc_middle/src/ty/instance.rs

+20-2
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ use std::path::PathBuf;
55
use rustc_data_structures::fx::FxHashMap;
66
use rustc_errors::ErrorGuaranteed;
77
use rustc_hir as hir;
8-
use rustc_hir::def::Namespace;
8+
use rustc_hir::def::{CtorKind, DefKind, Namespace};
99
use rustc_hir::def_id::{CrateNum, DefId};
1010
use rustc_hir::lang_items::LangItem;
1111
use rustc_index::bit_set::FiniteBitSet;
@@ -498,7 +498,8 @@ impl<'tcx> Instance<'tcx> {
498498

499499
/// Resolves a `(def_id, args)` pair to an (optional) instance -- most commonly,
500500
/// this is used to find the precise code that will run for a trait method invocation,
501-
/// if known.
501+
/// if known. This should only be used for functions and consts. If you want to
502+
/// resolve an associated type, use [`TyCtxt::try_normalize_erasing_regions`].
502503
///
503504
/// Returns `Ok(None)` if we cannot resolve `Instance` to a specific instance.
504505
/// For example, in a context like this,
@@ -527,6 +528,23 @@ impl<'tcx> Instance<'tcx> {
527528
def_id: DefId,
528529
args: GenericArgsRef<'tcx>,
529530
) -> Result<Option<Instance<'tcx>>, ErrorGuaranteed> {
531+
assert_matches!(
532+
tcx.def_kind(def_id),
533+
DefKind::Fn
534+
| DefKind::AssocFn
535+
| DefKind::Const
536+
| DefKind::AssocConst
537+
| DefKind::AnonConst
538+
| DefKind::InlineConst
539+
| DefKind::Static { .. }
540+
| DefKind::Ctor(_, CtorKind::Fn)
541+
| DefKind::Closure
542+
| DefKind::SyntheticCoroutineBody,
543+
"`Instance::try_resolve` should only be used to resolve instances of \
544+
functions, statics, and consts; to resolve associated types, use \
545+
`try_normalize_erasing_regions`."
546+
);
547+
530548
// Rust code can easily create exponentially-long types using only a
531549
// polynomial recursion depth. Even with the default recursion
532550
// depth, you can easily get cases that take >2^60 steps to run,

compiler/rustc_middle/src/util/mod.rs

-2
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,7 @@
11
pub mod bug;
2-
pub mod call_kind;
32
pub mod common;
43
pub mod find_self_call;
54

6-
pub use call_kind::{CallDesugaringKind, CallKind, call_kind};
75
pub use find_self_call::find_self_call;
86

97
#[derive(Default, Copy, Clone)]

0 commit comments

Comments
 (0)