Skip to content

Commit

Permalink
Auto merge of rust-lang#120157 - matthiaskrgr:rollup-f0p3wkk, r=matth…
Browse files Browse the repository at this point in the history
…iaskrgr

Rollup of 10 pull requests

Successful merges:

 - rust-lang#103730 (Added NonZeroXxx::from_mut(_unchecked)?)
 - rust-lang#113142 (optimize EscapeAscii's Display  and CStr's Debug)
 - rust-lang#118799 (Stabilize single-field offset_of)
 - rust-lang#119613 (Expose Obligations created during type inference.)
 - rust-lang#119752 (Avoid ICEs in trait names without `dyn`)
 - rust-lang#120132 (Teach tidy about line/col information for malformed features)
 - rust-lang#120135 (SMIR: Make the remaining "private" fields actually private)
 - rust-lang#120148 (`single_use_lifetimes`: Don't suggest deleting lifetimes with bounds)
 - rust-lang#120150 (Stabilize `round_ties_even`)
 - rust-lang#120155 (Don't use `ReErased` to detect type test promotion failed)

r? `@ghost`
`@rustbot` modify labels: rollup
  • Loading branch information
bors committed Jan 20, 2024
2 parents 5378c1c + bb816e6 commit 314384b
Show file tree
Hide file tree
Showing 69 changed files with 1,032 additions and 155 deletions.
14 changes: 9 additions & 5 deletions compiler/rustc_borrowck/src/region_infer/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ use rustc_middle::mir::{
};
use rustc_middle::traits::ObligationCause;
use rustc_middle::traits::ObligationCauseCode;
use rustc_middle::ty::{self, RegionVid, Ty, TyCtxt, TypeFoldable, TypeVisitableExt};
use rustc_middle::ty::{self, RegionVid, Ty, TyCtxt, TypeFoldable};
use rustc_mir_dataflow::points::DenseLocationMap;
use rustc_span::Span;

Expand Down Expand Up @@ -1145,6 +1145,7 @@ impl<'tcx> RegionInferenceContext<'tcx> {
}

let ty = ty.fold_with(&mut OpaqueFolder { tcx });
let mut failed = false;

