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 7 pull requests #131500

Closed
wants to merge 19 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
4af6137
Don't check unsize goal in MIR validation when opaques remain
compiler-errors Sep 28, 2024
7b3f161
Add gate for precise capturing in traits
compiler-errors Sep 29, 2024
e4bf471
Add variances to RPITITs
compiler-errors Sep 29, 2024
f2659ef
Clarify implicit captures for RPITIT
compiler-errors Sep 29, 2024
960ba89
Don't fire refinement lint if there are errors
compiler-errors Sep 29, 2024
becf664
Match std RUSTFLAGS for host and target for `mir-opt` test
jieyouxu Oct 9, 2024
62b24ea
Compiler: Replace remaining occurrences of "object safe" with "dyn co…
fmease Oct 9, 2024
2e7a52b
Rename feature object_safe_for_dispatch to dyn_compatible_for_dispatch
fmease Oct 9, 2024
20cebae
UI tests: Rename "object safe" to "dyn compatible"
fmease Oct 9, 2024
a21a9fe
Auto merge of #13464 - y21:issue13458, r=flip1995
bors Oct 10, 2024
b12dc20
add config to explicitely test rustc with autodiff/enzyme disabled
ZuseZ4 Oct 10, 2024
1edff46
Avoid redundant additions to PATH when linking
madsmtm Oct 10, 2024
1696043
Rollup merge of #130989 - compiler-errors:unsize-opaque, r=estebank
matthiaskrgr Oct 10, 2024
5d515e6
Rollup merge of #131033 - compiler-errors:precise-capturing-in-traits…
matthiaskrgr Oct 10, 2024
07aab90
Rollup merge of #131442 - jieyouxu:mir-opt-rebuild, r=onur-ozkan
matthiaskrgr Oct 10, 2024
760650c
Rollup merge of #131470 - EnzymeAD:enzyme-testinfra2, r=jieyouxu
matthiaskrgr Oct 10, 2024
d5624a2
Rollup merge of #131475 - fmease:compiler-mv-obj-safe-dyn-compat-2, r…
matthiaskrgr Oct 10, 2024
04257c1
Rollup merge of #131492 - flip1995:clippy-master-backport, r=matthias…
matthiaskrgr Oct 10, 2024
adb659f
Rollup merge of #131493 - madsmtm:avoid-redundant-linker-path, r=jiey…
matthiaskrgr Oct 10, 2024
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
19 changes: 14 additions & 5 deletions compiler/rustc_ast_lowering/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1573,11 +1573,20 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
// Feature gate for RPITIT + use<..>
match origin {
rustc_hir::OpaqueTyOrigin::FnReturn { in_trait_or_impl: Some(_), .. } => {
if let Some(span) = bounds.iter().find_map(|bound| match *bound {
ast::GenericBound::Use(_, span) => Some(span),
_ => None,
}) {
self.tcx.dcx().emit_err(errors::NoPreciseCapturesOnRpitit { span });
if !self.tcx.features().precise_capturing_in_traits
&& let Some(span) = bounds.iter().find_map(|bound| match *bound {
ast::GenericBound::Use(_, span) => Some(span),
_ => None,
})
{
let mut diag =
self.tcx.dcx().create_err(errors::NoPreciseCapturesOnRpitit { span });
add_feature_diagnostics(
&mut diag,
self.tcx.sess,
sym::precise_capturing_in_traits,
);
diag.emit();
}
}
_ => {}
Expand Down
4 changes: 4 additions & 0 deletions compiler/rustc_feature/src/removed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,10 @@ declare_features! (
/// then removed. But there was no utility storing it separately, so now
/// it's in this list.
(removed, no_stack_check, "1.0.0", None, None),
/// Allows making `dyn Trait` well-formed even if `Trait` is not dyn-compatible (object safe).
/// Renamed to `dyn_compatible_for_dispatch`.
(removed, object_safe_for_dispatch, "CURRENT_RUSTC_VERSION", Some(43561),
Some("renamed to `dyn_compatible_for_dispatch`")),
/// Allows using `#[on_unimplemented(..)]` on traits.
/// (Moved to `rustc_attrs`.)
(removed, on_unimplemented, "1.40.0", None, None),
Expand Down
17 changes: 10 additions & 7 deletions compiler/rustc_feature/src/unstable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,14 @@ declare_features! (
(unstable, doc_notable_trait, "1.52.0", Some(45040)),
/// Allows using the `may_dangle` attribute (RFC 1327).
(unstable, dropck_eyepatch, "1.10.0", Some(34761)),
/// Allows making `dyn Trait` well-formed even if `Trait` is not dyn-compatible[^1].
/// In that case, `dyn Trait: Trait` does not hold. Moreover, coercions and
/// casts in safe Rust to `dyn Trait` for such a `Trait` is also forbidden.
///
/// Renamed from `object_safe_for_dispatch`.
///
/// [^1]: Formerly known as "object safe".
(unstable, dyn_compatible_for_dispatch, "CURRENT_RUSTC_VERSION", Some(43561)),
/// Allows using the `#[fundamental]` attribute.
(unstable, fundamental, "1.0.0", Some(29635)),
/// Allows using `#[link_name="llvm.*"]`.
Expand Down Expand Up @@ -546,13 +554,6 @@ declare_features! (
(unstable, non_exhaustive_omitted_patterns_lint, "1.57.0", Some(89554)),
/// Allows `for<T>` binders in where-clauses
(incomplete, non_lifetime_binders, "1.69.0", Some(108185)),
/// Allows making `dyn Trait` well-formed even if `Trait` is not dyn-compatible[^1].
/// In that case, `dyn Trait: Trait` does not hold. Moreover, coercions and
/// casts in safe Rust to `dyn Trait` for such a `Trait` is also forbidden.
///
/// [^1]: Formerly known as "object safe".
// FIXME(dyn_compat_renaming): Rename feature.
(unstable, object_safe_for_dispatch, "1.40.0", Some(43561)),
/// Allows using enums in offset_of!
(unstable, offset_of_enum, "1.75.0", Some(120141)),
/// Allows using fields with slice type in offset_of!
Expand All @@ -565,6 +566,8 @@ declare_features! (
(incomplete, pin_ergonomics, "CURRENT_RUSTC_VERSION", Some(130494)),
/// Allows postfix match `expr.match { ... }`
(unstable, postfix_match, "1.79.0", Some(121618)),
/// Allows `use<..>` precise capturign on impl Trait in traits.
(unstable, precise_capturing_in_traits, "CURRENT_RUSTC_VERSION", Some(130044)),
/// Allows macro attributes on expressions, statements and non-inline modules.
(unstable, proc_macro_hygiene, "1.30.0", Some(54727)),
/// Makes `&` and `&mut` patterns eat only one layer of references in Rust 2024.
Expand Down
3 changes: 3 additions & 0 deletions compiler/rustc_hir_analysis/messages.ftl
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,9 @@ hir_analysis_late_bound_lifetime_in_apit = `impl Trait` can only mention lifetim
hir_analysis_late_bound_type_in_apit = `impl Trait` can only mention type parameters from an fn or impl
.label = type parameter declared here

hir_analysis_lifetime_implicitly_captured = `impl Trait` captures lifetime parameter, but it is not mentioned in `use<...>` precise captures list
.param_label = all lifetime parameters originating from a trait are captured implicitly

hir_analysis_lifetime_must_be_first = lifetime parameter `{$name}` must be listed before non-lifetime parameters
.label = move the lifetime before this parameter

Expand Down
25 changes: 16 additions & 9 deletions compiler/rustc_hir_analysis/src/check/check.rs
Original file line number Diff line number Diff line change
Expand Up @@ -589,15 +589,22 @@ fn check_opaque_precise_captures<'tcx>(tcx: TyCtxt<'tcx>, opaque_def_id: LocalDe
param_span: tcx.def_span(def_id),
});
} else {
// If the `use_span` is actually just the param itself, then we must
// have not duplicated the lifetime but captured the original.
// The "effective" `use_span` will be the span of the opaque itself,
// and the param span will be the def span of the param.
tcx.dcx().emit_err(errors::LifetimeNotCaptured {
opaque_span,
use_span: opaque_span,
param_span: use_span,
});
if tcx.def_kind(tcx.parent(param.def_id)) == DefKind::Trait {
tcx.dcx().emit_err(errors::LifetimeImplicitlyCaptured {
opaque_span,
param_span: tcx.def_span(param.def_id),
});
} else {
// If the `use_span` is actually just the param itself, then we must
// have not duplicated the lifetime but captured the original.
// The "effective" `use_span` will be the span of the opaque itself,
// and the param span will be the def span of the param.
tcx.dcx().emit_err(errors::LifetimeNotCaptured {
opaque_span,
use_span: opaque_span,
param_span: use_span,
});
}
}
continue;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,10 @@ pub(super) fn check_refining_return_position_impl_trait_in_trait<'tcx>(
return;
};

if hidden_tys.items().any(|(_, &ty)| ty.skip_binder().references_error()) {
return;
}

let mut collector = ImplTraitInTraitCollector { tcx, types: FxIndexSet::default() };
trait_m_sig.visit_with(&mut collector);

Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_hir_analysis/src/coherence/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,7 @@ fn check_object_overlap<'tcx>(
for component_def_id in component_def_ids {
if !tcx.is_dyn_compatible(component_def_id) {
// FIXME(dyn_compat_renaming): Rename test and update comment.
// Without the 'object_safe_for_dispatch' feature this is an error
// Without the 'dyn_compatible_for_dispatch' feature this is an error
// which will be reported by wfcheck. Ignore it here.
// This is tested by `coherence-impl-trait-for-trait-object-safe.rs`.
// With the feature enabled, the trait is not implemented automatically,
Expand Down
9 changes: 9 additions & 0 deletions compiler/rustc_hir_analysis/src/errors/precise_captures.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,15 @@ pub(crate) struct LifetimeNotCaptured {
pub opaque_span: Span,
}

#[derive(Diagnostic)]
#[diag(hir_analysis_lifetime_implicitly_captured)]
pub(crate) struct LifetimeImplicitlyCaptured {
#[primary_span]
pub opaque_span: Span,
#[label(hir_analysis_param_label)]
pub param_span: Span,
}

#[derive(Diagnostic)]
#[diag(hir_analysis_bad_precise_capture)]
pub(crate) struct BadPreciseCapture {
Expand Down
49 changes: 44 additions & 5 deletions compiler/rustc_hir_analysis/src/variance/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

use itertools::Itertools;
use rustc_arena::DroplessArena;
use rustc_hir as hir;
use rustc_hir::def::DefKind;
use rustc_hir::def_id::{DefId, LocalDefId};
use rustc_middle::query::Providers;
Expand Down Expand Up @@ -63,8 +64,29 @@ fn variances_of(tcx: TyCtxt<'_>, item_def_id: LocalDefId) -> &[ty::Variance] {
let crate_map = tcx.crate_variances(());
return crate_map.variances.get(&item_def_id.to_def_id()).copied().unwrap_or(&[]);
}
DefKind::AssocTy => match tcx.opt_rpitit_info(item_def_id.to_def_id()) {
Some(ty::ImplTraitInTraitData::Trait { opaque_def_id, .. }) => {
return variance_of_opaque(
tcx,
opaque_def_id.expect_local(),
ForceCaptureTraitArgs::Yes,
);
}
None | Some(ty::ImplTraitInTraitData::Impl { .. }) => {}
},
DefKind::OpaqueTy => {
return variance_of_opaque(tcx, item_def_id);
let force_capture_trait_args = if let hir::OpaqueTyOrigin::FnReturn {
parent: _,
in_trait_or_impl: Some(hir::RpitContext::Trait),
} =
tcx.hir_node_by_def_id(item_def_id).expect_opaque_ty().origin
{
ForceCaptureTraitArgs::Yes
} else {
ForceCaptureTraitArgs::No
};

return variance_of_opaque(tcx, item_def_id, force_capture_trait_args);
}
_ => {}
}
Expand All @@ -73,8 +95,18 @@ fn variances_of(tcx: TyCtxt<'_>, item_def_id: LocalDefId) -> &[ty::Variance] {
span_bug!(tcx.def_span(item_def_id), "asked to compute variance for wrong kind of item");
}

#[derive(Debug, Copy, Clone)]
enum ForceCaptureTraitArgs {
Yes,
No,
}

#[instrument(level = "trace", skip(tcx), ret)]
fn variance_of_opaque(tcx: TyCtxt<'_>, item_def_id: LocalDefId) -> &[ty::Variance] {
fn variance_of_opaque(
tcx: TyCtxt<'_>,
item_def_id: LocalDefId,
force_capture_trait_args: ForceCaptureTraitArgs,
) -> &[ty::Variance] {
let generics = tcx.generics_of(item_def_id);

// Opaque types may only use regions that are bound. So for
Expand Down Expand Up @@ -115,9 +147,7 @@ fn variance_of_opaque(tcx: TyCtxt<'_>, item_def_id: LocalDefId) -> &[ty::Varianc
#[instrument(level = "trace", skip(self), ret)]
fn visit_ty(&mut self, t: Ty<'tcx>) {
match t.kind() {
ty::Alias(_, ty::AliasTy { def_id, args, .. })
if matches!(self.tcx.def_kind(*def_id), DefKind::OpaqueTy) =>
{
ty::Alias(ty::Opaque, ty::AliasTy { def_id, args, .. }) => {
self.visit_opaque(*def_id, args);
}
_ => t.super_visit_with(self),
Expand All @@ -135,6 +165,15 @@ fn variance_of_opaque(tcx: TyCtxt<'_>, item_def_id: LocalDefId) -> &[ty::Varianc
let mut generics = generics;
while let Some(def_id) = generics.parent {
generics = tcx.generics_of(def_id);

// Don't mark trait params generic if we're in an RPITIT.
if matches!(force_capture_trait_args, ForceCaptureTraitArgs::Yes)
&& generics.parent.is_none()
{
debug_assert_eq!(tcx.def_kind(def_id), DefKind::Trait);
break;
}

for param in &generics.own_params {
match param.kind {
ty::GenericParamDefKind::Lifetime => {
Expand Down
5 changes: 4 additions & 1 deletion compiler/rustc_metadata/src/rmeta/encoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1100,9 +1100,12 @@ fn should_encode_variances<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, def_kind: Def
| DefKind::Fn
| DefKind::Ctor(..)
| DefKind::AssocFn => true,
DefKind::AssocTy => {
// Only encode variances for RPITITs (for traits)
matches!(tcx.opt_rpitit_info(def_id), Some(ty::ImplTraitInTraitData::Trait { .. }))
}
DefKind::Mod
| DefKind::Field
| DefKind::AssocTy
| DefKind::AssocConst
| DefKind::TyParam
| DefKind::ConstParam
Expand Down
4 changes: 4 additions & 0 deletions compiler/rustc_middle/src/ty/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -539,6 +539,10 @@ impl<'tcx> Interner for TyCtxt<'tcx> {
self.trait_def(trait_def_id).implement_via_object
}

fn is_impl_trait_in_trait(self, def_id: DefId) -> bool {
self.is_impl_trait_in_trait(def_id)
}

fn delay_bug(self, msg: impl ToString) -> ErrorGuaranteed {
self.dcx().span_delayed_bug(DUMMY_SP, msg.to_string())
}
Expand Down
11 changes: 11 additions & 0 deletions compiler/rustc_mir_transform/src/validate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -595,6 +595,17 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
&self,
pred: impl Upcast<TyCtxt<'tcx>, ty::Predicate<'tcx>>,
) -> bool {
let pred: ty::Predicate<'tcx> = pred.upcast(self.tcx);

// We sometimes have to use `defining_opaque_types` for predicates
// to succeed here and figuring out how exactly that should work
// is annoying. It is harmless enough to just not validate anything
// in that case. We still check this after analysis as all opaque
// types have been revealed at this point.
if pred.has_opaque_types() {
return true;
}

let infcx = self.tcx.infer_ctxt().build();
let ocx = ObligationCtxt::new(&infcx);
ocx.register_obligation(Obligation::new(
Expand Down
2 changes: 2 additions & 0 deletions compiler/rustc_session/src/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -454,6 +454,8 @@ impl Session {
let bin_path = filesearch::make_target_bin_path(&self.sysroot, config::host_triple());
let fallback_sysroot_paths = filesearch::sysroot_candidates()
.into_iter()
// Ignore sysroot candidate if it was the same as the sysroot path we just used.
.filter(|sysroot| *sysroot != self.sysroot)
.map(|sysroot| filesearch::make_target_bin_path(&sysroot, config::host_triple()));
let search_paths = std::iter::once(bin_path).chain(fallback_sysroot_paths);

Expand Down
2 changes: 2 additions & 0 deletions compiler/rustc_span/src/symbol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -777,6 +777,7 @@ symbols! {
dropck_eyepatch,
dropck_parametricity,
dylib,
dyn_compatible_for_dispatch,
dyn_metadata,
dyn_star,
dyn_trait,
Expand Down Expand Up @@ -1479,6 +1480,7 @@ symbols! {
powif64,
pre_dash_lto: "pre-lto",
precise_capturing,
precise_capturing_in_traits,
precise_pointer_size_matching,
pref_align_of,
prefetch_read_data,
Expand Down
24 changes: 10 additions & 14 deletions compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,8 @@
//! "Object safety" refers to the ability for a trait to be converted
//! to an object. In general, traits may only be converted to an
//! object if all of their methods meet certain criteria. In particular,
//! they must:
//! "Dyn-compatibility"[^1] refers to the ability for a trait to be converted
//! to a trait object. In general, traits may only be converted to a trait
//! object if certain criteria are met.
//!
//! - have a suitable receiver from which we can extract a vtable and coerce to a "thin" version
//! that doesn't contain the vtable;
//! - not reference the erased type `Self` except for in this receiver;
//! - not have generic type parameters.
//! [^1]: Formerly known as "object safety".

use std::iter;
use std::ops::ControlFlow;
Expand Down Expand Up @@ -506,8 +502,8 @@ fn virtual_call_violations_for_method<'tcx>(

/// This code checks that `receiver_is_dispatchable` is correctly implemented.
///
/// This check is outlined from the object safety check to avoid cycles with
/// layout computation, which relies on knowing whether methods are object safe.
/// This check is outlined from the dyn-compatibility check to avoid cycles with
/// layout computation, which relies on knowing whether methods are dyn-compatible.
fn check_receiver_correct<'tcx>(tcx: TyCtxt<'tcx>, trait_def_id: DefId, method: ty::AssocItem) {
if !is_vtable_safe_method(tcx, trait_def_id, method) {
return;
Expand Down Expand Up @@ -643,8 +639,8 @@ fn object_ty_for_trait<'tcx>(
/// contained by the trait object, because the object that needs to be coerced is behind
/// a pointer.
///
/// In practice, we cannot use `dyn Trait` explicitly in the obligation because it would result
/// in a new check that `Trait` is object safe, creating a cycle (until object_safe_for_dispatch
/// In practice, we cannot use `dyn Trait` explicitly in the obligation because it would result in
/// a new check that `Trait` is dyn-compatible, creating a cycle (until dyn_compatible_for_dispatch
/// is stabilized, see tracking issue <https://github.com/rust-lang/rust/issues/43561>).
/// Instead, we fudge a little by introducing a new type parameter `U` such that
/// `Self: Unsize<U>` and `U: Trait + ?Sized`, and use `U` in place of `dyn Trait`.
Expand Down Expand Up @@ -678,7 +674,7 @@ fn receiver_is_dispatchable<'tcx>(

// the type `U` in the query
// use a bogus type parameter to mimic a forall(U) query using u32::MAX for now.
// FIXME(mikeyhew) this is a total hack. Once object_safe_for_dispatch is stabilized, we can
// FIXME(mikeyhew) this is a total hack. Once dyn_compatible_for_dispatch is stabilized, we can
// replace this with `dyn Trait`
let unsized_self_ty: Ty<'tcx> =
Ty::new_param(tcx, u32::MAX, Symbol::intern("RustaceansAreAwesome"));
Expand Down Expand Up @@ -865,7 +861,7 @@ impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for IllegalSelfTypeVisitor<'tcx> {
}

fn visit_const(&mut self, ct: ty::Const<'tcx>) -> Self::Result {
// Constants can only influence object safety if they are generic and reference `Self`.
// Constants can only influence dyn-compatibility if they are generic and reference `Self`.
// This is only possible for unevaluated constants, so we walk these here.
self.tcx.expand_abstract_consts(ct).super_visit_with(self)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -881,7 +881,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
}

if let Some(principal) = data.principal() {
if !self.infcx.tcx.features().object_safe_for_dispatch {
if !self.infcx.tcx.features().dyn_compatible_for_dispatch {
principal.with_self_ty(self.tcx(), self_ty)
} else if self.tcx().is_dyn_compatible(principal.def_id()) {
principal.with_self_ty(self.tcx(), self_ty)
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_trait_selection/src/traits/wf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -829,7 +829,7 @@ impl<'a, 'tcx> TypeVisitor<TyCtxt<'tcx>> for WfPredicates<'a, 'tcx> {
// obligations that don't refer to Self and
// checking those

let defer_to_coercion = tcx.features().object_safe_for_dispatch;
let defer_to_coercion = tcx.features().dyn_compatible_for_dispatch;

if !defer_to_coercion {
if let Some(principal) = data.principal_def_id() {
Expand Down
2 changes: 2 additions & 0 deletions compiler/rustc_type_ir/src/interner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -261,6 +261,8 @@ pub trait Interner:

fn trait_may_be_implemented_via_object(self, trait_def_id: Self::DefId) -> bool;

fn is_impl_trait_in_trait(self, def_id: Self::DefId) -> bool;

fn delay_bug(self, msg: impl ToString) -> Self::ErrorGuaranteed;

fn is_general_coroutine(self, coroutine_def_id: Self::DefId) -> bool;
Expand Down
Loading
Loading