let ty = tcx.fold_regions(ty, |r, _depth| {
let r_vid = self.to_region_vid(r);
Expand All @@ -1160,15 +1161,18 @@ impl<'tcx> RegionInferenceContext<'tcx> {
.filter(|&u_r| !self.universal_regions.is_local_free_region(u_r))
.find(|&u_r| self.eval_equal(u_r, r_vid))
.map(|u_r| ty::Region::new_var(tcx, u_r))
// In the case of a failure, use `ReErased`. We will eventually
// return `None` in this case.
.unwrap_or(tcx.lifetimes.re_erased)
// In case we could not find a named region to map to,
// we will return `None` below.
.unwrap_or_else(|| {
failed = true;
r
})
});

debug!("try_promote_type_test_subject: folded ty = {:?}", ty);

// This will be true if we failed to promote some region.
if ty.has_erased_regions() {
if failed {
return None;
}

Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_error_codes/src/error_codes/E0795.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ Invalid argument for the `offset_of!` macro.
Erroneous code example:

```compile_fail,E0795
#![feature(offset_of, offset_of_enum)]
#![feature(offset_of_enum, offset_of_nested)]
let x = std::mem::offset_of!(Option<u8>, Some);
```
Expand All @@ -16,7 +16,7 @@ The offset of the contained `u8` in the `Option<u8>` can be found by specifying
the field name `0`:

```
#![feature(offset_of, offset_of_enum)]
#![feature(offset_of_enum, offset_of_nested)]
let x: usize = std::mem::offset_of!(Option<u8>, Some.0);
```
Expand Down
4 changes: 3 additions & 1 deletion compiler/rustc_feature/src/unstable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -549,7 +549,9 @@ declare_features! (
/// casts in safe Rust to `dyn Trait` for such a `Trait` is also forbidden.
(unstable, object_safe_for_dispatch, "1.40.0", Some(43561)),
/// Allows using enums in offset_of!
(unstable, offset_of_enum, "1.75.0", Some(106655)),
(unstable, offset_of_enum, "1.75.0", Some(120141)),
/// Allows using multiple nested field accesses in offset_of!
(unstable, offset_of_nested, "CURRENT_RUSTC_VERSION", Some(120140)),
/// Allows using `#[optimize(X)]`.
(unstable, optimize_attribute, "1.34.0", Some(54882)),
/// Allows macro attributes on expressions, statements and non-inline modules.
Expand Down
32 changes: 21 additions & 11 deletions compiler/rustc_hir_analysis/src/astconv/lint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,14 +78,17 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
fn maybe_lint_impl_trait(&self, self_ty: &hir::Ty<'_>, diag: &mut Diagnostic) -> bool {
let tcx = self.tcx();
let parent_id = tcx.hir().get_parent_item(self_ty.hir_id).def_id;
let (hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, generics, _), .. })
| hir::Node::TraitItem(hir::TraitItem {
kind: hir::TraitItemKind::Fn(sig, _),
generics,
..
})) = tcx.hir_node_by_def_id(parent_id)
else {
return false;
let (sig, generics, owner) = match tcx.hir_node_by_def_id(parent_id) {
hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, generics, _), .. }) => {
(sig, generics, None)
}
hir::Node::TraitItem(hir::TraitItem {
kind: hir::TraitItemKind::Fn(sig, _),
generics,
owner_id,
..
}) => (sig, generics, Some(tcx.parent(owner_id.to_def_id()))),
_ => return false,
};
let Ok(trait_name) = tcx.sess.source_map().span_to_snippet(self_ty.span) else {
return false;
Expand All @@ -94,6 +97,11 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
let is_object_safe = match self_ty.kind {
hir::TyKind::TraitObject(objects, ..) => {
objects.iter().all(|o| match o.trait_ref.path.res {
Res::Def(DefKind::Trait, id) if Some(id) == owner => {
// When we're dealing with a recursive trait, we don't want to downgrade
// the error, so we consider them to be object safe always. (#119652)
true
}
Res::Def(DefKind::Trait, id) => tcx.check_is_object_safe(id),
_ => false,
})
Expand Down Expand Up @@ -122,7 +130,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
],
Applicability::MachineApplicable,
);
} else {
} else if diag.is_error() {
// We'll emit the object safety error already, with a structured suggestion.
diag.downgrade_to_delayed_bug();
}
Expand All @@ -148,8 +156,10 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
}
if !is_object_safe {
diag.note(format!("`{trait_name}` it is not object safe, so it can't be `dyn`"));
// We'll emit the object safety error already, with a structured suggestion.
diag.downgrade_to_delayed_bug();
if diag.is_error() {
// We'll emit the object safety error already, with a structured suggestion.
diag.downgrade_to_delayed_bug();
}
} else {
let sugg = if let hir::TyKind::TraitObject([_, _, ..], _, _) = self_ty.kind {
// There are more than one trait bound, we need surrounding parentheses.
Expand Down
12 changes: 12 additions & 0 deletions compiler/rustc_hir_typeck/src/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3246,6 +3246,18 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
) -> Ty<'tcx> {
let container = self.to_ty(container).normalized;

if let Some(ident_2) = fields.get(1)
&& !self.tcx.features().offset_of_nested
{
rustc_session::parse::feature_err(
&self.tcx.sess,
sym::offset_of_nested,
ident_2.span,
"only a single ident or integer is stable as the field in offset_of",
)
.emit();
}

let mut field_indices = Vec::with_capacity(fields.len());
let mut current_container = container;
let mut fields = fields.into_iter();
Expand Down
24 changes: 21 additions & 3 deletions compiler/rustc_hir_typeck/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ use rustc_hir::{HirIdMap, Node};
use rustc_hir_analysis::astconv::AstConv;
use rustc_hir_analysis::check::check_abi;
use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
use rustc_infer::traits::ObligationInspector;
use rustc_middle::query::Providers;
use rustc_middle::traits;
use rustc_middle::ty::{self, Ty, TyCtxt};
Expand Down Expand Up @@ -139,7 +140,7 @@ fn used_trait_imports(tcx: TyCtxt<'_>, def_id: LocalDefId) -> &UnordSet<LocalDef

fn typeck<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> &ty::TypeckResults<'tcx> {
let fallback = move || tcx.type_of(def_id.to_def_id()).instantiate_identity();
typeck_with_fallback(tcx, def_id, fallback)
typeck_with_fallback(tcx, def_id, fallback, None)
}

/// Used only to get `TypeckResults` for type inference during error recovery.
Expand All @@ -149,14 +150,28 @@ fn diagnostic_only_typeck<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> &ty::T
let span = tcx.hir().span(tcx.local_def_id_to_hir_id(def_id));
Ty::new_error_with_message(tcx, span, "diagnostic only typeck table used")
};
typeck_with_fallback(tcx, def_id, fallback)
typeck_with_fallback(tcx, def_id, fallback, None)
}

#[instrument(level = "debug", skip(tcx, fallback), ret)]
/// Same as `typeck` but `inspect` is invoked on evaluation of each root obligation.
/// Inspecting obligations only works with the new trait solver.
/// This function is *only to be used* by external tools, it should not be
/// called from within rustc. Note, this is not a query, and thus is not cached.
pub fn inspect_typeck<'tcx>(
tcx: TyCtxt<'tcx>,
def_id: LocalDefId,
inspect: ObligationInspector<'tcx>,
) -> &'tcx ty::TypeckResults<'tcx> {
let fallback = move || tcx.type_of(def_id.to_def_id()).instantiate_identity();
typeck_with_fallback(tcx, def_id, fallback, Some(inspect))
}

#[instrument(level = "debug", skip(tcx, fallback, inspector), ret)]
fn typeck_with_fallback<'tcx>(
tcx: TyCtxt<'tcx>,
def_id: LocalDefId,
fallback: impl Fn() -> Ty<'tcx> + 'tcx,
inspector: Option<ObligationInspector<'tcx>>,
) -> &'tcx ty::TypeckResults<'tcx> {
// Closures' typeck results come from their outermost function,
// as they are part of the same "inference environment".
Expand All @@ -178,6 +193,9 @@ fn typeck_with_fallback<'tcx>(
let param_env = tcx.param_env(def_id);

let inh = Inherited::new(tcx, def_id);
if let Some(inspector) = inspector {
inh.infcx.attach_obligation_inspector(inspector);
}
let mut fcx = FnCtxt::new(&inh, param_env, def_id);

if let Some(hir::FnSig { header, decl, .. }) = fn_sig {
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_infer/src/infer/at.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ impl<'tcx> InferCtxt<'tcx> {
universe: self.universe.clone(),
intercrate,
next_trait_solver: self.next_trait_solver,
obligation_inspector: self.obligation_inspector.clone(),
}
}
}
Expand Down
16 changes: 15 additions & 1 deletion compiler/rustc_infer/src/infer/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@ use rustc_middle::infer::unify_key::{ConstVidKey, EffectVidKey};
use self::opaque_types::OpaqueTypeStorage;
pub(crate) use self::undo_log::{InferCtxtUndoLogs, Snapshot, UndoLog};

use crate::traits::{self, ObligationCause, PredicateObligations, TraitEngine, TraitEngineExt};
use crate::traits::{
self, ObligationCause, ObligationInspector, PredicateObligations, TraitEngine, TraitEngineExt,
};

use rustc_data_structures::fx::FxIndexMap;
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
Expand Down Expand Up @@ -334,6 +336,8 @@ pub struct InferCtxt<'tcx> {
pub intercrate: bool,

next_trait_solver: bool,

pub obligation_inspector: Cell<Option<ObligationInspector<'tcx>>>,
}

impl<'tcx> ty::InferCtxtLike for InferCtxt<'tcx> {
Expand Down Expand Up @@ -708,6 +712,7 @@ impl<'tcx> InferCtxtBuilder<'tcx> {
universe: Cell::new(ty::UniverseIndex::ROOT),
intercrate,
next_trait_solver,
obligation_inspector: Cell::new(None),
}
}
}
Expand Down Expand Up @@ -1718,6 +1723,15 @@ impl<'tcx> InferCtxt<'tcx> {
}
}
}

/// Attach a callback to be invoked on each root obligation evaluated in the new trait solver.
pub fn attach_obligation_inspector(&self, inspector: ObligationInspector<'tcx>) {
debug_assert!(
self.obligation_inspector.get().is_none(),
"shouldn't override a set obligation inspector"
);
self.obligation_inspector.set(Some(inspector));
}
}

impl<'tcx> TypeErrCtxt<'_, 'tcx> {
Expand Down
8 changes: 8 additions & 0 deletions compiler/rustc_infer/src/traits/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,15 @@ use std::hash::{Hash, Hasher};

use hir::def_id::LocalDefId;
use rustc_hir as hir;
use rustc_middle::traits::query::NoSolution;
use rustc_middle::traits::solve::Certainty;
use rustc_middle::ty::error::{ExpectedFound, TypeError};
use rustc_middle::ty::{self, Const, ToPredicate, Ty, TyCtxt};
use rustc_span::Span;

pub use self::ImplSource::*;
pub use self::SelectionError::*;
use crate::infer::InferCtxt;

pub use self::engine::{TraitEngine, TraitEngineExt};
pub use self::project::MismatchedProjectionTypes;
Expand Down Expand Up @@ -116,6 +119,11 @@ pub type PredicateObligations<'tcx> = Vec<PredicateObligation<'tcx>>;

pub type Selection<'tcx> = ImplSource<'tcx, PredicateObligation<'tcx>>;

/// A callback that can be provided to `inspect_typeck`. Invoked on evaluation
/// of root obligations.
pub type ObligationInspector<'tcx> =
fn(&InferCtxt<'tcx>, &PredicateObligation<'tcx>, Result<Certainty, NoSolution>);

pub struct FulfillmentError<'tcx> {
pub obligation: PredicateObligation<'tcx>,
pub code: FulfillmentErrorCode<'tcx>,
Expand Down
3 changes: 2 additions & 1 deletion compiler/rustc_resolve/src/late/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2567,8 +2567,9 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> {
debug!(?param.ident, ?param.ident.span, ?use_span);

let elidable = matches!(use_ctxt, LifetimeCtxt::Ref);
let deletion_span =
if param.bounds.is_empty() { deletion_span() } else { None };

let deletion_span = deletion_span();
self.r.lint_buffer.buffer_lint_with_diagnostic(
lint::builtin::SINGLE_USE_LIFETIMES,
param.id,
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_span/src/symbol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1153,6 +1153,7 @@ symbols! {
offset,
offset_of,
offset_of_enum,
offset_of_nested,
ok_or_else,
omit_gdb_pretty_printer_section,
on,
Expand Down
Loading

0 comments on commit 314384b

Please sign in to comment.